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
d1c0628abc71d9e669731bf91724ec1c45cc219c
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/group/opposite.lean
f481a76f59aa5ca7124a8c1d798392e56ddf1379
[ "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
19,927
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.group.inj_surj import algebra.group.commute import algebra.hom.equiv import algebra.opposites /-! # Group structures on the multiplicative and additive opposites -/ universes u v variables (α : Type u) namespace mul_opposite /-! ### Additive structures on `αᵐᵒᵖ` -/ instance [add_semigroup α] : add_semigroup (αᵐᵒᵖ) := unop_injective.add_semigroup _ (λ x y, rfl) instance [add_left_cancel_semigroup α] : add_left_cancel_semigroup αᵐᵒᵖ := unop_injective.add_left_cancel_semigroup _ (λ x y, rfl) instance [add_right_cancel_semigroup α] : add_right_cancel_semigroup αᵐᵒᵖ := unop_injective.add_right_cancel_semigroup _ (λ x y, rfl) instance [add_comm_semigroup α] : add_comm_semigroup αᵐᵒᵖ := unop_injective.add_comm_semigroup _ (λ x y, rfl) instance [add_zero_class α] : add_zero_class αᵐᵒᵖ := unop_injective.add_zero_class _ rfl (λ x y, rfl) instance [add_monoid α] : add_monoid αᵐᵒᵖ := unop_injective.add_monoid _ rfl (λ _ _, rfl) (λ _ _, rfl) instance [add_comm_monoid α] : add_comm_monoid αᵐᵒᵖ := unop_injective.add_comm_monoid _ rfl (λ _ _, rfl) (λ _ _, rfl) instance [sub_neg_monoid α] : sub_neg_monoid αᵐᵒᵖ := unop_injective.sub_neg_monoid _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) instance [add_group α] : add_group αᵐᵒᵖ := unop_injective.add_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) instance [add_comm_group α] : add_comm_group αᵐᵒᵖ := unop_injective.add_comm_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) /-! ### Multiplicative structures on `αᵐᵒᵖ` We also generate additive structures on `αᵃᵒᵖ` using `to_additive` -/ @[to_additive] instance [semigroup α] : semigroup αᵐᵒᵖ := { mul_assoc := λ x y z, unop_injective $ eq.symm $ mul_assoc (unop z) (unop y) (unop x), .. mul_opposite.has_mul α } @[to_additive] instance [right_cancel_semigroup α] : left_cancel_semigroup αᵐᵒᵖ := { mul_left_cancel := λ x y z H, unop_injective $ mul_right_cancel $ op_injective H, .. mul_opposite.semigroup α } @[to_additive] instance [left_cancel_semigroup α] : right_cancel_semigroup αᵐᵒᵖ := { mul_right_cancel := λ x y z H, unop_injective $ mul_left_cancel $ op_injective H, .. mul_opposite.semigroup α } @[to_additive] instance [comm_semigroup α] : comm_semigroup αᵐᵒᵖ := { mul_comm := λ x y, unop_injective $ mul_comm (unop y) (unop x), .. mul_opposite.semigroup α } @[to_additive] instance [mul_one_class α] : mul_one_class αᵐᵒᵖ := { one_mul := λ x, unop_injective $ mul_one $ unop x, mul_one := λ x, unop_injective $ one_mul $ unop x, .. mul_opposite.has_mul α, .. mul_opposite.has_one α } @[to_additive] instance [monoid α] : monoid αᵐᵒᵖ := { npow := λ n x, op $ x.unop ^ n, npow_zero' := λ x, unop_injective $ monoid.npow_zero' x.unop, npow_succ' := λ n x, unop_injective $ pow_succ' x.unop n, .. mul_opposite.semigroup α, .. mul_opposite.mul_one_class α } @[to_additive] instance [right_cancel_monoid α] : left_cancel_monoid αᵐᵒᵖ := { .. mul_opposite.left_cancel_semigroup α, .. mul_opposite.monoid α } @[to_additive] instance [left_cancel_monoid α] : right_cancel_monoid αᵐᵒᵖ := { .. mul_opposite.right_cancel_semigroup α, .. mul_opposite.monoid α } @[to_additive] instance [cancel_monoid α] : cancel_monoid αᵐᵒᵖ := { .. mul_opposite.right_cancel_monoid α, .. mul_opposite.left_cancel_monoid α } @[to_additive] instance [comm_monoid α] : comm_monoid αᵐᵒᵖ := { .. mul_opposite.monoid α, .. mul_opposite.comm_semigroup α } @[to_additive] instance [cancel_comm_monoid α] : cancel_comm_monoid αᵐᵒᵖ := { .. mul_opposite.cancel_monoid α, .. mul_opposite.comm_monoid α } @[to_additive] instance [div_inv_monoid α] : div_inv_monoid αᵐᵒᵖ := { zpow := λ n x, op $ x.unop ^ n, zpow_zero' := λ x, unop_injective $ div_inv_monoid.zpow_zero' x.unop, zpow_succ' := λ n x, unop_injective $ by rw [unop_op, zpow_of_nat, zpow_of_nat, pow_succ', unop_mul, unop_op], zpow_neg' := λ z x, unop_injective $ div_inv_monoid.zpow_neg' z x.unop, .. mul_opposite.monoid α, .. mul_opposite.has_inv α } @[to_additive] instance [group α] : group αᵐᵒᵖ := { mul_left_inv := λ x, unop_injective $ mul_inv_self $ unop x, .. mul_opposite.div_inv_monoid α, } @[to_additive] instance [comm_group α] : comm_group αᵐᵒᵖ := { .. mul_opposite.group α, .. mul_opposite.comm_monoid α } variable {α} @[simp, to_additive] lemma unop_div [div_inv_monoid α] (x y : αᵐᵒᵖ) : unop (x / y) = (unop y)⁻¹ * unop x := rfl @[simp, to_additive] lemma op_div [div_inv_monoid α] (x y : α) : op (x / y) = (op y)⁻¹ * op x := by simp [div_eq_mul_inv] @[simp, to_additive] lemma semiconj_by_op [has_mul α] {a x y : α} : semiconj_by (op a) (op y) (op x) ↔ semiconj_by a x y := by simp only [semiconj_by, ← op_mul, op_inj, eq_comm] @[simp, to_additive] lemma semiconj_by_unop [has_mul α] {a x y : αᵐᵒᵖ} : semiconj_by (unop a) (unop y) (unop x) ↔ semiconj_by a x y := by conv_rhs { rw [← op_unop a, ← op_unop x, ← op_unop y, semiconj_by_op] } @[to_additive] lemma _root_.semiconj_by.op [has_mul α] {a x y : α} (h : semiconj_by a x y) : semiconj_by (op a) (op y) (op x) := semiconj_by_op.2 h @[to_additive] lemma _root_.semiconj_by.unop [has_mul α] {a x y : αᵐᵒᵖ} (h : semiconj_by a x y) : semiconj_by (unop a) (unop y) (unop x) := semiconj_by_unop.2 h @[to_additive] lemma _root_.commute.op [has_mul α] {x y : α} (h : commute x y) : commute (op x) (op y) := h.op @[to_additive] lemma commute.unop [has_mul α] {x y : αᵐᵒᵖ} (h : commute x y) : commute (unop x) (unop y) := h.unop @[simp, to_additive] lemma commute_op [has_mul α] {x y : α} : commute (op x) (op y) ↔ commute x y := semiconj_by_op @[simp, to_additive] lemma commute_unop [has_mul α] {x y : αᵐᵒᵖ} : commute (unop x) (unop y) ↔ commute x y := semiconj_by_unop /-- The function `mul_opposite.op` is an additive equivalence. -/ @[simps { fully_applied := ff, simp_rhs := tt }] def op_add_equiv [has_add α] : α ≃+ αᵐᵒᵖ := { map_add' := λ a b, rfl, .. op_equiv } @[simp] lemma op_add_equiv_to_equiv [has_add α] : (op_add_equiv : α ≃+ αᵐᵒᵖ).to_equiv = op_equiv := rfl end mul_opposite /-! ### Multiplicative structures on `αᵃᵒᵖ` -/ namespace add_opposite instance [semigroup α] : semigroup (αᵃᵒᵖ) := unop_injective.semigroup _ (λ x y, rfl) instance [left_cancel_semigroup α] : left_cancel_semigroup αᵃᵒᵖ := unop_injective.left_cancel_semigroup _ (λ x y, rfl) instance [right_cancel_semigroup α] : right_cancel_semigroup αᵃᵒᵖ := unop_injective.right_cancel_semigroup _ (λ x y, rfl) instance [comm_semigroup α] : comm_semigroup αᵃᵒᵖ := unop_injective.comm_semigroup _ (λ x y, rfl) instance [mul_one_class α] : mul_one_class αᵃᵒᵖ := unop_injective.mul_one_class _ rfl (λ x y, rfl) instance {β} [has_pow α β] : has_pow αᵃᵒᵖ β := { pow := λ a b, op (unop a ^ b) } @[simp] lemma op_pow {β} [has_pow α β] (a : α) (b : β) : op (a ^ b) = op a ^ b := rfl @[simp] lemma unop_pow {β} [has_pow α β] (a : αᵃᵒᵖ) (b : β) : unop (a ^ b) = unop a ^ b := rfl instance [monoid α] : monoid αᵃᵒᵖ := unop_injective.monoid _ rfl (λ _ _, rfl) (λ _ _, rfl) instance [comm_monoid α] : comm_monoid αᵃᵒᵖ := unop_injective.comm_monoid _ rfl (λ _ _, rfl) (λ _ _, rfl) instance [div_inv_monoid α] : div_inv_monoid αᵃᵒᵖ := unop_injective.div_inv_monoid _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) instance [group α] : group αᵃᵒᵖ := unop_injective.group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) instance [comm_group α] : comm_group αᵃᵒᵖ := unop_injective.comm_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) variable {α} /-- The function `add_opposite.op` is a multiplicative equivalence. -/ @[simps { fully_applied := ff, simp_rhs := tt }] def op_mul_equiv [has_mul α] : α ≃* αᵃᵒᵖ := { map_mul' := λ a b, rfl, .. op_equiv } @[simp] lemma op_mul_equiv_to_equiv [has_mul α] : (op_mul_equiv : α ≃* αᵃᵒᵖ).to_equiv = op_equiv := rfl end add_opposite open mul_opposite /-- Inversion on a group is a `mul_equiv` to the opposite group. When `G` is commutative, there is `mul_equiv.inv`. -/ @[to_additive "Negation on an additive group is an `add_equiv` to the opposite group. When `G` is commutative, there is `add_equiv.inv`.", simps { fully_applied := ff, simp_rhs := tt }] def mul_equiv.inv' (G : Type*) [group G] : G ≃* Gᵐᵒᵖ := { map_mul' := λ x y, unop_injective $ mul_inv_rev x y, .. (equiv.inv G).trans op_equiv } /-- A semigroup homomorphism `f : M →ₙ* N` such that `f x` commutes with `f y` for all `x, y` defines a semigroup homomorphism to `Nᵐᵒᵖ`. -/ @[to_additive "An additive semigroup homomorphism `f : add_hom M N` such that `f x` additively commutes with `f y` for all `x, y` defines an additive semigroup homomorphism to `Sᵃᵒᵖ`.", simps {fully_applied := ff}] def mul_hom.to_opposite {M N : Type*} [has_mul M] [has_mul N] (f : M →ₙ* N) (hf : ∀ x y, commute (f x) (f y)) : M →ₙ* Nᵐᵒᵖ := { to_fun := mul_opposite.op ∘ f, map_mul' := λ x y, by simp [(hf x y).eq] } /-- A semigroup homomorphism `f : M →ₙ* N` such that `f x` commutes with `f y` for all `x, y` defines a semigroup homomorphism from `Mᵐᵒᵖ`. -/ @[to_additive "An additive semigroup homomorphism `f : add_hom M N` such that `f x` additively commutes with `f y` for all `x`, `y` defines an additive semigroup homomorphism from `Mᵃᵒᵖ`.", simps {fully_applied := ff}] def mul_hom.from_opposite {M N : Type*} [has_mul M] [has_mul N] (f : M →ₙ* N) (hf : ∀ x y, commute (f x) (f y)) : Mᵐᵒᵖ →ₙ* N := { to_fun := f ∘ mul_opposite.unop, map_mul' := λ x y, (f.map_mul _ _).trans (hf _ _).eq } /-- A monoid homomorphism `f : M →* N` such that `f x` commutes with `f y` for all `x, y` defines a monoid homomorphism to `Nᵐᵒᵖ`. -/ @[to_additive "An additive monoid homomorphism `f : M →+ N` such that `f x` additively commutes with `f y` for all `x, y` defines an additive monoid homomorphism to `Sᵃᵒᵖ`.", simps {fully_applied := ff}] def monoid_hom.to_opposite {M N : Type*} [mul_one_class M] [mul_one_class N] (f : M →* N) (hf : ∀ x y, commute (f x) (f y)) : M →* Nᵐᵒᵖ := { to_fun := mul_opposite.op ∘ f, map_one' := congr_arg op f.map_one, map_mul' := λ x y, by simp [(hf x y).eq] } /-- A monoid homomorphism `f : M →* N` such that `f x` commutes with `f y` for all `x, y` defines a monoid homomorphism from `Mᵐᵒᵖ`. -/ @[to_additive "An additive monoid homomorphism `f : M →+ N` such that `f x` additively commutes with `f y` for all `x`, `y` defines an additive monoid homomorphism from `Mᵃᵒᵖ`.", simps {fully_applied := ff}] def monoid_hom.from_opposite {M N : Type*} [mul_one_class M] [mul_one_class N] (f : M →* N) (hf : ∀ x y, commute (f x) (f y)) : Mᵐᵒᵖ →* N := { to_fun := f ∘ mul_opposite.unop, map_one' := f.map_one, map_mul' := λ x y, (f.map_mul _ _).trans (hf _ _).eq } /-- The units of the opposites are equivalent to the opposites of the units. -/ @[to_additive "The additive units of the additive opposites are equivalent to the additive opposites of the additive units."] def units.op_equiv {M} [monoid M] : (Mᵐᵒᵖ)ˣ ≃* (Mˣ)ᵐᵒᵖ := { to_fun := λ u, op ⟨unop u, unop ↑(u⁻¹), op_injective u.4, op_injective u.3⟩, inv_fun := mul_opposite.rec $ λ u, ⟨op ↑(u), op ↑(u⁻¹), unop_injective $ u.4, unop_injective u.3⟩, map_mul' := λ x y, unop_injective $ units.ext $ rfl, left_inv := λ x, units.ext $ by simp, right_inv := λ x, unop_injective $ units.ext $ rfl } @[simp, to_additive] lemma units.coe_unop_op_equiv {M} [monoid M] (u : (Mᵐᵒᵖ)ˣ) : ((units.op_equiv u).unop : M) = unop (u : Mᵐᵒᵖ) := rfl @[simp, to_additive] lemma units.coe_op_equiv_symm {M} [monoid M] (u : (Mˣ)ᵐᵒᵖ) : (units.op_equiv.symm u : Mᵐᵒᵖ) = op (u.unop : M) := rfl /-- A semigroup homomorphism `M →ₙ* N` can equivalently be viewed as a semigroup homomorphism `Mᵐᵒᵖ →ₙ* Nᵐᵒᵖ`. This is the action of the (fully faithful) `ᵐᵒᵖ`-functor on morphisms. -/ @[to_additive "An additive semigroup homomorphism `add_hom M N` can equivalently be viewed as an additive semigroup homomorphism `add_hom Mᵃᵒᵖ Nᵃᵒᵖ`. This is the action of the (fully faithful) `ᵃᵒᵖ`-functor on morphisms.", simps] def mul_hom.op {M N} [has_mul M] [has_mul N] : (M →ₙ* N) ≃ (Mᵐᵒᵖ →ₙ* Nᵐᵒᵖ) := { to_fun := λ f, { to_fun := op ∘ f ∘ unop, map_mul' := λ x y, unop_injective (f.map_mul y.unop x.unop) }, inv_fun := λ f, { to_fun := unop ∘ f ∘ op, map_mul' := λ x y, congr_arg unop (f.map_mul (op y) (op x)) }, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext x, simp } } /-- The 'unopposite' of a semigroup homomorphism `Mᵐᵒᵖ →ₙ* Nᵐᵒᵖ`. Inverse to `mul_hom.op`. -/ @[simp, to_additive "The 'unopposite' of an additive semigroup homomorphism `Mᵃᵒᵖ →ₙ+ Nᵃᵒᵖ`. Inverse to `add_hom.op`."] def mul_hom.unop {M N} [has_mul M] [has_mul N] : (Mᵐᵒᵖ →ₙ* Nᵐᵒᵖ) ≃ (M →ₙ* N) := mul_hom.op.symm /-- An additive semigroup homomorphism `add_hom M N` can equivalently be viewed as an additive homomorphism `add_hom Mᵐᵒᵖ Nᵐᵒᵖ`. This is the action of the (fully faithful) `ᵐᵒᵖ`-functor on morphisms. -/ @[simps] def add_hom.mul_op {M N} [has_add M] [has_add N] : (add_hom M N) ≃ (add_hom Mᵐᵒᵖ Nᵐᵒᵖ) := { to_fun := λ f, { to_fun := op ∘ f ∘ unop, map_add' := λ x y, unop_injective (f.map_add x.unop y.unop) }, inv_fun := λ f, { to_fun := unop ∘ f ∘ op, map_add' := λ x y, congr_arg unop (f.map_add (op x) (op y)) }, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, simp } } /-- The 'unopposite' of an additive semigroup hom `αᵐᵒᵖ →+ βᵐᵒᵖ`. Inverse to `add_hom.mul_op`. -/ @[simp] def add_hom.mul_unop {α β} [has_add α] [has_add β] : (add_hom αᵐᵒᵖ βᵐᵒᵖ) ≃ (add_hom α β) := add_hom.mul_op.symm /-- A monoid homomorphism `M →* N` can equivalently be viewed as a monoid homomorphism `Mᵐᵒᵖ →* Nᵐᵒᵖ`. This is the action of the (fully faithful) `ᵐᵒᵖ`-functor on morphisms. -/ @[to_additive "An additive monoid homomorphism `M →+ N` can equivalently be viewed as an additive monoid homomorphism `Mᵃᵒᵖ →+ Nᵃᵒᵖ`. This is the action of the (fully faithful) `ᵃᵒᵖ`-functor on morphisms.", simps] def monoid_hom.op {M N} [mul_one_class M] [mul_one_class N] : (M →* N) ≃ (Mᵐᵒᵖ →* Nᵐᵒᵖ) := { to_fun := λ f, { to_fun := op ∘ f ∘ unop, map_one' := congr_arg op f.map_one, map_mul' := λ x y, unop_injective (f.map_mul y.unop x.unop) }, inv_fun := λ f, { to_fun := unop ∘ f ∘ op, map_one' := congr_arg unop f.map_one, map_mul' := λ x y, congr_arg unop (f.map_mul (op y) (op x)) }, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext x, simp } } /-- The 'unopposite' of a monoid homomorphism `Mᵐᵒᵖ →* Nᵐᵒᵖ`. Inverse to `monoid_hom.op`. -/ @[simp, to_additive "The 'unopposite' of an additive monoid homomorphism `Mᵃᵒᵖ →+ Nᵃᵒᵖ`. Inverse to `add_monoid_hom.op`."] def monoid_hom.unop {M N} [mul_one_class M] [mul_one_class N] : (Mᵐᵒᵖ →* Nᵐᵒᵖ) ≃ (M →* N) := monoid_hom.op.symm /-- An additive homomorphism `M →+ N` can equivalently be viewed as an additive homomorphism `Mᵐᵒᵖ →+ Nᵐᵒᵖ`. This is the action of the (fully faithful) `ᵐᵒᵖ`-functor on morphisms. -/ @[simps] def add_monoid_hom.mul_op {M N} [add_zero_class M] [add_zero_class N] : (M →+ N) ≃ (Mᵐᵒᵖ →+ Nᵐᵒᵖ) := { to_fun := λ f, { to_fun := op ∘ f ∘ unop, map_zero' := unop_injective f.map_zero, map_add' := λ x y, unop_injective (f.map_add x.unop y.unop) }, inv_fun := λ f, { to_fun := unop ∘ f ∘ op, map_zero' := congr_arg unop f.map_zero, map_add' := λ x y, congr_arg unop (f.map_add (op x) (op y)) }, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, simp } } /-- The 'unopposite' of an additive monoid hom `αᵐᵒᵖ →+ βᵐᵒᵖ`. Inverse to `add_monoid_hom.mul_op`. -/ @[simp] def add_monoid_hom.mul_unop {α β} [add_zero_class α] [add_zero_class β] : (αᵐᵒᵖ →+ βᵐᵒᵖ) ≃ (α →+ β) := add_monoid_hom.mul_op.symm /-- A iso `α ≃+ β` can equivalently be viewed as an iso `αᵐᵒᵖ ≃+ βᵐᵒᵖ`. -/ @[simps] def add_equiv.mul_op {α β} [has_add α] [has_add β] : (α ≃+ β) ≃ (αᵐᵒᵖ ≃+ βᵐᵒᵖ) := { to_fun := λ f, op_add_equiv.symm.trans (f.trans op_add_equiv), inv_fun := λ f, op_add_equiv.trans (f.trans op_add_equiv.symm), left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, simp } } /-- The 'unopposite' of an iso `αᵐᵒᵖ ≃+ βᵐᵒᵖ`. Inverse to `add_equiv.mul_op`. -/ @[simp] def add_equiv.mul_unop {α β} [has_add α] [has_add β] : (αᵐᵒᵖ ≃+ βᵐᵒᵖ) ≃ (α ≃+ β) := add_equiv.mul_op.symm /-- A iso `α ≃* β` can equivalently be viewed as an iso `αᵐᵒᵖ ≃* βᵐᵒᵖ`. -/ @[to_additive "A iso `α ≃+ β` can equivalently be viewed as an iso `αᵃᵒᵖ ≃+ βᵃᵒᵖ`.", simps] def mul_equiv.op {α β} [has_mul α] [has_mul β] : (α ≃* β) ≃ (αᵐᵒᵖ ≃* βᵐᵒᵖ) := { to_fun := λ f, { to_fun := op ∘ f ∘ unop, inv_fun := op ∘ f.symm ∘ unop, left_inv := λ x, unop_injective (f.symm_apply_apply x.unop), right_inv := λ x, unop_injective (f.apply_symm_apply x.unop), map_mul' := λ x y, unop_injective (f.map_mul y.unop x.unop) }, inv_fun := λ f, { to_fun := unop ∘ f ∘ op, inv_fun := unop ∘ f.symm ∘ op, left_inv := λ x, by simp, right_inv := λ x, by simp, map_mul' := λ x y, congr_arg unop (f.map_mul (op y) (op x)) }, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, simp } } /-- The 'unopposite' of an iso `αᵐᵒᵖ ≃* βᵐᵒᵖ`. Inverse to `mul_equiv.op`. -/ @[simp, to_additive "The 'unopposite' of an iso `αᵃᵒᵖ ≃+ βᵃᵒᵖ`. Inverse to `add_equiv.op`."] def mul_equiv.unop {α β} [has_mul α] [has_mul β] : (αᵐᵒᵖ ≃* βᵐᵒᵖ) ≃ (α ≃* β) := mul_equiv.op.symm section ext /-- This ext lemma change equalities on `αᵐᵒᵖ →+ β` to equalities on `α →+ β`. This is useful because there are often ext lemmas for specific `α`s that will apply to an equality of `α →+ β` such as `finsupp.add_hom_ext'`. -/ @[ext] lemma add_monoid_hom.mul_op_ext {α β} [add_zero_class α] [add_zero_class β] (f g : αᵐᵒᵖ →+ β) (h : f.comp (op_add_equiv : α ≃+ αᵐᵒᵖ).to_add_monoid_hom = g.comp (op_add_equiv : α ≃+ αᵐᵒᵖ).to_add_monoid_hom) : f = g := add_monoid_hom.ext $ mul_opposite.rec $ λ x, (add_monoid_hom.congr_fun h : _) x end ext
27b480faaea07531c25a77ffffceb1ad88745c52
80162757f50b09d3cad5564907e4c9b00742e045
/measure.lean
2554bb312a2aa1aeaba453e6d81a727dfed7b2b1
[]
no_license
EdAyers/edlib
cc30d0a54fed347a85b6df6045f68e6b48bc71a3
78b8c5d91f023f939c102837d748868e2f3ed27d
refs/heads/master
1,586,459,758,216
1,571,322,179,000
1,571,322,179,000
160,538,917
2
0
null
null
null
null
UTF-8
Lean
false
false
4,861
lean
import .set .galois .lattice universes u variables {E : Type u} def seq : Type u → Type u := λ α, ℕ → α class σ_algebra {E : Type u} (ℰ : set (set E)) : Prop := (empty : ∅ ∈ ℰ) (compl : ∀ A ∈ ℰ, -A ∈ ℰ) (union : ∀ (As : ℕ → set E) (p : ∀ n, As n ∈ ℰ), (⋃ n, As n) ∈ ℰ) namespace σ_algebra variables {ℰ : set (set E)} [σ_algebra ℰ] lemma inter : ∀ (As : ℕ → set E) (p : ∀ n, As n ∈ ℰ), (⋂ n, As n) ∈ ℰ := begin intros As p,simp [set.Inter_compl], apply σ_algebra.compl, apply σ_algebra.union, intro n, apply σ_algebra.compl, apply p, end def algebra_on (E : Type u) : Type* := {ℰ:set(set E) // σ_algebra ℰ} instance : has_mem (set E) (algebra_on E) := ⟨λ a b, a ∈ b.val⟩ lemma ext : Π {ℰ₁ ℰ₂ : algebra_on E}, ℰ₁.val = ℰ₂.val → ℰ₁ = ℰ₂ |⟨_,_⟩ ⟨_,_⟩ rfl := rfl instance : partial_order (algebra_on E) := { le := λ ℰ₁ ℰ₂, ℰ₁.1 ⊆ ℰ₂.1 , le_refl := λ ℰ A, id , le_trans := λ A B C, set.subset.trans , le_antisymm := λ A B l r, ext $ set.subset.antisymm l r } def forget : (algebra_on E) → set (set E) := λ x, x.val inductive gen_free (𝒜 : set (set E)) : set E → Prop |basic : ∀ A ∈ 𝒜, gen_free A |empty : gen_free ∅ |compl : ∀ A, gen_free A → gen_free (-A) |union : ∀ (As : seq (set E)), (∀ n, gen_free (As n)) → gen_free (⋃ n, As n) def free (𝒜 : set (set E)) : algebra_on E := ⟨set_of $ gen_free 𝒜, {empty := gen_free.empty _,compl := gen_free.compl,union := gen_free.union}⟩ def gc : @galois_connection (set (set E)) (algebra_on E) _ _ free forget := λ 𝒜 ℰ, ⟨λ (h₁ : (free 𝒜).val ⊆ ℰ.val) A AA, h₁ (gen_free.basic A AA) ,λ (h₁ : 𝒜 ⊆ ℰ.val) A h₂, have ecu : σ_algebra ℰ.val, from ℰ.2, gen_free.rec_on h₂ (λ B BE, h₁ BE) (ecu.empty) (λ B _ BE, @σ_algebra.compl _ _ ecu B BE) (λ As _ q, @σ_algebra.union _ _ ecu As q) ⟩ def gi : @galois_insertion (set (set E)) (algebra_on E) _ _ free forget := { gc := gc , le_l_u := λ ℰ A mA, gen_free.basic A mA } instance : complete_lattice (algebra_on E) := complete_lattice_of_gi gi structure π_system (𝒜 : set (set E)) := (empty : ∅ ∈ 𝒜) (inter : ∀ (A B ∈ 𝒜), A ∩ B ∈ 𝒜) structure d_system (𝒜 : set (set E)) := (univ : set.univ ∈ 𝒜) (subs : ∀ (A B ∈ 𝒜), A ⊆ B → (B ∩ -A) ∈ 𝒜) (union : ∀ (f : seq (set E)), (∀ n, f n ∈ 𝒜) → (monotone f) → (⋃ n, f n) ∈ 𝒜) lemma dynkin {𝒜 𝒟 : set (set E)} (p: π_system 𝒜) (d : d_system 𝒟) (ss : 𝒜 ⊆ 𝒟) : (forget (free 𝒜) ⊆ 𝒟) := let 𝒟' := { B ∈ 𝒟 |∀ A ∈ 𝒜, B ∩ A ∈ 𝒟} in have h₁ : 𝒜 ⊆ 𝒟', from λ A mA, ⟨ss mA,λ X mX, ss (p.inter _ _ mA mX)⟩, have h₂ : set.univ ∈ 𝒟', from ⟨d.univ, λ A mA, begin apply ss, rw set.inter.univ, apply mA end⟩, have h₃ : ∀ (B₁ B₂ ∈ 𝒟'), B₁ ⊆ B₂ → B₂ ∩ -B₁ ∈ 𝒟', from λ B₁ B₂ ⟨m1,h1⟩ ⟨m2,h2⟩ sb, ⟨d.subs _ _ m1 m2 sb , λ A mA, have h₄ : (B₂ ∩ -B₁) ∩ A = (B₂ ∩ A) ∩ -(B₁ ∩ A), from set.ext $ λ x, ⟨λ ⟨⟨i,j⟩,k⟩, ⟨⟨i,k⟩,λ ⟨l,m⟩, j l⟩,λ ⟨⟨i,j⟩,f⟩, ⟨⟨i,λ k, f⟨k,j⟩⟩,j⟩⟩ , have h₅ : (B₂ ∩ A) ∈ 𝒟, from h2 A mA, have h₆ : (B₁ ∩ A) ∈ 𝒟, from h1 A mA, suffices (B₂ ∩ A) ∩ -(B₁ ∩ A) ∈ 𝒟, by simp [h₄, this], d.subs _ _ h₆ h₅ (λ x ⟨m2,ma⟩, ⟨sb m2, ma⟩) ⟩, have h₄: ∀ (f : seq (set E)), (∀ n, f n ∈ 𝒟') →(monotone f) → (⋃ n, f n) ∈ 𝒟', from λ f p m, ⟨d.union (f) (λ n, (p n).1) m, λ A mA, have h₅ : (⋃ n, f n) ∩ A = (⋃ n, (f n) ∩ A), from set.ext $ λ x, ⟨λ ⟨⟨i,j⟩,k⟩, ⟨i,⟨j,k⟩⟩,λ ⟨i,⟨j,k⟩⟩, ⟨⟨i,j⟩,k⟩⟩, suffices (⋃ n, (f n) ∩ A) ∈ 𝒟, by simp [h₅, this], d.union _ (λ n, (p n).2 A mA) (λ i j ij x ⟨p,q⟩, ⟨m ij p,q⟩) ⟩, λ A mA, gen_free.rec_on mA (λ A mA, ss mA) (ss p.empty) (λ B _ mB, suffices set.univ ∩ -B ∈ 𝒟, by simp [set.inter.univ] at this; assumption, d.subs B set.univ mB (d.univ) (λ _ _, ⟨⟩) ) (λ f _ q, _) end σ_algebra --def disjoint_sequence (ℰ : set (set E)) := {As:ℕ→set E//(∀ n, As n ∈ ℰ) ∧ (∀ n m, As n ∩ As m = ∅)}
2b40774a0e8e4d61a474b838dcfe4c2a1c937cbf
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/linear_algebra/free_module/finite/rank.lean
0de26d8d1ba11c7cb6fb3bf9cfddbab714cdfe4a
[ "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
7,820
lean
/- Copyright (c) 2021 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import linear_algebra.finrank import linear_algebra.free_module.rank import linear_algebra.free_module.finite.basic /-! # Rank of finite free modules > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This is a basic API for the rank of finite free modules. -/ --TODO: many results from `linear_algebra/finite_dimensional` should be moved here. universes u v w variables (R : Type u) (M : Type v) (N : Type w) open_locale tensor_product direct_sum big_operators cardinal open cardinal finite_dimensional fintype namespace finite_dimensional open module.free section ring variables [ring R] variables [add_comm_group M] [module R M] variables [add_comm_group N] [module R N] @[simp] lemma submodule.finrank_map_subtype_eq (p : submodule R M) (q : submodule R p) : finrank R (q.map p.subtype) = finrank R q := (submodule.equiv_subtype_map p q).symm.finrank_eq end ring section ring_finite variables [ring R] [strong_rank_condition R] variables [add_comm_group M] [module R M] [module.finite R M] variables [add_comm_group N] [module R N] [module.finite R N] /-- The rank of a finite module is finite. -/ lemma rank_lt_aleph_0 : module.rank R M < ℵ₀ := begin dunfold module.rank, letI := nontrivial_of_invariant_basis_number R, obtain ⟨S, hS⟩ := module.finite_def.mp ‹_›, refine (csupr_le' $ λ i, _).trans_lt (nat_lt_aleph_0 S.card), exact linear_independent_le_span_finset _ i.prop S hS, end /-- If `M` is finite, `finrank M = rank M`. -/ @[simp] lemma finrank_eq_rank : ↑(finrank R M) = module.rank R M := by { rw [finrank, cast_to_nat_of_lt_aleph_0 (rank_lt_aleph_0 R M)] } end ring_finite section ring_free variables [ring R] [strong_rank_condition R] variables [add_comm_group M] [module R M] [module.free R M] [module.finite R M] variables [add_comm_group N] [module R N] [module.free R N] [module.finite R N] /-- The finrank of a free module `M` over `R` is the cardinality of `choose_basis_index R M`. -/ lemma finrank_eq_card_choose_basis_index : finrank R M = @card (choose_basis_index R M) (@choose_basis_index.fintype R M _ _ _ _ (nontrivial_of_invariant_basis_number R) _) := begin letI := nontrivial_of_invariant_basis_number R, simp [finrank, rank_eq_card_choose_basis_index] end /-- The finrank of `(ι →₀ R)` is `fintype.card ι`. -/ @[simp] lemma finrank_finsupp {ι : Type v} [fintype ι] : finrank R (ι →₀ R) = card ι := by { rw [finrank, rank_finsupp_self, ← mk_to_nat_eq_card, to_nat_lift] } /-- The finrank of `(ι → R)` is `fintype.card ι`. -/ lemma finrank_pi {ι : Type v} [fintype ι] : finrank R (ι → R) = card ι := by simp [finrank] /-- The finrank of the direct sum is the sum of the finranks. -/ @[simp] lemma finrank_direct_sum {ι : Type v} [fintype ι] (M : ι → Type w) [Π (i : ι), add_comm_group (M i)] [Π (i : ι), module R (M i)] [Π (i : ι), module.free R (M i)] [Π (i : ι), module.finite R (M i)] : finrank R (⨁ i, M i) = ∑ i, finrank R (M i) := begin letI := nontrivial_of_invariant_basis_number R, simp only [finrank, λ i, rank_eq_card_choose_basis_index R (M i), rank_direct_sum, ← mk_sigma, mk_to_nat_eq_card, card_sigma], end /-- The finrank of `M × N` is `(finrank R M) + (finrank R N)`. -/ @[simp] lemma finrank_prod : finrank R (M × N) = (finrank R M) + (finrank R N) := by { simp [finrank, rank_lt_aleph_0 R M, rank_lt_aleph_0 R N] } /-- The finrank of a finite product is the sum of the finranks. -/ --TODO: this should follow from `linear_equiv.finrank_eq`, that is over a field. lemma finrank_pi_fintype {ι : Type v} [fintype ι] {M : ι → Type w} [Π (i : ι), add_comm_group (M i)] [Π (i : ι), module R (M i)] [Π (i : ι), module.free R (M i)] [Π (i : ι), module.finite R (M i)] : finrank R (Π i, M i) = ∑ i, finrank R (M i) := begin letI := nontrivial_of_invariant_basis_number R, simp only [finrank, λ i, rank_eq_card_choose_basis_index R (M i), rank_pi, ← mk_sigma, mk_to_nat_eq_card, card_sigma], end /-- If `m` and `n` are `fintype`, the finrank of `m × n` matrices is `(fintype.card m) * (fintype.card n)`. -/ lemma finrank_matrix (m n : Type*) [fintype m] [fintype n] : finrank R (matrix m n R) = (card m) * (card n) := by { simp [finrank] } variables {R M N} /-- Two finite and free modules are isomorphic if they have the same (finite) rank. -/ theorem nonempty_linear_equiv_of_finrank_eq (cond : finrank R M = finrank R N) : nonempty (M ≃ₗ[R] N) := nonempty_linear_equiv_of_lift_rank_eq $ by simp only [← finrank_eq_rank, cond, lift_nat_cast] /-- Two finite and free modules are isomorphic if and only if they have the same (finite) rank. -/ theorem nonempty_linear_equiv_iff_finrank_eq : nonempty (M ≃ₗ[R] N) ↔ finrank R M = finrank R N := ⟨λ ⟨h⟩, h.finrank_eq, λ h, nonempty_linear_equiv_of_finrank_eq h⟩ variables (M N) /-- Two finite and free modules are isomorphic if they have the same (finite) rank. -/ noncomputable def _root_.linear_equiv.of_finrank_eq (cond : finrank R M = finrank R N) : M ≃ₗ[R] N := classical.choice $ nonempty_linear_equiv_of_finrank_eq cond end ring_free section comm_ring variables [comm_ring R] [strong_rank_condition R] variables [add_comm_group M] [module R M] [module.free R M] [module.finite R M] variables [add_comm_group N] [module R N] [module.free R N] [module.finite R N] /-- The finrank of `M ⊗[R] N` is `(finrank R M) * (finrank R N)`. -/ @[simp] lemma finrank_tensor_product (M : Type v) (N : Type w) [add_comm_group M] [module R M] [module.free R M] [add_comm_group N] [module R N] [module.free R N] : finrank R (M ⊗[R] N) = (finrank R M) * (finrank R N) := by { simp [finrank] } end comm_ring end finite_dimensional section open finite_dimensional variables {R M N} variables [ring R] [strong_rank_condition R] variables [add_comm_group M] [module R M] variables [add_comm_group N] [module R N] lemma linear_map.finrank_le_finrank_of_injective [module.finite R N] {f : M →ₗ[R] N} (hf : function.injective f) : finrank R M ≤ finrank R N := finrank_le_finrank_of_rank_le_rank (linear_map.lift_rank_le_of_injective _ hf) (rank_lt_aleph_0 _ _) lemma linear_map.finrank_range_le [module.finite R M] (f : M →ₗ[R] N) : finrank R f.range ≤ finrank R M := finrank_le_finrank_of_rank_le_rank (lift_rank_range_le f) (rank_lt_aleph_0 _ _) /-- The dimension of a submodule is bounded by the dimension of the ambient space. -/ lemma submodule.finrank_le [module.finite R M] (s : submodule R M) : finrank R s ≤ finrank R M := by simpa only [cardinal.to_nat_lift] using to_nat_le_of_le_of_lt_aleph_0 (rank_lt_aleph_0 _ _) (rank_submodule_le s) /-- The dimension of a quotient is bounded by the dimension of the ambient space. -/ lemma submodule.finrank_quotient_le [module.finite R M] (s : submodule R M) : finrank R (M ⧸ s) ≤ finrank R M := by simpa only [cardinal.to_nat_lift] using to_nat_le_of_le_of_lt_aleph_0 (rank_lt_aleph_0 _ _) ((submodule.mkq s).rank_le_of_surjective (surjective_quot_mk _)) /-- Pushforwards of finite submodules have a smaller finrank. -/ lemma submodule.finrank_map_le (f : M →ₗ[R] N) (p : submodule R M) [module.finite R p] : finrank R (p.map f) ≤ finrank R p := finrank_le_finrank_of_rank_le_rank (lift_rank_map_le _ _) (rank_lt_aleph_0 _ _) lemma submodule.finrank_le_finrank_of_le {s t : submodule R M} [module.finite R t] (hst : s ≤ t) : finrank R s ≤ finrank R t := calc finrank R s = finrank R (s.comap t.subtype) : (submodule.comap_subtype_equiv_of_le hst).finrank_eq.symm ... ≤ finrank R t : submodule.finrank_le _ end
8765fa53a9031a8235cfb491deea0cca1b97c3d8
618003631150032a5676f229d13a079ac875ff77
/src/tactic/split_ifs.lean
bdd70fc1df3c53f818b6eefe104e31e085b00cbe
[ "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
3,297
lean
/- Copyright (c) 2018 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner. Tactic to split if-then-else-expressions. -/ import tactic.hint open expr tactic namespace tactic open interactive meta def find_if_cond : expr → option expr | e := e.fold none $ λ e _ acc, acc <|> do c ← match e with | `(@ite %%c %%_ _ _ _) := some c | `(@dite %%c %%_ _ _ _) := some c | _ := none end, guard ¬c.has_var, find_if_cond c <|> return c meta def find_if_cond_at (at_ : loc) : tactic (option expr) := do lctx ← at_.get_locals, lctx ← lctx.mmap infer_type, tgt ← target, let es := if at_.include_goal then tgt::lctx else lctx, return $ find_if_cond $ es.foldr app (default expr) run_cmd mk_simp_attr `split_if_reduction run_cmd add_doc_string `simp_attr.split_if_reduction "Simp set for if-then-else statements" attribute [split_if_reduction] if_pos if_neg dif_pos dif_neg meta def reduce_ifs_at (at_ : loc) : tactic unit := do sls ← get_user_simp_lemmas `split_if_reduction, let cfg : simp_config := { fail_if_unchanged := ff }, let discharger := assumption <|> (applyc `not_not_intro >> assumption), hs ← at_.get_locals, hs.mmap' (λ h, simp_hyp sls [] h cfg discharger >> skip), when at_.include_goal (simp_target sls [] cfg discharger) meta def split_if1 (c : expr) (n : name) (at_ : loc) : tactic unit := by_cases c n; reduce_ifs_at at_ private meta def get_next_name (names : ref (list name)) : tactic name := do ns ← read_ref names, match ns with | [] := get_unused_name `h | n::ns := do write_ref names ns, return n end private meta def value_known (c : expr) : tactic bool := do lctx ← local_context, lctx ← lctx.mmap infer_type, return $ c ∈ lctx ∨ `(¬%%c) ∈ lctx private meta def split_ifs_core (at_ : loc) (names : ref (list name)) : list expr → tactic unit | done := do some cond ← find_if_cond_at at_ | fail "no if-then-else expressions to split", let cond := match cond with `(¬%%p) := p | p := p end, if cond ∈ done then skip else do no_split ← value_known cond, if no_split then reduce_ifs_at at_; try (split_ifs_core (cond :: done)) else do n ← get_next_name names, split_if1 cond n at_; try (split_ifs_core (cond :: done)) meta def split_ifs (names : list name) (at_ : loc := loc.ns [none]) := using_new_ref names $ λ names, split_ifs_core at_ names [] namespace interactive open interactive interactive.types expr lean.parser /-- Splits all if-then-else-expressions into multiple goals. Given a goal of the form `g (if p then x else y)`, `split_ifs` will produce two goals: `p ⊢ g x` and `¬p ⊢ g y`. If there are multiple ite-expressions, then `split_ifs` will split them all, starting with a top-most one whose condition does not contain another ite-expression. `split_ifs at *` splits all ite-expressions in all hypotheses as well as the goal. `split_ifs with h₁ h₂ h₃` overrides the default names for the hypotheses. -/ meta def split_ifs (at_ : parse location) (names : parse with_ident_list) : tactic unit := tactic.split_ifs names at_ add_hint_tactic "split_ifs" add_tactic_doc { name := "split_ifs", category := doc_category.tactic, decl_names := [``split_ifs], tags := ["case bashing"] } end interactive end tactic
063c4d23adb730294fbe598424e0ac0f7d65b503
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/data/int/cast.lean
c40461788037fce92434ce584818ae0da9613e61
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
7,849
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.int.basic import data.nat.cast open nat namespace int /- cast (injection into groups with one) -/ @[simp, push_cast] theorem nat_cast_eq_coe_nat : ∀ n, @coe ℕ ℤ (@coe_to_lift _ _ nat.cast_coe) n = @coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ int.has_coe)) n | 0 := rfl | (n+1) := congr_arg (+(1:ℤ)) (nat_cast_eq_coe_nat n) /-- Coercion `ℕ → ℤ` as a `ring_hom`. -/ def of_nat_hom : ℕ →+* ℤ := ⟨coe, rfl, int.of_nat_mul, rfl, int.of_nat_add⟩ section cast variables {α : Type*} section variables [has_zero α] [has_one α] [has_add α] [has_neg α] /-- Canonical homomorphism from the integers to any ring(-like) structure `α` -/ protected def cast : ℤ → α | (n : ℕ) := n | -[1+ n] := -(n+1) -- see Note [coercion into rings] @[priority 900] instance cast_coe : has_coe_t ℤ α := ⟨int.cast⟩ @[simp, norm_cast] theorem cast_zero : ((0 : ℤ) : α) = 0 := rfl theorem cast_of_nat (n : ℕ) : (of_nat n : α) = n := rfl @[simp, norm_cast] theorem cast_coe_nat (n : ℕ) : ((n : ℤ) : α) = n := rfl theorem cast_coe_nat' (n : ℕ) : (@coe ℕ ℤ (@coe_to_lift _ _ nat.cast_coe) n : α) = n := by simp @[simp, norm_cast] theorem cast_neg_succ_of_nat (n : ℕ) : (-[1+ n] : α) = -(n + 1) := rfl end @[simp, norm_cast] theorem cast_one [add_monoid α] [has_one α] [has_neg α] : ((1 : ℤ) : α) = 1 := nat.cast_one @[simp] theorem cast_sub_nat_nat [add_group α] [has_one α] (m n) : ((int.sub_nat_nat m n : ℤ) : α) = m - n := begin unfold sub_nat_nat, cases e : n - m, { simp [sub_nat_nat, e, nat.le_of_sub_eq_zero e] }, { rw [sub_nat_nat, cast_neg_succ_of_nat, ← nat.cast_succ, ← e, nat.cast_sub $ _root_.le_of_lt $ nat.lt_of_sub_eq_succ e, neg_sub] }, end @[simp, norm_cast] theorem cast_neg_of_nat [add_group α] [has_one α] : ∀ n, ((neg_of_nat n : ℤ) : α) = -n | 0 := neg_zero.symm | (n+1) := rfl @[simp, norm_cast] theorem cast_add [add_group α] [has_one α] : ∀ m n, ((m + n : ℤ) : α) = m + n | (m : ℕ) (n : ℕ) := nat.cast_add _ _ | (m : ℕ) -[1+ n] := cast_sub_nat_nat _ _ | -[1+ m] (n : ℕ) := (cast_sub_nat_nat _ _).trans $ sub_eq_of_eq_add $ show (n:α) = -(m+1) + n + (m+1), by rw [add_assoc, ← cast_succ, ← nat.cast_add, add_comm, nat.cast_add, cast_succ, neg_add_cancel_left] | -[1+ m] -[1+ n] := show -((m + n + 1 + 1 : ℕ) : α) = -(m + 1) + -(n + 1), begin rw [← neg_add_rev, ← nat.cast_add_one, ← nat.cast_add_one, ← nat.cast_add], apply congr_arg (λ x:ℕ, -(x:α)), ac_refl end @[simp, norm_cast] theorem cast_neg [add_group α] [has_one α] : ∀ n, ((-n : ℤ) : α) = -n | (n : ℕ) := cast_neg_of_nat _ | -[1+ n] := (neg_neg _).symm @[simp, norm_cast] theorem cast_sub [add_group α] [has_one α] (m n) : ((m - n : ℤ) : α) = m - n := by simp [sub_eq_add_neg] @[simp, norm_cast] theorem cast_mul [ring α] : ∀ m n, ((m * n : ℤ) : α) = m * n | (m : ℕ) (n : ℕ) := nat.cast_mul _ _ | (m : ℕ) -[1+ n] := (cast_neg_of_nat _).trans $ show (-(m * (n + 1) : ℕ) : α) = m * -(n + 1), by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_mul_neg] | -[1+ m] (n : ℕ) := (cast_neg_of_nat _).trans $ show (-((m + 1) * n : ℕ) : α) = -(m + 1) * n, by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_neg_mul] | -[1+ m] -[1+ n] := show (((m + 1) * (n + 1) : ℕ) : α) = -(m + 1) * -(n + 1), by rw [nat.cast_mul, nat.cast_add_one, nat.cast_add_one, neg_mul_neg] /-- `coe : ℤ → α` as an `add_monoid_hom`. -/ def cast_add_hom (α : Type*) [add_group α] [has_one α] : ℤ →+ α := ⟨coe, cast_zero, cast_add⟩ @[simp] lemma coe_cast_add_hom [add_group α] [has_one α] : ⇑(cast_add_hom α) = coe := rfl /-- `coe : ℤ → α` as a `ring_hom`. -/ def cast_ring_hom (α : Type*) [ring α] : ℤ →+* α := ⟨coe, cast_one, cast_mul, cast_zero, cast_add⟩ @[simp] lemma coe_cast_ring_hom [ring α] : ⇑(cast_ring_hom α) = coe := rfl lemma cast_commute [ring α] (m : ℤ) (x : α) : commute ↑m x := int.cases_on m (λ n, n.cast_commute x) (λ n, ((n+1).cast_commute x).neg_left) lemma commute_cast [ring α] (x : α) (m : ℤ) : commute x m := (m.cast_commute x).symm @[simp, norm_cast] theorem coe_nat_bit0 (n : ℕ) : (↑(bit0 n) : ℤ) = bit0 ↑n := by {unfold bit0, simp} @[simp, norm_cast] theorem coe_nat_bit1 (n : ℕ) : (↑(bit1 n) : ℤ) = bit1 ↑n := by {unfold bit1, unfold bit0, simp} @[simp, norm_cast] theorem cast_bit0 [ring α] (n : ℤ) : ((bit0 n : ℤ) : α) = bit0 n := cast_add _ _ @[simp, norm_cast] theorem cast_bit1 [ring α] (n : ℤ) : ((bit1 n : ℤ) : α) = bit1 n := by rw [bit1, cast_add, cast_one, cast_bit0]; refl lemma cast_two [ring α] : ((2 : ℤ) : α) = 2 := by simp theorem cast_nonneg [linear_ordered_ring α] : ∀ {n : ℤ}, (0 : α) ≤ n ↔ 0 ≤ n | (n : ℕ) := by simp | -[1+ n] := by simpa [not_le_of_gt (neg_succ_lt_zero n)] using show -(n:α) < 1, from lt_of_le_of_lt (by simp) zero_lt_one @[simp, norm_cast] theorem cast_le [linear_ordered_ring α] {m n : ℤ} : (m : α) ≤ n ↔ m ≤ n := by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg] @[simp, norm_cast] theorem cast_lt [linear_ordered_ring α] {m n : ℤ} : (m : α) < n ↔ m < n := by simpa [-cast_le] using not_congr (@cast_le α _ n m) @[simp] theorem cast_nonpos [linear_ordered_ring α] {n : ℤ} : (n : α) ≤ 0 ↔ n ≤ 0 := by rw [← cast_zero, cast_le] @[simp] theorem cast_pos [linear_ordered_ring α] {n : ℤ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] @[simp] theorem cast_lt_zero [linear_ordered_ring α] {n : ℤ} : (n : α) < 0 ↔ n < 0 := by rw [← cast_zero, cast_lt] @[simp, norm_cast] theorem cast_min [decidable_linear_ordered_comm_ring α] {a b : ℤ} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [h, min] @[simp, norm_cast] theorem cast_max [decidable_linear_ordered_comm_ring α] {a b : ℤ} : (↑(max a b) : α) = max a b := by by_cases a ≤ b; simp [h, max] @[simp, norm_cast] theorem cast_abs [decidable_linear_ordered_comm_ring α] {q : ℤ} : ((abs q : ℤ) : α) = abs q := by simp [abs] end cast end int open int namespace add_monoid_hom variables {A : Type*} /-- Two additive monoid homomorphisms `f`, `g` from `ℤ` to an additive monoid are equal if `f 1 = g 1`. -/ @[ext] theorem ext_int [add_monoid A] {f g : ℤ →+ A} (h1 : f 1 = g 1) : f = g := have f.comp (int.of_nat_hom : ℕ →+ ℤ) = g.comp (int.of_nat_hom : ℕ →+ ℤ) := ext_nat h1, have ∀ n : ℕ, f n = g n := ext_iff.1 this, ext $ λ n, int.cases_on n this $ λ n, eq_on_neg (this $ n + 1) variables [add_group A] [has_one A] theorem eq_int_cast_hom (f : ℤ →+ A) (h1 : f 1 = 1) : f = int.cast_add_hom A := ext_int $ by simp [h1] theorem eq_int_cast (f : ℤ →+ A) (h1 : f 1 = 1) : ∀ n : ℤ, f n = n := ext_iff.1 (f.eq_int_cast_hom h1) end add_monoid_hom namespace ring_hom variables {α : Type*} {β : Type*} [ring α] [ring β] @[simp] lemma eq_int_cast (f : ℤ →+* α) (n : ℤ) : f n = n := f.to_add_monoid_hom.eq_int_cast f.map_one n lemma eq_int_cast' (f : ℤ →+* α) : f = int.cast_ring_hom α := ring_hom.ext f.eq_int_cast @[simp] lemma map_int_cast (f : α →+* β) (n : ℤ) : f n = n := (f.comp (int.cast_ring_hom α)).eq_int_cast n lemma ext_int {R : Type*} [semiring R] (f g : ℤ →+* R) : f = g := coe_add_monoid_hom_injective $ add_monoid_hom.ext_int $ f.map_one.trans g.map_one.symm instance int.subsingleton_ring_hom {R : Type*} [semiring R] : subsingleton (ℤ →+* R) := ⟨ring_hom.ext_int⟩ end ring_hom @[simp, norm_cast] theorem int.cast_id (n : ℤ) : ↑n = n := ((ring_hom.id ℤ).eq_int_cast n).symm
61333a390585f100dda1209b31036376b1a197f4
63abd62053d479eae5abf4951554e1064a4c45b4
/src/category_theory/limits/presheaf.lean
1909053324f4e419822c6b03d0229155f006ed8e
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
11,661
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.adjunction import category_theory.elements import category_theory.limits.functor_category import category_theory.limits.preserves.limits import category_theory.limits.shapes.terminal import category_theory.limits.types /-! # Colimit of representables This file constructs an adjunction `yoneda_adjunction` between `(Cᵒᵖ ⥤ Type u)` and `ℰ` given a functor `A : C ⥤ ℰ`, where the right adjoint sends `(E : ℰ)` to `c ↦ (A.obj c ⟶ E)` (provided `ℰ` has colimits). This adjunction is used to show that every presheaf is a colimit of representables. Further, the left adjoint `colimit_adj.extend_along_yoneda : (Cᵒᵖ ⥤ Type u) ⥤ ℰ` satisfies `yoneda ⋙ L ≅ A`, that is, an extension of `A : C ⥤ ℰ` to `(Cᵒᵖ ⥤ Type u) ⥤ ℰ` through `yoneda : C ⥤ Cᵒᵖ ⥤ Type u`. It is the left Kan extension of `A` along the yoneda embedding, sometimes known as the Yoneda extension. `unique_extension_along_yoneda` shows `extend_along_yoneda` is unique amongst cocontinuous functors with this property, establishing the presheaf category as the free cocompletion of a small category. ## Tags colimit, representable, presheaf, free cocompletion ## References * [S. MacLane, I. Moerdijk, *Sheaves in Geometry and Logic*][MM92] * https://ncatlab.org/nlab/show/Yoneda+extension -/ namespace category_theory noncomputable theory open category limits universes u₁ u₂ variables {C : Type u₁} [small_category C] variables {ℰ : Type u₂} [category.{u₁} ℰ] variable (A : C ⥤ ℰ) namespace colimit_adj /-- The functor taking `(E : ℰ) (c : Cᵒᵖ)` to the homset `(A.obj C ⟶ E)`. It is shown in `L_adjunction` that this functor has a left adjoint (provided `E` has colimits) given by taking colimits over categories of elements. In the case where `ℰ = Cᵒᵖ ⥤ Type u` and `A = yoneda`, this functor is isomorphic to the identity. Defined as in [MM92], Chapter I, Section 5, Theorem 2. -/ @[simps {rhs_md := semireducible}] def restricted_yoneda : ℰ ⥤ (Cᵒᵖ ⥤ Type u₁) := yoneda ⋙ (whiskering_left _ _ (Type u₁)).obj (functor.op A) /-- The functor `restricted_yoneda` is isomorphic to the identity functor when evaluated at the yoneda embedding. -/ def restricted_yoneda_yoneda : restricted_yoneda (yoneda : C ⥤ Cᵒᵖ ⥤ Type u₁) ≅ 𝟭 _ := nat_iso.of_components (λ P, nat_iso.of_components (λ X, yoneda_sections_small X.unop _) (λ X Y f, funext $ λ x, begin dsimp, rw ← functor_to_types.naturality _ _ x f (𝟙 _), dsimp, simp, end)) (λ _ _ _, rfl) /-- (Implementation). The equivalence of homsets which helps construct the left adjoint to `colimit_adj.restricted_yoneda`. It is shown in `restrict_yoneda_hom_equiv_natural` that this is a natural bijection. -/ def restrict_yoneda_hom_equiv (P : Cᵒᵖ ⥤ Type u₁) (E : ℰ) {c : cocone ((category_of_elements.π P).left_op ⋙ A)} (t : is_colimit c) : (c.X ⟶ E) ≃ (P ⟶ (restricted_yoneda A).obj E) := (t.hom_iso' E).to_equiv.trans { to_fun := λ k, { app := λ c p, k.1 (opposite.op ⟨_, p⟩), naturality' := λ c c' f, funext $ λ p, (k.2 (has_hom.hom.op ⟨f, rfl⟩ : (opposite.op ⟨c', P.map f p⟩ : P.elementsᵒᵖ) ⟶ opposite.op ⟨c, p⟩)).symm }, inv_fun := λ τ, { val := λ p, τ.app p.unop.1 p.unop.2, property := λ p p' f, begin simp_rw [← f.unop.2], apply (congr_fun (τ.naturality f.unop.1) p'.unop.2).symm, end }, left_inv := begin rintro ⟨k₁, k₂⟩, ext, dsimp, congr' 1, simp, end, right_inv := begin rintro ⟨_, _⟩, refl, end } /-- (Implementation). Show that the bijection in `restrict_yoneda_hom_equiv` is natural (on the right). -/ lemma restrict_yoneda_hom_equiv_natural (P : Cᵒᵖ ⥤ Type u₁) (E₁ E₂ : ℰ) (g : E₁ ⟶ E₂) {c : cocone _} (t : is_colimit c) (k : c.X ⟶ E₁) : restrict_yoneda_hom_equiv A P E₂ t (k ≫ g) = restrict_yoneda_hom_equiv A P E₁ t k ≫ (restricted_yoneda A).map g := begin ext _ X p, apply (assoc _ _ _).symm, end variables [has_colimits ℰ] /-- The left adjoint to the functor `restricted_yoneda` (shown in `yoneda_adjunction`). It is also an extension of `A` along the yoneda embedding (shown in `is_extension_along_yoneda`), in particular it is the left Kan extension of `A` through the yoneda embedding. -/ def extend_along_yoneda : (Cᵒᵖ ⥤ Type u₁) ⥤ ℰ := adjunction.left_adjoint_of_equiv (λ P E, restrict_yoneda_hom_equiv A P E (colimit.is_colimit _)) (λ P E E' g, restrict_yoneda_hom_equiv_natural A P E E' g _) @[simp] lemma extend_along_yoneda_obj (P : Cᵒᵖ ⥤ Type u₁) : (extend_along_yoneda A).obj P = colimit ((category_of_elements.π P).left_op ⋙ A) := rfl /-- Show `extend_along_yoneda` is left adjoint to `restricted_yoneda`. The construction of [MM92], Chapter I, Section 5, Theorem 2. -/ def yoneda_adjunction : extend_along_yoneda A ⊣ restricted_yoneda A := adjunction.adjunction_of_equiv_left _ _ /-- The initial object in the category of elements for a representable functor. In `is_initial` it is shown that this is initial. -/ def elements.initial (A : C) : (yoneda.obj A).elements := ⟨opposite.op A, 𝟙 _⟩ /-- Show that `elements.initial A` is initial in the category of elements for the `yoneda` functor. -/ def is_initial (A : C) : is_initial (elements.initial A) := { desc := λ s, ⟨s.X.2.op, comp_id _⟩, uniq' := λ s m w, begin simp_rw ← m.2, dsimp [elements.initial], simp, end } /-- `extend_along_yoneda A` is an extension of `A` to the presheaf category along the yoneda embedding. `unique_extension_along_yoneda` shows it is unique among functors preserving colimits with this property (up to isomorphism). The first part of [MM92], Chapter I, Section 5, Corollary 4. See Property 1 of https://ncatlab.org/nlab/show/Yoneda+extension#properties. -/ def is_extension_along_yoneda : (yoneda : C ⥤ Cᵒᵖ ⥤ Type u₁) ⋙ extend_along_yoneda A ≅ A := nat_iso.of_components (λ X, (colimit.is_colimit _).cocone_point_unique_up_to_iso (colimit_of_diagram_terminal (terminal_op_of_initial (is_initial _)) _)) begin intros X Y f, change (colimit.desc _ ⟨_, _⟩ ≫ colimit.desc _ _) = colimit.desc _ _ ≫ _, apply colimit.hom_ext, intro j, rw [colimit.ι_desc_assoc, colimit.ι_desc_assoc], change (colimit.ι _ _ ≫ 𝟙 _) ≫ colimit.desc _ _ = _, rw [comp_id, colimit.ι_desc], dsimp, rw ← A.map_comp, congr' 1, end /-- See Property 2 of https://ncatlab.org/nlab/show/Yoneda+extension#properties. -/ instance : preserves_colimits (extend_along_yoneda A) := (yoneda_adjunction A).left_adjoint_preserves_colimits end colimit_adj open colimit_adj /-- Since `extend_along_yoneda A` is adjoint to `restricted_yoneda A`, if we use `A = yoneda` then `restricted_yoneda A` is isomorphic to the identity, and so `extend_along_yoneda A` is as well. -/ def extend_along_yoneda_yoneda : extend_along_yoneda (yoneda : C ⥤ _) ≅ 𝟭 _ := adjunction.nat_iso_of_right_adjoint_nat_iso (yoneda_adjunction _) adjunction.id restricted_yoneda_yoneda /-- A functor to the presheaf category in which everything in the image is representable (witnessed by the fact that it factors through the yoneda embedding). `cocone_of_representable` gives a cocone for this functor which is a colimit and has point `P`. -/ -- Maybe this should be reducible or an abbreviation? def functor_to_representables (P : Cᵒᵖ ⥤ Type u₁) : (P.elements)ᵒᵖ ⥤ Cᵒᵖ ⥤ Type u₁ := (category_of_elements.π P).left_op ⋙ yoneda /-- This is a cocone with point `P` for the functor `functor_to_representables P`. It is shown in `colimit_of_representable P` that this cocone is a colimit: that is, we have exhibited an arbitrary presheaf `P` as a colimit of representables. The construction of [MM92], Chapter I, Section 5, Corollary 3. -/ def cocone_of_representable (P : Cᵒᵖ ⥤ Type u₁) : cocone (functor_to_representables P) := cocone.extend (colimit.cocone _) (extend_along_yoneda_yoneda.hom.app P) @[simp] lemma cocone_of_representable_X (P : Cᵒᵖ ⥤ Type u₁) : (cocone_of_representable P).X = P := rfl /-- An explicit formula for the legs of the cocone `cocone_of_representable`. -/ -- Marking this as a simp lemma seems to make things more awkward. lemma cocone_of_representable_ι_app (P : Cᵒᵖ ⥤ Type u₁) (j : (P.elements)ᵒᵖ): (cocone_of_representable P).ι.app j = (yoneda_sections_small _ _).inv j.unop.2 := colimit.ι_desc _ _ /-- The legs of the cocone `cocone_of_representable` are natural in the choice of presheaf. -/ lemma cocone_of_representable_naturality {P₁ P₂ : Cᵒᵖ ⥤ Type u₁} (α : P₁ ⟶ P₂) (j : (P₁.elements)ᵒᵖ) : (cocone_of_representable P₁).ι.app j ≫ α = (cocone_of_representable P₂).ι.app ((category_of_elements.map α).op.obj j) := begin ext T f, simpa [cocone_of_representable_ι_app] using functor_to_types.naturality _ _ α f.op _, end /-- The cocone with point `P` given by `the_cocone` is a colimit: that is, we have exhibited an arbitrary presheaf `P` as a colimit of representables. The result of [MM92], Chapter I, Section 5, Corollary 3. -/ def colimit_of_representable (P : Cᵒᵖ ⥤ Type u₁) : is_colimit (cocone_of_representable P) := begin apply is_colimit.of_point_iso (colimit.is_colimit (functor_to_representables P)), change is_iso (colimit.desc _ (cocone.extend _ _)), rw [colimit.desc_extend, colimit.desc_cocone], apply_instance, end /-- Given two functors L₁ and L₂ which preserve colimits, if they agree when restricted to the representable presheaves then they agree everywhere. -/ def nat_iso_of_nat_iso_on_representables (L₁ L₂ : (Cᵒᵖ ⥤ Type u₁) ⥤ ℰ) [preserves_colimits L₁] [preserves_colimits L₂] (h : yoneda ⋙ L₁ ≅ yoneda ⋙ L₂) : L₁ ≅ L₂ := begin apply nat_iso.of_components _ _, { intro P, refine (is_colimit_of_preserves L₁ (colimit_of_representable P)).cocone_points_iso_of_nat_iso (is_colimit_of_preserves L₂ (colimit_of_representable P)) _, apply functor.associator _ _ _ ≪≫ _, exact iso_whisker_left (category_of_elements.π P).left_op h }, { intros P₁ P₂ f, apply (is_colimit_of_preserves L₁ (colimit_of_representable P₁)).hom_ext, intro j, dsimp only [id.def, is_colimit.cocone_points_iso_of_nat_iso_hom, iso_whisker_left_hom], have : (L₁.map_cocone (cocone_of_representable P₁)).ι.app j ≫ L₁.map f = (L₁.map_cocone (cocone_of_representable P₂)).ι.app ((category_of_elements.map f).op.obj j), { dsimp, rw [← L₁.map_comp, cocone_of_representable_naturality], refl }, rw [reassoc_of this, is_colimit.ι_map_assoc, is_colimit.ι_map], dsimp, rw [← L₂.map_comp, cocone_of_representable_naturality], refl } end variable [has_colimits ℰ] /-- Show that `extend_along_yoneda` is the unique colimit-preserving functor which extends `A` to the presheaf category. The second part of [MM92], Chapter I, Section 5, Corollary 4. See Property 3 of https://ncatlab.org/nlab/show/Yoneda+extension#properties. -/ def unique_extension_along_yoneda (L : (Cᵒᵖ ⥤ Type u₁) ⥤ ℰ) (hL : yoneda ⋙ L ≅ A) [preserves_colimits L] : L ≅ extend_along_yoneda A := nat_iso_of_nat_iso_on_representables _ _ (hL ≪≫ (is_extension_along_yoneda _).symm) end category_theory
982b568824b315db0ed9571285868eab32db4bbe
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/dynamics/periodic_pts_auto.lean
d0fe63994c4d81e7103155ae9a4ee2370a954d1b
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
10,769
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Yury G. Kudryashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.dynamics.fixed_points.basic import Mathlib.data.set.lattice import Mathlib.data.pnat.basic import Mathlib.PostPort universes u_1 u_2 namespace Mathlib /-! # Periodic points A point `x : α` is a periodic point of `f : α → α` of period `n` if `f^[n] x = x`. ## Main definitions * `is_periodic_pt f n x` : `x` is a periodic point of `f` of period `n`, i.e. `f^[n] x = x`. We do not require `n > 0` in the definition. * `pts_of_period f n` : the set `{x | is_periodic_pt f n x}`. Note that `n` is not required to be the minimal period of `x`. * `periodic_pts f` : the set of all periodic points of `f`. * `minimal_period f x` : the minimal period of a point `x` under an endomorphism `f` or zero if `x` is not a periodic point of `f`. ## Main statements We provide “dot syntax”-style operations on terms of the form `h : is_periodic_pt f n x` including arithmetic operations on `n` and `h.map (hg : semiconj_by g f f')`. We also prove that `f` is bijective on each set `pts_of_period f n` and on `periodic_pts f`. Finally, we prove that `x` is a periodic point of `f` of period `n` if and only if `minimal_period f x | n`. ## References * https://en.wikipedia.org/wiki/Periodic_point -/ namespace function /-- A point `x` is a periodic point of `f : α → α` of period `n` if `f^[n] x = x`. Note that we do not require `0 < n` in this definition. Many theorems about periodic points need this assumption. -/ def is_periodic_pt {α : Type u_1} (f : α → α) (n : ℕ) (x : α) := is_fixed_pt (nat.iterate f n) x /-- A fixed point of `f` is a periodic point of `f` of any prescribed period. -/ theorem is_fixed_pt.is_periodic_pt {α : Type u_1} {f : α → α} {x : α} (hf : is_fixed_pt f x) (n : ℕ) : is_periodic_pt f n x := is_fixed_pt.iterate hf n /-- For the identity map, all points are periodic. -/ theorem is_periodic_id {α : Type u_1} (n : ℕ) (x : α) : is_periodic_pt id n x := is_fixed_pt.is_periodic_pt (is_fixed_pt_id x) n /-- Any point is a periodic point of period `0`. -/ theorem is_periodic_pt_zero {α : Type u_1} (f : α → α) (x : α) : is_periodic_pt f 0 x := is_fixed_pt_id x namespace is_periodic_pt protected instance decidable {α : Type u_1} [DecidableEq α] {f : α → α} {n : ℕ} {x : α} : Decidable (is_periodic_pt f n x) := is_fixed_pt.decidable protected theorem is_fixed_pt {α : Type u_1} {f : α → α} {x : α} {n : ℕ} (hf : is_periodic_pt f n x) : is_fixed_pt (nat.iterate f n) x := hf protected theorem map {α : Type u_1} {β : Type u_2} {fa : α → α} {fb : β → β} {x : α} {n : ℕ} (hx : is_periodic_pt fa n x) {g : α → β} (hg : semiconj g fa fb) : is_periodic_pt fb n (g x) := is_fixed_pt.map hx (semiconj.iterate_right hg n) theorem apply_iterate {α : Type u_1} {f : α → α} {x : α} {n : ℕ} (hx : is_periodic_pt f n x) (m : ℕ) : is_periodic_pt f n (nat.iterate f m x) := is_periodic_pt.map hx (commute.iterate_self f m) protected theorem apply {α : Type u_1} {f : α → α} {x : α} {n : ℕ} (hx : is_periodic_pt f n x) : is_periodic_pt f n (f x) := apply_iterate hx 1 protected theorem add {α : Type u_1} {f : α → α} {x : α} {m : ℕ} {n : ℕ} (hn : is_periodic_pt f n x) (hm : is_periodic_pt f m x) : is_periodic_pt f (n + m) x := eq.mpr (id (Eq._oldrec (Eq.refl (is_periodic_pt f (n + m) x)) (equations._eqn_1 f (n + m) x))) (eq.mpr (id (Eq._oldrec (Eq.refl (is_fixed_pt (nat.iterate f (n + m)) x)) (iterate_add f n m))) (is_fixed_pt.comp hn hm)) theorem left_of_add {α : Type u_1} {f : α → α} {x : α} {m : ℕ} {n : ℕ} (hn : is_periodic_pt f (n + m) x) (hm : is_periodic_pt f m x) : is_periodic_pt f n x := sorry theorem right_of_add {α : Type u_1} {f : α → α} {x : α} {m : ℕ} {n : ℕ} (hn : is_periodic_pt f (n + m) x) (hm : is_periodic_pt f n x) : is_periodic_pt f m x := left_of_add (eq.mp (Eq._oldrec (Eq.refl (is_periodic_pt f (n + m) x)) (add_comm n m)) hn) hm protected theorem sub {α : Type u_1} {f : α → α} {x : α} {m : ℕ} {n : ℕ} (hm : is_periodic_pt f m x) (hn : is_periodic_pt f n x) : is_periodic_pt f (m - n) x := sorry protected theorem mul_const {α : Type u_1} {f : α → α} {x : α} {m : ℕ} (hm : is_periodic_pt f m x) (n : ℕ) : is_periodic_pt f (m * n) x := sorry protected theorem const_mul {α : Type u_1} {f : α → α} {x : α} {m : ℕ} (hm : is_periodic_pt f m x) (n : ℕ) : is_periodic_pt f (n * m) x := sorry theorem trans_dvd {α : Type u_1} {f : α → α} {x : α} {m : ℕ} (hm : is_periodic_pt f m x) {n : ℕ} (hn : m ∣ n) : is_periodic_pt f n x := sorry protected theorem iterate {α : Type u_1} {f : α → α} {x : α} {n : ℕ} (hf : is_periodic_pt f n x) (m : ℕ) : is_periodic_pt (nat.iterate f m) n x := sorry protected theorem mod {α : Type u_1} {f : α → α} {x : α} {m : ℕ} {n : ℕ} (hm : is_periodic_pt f m x) (hn : is_periodic_pt f n x) : is_periodic_pt f (m % n) x := left_of_add (eq.mp (Eq._oldrec (Eq.refl (is_periodic_pt f m x)) (Eq.symm (nat.mod_add_div m n))) hm) (is_periodic_pt.mul_const hn (m / n)) protected theorem gcd {α : Type u_1} {f : α → α} {x : α} {m : ℕ} {n : ℕ} (hm : is_periodic_pt f m x) (hn : is_periodic_pt f n x) : is_periodic_pt f (nat.gcd m n) x := sorry /-- If `f` sends two periodic points `x` and `y` of the same positive period to the same point, then `x = y`. For a similar statement about points of different periods see `eq_of_apply_eq`. -/ theorem eq_of_apply_eq_same {α : Type u_1} {f : α → α} {x : α} {y : α} {n : ℕ} (hx : is_periodic_pt f n x) (hy : is_periodic_pt f n y) (hn : 0 < n) (h : f x = f y) : x = y := sorry /-- If `f` sends two periodic points `x` and `y` of positive periods to the same point, then `x = y`. -/ theorem eq_of_apply_eq {α : Type u_1} {f : α → α} {x : α} {y : α} {m : ℕ} {n : ℕ} (hx : is_periodic_pt f m x) (hy : is_periodic_pt f n y) (hm : 0 < m) (hn : 0 < n) (h : f x = f y) : x = y := eq_of_apply_eq_same (is_periodic_pt.mul_const hx n) (is_periodic_pt.const_mul hy m) (mul_pos hm hn) h end is_periodic_pt /-- The set of periodic points of a given (possibly non-minimal) period. -/ def pts_of_period {α : Type u_1} (f : α → α) (n : ℕ) : set α := set_of fun (x : α) => is_periodic_pt f n x @[simp] theorem mem_pts_of_period {α : Type u_1} {f : α → α} {x : α} {n : ℕ} : x ∈ pts_of_period f n ↔ is_periodic_pt f n x := iff.rfl theorem semiconj.maps_to_pts_of_period {α : Type u_1} {β : Type u_2} {fa : α → α} {fb : β → β} {g : α → β} (h : semiconj g fa fb) (n : ℕ) : set.maps_to g (pts_of_period fa n) (pts_of_period fb n) := semiconj.maps_to_fixed_pts (semiconj.iterate_right h n) theorem bij_on_pts_of_period {α : Type u_1} (f : α → α) {n : ℕ} (hn : 0 < n) : set.bij_on f (pts_of_period f n) (pts_of_period f n) := sorry theorem directed_pts_of_period_pnat {α : Type u_1} (f : α → α) : directed has_subset.subset fun (n : ℕ+) => pts_of_period f ↑n := sorry /-- The set of periodic points of a map `f : α → α`. -/ def periodic_pts {α : Type u_1} (f : α → α) : set α := set_of fun (x : α) => ∃ (n : ℕ), ∃ (H : n > 0), is_periodic_pt f n x theorem mk_mem_periodic_pts {α : Type u_1} {f : α → α} {x : α} {n : ℕ} (hn : 0 < n) (hx : is_periodic_pt f n x) : x ∈ periodic_pts f := Exists.intro n (Exists.intro hn hx) theorem mem_periodic_pts {α : Type u_1} {f : α → α} {x : α} : x ∈ periodic_pts f ↔ ∃ (n : ℕ), ∃ (H : n > 0), is_periodic_pt f n x := iff.rfl theorem bUnion_pts_of_period {α : Type u_1} (f : α → α) : (set.Union fun (n : ℕ) => set.Union fun (H : n > 0) => pts_of_period f n) = periodic_pts f := sorry theorem Union_pnat_pts_of_period {α : Type u_1} (f : α → α) : (set.Union fun (n : ℕ+) => pts_of_period f ↑n) = periodic_pts f := Eq.trans supr_subtype (bUnion_pts_of_period f) theorem bij_on_periodic_pts {α : Type u_1} (f : α → α) : set.bij_on f (periodic_pts f) (periodic_pts f) := Union_pnat_pts_of_period f ▸ set.bij_on_Union_of_directed (directed_pts_of_period_pnat f) fun (i : ℕ+) => bij_on_pts_of_period f (pnat.pos i) theorem semiconj.maps_to_periodic_pts {α : Type u_1} {β : Type u_2} {fa : α → α} {fb : β → β} {g : α → β} (h : semiconj g fa fb) : set.maps_to g (periodic_pts fa) (periodic_pts fb) := sorry /-- Minimal period of a point `x` under an endomorphism `f`. If `x` is not a periodic point of `f`, then `minimal_period f x = 0`. -/ def minimal_period {α : Type u_1} (f : α → α) (x : α) : ℕ := dite (x ∈ periodic_pts f) (fun (h : x ∈ periodic_pts f) => nat.find h) fun (h : ¬x ∈ periodic_pts f) => 0 theorem is_periodic_pt_minimal_period {α : Type u_1} (f : α → α) (x : α) : is_periodic_pt f (minimal_period f x) x := sorry theorem minimal_period_pos_of_mem_periodic_pts {α : Type u_1} {f : α → α} {x : α} (hx : x ∈ periodic_pts f) : 0 < minimal_period f x := sorry theorem is_periodic_pt.minimal_period_pos {α : Type u_1} {f : α → α} {x : α} {n : ℕ} (hn : 0 < n) (hx : is_periodic_pt f n x) : 0 < minimal_period f x := minimal_period_pos_of_mem_periodic_pts (mk_mem_periodic_pts hn hx) theorem minimal_period_pos_iff_mem_periodic_pts {α : Type u_1} {f : α → α} {x : α} : 0 < minimal_period f x ↔ x ∈ periodic_pts f := sorry theorem is_periodic_pt.minimal_period_le {α : Type u_1} {f : α → α} {x : α} {n : ℕ} (hn : 0 < n) (hx : is_periodic_pt f n x) : minimal_period f x ≤ n := sorry theorem is_periodic_pt.eq_zero_of_lt_minimal_period {α : Type u_1} {f : α → α} {x : α} {n : ℕ} (hx : is_periodic_pt f n x) (hn : n < minimal_period f x) : n = 0 := Eq.symm (or.resolve_right (eq_or_lt_of_le (nat.zero_le n)) fun (hn0 : 0 < n) => iff.mpr not_lt (is_periodic_pt.minimal_period_le hn0 hx) hn) theorem is_periodic_pt.minimal_period_dvd {α : Type u_1} {f : α → α} {x : α} {n : ℕ} (hx : is_periodic_pt f n x) : minimal_period f x ∣ n := sorry theorem is_periodic_pt_iff_minimal_period_dvd {α : Type u_1} {f : α → α} {x : α} {n : ℕ} : is_periodic_pt f n x ↔ minimal_period f x ∣ n := { mp := is_periodic_pt.minimal_period_dvd, mpr := fun (h : minimal_period f x ∣ n) => is_periodic_pt.trans_dvd (is_periodic_pt_minimal_period f x) h } end Mathlib
961d9eb9c7d24d3783932abc21b154677ac7543f
4727251e0cd73359b15b664c3170e5d754078599
/test/library_search/ring_theory.lean
11c3534b0b6e24f47c81892ee6700215bf71e265
[ "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
768
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import tactic.suggest import ring_theory.principal_ideal_domain import ring_theory.polynomial open_locale polynomial /- Turn off trace messages so they don't pollute the test build: -/ set_option trace.silence_library_search true example {α : Type} [euclidean_domain α] {S : ideal α} {x y : α} (hy : y ∈ S) : x % y ∈ S ↔ x ∈ S := by library_search -- exact mod_mem_iff hy variables {R : Type} [comm_ring R] [decidable_eq R] variables {I : ideal R[X]} example {m n : ℕ} (H : m ≤ n) : I.leading_coeff_nth m ≤ I.leading_coeff_nth n := by library_search -- exact ideal.leading_coeff_nth_mono I H
b84a969f7b1bd82b0fc3f48ba42977dbfc83c214
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/nat/modeq_auto.lean
5dabd559d1038f7b96ba2483d9a04294b79feef9
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
9,760
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.gcd import Mathlib.tactic.abel import Mathlib.data.list.rotate import Mathlib.PostPort universes u_1 namespace Mathlib /- # Congruences modulo a natural number This file defines the equivalence relation `a ≡ b [MOD n]` on the natural numbers, and proves basic properties about it such as the Chinese Remainder Theorem `modeq_and_modeq_iff_modeq_mul`. ## Notations `a ≡ b [MOD n]` is notation for `modeq n a b`, which is defined to mean `a % n = b % n`. ## Tags modeq, congruence, mod, MOD, modulo -/ namespace nat /-- Modular equality. `modeq n a b`, or `a ≡ b [MOD n]`, means that `a - b` is a multiple of `n`. -/ def modeq (n : ℕ) (a : ℕ) (b : ℕ) := a % n = b % n namespace modeq protected theorem refl {n : ℕ} (a : ℕ) : modeq n a a := rfl protected theorem symm {n : ℕ} {a : ℕ} {b : ℕ} : modeq n a b → modeq n b a := Eq.symm protected theorem trans {n : ℕ} {a : ℕ} {b : ℕ} {c : ℕ} : modeq n a b → modeq n b c → modeq n a c := Eq.trans protected theorem comm {n : ℕ} {a : ℕ} {b : ℕ} : modeq n a b ↔ modeq n b a := { mp := modeq.symm, mpr := modeq.symm } theorem modeq_zero_iff {n : ℕ} {a : ℕ} : modeq n a 0 ↔ n ∣ a := eq.mpr (id (Eq._oldrec (Eq.refl (modeq n a 0 ↔ n ∣ a)) (equations._eqn_1 n a 0))) (eq.mpr (id (Eq._oldrec (Eq.refl (a % n = 0 % n ↔ n ∣ a)) (zero_mod n))) (eq.mpr (id (Eq._oldrec (Eq.refl (a % n = 0 ↔ n ∣ a)) (propext (dvd_iff_mod_eq_zero n a)))) (iff.refl (a % n = 0)))) theorem modeq_iff_dvd {n : ℕ} {a : ℕ} {b : ℕ} : modeq n a b ↔ ↑n ∣ ↑b - ↑a := sorry theorem modeq_of_dvd {n : ℕ} {a : ℕ} {b : ℕ} : ↑n ∣ ↑b - ↑a → modeq n a b := iff.mpr modeq_iff_dvd theorem dvd_of_modeq {n : ℕ} {a : ℕ} {b : ℕ} : modeq n a b → ↑n ∣ ↑b - ↑a := iff.mp modeq_iff_dvd /-- A variant of `modeq_iff_dvd` with `nat` divisibility -/ theorem modeq_iff_dvd' {n : ℕ} {a : ℕ} {b : ℕ} (h : a ≤ b) : modeq n a b ↔ n ∣ b - a := eq.mpr (id (Eq._oldrec (Eq.refl (modeq n a b ↔ n ∣ b - a)) (propext modeq_iff_dvd))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑n ∣ ↑b - ↑a ↔ n ∣ b - a)) (Eq.symm (propext int.coe_nat_dvd)))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑n ∣ ↑b - ↑a ↔ ↑n ∣ ↑(b - a))) (int.coe_nat_sub h))) (iff.refl (↑n ∣ ↑b - ↑a)))) theorem mod_modeq (a : ℕ) (n : ℕ) : modeq n (a % n) a := mod_mod a n theorem modeq_of_dvd_of_modeq {n : ℕ} {m : ℕ} {a : ℕ} {b : ℕ} (d : m ∣ n) (h : modeq n a b) : modeq m a b := modeq_of_dvd (dvd_trans (iff.mpr int.coe_nat_dvd d) (dvd_of_modeq h)) theorem modeq_mul_left' {n : ℕ} {a : ℕ} {b : ℕ} (c : ℕ) (h : modeq n a b) : modeq (c * n) (c * a) (c * b) := sorry theorem modeq_mul_left {n : ℕ} {a : ℕ} {b : ℕ} (c : ℕ) (h : modeq n a b) : modeq n (c * a) (c * b) := modeq_of_dvd_of_modeq (dvd_mul_left n c) (modeq_mul_left' c h) theorem modeq_mul_right' {n : ℕ} {a : ℕ} {b : ℕ} (c : ℕ) (h : modeq n a b) : modeq (n * c) (a * c) (b * c) := eq.mpr (id (Eq._oldrec (Eq.refl (modeq (n * c) (a * c) (b * c))) (mul_comm a c))) (eq.mpr (id (Eq._oldrec (Eq.refl (modeq (n * c) (c * a) (b * c))) (mul_comm b c))) (eq.mpr (id (Eq._oldrec (Eq.refl (modeq (n * c) (c * a) (c * b))) (mul_comm n c))) (modeq_mul_left' c h))) theorem modeq_mul_right {n : ℕ} {a : ℕ} {b : ℕ} (c : ℕ) (h : modeq n a b) : modeq n (a * c) (b * c) := eq.mpr (id (Eq._oldrec (Eq.refl (modeq n (a * c) (b * c))) (mul_comm a c))) (eq.mpr (id (Eq._oldrec (Eq.refl (modeq n (c * a) (b * c))) (mul_comm b c))) (modeq_mul_left c h)) theorem modeq_mul {n : ℕ} {a : ℕ} {b : ℕ} {c : ℕ} {d : ℕ} (h₁ : modeq n a b) (h₂ : modeq n c d) : modeq n (a * c) (b * d) := modeq.trans (modeq_mul_left a h₂) (modeq_mul_right d h₁) theorem modeq_pow {n : ℕ} {a : ℕ} {b : ℕ} (m : ℕ) (h : modeq n a b) : modeq n (a ^ m) (b ^ m) := sorry theorem modeq_add {n : ℕ} {a : ℕ} {b : ℕ} {c : ℕ} {d : ℕ} (h₁ : modeq n a b) (h₂ : modeq n c d) : modeq n (a + c) (b + d) := sorry theorem modeq_add_cancel_left {n : ℕ} {a : ℕ} {b : ℕ} {c : ℕ} {d : ℕ} (h₁ : modeq n a b) (h₂ : modeq n (a + c) (b + d)) : modeq n c d := sorry theorem modeq_add_cancel_right {n : ℕ} {a : ℕ} {b : ℕ} {c : ℕ} {d : ℕ} (h₁ : modeq n c d) (h₂ : modeq n (a + c) (b + d)) : modeq n a b := modeq_add_cancel_left h₁ (eq.mp (Eq._oldrec (Eq.refl (modeq n (c + a) (b + d))) (add_comm b d)) (eq.mp (Eq._oldrec (Eq.refl (modeq n (a + c) (b + d))) (add_comm a c)) h₂)) theorem modeq_of_modeq_mul_left {n : ℕ} {a : ℕ} {b : ℕ} (m : ℕ) (h : modeq (m * n) a b) : modeq n a b := eq.mpr (id (Eq._oldrec (Eq.refl (modeq n a b)) (propext modeq_iff_dvd))) (dvd.trans (dvd_mul_left ↑n ↑m) (eq.mp (Eq._oldrec (Eq.refl (modeq (m * n) a b)) (propext modeq_iff_dvd)) h)) theorem modeq_of_modeq_mul_right {n : ℕ} {a : ℕ} {b : ℕ} (m : ℕ) : modeq (n * m) a b → modeq n a b := mul_comm m n ▸ modeq_of_modeq_mul_left m theorem modeq_one {a : ℕ} {b : ℕ} : modeq 1 a b := modeq_of_dvd (one_dvd (↑b - ↑a)) /-- The natural number less than `lcm n m` congruent to `a` mod `n` and `b` mod `m` -/ def chinese_remainder' {n : ℕ} {m : ℕ} {a : ℕ} {b : ℕ} (h : modeq (gcd n m) a b) : Subtype fun (k : ℕ) => modeq n k a ∧ modeq m k b := dite (n = 0) (fun (hn : n = 0) => { val := a, property := sorry }) fun (hn : ¬n = 0) => dite (m = 0) (fun (hm : m = 0) => { val := b, property := sorry }) fun (hm : ¬m = 0) => { val := sorry, property := sorry } /-- The natural number less than `n*m` congruent to `a` mod `n` and `b` mod `m` -/ def chinese_remainder {n : ℕ} {m : ℕ} (co : coprime n m) (a : ℕ) (b : ℕ) : Subtype fun (k : ℕ) => modeq n k a ∧ modeq m k b := chinese_remainder' sorry theorem modeq_and_modeq_iff_modeq_mul {a : ℕ} {b : ℕ} {m : ℕ} {n : ℕ} (hmn : coprime m n) : modeq m a b ∧ modeq n a b ↔ modeq (m * n) a b := sorry theorem coprime_of_mul_modeq_one (b : ℕ) {a : ℕ} {n : ℕ} (h : modeq n (a * b) 1) : coprime a n := sorry end modeq @[simp] theorem mod_mul_right_mod (a : ℕ) (b : ℕ) (c : ℕ) : a % (b * c) % b = a % b := modeq.modeq_of_modeq_mul_right c (modeq.mod_modeq a (b * c)) @[simp] theorem mod_mul_left_mod (a : ℕ) (b : ℕ) (c : ℕ) : a % (b * c) % c = a % c := modeq.modeq_of_modeq_mul_left b (modeq.mod_modeq a (b * c)) theorem div_mod_eq_mod_mul_div (a : ℕ) (b : ℕ) (c : ℕ) : a / b % c = a % (b * c) / b := sorry theorem add_mod_add_ite (a : ℕ) (b : ℕ) (c : ℕ) : (a + b) % c + ite (c ≤ a % c + b % c) c 0 = a % c + b % c := sorry theorem add_mod_of_add_mod_lt {a : ℕ} {b : ℕ} {c : ℕ} (hc : a % c + b % c < c) : (a + b) % c = a % c + b % c := sorry theorem add_mod_add_of_le_add_mod {a : ℕ} {b : ℕ} {c : ℕ} (hc : c ≤ a % c + b % c) : (a + b) % c + c = a % c + b % c := eq.mpr (id (Eq._oldrec (Eq.refl ((a + b) % c + c = a % c + b % c)) (Eq.symm (add_mod_add_ite a b c)))) (eq.mpr (id (Eq._oldrec (Eq.refl ((a + b) % c + c = (a + b) % c + ite (c ≤ a % c + b % c) c 0)) (if_pos hc))) (Eq.refl ((a + b) % c + c))) theorem add_div {a : ℕ} {b : ℕ} {c : ℕ} (hc0 : 0 < c) : (a + b) / c = a / c + b / c + ite (c ≤ a % c + b % c) 1 0 := sorry theorem add_div_eq_of_add_mod_lt {a : ℕ} {b : ℕ} {c : ℕ} (hc : a % c + b % c < c) : (a + b) / c = a / c + b / c := sorry protected theorem add_div_of_dvd_right {a : ℕ} {b : ℕ} {c : ℕ} (hca : c ∣ a) : (a + b) / c = a / c + b / c := sorry protected theorem add_div_of_dvd_left {a : ℕ} {b : ℕ} {c : ℕ} (hca : c ∣ b) : (a + b) / c = a / c + b / c := sorry theorem add_div_eq_of_le_mod_add_mod {a : ℕ} {b : ℕ} {c : ℕ} (hc : c ≤ a % c + b % c) (hc0 : 0 < c) : (a + b) / c = a / c + b / c + 1 := eq.mpr (id (Eq._oldrec (Eq.refl ((a + b) / c = a / c + b / c + 1)) (add_div hc0))) (eq.mpr (id (Eq._oldrec (Eq.refl (a / c + b / c + ite (c ≤ a % c + b % c) 1 0 = a / c + b / c + 1)) (if_pos hc))) (Eq.refl (a / c + b / c + 1))) theorem add_div_le_add_div (a : ℕ) (b : ℕ) (c : ℕ) : a / c + b / c ≤ (a + b) / c := sorry theorem le_mod_add_mod_of_dvd_add_of_not_dvd {a : ℕ} {b : ℕ} {c : ℕ} (h : c ∣ a + b) (ha : ¬c ∣ a) : c ≤ a % c + b % c := sorry theorem odd_mul_odd {n : ℕ} {m : ℕ} (hn1 : n % bit0 1 = 1) (hm1 : m % bit0 1 = 1) : n * m % bit0 1 = 1 := (fun (this : n * m % bit0 1 = 1 * 1 % bit0 1) => this) (modeq.modeq_mul hn1 hm1) theorem odd_mul_odd_div_two {m : ℕ} {n : ℕ} (hm1 : m % bit0 1 = 1) (hn1 : n % bit0 1 = 1) : m * n / bit0 1 = m * (n / bit0 1) + m / bit0 1 := sorry theorem odd_of_mod_four_eq_one {n : ℕ} (h : n % bit0 (bit0 1) = 1) : n % bit0 1 = 1 := modeq.modeq_of_modeq_mul_left (bit0 1) h theorem odd_of_mod_four_eq_three {n : ℕ} (h : n % bit0 (bit0 1) = bit1 1) : n % bit0 1 = 1 := modeq.modeq_of_modeq_mul_left (bit0 1) h end nat namespace list theorem nth_rotate {α : Type u_1} {l : List α} {n : ℕ} {m : ℕ} (hml : m < length l) : nth (rotate l n) m = nth l ((m + n) % length l) := sorry theorem rotate_eq_self_iff_eq_repeat {α : Type u_1} [hα : Nonempty α] {l : List α} : (∀ (n : ℕ), rotate l n = l) ↔ ∃ (a : α), l = repeat a (length l) := sorry end Mathlib
36f92e8b4aef7766fd00be5de3b8c960704966d6
5e42295de7f5bcdf224b94603a8ec29b17c2d367
/mul_tests.lean
5a4d4c22c8170388434afc1ac21df6c9b62c0416
[]
no_license
pnmadelaine/lean_polya
9369e0d87dce773f91383bb58ac6fde0a00a1a40
1c62b0b3fa71044b0225ce28030627d251b08ebc
refs/heads/master
1,590,161,172,243
1,515,010,019,000
1,515,010,019,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,124
lean
import .control open polya tactic variables x y z u v w r : ℚ --set_option profiler true --set_option trace.app_builder true set_option profiler true example (h1 : u > 0) (h2 : u < 1*v) (h3 : z > 0) (h4 : 1*z + 1*1 < 1*w) (h5 : rat.pow (1*u + 1*v + 1*z) 3 ≥ 1* rat.pow (1*u + 1*v + 1*w + 1*1) 5) : false := by polya h1 h2 h3 h4 h5 example (h1 : u > 1*1) (h2 : u < 1*v) (h3 : rat.pow u 15 > 1*rat.pow v 17) : false := by polya h1 h2 h3 -- reconstruction fails /-example (h1 : u > 1*1) (h2 : u < 1*v) (h3 : rat.pow u 15 > 1*rat.pow v 19007) : false := by polya h1 h2 h3 -/ example (h1 : x > 0) (h2 : x < 1*1) (h3 : rat.pow x 2 ≥ 1*x) : false := by polya h1 h2 h3 /- 0 \leq n, \; n < (K / 2)x, \; 0 < C, \; 0 < \varepsilon < 1 \myRightarrow \left(1 + \frac{\varepsilon}{3 (C + 3)}\right) \cdot n < K x -/ section variables n K C eps : ℚ example (h1 : 0 ≤ n) (h2 : n < (1/2)*K*x) (h3 : 0 < C) (h4 : 0 < eps) (h5 : eps < 1) (h6 : 1 + (1/3)*eps*rat.pow (C+3) (-1)*n < K*x) : false := by polya h1 h2 h3 h4 h5 h6 end /- Tests from the old Polya repository. -/ -- line 44 example (h1 : u > 0) (h2 : u < 1*v) (h3 : v < 1*1) (h4 : 1 ≤ (1/2)*x) (h5 : x ≤ 1*y) (h6 : ((rat.pow u 2)*x) ≥ (1/2)*(v*rat.pow y 2)) : false := by polya h1 h2 h3 h4 h5 h6 --h7 h8 -- line 50 example (h1 : x > 1*1) (h2 : (1 + rat.pow y 2)*x < 1*(1 + rat.pow y 2)) : false := by polya h1 h2 -- line 56 example (h1 : x > 0) (h2 : x < 1*1) (h3 : rat.pow (1*1 + (-1)*x) (-1) ≤ 1*(rat.pow (1*1 + (-1)*rat.pow x 2) (-1))) : false := by polya h1 h2 h3 -- line 62 example (h1 : u > 0) (h2 : u < 1*v) (h3 : z > 0) (h4 : 1*z + 1*1 < 1*w) (h5 : rat.pow (1*u + 1*v + 1*z) 3 ≥ 1* rat.pow (1*u + 1*v + 1*w + 1*1) 5) : false := by polya h1 h2 h3 h4 h5 -- line 68 example (h1 : u > 0) (h2 : u < 1*v) (h3 : z > 0) (h4 : 1*z + 1*1 < 1*w) (h5 : rat.pow (1*u + 1*v + 1*z) 33 ≥ 1* rat.pow (1*u + 1*v + 1*w + 1*1) 55) : false := by polya h1 h2 h3 h4 h5 -- line 74 -- see top of file. goes forever, normalization problem? /-example (h1 : u > 0) (h2 : u < 1*(rat.pow (1*rat.pow v 2 + 23*1) 3)) (h3 : z > 0) (h4 : 1*z + 1*1 < 1*w) (h5 : rat.pow (1*u + (1*rat.pow (1*rat.pow v 2 + 23*1) 3) + 1*z) 3 ≥ 1*(rat.pow (1*u + 1*rat.pow (1*rat.pow v 2 + 23*1) 3 + 1*w + 1*1) 5)) : false := by polya h1 h2 h3 h4 h5-/ -- line 263 -- fails, sign inference too weak example (h1 : x > 0) (h2 : y < 1*z) (h3 : x * y < 1*(x * z)) : false := by polya h1 h2 h3 -- line 295 example (h1 : x * (y+z) ≤ 0) (h2 : y + z > 0) (h3 : x ≥ 0) (h4 : x*w > 0) : false := by polya h1 h2 h3 h4 -- line 299 example (h1 : x > 0) (h2 : x < 3*y) (h3 : u < 1*v) (h4 : v < 0) (h5 : 1 < 1*rat.pow v 2) (h6 : rat.pow v 2 < 1*x) (h7 : 1*(u*rat.pow (3*y) 2) + 1*1 ≥ 1*(1*(rat.pow x 2*v) + 1*x)) : false := by polya h1 h2 h3 h4 h5 h6 -- line 304 hangs? /-example (h1 : x > 0) (h2 : x < y) (h3 : 0 < u) (h4 : u < v) (h5 : 0 < w + z) (h6 : w + z < r - 1) (h7 : u + (rat.pow (1+x) 2)*(2*w + 2*z + 3) < 2*v + rat.pow (1+y) 2 * (2*r + 1)) : false := by polya h1 h2 h3 h4 h5 h6 h7-/ local infix `**`:1000 := rat.pow #exit -- line 309 example (h1 : x + rat.pow y (-1) < 2) (h2 : y < 0) (h3 : y * rat.pow x (-1) > 1) (h4 : -2 ≤ x) (h5 : x < 2) (h6 : -2 ≤ y) (h7 : y ≤ 2) (h8 : rat.pow x 2 * rat.pow y (-1) > 1 - x) : false := by polya h1 h2 h3 h4 h5 h6 h7 h8 #exit -- line 314 example (h1 : 0 < u) (h2 : u < v) (h3 : 1 < x) (h4 : x < y) (h5 : 0 < w) (h6 : w < z) (h7 : u + x*w < v+(rat.pow y 2)*z) : false := by polya h1 h2 h3 h4 h5 h6 h7 -- line 319 example (h1 : x + rat.pow y (-1) < 2) (h2 : y < 0) (h3 : y * rat.pow x (-1) > 1) (h4 : -2 ≤ x) (h5 : x ≤ 2) (h6 : y ≤ 2) (h7 : -2 ≤ y) (h8 : rat.pow x 2 * rat.pow y (-1) > 1 - x) : false := by polya h1 h2 h3 h4 h5 h6 h7 h8 -- 323 example (h1 : 0 < x) (h2 : x < y) (h3 : 0 < u) (h4 : u < v) (h5 : 0 < w + z) (h6 : w + z < r - 1) (h7 : u + rat.pow (1 + x) 2 * (2 * w + 2 * z + 3) >= 2 * v + rat.pow (1 + y) 2 * (2 * r + 1)) : false := by polya h1 h2 h3 h4 h5 h6 h7 -- 328 example (h1 : 0 < x) (h2 : x < 3 * y) (h3 : u < v) (h3' : v < 0) (h4 : 1 < v**2) (h5 : v**2 < x) (h6 : u * (3 * y)**2 + 1 >= x**2 * v + x) : false := by polya h1 h2 h3 h3' h4 h5 h6 --337 example (h1 : 1 < x) (h2 : 1 < y) (h3 : 1 < z) (h4 : 1 >= x * (1 + z * y)) : false := by polya h1 h2 h3 h4 -- 346 example (h1 : x < 1) (h2 : 1 < y) (h3 : x * y > 1) (h4 : u + x >= y + 1) (h5 : x**2 * y < 2 - u * x * y) : false := by polya h1 h2 h3 h4 h5 -- 350 example (h1 : x**21 > 0) (h2 : x**3 < 1) (h3 : y**55 > 0) (h4 : y < 1) (h5 : a + b < a * b) : false := by polya h1 h2 h3 h4 h5 -- 354 example (h1 : 0 < x) (h2 : y < z) (h3 : y < 0) (h4 : z > 0) (h5 : x * y ≥ x * z) : false := by polya h1 h2 h3 h4 h5 --359 example (h1 : 0 < z) (h2 : y < z) (h3 : y = 0) (h4 : z > 0) (h5 : x * y ≥ x * z) : false := by polya h1 h2 h3 h4 h5 -- 371 example (h1 : x > 1) (h2 : z = y**2) (h3 : 1+z*x < 1+z) : false := by polya h1 h2 h3 -- 384 example (h1 : x = z) (h2 : y = w) (h3 : x > 0) (h4 : y > 0) (h5 : x * y ≠ z * w) : false := by polya h1 h2 h3 h4 h5 -- 389 example (h1 : x > 2*y) (h2 : x = 3*y) (h3 : y ≤ 0) : false := by polya h1 h2 h3 example (h1 : x > 0) (h2 : 1 < 1 * x) (h3 : 1 < 1 * (rat.pow x (-1))) : false := by polya h1 h2 h3 example (h1 : x > 0) (h2 : x < 1*1) (h3 : rat.pow (1*1 + (-1)*x) (-1) ≤ 1*(rat.pow (1*1 + (-1)*rat.pow x 2) (-1))) : false := by polya h1 h2 h3 example (h1 : x > 1*1) (h1' : y ≥ 0) (h2 : (1 + y)*x < 1*(1 + y)) : false := by polya h1 h1' h2 example (e1 : x > 0) /-(e2' : x*y > 0)-/ (e2' : y > 0) (e2 : x > 1*y) (e3 : z > 1*x) (e3' : z > 0) (e4 : y > 1*z) : false := by polya e1 e2' e2 e3 e3' e4 example (e1 : x > 0) (e2 : y > 0) (e2' : z > 0) (e3 : y > 1*z) (e4 : x > 1*z) (e5 : x*y<1*(rat.pow z 2)) : false := by polya e1 e2 e2' e3 e4 e5 #exit /-set_option trace.app_builder true example (h0 : (1 : ℚ) > 0) (h1 : x > 1*1) (h1' : y ≥ 0) (h2 : (1 + y)*x < 1*(1 + y)) : false := by do exps ← monad.mapm get_local [`h0, `h1, `h1', `h2], bb ← add_proofs_to_blackboard blackboard.mk_empty exps, bb.trace_exprs, trace "-----", bb.trace, trace "-----", (_, bb) ← return $ add_new_ineqs bb, (_, bb) ← return $ prod_form.add_new_ineqs bb, --(_, bb) ← return $ add_new_ineqs bb, --(_, bb) ← return $ prod_form.add_new_ineqs bb, trace "-----", bb.trace, trace $ ("contr found", bb.contr_found), pf ← bb.contr.reconstruct, apply pf #exit example (h0 : (1 : ℚ) > 0) (h1 : x > 1*1) (h2 : (1 + rat.pow y 2)*x < 1*(1 + rat.pow y 2)) (ht : rat.pow y 2 ≥ 0) : false := by do exps ← monad.mapm get_local [`h0, `h1, `h2, `ht], bb ← add_proofs_to_blackboard blackboard.mk_empty exps, bb.trace_exprs, trace "-----", bb.trace, trace "-----", (_, bb) ← return $ add_new_ineqs bb, (_, bb) ← return $ prod_form.add_new_ineqs bb, (_, bb) ← return $ add_new_ineqs bb, (_, bb) ← return $ prod_form.add_new_ineqs bb, trace "-----", bb.trace, trace $ ("contr found", bb.contr_found), pf ← bb.contr.reconstruct, apply pf-/ #exit set_option trace.app_builder true --set_option pp.implicit true --set_option pp.numerals false -- left off with : bug at prod_form.to_expr?? example (e1 : x > 0) /-(e2' : x*y > 0)-/ (e2' : y > 0) (e2 : x > 1*y) (e3 : z > 1*x) (e3' : z > 0) (e4 : y > 1*z) : false := by do exps ← monad.mapm get_local [`e1, `e2, `e2', `e3, `e3', `e4], bb ← add_proofs_to_blackboard blackboard.mk_empty exps, bb.trace_exprs, trace "-----", bb.trace, trace "-----", (_, bb) ← return $ prod_form.add_new_ineqs bb, trace "-----", bb.trace, trace $ ("contr found", bb.contr_found), pf ← bb.contr.reconstruct, apply pf #exit example (e1 : x > 0) (e2 : y > 0) (e2' : z > 0) (e3 : y > 1*z) (e4 : x > 1*z) (e5 : x*y<1*(rat.pow z 2)) (e6 : rat.pow z 2 > 0) (e7 : x*y > 0) : false := by do exps ← monad.mapm get_local [`e1, `e2, `e2', `e3, `e4, `e5, `e6, `e7], bb ← add_proofs_to_blackboard blackboard.mk_empty exps, bb.trace_exprs, --(l, _) ← return $ get_add_defs bb, --trace l, (_, bb) ← return $ prod_form.add_new_ineqs bb, --bb.trace, trace $ ("contr found", bb.contr_found), pf ← bb.contr.reconstruct, apply pf
37e2a8b05aa521502933611d755625799e8f75ad
82e44445c70db0f03e30d7be725775f122d72f3e
/src/topology/category/Profinite/default.lean
a4b584a78e1f677fbb1bc6d34b25ad89b020ce54
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
9,517
lean
/- Copyright (c) 2020 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Calle Sönne -/ import topology.category.CompHaus import topology.connected import topology.subset_properties import category_theory.adjunction.reflective import category_theory.monad.limits import category_theory.Fintype /-! # The category of Profinite Types We construct the category of profinite topological spaces, often called profinite sets -- perhaps they could be called profinite types in Lean. The type of profinite topological spaces is called `Profinite`. It has a category instance and is a fully faithful subcategory of `Top`. The fully faithful functor is called `Profinite_to_Top`. ## Implementation notes A profinite type is defined to be a topological space which is compact, Hausdorff and totally disconnected. ## TODO 0. Link to category of projective limits of finite discrete sets. 1. finite coproducts 2. Clausen/Scholze topology on the category `Profinite`. ## Tags profinite -/ universe variable u open category_theory /-- The type of profinite topological spaces. -/ structure Profinite := (to_CompHaus : CompHaus) [is_totally_disconnected : totally_disconnected_space to_CompHaus] namespace Profinite /-- Construct a term of `Profinite` from a type endowed with the structure of a compact, Hausdorff and totally disconnected topological space. -/ def of (X : Type*) [topological_space X] [compact_space X] [t2_space X] [totally_disconnected_space X] : Profinite := ⟨⟨⟨X⟩⟩⟩ instance : inhabited Profinite := ⟨Profinite.of pempty⟩ instance category : category Profinite := induced_category.category to_CompHaus instance concrete_category : concrete_category Profinite := induced_category.concrete_category _ instance has_forget₂ : has_forget₂ Profinite Top := induced_category.has_forget₂ _ instance : has_coe_to_sort Profinite := ⟨Type*, λ X, X.to_CompHaus⟩ instance {X : Profinite} : totally_disconnected_space X := X.is_totally_disconnected -- We check that we automatically infer that Profinite sets are compact and Hausdorff. example {X : Profinite} : compact_space X := infer_instance example {X : Profinite} : t2_space X := infer_instance @[simp] lemma coe_to_CompHaus {X : Profinite} : (X.to_CompHaus : Type*) = X := rfl @[simp] lemma coe_id (X : Profinite) : (𝟙 X : X → X) = id := rfl @[simp] lemma coe_comp {X Y Z : Profinite} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g : X → Z) = g ∘ f := rfl end Profinite /-- The fully faithful embedding of `Profinite` in `CompHaus`. -/ @[simps, derive [full, faithful]] def Profinite_to_CompHaus : Profinite ⥤ CompHaus := induced_functor _ /-- The fully faithful embedding of `Profinite` in `Top`. This is definitionally the same as the obvious composite. -/ @[simps, derive [full, faithful]] def Profinite.to_Top : Profinite ⥤ Top := forget₂ _ _ @[simp] lemma Profinite.to_CompHaus_to_Top : Profinite_to_CompHaus ⋙ CompHaus_to_Top = Profinite.to_Top := rfl section Profinite local attribute [instance] connected_component_setoid /-- (Implementation) The object part of the connected_components functor from compact Hausdorff spaces to Profinite spaces, given by quotienting a space by its connected components. See: https://stacks.math.columbia.edu/tag/0900 -/ -- Without explicit universe annotations here, Lean introduces two universe variables and -- unhelpfully defines a function `CompHaus.{max u₁ u₂} → Profinite.{max u₁ u₂}`. def CompHaus.to_Profinite_obj (X : CompHaus.{u}) : Profinite.{u} := { to_CompHaus := { to_Top := Top.of (connected_components X), is_compact := quotient.compact_space, is_hausdorff := connected_components.t2 }, is_totally_disconnected := connected_components.totally_disconnected_space } /-- (Implementation) The bijection of homsets to establish the reflective adjunction of Profinite spaces in compact Hausdorff spaces. -/ def Profinite.to_CompHaus_equivalence (X : CompHaus.{u}) (Y : Profinite.{u}) : (CompHaus.to_Profinite_obj X ⟶ Y) ≃ (X ⟶ Profinite_to_CompHaus.obj Y) := { to_fun := λ f, { to_fun := f.1 ∘ quotient.mk, continuous_to_fun := continuous.comp f.2 (continuous_quotient_mk) }, inv_fun := λ g, { to_fun := continuous.connected_components_lift g.2, continuous_to_fun := continuous.connected_components_lift_continuous g.2}, left_inv := λ f, continuous_map.ext $ λ x, quotient.induction_on x $ λ a, rfl, right_inv := λ f, continuous_map.ext $ λ x, rfl } /-- The connected_components functor from compact Hausdorff spaces to profinite spaces, left adjoint to the inclusion functor. -/ def CompHaus.to_Profinite : CompHaus ⥤ Profinite := adjunction.left_adjoint_of_equiv Profinite.to_CompHaus_equivalence (λ _ _ _ _ _, rfl) lemma CompHaus.to_Profinite_obj' (X : CompHaus) : ↥(CompHaus.to_Profinite.obj X) = connected_components X := rfl /-- Finite types are given the discrete topology. -/ def Fintype.discrete_topology (A : Fintype) : topological_space A := ⊥ section discrete_topology local attribute [instance] Fintype.discrete_topology /-- The natural functor from `Fintype` to `Profinite`, endowing a finite type with the discrete topology. -/ @[simps] def Fintype.to_Profinite : Fintype ⥤ Profinite := { obj := λ A, Profinite.of A, map := λ _ _ f, ⟨f⟩ } end discrete_topology end Profinite namespace Profinite /-- An explicit limit cone for a functor `F : J ⥤ Profinite`, defined in terms of `Top.limit_cone`. -/ def limit_cone {J : Type u} [small_category J] (F : J ⥤ Profinite.{u}) : limits.cone F := { X := { to_CompHaus := (CompHaus.limit_cone (F ⋙ Profinite_to_CompHaus)).X, is_totally_disconnected := begin change totally_disconnected_space ↥{u : Π (j : J), (F.obj j) | _}, exact subtype.totally_disconnected_space, end }, π := { app := (CompHaus.limit_cone (F ⋙ Profinite_to_CompHaus)).π.app } } /-- The limit cone `Profinite.limit_cone F` is indeed a limit cone. -/ def limit_cone_is_limit {J : Type u} [small_category J] (F : J ⥤ Profinite.{u}) : limits.is_limit (limit_cone F) := { lift := λ S, (CompHaus.limit_cone_is_limit (F ⋙ Profinite_to_CompHaus)).lift (Profinite_to_CompHaus.map_cone S), uniq' := λ S m h, (CompHaus.limit_cone_is_limit _).uniq (Profinite_to_CompHaus.map_cone S) _ h } /-- The adjunction between CompHaus.to_Profinite and Profinite.to_CompHaus -/ def to_Profinite_adj_to_CompHaus : CompHaus.to_Profinite ⊣ Profinite_to_CompHaus := adjunction.adjunction_of_equiv_left _ _ /-- The category of profinite sets is reflective in the category of compact hausdroff spaces -/ instance to_CompHaus.reflective : reflective Profinite_to_CompHaus := { to_is_right_adjoint := ⟨CompHaus.to_Profinite, Profinite.to_Profinite_adj_to_CompHaus⟩ } noncomputable instance to_CompHaus.creates_limits : creates_limits Profinite_to_CompHaus := monadic_creates_limits _ noncomputable instance to_Top.reflective : reflective Profinite.to_Top := reflective.comp Profinite_to_CompHaus CompHaus_to_Top noncomputable instance to_Top.creates_limits : creates_limits Profinite.to_Top := monadic_creates_limits _ instance has_limits : limits.has_limits Profinite := has_limits_of_has_limits_creates_limits Profinite.to_Top instance has_colimits : limits.has_colimits Profinite := has_colimits_of_reflective Profinite_to_CompHaus noncomputable instance forget_preserves_limits : limits.preserves_limits (forget Profinite) := by apply limits.comp_preserves_limits Profinite.to_Top (forget Top) variables {X Y : Profinite.{u}} (f : X ⟶ Y) /-- Any morphism of profinite spaces is a closed map. -/ lemma is_closed_map : is_closed_map f := CompHaus.is_closed_map _ /-- Any continuous bijection of profinite spaces induces an isomorphism. -/ lemma is_iso_of_bijective (bij : function.bijective f) : is_iso f := begin haveI := CompHaus.is_iso_of_bijective (Profinite_to_CompHaus.map f) bij, exact is_iso_of_fully_faithful Profinite_to_CompHaus _ end /-- Any continuous bijection of profinite spaces induces an isomorphism. -/ noncomputable def iso_of_bijective (bij : function.bijective f) : X ≅ Y := by letI := Profinite.is_iso_of_bijective f bij; exact as_iso f instance forget_reflects_isomorphisms : reflects_isomorphisms (forget Profinite) := ⟨by introsI A B f hf; exact Profinite.is_iso_of_bijective _ ((is_iso_iff_bijective ⇑f).mp hf)⟩ /-- Construct an isomorphism from a homeomorphism. -/ @[simps hom inv] def iso_of_homeo (f : X ≃ₜ Y) : X ≅ Y := { hom := ⟨f, f.continuous⟩, inv := ⟨f.symm, f.symm.continuous⟩, hom_inv_id' := by { ext x, exact f.symm_apply_apply x }, inv_hom_id' := by { ext x, exact f.apply_symm_apply x } } /-- Construct a homeomorphism from an isomorphism. -/ @[simps] def homeo_of_iso (f : X ≅ Y) : X ≃ₜ Y := { to_fun := f.hom, inv_fun := f.inv, left_inv := λ x, by { change (f.hom ≫ f.inv) x = x, rw [iso.hom_inv_id, coe_id, id.def] }, right_inv := λ x, by { change (f.inv ≫ f.hom) x = x, rw [iso.inv_hom_id, coe_id, id.def] }, continuous_to_fun := f.hom.continuous, continuous_inv_fun := f.inv.continuous } /-- The equivalence between isomorphisms in `Profinite` and homeomorphisms of topological spaces. -/ @[simps] def iso_equiv_homeo : (X ≅ Y) ≃ (X ≃ₜ Y) := { to_fun := homeo_of_iso, inv_fun := iso_of_homeo, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, refl } } end Profinite
0bd0b5cdc036796ef3a670603225933a31549efe
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/set_theory/zfc.lean
206cbe31934c092ca4663997f7fb4868a7755830
[ "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
34,260
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.set.basic /-! # A model of ZFC In this file, we model Zermelo-Fraenkel set theory (+ Choice) using Lean's underlying type theory. We do this in four main steps: * Define pre-sets inductively. * Define extensional equivalence on pre-sets and give it a `setoid` instance. * Define ZFC sets by quotienting pre-sets by extensional equivalence. * Define classes as sets of ZFC sets. Then the rest is usual set theory. ## The model * `pSet`: Pre-set. A pre-set is inductively defined by its indexing type and its members, which are themselves pre-sets. * `Set`: ZFC set. Defined as `pSet` quotiented by `pSet.equiv`, the extensional equivalence. * `Class`: Class. Defined as `set Set`. * `Set.choice`: Axiom of choice. Proved from Lean's axiom of choice. ## Other definitions * `arity α n`: `n`-ary function `α → α → ... → α`. Defined inductively. * `arity.const a n`: `n`-ary constant function equal to `a`. * `pSet.type`: Underlying type of a pre-set. * `pSet.func`: Underlying family of pre-sets of a pre-set. * `pSet.equiv`: Extensional equivalence of pre-sets. Defined inductively. * `pSet.omega`, `Set.omega`: The von Neumann ordinal `ω` as a `pSet`, as a `Set`. * `pSet.arity.equiv`: Extensional equivalence of `n`-ary `pSet`-valued functions. Extension of `pSet.equiv`. * `pSet.resp`: Collection of `n`-ary `pSet`-valued functions that respect extensional equivalence. * `pSet.eval`: Turns a `pSet`-valued function that respect extensional equivalence into a `Set`-valued function. * `classical.all_definable`: All functions are classically definable. * `Set.is_func` : Predicate that a ZFC set is a subset of `x × y` that can be considered as a ZFC function `x → y`. That is, each member of `x` is related by the ZFC set to exactly one member of `y`. * `Set.funs`: ZFC set of ZFC functions `x → y`. * `Class.iota`: Definite description operator. ## Notes To avoid confusion between the Lean `set` and the ZFC `Set`, docstrings in this file refer to them respectively as "`set`" and "ZFC set". ## TODO Prove `Set.map_definable_aux` computably. -/ universes u v /-- The type of `n`-ary functions `α → α → ... → α`. -/ def arity (α : Type u) : ℕ → Type u | 0 := α | (n+1) := α → arity n namespace arity /-- Constant `n`-ary function with value `a`. -/ def const {α : Type u} (a : α) : ∀ n, arity α n | 0 := a | (n+1) := λ _, const n instance arity.inhabited {α n} [inhabited α] : inhabited (arity α n) := ⟨const default _⟩ end arity /-- The type of pre-sets in universe `u`. A pre-set is a family of pre-sets indexed by a type in `Type u`. The ZFC universe is defined as a quotient of this to ensure extensionality. -/ inductive pSet : Type (u+1) | mk (α : Type u) (A : α → pSet) : pSet namespace pSet /-- The underlying type of a pre-set -/ def type : pSet → Type u | ⟨α, A⟩ := α /-- The underlying pre-set family of a pre-set -/ def func : Π (x : pSet), x.type → pSet | ⟨α, A⟩ := A theorem mk_type_func : Π (x : pSet), mk x.type x.func = x | ⟨α, A⟩ := rfl /-- Two pre-sets are extensionally equivalent if every element of the first family is extensionally equivalent to some element of the second family and vice-versa. -/ def equiv (x y : pSet) : Prop := pSet.rec (λ α z m ⟨β, B⟩, (∀ a, ∃ b, m a (B b)) ∧ (∀ b, ∃ a, m a (B b))) x y theorem equiv.refl (x) : equiv x x := pSet.rec_on x $ λ α A IH, ⟨λ a, ⟨a, IH a⟩, λ a, ⟨a, IH a⟩⟩ theorem equiv.rfl : ∀ {x}, equiv x x := equiv.refl theorem equiv.euc {x} : Π {y z}, equiv x y → equiv z y → equiv x z := pSet.rec_on x $ λ α A IH y, pSet.cases_on y $ λ β B ⟨γ, Γ⟩ ⟨αβ, βα⟩ ⟨γβ, βγ⟩, ⟨λ a, let ⟨b, ab⟩ := αβ a, ⟨c, bc⟩ := βγ b in ⟨c, IH a ab bc⟩, λ c, let ⟨b, cb⟩ := γβ c, ⟨a, ba⟩ := βα b in ⟨a, IH a ba cb⟩⟩ theorem equiv.symm {x y} : equiv x y → equiv y x := (equiv.refl y).euc theorem equiv.trans {x y z} (h1 : equiv x y) (h2 : equiv y z) : equiv x z := h1.euc h2.symm instance setoid : setoid pSet := ⟨pSet.equiv, equiv.refl, λ x y, equiv.symm, λ x y z, equiv.trans⟩ /-- A pre-set is a subset of another pre-set if every element of the first family is extensionally equivalent to some element of the second family.-/ protected def subset : pSet → pSet → Prop | ⟨α, A⟩ ⟨β, B⟩ := ∀ a, ∃ b, equiv (A a) (B b) instance : has_subset pSet := ⟨pSet.subset⟩ theorem equiv.ext : Π (x y : pSet), equiv x y ↔ (x ⊆ y ∧ y ⊆ x) | ⟨α, A⟩ ⟨β, B⟩ := ⟨λ ⟨αβ, βα⟩, ⟨αβ, λ b, let ⟨a, h⟩ := βα b in ⟨a, equiv.symm h⟩⟩, λ ⟨αβ, βα⟩, ⟨αβ, λ b, let ⟨a, h⟩ := βα b in ⟨a, equiv.symm h⟩⟩⟩ theorem subset.congr_left : Π {x y z : pSet}, equiv x y → (x ⊆ z ↔ y ⊆ z) | ⟨α, A⟩ ⟨β, B⟩ ⟨γ, Γ⟩ ⟨αβ, βα⟩ := ⟨λ αγ b, let ⟨a, ba⟩ := βα b, ⟨c, ac⟩ := αγ a in ⟨c, (equiv.symm ba).trans ac⟩, λ βγ a, let ⟨b, ab⟩ := αβ a, ⟨c, bc⟩ := βγ b in ⟨c, equiv.trans ab bc⟩⟩ theorem subset.congr_right : Π {x y z : pSet}, equiv x y → (z ⊆ x ↔ z ⊆ y) | ⟨α, A⟩ ⟨β, B⟩ ⟨γ, Γ⟩ ⟨αβ, βα⟩ := ⟨λ γα c, let ⟨a, ca⟩ := γα c, ⟨b, ab⟩ := αβ a in ⟨b, ca.trans ab⟩, λ γβ c, let ⟨b, cb⟩ := γβ c, ⟨a, ab⟩ := βα b in ⟨a, cb.trans (equiv.symm ab)⟩⟩ /-- `x ∈ y` as pre-sets if `x` is extensionally equivalent to a member of the family `y`. -/ def mem : pSet → pSet → Prop | x ⟨β, B⟩ := ∃ b, equiv x (B b) instance : has_mem pSet.{u} pSet.{u} := ⟨mem⟩ theorem mem.mk {α: Type u} (A : α → pSet) (a : α) : A a ∈ mk α A := ⟨a, equiv.refl (A a)⟩ theorem mem.ext : Π {x y : pSet.{u}}, (∀ w : pSet.{u}, w ∈ x ↔ w ∈ y) → equiv x y | ⟨α, A⟩ ⟨β, B⟩ h := ⟨λ a, (h (A a)).1 (mem.mk A a), λ b, let ⟨a, ha⟩ := (h (B b)).2 (mem.mk B b) in ⟨a, ha.symm⟩⟩ theorem mem.congr_right : Π {x y : pSet.{u}}, equiv x y → (∀ {w : pSet.{u}}, w ∈ x ↔ w ∈ y) | ⟨α, A⟩ ⟨β, B⟩ ⟨αβ, βα⟩ w := ⟨λ ⟨a, ha⟩, let ⟨b, hb⟩ := αβ a in ⟨b, ha.trans hb⟩, λ ⟨b, hb⟩, let ⟨a, ha⟩ := βα b in ⟨a, hb.euc ha⟩⟩ theorem equiv_iff_mem {x y : pSet.{u}} : equiv x y ↔ (∀ {w : pSet.{u}}, w ∈ x ↔ w ∈ y) := ⟨mem.congr_right, match x, y with | ⟨α, A⟩, ⟨β, B⟩, h := ⟨λ a, h.1 (mem.mk A a), λ b, let ⟨a, h⟩ := h.2 (mem.mk B b) in ⟨a, h.symm⟩⟩ end⟩ theorem mem.congr_left : Π {x y : pSet.{u}}, equiv x y → (∀ {w : pSet.{u}}, x ∈ w ↔ y ∈ w) | x y h ⟨α, A⟩ := ⟨λ ⟨a, ha⟩, ⟨a, h.symm.trans ha⟩, λ ⟨a, ha⟩, ⟨a, h.trans ha⟩⟩ /-- Convert a pre-set to a `set` of pre-sets. -/ def to_set (u : pSet.{u}) : set pSet.{u} := {x | x ∈ u} /-- Two pre-sets are equivalent iff they have the same members. -/ theorem equiv.eq {x y : pSet} : equiv x y ↔ to_set x = to_set y := equiv_iff_mem.trans set.ext_iff.symm instance : has_coe pSet (set pSet) := ⟨to_set⟩ /-- The empty pre-set -/ protected def empty : pSet := ⟨ulift empty, λ e, match e with end⟩ instance : has_emptyc pSet := ⟨pSet.empty⟩ instance : inhabited pSet := ⟨∅⟩ theorem mem_empty (x : pSet.{u}) : x ∉ (∅ : pSet.{u}) := λ e, match e with end /-- Insert an element into a pre-set -/ protected def insert : pSet → pSet → pSet | u ⟨α, A⟩ := ⟨option α, λ o, option.rec u A o⟩ instance : has_insert pSet pSet := ⟨pSet.insert⟩ instance : has_singleton pSet pSet := ⟨λ s, insert s ∅⟩ instance : is_lawful_singleton pSet pSet := ⟨λ _, rfl⟩ /-- The n-th von Neumann ordinal -/ def of_nat : ℕ → pSet | 0 := ∅ | (n+1) := pSet.insert (of_nat n) (of_nat n) /-- The von Neumann ordinal ω -/ def omega : pSet := ⟨ulift ℕ, λ n, of_nat n.down⟩ /-- The pre-set separation operation `{x ∈ a | p x}` -/ protected def sep (p : set pSet) : pSet → pSet | ⟨α, A⟩ := ⟨{a // p (A a)}, λ x, A x.1⟩ instance : has_sep pSet pSet := ⟨pSet.sep⟩ /-- The pre-set powerset operator -/ def powerset : pSet → pSet | ⟨α, A⟩ := ⟨set α, λ p, ⟨{a // p a}, λ x, A x.1⟩⟩ theorem mem_powerset : Π {x y : pSet}, y ∈ powerset x ↔ y ⊆ x | ⟨α, A⟩ ⟨β, B⟩ := ⟨λ ⟨p, e⟩, (subset.congr_left e).2 $ λ ⟨a, pa⟩, ⟨a, equiv.refl (A a)⟩, λ βα, ⟨{a | ∃ b, equiv (B b) (A a)}, λ b, let ⟨a, ba⟩ := βα b in ⟨⟨a, b, ba⟩, ba⟩, λ ⟨a, b, ba⟩, ⟨b, ba⟩⟩⟩ /-- The pre-set union operator -/ def Union : pSet → pSet | ⟨α, A⟩ := ⟨Σx, (A x).type, λ ⟨x, y⟩, (A x).func y⟩ theorem mem_Union : Π {x y : pSet.{u}}, y ∈ Union x ↔ ∃ z : pSet.{u}, ∃ _ : z ∈ x, y ∈ z | ⟨α, A⟩ y := ⟨λ ⟨⟨a, c⟩, (e : equiv y ((A a).func c))⟩, have func (A a) c ∈ mk (A a).type (A a).func, from mem.mk (A a).func c, ⟨_, mem.mk _ _, (mem.congr_left e).2 (by rwa mk_type_func at this)⟩, λ ⟨⟨β, B⟩, ⟨a, (e : equiv (mk β B) (A a))⟩, ⟨b, yb⟩⟩, by { rw ←(mk_type_func (A a)) at e, exact let ⟨βt, tβ⟩ := e, ⟨c, bc⟩ := βt b in ⟨⟨a, c⟩, yb.trans bc⟩ }⟩ /-- The image of a function from pre-sets to pre-sets. -/ def image (f : pSet.{u} → pSet.{u}) : pSet.{u} → pSet | ⟨α, A⟩ := ⟨α, λ a, f (A a)⟩ theorem mem_image {f : pSet.{u} → pSet.{u}} (H : ∀ {x y}, equiv x y → equiv (f x) (f y)) : Π {x y : pSet.{u}}, y ∈ image f x ↔ ∃ z ∈ x, equiv y (f z) | ⟨α, A⟩ y := ⟨λ ⟨a, ya⟩, ⟨A a, mem.mk A a, ya⟩, λ ⟨z, ⟨a, za⟩, yz⟩, ⟨a, yz.trans (H za)⟩⟩ /-- Universe lift operation -/ protected def lift : pSet.{u} → pSet.{max u v} | ⟨α, A⟩ := ⟨ulift α, λ ⟨x⟩, lift (A x)⟩ /-- Embedding of one universe in another -/ @[nolint check_univs] -- intended to be used with explicit universe parameters def embed : pSet.{max (u+1) v} := ⟨ulift.{v u+1} pSet, λ ⟨x⟩, pSet.lift.{u (max (u+1) v)} x⟩ theorem lift_mem_embed : Π (x : pSet.{u}), pSet.lift.{u (max (u+1) v)} x ∈ embed.{u v} := λ x, ⟨⟨x⟩, equiv.rfl⟩ /-- Function equivalence is defined so that `f ~ g` iff `∀ x y, x ~ y → f x ~ g y`. This extends to equivalence of `n`-ary functions. -/ def arity.equiv : Π {n}, arity pSet.{u} n → arity pSet.{u} n → Prop | 0 a b := equiv a b | (n+1) a b := ∀ x y, equiv x y → arity.equiv (a x) (b y) lemma arity.equiv_const {a : pSet.{u}} : ∀ n, arity.equiv (arity.const a n) (arity.const a n) | 0 := equiv.rfl | (n+1) := λ x y h, arity.equiv_const _ /-- `resp n` is the collection of n-ary functions on `pSet` that respect equivalence, i.e. when the inputs are equivalent the output is as well. -/ def resp (n) := {x : arity pSet.{u} n // arity.equiv x x} instance resp.inhabited {n} : inhabited (resp n) := ⟨⟨arity.const default _, arity.equiv_const _⟩⟩ /-- The `n`-ary image of a `(n + 1)`-ary function respecting equivalence as a function respecting equivalence. -/ def resp.f {n} (f : resp (n+1)) (x : pSet) : resp n := ⟨f.1 x, f.2 _ _ $ equiv.refl x⟩ /-- Function equivalence for functions respecting equivalence. See `pSet.arity.equiv`. -/ def resp.equiv {n} (a b : resp n) : Prop := arity.equiv a.1 b.1 theorem resp.refl {n} (a : resp n) : resp.equiv a a := a.2 theorem resp.euc : Π {n} {a b c : resp n}, resp.equiv a b → resp.equiv c b → resp.equiv a c | 0 a b c hab hcb := hab.euc hcb | (n+1) a b c hab hcb := λ x y h, @resp.euc n (a.f x) (b.f y) (c.f y) (hab _ _ h) (hcb _ _ $ equiv.refl y) instance resp.setoid {n} : setoid (resp n) := ⟨resp.equiv, resp.refl, λ x y h, resp.euc (resp.refl y) h, λ x y z h1 h2, resp.euc h1 $ resp.euc (resp.refl z) h2⟩ end pSet /-- The ZFC universe of sets consists of the type of pre-sets, quotiented by extensional equivalence. -/ def Set : Type (u+1) := quotient pSet.setoid.{u} namespace pSet namespace resp /-- Helper function for `pSet.eval`. -/ def eval_aux : Π {n}, {f : resp n → arity Set.{u} n // ∀ (a b : resp n), resp.equiv a b → f a = f b} | 0 := ⟨λ a, ⟦a.1⟧, λ a b h, quotient.sound h⟩ | (n+1) := let F : resp (n + 1) → arity Set (n + 1) := λ a, @quotient.lift _ _ pSet.setoid (λ x, eval_aux.1 (a.f x)) (λ b c h, eval_aux.2 _ _ (a.2 _ _ h)) in ⟨F, λ b c h, funext $ @quotient.ind _ _ (λ q, F b q = F c q) $ λ z, eval_aux.2 (resp.f b z) (resp.f c z) (h _ _ (equiv.refl z))⟩ /-- An equivalence-respecting function yields an n-ary ZFC set function. -/ def eval (n) : resp n → arity Set.{u} n := eval_aux.1 theorem eval_val {n f x} : (@eval (n+1) f : Set → arity Set n) ⟦x⟧ = eval n (resp.f f x) := rfl end resp /-- A set function is "definable" if it is the image of some n-ary pre-set function. This isn't exactly definability, but is useful as a sufficient condition for functions that have a computable image. -/ class inductive definable (n) : arity Set.{u} n → Type (u+1) | mk (f) : definable (resp.eval _ f) attribute [instance] definable.mk /-- The evaluation of a function respecting equivalence is definable, by that same function. -/ def definable.eq_mk {n} (f) : Π {s : arity Set.{u} n} (H : resp.eval _ f = s), definable n s | ._ rfl := ⟨f⟩ /-- Turns a definable function into a function that respects equivalence. -/ def definable.resp {n} : Π (s : arity Set.{u} n) [definable n s], resp n | ._ ⟨f⟩ := f theorem definable.eq {n} : Π (s : arity Set.{u} n) [H : definable n s], (@definable.resp n s H).eval _ = s | ._ ⟨f⟩ := rfl end pSet namespace classical open pSet /-- All functions are classically definable. -/ noncomputable def all_definable : Π {n} (F : arity Set.{u} n), definable n F | 0 F := let p := @quotient.exists_rep pSet _ F in definable.eq_mk ⟨some p, equiv.rfl⟩ (some_spec p) | (n+1) (F : arity Set.{u} (n + 1)) := begin have I := λ x, (all_definable (F x)), refine definable.eq_mk ⟨λ x : pSet, (@definable.resp _ _ (I ⟦x⟧)).1, _⟩ _, { dsimp [arity.equiv], introsI x y h, rw @quotient.sound pSet _ _ _ h, exact (definable.resp (F ⟦y⟧)).2 }, refine funext (λ q, quotient.induction_on q $ λ x, _), simp_rw [resp.eval_val, resp.f, subtype.val_eq_coe, subtype.coe_eta], exact @definable.eq _ (F ⟦x⟧) (I ⟦x⟧), end end classical namespace Set open pSet /-- Turns a pre-set into a ZFC set. -/ def mk : pSet → Set := quotient.mk @[simp] theorem mk_eq (x : pSet) : @eq Set ⟦x⟧ (mk x) := rfl @[simp] lemma eval_mk {n f x} : (@resp.eval (n+1) f : Set → arity Set n) (mk x) = resp.eval n (resp.f f x) := rfl /-- The membership relation for ZFC sets is inherited from the membership relation for pre-sets. -/ def mem : Set → Set → Prop := quotient.lift₂ pSet.mem (λ x y x' y' hx hy, propext ((mem.congr_left hx).trans (mem.congr_right hy))) instance : has_mem Set Set := ⟨mem⟩ /-- Convert a ZFC set into a `set` of ZFC sets -/ def to_set (u : Set.{u}) : set Set.{u} := {x | x ∈ u} /-- `x ⊆ y` as ZFC sets means that all members of `x` are members of `y`. -/ protected def subset (x y : Set.{u}) := ∀ ⦃z⦄, z ∈ x → z ∈ y instance has_subset : has_subset Set := ⟨Set.subset⟩ lemma subset_def {x y : Set.{u}} : x ⊆ y ↔ ∀ ⦃z⦄, z ∈ x → z ∈ y := iff.rfl theorem subset_iff : Π (x y : pSet), mk x ⊆ mk y ↔ x ⊆ y | ⟨α, A⟩ ⟨β, B⟩ := ⟨λ h a, @h ⟦A a⟧ (mem.mk A a), λ h z, quotient.induction_on z (λ z ⟨a, za⟩, let ⟨b, ab⟩ := h a in ⟨b, za.trans ab⟩)⟩ theorem ext {x y : Set.{u}} : (∀ z : Set.{u}, z ∈ x ↔ z ∈ y) → x = y := quotient.induction_on₂ x y (λ u v h, quotient.sound (mem.ext (λ w, h ⟦w⟧))) theorem ext_iff {x y : Set.{u}} : (∀ z : Set.{u}, z ∈ x ↔ z ∈ y) ↔ x = y := ⟨ext, λ h, by simp [h]⟩ /-- The empty ZFC set -/ def empty : Set := mk ∅ instance : has_emptyc Set := ⟨empty⟩ instance : inhabited Set := ⟨∅⟩ @[simp] theorem mem_empty (x) : x ∉ (∅ : Set.{u}) := quotient.induction_on x pSet.mem_empty theorem eq_empty (x : Set.{u}) : x = ∅ ↔ ∀ y : Set.{u}, y ∉ x := ⟨λ h y, (h.symm ▸ mem_empty y), λ h, ext (λ y, ⟨λ yx, absurd yx (h y), λ y0, absurd y0 (mem_empty _)⟩)⟩ /-- `insert x y` is the set `{x} ∪ y` -/ protected def insert : Set → Set → Set := resp.eval 2 ⟨pSet.insert, λ u v uv ⟨α, A⟩ ⟨β, B⟩ ⟨αβ, βα⟩, ⟨λ o, match o with | some a := let ⟨b, hb⟩ := αβ a in ⟨some b, hb⟩ | none := ⟨none, uv⟩ end, λ o, match o with | some b := let ⟨a, ha⟩ := βα b in ⟨some a, ha⟩ | none := ⟨none, uv⟩ end⟩⟩ instance : has_insert Set Set := ⟨Set.insert⟩ instance : has_singleton Set Set := ⟨λ x, insert x ∅⟩ instance : is_lawful_singleton Set Set := ⟨λ x, rfl⟩ @[simp] theorem mem_insert {x y z : Set.{u}} : x ∈ insert y z ↔ x = y ∨ x ∈ z := quotient.induction_on₃ x y z (λ x y ⟨α, A⟩, show x ∈ pSet.mk (option α) (λ o, option.rec y A o) ↔ mk x = mk y ∨ x ∈ pSet.mk α A, from ⟨λ m, match m with | ⟨some a, ha⟩ := or.inr ⟨a, ha⟩ | ⟨none, h⟩ := or.inl (quotient.sound h) end, λ m, match m with | or.inr ⟨a, ha⟩ := ⟨some a, ha⟩ | or.inl h := ⟨none, quotient.exact h⟩ end⟩) @[simp] theorem mem_singleton {x y : Set.{u}} : x ∈ @singleton Set.{u} Set.{u} _ y ↔ x = y := iff.trans mem_insert ⟨λ o, or.rec (λ h, h) (λ n, absurd n (mem_empty _)) o, or.inl⟩ @[simp] theorem mem_pair {x y z : Set.{u}} : x ∈ ({y, z} : Set) ↔ x = y ∨ x = z := iff.trans mem_insert $ or_congr iff.rfl mem_singleton /-- `omega` is the first infinite von Neumann ordinal -/ def omega : Set := mk omega @[simp] theorem omega_zero : ∅ ∈ omega := ⟨⟨0⟩, equiv.rfl⟩ @[simp] theorem omega_succ {n} : n ∈ omega.{u} → insert n n ∈ omega.{u} := quotient.induction_on n (λ x ⟨⟨n⟩, h⟩, ⟨⟨n+1⟩, have Set.insert ⟦x⟧ ⟦x⟧ = Set.insert ⟦of_nat n⟧ ⟦of_nat n⟧, by rw (@quotient.sound pSet _ _ _ h), quotient.exact this⟩) /-- `{x ∈ a | p x}` is the set of elements in `a` satisfying `p` -/ protected def sep (p : Set → Prop) : Set → Set := resp.eval 1 ⟨pSet.sep (λ y, p ⟦y⟧), λ ⟨α, A⟩ ⟨β, B⟩ ⟨αβ, βα⟩, ⟨λ ⟨a, pa⟩, let ⟨b, hb⟩ := αβ a in ⟨⟨b, by rwa ←(@quotient.sound pSet _ _ _ hb)⟩, hb⟩, λ ⟨b, pb⟩, let ⟨a, ha⟩ := βα b in ⟨⟨a, by rwa (@quotient.sound pSet _ _ _ ha)⟩, ha⟩⟩⟩ instance : has_sep Set Set := ⟨Set.sep⟩ @[simp] theorem mem_sep {p : Set.{u} → Prop} {x y : Set.{u}} : y ∈ {y ∈ x | p y} ↔ y ∈ x ∧ p y := quotient.induction_on₂ x y (λ ⟨α, A⟩ y, ⟨λ ⟨⟨a, pa⟩, h⟩, ⟨⟨a, h⟩, by { rw (@quotient.sound pSet _ _ _ h), exact pa }⟩, λ ⟨⟨a, h⟩, pa⟩, ⟨⟨a, by { rw ←(@quotient.sound pSet _ _ _ h), exact pa }⟩, h⟩⟩) /-- The powerset operation, the collection of subsets of a ZFC set -/ def powerset : Set → Set := resp.eval 1 ⟨powerset, λ ⟨α, A⟩ ⟨β, B⟩ ⟨αβ, βα⟩, ⟨λ p, ⟨{b | ∃ a, p a ∧ equiv (A a) (B b)}, λ ⟨a, pa⟩, let ⟨b, ab⟩ := αβ a in ⟨⟨b, a, pa, ab⟩, ab⟩, λ ⟨b, a, pa, ab⟩, ⟨⟨a, pa⟩, ab⟩⟩, λ q, ⟨{a | ∃ b, q b ∧ equiv (A a) (B b)}, λ ⟨a, b, qb, ab⟩, ⟨⟨b, qb⟩, ab⟩, λ ⟨b, qb⟩, let ⟨a, ab⟩ := βα b in ⟨⟨a, b, qb, ab⟩, ab⟩⟩⟩⟩ @[simp] theorem mem_powerset {x y : Set.{u}} : y ∈ powerset x ↔ y ⊆ x := quotient.induction_on₂ x y ( λ ⟨α, A⟩ ⟨β, B⟩, show (⟨β, B⟩ : pSet.{u}) ∈ (pSet.powerset.{u} ⟨α, A⟩) ↔ _, by simp [mem_powerset, subset_iff]) theorem Union_lem {α β : Type u} (A : α → pSet) (B : β → pSet) (αβ : ∀ a, ∃ b, equiv (A a) (B b)) : ∀ a, ∃ b, (equiv ((Union ⟨α, A⟩).func a) ((Union ⟨β, B⟩).func b)) | ⟨a, c⟩ := let ⟨b, hb⟩ := αβ a in begin induction ea : A a with γ Γ, induction eb : B b with δ Δ, rw [ea, eb] at hb, cases hb with γδ δγ, exact let c : type (A a) := c, ⟨d, hd⟩ := γδ (by rwa ea at c) in have pSet.equiv ((A a).func c) ((B b).func (eq.rec d (eq.symm eb))), from match A a, B b, ea, eb, c, d, hd with ._, ._, rfl, rfl, x, y, hd := hd end, ⟨⟨b, eq.rec d (eq.symm eb)⟩, this⟩ end /-- The union operator, the collection of elements of elements of a ZFC set -/ def Union : Set → Set := resp.eval 1 ⟨pSet.Union, λ ⟨α, A⟩ ⟨β, B⟩ ⟨αβ, βα⟩, ⟨Union_lem A B αβ, λ a, exists.elim (Union_lem B A (λ b, exists.elim (βα b) (λ c hc, ⟨c, pSet.equiv.symm hc⟩)) a) (λ b hb, ⟨b, pSet.equiv.symm hb⟩)⟩⟩ notation `⋃` := Union @[simp] theorem mem_Union {x y : Set.{u}} : y ∈ Union x ↔ ∃ z ∈ x, y ∈ z := quotient.induction_on₂ x y (λ x y, iff.trans mem_Union ⟨λ ⟨z, h⟩, ⟨⟦z⟧, h⟩, λ ⟨z, h⟩, quotient.induction_on z (λ z h, ⟨z, h⟩) h⟩) @[simp] theorem Union_singleton {x : Set.{u}} : Union {x} = x := ext $ λ y, by simp_rw [mem_Union, exists_prop, mem_singleton, exists_eq_left] theorem singleton_inj {x y : Set.{u}} (H : ({x} : Set) = {y}) : x = y := let this := congr_arg Union H in by rwa [Union_singleton, Union_singleton] at this /-- The binary union operation -/ protected def union (x y : Set.{u}) : Set.{u} := ⋃ {x, y} /-- The binary intersection operation -/ protected def inter (x y : Set.{u}) : Set.{u} := {z ∈ x | z ∈ y} /-- The set difference operation -/ protected def diff (x y : Set.{u}) : Set.{u} := {z ∈ x | z ∉ y} instance : has_union Set := ⟨Set.union⟩ instance : has_inter Set := ⟨Set.inter⟩ instance : has_sdiff Set := ⟨Set.diff⟩ @[simp] theorem mem_union {x y z : Set.{u}} : z ∈ x ∪ y ↔ z ∈ x ∨ z ∈ y := iff.trans mem_Union ⟨λ ⟨w, wxy, zw⟩, match mem_pair.1 wxy with | or.inl wx := or.inl (by rwa ←wx) | or.inr wy := or.inr (by rwa ←wy) end, λ zxy, match zxy with | or.inl zx := ⟨x, mem_pair.2 (or.inl rfl), zx⟩ | or.inr zy := ⟨y, mem_pair.2 (or.inr rfl), zy⟩ end⟩ @[simp] theorem mem_inter {x y z : Set.{u}} : z ∈ x ∩ y ↔ z ∈ x ∧ z ∈ y := @@mem_sep (λ z : Set.{u}, z ∈ y) @[simp] theorem mem_diff {x y z : Set.{u}} : z ∈ x \ y ↔ z ∈ x ∧ z ∉ y := @@mem_sep (λ z : Set.{u}, z ∉ y) theorem induction_on {p : Set → Prop} (x) (h : ∀ x, (∀ y ∈ x, p y) → p x) : p x := quotient.induction_on x $ λ u, pSet.rec_on u $ λ α A IH, h _ $ λ y, show @has_mem.mem _ _ Set.has_mem y ⟦⟨α, A⟩⟧ → p y, from quotient.induction_on y (λ v ⟨a, ha⟩, by { rw (@quotient.sound pSet _ _ _ ha), exact IH a }) theorem regularity (x : Set.{u}) (h : x ≠ ∅) : ∃ y ∈ x, x ∩ y = ∅ := classical.by_contradiction $ λ ne, h $ (eq_empty x).2 $ λ y, induction_on y $ λ z (IH : ∀ w : Set.{u}, w ∈ z → w ∉ x), show z ∉ x, from λ zx, ne ⟨z, zx, (eq_empty _).2 (λ w wxz, let ⟨wx, wz⟩ := mem_inter.1 wxz in IH w wz wx)⟩ /-- The image of a (definable) ZFC set function -/ def image (f : Set → Set) [H : definable 1 f] : Set → Set := let r := @definable.resp 1 f _ in resp.eval 1 ⟨image r.1, λ x y e, mem.ext $ λ z, iff.trans (mem_image r.2) $ iff.trans (by exact ⟨λ ⟨w, h1, h2⟩, ⟨w, (mem.congr_right e).1 h1, h2⟩, λ ⟨w, h1, h2⟩, ⟨w, (mem.congr_right e).2 h1, h2⟩⟩) $ iff.symm (mem_image r.2)⟩ theorem image.mk : Π (f : Set.{u} → Set.{u}) [H : definable 1 f] (x) {y} (h : y ∈ x), f y ∈ @image f H x | ._ ⟨F⟩ x y := quotient.induction_on₂ x y $ λ ⟨α, A⟩ y ⟨a, ya⟩, ⟨a, F.2 _ _ ya⟩ @[simp] theorem mem_image : Π {f : Set.{u} → Set.{u}} [H : definable 1 f] {x y : Set.{u}}, y ∈ @image f H x ↔ ∃ z ∈ x, f z = y | ._ ⟨F⟩ x y := quotient.induction_on₂ x y $ λ ⟨α, A⟩ y, ⟨λ ⟨a, ya⟩, ⟨⟦A a⟧, mem.mk A a, eq.symm $ quotient.sound ya⟩, λ ⟨z, hz, e⟩, e ▸ image.mk _ _ hz⟩ /-- Kuratowski ordered pair -/ def pair (x y : Set.{u}) : Set.{u} := {{x}, {x, y}} /-- A subset of pairs `{(a, b) ∈ x × y | p a b}` -/ def pair_sep (p : Set.{u} → Set.{u} → Prop) (x y : Set.{u}) : Set.{u} := {z ∈ powerset (powerset (x ∪ y)) | ∃ a ∈ x, ∃ b ∈ y, z = pair a b ∧ p a b} @[simp] theorem mem_pair_sep {p} {x y z : Set.{u}} : z ∈ pair_sep p x y ↔ ∃ a ∈ x, ∃ b ∈ y, z = pair a b ∧ p a b := begin refine mem_sep.trans ⟨and.right, λ e, ⟨_, e⟩⟩, rcases e with ⟨a, ax, b, bY, rfl, pab⟩, simp only [mem_powerset, subset_def, mem_union, pair, mem_pair], rintros u (rfl|rfl) v; simp only [mem_singleton, mem_pair], { rintro rfl, exact or.inl ax }, { rintro (rfl|rfl); [left, right]; assumption } end theorem pair_inj {x y x' y' : Set.{u}} (H : pair x y = pair x' y') : x = x' ∧ y = y' := begin have ae := ext_iff.2 H, simp [pair] at ae, have : x = x', { cases (ae {x}).1 (by simp) with h h, { exact singleton_inj h }, { have m : x' ∈ ({x} : Set), { rw h, simp }, simp at m, simp [*] } }, subst x', have he : y = x → y = y', { intro yx, subst y, cases (ae {x, y'}).2 (by simp only [eq_self_iff_true, or_true]) with xy'x xy'xx, { rw [eq_comm, ←mem_singleton, ←xy'x, mem_pair], exact or.inr rfl }, { have yxx := (ext_iff.2 xy'xx y').1 (by simp), simp at yxx, subst y' } }, have xyxy' := (ae {x, y}).1 (by simp), cases xyxy' with xyx xyy', { have yx := (ext_iff.2 xyx y).1 (by simp), simp at yx, simp [he yx] }, { have yxy' := (ext_iff.2 xyy' y).1 (by simp), simp at yxy', cases yxy' with yx yy', { simp [he yx] }, { simp [yy'] } } end /-- The cartesian product, `{(a, b) | a ∈ x, b ∈ y}` -/ def prod : Set.{u} → Set.{u} → Set.{u} := pair_sep (λ a b, true) @[simp] theorem mem_prod {x y z : Set.{u}} : z ∈ prod x y ↔ ∃ a ∈ x, ∃ b ∈ y, z = pair a b := by simp [prod] @[simp] theorem pair_mem_prod {x y a b : Set.{u}} : pair a b ∈ prod x y ↔ a ∈ x ∧ b ∈ y := ⟨λ h, let ⟨a', a'x, b', b'y, e⟩ := mem_prod.1 h in match a', b', pair_inj e, a'x, b'y with ._, ._, ⟨rfl, rfl⟩, ax, bY := ⟨ax, bY⟩ end, λ ⟨ax, bY⟩, mem_prod.2 ⟨a, ax, b, bY, rfl⟩⟩ /-- `is_func x y f` is the assertion that `f` is a subset of `x × y` which relates to each element of `x` a unique element of `y`, so that we can consider `f`as a ZFC function `x → y`. -/ def is_func (x y f : Set.{u}) : Prop := f ⊆ prod x y ∧ ∀ z : Set.{u}, z ∈ x → ∃! w, pair z w ∈ f /-- `funs x y` is `y ^ x`, the set of all set functions `x → y` -/ def funs (x y : Set.{u}) : Set.{u} := {f ∈ powerset (prod x y) | is_func x y f} @[simp] theorem mem_funs {x y f : Set.{u}} : f ∈ funs x y ↔ is_func x y f := by simp [funs, is_func] -- TODO(Mario): Prove this computably noncomputable instance map_definable_aux (f : Set → Set) [H : definable 1 f] : definable 1 (λ y, pair y (f y)) := @classical.all_definable 1 _ /-- Graph of a function: `map f x` is the ZFC function which maps `a ∈ x` to `f a` -/ noncomputable def map (f : Set → Set) [H : definable 1 f] : Set → Set := image (λ y, pair y (f y)) @[simp] theorem mem_map {f : Set → Set} [H : definable 1 f] {x y : Set} : y ∈ map f x ↔ ∃ z ∈ x, pair z (f z) = y := mem_image theorem map_unique {f : Set.{u} → Set.{u}} [H : definable 1 f] {x z : Set.{u}} (zx : z ∈ x) : ∃! w, pair z w ∈ map f x := ⟨f z, image.mk _ _ zx, λ y yx, let ⟨w, wx, we⟩ := mem_image.1 yx, ⟨wz, fy⟩ := pair_inj we in by rw[←fy, wz]⟩ @[simp] theorem map_is_func {f : Set → Set} [H : definable 1 f] {x y : Set} : is_func x y (map f x) ↔ ∀ z ∈ x, f z ∈ y := ⟨λ ⟨ss, h⟩ z zx, let ⟨t, t1, t2⟩ := h z zx in (t2 (f z) (image.mk _ _ zx)).symm ▸ (pair_mem_prod.1 (ss t1)).right, λ h, ⟨λ y yx, let ⟨z, zx, ze⟩ := mem_image.1 yx in ze ▸ pair_mem_prod.2 ⟨zx, h z zx⟩, λ z, map_unique⟩⟩ end Set /-- The collection of all classes. A class is defined as a `set` of ZFC sets. -/ def Class := set Set namespace Class instance : has_subset Class := ⟨set.subset⟩ instance : has_sep Set Class := ⟨set.sep⟩ instance : has_emptyc Class := ⟨λ a, false⟩ instance : inhabited Class := ⟨∅⟩ instance : has_insert Set Class := ⟨set.insert⟩ instance : has_union Class := ⟨set.union⟩ instance : has_inter Class := ⟨set.inter⟩ instance : has_neg Class := ⟨set.compl⟩ instance : has_sdiff Class := ⟨set.diff⟩ /-- Coerce a ZFC set into a class -/ def of_Set (x : Set.{u}) : Class.{u} := {y | y ∈ x} instance : has_coe Set Class := ⟨of_Set⟩ /-- The universal class -/ def univ : Class := set.univ /-- Assert that `A` is a ZFC set satisfying `p` -/ def to_Set (p : Set.{u} → Prop) (A : Class.{u}) : Prop := ∃ x, ↑x = A ∧ p x /-- `A ∈ B` if `A` is a ZFC set which is a member of `B` -/ protected def mem (A B : Class.{u}) : Prop := to_Set.{u} B A instance : has_mem Class Class := ⟨Class.mem⟩ theorem mem_univ {A : Class.{u}} : A ∈ univ.{u} ↔ ∃ x : Set.{u}, ↑x = A := exists_congr $ λ x, and_true _ /-- Convert a conglomerate (a collection of classes) into a class -/ def Cong_to_Class (x : set Class.{u}) : Class.{u} := {y | ↑y ∈ x} /-- Convert a class into a conglomerate (a collection of classes) -/ def Class_to_Cong (x : Class.{u}) : set Class.{u} := {y | y ∈ x} /-- The power class of a class is the class of all subclasses that are ZFC sets -/ def powerset (x : Class) : Class := Cong_to_Class (set.powerset x) /-- The union of a class is the class of all members of ZFC sets in the class -/ def Union (x : Class) : Class := set.sUnion (Class_to_Cong x) notation `⋃` := Union theorem of_Set.inj {x y : Set.{u}} (h : (x : Class.{u}) = y) : x = y := Set.ext $ λ z, by { change (x : Class.{u}) z ↔ (y : Class.{u}) z, rw h } @[simp] theorem to_Set_of_Set (p : Set.{u} → Prop) (x : Set.{u}) : to_Set p x ↔ p x := ⟨λ ⟨y, yx, py⟩, by rwa of_Set.inj yx at py, λ px, ⟨x, rfl, px⟩⟩ @[simp] theorem mem_hom_left (x : Set.{u}) (A : Class.{u}) : (x : Class.{u}) ∈ A ↔ A x := to_Set_of_Set _ _ @[simp] theorem mem_hom_right (x y : Set.{u}) : (y : Class.{u}) x ↔ x ∈ y := iff.rfl @[simp] theorem subset_hom (x y : Set.{u}) : (x : Class.{u}) ⊆ y ↔ x ⊆ y := iff.rfl @[simp] theorem sep_hom (p : Set.{u} → Prop) (x : Set.{u}) : (↑{y ∈ x | p y} : Class.{u}) = {y ∈ x | p y} := set.ext $ λ y, Set.mem_sep @[simp] theorem empty_hom : ↑(∅ : Set.{u}) = (∅ : Class.{u}) := set.ext $ λ y, (iff_false _).2 (Set.mem_empty y) @[simp] theorem insert_hom (x y : Set.{u}) : (@insert Set.{u} Class.{u} _ x y) = ↑(insert x y) := set.ext $ λ z, iff.symm Set.mem_insert @[simp] theorem union_hom (x y : Set.{u}) : (x : Class.{u}) ∪ y = (x ∪ y : Set.{u}) := set.ext $ λ z, iff.symm Set.mem_union @[simp] theorem inter_hom (x y : Set.{u}) : (x : Class.{u}) ∩ y = (x ∩ y : Set.{u}) := set.ext $ λ z, iff.symm Set.mem_inter @[simp] theorem diff_hom (x y : Set.{u}) : (x : Class.{u}) \ y = (x \ y : Set.{u}) := set.ext $ λ z, iff.symm Set.mem_diff @[simp] theorem powerset_hom (x : Set.{u}) : powerset.{u} x = Set.powerset x := set.ext $ λ z, iff.symm Set.mem_powerset @[simp] theorem Union_hom (x : Set.{u}) : Union.{u} x = Set.Union x := set.ext $ λ z, by { refine iff.trans _ Set.mem_Union.symm, exact ⟨λ ⟨._, ⟨a, rfl, ax⟩, za⟩, ⟨a, ax, za⟩, λ ⟨a, ax, za⟩, ⟨_, ⟨a, rfl, ax⟩, za⟩⟩ } /-- The definite description operator, which is `{x}` if `{a | p a} = {x}` and `∅` otherwise. -/ def iota (p : Set → Prop) : Class := Union {x | ∀ y, p y ↔ y = x} theorem iota_val (p : Set → Prop) (x : Set) (H : ∀ y, p y ↔ y = x) : iota p = ↑x := set.ext $ λ y, ⟨λ ⟨._, ⟨x', rfl, h⟩, yx'⟩, by rwa ←((H x').1 $ (h x').2 rfl), λ yx, ⟨_, ⟨x, rfl, H⟩, yx⟩⟩ /-- Unlike the other set constructors, the `iota` definite descriptor is a set for any set input, but not constructively so, so there is no associated `(Set → Prop) → Set` function. -/ theorem iota_ex (p) : iota.{u} p ∈ univ.{u} := mem_univ.2 $ or.elim (classical.em $ ∃ x, ∀ y, p y ↔ y = x) (λ ⟨x, h⟩, ⟨x, eq.symm $ iota_val p x h⟩) (λ hn, ⟨∅, set.ext (λ z, empty_hom.symm ▸ ⟨false.rec _, λ ⟨._, ⟨x, rfl, H⟩, zA⟩, hn ⟨x, H⟩⟩)⟩) /-- Function value -/ def fval (F A : Class.{u}) : Class.{u} := iota (λ y, to_Set (λ x, F (Set.pair x y)) A) infixl `′`:100 := fval theorem fval_ex (F A : Class.{u}) : F ′ A ∈ univ.{u} := iota_ex _ end Class namespace Set @[simp] theorem map_fval {f : Set.{u} → Set.{u}} [H : pSet.definable 1 f] {x y : Set.{u}} (h : y ∈ x) : (Set.map f x ′ y : Class.{u}) = f y := Class.iota_val _ _ (λ z, by { rw [Class.to_Set_of_Set, Class.mem_hom_right, mem_map], exact ⟨λ ⟨w, wz, pr⟩, let ⟨wy, fw⟩ := Set.pair_inj pr in by rw[←fw, wy], λ e, by { subst e, exact ⟨_, h, rfl⟩ }⟩ }) variables (x : Set.{u}) (h : ∅ ∉ x) /-- A choice function on the class of nonempty ZFC sets. -/ noncomputable def choice : Set := @map (λ y, classical.epsilon (λ z, z ∈ y)) (classical.all_definable _) x include h theorem choice_mem_aux (y : Set.{u}) (yx : y ∈ x) : classical.epsilon (λ z : Set.{u}, z ∈ y) ∈ y := @classical.epsilon_spec _ (λ z : Set.{u}, z ∈ y) $ classical.by_contradiction $ λ n, h $ by rwa ←((eq_empty y).2 $ λ z zx, n ⟨z, zx⟩) theorem choice_is_func : is_func x (Union x) (choice x) := (@map_is_func _ (classical.all_definable _) _ _).2 $ λ y yx, mem_Union.2 ⟨y, yx, choice_mem_aux x h y yx⟩ theorem choice_mem (y : Set.{u}) (yx : y ∈ x) : (choice x ′ y : Class.{u}) ∈ (y : Class.{u}) := begin delta choice, rw [map_fval yx, Class.mem_hom_left, Class.mem_hom_right], exact choice_mem_aux x h y yx end end Set
21d1cf5bccc43878851b2f819a9f071f09e57e34
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/pattern2.lean
b9f4d1bd8876b1ec956bd6132d10fa80b314d877
[ "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
274
lean
constant f : nat → nat → nat constant g : nat → nat → nat attribute g [no_pattern] namespace foo definition lemma1 [forward] {a b : nat} : f a b = g a b := sorry end foo print foo.lemma1 open foo print foo.lemma1 attribute foo.lemma1 [forward] print foo.lemma1
91641e47d52a4d5a35d6c211db31535d5dcacda7
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/src/Lean/Elab/Tactic/Location.lean
3ab5916f593c4c15e5e09ae4b3bef7eda7d9d32e
[ "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
978
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 -/ namespace Lean.Elab.Tactic inductive Location where | wildcard | target | localDecls (userNames : Array Name) /- Recall that ``` def locationWildcard := parser! "*" def locationTarget := parser! unicodeSymbol "⊢" "|-" def locationHyp := parser! many1 ident def location := parser! "at " >> (locationWildcard <|> locationTarget <|> locationHyp) ``` -/ def expandLocation (stx : Syntax) : Location := let arg := stx[1] if arg.getKind == ``Parser.Tactic.locationWildcard then Location.wildcard else if arg.getKind == ``Parser.Tactic.locationTarget then Location.target else Location.localDecls $ arg[0].getArgs.map fun stx => stx.getId def expandOptLocation (stx : Syntax) : Location := if stx.isNone then Location.target else expandLocation stx[0] end Lean.Elab.Tactic
5386fb2559ca28a4ce2c03f27a3d2b4c4c7f1142
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/algebra/pi_instances.lean
c6407e3f7f455946f67d00429ec28f6efcbfc99f
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
17,599
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot Pi instances for algebraic structures. -/ import order.basic import algebra.module algebra.group import data.finset import tactic.pi_instances namespace pi universes u v w variable {I : Type u} -- The indexing type variable {f : I → Type v} -- The family of types already equiped with instances variables (x y : Π i, f i) (i : I) instance has_zero [∀ i, has_zero $ f i] : has_zero (Π i : I, f i) := ⟨λ i, 0⟩ @[simp] lemma zero_apply [∀ i, has_zero $ f i] : (0 : Π i, f i) i = 0 := rfl instance has_one [∀ i, has_one $ f i] : has_one (Π i : I, f i) := ⟨λ i, 1⟩ @[simp] lemma one_apply [∀ i, has_one $ f i] : (1 : Π i, f i) i = 1 := rfl attribute [to_additive pi.has_zero] pi.has_one attribute [to_additive pi.zero_apply] pi.one_apply instance has_add [∀ i, has_add $ f i] : has_add (Π i : I, f i) := ⟨λ x y, λ i, x i + y i⟩ @[simp] lemma add_apply [∀ i, has_add $ f i] : (x + y) i = x i + y i := rfl instance has_mul [∀ i, has_mul $ f i] : has_mul (Π i : I, f i) := ⟨λ x y, λ i, x i * y i⟩ @[simp] lemma mul_apply [∀ i, has_mul $ f i] : (x * y) i = x i * y i := rfl attribute [to_additive pi.has_add] pi.has_mul attribute [to_additive pi.add_apply] pi.mul_apply instance has_inv [∀ i, has_inv $ f i] : has_inv (Π i : I, f i) := ⟨λ x, λ i, (x i)⁻¹⟩ @[simp] lemma inv_apply [∀ i, has_inv $ f i] : x⁻¹ i = (x i)⁻¹ := rfl instance has_neg [∀ i, has_neg $ f i] : has_neg (Π i : I, f i) := ⟨λ x, λ i, -(x i)⟩ @[simp] lemma neg_apply [∀ i, has_neg $ f i] : (-x) i = -x i := rfl attribute [to_additive pi.has_neg] pi.has_inv attribute [to_additive pi.neg_apply] pi.inv_apply instance has_scalar {α : Type*} [∀ i, has_scalar α $ f i] : has_scalar α (Π i : I, f i) := ⟨λ s x, λ i, s • (x i)⟩ @[simp] lemma smul_apply {α : Type*} [∀ i, has_scalar α $ f i] (s : α) : (s • x) i = s • x i := rfl instance semigroup [∀ i, semigroup $ f i] : semigroup (Π i : I, f i) := by pi_instance instance comm_semigroup [∀ i, comm_semigroup $ f i] : comm_semigroup (Π i : I, f i) := by pi_instance instance monoid [∀ i, monoid $ f i] : monoid (Π i : I, f i) := by pi_instance instance comm_monoid [∀ i, comm_monoid $ f i] : comm_monoid (Π i : I, f i) := by pi_instance instance group [∀ i, group $ f i] : group (Π i : I, f i) := by pi_instance instance comm_group [∀ i, comm_group $ f i] : comm_group (Π i : I, f i) := by pi_instance instance add_semigroup [∀ i, add_semigroup $ f i] : add_semigroup (Π i : I, f i) := by pi_instance instance add_comm_semigroup [∀ i, add_comm_semigroup $ f i] : add_comm_semigroup (Π i : I, f i) := by pi_instance instance add_monoid [∀ i, add_monoid $ f i] : add_monoid (Π i : I, f i) := by pi_instance instance add_comm_monoid [∀ i, add_comm_monoid $ f i] : add_comm_monoid (Π i : I, f i) := by pi_instance instance add_group [∀ i, add_group $ f i] : add_group (Π i : I, f i) := by pi_instance instance add_comm_group [∀ i, add_comm_group $ f i] : add_comm_group (Π i : I, f i) := by pi_instance instance ring [∀ i, ring $ f i] : ring (Π i : I, f i) := by pi_instance instance comm_ring [∀ i, comm_ring $ f i] : comm_ring (Π i : I, f i) := by pi_instance instance mul_action (α) {m : monoid α} [∀ i, mul_action α $ f i] : mul_action α (Π i : I, f i) := { smul := λ c f i, c • f i, mul_smul := λ r s f, funext $ λ i, mul_smul _ _ _, one_smul := λ f, funext $ λ i, one_smul α _ } instance distrib_mul_action (α) {m : monoid α} [∀ i, add_monoid $ f i] [∀ i, distrib_mul_action α $ f i] : distrib_mul_action α (Π i : I, f i) := { smul_zero := λ c, funext $ λ i, smul_zero _, smul_add := λ c f g, funext $ λ i, smul_add _ _ _, ..pi.mul_action _ } variables (I f) instance semimodule (α) {r : semiring α} [∀ i, add_comm_monoid $ f i] [∀ i, semimodule α $ f i] : semimodule α (Π i : I, f i) := { add_smul := λ c f g, funext $ λ i, add_smul _ _ _, zero_smul := λ f, funext $ λ i, zero_smul α _, ..pi.distrib_mul_action _ } variables {I f} instance module (α) {r : ring α} [∀ i, add_comm_group $ f i] [∀ i, module α $ f i] : module α (Π i : I, f i) := {..pi.semimodule I f α} instance vector_space (α) {r : discrete_field α} [∀ i, add_comm_group $ f i] [∀ i, vector_space α $ f i] : vector_space α (Π i : I, f i) := {..pi.module α} instance left_cancel_semigroup [∀ i, left_cancel_semigroup $ f i] : left_cancel_semigroup (Π i : I, f i) := by pi_instance instance add_left_cancel_semigroup [∀ i, add_left_cancel_semigroup $ f i] : add_left_cancel_semigroup (Π i : I, f i) := by pi_instance instance right_cancel_semigroup [∀ i, right_cancel_semigroup $ f i] : right_cancel_semigroup (Π i : I, f i) := by pi_instance instance add_right_cancel_semigroup [∀ i, add_right_cancel_semigroup $ f i] : add_right_cancel_semigroup (Π i : I, f i) := by pi_instance instance ordered_cancel_comm_monoid [∀ i, ordered_cancel_comm_monoid $ f i] : ordered_cancel_comm_monoid (Π i : I, f i) := by pi_instance attribute [to_additive pi.add_semigroup] pi.semigroup attribute [to_additive pi.add_comm_semigroup] pi.comm_semigroup attribute [to_additive pi.add_monoid] pi.monoid attribute [to_additive pi.add_comm_monoid] pi.comm_monoid attribute [to_additive pi.add_group] pi.group attribute [to_additive pi.add_comm_group] pi.comm_group attribute [to_additive pi.add_left_cancel_semigroup] pi.left_cancel_semigroup attribute [to_additive pi.add_right_cancel_semigroup] pi.right_cancel_semigroup @[to_additive pi.list_sum_apply] lemma list_prod_apply {α : Type*} {β : α → Type*} [∀a, monoid (β a)] (a : α) : ∀ (l : list (Πa, β a)), l.prod a = (l.map (λf:Πa, β a, f a)).prod | [] := rfl | (f :: l) := by simp [mul_apply f l.prod a, list_prod_apply l] @[to_additive pi.multiset_sum_apply] lemma multiset_prod_apply {α : Type*} {β : α → Type*} [∀a, comm_monoid (β a)] (a : α) (s : multiset (Πa, β a)) : s.prod a = (s.map (λf:Πa, β a, f a)).prod := quotient.induction_on s $ assume l, begin simp [list_prod_apply a l] end @[to_additive pi.finset_sum_apply] lemma finset_prod_apply {α : Type*} {β : α → Type*} {γ} [∀a, comm_monoid (β a)] (a : α) (s : finset γ) (g : γ → Πa, β a) : s.prod g a = s.prod (λc, g c a) := show (s.val.map g).prod a = (s.val.map (λc, g c a)).prod, by rw [multiset_prod_apply, multiset.map_map] def is_ring_hom_pi {α : Type u} {β : α → Type v} [R : Π a : α, ring (β a)] {γ : Type w} [ring γ] (f : Π a : α, γ → β a) [Rh : Π a : α, is_ring_hom (f a)] : is_ring_hom (λ x b, f b x) := begin dsimp at *, split, -- It's a pity that these can't be done using `simp` lemmas. { ext, rw [is_ring_hom.map_one (f x)], refl, }, { intros x y, ext1 z, rw [is_ring_hom.map_mul (f z)], refl, }, { intros x y, ext1 z, rw [is_ring_hom.map_add (f z)], refl, } end end pi namespace prod variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {p q : α × β} instance [has_add α] [has_add β] : has_add (α × β) := ⟨λp q, (p.1 + q.1, p.2 + q.2)⟩ @[to_additive prod.has_add] instance [has_mul α] [has_mul β] : has_mul (α × β) := ⟨λp q, (p.1 * q.1, p.2 * q.2)⟩ @[simp, to_additive prod.fst_add] lemma fst_mul [has_mul α] [has_mul β] : (p * q).1 = p.1 * q.1 := rfl @[simp, to_additive prod.snd_add] lemma snd_mul [has_mul α] [has_mul β] : (p * q).2 = p.2 * q.2 := rfl @[simp, to_additive prod.mk_add_mk] lemma mk_mul_mk [has_mul α] [has_mul β] (a₁ a₂ : α) (b₁ b₂ : β) : (a₁, b₁) * (a₂, b₂) = (a₁ * a₂, b₁ * b₂) := rfl instance [has_zero α] [has_zero β] : has_zero (α × β) := ⟨(0, 0)⟩ @[to_additive prod.has_zero] instance [has_one α] [has_one β] : has_one (α × β) := ⟨(1, 1)⟩ @[simp, to_additive prod.fst_zero] lemma fst_one [has_one α] [has_one β] : (1 : α × β).1 = 1 := rfl @[simp, to_additive prod.snd_zero] lemma snd_one [has_one α] [has_one β] : (1 : α × β).2 = 1 := rfl @[to_additive prod.zero_eq_mk] lemma one_eq_mk [has_one α] [has_one β] : (1 : α × β) = (1, 1) := rfl instance [has_neg α] [has_neg β] : has_neg (α × β) := ⟨λp, (- p.1, - p.2)⟩ @[to_additive prod.has_neg] instance [has_inv α] [has_inv β] : has_inv (α × β) := ⟨λp, (p.1⁻¹, p.2⁻¹)⟩ @[simp, to_additive prod.fst_neg] lemma fst_inv [has_inv α] [has_inv β] : (p⁻¹).1 = (p.1)⁻¹ := rfl @[simp, to_additive prod.snd_neg] lemma snd_inv [has_inv α] [has_inv β] : (p⁻¹).2 = (p.2)⁻¹ := rfl @[to_additive prod.neg_mk] lemma inv_mk [has_inv α] [has_inv β] (a : α) (b : β) : (a, b)⁻¹ = (a⁻¹, b⁻¹) := rfl instance [add_semigroup α] [add_semigroup β] : add_semigroup (α × β) := { add_assoc := assume a b c, mk.inj_iff.mpr ⟨add_assoc _ _ _, add_assoc _ _ _⟩, .. prod.has_add } @[to_additive prod.add_semigroup] instance [semigroup α] [semigroup β] : semigroup (α × β) := { mul_assoc := assume a b c, mk.inj_iff.mpr ⟨mul_assoc _ _ _, mul_assoc _ _ _⟩, .. prod.has_mul } instance [add_monoid α] [add_monoid β] : add_monoid (α × β) := { zero_add := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨zero_add _, zero_add _⟩, add_zero := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨add_zero _, add_zero _⟩, .. prod.add_semigroup, .. prod.has_zero } @[to_additive prod.add_monoid] instance [monoid α] [monoid β] : monoid (α × β) := { one_mul := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨one_mul _, one_mul _⟩, mul_one := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨mul_one _, mul_one _⟩, .. prod.semigroup, .. prod.has_one } instance [add_group α] [add_group β] : add_group (α × β) := { add_left_neg := assume a, mk.inj_iff.mpr ⟨add_left_neg _, add_left_neg _⟩, .. prod.add_monoid, .. prod.has_neg } @[to_additive prod.add_group] instance [group α] [group β] : group (α × β) := { mul_left_inv := assume a, mk.inj_iff.mpr ⟨mul_left_inv _, mul_left_inv _⟩, .. prod.monoid, .. prod.has_inv } instance [add_comm_semigroup α] [add_comm_semigroup β] : add_comm_semigroup (α × β) := { add_comm := assume a b, mk.inj_iff.mpr ⟨add_comm _ _, add_comm _ _⟩, .. prod.add_semigroup } @[to_additive prod.add_comm_semigroup] instance [comm_semigroup α] [comm_semigroup β] : comm_semigroup (α × β) := { mul_comm := assume a b, mk.inj_iff.mpr ⟨mul_comm _ _, mul_comm _ _⟩, .. prod.semigroup } instance [add_comm_monoid α] [add_comm_monoid β] : add_comm_monoid (α × β) := { .. prod.add_comm_semigroup, .. prod.add_monoid } @[to_additive prod.add_comm_monoid] instance [comm_monoid α] [comm_monoid β] : comm_monoid (α × β) := { .. prod.comm_semigroup, .. prod.monoid } instance [add_comm_group α] [add_comm_group β] : add_comm_group (α × β) := { .. prod.add_comm_semigroup, .. prod.add_group } @[to_additive prod.add_comm_group] instance [comm_group α] [comm_group β] : comm_group (α × β) := { .. prod.comm_semigroup, .. prod.group } @[to_additive fst.is_add_monoid_hom] lemma fst.is_monoid_hom [monoid α] [monoid β] : is_monoid_hom (prod.fst : α × β → α) := { map_mul := λ _ _, rfl, map_one := rfl } @[to_additive snd.is_add_monoid_hom] lemma snd.is_monoid_hom [monoid α] [monoid β] : is_monoid_hom (prod.snd : α × β → β) := { map_mul := λ _ _, rfl, map_one := rfl } @[to_additive fst.is_add_group_hom] lemma fst.is_group_hom [group α] [group β] : is_group_hom (prod.fst : α × β → α) := by refine_struct {..}; simp @[to_additive snd.is_add_group_hom] lemma snd.is_group_hom [group α] [group β] : is_group_hom (prod.snd : α × β → β) := by refine_struct {..}; simp attribute [instance] fst.is_monoid_hom fst.is_add_monoid_hom snd.is_monoid_hom snd.is_add_monoid_hom fst.is_group_hom fst.is_add_group_hom snd.is_group_hom snd.is_add_group_hom @[to_additive prod.fst_sum] lemma fst_prod [comm_monoid α] [comm_monoid β] {t : finset γ} {f : γ → α × β} : (t.prod f).1 = t.prod (λc, (f c).1) := (finset.prod_hom prod.fst).symm @[to_additive prod.snd_sum] lemma snd_prod [comm_monoid α] [comm_monoid β] {t : finset γ} {f : γ → α × β} : (t.prod f).2 = t.prod (λc, (f c).2) := (finset.prod_hom prod.snd).symm instance [semiring α] [semiring β] : semiring (α × β) := { zero_mul := λ a, mk.inj_iff.mpr ⟨zero_mul _, zero_mul _⟩, mul_zero := λ a, mk.inj_iff.mpr ⟨mul_zero _, mul_zero _⟩, left_distrib := λ a b c, mk.inj_iff.mpr ⟨left_distrib _ _ _, left_distrib _ _ _⟩, right_distrib := λ a b c, mk.inj_iff.mpr ⟨right_distrib _ _ _, right_distrib _ _ _⟩, ..prod.add_comm_monoid, ..prod.monoid } instance [ring α] [ring β] : ring (α × β) := { ..prod.add_comm_group, ..prod.semiring } instance [comm_ring α] [comm_ring β] : comm_ring (α × β) := { ..prod.ring, ..prod.comm_monoid } instance [nonzero_comm_ring α] [comm_ring β] : nonzero_comm_ring (α × β) := { zero_ne_one := mt (congr_arg prod.fst) zero_ne_one, ..prod.comm_ring } instance fst.is_semiring_hom [semiring α] [semiring β] : is_semiring_hom (prod.fst : α × β → α) := by refine_struct {..}; simp instance snd.is_semiring_hom [semiring α] [semiring β] : is_semiring_hom (prod.snd : α × β → β) := by refine_struct {..}; simp instance fst.is_ring_hom [ring α] [ring β] : is_ring_hom (prod.fst : α × β → α) := by refine_struct {..}; simp instance snd.is_ring_hom [ring α] [ring β] : is_ring_hom (prod.snd : α × β → β) := by refine_struct {..}; simp /-- Left injection function for the inner product From a vector space (and also group and module) perspective the product is the same as the sum of two vector spaces. `inl` and `inr` provide the corresponding injection functions. -/ def inl [has_zero β] (a : α) : α × β := (a, 0) /-- Right injection function for the inner product -/ def inr [has_zero α] (b : β) : α × β := (0, b) lemma injective_inl [has_zero β] : function.injective (inl : α → α × β) := assume x y h, (prod.mk.inj_iff.mp h).1 lemma injective_inr [has_zero α] : function.injective (inr : β → α × β) := assume x y h, (prod.mk.inj_iff.mp h).2 @[simp] lemma inl_eq_inl [has_zero β] {a₁ a₂ : α} : (inl a₁ : α × β) = inl a₂ ↔ a₁ = a₂ := iff.intro (assume h, injective_inl h) (assume h, h ▸ rfl) @[simp] lemma inr_eq_inr [has_zero α] {b₁ b₂ : β} : (inr b₁ : α × β) = inr b₂ ↔ b₁ = b₂ := iff.intro (assume h, injective_inr h) (assume h, h ▸ rfl) @[simp] lemma inl_eq_inr [has_zero α] [has_zero β] {a : α} {b : β} : inl a = inr b ↔ a = 0 ∧ b = 0 := by constructor; simp [inl, inr] {contextual := tt} @[simp] lemma inr_eq_inl [has_zero α] [has_zero β] {a : α} {b : β} : inr b = inl a ↔ a = 0 ∧ b = 0 := by constructor; simp [inl, inr] {contextual := tt} @[simp] lemma fst_inl [has_zero β] (a : α) : (inl a : α × β).1 = a := rfl @[simp] lemma snd_inl [has_zero β] (a : α) : (inl a : α × β).2 = 0 := rfl @[simp] lemma fst_inr [has_zero α] (b : β) : (inr b : α × β).1 = 0 := rfl @[simp] lemma snd_inr [has_zero α] (b : β) : (inr b : α × β).2 = b := rfl instance [has_scalar α β] [has_scalar α γ] : has_scalar α (β × γ) := ⟨λa p, (a • p.1, a • p.2)⟩ @[simp] theorem smul_fst [has_scalar α β] [has_scalar α γ] (a : α) (x : β × γ) : (a • x).1 = a • x.1 := rfl @[simp] theorem smul_snd [has_scalar α β] [has_scalar α γ] (a : α) (x : β × γ) : (a • x).2 = a • x.2 := rfl @[simp] theorem smul_mk [has_scalar α β] [has_scalar α γ] (a : α) (b : β) (c : γ) : a • (b, c) = (a • b, a • c) := rfl instance {r : semiring α} [add_comm_monoid β] [add_comm_monoid γ] [semimodule α β] [semimodule α γ] : semimodule α (β × γ) := { smul_add := assume a p₁ p₂, mk.inj_iff.mpr ⟨smul_add _ _ _, smul_add _ _ _⟩, add_smul := assume a p₁ p₂, mk.inj_iff.mpr ⟨add_smul _ _ _, add_smul _ _ _⟩, mul_smul := assume a₁ a₂ p, mk.inj_iff.mpr ⟨mul_smul _ _ _, mul_smul _ _ _⟩, one_smul := assume ⟨b, c⟩, mk.inj_iff.mpr ⟨one_smul _ _, one_smul _ _⟩, zero_smul := assume ⟨b, c⟩, mk.inj_iff.mpr ⟨zero_smul _ _, zero_smul _ _⟩, smul_zero := assume a, mk.inj_iff.mpr ⟨smul_zero _, smul_zero _⟩, .. prod.has_scalar } instance {r : ring α} [add_comm_group β] [add_comm_group γ] [module α β] [module α γ] : module α (β × γ) := {} instance {r : discrete_field α} [add_comm_group β] [add_comm_group γ] [vector_space α β] [vector_space α γ] : vector_space α (β × γ) := {} end prod namespace finset @[to_additive finset.prod_mk_sum] lemma prod_mk_prod {α β γ : Type*} [comm_monoid α] [comm_monoid β] (s : finset γ) (f : γ → α) (g : γ → β) : (s.prod f, s.prod g) = s.prod (λ x, (f x, g x)) := by haveI := classical.dec_eq γ; exact finset.induction_on s rfl (by simp [prod.ext_iff] {contextual := tt}) end finset
dcbfccb46244556ea5b7e31cd4af93d6cbdfefc2
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/algebraic_geometry/structure_sheaf.lean
d5900daff1cb1d953bc6bf1f37376bfe7512ec43
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
45,262
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Scott Morrison -/ import algebraic_geometry.prime_spectrum import algebra.category.CommRing.colimits import algebra.category.CommRing.limits import topology.sheaves.local_predicate import ring_theory.localization import ring_theory.subring /-! # The structure sheaf on `prime_spectrum R`. We define the structure sheaf on `Top.of (prime_spectrum R)`, for a commutative ring `R` and prove basic properties about it. We define this as a subsheaf of the sheaf of dependent functions into the localizations, cut out by the condition that the function must be locally equal to a ratio of elements of `R`. Because the condition "is equal to a fraction" passes to smaller open subsets, the subset of functions satisfying this condition is automatically a subpresheaf. Because the condition "is locally equal to a fraction" is local, it is also a subsheaf. (It may be helpful to refer back to `topology.sheaves.sheaf_of_functions`, where we show that dependent functions into any type family form a sheaf, and also `topology.sheaves.local_predicate`, where we characterise the predicates which pick out sub-presheaves and sub-sheaves of these sheaves.) We also set up the ring structure, obtaining `structure_sheaf R : sheaf CommRing (Top.of (prime_spectrum R))`. We then construct two basic isomorphisms, relating the structure sheaf to the underlying ring `R`. First, `structure_sheaf.stalk_iso` gives an isomorphism between the stalk of the structure sheaf at a point `p` and the localization of `R` at the prime ideal `p`. Second, `structure_sheaf.basic_open_iso` gives an isomorphism between the structure sheaf on `basic_open f` and the localization of `R` at the submonoid of powers of `f`. ## References * [Robin Hartshorne, *Algebraic Geometry*][Har77] -/ universe u noncomputable theory variables (R : Type u) [comm_ring R] open Top open topological_space open category_theory open opposite namespace algebraic_geometry /-- The prime spectrum, just as a topological space. -/ def prime_spectrum.Top : Top := Top.of (prime_spectrum R) namespace structure_sheaf /-- The type family over `prime_spectrum R` consisting of the localization over each point. -/ @[derive [comm_ring, local_ring]] def localizations (P : prime_spectrum.Top R) : Type u := localization.at_prime P.as_ideal instance (P : prime_spectrum.Top R) : inhabited (localizations R P) := ⟨1⟩ instance (U : opens (prime_spectrum.Top R)) (x : U) : algebra R (localizations R x) := localization.algebra instance (U : opens (prime_spectrum.Top R)) (x : U) : is_localization.at_prime (localizations R x) (x : prime_spectrum.Top R).as_ideal := localization.is_localization variables {R} /-- The predicate saying that a dependent function on an open `U` is realised as a fixed fraction `r / s` in each of the stalks (which are localizations at various prime ideals). -/ def is_fraction {U : opens (prime_spectrum.Top R)} (f : Π x : U, localizations R x) : Prop := ∃ (r s : R), ∀ x : U, ¬ (s ∈ x.1.as_ideal) ∧ f x * algebra_map _ _ s = algebra_map _ _ r lemma is_fraction.eq_mk' {U : opens (prime_spectrum.Top R)} {f : Π x : U, localizations R x} (hf : is_fraction f) : ∃ (r s : R) , ∀ x : U, ∃ (hs : s ∉ x.1.as_ideal), f x = is_localization.mk' (localization.at_prime _) r (⟨s, hs⟩ : (x : prime_spectrum.Top R).as_ideal.prime_compl) := begin rcases hf with ⟨r, s, h⟩, refine ⟨r, s, λ x, ⟨(h x).1, (is_localization.mk'_eq_iff_eq_mul.mpr _).symm⟩⟩, exact (h x).2.symm, end variables (R) /-- The predicate `is_fraction` is "prelocal", in the sense that if it holds on `U` it holds on any open subset `V` of `U`. -/ def is_fraction_prelocal : prelocal_predicate (localizations R) := { pred := λ U f, is_fraction f, res := by { rintro V U i f ⟨r, s, w⟩, exact ⟨r, s, λ x, w (i x)⟩ } } /-- We will define the structure sheaf as the subsheaf of all dependent functions in `Π x : U, localizations R x` consisting of those functions which can locally be expressed as a ratio of (the images in the localization of) elements of `R`. Quoting Hartshorne: For an open set $U ⊆ Spec A$, we define $𝒪(U)$ to be the set of functions $s : U → ⨆_{𝔭 ∈ U} A_𝔭$, such that $s(𝔭) ∈ A_𝔭$ for each $𝔭$, and such that $s$ is locally a quotient of elements of $A$: to be precise, we require that for each $𝔭 ∈ U$, there is a neighborhood $V$ of $𝔭$, contained in $U$, and elements $a, f ∈ A$, such that for each $𝔮 ∈ V, f ∉ 𝔮$, and $s(𝔮) = a/f$ in $A_𝔮$. Now Hartshorne had the disadvantage of not knowing about dependent functions, so we replace his circumlocution about functions into a disjoint union with `Π x : U, localizations x`. -/ def is_locally_fraction : local_predicate (localizations R) := (is_fraction_prelocal R).sheafify @[simp] lemma is_locally_fraction_pred {U : opens (prime_spectrum.Top R)} (f : Π x : U, localizations R x) : (is_locally_fraction R).pred f = ∀ x : U, ∃ (V) (m : x.1 ∈ V) (i : V ⟶ U), ∃ (r s : R), ∀ y : V, ¬ (s ∈ y.1.as_ideal) ∧ f (i y : U) * algebra_map _ _ s = algebra_map _ _ r := rfl /-- The functions satisfying `is_locally_fraction` form a subring. -/ def sections_subring (U : (opens (prime_spectrum.Top R))ᵒᵖ) : subring (Π x : unop U, localizations R x) := { carrier := { f | (is_locally_fraction R).pred f }, zero_mem' := begin refine λ x, ⟨unop U, x.2, 𝟙 _, 0, 1, λ y, ⟨_, _⟩⟩, { rw ←ideal.ne_top_iff_one, exact y.1.is_prime.1, }, { simp, }, end, one_mem' := begin refine λ x, ⟨unop U, x.2, 𝟙 _, 1, 1, λ y, ⟨_, _⟩⟩, { rw ←ideal.ne_top_iff_one, exact y.1.is_prime.1, }, { simp, }, end, add_mem' := begin intros a b ha hb x, rcases ha x with ⟨Va, ma, ia, ra, sa, wa⟩, rcases hb x with ⟨Vb, mb, ib, rb, sb, wb⟩, refine ⟨Va ⊓ Vb, ⟨ma, mb⟩, opens.inf_le_left _ _ ≫ ia, ra * sb + rb * sa, sa * sb, _⟩, intro y, rcases wa (opens.inf_le_left _ _ y) with ⟨nma, wa⟩, rcases wb (opens.inf_le_right _ _ y) with ⟨nmb, wb⟩, fsplit, { intro H, cases y.1.is_prime.mem_or_mem H; contradiction, }, { simp only [add_mul, ring_hom.map_add, pi.add_apply, ring_hom.map_mul], erw [←wa, ←wb], simp only [mul_assoc], congr' 2, rw [mul_comm], refl, } end, neg_mem' := begin intros a ha x, rcases ha x with ⟨V, m, i, r, s, w⟩, refine ⟨V, m, i, -r, s, _⟩, intro y, rcases w y with ⟨nm, w⟩, fsplit, { exact nm, }, { simp only [ring_hom.map_neg, pi.neg_apply], erw [←w], simp only [neg_mul_eq_neg_mul_symm], } end, mul_mem' := begin intros a b ha hb x, rcases ha x with ⟨Va, ma, ia, ra, sa, wa⟩, rcases hb x with ⟨Vb, mb, ib, rb, sb, wb⟩, refine ⟨Va ⊓ Vb, ⟨ma, mb⟩, opens.inf_le_left _ _ ≫ ia, ra * rb, sa * sb, _⟩, intro y, rcases wa (opens.inf_le_left _ _ y) with ⟨nma, wa⟩, rcases wb (opens.inf_le_right _ _ y) with ⟨nmb, wb⟩, fsplit, { intro H, cases y.1.is_prime.mem_or_mem H; contradiction, }, { simp only [pi.mul_apply, ring_hom.map_mul], erw [←wa, ←wb], simp only [mul_left_comm, mul_assoc, mul_comm], refl, } end, } end structure_sheaf open structure_sheaf /-- The structure sheaf (valued in `Type`, not yet `CommRing`) is the subsheaf consisting of functions satisfying `is_locally_fraction`. -/ def structure_sheaf_in_Type : sheaf (Type u) (prime_spectrum.Top R):= subsheaf_to_Types (is_locally_fraction R) instance comm_ring_structure_sheaf_in_Type_obj (U : (opens (prime_spectrum.Top R))ᵒᵖ) : comm_ring ((structure_sheaf_in_Type R).presheaf.obj U) := (sections_subring R U).to_comm_ring open prime_spectrum /-- The structure presheaf, valued in `CommRing`, constructed by dressing up the `Type` valued structure presheaf. -/ @[simps] def structure_presheaf_in_CommRing : presheaf CommRing (prime_spectrum.Top R) := { obj := λ U, CommRing.of ((structure_sheaf_in_Type R).presheaf.obj U), map := λ U V i, { to_fun := ((structure_sheaf_in_Type R).presheaf.map i), map_zero' := rfl, map_add' := λ x y, rfl, map_one' := rfl, map_mul' := λ x y, rfl, }, } /-- Some glue, verifying that that structure presheaf valued in `CommRing` agrees with the `Type` valued structure presheaf. -/ def structure_presheaf_comp_forget : structure_presheaf_in_CommRing R ⋙ (forget CommRing) ≅ (structure_sheaf_in_Type R).presheaf := nat_iso.of_components (λ U, iso.refl _) (by tidy) open Top.presheaf /-- The structure sheaf on $Spec R$, valued in `CommRing`. This is provided as a bundled `SheafedSpace` as `Spec.SheafedSpace R` later. -/ def structure_sheaf : sheaf CommRing (prime_spectrum.Top R) := { presheaf := structure_presheaf_in_CommRing R, sheaf_condition := -- We check the sheaf condition under `forget CommRing`. (sheaf_condition_equiv_sheaf_condition_comp _ _).symm (sheaf_condition_equiv_of_iso (structure_presheaf_comp_forget R).symm (structure_sheaf_in_Type R).sheaf_condition), } namespace structure_sheaf @[simp] lemma res_apply (U V : opens (prime_spectrum.Top R)) (i : V ⟶ U) (s : (structure_sheaf R).presheaf.obj (op U)) (x : V) : ((structure_sheaf R).presheaf.map i.op s).1 x = (s.1 (i x) : _) := rfl /- Notation in this comment X = Spec R OX = structure sheaf In the following we construct an isomorphism between OX_p and R_p given any point p corresponding to a prime ideal in R. We do this via 8 steps: 1. def const (f g : R) (V) (hv : V ≤ D_g) : OX(V) [for api] 2. def to_open (U) : R ⟶ OX(U) 3. [2] def to_stalk (p : Spec R) : R ⟶ OX_p 4. [2] def to_basic_open (f : R) : R_f ⟶ OX(D_f) 5. [3] def localization_to_stalk (p : Spec R) : R_p ⟶ OX_p 6. def open_to_localization (U) (p) (hp : p ∈ U) : OX(U) ⟶ R_p 7. [6] def stalk_to_fiber_ring_hom (p : Spec R) : OX_p ⟶ R_p 8. [5,7] def stalk_iso (p : Spec R) : OX_p ≅ R_p In the square brackets we list the dependencies of a construction on the previous steps. -/ /-- The section of `structure_sheaf R` on an open `U` sending each `x ∈ U` to the element `f/g` in the localization of `R` at `x`. -/ def const (f g : R) (U : opens (prime_spectrum.Top R)) (hu : ∀ x ∈ U, g ∈ (x : prime_spectrum.Top R).as_ideal.prime_compl) : (structure_sheaf R).presheaf.obj (op U) := ⟨λ x, is_localization.mk' _ f ⟨g, hu x x.2⟩, λ x, ⟨U, x.2, 𝟙 _, f, g, λ y, ⟨hu y y.2, is_localization.mk'_spec _ _ _⟩⟩⟩ @[simp] lemma const_apply (f g : R) (U : opens (prime_spectrum.Top R)) (hu : ∀ x ∈ U, g ∈ (x : prime_spectrum.Top R).as_ideal.prime_compl) (x : U) : (const R f g U hu).1 x = is_localization.mk' _ f ⟨g, hu x x.2⟩ := rfl lemma const_apply' (f g : R) (U : opens (prime_spectrum.Top R)) (hu : ∀ x ∈ U, g ∈ (x : prime_spectrum.Top R).as_ideal.prime_compl) (x : U) (hx : g ∈ (as_ideal (x : prime_spectrum.Top R)).prime_compl) : (const R f g U hu).1 x = is_localization.mk' _ f ⟨g, hx⟩ := rfl lemma exists_const (U) (s : (structure_sheaf R).presheaf.obj (op U)) (x : prime_spectrum.Top R) (hx : x ∈ U) : ∃ (V : opens (prime_spectrum.Top R)) (hxV : x ∈ V) (i : V ⟶ U) (f g : R) hg, const R f g V hg = (structure_sheaf R).presheaf.map i.op s := let ⟨V, hxV, iVU, f, g, hfg⟩ := s.2 ⟨x, hx⟩ in ⟨V, hxV, iVU, f, g, λ y hyV, (hfg ⟨y, hyV⟩).1, subtype.eq $ funext $ λ y, is_localization.mk'_eq_iff_eq_mul.2 $ eq.symm $ (hfg y).2⟩ @[simp] lemma res_const (f g : R) (U hu V hv i) : (structure_sheaf R).presheaf.map i (const R f g U hu) = const R f g V hv := rfl lemma res_const' (f g : R) (V hv) : (structure_sheaf R).presheaf.map (hom_of_le hv).op (const R f g (basic_open g) (λ _, id)) = const R f g V hv := rfl lemma const_zero (f : R) (U hu) : const R 0 f U hu = 0 := subtype.eq $ funext $ λ x, is_localization.mk'_eq_iff_eq_mul.2 $ by erw [ring_hom.map_zero, subtype.val_eq_coe, subring.coe_zero, pi.zero_apply, zero_mul] lemma const_self (f : R) (U hu) : const R f f U hu = 1 := subtype.eq $ funext $ λ x, is_localization.mk'_self _ _ lemma const_one (U) : const R 1 1 U (λ p _, submonoid.one_mem _) = 1 := const_self R 1 U _ lemma const_add (f₁ f₂ g₁ g₂ : R) (U hu₁ hu₂) : const R f₁ g₁ U hu₁ + const R f₂ g₂ U hu₂ = const R (f₁ * g₂ + f₂ * g₁) (g₁ * g₂) U (λ x hx, submonoid.mul_mem _ (hu₁ x hx) (hu₂ x hx)) := subtype.eq $ funext $ λ x, eq.symm $ by convert is_localization.mk'_add f₁ f₂ ⟨g₁, hu₁ x x.2⟩ ⟨g₂, hu₂ x x.2⟩ lemma const_mul (f₁ f₂ g₁ g₂ : R) (U hu₁ hu₂) : const R f₁ g₁ U hu₁ * const R f₂ g₂ U hu₂ = const R (f₁ * f₂) (g₁ * g₂) U (λ x hx, submonoid.mul_mem _ (hu₁ x hx) (hu₂ x hx)) := subtype.eq $ funext $ λ x, eq.symm $ by convert is_localization.mk'_mul _ f₁ f₂ ⟨g₁, hu₁ x x.2⟩ ⟨g₂, hu₂ x x.2⟩ lemma const_ext {f₁ f₂ g₁ g₂ : R} {U hu₁ hu₂} (h : f₁ * g₂ = f₂ * g₁) : const R f₁ g₁ U hu₁ = const R f₂ g₂ U hu₂ := subtype.eq $ funext $ λ x, is_localization.mk'_eq_of_eq h.symm lemma const_congr {f₁ f₂ g₁ g₂ : R} {U hu} (hf : f₁ = f₂) (hg : g₁ = g₂) : const R f₁ g₁ U hu = const R f₂ g₂ U (hg ▸ hu) := by substs hf hg lemma const_mul_rev (f g : R) (U hu₁ hu₂) : const R f g U hu₁ * const R g f U hu₂ = 1 := by rw [const_mul, const_congr R rfl (mul_comm g f), const_self] lemma const_mul_cancel (f g₁ g₂ : R) (U hu₁ hu₂) : const R f g₁ U hu₁ * const R g₁ g₂ U hu₂ = const R f g₂ U hu₂ := by { rw [const_mul, const_ext], rw mul_assoc } lemma const_mul_cancel' (f g₁ g₂ : R) (U hu₁ hu₂) : const R g₁ g₂ U hu₂ * const R f g₁ U hu₁ = const R f g₂ U hu₂ := by rw [mul_comm, const_mul_cancel] /-- The canonical ring homomorphism interpreting an element of `R` as a section of the structure sheaf. -/ def to_open (U : opens (prime_spectrum.Top R)) : CommRing.of R ⟶ (structure_sheaf R).presheaf.obj (op U) := { to_fun := λ f, ⟨λ x, algebra_map R _ f, λ x, ⟨U, x.2, 𝟙 _, f, 1, λ y, ⟨(ideal.ne_top_iff_one _).1 y.1.2.1, by { rw [ring_hom.map_one, mul_one], refl } ⟩⟩⟩, map_one' := subtype.eq $ funext $ λ x, ring_hom.map_one _, map_mul' := λ f g, subtype.eq $ funext $ λ x, ring_hom.map_mul _ _ _, map_zero' := subtype.eq $ funext $ λ x, ring_hom.map_zero _, map_add' := λ f g, subtype.eq $ funext $ λ x, ring_hom.map_add _ _ _ } @[simp] lemma to_open_res (U V : opens (prime_spectrum.Top R)) (i : V ⟶ U) : to_open R U ≫ (structure_sheaf R).presheaf.map i.op = to_open R V := rfl @[simp] lemma to_open_apply (U : opens (prime_spectrum.Top R)) (f : R) (x : U) : (to_open R U f).1 x = algebra_map _ _ f := rfl lemma to_open_eq_const (U : opens (prime_spectrum.Top R)) (f : R) : to_open R U f = const R f 1 U (λ x _, (ideal.ne_top_iff_one _).1 x.2.1) := subtype.eq $ funext $ λ x, eq.symm $ is_localization.mk'_one _ f /-- The canonical ring homomorphism interpreting an element of `R` as an element of the stalk of `structure_sheaf R` at `x`. -/ def to_stalk (x : prime_spectrum.Top R) : CommRing.of R ⟶ (structure_sheaf R).presheaf.stalk x := (to_open R ⊤ ≫ (structure_sheaf R).presheaf.germ ⟨x, ⟨⟩⟩ : _) @[simp] lemma to_open_germ (U : opens (prime_spectrum.Top R)) (x : U) : to_open R U ≫ (structure_sheaf R).presheaf.germ x = to_stalk R x := by { rw [← to_open_res R ⊤ U (hom_of_le le_top : U ⟶ ⊤), category.assoc, presheaf.germ_res], refl } @[simp] lemma germ_to_open (U : opens (prime_spectrum.Top R)) (x : U) (f : R) : (structure_sheaf R).presheaf.germ x (to_open R U f) = to_stalk R x f := by { rw ← to_open_germ, refl } lemma germ_to_top (x : prime_spectrum.Top R) (f : R) : (structure_sheaf R).presheaf.germ (⟨x, trivial⟩ : (⊤ : opens (prime_spectrum.Top R))) (to_open R ⊤ f) = to_stalk R x f := rfl lemma is_unit_to_basic_open_self (f : R) : is_unit (to_open R (basic_open f) f) := is_unit_of_mul_eq_one _ (const R 1 f (basic_open f) (λ _, id)) $ by rw [to_open_eq_const, const_mul_rev] lemma is_unit_to_stalk (x : prime_spectrum.Top R) (f : x.as_ideal.prime_compl) : is_unit (to_stalk R x (f : R)) := by { erw ← germ_to_open R (basic_open (f : R)) ⟨x, f.2⟩ (f : R), exact ring_hom.is_unit_map _ (is_unit_to_basic_open_self R f) } /-- The canonical ring homomorphism from the localization of `R` at `p` to the stalk of the structure sheaf at the point `p`. -/ def localization_to_stalk (x : prime_spectrum.Top R) : CommRing.of (localization.at_prime x.as_ideal) ⟶ (structure_sheaf R).presheaf.stalk x := show localization.at_prime x.as_ideal →+* _, from is_localization.lift (is_unit_to_stalk R x) @[simp] lemma localization_to_stalk_of (x : prime_spectrum.Top R) (f : R) : localization_to_stalk R x (algebra_map _ (localization _) f) = to_stalk R x f := is_localization.lift_eq _ f @[simp] lemma localization_to_stalk_mk' (x : prime_spectrum.Top R) (f : R) (s : (as_ideal x).prime_compl) : localization_to_stalk R x (is_localization.mk' _ f s : localization _) = (structure_sheaf R).presheaf.germ (⟨x, s.2⟩ : basic_open (s : R)) (const R f s (basic_open s) (λ _, id)) := (is_localization.lift_mk'_spec _ _ _ _).2 $ by erw [← germ_to_open R (basic_open s) ⟨x, s.2⟩, ← germ_to_open R (basic_open s) ⟨x, s.2⟩, ← ring_hom.map_mul, to_open_eq_const, to_open_eq_const, const_mul_cancel'] /-- The ring homomorphism that takes a section of the structure sheaf of `R` on the open set `U`, implemented as a subtype of dependent functions to localizations at prime ideals, and evaluates the section on the point corresponding to a given prime ideal. -/ def open_to_localization (U : opens (prime_spectrum.Top R)) (x : prime_spectrum.Top R) (hx : x ∈ U) : (structure_sheaf R).presheaf.obj (op U) ⟶ CommRing.of (localization.at_prime x.as_ideal) := { to_fun := λ s, (s.1 ⟨x, hx⟩ : _), map_one' := rfl, map_mul' := λ _ _, rfl, map_zero' := rfl, map_add' := λ _ _, rfl } @[simp] lemma coe_open_to_localization (U : opens (prime_spectrum.Top R)) (x : prime_spectrum.Top R) (hx : x ∈ U) : (open_to_localization R U x hx : (structure_sheaf R).presheaf.obj (op U) → localization.at_prime x.as_ideal) = (λ s, (s.1 ⟨x, hx⟩ : _)) := rfl lemma open_to_localization_apply (U : opens (prime_spectrum.Top R)) (x : prime_spectrum.Top R) (hx : x ∈ U) (s : (structure_sheaf R).presheaf.obj (op U)) : open_to_localization R U x hx s = (s.1 ⟨x, hx⟩ : _) := rfl /-- The ring homomorphism from the stalk of the structure sheaf of `R` at a point corresponding to a prime ideal `p` to the localization of `R` at `p`, formed by gluing the `open_to_localization` maps. -/ def stalk_to_fiber_ring_hom (x : prime_spectrum.Top R) : (structure_sheaf R).presheaf.stalk x ⟶ CommRing.of (localization.at_prime x.as_ideal) := limits.colimit.desc (((open_nhds.inclusion x).op) ⋙ (structure_sheaf R).presheaf) { X := _, ι := { app := λ U, open_to_localization R ((open_nhds.inclusion _).obj (unop U)) x (unop U).2, } } @[simp] lemma germ_comp_stalk_to_fiber_ring_hom (U : opens (prime_spectrum.Top R)) (x : U) : (structure_sheaf R).presheaf.germ x ≫ stalk_to_fiber_ring_hom R x = open_to_localization R U x x.2 := limits.colimit.ι_desc _ _ @[simp] lemma stalk_to_fiber_ring_hom_germ' (U : opens (prime_spectrum.Top R)) (x : prime_spectrum.Top R) (hx : x ∈ U) (s : (structure_sheaf R).presheaf.obj (op U)) : stalk_to_fiber_ring_hom R x ((structure_sheaf R).presheaf.germ ⟨x, hx⟩ s) = (s.1 ⟨x, hx⟩ : _) := ring_hom.ext_iff.1 (germ_comp_stalk_to_fiber_ring_hom R U ⟨x, hx⟩ : _) s @[simp] lemma stalk_to_fiber_ring_hom_germ (U : opens (prime_spectrum.Top R)) (x : U) (s : (structure_sheaf R).presheaf.obj (op U)) : stalk_to_fiber_ring_hom R x ((structure_sheaf R).presheaf.germ x s) = s.1 x := by { cases x, exact stalk_to_fiber_ring_hom_germ' R U _ _ _ } @[simp] lemma to_stalk_comp_stalk_to_fiber_ring_hom (x : prime_spectrum.Top R) : to_stalk R x ≫ stalk_to_fiber_ring_hom R x = (algebra_map _ _ : R →+* localization _) := by { erw [to_stalk, category.assoc, germ_comp_stalk_to_fiber_ring_hom], refl } @[simp] lemma stalk_to_fiber_ring_hom_to_stalk (x : prime_spectrum.Top R) (f : R) : stalk_to_fiber_ring_hom R x (to_stalk R x f) = algebra_map _ (localization _) f := ring_hom.ext_iff.1 (to_stalk_comp_stalk_to_fiber_ring_hom R x) _ /-- The ring isomorphism between the stalk of the structure sheaf of `R` at a point `p` corresponding to a prime ideal in `R` and the localization of `R` at `p`. -/ @[simps] def stalk_iso (x : prime_spectrum.Top R) : (structure_sheaf R).presheaf.stalk x ≅ CommRing.of (localization.at_prime x.as_ideal) := { hom := stalk_to_fiber_ring_hom R x, inv := localization_to_stalk R x, hom_inv_id' := (structure_sheaf R).presheaf.stalk_hom_ext $ λ U hxU, begin ext s, simp only [comp_apply], rw [id_apply, stalk_to_fiber_ring_hom_germ'], obtain ⟨V, hxV, iVU, f, g, hg, hs⟩ := exists_const _ _ s x hxU, erw [← res_apply R U V iVU s ⟨x, hxV⟩, ← hs, const_apply, localization_to_stalk_mk'], refine (structure_sheaf R).presheaf.germ_ext V hxV (hom_of_le hg) iVU _, erw [← hs, res_const'] end, inv_hom_id' := @is_localization.ring_hom_ext R _ x.as_ideal.prime_compl (localization.at_prime x.as_ideal) _ _ (localization.at_prime x.as_ideal) _ _ (ring_hom.comp (stalk_to_fiber_ring_hom R x) (localization_to_stalk R x)) (ring_hom.id (localization.at_prime _)) $ by { ext f, simp only [ring_hom.comp_apply, ring_hom.id_apply, localization_to_stalk_of, stalk_to_fiber_ring_hom_to_stalk] } } /-- The canonical ring homomorphism interpreting `s ∈ R_f` as a section of the structure sheaf on the basic open defined by `f ∈ R`. -/ def to_basic_open (f : R) : localization.away f →+* (structure_sheaf R).presheaf.obj (op $ basic_open f) := is_localization.away.lift f (is_unit_to_basic_open_self R f) @[simp] lemma to_basic_open_mk' (s f : R) (g : submonoid.powers s) : to_basic_open R s (is_localization.mk' (localization.away s) f g) = const R f g (basic_open s) (λ x hx, submonoid.powers_subset hx g.2) := (is_localization.lift_mk'_spec _ _ _ _).2 $ by rw [to_open_eq_const, to_open_eq_const, const_mul_cancel'] @[simp] lemma localization_to_basic_open (f : R) : ring_hom.comp (to_basic_open R f) (algebra_map R (localization.away f)) = to_open R (basic_open f) := ring_hom.ext $ λ g, by rw [to_basic_open, is_localization.away.lift, ring_hom.comp_apply, is_localization.lift_eq] @[simp] lemma to_basic_open_to_map (s f : R) : to_basic_open R s (algebra_map R (localization.away s) f) = const R f 1 (basic_open s) (λ _ _, submonoid.one_mem _) := (is_localization.lift_eq _ _).trans $ to_open_eq_const _ _ _ -- The proof here follows the argument in Hartshorne's Algebraic Geometry, Proposition II.2.2. lemma to_basic_open_injective (f : R) : function.injective (to_basic_open R f) := begin intros s t h_eq, obtain ⟨a, ⟨b, hb⟩, rfl⟩ := is_localization.mk'_surjective (submonoid.powers f) s, obtain ⟨c, ⟨d, hd⟩, rfl⟩ := is_localization.mk'_surjective (submonoid.powers f) t, simp only [to_basic_open_mk'] at h_eq, rw is_localization.eq, -- We know that the fractions `a/b` and `c/d` are equal as sections of the structure sheaf on -- `basic_open f`. We need to show that they agree as elements in the localization of `R` at `f`. -- This amounts showing that `a * d * r = c * b * r`, for some power `r = f ^ n` of `f`. -- We define `I` as the ideal of *all* elements `r` satisfying the above equation. let I : ideal R := { carrier := {r : R | a * d * r = c * b * r}, zero_mem' := by simp only [set.mem_set_of_eq, mul_zero], add_mem' := λ r₁ r₂ hr₁ hr₂, by { dsimp at hr₁ hr₂ ⊢, simp only [mul_add, hr₁, hr₂] }, smul_mem' := λ r₁ r₂ hr₂, by { dsimp at hr₂ ⊢, simp only [mul_comm r₁ r₂, ← mul_assoc, hr₂] }}, -- Our claim now reduces to showing that `f` is contained in the radical of `I` suffices : f ∈ I.radical, { cases this with n hn, exact ⟨⟨f ^ n, n, rfl⟩, hn⟩ }, rw [← vanishing_ideal_zero_locus_eq_radical, mem_vanishing_ideal], intros p hfp, contrapose hfp, rw [mem_zero_locus, set.not_subset], have := congr_fun (congr_arg subtype.val h_eq) ⟨p,hfp⟩, rw [const_apply, const_apply, is_localization.eq] at this, cases this with r hr, exact ⟨r.1, hr, r.2⟩ end /- Auxiliary lemma for surjectivity of `to_basic_open`. Every section can locally be represented on basic opens `basic_opens g` as a fraction `f/g` -/ lemma locally_const_basic_open (U : opens (prime_spectrum.Top R)) (s : (structure_sheaf R).presheaf.obj (op U)) (x : U) : ∃ (f g : R) (i : basic_open g ⟶ U), x.1 ∈ basic_open g ∧ const R f g (basic_open g) (λ y hy, hy) = (structure_sheaf R).presheaf.map i.op s := begin -- First, any section `s` can be represented as a fraction `f/g` on some open neighborhood of `x` -- and we may pass to a `basic_open h`, since these form a basis obtain ⟨V, (hxV : x.1 ∈ V.1), iVU, f, g, (hVDg : V ⊆ basic_open g), s_eq⟩ := exists_const R U s x.1 x.2, obtain ⟨_, ⟨h, rfl⟩, hxDh, (hDhV : basic_open h ⊆ V)⟩ := is_topological_basis_basic_opens.exists_subset_of_mem_open hxV V.2, -- The problem is of course, that `g` and `h` don't need to coincide. -- But, since `basic_open h ≤ basic_open g`, some power of `h` must be a multiple of `g` cases (basic_open_le_basic_open_iff h g).mp (set.subset.trans hDhV hVDg) with n hn, -- Actually, we will need a *nonzero* power of `h`. -- This is because we will need the equality `basic_open (h ^ n) = basic_open h`, which only -- holds for a nonzero power `n`. We therefore artificially increase `n` by one. replace hn := ideal.mul_mem_left (ideal.span {g}) h hn, rw [← pow_succ, ideal.mem_span_singleton'] at hn, cases hn with c hc, have basic_opens_eq := basic_open_pow h (n+1) (by linarith), have i_basic_open := eq_to_hom basic_opens_eq ≫ hom_of_le hDhV, -- We claim that `(f * c) / h ^ (n+1)` is our desired representation use [f * c, h ^ (n+1), i_basic_open ≫ iVU, (basic_opens_eq.symm.le : _) hxDh], rw [op_comp, functor.map_comp, comp_apply, ← s_eq, res_const], -- Note that the last rewrite here generated an additional goal, which was a parameter -- of `res_const`. We prove this goal first swap, { intros y hy, rw basic_opens_eq at hy, exact (set.subset.trans hDhV hVDg : _) hy }, -- All that is left is a simple calculation apply const_ext, rw [mul_assoc f c g, hc], end /- Auxiliary lemma for surjectivity of `to_basic_open`. A local representation of a section `s` as fractions `a i / h i` on finitely many basic opens `basic_open (h i)` can be "normalized" in such a way that `a i * h j = h i * a j` for all `i, j` -/ lemma normalize_finite_fraction_representation (U : opens (prime_spectrum.Top R)) (s : (structure_sheaf R).presheaf.obj (op U)) {ι : Type*} (t : finset ι) (a h : ι → R) (iDh : Π i : ι, basic_open (h i) ⟶ U) (h_cover : U.1 ⊆ ⋃ i ∈ t, (basic_open (h i)).1) (hs : ∀ i : ι, const R (a i) (h i) (basic_open (h i)) (λ y hy, hy) = (structure_sheaf R).presheaf.map (iDh i).op s) : ∃ (a' h' : ι → R) (iDh' : Π i : ι, (basic_open (h' i)) ⟶ U), (U.1 ⊆ ⋃ i ∈ t, (basic_open (h' i)).1) ∧ (∀ i j ∈ t, a' i * h' j = h' i * a' j) ∧ (∀ i ∈ t, (structure_sheaf R).presheaf.map (iDh' i).op s = const R (a' i) (h' i) (basic_open (h' i)) (λ y hy, hy)) := begin -- First we show that the fractions `(a i * h j) / (h i * h j)` and `(h i * a j) / (h i * h j)` -- coincide in the localization of `R` at `h i * h j` have fractions_eq : ∀ (i j : ι), is_localization.mk' (localization.away _) (a i * h j) ⟨h i * h j, submonoid.mem_powers _⟩ = is_localization.mk' _ (h i * a j) ⟨h i * h j, submonoid.mem_powers _⟩, { intros i j, let D := basic_open (h i * h j), let iDi : D ⟶ basic_open (h i) := hom_of_le (basic_open_mul_le_left _ _), let iDj : D ⟶ basic_open (h j) := hom_of_le (basic_open_mul_le_right _ _), -- Crucially, we need injectivity of `to_basic_open` apply to_basic_open_injective R (h i * h j), rw [to_basic_open_mk', to_basic_open_mk'], simp only [set_like.coe_mk], -- Here, both sides of the equation are equal to a restriction of `s` transitivity, convert congr_arg ((structure_sheaf R).presheaf.map iDj.op) (hs j).symm using 1, convert congr_arg ((structure_sheaf R).presheaf.map iDi.op) (hs i) using 1, swap, all_goals { rw res_const, apply const_ext, ring }, -- The remaining two goals were generated during the rewrite of `res_const` -- These can be solved immediately exacts [basic_open_mul_le_right _ _, basic_open_mul_le_left _ _] }, -- From the equality in the localization, we obtain for each `(i,j)` some power `(h i * h j) ^ n` -- which equalizes `a i * h j` and `h i * a j` have exists_power : ∀ (i j : ι), ∃ n : ℕ, a i * h j * (h i * h j) ^ n = h i * a j * (h i * h j) ^ n, { intros i j, obtain ⟨⟨c, n, rfl⟩, hc⟩ := is_localization.eq.mp (fractions_eq i j), use (n+1), rw pow_succ, dsimp at hc, convert hc using 1 ; ring }, let n := λ (p : ι × ι), (exists_power p.1 p.2).some, have n_spec := λ (p : ι × ι), (exists_power p.fst p.snd).some_spec, -- We need one power `(h i * h j) ^ N` that works for *all* pairs `(i,j)` -- Since there are only finitely many indices involved, we can pick the supremum. let N := (t.product t).sup n, have basic_opens_eq : ∀ i : ι, basic_open ((h i) ^ (N+1)) = basic_open (h i) := λ i, basic_open_pow _ _ (by linarith), -- Expanding the fraction `a i / h i` by the power `(h i) ^ N` gives the desired normalization refine ⟨(λ i, a i * (h i) ^ N), (λ i, (h i) ^ (N + 1)), (λ i, eq_to_hom (basic_opens_eq i) ≫ iDh i), _, _, _⟩, { simpa only [basic_opens_eq] using h_cover }, { intros i j hi hj, -- Here we need to show that our new fractions `a i / h i` satisfy the normalization condition -- Of course, the power `N` we used to expand the fractions might be bigger than the power -- `n (i, j)` which was originally chosen. We denote their difference by `k` have n_le_N : n (i, j) ≤ N := finset.le_sup (finset.mem_product.mpr ⟨hi, hj⟩), cases nat.le.dest n_le_N with k hk, simp only [← hk, pow_add, pow_one], -- To accommodate for the difference `k`, we multiply both sides of the equation `n_spec (i, j)` -- by `(h i * h j) ^ k` convert congr_arg (λ z, z * (h i * h j) ^ k) (n_spec (i, j)) using 1 ; { simp only [n, mul_pow], ring } }, -- Lastly, we need to show that the new fractions still represent our original `s` intros i hi, rw [op_comp, functor.map_comp, comp_apply, ← hs, res_const], -- additional goal spit out by `res_const` swap, exact (basic_opens_eq i).le, apply const_ext, rw pow_succ, ring end open_locale classical open_locale big_operators -- The proof here follows the argument in Hartshorne's Algebraic Geometry, Proposition II.2.2. lemma to_basic_open_surjective (f : R) : function.surjective (to_basic_open R f) := begin intro s, -- In this proof, `basic_open f` will play two distinct roles: Firstly, it is an open set in the -- prime spectrum. Secondly, it is used as an indexing type for various families of objects -- (open sets, ring elements, ...). In order to make the distinction clear, we introduce a type -- alias `ι` that is used whenever we want think of it as an indexing type. let ι : Type u := basic_open f, -- First, we pick some cover of basic opens, on which we can represent `s` as a fraction choose a' h' iDh' hxDh' s_eq' using locally_const_basic_open R (basic_open f) s, -- Since basic opens are compact, we can pass to a finite subcover obtain ⟨t, ht_cover'⟩ := (is_compact_basic_open f).elim_finite_subcover (λ (i : ι), (basic_open (h' i)).1) (λ i, is_open_basic_open) (λ x hx, _), swap, { -- Here, we need to show that our basic opens actually form a cover of `basic_open f` rw set.mem_Union, exact ⟨⟨x,hx⟩, hxDh' ⟨x, hx⟩⟩ }, -- We use the normalization lemma from above to obtain the relation `a i * h j = h i * a j` obtain ⟨a, h, iDh, ht_cover, ah_ha, s_eq⟩ := normalize_finite_fraction_representation R (basic_open f) s t a' h' iDh' ht_cover' s_eq', clear s_eq' iDh' hxDh' ht_cover' a' h', -- Next we show that some power of `f` is a linear combination of the `h i` obtain ⟨n, hn⟩ : f ∈ (ideal.span (h '' ↑t)).radical, { rw [← vanishing_ideal_zero_locus_eq_radical, zero_locus_span], simp_rw [subtype.val_eq_coe, basic_open_eq_zero_locus_compl] at ht_cover, rw set.compl_subset_comm at ht_cover, -- Why doesn't `simp_rw` do this? simp_rw [set.compl_Union, compl_compl, ← zero_locus_Union, ← finset.set_bUnion_coe, ← set.image_eq_Union ] at ht_cover, apply vanishing_ideal_anti_mono ht_cover, exact subset_vanishing_ideal_zero_locus {f} (set.mem_singleton f) }, replace hn := ideal.mul_mem_left _ f hn, erw [←pow_succ, finsupp.mem_span_image_iff_total] at hn, rcases hn with ⟨b, b_supp, hb⟩, rw finsupp.total_apply_of_mem_supported R b_supp at hb, dsimp at hb, -- Finally, we have all the ingredients. -- We claim that our preimage is given by `(∑ (i : ι) in t, b i * a i) / f ^ (n+1)` use is_localization.mk' (localization.away f) (∑ (i : ι) in t, b i * a i) (⟨f ^ (n+1), n+1, rfl⟩ : submonoid.powers _), rw to_basic_open_mk', -- Since the structure sheaf is a sheaf, we can show the desired equality locally. -- Annoyingly, `sheaf.eq_of_locally_eq` requires an open cover indexed by a *type*, so we need to -- coerce our finset `t` to a type first. let tt := ((t : set (basic_open f)) : Type u), apply (structure_sheaf R).eq_of_locally_eq' (λ i : tt, basic_open (h i)) (basic_open f) (λ i : tt, iDh i), { -- This feels a little redundant, since already have `ht_cover` as a hypothesis -- Unfortunately, `ht_cover` uses a bounded union over the set `t`, while here we have the -- Union indexed by the type `tt`, so we need some boilerplate to translate one to the other intros x hx, erw topological_space.opens.mem_supr, have := ht_cover hx, rw [← finset.set_bUnion_coe, set.mem_bUnion_iff] at this, rcases this with ⟨i, i_mem, x_mem⟩, use [i, i_mem] }, rintro ⟨i, hi⟩, dsimp, change (structure_sheaf R).presheaf.map _ _ = (structure_sheaf R).presheaf.map _ _, rw [s_eq i hi, res_const], -- Again, `res_const` spits out an additional goal swap, { intros y hy, change y ∈ basic_open (f ^ (n+1)), rw basic_open_pow f (n+1) (by linarith), exact (le_of_hom (iDh i) : _) hy }, -- The rest of the proof is just computation apply const_ext, rw [← hb, finset.sum_mul, finset.mul_sum], apply finset.sum_congr rfl, intros j hj, rw [mul_assoc, ah_ha j i hj hi], ring end instance is_iso_to_basic_open (f : R) : is_iso (show CommRing.of _ ⟶ _, from to_basic_open R f) := begin haveI : is_iso ((forget CommRing).map (show CommRing.of _ ⟶ _, from to_basic_open R f)) := (is_iso_iff_bijective _).mpr ⟨to_basic_open_injective R f, to_basic_open_surjective R f⟩, exact is_iso_of_reflects_iso _ (forget CommRing), end /-- The ring isomorphism between the structure sheaf on `basic_open f` and the localization of `R` at the submonoid of powers of `f`. -/ def basic_open_iso (f : R) : (structure_sheaf R).presheaf.obj (op (basic_open f)) ≅ CommRing.of (localization.away f) := (as_iso (show CommRing.of _ ⟶ _, from to_basic_open R f)).symm @[elementwise] lemma to_global_factors : to_open R ⊤ = (CommRing.of_hom (algebra_map R (localization.away (1 : R)))) ≫ (to_basic_open R (1 : R)) ≫ (structure_sheaf R).presheaf.map (eq_to_hom (basic_open_one.symm)).op := begin change to_open R ⊤ = (to_basic_open R 1).comp _ ≫ _, unfold CommRing.of_hom, rw [localization_to_basic_open R, to_open_res], end instance is_iso_to_global : is_iso (to_open R ⊤) := begin let hom := CommRing.of_hom (algebra_map R (localization.away (1 : R))), haveI : is_iso hom := is_iso.of_iso ((is_localization.at_one R (localization.away (1 : R))).to_ring_equiv.to_CommRing_iso), rw to_global_factors R, apply_instance end /-- The ring isomorphism between the ring `R` and the global sections `Γ(X, 𝒪ₓ)`. -/ @[simps] def global_sections_iso : CommRing.of R ≅ (structure_sheaf R).presheaf.obj (op ⊤) := as_iso (to_open R ⊤) @[simp] lemma global_sections_iso_hom (R : CommRing) : (global_sections_iso R).hom = to_open R ⊤ := rfl section comap variables {R} {S : Type u} [comm_ring S] {P : Type u} [comm_ring P] /-- Given a ring homomorphism `f : R →+* S`, an open set `U` of the prime spectrum of `R` and an open set `V` of the prime spectrum of `S`, such that `V ⊆ (comap f) ⁻¹' U`, we can push a section `s` on `U` to a section on `V`, by composing with `localization.local_ring_hom _ _ f` from the left and `comap f` from the right. Explicitly, if `s` evaluates on `comap f p` to `a / b`, its image on `V` evaluates on `p` to `f(a) / f(b)`. At the moment, we work with arbitrary dependent functions `s : Π x : U, localizations R x`. Below, we prove the predicate `is_locally_fraction` is preserved by this map, hence it can be extended to a morphism between the structure sheaves of `R` and `S`. -/ def comap_fun (f : R →+* S) (U : opens (prime_spectrum.Top R)) (V : opens (prime_spectrum.Top S)) (hUV : V.1 ⊆ (prime_spectrum.comap f) ⁻¹' U.1) (s : Π x : U, localizations R x) (y : V) : localizations S y := localization.local_ring_hom (prime_spectrum.comap f y.1).as_ideal _ f rfl (s ⟨(prime_spectrum.comap f y.1), hUV y.2⟩ : _) lemma comap_fun_is_locally_fraction (f : R →+* S) (U : opens (prime_spectrum.Top R)) (V : opens (prime_spectrum.Top S)) (hUV : V.1 ⊆ (prime_spectrum.comap f) ⁻¹' U.1) (s : Π x : U, localizations R x) (hs : (is_locally_fraction R).to_prelocal_predicate.pred s) : (is_locally_fraction S).to_prelocal_predicate.pred (comap_fun f U V hUV s) := begin rintro ⟨p, hpV⟩, -- Since `s` is locally fraction, we can find a neighborhood `W` of `prime_spectrum.comap f p` -- in `U`, such that `s = a / b` on `W`, for some ring elements `a, b : R`. rcases hs ⟨prime_spectrum.comap f p, hUV hpV⟩ with ⟨W, m, iWU, a, b, h_frac⟩, -- We claim that we can write our new section as the fraction `f a / f b` on the neighborhood -- `(comap f) ⁻¹ W ⊓ V` of `p`. refine ⟨opens.comap (comap_continuous f) W ⊓ V, ⟨m, hpV⟩, opens.inf_le_right _ _, f a, f b, _⟩, rintro ⟨q, ⟨hqW, hqV⟩⟩, specialize h_frac ⟨prime_spectrum.comap f q, hqW⟩, refine ⟨h_frac.1, _⟩, dsimp only [comap_fun], erw [← localization.local_ring_hom_to_map ((prime_spectrum.comap f q).as_ideal), ← ring_hom.map_mul, h_frac.2, localization.local_ring_hom_to_map], refl, end /-- For a ring homomorphism `f : R →+* S` and open sets `U` and `V` of the prime spectra of `R` and `S` such that `V ⊆ (comap f) ⁻¹ U`, the induced ring homomorphism from the structure sheaf of `R` at `U` to the structure sheaf of `S` at `V`. Explicitly, this map is given as follows: For a point `p : V`, if the section `s` evaluates on `p` to the fraction `a / b`, its image on `V` evaluates on `p` to the fraction `f(a) / f(b)`. -/ def comap (f : R →+* S) (U : opens (prime_spectrum.Top R)) (V : opens (prime_spectrum.Top S)) (hUV : V.1 ⊆ (prime_spectrum.comap f) ⁻¹' U.1) : (structure_sheaf R).presheaf.obj (op U) →+* (structure_sheaf S).presheaf.obj (op V) := { to_fun := λ s, ⟨comap_fun f U V hUV s.1, comap_fun_is_locally_fraction f U V hUV s.1 s.2⟩, map_one' := subtype.ext $ funext $ λ p, by { rw [subtype.coe_mk, subtype.val_eq_coe, comap_fun, (sections_subring R (op U)).coe_one, pi.one_apply, ring_hom.map_one], refl }, map_zero' := subtype.ext $ funext $ λ p, by { rw [subtype.coe_mk, subtype.val_eq_coe, comap_fun, (sections_subring R (op U)).coe_zero, pi.zero_apply, ring_hom.map_zero], refl }, map_add' := λ s t, subtype.ext $ funext $ λ p, by { rw [subtype.coe_mk, subtype.val_eq_coe, comap_fun, (sections_subring R (op U)).coe_add, pi.add_apply, ring_hom.map_add], refl }, map_mul' := λ s t, subtype.ext $ funext $ λ p, by { rw [subtype.coe_mk, subtype.val_eq_coe, comap_fun, (sections_subring R (op U)).coe_mul, pi.mul_apply, ring_hom.map_mul], refl } } @[simp] lemma comap_apply (f : R →+* S) (U : opens (prime_spectrum.Top R)) (V : opens (prime_spectrum.Top S)) (hUV : V.1 ⊆ (prime_spectrum.comap f) ⁻¹' U.1) (s : (structure_sheaf R).presheaf.obj (op U)) (p : V) : (comap f U V hUV s).1 p = localization.local_ring_hom (prime_spectrum.comap f p.1).as_ideal _ f rfl (s.1 ⟨(prime_spectrum.comap f p.1), hUV p.2⟩ : _) := rfl lemma comap_const (f : R →+* S) (U : opens (prime_spectrum.Top R)) (V : opens (prime_spectrum.Top S)) (hUV : V.1 ⊆ (prime_spectrum.comap f) ⁻¹' U.1) (a b : R) (hb : ∀ x : prime_spectrum R, x ∈ U → b ∈ x.as_ideal.prime_compl) : comap f U V hUV (const R a b U hb) = const S (f a) (f b) V (λ p hpV, hb (prime_spectrum.comap f p) (hUV hpV)) := subtype.eq $ funext $ λ p, begin rw [comap_apply, const_apply, const_apply], erw localization.local_ring_hom_mk', refl, end /-- For an inclusion `i : V ⟶ U` between open sets of the prime spectrum of `R`, the comap of the identity from OO_X(U) to OO_X(V) equals as the restriction map of the structure sheaf. This is a generalization of the fact that, for fixed `U`, the comap of the identity from OO_X(U) to OO_X(U) is the identity. -/ lemma comap_id_eq_map (U V : opens (prime_spectrum.Top R)) (iVU : V ⟶ U) : comap (ring_hom.id R) U V (λ p hpV, le_of_hom iVU $ by rwa prime_spectrum.comap_id) = (structure_sheaf R).presheaf.map iVU.op := ring_hom.ext $ λ s, subtype.eq $ funext $ λ p, begin rw comap_apply, -- Unfortunately, we cannot use `localization.local_ring_hom_id` here, because -- `prime_spectrum.comap (ring_hom.id R) p` is not *definitionally* equal to `p`. Instead, we use -- that we can write `s` as a fraction `a/b` in a small neighborhood around `p`. Since -- `prime_spectrum.comap (ring_hom.id R) p` equals `p`, it is also contained in the same -- neighborhood, hence `s` equals `a/b` there too. obtain ⟨W, hpW, iWU, h⟩ := s.2 (iVU p), obtain ⟨a, b, h'⟩ := h.eq_mk', obtain ⟨hb₁, s_eq₁⟩ := h' ⟨p, hpW⟩, obtain ⟨hb₂, s_eq₂⟩ := h' ⟨prime_spectrum.comap (ring_hom.id _) p.1, by rwa prime_spectrum.comap_id⟩, dsimp only at s_eq₁ s_eq₂, erw [s_eq₂, localization.local_ring_hom_mk', ← s_eq₁, ← res_apply], end /-- The comap of the identity is the identity. In this variant of the lemma, two open subsets `U` and `V` are given as arguments, together with a proof that `U = V`. This is be useful when `U` and `V` are not definitionally equal. -/ lemma comap_id (U V : opens (prime_spectrum.Top R)) (hUV : U = V) : comap (ring_hom.id R) U V (λ p hpV, by rwa [hUV, prime_spectrum.comap_id]) = eq_to_hom (show (structure_sheaf R).presheaf.obj (op U) = _, by rw hUV) := by erw [comap_id_eq_map U V (eq_to_hom hUV.symm), eq_to_hom_op, eq_to_hom_map] @[simp] lemma comap_id' (U : opens (prime_spectrum.Top R)) : comap (ring_hom.id R) U U (λ p hpU, by rwa prime_spectrum.comap_id) = ring_hom.id _ := by { rw comap_id U U rfl, refl } lemma comap_comp (f : R →+* S) (g : S →+* P) (U : opens (prime_spectrum.Top R)) (V : opens (prime_spectrum.Top S)) (W : opens (prime_spectrum.Top P)) (hUV : ∀ p ∈ V, prime_spectrum.comap f p ∈ U) (hVW : ∀ p ∈ W, prime_spectrum.comap g p ∈ V) : comap (g.comp f) U W (λ p hpW, hUV (prime_spectrum.comap g p) (hVW p hpW)) = (comap g V W hVW).comp (comap f U V hUV) := ring_hom.ext $ λ s, subtype.eq $ funext $ λ p, begin rw comap_apply, erw localization.local_ring_hom_comp _ (prime_spectrum.comap g p.1).as_ideal, -- refl works here, because `prime_spectrum.comap (g.comp f) p` is defeq to -- `prime_spectrum.comap f (prime_spectrum.comap g p)` refl, end @[elementwise, reassoc] lemma to_open_comp_comap (f : R →+* S) : to_open R ⊤ ≫ comap f ⊤ ⊤ (λ p hpV, trivial) = @category_theory.category_struct.comp _ _ (CommRing.of R) (CommRing.of S) _ f (to_open S ⊤) := ring_hom.ext $ λ s, subtype.eq $ funext $ λ p, begin simp_rw [comp_apply, comap_apply, subtype.val_eq_coe], erw localization.local_ring_hom_to_map, refl, end end comap end structure_sheaf end algebraic_geometry
7afb4e76d1a108e1e96b8d208085186c0e586c60
c3f2fcd060adfa2ca29f924839d2d925e8f2c685
/tests/lean/run/simple.lean
e2ae78513fec5deb3f7a1034cf914ac2694180e1
[ "Apache-2.0" ]
permissive
respu/lean
6582d19a2f2838a28ecd2b3c6f81c32d07b5341d
8c76419c60b63d0d9f7bc04ebb0b99812d0ec654
refs/heads/master
1,610,882,451,231
1,427,747,084,000
1,427,747,429,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
571
lean
prelude definition Prop : Type.{1} := Type.{0} context parameter A : Type definition eq (a b : A) : Prop := ∀P : A → Prop, P a → P b theorem subst (P : A → Prop) (a b : A) (H1 : eq a b) (H2 : P a) : P b := H1 P H2 theorem refl (a : A) : eq a a := λ (P : A → Prop) (H : P a), H theorem symm (a b : A) (H : eq a b) : eq b a := subst (λ x : A, eq x a) a b H (refl a) theorem trans (a b c : A) (H1 : eq a b) (H2 : eq b c) : eq a c := subst (λ x : A, eq a x) b c H2 H1 end check subst.{1} check refl.{1} check symm.{1} check trans.{1}
395c069f529300c582165081f80251ae69a98540
78269ad0b3c342b20786f60690708b6e328132b0
/src/library_dev/algebra/ring.lean
d16b057d380f0efa953a3f8104247552c03e2ad6
[]
no_license
dselsam/library_dev
e74f46010fee9c7b66eaa704654cad0fcd2eefca
1b4e34e7fb067ea5211714d6d3ecef5132fc8218
refs/heads/master
1,610,372,841,675
1,497,014,421,000
1,497,014,421,000
86,526,137
0
0
null
1,490,752,133,000
1,490,752,132,000
null
UTF-8
Lean
false
false
10,662
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, Floris van Doorn -/ open eq universe variable uu variable {A : Type uu} /- comm semiring -/ section comm_semiring variables [comm_semiring A] (a b c : A) @[instance] def comm_semiring_has_dvd : has_dvd A := has_dvd.mk (λ a b, ∃ c, b = a * c) -- TODO: this used to not have c explicit, but that seems to be important -- for use with tactics, similar to exist.intro theorem dvd.intro {a b : A} (c : A) (h : a * c = b) : a ∣ b := exists.intro c h^.symm def dvd_of_mul_right_eq := @dvd.intro theorem dvd.intro_left {a b : A} (c : A) (h : c * a = b) : a ∣ b := dvd.intro _ (begin rewrite mul_comm at h, apply h end) def dvd_of_mul_left_eq := @dvd.intro_left theorem exists_eq_mul_right_of_dvd {a b : A} (h : a ∣ b) : ∃ c, b = a * c := h theorem dvd.elim {P : Prop} {a b : A} (H₁ : a ∣ b) (H₂ : ∀ c, b = a * c → P) : P := exists.elim H₁ H₂ theorem exists_eq_mul_left_of_dvd {a b : A} (h : a ∣ b) : ∃ c, b = c * a := dvd.elim h (take c, assume H1 : b = a * c, exists.intro c (eq.trans H1 (mul_comm a c))) theorem dvd.elim_left {P : Prop} {a b : A} (h₁ : a ∣ b) (h₂ : ∀ c, b = c * a → P) : P := exists.elim (exists_eq_mul_left_of_dvd h₁) (take c, assume h₃ : b = c * a, h₂ c h₃) @[simp] theorem dvd_refl : a ∣ a := dvd.intro 1 (by simp) theorem dvd_trans {a b c : A} (h₁ : a ∣ b) (h₂ : b ∣ c) : a ∣ c := match h₁, h₂ with | ⟨d, (h₃ : b = a * d)⟩, ⟨e, (h₄ : c = b * e)⟩ := ⟨d * e, show c = a * (d * e), by simp [h₃, h₄]⟩ end def dvd.trans := @dvd_trans theorem eq_zero_of_zero_dvd {a : A} (h : 0 ∣ a) : a = 0 := dvd.elim h (take c, assume H' : a = 0 * c, eq.trans H' (zero_mul c)) @[simp] theorem dvd_zero : a ∣ 0 := dvd.intro 0 (by simp) @[simp] theorem one_dvd : 1 ∣ a := dvd.intro a (by simp) @[simp] theorem dvd_mul_right : a ∣ a * b := dvd.intro b rfl @[simp] theorem dvd_mul_left : a ∣ b * a := dvd.intro b (by simp) theorem dvd_mul_of_dvd_left {a b : A} (h : a ∣ b) (c : A) : a ∣ b * c := dvd.elim h (λ d h', begin rw [h', mul_assoc], apply dvd_mul_right end) theorem dvd_mul_of_dvd_right {a b : A} (h : a ∣ b) (c : A) : a ∣ c * b := begin rw mul_comm, exact dvd_mul_of_dvd_left h _ end theorem mul_dvd_mul {a b c d : A} (dvd_ab : a ∣ b) (dvd_cd : c ∣ d) : a * c ∣ b * d := dvd.elim dvd_ab (take e, assume beq, dvd.elim dvd_cd (take f, assume deq, dvd.intro (e * f) (by simp [beq, deq]))) theorem mul_dvd_mul_left (a : A) {b c : A} (h : b ∣ c) : a * b ∣ a * c := mul_dvd_mul (dvd_refl a) h theorem mul_dvd_mul_right {a b : A} (h : a ∣ b) (c : A) : a * c ∣ b * c := mul_dvd_mul h (dvd_refl c) theorem dvd_add {a b c : A} (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b + c := dvd.elim h₁ (λ d hd, dvd.elim h₂ (λ e he, dvd.intro (d + e) (by simp [left_distrib, hd, he]))) /- -- TODO: this should work, but doesn't. -- The function definition system says we don't have well-founded recursion theorem mul_dvd_mul' {a b c d : A} (dvd_ab : a ∣ b) (dvd_cd : c ∣ d) : a * c ∣ b * d := match dvd_ab, dvd_cd with | ⟨e, (he : b = a * e)⟩, ⟨f, (hf : d = c * f)⟩ := begin subst he, subst hf, apply (@dvd.intro A _ _ _ (e * f)), simp end end -/ theorem dvd_of_mul_right_dvd {a b c : A} (h : a * b ∣ c) : a ∣ c := dvd.elim h (begin intros d h₁, rw [h₁, mul_assoc], apply dvd_mul_right end) theorem dvd_of_mul_left_dvd {a b c : A} (h : a * b ∣ c) : b ∣ c := dvd.elim h (λ d ceq, dvd.intro (a * d) (by simp [ceq])) end comm_semiring /- ring -/ section variables [ring A] (a b c d e : A) theorem mul_add_eq_mul_add_iff_sub_mul_add_eq : a * e + c = b * e + d ↔ (a - b) * e + c = d := calc a * e + c = b * e + d ↔ a * e + c = d + b * e : by simp ... ↔ a * e + c - b * e = d : iff.intro (λ h, begin simp [h] end) (λ h, begin simp [h^.symm] end) ... ↔ (a - b) * e + c = d : begin simp [@sub_eq_add_neg A, @right_distrib A] end theorem sub_mul_add_eq_of_mul_add_eq_mul_add : a * e + c = b * e + d → (a - b) * e + c = d := assume h, calc (a - b) * e + c = (a * e + c) - b * e : begin simp [@sub_eq_add_neg A, @right_distrib A] end ... = d : begin rewrite h, simp [@add_sub_cancel A] end theorem mul_neg_one_eq_neg : a * (-1) = -a := have a + a * -1 = 0, from calc a + a * -1 = a * 1 + a * -1 : by simp ... = a * (1 + -1) : eq.symm (left_distrib a 1 (-1)) ... = 0 : by simp, symm (neg_eq_of_add_eq_zero this) theorem ne_zero_and_ne_zero_of_mul_ne_zero {a b : A} (h : a * b ≠ 0) : a ≠ 0 ∧ b ≠ 0 := begin split, intro ha, apply h, simp [ha], intro hb, apply h, simp [hb] end end section variables [comm_ring A] {a b c d e : A} local attribute [simp] left_distrib right_distrib theorem dvd_neg_of_dvd (h : a ∣ b) : (a ∣ -b) := dvd.elim h (take c, suppose b = a * c, dvd.intro (-c) (by simp [this])) theorem dvd_of_dvd_neg (h : a ∣ -b) : (a ∣ b) := let t := dvd_neg_of_dvd h in by rwa neg_neg at t theorem dvd_neg_iff_dvd : (a ∣ -b) ↔ (a ∣ b) := ⟨dvd_of_dvd_neg, dvd_neg_of_dvd⟩ theorem neg_dvd_of_dvd (h : a ∣ b) : -a ∣ b := dvd.elim h (take c, suppose b = a * c, dvd.intro (-c) (by simp [this])) theorem dvd_of_neg_dvd (h : -a ∣ b) : a ∣ b := let t := neg_dvd_of_dvd h in by rwa neg_neg at t theorem neg_dvd_iff_dvd : (-a ∣ b) ↔ (a ∣ b) := ⟨dvd_of_neg_dvd, neg_dvd_of_dvd⟩ theorem dvd_sub (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b - c := dvd_add h₁ (dvd_neg_of_dvd h₂) theorem dvd_add_iff_left {a b c : A} (h : a ∣ c) : a ∣ b ↔ a ∣ b + c := ⟨λh₂, dvd_add h₂ h, λH, by note t := dvd_sub H h; rwa add_sub_cancel at t⟩ theorem dvd_add_iff_right {a b c : A} (h : a ∣ b) : a ∣ c ↔ a ∣ b + c := by rw add_comm; exact dvd_add_iff_left h end /- integral domains -/ section variables [s : integral_domain A] (a b c d e : A) include s theorem eq_of_mul_eq_mul_right_of_ne_zero {a b c : A} (ha : a ≠ 0) (h : b * a = c * a) : b = c := have b * a - c * a = 0, by simp [h], have (b - c) * a = 0, by rewrite [mul_sub_right_distrib, this], have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this)^.resolve_right ha, eq_of_sub_eq_zero this theorem eq_of_mul_eq_mul_left_of_ne_zero {a b c : A} (ha : a ≠ 0) (h : a * b = a * c) : b = c := have a * b - a * c = 0, by simp [h], have a * (b - c) = 0, by rewrite [mul_sub_left_distrib, this], have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this)^.resolve_left ha, eq_of_sub_eq_zero this -- TODO: do we want the iff versions? -- theorem dvd_of_mul_dvd_mul_left {a b c : A} (Ha : a ≠ 0) (Hdvd : (a * b ∣ a * c)) : (b ∣ c) := -- sorry /- dvd.elim Hdvd (take d, suppose a * c = a * b * d, have b * d = c, from eq_of_mul_eq_mul_left Ha begin rewrite -mul.assoc, symmetry, exact this end, dvd.intro this) -/ -- theorem dvd_of_mul_dvd_mul_right {a b c : A} (Ha : a ≠ 0) (Hdvd : (b * a ∣ c * a)) : (b ∣ c) := -- sorry /- dvd.elim Hdvd (take d, suppose c * a = b * a * d, have b * d * a = c * a, from by rewrite [mul.right_comm, -this], have b * d = c, from eq_of_mul_eq_mul_right Ha this, dvd.intro this) -/ end /- namespace norm_num local attribute bit0 bit1 add1 [reducible] local attribute right_distrib left_distrib [simp] theorem mul_zero [mul_zero_class A] (a : A) : a * zero = zero := sorry -- by simp theorem zero_mul [mul_zero_class A] (a : A) : zero * a = zero := sorry -- by simp theorem mul_one [monoid A] (a : A) : a * one = a := sorry -- by simp theorem mul_bit0 [distrib A] (a b : A) : a * (bit0 b) = bit0 (a * b) := sorry -- by simp theorem mul_bit0_helper [distrib A] (a b t : A) (h : a * b = t) : a * (bit0 b) = bit0 t := sorry -- by rewrite -H; simp theorem mul_bit1 [semiring A] (a b : A) : a * (bit1 b) = bit0 (a * b) + a := sorry -- by simp theorem mul_bit1_helper [semiring A] (a b s t : A) (Hs : a * b = s) (Ht : bit0 s + a = t) : a * (bit1 b) = t := sorry -- by simp theorem subst_into_prod [has_mul A] (l r tl tr t : A) (prl : l = tl) (prr : r = tr) (prt : tl * tr = t) : l * r = t := sorry -- by simp theorem mk_cong (op : A → A) (a b : A) (h : a = b) : op a = op b := sorry -- by simp theorem neg_add_neg_eq_of_add_add_eq_zero [add_comm_group A] (a b c : A) (h : c + a + b = 0) : -a + -b = c := sorry /- begin apply add_neg_eq_of_eq_add, apply neg_eq_of_add_eq_zero, simp end -/ theorem neg_add_neg_helper [add_comm_group A] (a b c : A) (h : a + b = c) : -a + -b = -c := sorry -- begin apply iff.mp !neg_eq_neg_iff_eq, simp end theorem neg_add_pos_eq_of_eq_add [add_comm_group A] (a b c : A) (h : b = c + a) : -a + b = c := sorry -- begin apply neg_add_eq_of_eq_add, simp end theorem neg_add_pos_helper1 [add_comm_group A] (a b c : A) (h : b + c = a) : -a + b = -c := sorry -- begin apply neg_add_eq_of_eq_add, apply eq_add_neg_of_add_eq H end theorem neg_add_pos_helper2 [add_comm_group A] (a b c : A) (h : a + c = b) : -a + b = c := sorry -- begin apply neg_add_eq_of_eq_add, rewrite H end theorem pos_add_neg_helper [add_comm_group A] (a b c : A) (h : b + a = c) : a + b = c := sorry -- by simp theorem sub_eq_add_neg_helper [add_comm_group A] (t₁ t₂ e w₁ w₂: A) (H₁ : t₁ = w₁) (H₂ : t₂ = w₂) (h : w₁ + -w₂ = e) : t₁ - t₂ = e := sorry -- by simp theorem pos_add_pos_helper [add_comm_group A] (a b c h₁ h₂ : A) (H₁ : a = h₁) (H₂ : b = h₂) (h : h₁ + h₂ = c) : a + b = c := sorry -- by simp theorem subst_into_subtr [add_group A] (l r t : A) (prt : l + -r = t) : l - r = t := sorry -- by simp theorem neg_neg_helper [add_group A] (a b : A) (h : a = -b) : -a = b := sorry -- by simp theorem neg_mul_neg_helper [ring A] (a b c : A) (h : a * b = c) : (-a) * (-b) = c := sorry -- by simp theorem neg_mul_pos_helper [ring A] (a b c : A) (h : a * b = c) : (-a) * b = -c := sorry -- by simp theorem pos_mul_neg_helper [ring A] (a b c : A) (h : a * b = c) : a * (-b) = -c := sorry -- by simp end norm_num attribute [simp] zero_mul mul_zero attribute [simp] neg_mul_eq_neg_mul_symm mul_neg_eq_neg_mul_symm attribute [simp] left_distrib right_distrib -/
6105699f07c8b9b5ef95a69511cfa61a7c64e9a3
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/geometry/manifold/smooth_manifold_with_corners.lean
0cf4354e8dd82e643fc7657c0067908f5811fc1b
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
35,026
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.calculus.times_cont_diff import geometry.manifold.charted_space /-! # Smooth manifolds (possibly with boundary or corners) A smooth manifold is a manifold modelled on a normed vector space, or a subset like a half-space (to get manifolds with boundaries) for which the changes of coordinates are smooth maps. We define a model with corners as a map `I : H → E` embedding nicely the topological space `H` in the vector space `E` (or more precisely as a structure containing all the relevant properties). Given such a model with corners `I` on `(E, H)`, we define the groupoid of local homeomorphisms of `H` which are smooth when read in `E` (for any regularity `n : with_top ℕ`). With this groupoid at hand and the general machinery of charted spaces, we thus get the notion of `C^n` manifold with respect to any model with corners `I` on `(E, H)`. We also introduce a specific type class for `C^∞` manifolds as these are the most commonly used. ## Main definitions * `model_with_corners 𝕜 E H` : a structure containing informations on the way a space `H` embeds in a model vector space E over the field `𝕜`. This is all that is needed to define a smooth manifold with model space `H`, and model vector space `E`. * `model_with_corners_self 𝕜 E` : trivial model with corners structure on the space `E` embedded in itself by the identity. * `times_cont_diff_groupoid n I` : when `I` is a model with corners on `(𝕜, E, H)`, this is the groupoid of local homeos of `H` which are of class `C^n` over the normed field `𝕜`, when read in `E`. * `smooth_manifold_with_corners I M` : a type class saying that the charted space `M`, modelled on the space `H`, has `C^∞` changes of coordinates with respect to the model with corners `I` on `(𝕜, E, H)`. This type class is just a shortcut for `has_groupoid M (times_cont_diff_groupoid ∞ I)`. * `ext_chart_at I x`: in a smooth manifold with corners with the model `I` on `(E, H)`, the charts take values in `H`, but often we may want to use their `E`-valued version, obtained by composing the charts with `I`. Since the target is in general not open, we can not register them as local homeomorphisms, but we register them as local equivs. `ext_chart_at I x` is the canonical such local equiv around `x`. As specific examples of models with corners, we define (in the file `real_instances.lean`) * `model_with_corners_self ℝ (euclidean_space (fin n))` for the model space used to define `n`-dimensional real manifolds without boundary (with notation `𝓡 n` in the locale `manifold`) * `model_with_corners ℝ (euclidean_space (fin n)) (euclidean_half_space n)` for the model space used to define `n`-dimensional real manifolds with boundary (with notation `𝓡∂ n` in the locale `manifold`) * `model_with_corners ℝ (euclidean_space (fin n)) (euclidean_quadrant n)` for the model space used to define `n`-dimensional real manifolds with corners With these definitions at hand, to invoke an `n`-dimensional real manifold without boundary, one could use `variables {n : ℕ} {M : Type*} [topological_space M] [charted_space (euclidean_space (fin n)) M] [smooth_manifold_with_corners (𝓡 n) M]`. However, this is not the recommended way: a theorem proved using this assumption would not apply for instance to the tangent space of such a manifold, which is modelled on `(euclidean_space (fin n)) × (euclidean_space (fin n))` and not on `euclidean_space (fin (2 * n))`! In the same way, it would not apply to product manifolds, modelled on `(euclidean_space (fin n)) × (euclidean_space (fin m))`. The right invocation does not focus on one specific construction, but on all constructions sharing the right properties, like `variables {E : Type*} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {I : model_with_corners ℝ E E} [I.boundaryless] {M : Type*} [topological_space M] [charted_space E M] [smooth_manifold_with_corners I M]` Here, `I.boundaryless` is a typeclass property ensuring that there is no boundary (this is for instance the case for `model_with_corners_self`, or products of these). Note that one could consider as a natural assumption to only use the trivial model with corners `model_with_corners_self ℝ E`, but again in product manifolds the natural model with corners will not be this one but the product one (and they are not defeq as `(λp : E × F, (p.1, p.2))` is not defeq to the identity). So, it is important to use the above incantation to maximize the applicability of theorems. ## Implementation notes We want to talk about manifolds modelled on a vector space, but also on manifolds with boundary, modelled on a half space (or even manifolds with corners). For the latter examples, we still want to define smooth functions, tangent bundles, and so on. As smooth functions are well defined on vector spaces or subsets of these, one could take for model space a subtype of a vector space. With the drawback that the whole vector space itself (which is the most basic example) is not directly a subtype of itself: the inclusion of `univ : set E` in `set E` would show up in the definition, instead of `id`. A good abstraction covering both cases it to have a vector space `E` (with basic example the Euclidean space), a model space `H` (with basic example the upper half space), and an embedding of `H` into `E` (which can be the identity for `H = E`, or `subtype.val` for manifolds with corners). We say that the pair `(E, H)` with their embedding is a model with corners, and we encompass all the relevant properties (in particular the fact that the image of `H` in `E` should have unique differentials) in the definition of `model_with_corners`. We concentrate on `C^∞` manifolds: all the definitions work equally well for `C^n` manifolds, but later on it is a pain to carry all over the smoothness parameter, especially when one wants to deal with `C^k` functions as there would be additional conditions `k ≤ n` everywhere. Since one deals almost all the time with `C^∞` (or analytic) manifolds, this seems to be a reasonable choice that one could revisit later if needed. `C^k` manifolds are still available, but they should be called using `has_groupoid M (times_cont_diff_groupoid k I)` where `I` is the model with corners. I have considered using the model with corners `I` as a typeclass argument, possibly `out_param`, to get lighter notations later on, but it did not turn out right, as on `E × F` there are two natural model with corners, the trivial (identity) one, and the product one, and they are not defeq and one needs to indicate to Lean which one we want to use. This means that when talking on objects on manifolds one will most often need to specify the model with corners one is using. For instance, the tangent bundle will be `tangent_bundle I M` and the derivative will be `mfderiv I I' f`, instead of the more natural notations `tangent_bundle 𝕜 M` and `mfderiv 𝕜 f` (the field has to be explicit anyway, as some manifolds could be considered both as real and complex manifolds). -/ noncomputable theory universes u v w u' v' w' open set filter open_locale manifold filter topological_space localized "notation `∞` := (⊤ : with_top ℕ)" in manifold section model_with_corners /-! ### Models with corners. -/ /-- A structure containing informations on the way a space `H` embeds in a model vector space `E` over the field `𝕜`. This is all what is needed to define a smooth manifold with model space `H`, and model vector space `E`. -/ @[nolint has_inhabited_instance] structure model_with_corners (𝕜 : Type*) [nondiscrete_normed_field 𝕜] (E : Type*) [normed_group E] [normed_space 𝕜 E] (H : Type*) [topological_space H] extends local_equiv H E := (source_eq : source = univ) (unique_diff' : unique_diff_on 𝕜 (range to_fun)) (continuous_to_fun : continuous to_fun . tactic.interactive.continuity') (continuous_inv_fun : continuous inv_fun . tactic.interactive.continuity') attribute [simp, mfld_simps] model_with_corners.source_eq /-- A vector space is a model with corners. -/ def model_with_corners_self (𝕜 : Type*) [nondiscrete_normed_field 𝕜] (E : Type*) [normed_group E] [normed_space 𝕜 E] : model_with_corners 𝕜 E E := { to_fun := id, inv_fun := id, source := univ, target := univ, source_eq := rfl, map_source' := λ_ _, mem_univ _, map_target' := λ_ _, mem_univ _, left_inv' := λ_ _, rfl, right_inv' := λ_ _, rfl, unique_diff' := by { rw range_id, exact unique_diff_on_univ }, continuous_to_fun := continuous_id, continuous_inv_fun := continuous_id } localized "notation `𝓘(` 𝕜 `, ` E `)` := model_with_corners_self 𝕜 E" in manifold localized "notation `𝓘(` 𝕜 `)` := model_with_corners_self 𝕜 𝕜" in manifold section variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) instance : has_coe_to_fun (model_with_corners 𝕜 E H) := ⟨_, λ e, e.to_fun⟩ /-- The inverse to a model with corners, only registered as a local equiv. -/ protected def model_with_corners.symm : local_equiv E H := I.to_local_equiv.symm /- Register a few lemmas to make sure that `simp` puts expressions in normal form -/ @[simp, mfld_simps] lemma model_with_corners.to_local_equiv_coe : (I.to_local_equiv : H → E) = I := rfl @[simp, mfld_simps] lemma model_with_corners.mk_coe (e : local_equiv H E) (a b c d) : ((model_with_corners.mk e a b c d : model_with_corners 𝕜 E H) : H → E) = (e : H → E) := rfl @[simp, mfld_simps] lemma model_with_corners.to_local_equiv_coe_symm : (I.to_local_equiv.symm : E → H) = I.symm := rfl @[simp, mfld_simps] lemma model_with_corners.mk_coe_symm (e : local_equiv H E) (a b c d) : ((model_with_corners.mk e a b c d : model_with_corners 𝕜 E H).symm : E → H) = (e.symm : E → H) := rfl lemma model_with_corners.unique_diff : unique_diff_on 𝕜 (range I) := I.unique_diff' protected lemma model_with_corners.continuous : continuous I := I.continuous_to_fun lemma model_with_corners.continuous_symm : continuous I.symm := I.continuous_inv_fun section variables (𝕜 E) /-- In the trivial model with corners, the associated local equiv is the identity. -/ @[simp, mfld_simps] lemma model_with_corners_self_local_equiv : (model_with_corners_self 𝕜 E).to_local_equiv = local_equiv.refl E := rfl @[simp, mfld_simps] lemma model_with_corners_self_coe : (model_with_corners_self 𝕜 E : E → E) = id := rfl @[simp, mfld_simps] lemma model_with_corners_self_coe_symm : ((model_with_corners_self 𝕜 E).symm : E → E) = id := rfl end @[simp, mfld_simps] lemma model_with_corners.target_eq : I.target = range (I : H → E) := by { rw [← image_univ, ← I.source_eq], exact (I.to_local_equiv.image_source_eq_target).symm } @[simp, mfld_simps] lemma model_with_corners.left_inv (x : H) : I.symm (I x) = x := by { refine I.left_inv' _, simp } protected lemma model_with_corners.left_inverse : function.left_inverse I.symm I := I.left_inv @[simp, mfld_simps] lemma model_with_corners.symm_comp_self : I.symm ∘ I = id := I.left_inverse.comp_eq_id protected lemma model_with_corners.right_inv_on : right_inv_on I.symm I (range I) := I.left_inverse.right_inv_on_range @[simp, mfld_simps] lemma model_with_corners.right_inv {x : E} (hx : x ∈ range I) : I (I.symm x) = x := I.right_inv_on hx lemma model_with_corners.image (s : set H) : I '' s = I.symm ⁻¹' s ∩ range I := begin refine (I.to_local_equiv.image_eq_target_inter_inv_preimage _).trans _, { rw I.source_eq, exact subset_univ _ }, { rw [inter_comm, I.target_eq, I.to_local_equiv_coe_symm] } end protected lemma model_with_corners.closed_embedding : closed_embedding I := I.left_inverse.closed_embedding I.continuous_symm I.continuous lemma model_with_corners.closed_range : is_closed (range I) := I.closed_embedding.closed_range lemma model_with_corners.map_nhds_eq (x : H) : map I (𝓝 x) = 𝓝[range I] (I x) := I.closed_embedding.to_embedding.map_nhds_eq x lemma model_with_corners.image_mem_nhds_within {x : H} {s : set H} (hs : s ∈ 𝓝 x) : I '' s ∈ 𝓝[range I] (I x) := I.map_nhds_eq x ▸ image_mem_map hs lemma model_with_corners.symm_map_nhds_within_range (x : H) : map I.symm (𝓝[range I] (I x)) = 𝓝 x := by rw [← I.map_nhds_eq, map_map, I.symm_comp_self, map_id] lemma model_with_corners.unique_diff_preimage {s : set H} (hs : is_open s) : unique_diff_on 𝕜 (I.symm ⁻¹' s ∩ range I) := by { rw inter_comm, exact I.unique_diff.inter (hs.preimage I.continuous_inv_fun) } lemma model_with_corners.unique_diff_preimage_source {β : Type*} [topological_space β] {e : local_homeomorph H β} : unique_diff_on 𝕜 (I.symm ⁻¹' (e.source) ∩ range I) := I.unique_diff_preimage e.open_source lemma model_with_corners.unique_diff_at_image {x : H} : unique_diff_within_at 𝕜 (range I) (I x) := I.unique_diff _ (mem_range_self _) lemma model_with_corners.locally_compact [locally_compact_space E] (I : model_with_corners 𝕜 E H) : locally_compact_space H := begin have : ∀ (x : H), (𝓝 x).has_basis (λ s, s ∈ 𝓝 (I x) ∧ is_compact s) (λ s, I.symm '' (s ∩ range ⇑I)), { intro x, rw ← I.symm_map_nhds_within_range, exact ((compact_basis_nhds (I x)).inf_principal _).map _ }, refine locally_compact_space_of_has_basis this _, rintro x s ⟨-, hsc⟩, exact (hsc.inter_right I.closed_range).image I.continuous_symm end end section model_with_corners_prod /-- Given two model_with_corners `I` on `(E, H)` and `I'` on `(E', H')`, we define the model with corners `I.prod I'` on `(E × E', H × H')`. This appears in particular for the manifold structure on the tangent bundle to a manifold modelled on `(E, H)`: it will be modelled on `(E × E, H × E)`. -/ def model_with_corners.prod {𝕜 : Type u} [nondiscrete_normed_field 𝕜] {E : Type v} [normed_group E] [normed_space 𝕜 E] {H : Type w} [topological_space H] (I : model_with_corners 𝕜 E H) {E' : Type v'} [normed_group E'] [normed_space 𝕜 E'] {H' : Type w'} [topological_space H'] (I' : model_with_corners 𝕜 E' H') : model_with_corners 𝕜 (E × E') (model_prod H H') := { to_fun := λ p, (I p.1, I' p.2), inv_fun := λ p, (I.symm p.1, I'.symm p.2), source := (univ : set (H × H')), target := set.prod (range I) (range I'), map_source' := λ ⟨x, x'⟩ _, by simp [-mem_range, mem_range_self], map_target' := λ ⟨x, x'⟩ _, mem_univ _, left_inv' := λ ⟨x, x'⟩ _, by simp, right_inv' := λ ⟨x, x'⟩ ⟨hx, hx'⟩, by simp [hx, hx'], source_eq := rfl, unique_diff' := begin have : range (λ(p : model_prod H H'), (I p.1, I' p.2)) = set.prod (range I) (range I'), by { dsimp [model_prod], rw ← prod_range_range_eq }, rw this, exact unique_diff_on.prod I.unique_diff I'.unique_diff, end, continuous_to_fun := (continuous.comp I.continuous_to_fun continuous_fst).prod_mk (continuous.comp I'.continuous_to_fun continuous_snd), continuous_inv_fun := (continuous.comp I.continuous_inv_fun continuous_fst).prod_mk (continuous.comp I'.continuous_inv_fun continuous_snd) } /-- Special case of product model with corners, which is trivial on the second factor. This shows up as the model to tangent bundles. -/ @[reducible] def model_with_corners.tangent {𝕜 : Type u} [nondiscrete_normed_field 𝕜] {E : Type v} [normed_group E] [normed_space 𝕜 E] {H : Type w} [topological_space H] (I : model_with_corners 𝕜 E H) : model_with_corners 𝕜 (E × E) (model_prod H E) := I.prod (model_with_corners_self 𝕜 E) variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {F : Type*} [normed_group F] [normed_space 𝕜 F] {F' : Type*} [normed_group F'] [normed_space 𝕜 F'] {H : Type*} [topological_space H] {H' : Type*} [topological_space H'] {G : Type*} [topological_space G] {G' : Type*} [topological_space G'] {I : model_with_corners 𝕜 E H} {J : model_with_corners 𝕜 F G} @[simp, mfld_simps] lemma model_with_corners_prod_to_local_equiv : (I.prod J).to_local_equiv = (I.to_local_equiv).prod (J.to_local_equiv) := begin ext1 x, { refl, }, { intro x, refl, }, { simp only [set.univ_prod_univ, model_with_corners.source_eq, local_equiv.prod_source], } end @[simp, mfld_simps] lemma model_with_corners_prod_coe (I : model_with_corners 𝕜 E H) (I' : model_with_corners 𝕜 E' H') : (I.prod I' : _ × _ → _ × _) = prod.map I I' := rfl @[simp, mfld_simps] lemma model_with_corners_prod_coe_symm (I : model_with_corners 𝕜 E H) (I' : model_with_corners 𝕜 E' H') : ((I.prod I').symm : _ × _ → _ × _) = prod.map I.symm I'.symm := rfl end model_with_corners_prod section boundaryless /-- Property ensuring that the model with corners `I` defines manifolds without boundary. -/ class model_with_corners.boundaryless {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) : Prop := (range_eq_univ : range I = univ) /-- The trivial model with corners has no boundary -/ instance model_with_corners_self_boundaryless (𝕜 : Type*) [nondiscrete_normed_field 𝕜] (E : Type*) [normed_group E] [normed_space 𝕜 E] : (model_with_corners_self 𝕜 E).boundaryless := ⟨by simp⟩ /-- If two model with corners are boundaryless, their product also is -/ instance model_with_corners.range_eq_univ_prod {𝕜 : Type u} [nondiscrete_normed_field 𝕜] {E : Type v} [normed_group E] [normed_space 𝕜 E] {H : Type w} [topological_space H] (I : model_with_corners 𝕜 E H) [I.boundaryless] {E' : Type v'} [normed_group E'] [normed_space 𝕜 E'] {H' : Type w'} [topological_space H'] (I' : model_with_corners 𝕜 E' H') [I'.boundaryless] : (I.prod I').boundaryless := begin split, dsimp [model_with_corners.prod, model_prod], rw [← prod_range_range_eq, model_with_corners.boundaryless.range_eq_univ, model_with_corners.boundaryless.range_eq_univ, univ_prod_univ] end end boundaryless section times_cont_diff_groupoid /-! ### Smooth functions on models with corners -/ variables {m n : with_top ℕ} {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) {M : Type*} [topological_space M] variable (n) /-- Given a model with corners `(E, H)`, we define the groupoid of `C^n` transformations of `H` as the maps that are `C^n` when read in `E` through `I`. -/ def times_cont_diff_groupoid : structure_groupoid H := pregroupoid.groupoid { property := λf s, times_cont_diff_on 𝕜 n (I ∘ f ∘ I.symm) (I.symm ⁻¹' s ∩ range I), comp := λf g u v hf hg hu hv huv, begin have : I ∘ (g ∘ f) ∘ I.symm = (I ∘ g ∘ I.symm) ∘ (I ∘ f ∘ I.symm), by { ext x, simp }, rw this, apply times_cont_diff_on.comp hg _, { rintros x ⟨hx1, hx2⟩, simp only with mfld_simps at ⊢ hx1, exact hx1.2 }, { refine hf.mono _, rintros x ⟨hx1, hx2⟩, exact ⟨hx1.1, hx2⟩ } end, id_mem := begin apply times_cont_diff_on.congr (times_cont_diff_id.times_cont_diff_on), rintros x ⟨hx1, hx2⟩, rcases mem_range.1 hx2 with ⟨y, hy⟩, rw ← hy, simp only with mfld_simps, end, locality := λf u hu H, begin apply times_cont_diff_on_of_locally_times_cont_diff_on, rintros y ⟨hy1, hy2⟩, rcases mem_range.1 hy2 with ⟨x, hx⟩, rw ← hx at ⊢ hy1, simp only with mfld_simps at ⊢ hy1, rcases H x hy1 with ⟨v, v_open, xv, hv⟩, have : ((I.symm ⁻¹' (u ∩ v)) ∩ (range I)) = ((I.symm ⁻¹' u) ∩ (range I) ∩ I.symm ⁻¹' v), { rw [preimage_inter, inter_assoc, inter_assoc], congr' 1, rw inter_comm }, rw this at hv, exact ⟨I.symm ⁻¹' v, v_open.preimage I.continuous_symm, by simpa, hv⟩ end, congr := λf g u hu fg hf, begin apply hf.congr, rintros y ⟨hy1, hy2⟩, rcases mem_range.1 hy2 with ⟨x, hx⟩, rw ← hx at ⊢ hy1, simp only with mfld_simps at ⊢ hy1, rw fg _ hy1 end } variable {n} /-- Inclusion of the groupoid of `C^n` local diffeos in the groupoid of `C^m` local diffeos when `m ≤ n` -/ lemma times_cont_diff_groupoid_le (h : m ≤ n) : times_cont_diff_groupoid n I ≤ times_cont_diff_groupoid m I := begin rw [times_cont_diff_groupoid, times_cont_diff_groupoid], apply groupoid_of_pregroupoid_le, assume f s hfs, exact times_cont_diff_on.of_le hfs h end /-- The groupoid of `0`-times continuously differentiable maps is just the groupoid of all local homeomorphisms -/ lemma times_cont_diff_groupoid_zero_eq : times_cont_diff_groupoid 0 I = continuous_groupoid H := begin apply le_antisymm le_top, assume u hu, -- we have to check that every local homeomorphism belongs to `times_cont_diff_groupoid 0 I`, -- by unfolding its definition change u ∈ times_cont_diff_groupoid 0 I, rw [times_cont_diff_groupoid, mem_groupoid_of_pregroupoid], simp only [times_cont_diff_on_zero], split, { apply continuous_on.comp (@continuous.continuous_on _ _ _ _ _ univ I.continuous) _ (subset_univ _), apply continuous_on.comp u.continuous_to_fun I.continuous_symm.continuous_on (inter_subset_left _ _) }, { apply continuous_on.comp (@continuous.continuous_on _ _ _ _ _ univ I.continuous) _ (subset_univ _), apply continuous_on.comp u.continuous_inv_fun I.continuous_inv_fun.continuous_on (inter_subset_left _ _) }, end variable (n) /-- An identity local homeomorphism belongs to the `C^n` groupoid. -/ lemma of_set_mem_times_cont_diff_groupoid {s : set H} (hs : is_open s) : local_homeomorph.of_set s hs ∈ times_cont_diff_groupoid n I := begin rw [times_cont_diff_groupoid, mem_groupoid_of_pregroupoid], suffices h : times_cont_diff_on 𝕜 n (I ∘ I.symm) (I.symm ⁻¹' s ∩ range I), by simp [h], have : times_cont_diff_on 𝕜 n id (univ : set E) := times_cont_diff_id.times_cont_diff_on, exact this.congr_mono (λ x hx, by simp [hx.2]) (subset_univ _) end /-- The composition of a local homeomorphism from `H` to `M` and its inverse belongs to the `C^n` groupoid. -/ lemma symm_trans_mem_times_cont_diff_groupoid (e : local_homeomorph M H) : e.symm.trans e ∈ times_cont_diff_groupoid n I := begin have : e.symm.trans e ≈ local_homeomorph.of_set e.target e.open_target := local_homeomorph.trans_symm_self _, exact structure_groupoid.eq_on_source _ (of_set_mem_times_cont_diff_groupoid n I e.open_target) this end variables {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] /-- The product of two smooth local homeomorphisms is smooth. -/ lemma times_cont_diff_groupoid_prod {I : model_with_corners 𝕜 E H} {I' : model_with_corners 𝕜 E' H'} {e : local_homeomorph H H} {e' : local_homeomorph H' H'} (he : e ∈ times_cont_diff_groupoid ⊤ I) (he' : e' ∈ times_cont_diff_groupoid ⊤ I') : e.prod e' ∈ times_cont_diff_groupoid ⊤ (I.prod I') := begin cases he with he he_symm, cases he' with he' he'_symm, simp only at he he_symm he' he'_symm, split; simp only [local_equiv.prod_source, local_homeomorph.prod_to_local_equiv], { have h3 := times_cont_diff_on.prod_map he he', rw [← model_with_corners.image I _, ← model_with_corners.image I' _, set.prod_image_image_eq] at h3, rw ← model_with_corners.image (I.prod I') _, exact h3, }, { have h3 := times_cont_diff_on.prod_map he_symm he'_symm, rw [← model_with_corners.image I _, ← model_with_corners.image I' _, set.prod_image_image_eq] at h3, rw ← model_with_corners.image (I.prod I') _, exact h3, } end /-- The `C^n` groupoid is closed under restriction. -/ instance : closed_under_restriction (times_cont_diff_groupoid n I) := (closed_under_restriction_iff_id_le _).mpr begin apply structure_groupoid.le_iff.mpr, rintros e ⟨s, hs, hes⟩, apply (times_cont_diff_groupoid n I).eq_on_source' _ _ _ hes, exact of_set_mem_times_cont_diff_groupoid n I hs, end end times_cont_diff_groupoid end model_with_corners section smooth_manifold_with_corners /-! ### Smooth manifolds with corners -/ set_option old_structure_cmd true /-- Typeclass defining smooth manifolds with corners with respect to a model with corners, over a field `𝕜` and with infinite smoothness to simplify typeclass search and statements later on. -/ @[ancestor has_groupoid] class smooth_manifold_with_corners {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) (M : Type*) [topological_space M] [charted_space H M] extends has_groupoid M (times_cont_diff_groupoid ∞ I) : Prop lemma smooth_manifold_with_corners_of_times_cont_diff_on {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) (M : Type*) [topological_space M] [charted_space H M] (h : ∀ (e e' : local_homeomorph M H), e ∈ atlas H M → e' ∈ atlas H M → times_cont_diff_on 𝕜 ⊤ (I ∘ (e.symm ≫ₕ e') ∘ I.symm) (I.symm ⁻¹' (e.symm ≫ₕ e').source ∩ range I)) : smooth_manifold_with_corners I M := { compatible := begin haveI : has_groupoid M (times_cont_diff_groupoid ∞ I) := has_groupoid_of_pregroupoid _ h, apply structure_groupoid.compatible, end } /-- For any model with corners, the model space is a smooth manifold -/ instance model_space_smooth {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] {I : model_with_corners 𝕜 E H} : smooth_manifold_with_corners I H := { .. has_groupoid_model_space _ _ } end smooth_manifold_with_corners namespace smooth_manifold_with_corners /- We restate in the namespace `smooth_manifolds_with_corners` some lemmas that hold for general charted space with a structure groupoid, avoiding the need to specify the groupoid `times_cont_diff_groupoid ∞ I` explicitly. -/ variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) (M : Type*) [topological_space M] [charted_space H M] /-- The maximal atlas of `M` for the smooth manifold with corners structure corresponding to the model with corners `I`. -/ def maximal_atlas := (times_cont_diff_groupoid ∞ I).maximal_atlas M variable {M} lemma mem_maximal_atlas_of_mem_atlas [smooth_manifold_with_corners I M] {e : local_homeomorph M H} (he : e ∈ atlas H M) : e ∈ maximal_atlas I M := structure_groupoid.mem_maximal_atlas_of_mem_atlas _ he lemma chart_mem_maximal_atlas [smooth_manifold_with_corners I M] (x : M) : chart_at H x ∈ maximal_atlas I M := structure_groupoid.chart_mem_maximal_atlas _ x variable {I} lemma compatible_of_mem_maximal_atlas {e e' : local_homeomorph M H} (he : e ∈ maximal_atlas I M) (he' : e' ∈ maximal_atlas I M) : e.symm.trans e' ∈ times_cont_diff_groupoid ∞ I := structure_groupoid.compatible_of_mem_maximal_atlas he he' /-- The product of two smooth manifolds with corners is naturally a smooth manifold with corners. -/ instance prod {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H : Type*} [topological_space H] {I : model_with_corners 𝕜 E H} {H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'} (M : Type*) [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] (M' : Type*) [topological_space M'] [charted_space H' M'] [smooth_manifold_with_corners I' M'] : smooth_manifold_with_corners (I.prod I') (M×M') := { compatible := begin rintros f g ⟨f1, hf1, f2, hf2, hf⟩ ⟨g1, hg1, g2, hg2, hg⟩, rw [hf, hg, local_homeomorph.prod_symm, local_homeomorph.prod_trans], have h1 := has_groupoid.compatible (times_cont_diff_groupoid ⊤ I) hf1 hg1, have h2 := has_groupoid.compatible (times_cont_diff_groupoid ⊤ I') hf2 hg2, exact times_cont_diff_groupoid_prod h1 h2, end } end smooth_manifold_with_corners section extended_charts open_locale topological_space variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) {M : Type*} [topological_space M] [charted_space H M] (x : M) {s t : set M} /-! ### Extended charts In a smooth manifold with corners, the model space is the space `H`. However, we will also need to use extended charts taking values in the model vector space `E`. These extended charts are not `local_homeomorph` as the target is not open in `E` in general, but we can still register them as `local_equiv`. -/ /-- The preferred extended chart on a manifold with corners around a point `x`, from a neighborhood of `x` to the model vector space. -/ @[simp, mfld_simps] def ext_chart_at (x : M) : local_equiv M E := (chart_at H x).to_local_equiv.trans I.to_local_equiv lemma ext_chart_at_source : (ext_chart_at I x).source = (chart_at H x).source := by rw [ext_chart_at, local_equiv.trans_source, I.source_eq, preimage_univ, inter_univ] lemma ext_chart_at_open_source : is_open (ext_chart_at I x).source := by { rw ext_chart_at_source, exact (chart_at H x).open_source } lemma mem_ext_chart_source : x ∈ (ext_chart_at I x).source := by simp only with mfld_simps lemma ext_chart_at_to_inv : (ext_chart_at I x).symm ((ext_chart_at I x) x) = x := by simp only with mfld_simps lemma ext_chart_at_source_mem_nhds : (ext_chart_at I x).source ∈ 𝓝 x := mem_nhds_sets (ext_chart_at_open_source I x) (mem_ext_chart_source I x) lemma ext_chart_at_continuous_on : continuous_on (ext_chart_at I x) (ext_chart_at I x).source := begin refine continuous_on.comp I.continuous.continuous_on _ subset_preimage_univ, rw ext_chart_at_source, exact (chart_at H x).continuous_on end lemma ext_chart_at_continuous_at : continuous_at (ext_chart_at I x) x := (ext_chart_at_continuous_on I x x (mem_ext_chart_source I x)).continuous_at (ext_chart_at_source_mem_nhds I x) lemma ext_chart_at_continuous_on_symm : continuous_on (ext_chart_at I x).symm (ext_chart_at I x).target := begin apply continuous_on.comp (chart_at H x).continuous_on_symm I.continuous_symm.continuous_on, simp [ext_chart_at, local_equiv.trans_target] end lemma ext_chart_at_target_mem_nhds_within : (ext_chart_at I x).target ∈ 𝓝[range I] ((ext_chart_at I x) x) := begin rw [ext_chart_at, local_equiv.trans_target], simp only [function.comp_app, local_equiv.coe_trans, model_with_corners.target_eq], refine inter_mem_nhds_within _ (mem_nhds_sets ((chart_at H x).open_target.preimage I.continuous_symm) _), simp only with mfld_simps end lemma ext_chart_at_coe (p : M) : (ext_chart_at I x) p = I ((chart_at H x : M → H) p) := rfl lemma ext_chart_at_coe_symm (p : E) : (ext_chart_at I x).symm p = ((chart_at H x).symm : H → M) (I.symm p) := rfl lemma nhds_within_ext_chart_target_eq : 𝓝[(ext_chart_at I x).target] ((ext_chart_at I x) x) = 𝓝[range I] ((ext_chart_at I x) x) := begin apply le_antisymm, { apply nhds_within_mono, simp only with mfld_simps}, { apply nhds_within_le_of_mem (ext_chart_at_target_mem_nhds_within _ _) } end lemma ext_chart_continuous_at_symm' {x' : M} (h : x' ∈ (ext_chart_at I x).source) : continuous_at (ext_chart_at I x).symm ((ext_chart_at I x) x') := begin apply continuous_at.comp, { rw ext_chart_at_source at h, simp only with mfld_simps, exact ((chart_at H x).continuous_on_symm _ ((chart_at H x).map_source h)).continuous_at (mem_nhds_sets (chart_at H x).open_target ((chart_at H x).map_source h)) }, { exact I.continuous_symm.continuous_at } end lemma ext_chart_continuous_at_symm : continuous_at (ext_chart_at I x).symm ((ext_chart_at I x) x) := ext_chart_continuous_at_symm' I x (mem_ext_chart_source I x) /-- Technical lemma ensuring that the preimage under an extended chart of a neighborhood of a point in the source is a neighborhood of the preimage, within a set. -/ lemma ext_chart_preimage_mem_nhds_within' {x' : M} (h : x' ∈ (ext_chart_at I x).source) (ht : t ∈ 𝓝[s] x') : (ext_chart_at I x).symm ⁻¹' t ∈ 𝓝[(ext_chart_at I x).symm ⁻¹' s ∩ range I] ((ext_chart_at I x) x') := begin apply (ext_chart_continuous_at_symm' I x h).continuous_within_at.tendsto_nhds_within_image, rw (ext_chart_at I x).left_inv h, apply nhds_within_mono _ _ ht, have : (ext_chart_at I x).symm '' ((ext_chart_at I x).symm ⁻¹' s) ⊆ s := image_preimage_subset _ _, exact subset.trans (image_subset _ (inter_subset_left _ _)) this end /-- Technical lemma ensuring that the preimage under an extended chart of a neighborhood of the base point is a neighborhood of the preimage, within a set. -/ lemma ext_chart_preimage_mem_nhds_within (ht : t ∈ 𝓝[s] x) : (ext_chart_at I x).symm ⁻¹' t ∈ 𝓝[(ext_chart_at I x).symm ⁻¹' s ∩ range I] ((ext_chart_at I x) x) := ext_chart_preimage_mem_nhds_within' I x (mem_ext_chart_source I x) ht /-- Technical lemma ensuring that the preimage under an extended chart of a neighborhood of a point is a neighborhood of the preimage. -/ lemma ext_chart_preimage_mem_nhds (ht : t ∈ 𝓝 x) : (ext_chart_at I x).symm ⁻¹' t ∈ 𝓝 ((ext_chart_at I x) x) := begin apply (ext_chart_continuous_at_symm I x).preimage_mem_nhds, rwa (ext_chart_at I x).left_inv (mem_ext_chart_source _ _) end /-- Technical lemma to rewrite suitably the preimage of an intersection under an extended chart, to bring it into a convenient form to apply derivative lemmas. -/ lemma ext_chart_preimage_inter_eq : ((ext_chart_at I x).symm ⁻¹' (s ∩ t) ∩ range I) = ((ext_chart_at I x).symm ⁻¹' s ∩ range I) ∩ ((ext_chart_at I x).symm ⁻¹' t) := by mfld_set_tac end extended_charts /-- In the case of the manifold structure on a vector space, the extended charts are just the identity.-/ lemma ext_chart_model_space_eq_id (𝕜 : Type*) [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] (x : E) : ext_chart_at (model_with_corners_self 𝕜 E) x = local_equiv.refl E := by simp only with mfld_simps
59f987ced23977bc717962393337fe710061b975
4727251e0cd73359b15b664c3170e5d754078599
/src/measure_theory/category/Meas.lean
07d607a524b277090bd4de8b173e532d6fe54a8f
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
4,418
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 -/ import measure_theory.measure.giry_monad import category_theory.concrete_category.unbundled_hom import category_theory.monad.algebra import topology.category.Top.basic /-! # The category of measurable spaces Measurable spaces and measurable functions form a (concrete) category `Meas`. ## Main definitions * `Measure : Meas ⥤ Meas`: the functor which sends a measurable space `X` to the space of measures on `X`; it is a monad (the "Giry monad"). * `Borel : Top ⥤ Meas`: sends a topological space `X` to `X` equipped with the `σ`-algebra of Borel sets (the `σ`-algebra generated by the open subsets of `X`). ## Tags measurable space, giry monad, borel -/ noncomputable theory open category_theory measure_theory open_locale ennreal universes u v /-- The category of measurable spaces and measurable functions. -/ def Meas : Type (u+1) := bundled measurable_space namespace Meas instance : has_coe_to_sort Meas Type* := bundled.has_coe_to_sort instance (X : Meas) : measurable_space X := X.str /-- Construct a bundled `Meas` from the underlying type and the typeclass. -/ def of (α : Type u) [measurable_space α] : Meas := ⟨α⟩ @[simp] lemma coe_of (X : Type u) [measurable_space X] : (of X : Type u) = X := rfl instance unbundled_hom : unbundled_hom @measurable := ⟨@measurable_id, @measurable.comp⟩ attribute [derive [large_category, concrete_category]] Meas instance : inhabited Meas := ⟨Meas.of empty⟩ /-- `Measure X` is the measurable space of measures over the measurable space `X`. It is the weakest measurable space, s.t. λμ, μ s is measurable for all measurable sets `s` in `X`. An important purpose is to assign a monadic structure on it, the Giry monad. In the Giry monad, the pure values are the Dirac measure, and the bind operation maps to the integral: `(μ >>= ν) s = ∫ x. (ν x) s dμ`. In probability theory, the `Meas`-morphisms `X → Prob X` are (sub-)Markov kernels (here `Prob` is the restriction of `Measure` to (sub-)probability space.) -/ def Measure : Meas ⥤ Meas := { obj := λX, ⟨@measure_theory.measure X.1 X.2⟩, map := λX Y f, ⟨measure.map (f : X → Y), measure.measurable_map f f.2⟩, map_id' := assume ⟨α, I⟩, subtype.eq $ funext $ assume μ, @measure.map_id α I μ, map_comp':= assume X Y Z ⟨f, hf⟩ ⟨g, hg⟩, subtype.eq $ funext $ assume μ, (measure.map_map hg hf).symm } /-- The Giry monad, i.e. the monadic structure associated with `Measure`. -/ def Giry : category_theory.monad Meas := { to_functor := Measure, η' := { app := λX, ⟨@measure.dirac X.1 X.2, measure.measurable_dirac⟩, naturality' := assume X Y ⟨f, hf⟩, subtype.eq $ funext $ assume a, (measure.map_dirac hf a).symm }, μ' := { app := λX, ⟨@measure.join X.1 X.2, measure.measurable_join⟩, naturality' := assume X Y ⟨f, hf⟩, subtype.eq $ funext $ assume μ, measure.join_map_map hf μ }, assoc' := assume α, subtype.eq $ funext $ assume μ, @measure.join_map_join _ _ _, left_unit' := assume α, subtype.eq $ funext $ assume μ, @measure.join_dirac _ _ _, right_unit' := assume α, subtype.eq $ funext $ assume μ, @measure.join_map_dirac _ _ _ } /-- An example for an algebra on `Measure`: the nonnegative Lebesgue integral is a hom, behaving nicely under the monad operations. -/ def Integral : Giry.algebra := { A := Meas.of ℝ≥0∞ , a := ⟨λm:measure ℝ≥0∞, ∫⁻ x, x ∂m, measure.measurable_lintegral measurable_id ⟩, unit' := subtype.eq $ funext $ assume r:ℝ≥0∞, lintegral_dirac' _ measurable_id, assoc' := subtype.eq $ funext $ assume μ : measure (measure ℝ≥0∞), show ∫⁻ x, x ∂ μ.join = ∫⁻ x, x ∂ (measure.map (λm:measure ℝ≥0∞, ∫⁻ x, x ∂m) μ), by rw [measure.lintegral_join, lintegral_map]; apply_rules [measurable_id, measure.measurable_lintegral] } end Meas instance Top.has_forget_to_Meas : has_forget₂ Top.{u} Meas.{u} := bundled_hom.mk_has_forget₂ borel (λ X Y f, ⟨f.1, f.2.borel_measurable⟩) (by intros; refl) /-- The Borel functor, the canonical embedding of topological spaces into measurable spaces. -/ @[reducible] def Borel : Top.{u} ⥤ Meas.{u} := forget₂ Top.{u} Meas.{u}
0d02d1c651c03deb6366a2fba5cecfa4aad51916
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/measure_theory/function/special_functions.lean
a4cfabfd58e7ba87f5dab83a82561551d0cfc732
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,403
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.special_functions.pow import analysis.normed_space.inner_product import measure_theory.constructions.borel_space /-! # Measurability of real and complex functions We show that most standard real and complex functions are measurable, notably `exp`, `cos`, `sin`, `cosh`, `sinh`, `log`, `pow`, `arcsin`, `arccos`, `arctan`, and scalar products. -/ noncomputable theory open_locale nnreal ennreal namespace real @[measurability] lemma measurable_exp : measurable exp := continuous_exp.measurable @[measurability] lemma measurable_log : measurable log := measurable_of_measurable_on_compl_singleton 0 $ continuous.measurable $ continuous_on_iff_continuous_restrict.1 continuous_on_log @[measurability] lemma measurable_sin : measurable sin := continuous_sin.measurable @[measurability] lemma measurable_cos : measurable cos := continuous_cos.measurable @[measurability] lemma measurable_sinh : measurable sinh := continuous_sinh.measurable @[measurability] lemma measurable_cosh : measurable cosh := continuous_cosh.measurable @[measurability] lemma measurable_arcsin : measurable arcsin := continuous_arcsin.measurable @[measurability] lemma measurable_arccos : measurable arccos := continuous_arccos.measurable @[measurability] lemma measurable_arctan : measurable arctan := continuous_arctan.measurable end real namespace complex @[measurability] lemma measurable_re : measurable re := continuous_re.measurable @[measurability] lemma measurable_im : measurable im := continuous_im.measurable @[measurability] lemma measurable_of_real : measurable (coe : ℝ → ℂ) := continuous_of_real.measurable @[measurability] lemma measurable_exp : measurable exp := continuous_exp.measurable @[measurability] lemma measurable_sin : measurable sin := continuous_sin.measurable @[measurability] lemma measurable_cos : measurable cos := continuous_cos.measurable @[measurability] lemma measurable_sinh : measurable sinh := continuous_sinh.measurable @[measurability] lemma measurable_cosh : measurable cosh := continuous_cosh.measurable @[measurability] lemma measurable_arg : measurable arg := have A : measurable (λ x : ℂ, real.arcsin (x.im / x.abs)), from real.measurable_arcsin.comp (measurable_im.div measurable_norm), have B : measurable (λ x : ℂ, real.arcsin ((-x).im / x.abs)), from real.measurable_arcsin.comp ((measurable_im.comp measurable_neg).div measurable_norm), measurable.ite (is_closed_le continuous_const continuous_re).measurable_set A $ measurable.ite (is_closed_le continuous_const continuous_im).measurable_set (B.add_const _) (B.sub_const _) @[measurability] lemma measurable_log : measurable log := (measurable_of_real.comp $ real.measurable_log.comp measurable_norm).add $ (measurable_of_real.comp measurable_arg).mul_const I end complex namespace is_R_or_C variables {𝕜 : Type*} [is_R_or_C 𝕜] [measurable_space 𝕜] [opens_measurable_space 𝕜] @[measurability] lemma measurable_re : measurable (re : 𝕜 → ℝ) := continuous_re.measurable @[measurability] lemma measurable_im : measurable (im : 𝕜 → ℝ) := continuous_im.measurable end is_R_or_C section real_composition open real variables {α : Type*} [measurable_space α] {f : α → ℝ} (hf : measurable f) @[measurability] lemma measurable.exp : measurable (λ x, real.exp (f x)) := real.measurable_exp.comp hf @[measurability] lemma measurable.log : measurable (λ x, log (f x)) := measurable_log.comp hf @[measurability] lemma measurable.cos : measurable (λ x, real.cos (f x)) := real.measurable_cos.comp hf @[measurability] lemma measurable.sin : measurable (λ x, real.sin (f x)) := real.measurable_sin.comp hf @[measurability] lemma measurable.cosh : measurable (λ x, real.cosh (f x)) := real.measurable_cosh.comp hf @[measurability] lemma measurable.sinh : measurable (λ x, real.sinh (f x)) := real.measurable_sinh.comp hf @[measurability] lemma measurable.arctan : measurable (λ x, arctan (f x)) := measurable_arctan.comp hf @[measurability] lemma measurable.sqrt : measurable (λ x, sqrt (f x)) := continuous_sqrt.measurable.comp hf end real_composition section complex_composition open complex variables {α : Type*} [measurable_space α] {f : α → ℂ} (hf : measurable f) @[measurability] lemma measurable.cexp : measurable (λ x, complex.exp (f x)) := complex.measurable_exp.comp hf @[measurability] lemma measurable.ccos : measurable (λ x, complex.cos (f x)) := complex.measurable_cos.comp hf @[measurability] lemma measurable.csin : measurable (λ x, complex.sin (f x)) := complex.measurable_sin.comp hf @[measurability] lemma measurable.ccosh : measurable (λ x, complex.cosh (f x)) := complex.measurable_cosh.comp hf @[measurability] lemma measurable.csinh : measurable (λ x, complex.sinh (f x)) := complex.measurable_sinh.comp hf @[measurability] lemma measurable.carg : measurable (λ x, arg (f x)) := measurable_arg.comp hf @[measurability] lemma measurable.clog : measurable (λ x, log (f x)) := measurable_log.comp hf end complex_composition section is_R_or_C_composition variables {α 𝕜 : Type*} [is_R_or_C 𝕜] [measurable_space α] [measurable_space 𝕜] [opens_measurable_space 𝕜] {f : α → 𝕜} {μ : measure_theory.measure α} @[measurability] lemma measurable.re (hf : measurable f) : measurable (λ x, is_R_or_C.re (f x)) := is_R_or_C.measurable_re.comp hf @[measurability] lemma ae_measurable.re (hf : ae_measurable f μ) : ae_measurable (λ x, is_R_or_C.re (f x)) μ := is_R_or_C.measurable_re.comp_ae_measurable hf @[measurability] lemma measurable.im (hf : measurable f) : measurable (λ x, is_R_or_C.im (f x)) := is_R_or_C.measurable_im.comp hf @[measurability] lemma ae_measurable.im (hf : ae_measurable f μ) : ae_measurable (λ x, is_R_or_C.im (f x)) μ := is_R_or_C.measurable_im.comp_ae_measurable hf end is_R_or_C_composition section pow_instances instance complex.has_measurable_pow : has_measurable_pow ℂ ℂ := ⟨measurable.ite (measurable_fst (measurable_set_singleton 0)) (measurable.ite (measurable_snd (measurable_set_singleton 0)) measurable_one measurable_zero) (measurable_fst.clog.mul measurable_snd).cexp⟩ instance real.has_measurable_pow : has_measurable_pow ℝ ℝ := ⟨complex.measurable_re.comp $ ((complex.measurable_of_real.comp measurable_fst).pow (complex.measurable_of_real.comp measurable_snd))⟩ instance nnreal.has_measurable_pow : has_measurable_pow ℝ≥0 ℝ := ⟨(measurable_fst.coe_nnreal_real.pow measurable_snd).subtype_mk⟩ instance ennreal.has_measurable_pow : has_measurable_pow ℝ≥0∞ ℝ := begin refine ⟨ennreal.measurable_of_measurable_nnreal_prod _ _⟩, { simp_rw ennreal.coe_rpow_def, refine measurable.ite _ measurable_const (measurable_fst.pow measurable_snd).coe_nnreal_ennreal, exact measurable_set.inter (measurable_fst (measurable_set_singleton 0)) (measurable_snd measurable_set_Iio), }, { simp_rw ennreal.top_rpow_def, refine measurable.ite measurable_set_Ioi measurable_const _, exact measurable.ite (measurable_set_singleton 0) measurable_const measurable_const, }, end end pow_instances section variables {α : Type*} {𝕜 : Type*} {E : Type*} [is_R_or_C 𝕜] [inner_product_space 𝕜 E] local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y @[measurability] lemma measurable.inner [measurable_space α] [measurable_space E] [opens_measurable_space E] [topological_space.second_countable_topology E] [measurable_space 𝕜] [borel_space 𝕜] {f g : α → E} (hf : measurable f) (hg : measurable g) : measurable (λ t, ⟪f t, g t⟫) := continuous.measurable2 continuous_inner hf hg @[measurability] lemma ae_measurable.inner [measurable_space α] [measurable_space E] [opens_measurable_space E] [topological_space.second_countable_topology E] [measurable_space 𝕜] [borel_space 𝕜] {μ : measure_theory.measure α} {f g : α → E} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ x, ⟪f x, g x⟫) μ := begin refine ⟨λ x, ⟪hf.mk f x, hg.mk g x⟫, hf.measurable_mk.inner hg.measurable_mk, _⟩, refine hf.ae_eq_mk.mp (hg.ae_eq_mk.mono (λ x hxg hxf, _)), dsimp only, congr, { exact hxf, }, { exact hxg, }, end end
7c167fb518f0221b1978dd505be746944322faf8
3dc4623269159d02a444fe898d33e8c7e7e9461b
/.github/workflows/project_1_a_decrire/projet_A2/X.lean
bb2813073fa377cf61976eb44a41c61c1787e5af
[]
no_license
Or7ando/lean
cc003e6c41048eae7c34aa6bada51c9e9add9e66
d41169cf4e416a0d42092fb6bdc14131cee9dd15
refs/heads/master
1,650,600,589,722
1,587,262,906,000
1,587,262,906,000
255,387,160
0
0
null
null
null
null
UTF-8
Lean
false
false
2,294
lean
import .A2_disc open A2_disc open is_ring_hom lemma power_commute_with_morph {A B :Type}[comm_ring A][comm_ring B](f : A → B)[is_ring_hom f](n : ℕ) : ∀ x : A, f( x^n ) = (f x)^n := λ x, nat.rec_on n (show f(x^0) = (f x)^0, {rw [pow_zero x,pow_zero (f x)], exact map_one f,}) (assume n, assume rec_hyp : f(x^n) = (f(x))^n, show f(x^(n+1)) = (f(x))^(n+1),{rw [pow_succ x n,pow_succ (f(x)) n,← rec_hyp],exact map_mul (f)}) structure X (R : Type)[comm_ring R] := (x y : R) (inv : R) (certif : (x-y)^2 * inv = 1) namespace X section variables {R : Type} [comm_ring R] lemma diec_certif : ∀ {ζ1 ζ2 : X R}, (ζ1.x = ζ2.x) → (ζ1.y = ζ2.y) → (ζ1.x - ζ1.y)^2 = (ζ2.x - ζ2.y)^2 := begin intros ζ1 ζ2, intros h1 h2, rw [h1,h2], end @[ext] lemma ext : ∀ {ζ1 ζ2 : X R}, (ζ1.x = ζ2.x) → (ζ1.y = ζ2.y) → ζ1 = ζ2 := λ ζ1 ζ2, begin intro hx, intro hy, cases ζ1, cases ζ2, congr; try {assumption}, apply A2_disc.inverse_unique, exact ζ1_certif, exact ζ2_certif, exact diec_certif hx hy, end def map_X {A B :Type }[comm_ring A][comm_ring B](f : A → B)[is_ring_hom f] : X A → X B := λ η, begin exact {x := f η.x, y := f η.y, inv := f η.inv,certif := begin rw [← map_sub f,← power_commute_with_morph f,← map_mul f,η.certif], exact map_one f, end } end lemma map_comp_x {A B :Type }[comm_ring A][comm_ring B](f : A → B)[is_ring_hom f] (ζ : X (A) ) : (map_X f ζ).x = f ζ.x := rfl lemma map_comp_y {A B :Type }[comm_ring A][comm_ring B](f : A → B)[is_ring_hom f] (ζ : X (A) ) : (map_X f ζ).y = f ζ.y := rfl lemma map_comp_inv {A B :Type }[comm_ring A][comm_ring B](f : A → B)[is_ring_hom f] (ζ : X (A) ) : (map_X f ζ).inv = f ζ.inv := rfl def 𝕏 : CommRing ⥤ Type := { obj := λ R, X R, map := λ R R' f, map_X f, } end #print 𝕏 end X
1f75621bc973bf1bb305ca763b2578cd9bb0ce74
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebraic_topology/simplex_category.lean
b1e224344c08eafea94f9c3ee1884d889b8b3ece
[ "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
27,481
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Scott Morrison, Adam Topaz -/ import category_theory.skeletal import tactic.linarith import data.fintype.sort import order.category.NonemptyFinLinOrd import category_theory.functor.reflects_isomorphisms /-! # The simplex category We construct a skeletal model of the simplex category, with objects `ℕ` and the morphism `n ⟶ m` being the monotone maps from `fin (n+1)` to `fin (m+1)`. We show that this category is equivalent to `NonemptyFinLinOrd`. ## Remarks The definitions `simplex_category` and `simplex_category.hom` are marked as irreducible. We provide the following functions to work with these objects: 1. `simplex_category.mk` creates an object of `simplex_category` out of a natural number. Use the notation `[n]` in the `simplicial` locale. 2. `simplex_category.len` gives the "length" of an object of `simplex_category`, as a natural. 3. `simplex_category.hom.mk` makes a morphism out of a monotone map between `fin`'s. 4. `simplex_category.hom.to_order_hom` gives the underlying monotone map associated to a term of `simplex_category.hom`. -/ universe v open category_theory /-- The simplex category: * objects are natural numbers `n : ℕ` * morphisms from `n` to `m` are monotone functions `fin (n+1) → fin (m+1)` -/ @[derive inhabited, irreducible] def simplex_category := ℕ namespace simplex_category section local attribute [semireducible] simplex_category -- TODO: Make `mk` irreducible. /-- Interpet a natural number as an object of the simplex category. -/ def mk (n : ℕ) : simplex_category := n localized "notation (name := simplex_category.mk) `[`n`]` := simplex_category.mk n" in simplicial -- TODO: Make `len` irreducible. /-- The length of an object of `simplex_category`. -/ def len (n : simplex_category) : ℕ := n @[ext] lemma ext (a b : simplex_category) : a.len = b.len → a = b := id @[simp] lemma len_mk (n : ℕ) : [n].len = n := rfl @[simp] lemma mk_len (n : simplex_category) : [n.len] = n := rfl /-- A recursor for `simplex_category`. Use it as `induction Δ using simplex_category.rec`. -/ protected def rec {F : Π (Δ : simplex_category), Sort*} (h : ∀ (n : ℕ), F [n]) : Π X, F X := λ n, h n.len /-- Morphisms in the simplex_category. -/ @[irreducible, nolint has_nonempty_instance] protected def hom (a b : simplex_category) := fin (a.len + 1) →o fin (b.len + 1) namespace hom local attribute [semireducible] simplex_category.hom /-- Make a moprhism in `simplex_category` from a monotone map of fin's. -/ def mk {a b : simplex_category} (f : fin (a.len + 1) →o fin (b.len + 1)) : simplex_category.hom a b := f /-- Recover the monotone map from a morphism in the simplex category. -/ def to_order_hom {a b : simplex_category} (f : simplex_category.hom a b) : fin (a.len + 1) →o fin (b.len + 1) := f @[ext] lemma ext {a b : simplex_category} (f g : simplex_category.hom a b) : f.to_order_hom = g.to_order_hom → f = g := id @[simp] lemma mk_to_order_hom {a b : simplex_category} (f : simplex_category.hom a b) : mk (f.to_order_hom) = f := rfl @[simp] lemma to_order_hom_mk {a b : simplex_category} (f : fin (a.len + 1) →o fin (b.len + 1)) : (mk f).to_order_hom = f := rfl lemma mk_to_order_hom_apply {a b : simplex_category} (f : fin (a.len + 1) →o fin (b.len + 1)) (i : fin (a.len + 1)) : (mk f).to_order_hom i = f i := rfl /-- Identity morphisms of `simplex_category`. -/ @[simp] def id (a : simplex_category) : simplex_category.hom a a := mk order_hom.id /-- Composition of morphisms of `simplex_category`. -/ @[simp] def comp {a b c : simplex_category} (f : simplex_category.hom b c) (g : simplex_category.hom a b) : simplex_category.hom a c := mk $ f.to_order_hom.comp g.to_order_hom end hom @[simps] instance small_category : small_category.{0} simplex_category := { hom := λ n m, simplex_category.hom n m, id := λ m, simplex_category.hom.id _, comp := λ _ _ _ f g, simplex_category.hom.comp g f, } /-- The constant morphism from [0]. -/ def const (x : simplex_category) (i : fin (x.len+1)) : [0] ⟶ x := hom.mk $ ⟨λ _, i, by tauto⟩ @[simp] lemma const_comp (x y : simplex_category) (i : fin (x.len + 1)) (f : x ⟶ y) : const x i ≫ f = const y (f.to_order_hom i) := rfl /-- Make a morphism `[n] ⟶ [m]` from a monotone map between fin's. This is useful for constructing morphisms beetween `[n]` directly without identifying `n` with `[n].len`. -/ @[simp] def mk_hom {n m : ℕ} (f : (fin (n+1)) →o (fin (m+1))) : [n] ⟶ [m] := simplex_category.hom.mk f lemma hom_zero_zero (f : [0] ⟶ [0]) : f = 𝟙 _ := by { ext : 2, dsimp, apply subsingleton.elim } end open_locale simplicial section generators /-! ## Generating maps for the simplex category TODO: prove that the simplex category is equivalent to one given by the following generators and relations. -/ /-- The `i`-th face map from `[n]` to `[n+1]` -/ def δ {n} (i : fin (n+2)) : [n] ⟶ [n+1] := mk_hom (fin.succ_above i).to_order_hom /-- The `i`-th degeneracy map from `[n+1]` to `[n]` -/ def σ {n} (i : fin (n+1)) : [n+1] ⟶ [n] := mk_hom { to_fun := fin.pred_above i, monotone' := fin.pred_above_right_monotone i } /-- The generic case of the first simplicial identity -/ lemma δ_comp_δ {n} {i j : fin (n+2)} (H : i ≤ j) : δ i ≫ δ j.succ = δ j ≫ δ i.cast_succ := begin ext k, dsimp [δ, fin.succ_above], simp only [order_embedding.to_order_hom_coe, order_embedding.coe_of_strict_mono, function.comp_app, simplex_category.hom.to_order_hom_mk, order_hom.comp_coe], rcases i with ⟨i, _⟩, rcases j with ⟨j, _⟩, rcases k with ⟨k, _⟩, split_ifs; { simp at *; linarith }, end /-- The special case of the first simplicial identity -/ lemma δ_comp_δ_self {n} {i : fin (n+2)} : δ i ≫ δ i.cast_succ = δ i ≫ δ i.succ := (δ_comp_δ (le_refl i)).symm /-- The second simplicial identity -/ lemma δ_comp_σ_of_le {n} {i : fin (n+2)} {j : fin (n+1)} (H : i ≤ j.cast_succ) : δ i.cast_succ ≫ σ j.succ = σ j ≫ δ i := begin ext k, suffices : ite (j.succ.cast_succ < ite (k < i) k.cast_succ k.succ) (ite (k < i) (k:ℕ) (k + 1) - 1) (ite (k < i) k (k + 1)) = ite ((if h : (j:ℕ) < k then k.pred (by { rintro rfl, exact nat.not_lt_zero _ h }) else k.cast_lt (by { cases j, cases k, simp only [len_mk], linarith })).cast_succ < i) (ite (j.cast_succ < k) (k - 1) k) (ite (j.cast_succ < k) (k - 1) k + 1), { dsimp [δ, σ, fin.succ_above, fin.pred_above], simp [fin.pred_above] with push_cast, convert rfl }, rcases i with ⟨i, _⟩, rcases j with ⟨j, _⟩, rcases k with ⟨k, _⟩, simp only [fin.mk_le_mk, fin.cast_succ_mk] at H, dsimp, split_ifs, -- Most of the goals can now be handled by `linarith`, -- but we have to deal with two of them by hand. swap 8, { exact (nat.succ_pred_eq_of_pos (lt_of_le_of_lt (zero_le _) ‹_›)).symm, }, swap 7, { have : k ≤ i := nat.le_of_pred_lt ‹_›, linarith, }, -- Hope for the best from `linarith`: all_goals { try { refl <|> simp at * }; linarith, }, end /-- The first part of the third simplicial identity -/ lemma δ_comp_σ_self {n} {i : fin (n+1)} : δ i.cast_succ ≫ σ i = 𝟙 [n] := begin ext j, suffices : ite (fin.cast_succ i < ite (j < i) (fin.cast_succ j) j.succ) (ite (j < i) (j:ℕ) (j + 1) - 1) (ite (j < i) j (j + 1)) = j, { dsimp [δ, σ, fin.succ_above, fin.pred_above], simpa [fin.pred_above] with push_cast }, rcases i with ⟨i, _⟩, rcases j with ⟨j, _⟩, dsimp, split_ifs; { simp at *; linarith, }, end /-- The second part of the third simplicial identity -/ lemma δ_comp_σ_succ {n} {i : fin (n+1)} : δ i.succ ≫ σ i = 𝟙 [n] := begin ext j, rcases i with ⟨i, _⟩, rcases j with ⟨j, _⟩, dsimp [δ, σ, fin.succ_above, fin.pred_above], simp [fin.pred_above] with push_cast, split_ifs; { simp at *; linarith, }, end /-- The fourth simplicial identity -/ lemma δ_comp_σ_of_gt {n} {i : fin (n+2)} {j : fin (n+1)} (H : j.cast_succ < i) : δ i.succ ≫ σ j.cast_succ = σ j ≫ δ i := begin ext k, dsimp [δ, σ, fin.succ_above, fin.pred_above], rcases i with ⟨i, _⟩, rcases j with ⟨j, _⟩, rcases k with ⟨k, _⟩, simp only [fin.mk_lt_mk, fin.cast_succ_mk] at H, suffices : ite (_ < ite (k < i + 1) _ _) _ _ = ite _ (ite (j < k) (k - 1) k) (ite (j < k) (k - 1) k + 1), { simpa [apply_dite fin.cast_succ, fin.pred_above] with push_cast, }, split_ifs, -- Most of the goals can now be handled by `linarith`, -- but we have to deal with three of them by hand. swap 2, { simp only [fin.mk_lt_mk] at h_1, simp only [not_lt] at h_2, simp only [self_eq_add_right, one_ne_zero], exact lt_irrefl (k - 1) (lt_of_lt_of_le (nat.pred_lt (ne_of_lt (lt_of_le_of_lt (zero_le _) h_1)).symm) (le_trans (nat.le_of_lt_succ h) h_2)) }, swap 4, { simp only [fin.mk_lt_mk] at h_1, simp only [not_lt] at h, simp only [nat.add_succ_sub_one, add_zero], exfalso, exact lt_irrefl _ (lt_of_le_of_lt (nat.le_pred_of_lt (nat.lt_of_succ_le h)) h_3), }, swap 4, { simp only [fin.mk_lt_mk] at h_1, simp only [not_lt] at h_3, simp only [nat.add_succ_sub_one, add_zero], exact (nat.succ_pred_eq_of_pos (lt_of_le_of_lt (zero_le _) h_2)).symm, }, -- Hope for the best from `linarith`: all_goals { simp at h_1 h_2 ⊢; linarith, }, end local attribute [simp] fin.pred_mk /-- The fifth simplicial identity -/ lemma σ_comp_σ {n} {i j : fin (n+1)} (H : i ≤ j) : σ i.cast_succ ≫ σ j = σ j.succ ≫ σ i := begin ext k, dsimp [σ, fin.pred_above], rcases i with ⟨i, _⟩, rcases j with ⟨j, _⟩, rcases k with ⟨k, _⟩, simp only [fin.mk_le_mk] at H, -- At this point `simp with push_cast` makes good progress, but neither `simp?` nor `squeeze_simp` -- return usable sets of lemmas. -- To avoid using a non-terminal simp, we make a `suffices` statement indicating the shape -- of the goal we're looking for, and then use `simpa with push_cast`. -- I'm not sure this is actually much more robust that a non-terminal simp. suffices : ite (_ < dite (i < k) _ _) _ _ = ite (_ < dite (j + 1 < k) _ _) _ _, { simpa [fin.pred_above] with push_cast, }, split_ifs, -- `split_ifs` created 12 goals. -- Most of them are dealt with `by simp at *; linarith`, -- but we pull out two harder ones to do by hand. swap 3, { simp only [not_lt] at h_2, exact false.elim (lt_irrefl (k - 1) (lt_of_lt_of_le (nat.pred_lt (id (ne_of_lt (lt_of_le_of_lt (zero_le i) h)).symm)) (le_trans h_2 (nat.succ_le_of_lt h_1)))) }, swap 3, { simp only [subtype.mk_lt_mk, not_lt] at h_1, exact false.elim (lt_irrefl j (lt_of_lt_of_le (nat.pred_lt_pred (nat.succ_ne_zero j) h_2) h_1)) }, -- Deal with the rest automatically. all_goals { simp at *; linarith, }, end end generators section skeleton /-- The functor that exhibits `simplex_category` as skeleton of `NonemptyFinLinOrd` -/ @[simps obj map] def skeletal_functor : simplex_category ⥤ NonemptyFinLinOrd.{v} := { obj := λ a, NonemptyFinLinOrd.of $ ulift (fin (a.len + 1)), map := λ a b f, ⟨λ i, ulift.up (f.to_order_hom i.down), λ i j h, f.to_order_hom.monotone h⟩, map_id' := λ a, by { ext, simp, }, map_comp' := λ a b c f g, by { ext, simp, }, } lemma skeletal : skeletal simplex_category := λ X Y ⟨I⟩, begin suffices : fintype.card (fin (X.len+1)) = fintype.card (fin (Y.len+1)), { ext, simpa }, { apply fintype.card_congr, refine equiv.ulift.symm.trans (((skeletal_functor ⋙ forget _).map_iso I).to_equiv.trans _), apply equiv.ulift } end namespace skeletal_functor instance : full skeletal_functor.{v} := { preimage := λ a b f, simplex_category.hom.mk ⟨λ i, (f (ulift.up i)).down, λ i j h, f.monotone h⟩, witness' := by { intros m n f, dsimp at *, ext1 ⟨i⟩, ext1, ext1, cases x, simp, } } instance : faithful skeletal_functor.{v} := { map_injective' := λ m n f g h, begin ext1, ext1, ext1 i, apply ulift.up.inj, change (skeletal_functor.map f) ⟨i⟩ = (skeletal_functor.map g) ⟨i⟩, rw h, end } instance : ess_surj skeletal_functor.{v} := { mem_ess_image := λ X, ⟨mk (fintype.card X - 1 : ℕ), ⟨begin have aux : fintype.card X = fintype.card X - 1 + 1, { exact (nat.succ_pred_eq_of_pos $ fintype.card_pos_iff.mpr ⟨⊥⟩).symm, }, let f := mono_equiv_of_fin X aux, have hf := (finset.univ.order_emb_of_fin aux).strict_mono, refine { hom := ⟨λ i, f i.down, _⟩, inv := ⟨λ i, ⟨f.symm i⟩, _⟩, hom_inv_id' := _, inv_hom_id' := _ }, { rintro ⟨i⟩ ⟨j⟩ h, show f i ≤ f j, exact hf.monotone h, }, { intros i j h, show f.symm i ≤ f.symm j, rw ← hf.le_iff_le, show f (f.symm i) ≤ f (f.symm j), simpa only [order_iso.apply_symm_apply], }, { ext1, ext1 ⟨i⟩, ext1, exact f.symm_apply_apply i }, { ext1, ext1 i, exact f.apply_symm_apply i }, end⟩⟩, } noncomputable instance is_equivalence : is_equivalence (skeletal_functor.{v}) := equivalence.of_fully_faithfully_ess_surj skeletal_functor end skeletal_functor /-- The equivalence that exhibits `simplex_category` as skeleton of `NonemptyFinLinOrd` -/ noncomputable def skeletal_equivalence : simplex_category ≌ NonemptyFinLinOrd.{v} := functor.as_equivalence skeletal_functor end skeleton /-- `simplex_category` is a skeleton of `NonemptyFinLinOrd`. -/ noncomputable def is_skeleton_of : is_skeleton_of NonemptyFinLinOrd simplex_category skeletal_functor.{v} := { skel := skeletal, eqv := skeletal_functor.is_equivalence } /-- The truncated simplex category. -/ @[derive small_category] def truncated (n : ℕ) := full_subcategory (λ a : simplex_category, a.len ≤ n) namespace truncated instance {n} : inhabited (truncated n) := ⟨⟨[0],by simp⟩⟩ /-- The fully faithful inclusion of the truncated simplex category into the usual simplex category. -/ @[derive [full, faithful]] def inclusion {n : ℕ} : simplex_category.truncated n ⥤ simplex_category := full_subcategory_inclusion _ end truncated section concrete instance : concrete_category.{0} simplex_category := { forget := { obj := λ i, fin (i.len + 1), map := λ i j f, f.to_order_hom }, forget_faithful := {} } end concrete section epi_mono /-- A morphism in `simplex_category` is a monomorphism precisely when it is an injective function -/ theorem mono_iff_injective {n m : simplex_category} {f : n ⟶ m} : mono f ↔ function.injective f.to_order_hom := begin split, { introsI m x y h, have H : const n x ≫ f = const n y ≫ f, { dsimp, rw h }, change (n.const x).to_order_hom 0 = (n.const y).to_order_hom 0, rw cancel_mono f at H, rw H }, { exact concrete_category.mono_of_injective f } end /-- A morphism in `simplex_category` is an epimorphism if and only if it is a surjective function -/ lemma epi_iff_surjective {n m : simplex_category} {f: n ⟶ m} : epi f ↔ function.surjective f.to_order_hom := begin split, { introsI hyp_f_epi x, by_contra' h_ab, -- The proof is by contradiction: assume f is not surjective, -- then introduce two non-equal auxiliary functions equalizing f, and get a contradiction. -- First we define the two auxiliary functions. set chi_1 : m ⟶ [1] := hom.mk ⟨λ u, if u ≤ x then 0 else 1, begin intros a b h, dsimp only [], split_ifs with h1 h2 h3, any_goals { exact le_rfl }, { exact bot_le }, { exact false.elim (h1 (le_trans h h3)) } end ⟩, set chi_2 : m ⟶ [1] := hom.mk ⟨λ u, if u < x then 0 else 1, begin intros a b h, dsimp only [], split_ifs with h1 h2 h3, any_goals { exact le_rfl }, { exact bot_le }, { exact false.elim (h1 (lt_of_le_of_lt h h3)) } end ⟩, -- The two auxiliary functions equalize f have f_comp_chi_i : f ≫ chi_1 = f ≫ chi_2, { dsimp, ext, simp [le_iff_lt_or_eq, h_ab x_1] }, -- We now just have to show the two auxiliary functions are not equal. rw category_theory.cancel_epi f at f_comp_chi_i, rename f_comp_chi_i eq_chi_i, apply_fun (λ e, e.to_order_hom x) at eq_chi_i, suffices : (0 : fin 2) = 1, by exact bot_ne_top this, simpa using eq_chi_i }, { exact concrete_category.epi_of_surjective f } end /-- A monomorphism in `simplex_category` must increase lengths-/ lemma len_le_of_mono {x y : simplex_category} {f : x ⟶ y} : mono f → (x.len ≤ y.len) := begin intro hyp_f_mono, have f_inj : function.injective f.to_order_hom.to_fun, { exact mono_iff_injective.elim_left (hyp_f_mono) }, simpa using fintype.card_le_of_injective f.to_order_hom.to_fun f_inj, end lemma le_of_mono {n m : ℕ} {f : [n] ⟶ [m]} : (category_theory.mono f) → (n ≤ m) := len_le_of_mono /-- An epimorphism in `simplex_category` must decrease lengths-/ lemma len_le_of_epi {x y : simplex_category} {f : x ⟶ y} : epi f → y.len ≤ x.len := begin intro hyp_f_epi, have f_surj : function.surjective f.to_order_hom.to_fun, { exact epi_iff_surjective.elim_left (hyp_f_epi) }, simpa using fintype.card_le_of_surjective f.to_order_hom.to_fun f_surj, end lemma le_of_epi {n m : ℕ} {f : [n] ⟶ [m]} : epi f → (m ≤ n) := len_le_of_epi instance {n : ℕ} {i : fin (n+2)} : mono (δ i) := begin rw mono_iff_injective, exact fin.succ_above_right_injective, end instance {n : ℕ} {i : fin (n+1)} : epi (σ i) := begin rw epi_iff_surjective, intro b, simp only [σ, mk_hom, hom.to_order_hom_mk, order_hom.coe_fun_mk], by_cases b ≤ i, { use b, rw fin.pred_above_below i b (by simpa only [fin.coe_eq_cast_succ] using h), simp only [fin.coe_eq_cast_succ, fin.cast_pred_cast_succ], }, { use b.succ, rw [fin.pred_above_above i b.succ _, fin.pred_succ], rw not_le at h, rw fin.lt_iff_coe_lt_coe at h ⊢, simpa only [fin.coe_succ, fin.coe_cast_succ] using nat.lt.step h, } end instance : reflects_isomorphisms (forget simplex_category) := ⟨begin intros x y f, introI, exact is_iso.of_iso { hom := f, inv := hom.mk { to_fun := inv ((forget simplex_category).map f), monotone' :=λ y₁ y₂ h, begin by_cases h' : y₁ < y₂, { by_contradiction h'', have eq := λ i, congr_hom (iso.inv_hom_id (as_iso ((forget _).map f))) i, have ineq := f.to_order_hom.monotone' (le_of_not_ge h''), dsimp at ineq, erw [eq, eq] at ineq, exact not_le.mpr h' ineq, }, { rw eq_of_le_of_not_lt h h', } end, }, hom_inv_id' := by { ext1, ext1, exact iso.hom_inv_id (as_iso ((forget _).map f)), }, inv_hom_id' := by { ext1, ext1, exact iso.inv_hom_id (as_iso ((forget _).map f)), }, }, end⟩ lemma is_iso_of_bijective {x y : simplex_category} {f : x ⟶ y} (hf : function.bijective (f.to_order_hom.to_fun)) : is_iso f := begin haveI : is_iso ((forget simplex_category).map f) := (is_iso_iff_bijective _).mpr hf, exact is_iso_of_reflects_iso f (forget simplex_category), end /-- An isomorphism in `simplex_category` induces an `order_iso`. -/ @[simp] def order_iso_of_iso {x y : simplex_category} (e : x ≅ y) : fin (x.len+1) ≃o fin (y.len+1) := equiv.to_order_iso { to_fun := e.hom.to_order_hom, inv_fun := e.inv.to_order_hom, left_inv := λ i, by simpa only using congr_arg (λ φ, (hom.to_order_hom φ) i) e.hom_inv_id', right_inv := λ i, by simpa only using congr_arg (λ φ, (hom.to_order_hom φ) i) e.inv_hom_id', } e.hom.to_order_hom.monotone e.inv.to_order_hom.monotone lemma iso_eq_iso_refl {x : simplex_category} (e : x ≅ x) : e = iso.refl x := begin have h : (finset.univ : finset (fin (x.len+1))).card = x.len+1 := finset.card_fin (x.len+1), have eq₁ := finset.order_emb_of_fin_unique' h (λ i, finset.mem_univ ((order_iso_of_iso e) i)), have eq₂ := finset.order_emb_of_fin_unique' h (λ i, finset.mem_univ ((order_iso_of_iso (iso.refl x)) i)), ext1, ext1, convert congr_arg (λ φ, (order_embedding.to_order_hom φ)) (eq₁.trans eq₂.symm), ext1, ext1 i, refl, end lemma eq_id_of_is_iso {x : simplex_category} {f : x ⟶ x} (hf : is_iso f) : f = 𝟙 _ := congr_arg (λ (φ : _ ≅ _), φ.hom) (iso_eq_iso_refl (as_iso f)) lemma eq_σ_comp_of_not_injective' {n : ℕ} {Δ' : simplex_category} (θ : mk (n+1) ⟶ Δ') (i : fin (n+1)) (hi : θ.to_order_hom i.cast_succ = θ.to_order_hom i.succ): ∃ (θ' : mk n ⟶ Δ'), θ = σ i ≫ θ' := begin use δ i.succ ≫ θ, ext1, ext1, ext1 x, simp only [hom.to_order_hom_mk, function.comp_app, order_hom.comp_coe, hom.comp, small_category_comp, σ, mk_hom, order_hom.coe_fun_mk], by_cases h' : x ≤ i.cast_succ, { rw fin.pred_above_below i x h', have eq := fin.cast_succ_cast_pred (gt_of_gt_of_ge (fin.cast_succ_lt_last i) h'), erw fin.succ_above_below i.succ x.cast_pred _, swap, { rwa [eq, ← fin.le_cast_succ_iff], }, rw eq, }, { simp only [not_le] at h', let y := x.pred begin intro h, rw h at h', simpa only [fin.lt_iff_coe_lt_coe, nat.not_lt_zero, fin.coe_zero] using h', end, simp only [show x = y.succ, by rw fin.succ_pred] at h' ⊢, rw [fin.pred_above_above i y.succ h', fin.pred_succ], by_cases h'' : y = i, { rw h'', convert hi.symm, erw fin.succ_above_below i.succ _, exact fin.lt_succ, }, { erw fin.succ_above_above i.succ _, simp only [fin.lt_iff_coe_lt_coe, fin.le_iff_coe_le_coe, fin.coe_succ, fin.coe_cast_succ, nat.lt_succ_iff, fin.ext_iff] at h' h'' ⊢, cases nat.le.dest h' with c hc, cases c, { exfalso, rw [add_zero] at hc, rw [hc] at h'', exact h'' rfl, }, { rw ← hc, simp only [add_le_add_iff_left, nat.succ_eq_add_one, le_add_iff_nonneg_left, zero_le], }, }, } end lemma eq_σ_comp_of_not_injective {n : ℕ} {Δ' : simplex_category} (θ : mk (n+1) ⟶ Δ') (hθ : ¬function.injective θ.to_order_hom) : ∃ (i : fin (n+1)) (θ' : mk n ⟶ Δ'), θ = σ i ≫ θ' := begin simp only [function.injective, exists_prop, not_forall] at hθ, -- as θ is not injective, there exists `x<y` such that `θ x = θ y` -- and then, `θ x = θ (x+1)` have hθ₂ : ∃ (x y : fin (n+2)), (hom.to_order_hom θ) x = (hom.to_order_hom θ) y ∧ x<y, { rcases hθ with ⟨x, y, ⟨h₁, h₂⟩⟩, by_cases x<y, { exact ⟨x, y, ⟨h₁, h⟩⟩, }, { refine ⟨y, x, ⟨h₁.symm, _⟩⟩, cases lt_or_eq_of_le (not_lt.mp h) with h' h', { exact h', }, { exfalso, exact h₂ h'.symm, }, }, }, rcases hθ₂ with ⟨x, y, ⟨h₁, h₂⟩⟩, let z := x.cast_pred, use z, simp only [← (show z.cast_succ = x, by exact fin.cast_succ_cast_pred (lt_of_lt_of_le h₂ (fin.le_last y)))] at h₁ h₂, apply eq_σ_comp_of_not_injective', rw fin.cast_succ_lt_iff_succ_le at h₂, apply le_antisymm, { exact θ.to_order_hom.monotone (le_of_lt (fin.cast_succ_lt_succ z)), }, { rw h₁, exact θ.to_order_hom.monotone h₂, }, end lemma eq_comp_δ_of_not_surjective' {n : ℕ} {Δ : simplex_category} (θ : Δ ⟶ mk (n+1)) (i : fin (n+2)) (hi : ∀ x, θ.to_order_hom x ≠ i) : ∃ (θ' : Δ ⟶ (mk n)), θ = θ' ≫ δ i := begin by_cases i < fin.last (n+1), { use θ ≫ σ (fin.cast_pred i), ext1, ext1, ext1 x, simp only [hom.to_order_hom_mk, function.comp_app, order_hom.comp_coe, hom.comp, small_category_comp], by_cases h' : θ.to_order_hom x ≤ i, { simp only [σ, mk_hom, hom.to_order_hom_mk, order_hom.coe_fun_mk], rw fin.pred_above_below (fin.cast_pred i) (θ.to_order_hom x) (by simpa [fin.cast_succ_cast_pred h] using h'), erw fin.succ_above_below i, swap, { simp only [fin.lt_iff_coe_lt_coe, fin.coe_cast_succ], exact lt_of_le_of_lt (fin.coe_cast_pred_le_self _) (fin.lt_iff_coe_lt_coe.mp ((ne.le_iff_lt (hi x)).mp h')), }, rw fin.cast_succ_cast_pred, apply lt_of_le_of_lt h' h, }, { simp only [not_le] at h', simp only [σ, mk_hom, hom.to_order_hom_mk, order_hom.coe_fun_mk, fin.pred_above_above (fin.cast_pred i) (θ.to_order_hom x) (by simpa only [fin.cast_succ_cast_pred h] using h')], erw [fin.succ_above_above i _, fin.succ_pred], simpa only [fin.le_iff_coe_le_coe, fin.coe_cast_succ, fin.coe_pred] using nat.le_pred_of_lt (fin.lt_iff_coe_lt_coe.mp h'), }, }, { obtain rfl := le_antisymm (fin.le_last i) (not_lt.mp h), use θ ≫ σ (fin.last _), ext1, ext1, ext1 x, simp only [hom.to_order_hom_mk, function.comp_app, order_hom.comp_coe, hom.comp, small_category_comp, σ, δ, mk_hom, order_hom.coe_fun_mk, order_embedding.to_order_hom_coe, fin.pred_above_last, fin.succ_above_last, fin.cast_succ_cast_pred ((ne.le_iff_lt (hi x)).mp (fin.le_last _))], }, end lemma eq_comp_δ_of_not_surjective {n : ℕ} {Δ : simplex_category} (θ : Δ ⟶ mk (n+1)) (hθ : ¬function.surjective θ.to_order_hom) : ∃ (i : fin (n+2)) (θ' : Δ ⟶ (mk n)), θ = θ' ≫ δ i := begin cases not_forall.mp hθ with i hi, use i, exact eq_comp_δ_of_not_surjective' θ i (not_exists.mp hi), end lemma eq_id_of_mono {x : simplex_category} (i : x ⟶ x) [mono i] : i = 𝟙 _ := begin apply eq_id_of_is_iso, apply is_iso_of_bijective, dsimp, rw [fintype.bijective_iff_injective_and_card i.to_order_hom, ← mono_iff_injective, eq_self_iff_true, and_true], apply_instance, end lemma eq_id_of_epi {x : simplex_category} (i : x ⟶ x) [epi i] : i = 𝟙 _ := begin apply eq_id_of_is_iso, apply is_iso_of_bijective, dsimp, rw [fintype.bijective_iff_surjective_and_card i.to_order_hom, ← epi_iff_surjective, eq_self_iff_true, and_true], apply_instance, end lemma eq_σ_of_epi {n : ℕ} (θ : mk (n+1) ⟶ mk n) [epi θ] : ∃ (i : fin (n+1)), θ = σ i := begin rcases eq_σ_comp_of_not_injective θ _ with ⟨i, θ', h⟩, swap, { by_contradiction, simpa only [nat.one_ne_zero, add_le_iff_nonpos_right, nonpos_iff_eq_zero] using le_of_mono (mono_iff_injective.mpr h), }, use i, haveI : epi (σ i ≫ θ') := by { rw ← h, apply_instance, }, haveI := category_theory.epi_of_epi (σ i) θ', rw [h, eq_id_of_epi θ', category.comp_id], end lemma eq_δ_of_mono {n : ℕ} (θ : mk n ⟶ mk (n+1)) [mono θ] : ∃ (i : fin (n+2)), θ = δ i := begin rcases eq_comp_δ_of_not_surjective θ _ with ⟨i, θ', h⟩, swap, { by_contradiction, simpa only [add_le_iff_nonpos_right, nonpos_iff_eq_zero] using le_of_epi (epi_iff_surjective.mpr h), }, use i, haveI : mono (θ' ≫ δ i) := by { rw ← h, apply_instance, }, haveI := category_theory.mono_of_mono θ' (δ i), rw [h, eq_id_of_mono θ', category.id_comp], end end epi_mono /-- This functor `simplex_category ⥤ Cat` sends `[n]` (for `n : ℕ`) to the category attached to the ordered set `{0, 1, ..., n}` -/ @[simps obj map] def to_Cat : simplex_category ⥤ Cat.{0} := simplex_category.skeletal_functor ⋙ forget₂ NonemptyFinLinOrd LinearOrder ⋙ forget₂ LinearOrder Lattice ⋙ forget₂ Lattice PartialOrder ⋙ forget₂ PartialOrder Preorder ⋙ Preorder_to_Cat end simplex_category
96d28dc3f0256a236329793be159b74d90aff44d
43390109ab88557e6090f3245c47479c123ee500
/src/M3P14/pow_example.lean
028934524669f43563a9db4b63419148cef1f670
[ "Apache-2.0" ]
permissive
Ja1941/xena-UROP-2018
41f0956519f94d56b8bf6834a8d39473f4923200
b111fb87f343cf79eca3b886f99ee15c1dd9884b
refs/heads/master
1,662,355,955,139
1,590,577,325,000
1,590,577,325,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,116
lean
import xenalib.nat_stuff import chris_hughes_various.zmod /- Here is my memory of the situation Clara and Jason were faced with -/ --set_option pp.all true --set_option pp.notation false example (a : ℕ) (p : ℕ) [pos_nat p] (Hodd : 2 ∣ (p - 1)) (x : ℤ) (H1 : ↑(a ^ (p - 1)) - 1 ≡ 0 [ZMOD ↑p]) (H2 : x ≡ (↑a)^2 [ZMOD ↑p]) : x ^ ((p-1) / 2) ≡ 1 [ZMOD ↑p] := -- A mathematician would just say "substitute x = a^2 and we're done" -- Lean says "naturals aren't integers, and congruence is not equality, so no" -- I say "that's OK, we just explain to Lean exactly why things which are -- "obviously equal" are equal" begin rw nat.cast_pow' a 2 at H2, rw ←zmod.eq_iff_modeq_int at H2, -- H2 now an equality in the ring Z/pZ rw ←zmod.eq_iff_modeq_int, rw ←int.cast_pow, -- we can finally rewrite! rw H2, -- we now have to convince Lean that this is just H1 rw int.cast_pow, rw nat.cast_pow', rw nat.pow_pow, rw nat.mul_div (show 2 ≠ 0, from dec_trivial) Hodd, apply eq_of_sub_eq_zero, rw ←int.cast_sub, rw ←zmod.eq_iff_modeq_int at H1, exact H1 end
0ce01e3eae5ed3465436133e16d484678f3e0564
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/03_Propositions_and_Proofs.org.18.lean
e1ec21372a9ea77411a3e948d8c6c71232422505
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
173
lean
/- page 39 -/ import standard variables p q : Prop -- BEGIN example (Hp : p) (Hq : q) : p ∧ q := and.intro Hp Hq check assume (Hp : p) (Hq : q), and.intro Hp Hq -- END
13e35756b5a8b0409d45f226f9a2353f6f42cab4
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/algebra/category/CommRing/colimits.lean
ac5a048bf6356c27f23401b7a20e7834ee32ec8e
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
12,681
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 algebra.category.CommRing.basic /-! # The category of commutative rings has all colimits. This file uses a "pre-automated" approach, just as for `Mon/colimits.lean`. It is a very uniform approach, that conceivably could be synthesised directly by a tactic that analyses the shape of `comm_ring` and `ring_hom`. -/ universes u v open category_theory open category_theory.limits -- [ROBOT VOICE]: -- You should pretend for now that this file was automatically generated. -- It follows the same template as colimits in Mon. /- `#print comm_ring` says: structure comm_ring : Type u → Type u fields: comm_ring.zero : Π (α : Type u) [c : comm_ring α], α comm_ring.one : Π (α : Type u) [c : comm_ring α], α comm_ring.neg : Π {α : Type u} [c : comm_ring α], α → α comm_ring.add : Π {α : Type u} [c : comm_ring α], α → α → α comm_ring.mul : Π {α : Type u} [c : comm_ring α], α → α → α comm_ring.zero_add : ∀ {α : Type u} [c : comm_ring α] (a : α), 0 + a = a comm_ring.add_zero : ∀ {α : Type u} [c : comm_ring α] (a : α), a + 0 = a comm_ring.one_mul : ∀ {α : Type u} [c : comm_ring α] (a : α), 1 * a = a comm_ring.mul_one : ∀ {α : Type u} [c : comm_ring α] (a : α), a * 1 = a comm_ring.add_left_neg : ∀ {α : Type u} [c : comm_ring α] (a : α), -a + a = 0 comm_ring.add_comm : ∀ {α : Type u} [c : comm_ring α] (a b : α), a + b = b + a comm_ring.mul_comm : ∀ {α : Type u} [c : comm_ring α] (a b : α), a * b = b * a comm_ring.add_assoc : ∀ {α : Type u} [c : comm_ring α] (a b c_1 : α), a + b + c_1 = a + (b + c_1) comm_ring.mul_assoc : ∀ {α : Type u} [c : comm_ring α] (a b c_1 : α), a * b * c_1 = a * (b * c_1) comm_ring.left_distrib : ∀ {α : Type u} [c : comm_ring α] (a b c_1 : α), a * (b + c_1) = a * b + a * c_1 comm_ring.right_distrib : ∀ {α : Type u} [c : comm_ring α] (a b c_1 : α), (a + b) * c_1 = a * c_1 + b * c_1 -/ namespace CommRing.colimits /-! We build the colimit of a diagram in `CommRing` by constructing the free commutative ring on the disjoint union of all the commutative rings in the diagram, then taking the quotient by the commutative ring laws within each commutative ring, and the identifications given by the morphisms in the diagram. -/ variables {J : Type v} [small_category J] (F : J ⥤ CommRing.{v}) /-- An inductive type representing all commutative ring expressions (without relations) on a collection of types indexed by the objects of `J`. -/ inductive prequotient -- There's always `of` | of : Π (j : J) (x : F.obj j), prequotient -- Then one generator for each operation | zero : prequotient | one : prequotient | neg : prequotient → prequotient | add : prequotient → prequotient → prequotient | mul : prequotient → prequotient → prequotient instance : inhabited (prequotient F) := ⟨prequotient.zero⟩ open prequotient /-- The relation on `prequotient` saying when two expressions are equal because of the commutative ring laws, or because one element is mapped to another by a morphism in the diagram. -/ inductive relation : prequotient F → prequotient F → Prop -- Make it an equivalence relation: | refl : Π (x), relation x x | symm : Π (x y) (h : relation x y), relation y x | trans : Π (x y z) (h : relation x y) (k : relation y z), relation x z -- There's always a `map` relation | map : Π (j j' : J) (f : j ⟶ j') (x : F.obj j), relation (of j' (F.map f x)) (of j x) -- Then one relation per operation, describing the interaction with `of` | zero : Π (j), relation (of j 0) zero | one : Π (j), relation (of j 1) one | neg : Π (j) (x : F.obj j), relation (of j (-x)) (neg (of j x)) | add : Π (j) (x y : F.obj j), relation (of j (x + y)) (add (of j x) (of j y)) | mul : Π (j) (x y : F.obj j), relation (of j (x * y)) (mul (of j x) (of j y)) -- Then one relation per argument of each operation | neg_1 : Π (x x') (r : relation x x'), relation (neg x) (neg x') | add_1 : Π (x x' y) (r : relation x x'), relation (add x y) (add x' y) | add_2 : Π (x y y') (r : relation y y'), relation (add x y) (add x y') | mul_1 : Π (x x' y) (r : relation x x'), relation (mul x y) (mul x' y) | mul_2 : Π (x y y') (r : relation y y'), relation (mul x y) (mul x y') -- And one relation per axiom | zero_add : Π (x), relation (add zero x) x | add_zero : Π (x), relation (add x zero) x | one_mul : Π (x), relation (mul one x) x | mul_one : Π (x), relation (mul x one) x | add_left_neg : Π (x), relation (add (neg x) x) zero | add_comm : Π (x y), relation (add x y) (add y x) | mul_comm : Π (x y), relation (mul x y) (mul y x) | add_assoc : Π (x y z), relation (add (add x y) z) (add x (add y z)) | mul_assoc : Π (x y z), relation (mul (mul x y) z) (mul x (mul y z)) | left_distrib : Π (x y z), relation (mul x (add y z)) (add (mul x y) (mul x z)) | right_distrib : Π (x y z), relation (mul (add x y) z) (add (mul x z) (mul y z)) /-- The setoid corresponding to commutative expressions modulo monoid relations and identifications. -/ def colimit_setoid : setoid (prequotient F) := { r := relation F, iseqv := ⟨relation.refl, relation.symm, relation.trans⟩ } attribute [instance] colimit_setoid /-- The underlying type of the colimit of a diagram in `CommRing`. -/ @[derive inhabited] def colimit_type : Type v := quotient (colimit_setoid F) instance : comm_ring (colimit_type F) := { zero := begin exact quot.mk _ zero end, one := begin exact quot.mk _ one end, neg := begin fapply @quot.lift, { intro x, exact quot.mk _ (neg x) }, { intros x x' r, apply quot.sound, exact relation.neg_1 _ _ r }, end, add := begin fapply @quot.lift _ _ ((colimit_type F) → (colimit_type F)), { intro x, fapply @quot.lift, { intro y, exact quot.mk _ (add x y) }, { intros y y' r, apply quot.sound, exact relation.add_2 _ _ _ r } }, { intros x x' r, funext y, induction y, dsimp, apply quot.sound, { exact relation.add_1 _ _ _ r }, { refl } }, end, mul := begin fapply @quot.lift _ _ ((colimit_type F) → (colimit_type F)), { intro x, fapply @quot.lift, { intro y, exact quot.mk _ (mul x y) }, { intros y y' r, apply quot.sound, exact relation.mul_2 _ _ _ r } }, { intros x x' r, funext y, induction y, dsimp, apply quot.sound, { exact relation.mul_1 _ _ _ r }, { refl } }, end, zero_add := λ x, begin induction x, dsimp, apply quot.sound, apply relation.zero_add, refl, end, add_zero := λ x, begin induction x, dsimp, apply quot.sound, apply relation.add_zero, refl, end, one_mul := λ x, begin induction x, dsimp, apply quot.sound, apply relation.one_mul, refl, end, mul_one := λ x, begin induction x, dsimp, apply quot.sound, apply relation.mul_one, refl, end, add_left_neg := λ x, begin induction x, dsimp, apply quot.sound, apply relation.add_left_neg, refl, end, add_comm := λ x y, begin induction x, induction y, dsimp, apply quot.sound, apply relation.add_comm, refl, refl, end, mul_comm := λ x y, begin induction x, induction y, dsimp, apply quot.sound, apply relation.mul_comm, refl, refl, end, add_assoc := λ x y z, begin induction x, induction y, induction z, dsimp, apply quot.sound, apply relation.add_assoc, refl, refl, refl, end, mul_assoc := λ x y z, begin induction x, induction y, induction z, dsimp, apply quot.sound, apply relation.mul_assoc, refl, refl, refl, end, left_distrib := λ x y z, begin induction x, induction y, induction z, dsimp, apply quot.sound, apply relation.left_distrib, refl, refl, refl, end, right_distrib := λ x y z, begin induction x, induction y, induction z, dsimp, apply quot.sound, apply relation.right_distrib, refl, refl, refl, end, } @[simp] lemma quot_zero : quot.mk setoid.r zero = (0 : colimit_type F) := rfl @[simp] lemma quot_one : quot.mk setoid.r one = (1 : colimit_type F) := rfl @[simp] lemma quot_neg (x) : quot.mk setoid.r (neg x) = (-(quot.mk setoid.r x) : colimit_type F) := rfl @[simp] lemma quot_add (x y) : quot.mk setoid.r (add x y) = ((quot.mk setoid.r x) + (quot.mk setoid.r y) : colimit_type F) := rfl @[simp] lemma quot_mul (x y) : quot.mk setoid.r (mul x y) = ((quot.mk setoid.r x) * (quot.mk setoid.r y) : colimit_type F) := rfl /-- The bundled commutative ring giving the colimit of a diagram. -/ def colimit : CommRing := CommRing.of (colimit_type F) /-- The function from a given commutative ring in the diagram to the colimit commutative ring. -/ def cocone_fun (j : J) (x : F.obj j) : colimit_type F := quot.mk _ (of j x) /-- The ring homomorphism from a given commutative ring in the diagram to the colimit commutative ring. -/ def cocone_morphism (j : J) : F.obj j ⟶ colimit F := { to_fun := cocone_fun F j, map_one' := by apply quot.sound; apply relation.one, map_mul' := by intros; apply quot.sound; apply relation.mul, map_zero' := by apply quot.sound; apply relation.zero, map_add' := by intros; apply quot.sound; apply relation.add } @[simp] lemma cocone_naturality {j j' : J} (f : j ⟶ j') : F.map f ≫ (cocone_morphism F j') = cocone_morphism F j := begin ext, apply quot.sound, apply relation.map, end @[simp] lemma cocone_naturality_components (j j' : J) (f : j ⟶ j') (x : F.obj j): (cocone_morphism F j') (F.map f x) = (cocone_morphism F j) x := by { rw ←cocone_naturality F f, refl } /-- The cocone over the proposed colimit commutative ring. -/ def colimit_cocone : cocone F := { X := colimit F, ι := { app := cocone_morphism F } }. /-- The function from the free commutative ring on the diagram to the cone point of any other cocone. -/ @[simp] def desc_fun_lift (s : cocone F) : prequotient F → s.X | (of j x) := (s.ι.app j) x | zero := 0 | one := 1 | (neg x) := -(desc_fun_lift x) | (add x y) := desc_fun_lift x + desc_fun_lift y | (mul x y) := desc_fun_lift x * desc_fun_lift y /-- The function from the colimit commutative ring to the cone point of any other cocone. -/ def desc_fun (s : cocone F) : colimit_type F → s.X := begin fapply quot.lift, { exact desc_fun_lift F s }, { intros x y r, induction r; try { dsimp }, -- refl { refl }, -- symm { exact r_ih.symm }, -- trans { exact eq.trans r_ih_h r_ih_k }, -- map { simp, }, -- zero { simp, }, -- one { simp, }, -- neg { simp, }, -- add { simp, }, -- mul { simp, }, -- neg_1 { rw r_ih, }, -- add_1 { rw r_ih, }, -- add_2 { rw r_ih, }, -- mul_1 { rw r_ih, }, -- mul_2 { rw r_ih, }, -- zero_add { rw zero_add, }, -- add_zero { rw add_zero, }, -- one_mul { rw one_mul, }, -- mul_one { rw mul_one, }, -- add_left_neg { rw add_left_neg, }, -- add_comm { rw add_comm, }, -- mul_comm { rw mul_comm, }, -- add_assoc { rw add_assoc, }, -- mul_assoc { rw mul_assoc, }, -- left_distrib { rw left_distrib, }, -- right_distrib { rw right_distrib, }, } end /-- The ring homomorphism from the colimit commutative ring to the cone point of any other cocone. -/ def desc_morphism (s : cocone F) : colimit F ⟶ s.X := { to_fun := desc_fun F s, map_one' := rfl, map_zero' := rfl, map_add' := λ x y, by { induction x; induction y; refl }, map_mul' := λ x y, by { induction x; induction y; refl }, } /-- Evidence that the proposed colimit is the colimit. -/ def colimit_is_colimit : is_colimit (colimit_cocone F) := { desc := λ s, desc_morphism F s, uniq' := λ s m w, begin ext, induction x, induction x, { have w' := congr_fun (congr_arg (λ f : F.obj x_j ⟶ s.X, (f : F.obj x_j → s.X)) (w x_j)) x_x, erw w', refl, }, { simp, }, { simp, }, { simp *, }, { simp *, }, { simp *, }, refl end }. instance has_colimits_CommRing : has_colimits CommRing := { has_colimits_of_shape := λ J 𝒥, { has_colimit := λ F, by exactI { cocone := colimit_cocone F, is_colimit := colimit_is_colimit F } } } end CommRing.colimits
3bda59b5944b64b6b74273178ec71f8b523f95cd
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/07_Induction_and_Recursion.org.5.lean
77eb0fbaa1eec489a9b808eca6069cd4920abc0d
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
563
lean
/- page 101 -/ import standard import data.list open list definition tail {A : Type} : list A → list A | tail nil := nil | tail (h :: t) := t -- Parameter A may occur after ':' definition tail2 : Π {A : Type}, list A → list A | tail2 (@nil A) := (@nil A) | tail2 (h :: t) := t -- @ is allowed on the left-hand-side definition tail3 : Π {A : Type}, list A → list A | @tail3 A nil := nil | @tail3 A (h :: t) := t -- A is explicit parameter definition tail4 : Π (A : Type), list A → list A | tail4 A nil := nil | tail4 A (h :: t) := t
552111b73ebbd18d88987bcba67110e7859e5e6c
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/linear_algebra/determinant.lean
5c97a9a46f9dde6b5a793f2466ddc207e8b8781d
[ "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
22,603
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Patrick Massot, Casper Putz, Anne Baanen -/ import linear_algebra.multilinear.basis import linear_algebra.matrix.reindex import ring_theory.algebra_tower import tactic.field_simp import linear_algebra.matrix.nonsingular_inverse import linear_algebra.matrix.basis /-! # Determinant of families of vectors This file defines the determinant of an endomorphism, and of a family of vectors with respect to some basis. For the determinant of a matrix, see the file `linear_algebra.matrix.determinant`. ## Main definitions In the list below, and in all this file, `R` is a commutative ring (semiring is sometimes enough), `M` and its variations are `R`-modules, `ι`, `κ`, `n` and `m` are finite types used for indexing. * `basis.det`: the determinant of a family of vectors with respect to a basis, as a multilinear map * `linear_map.det`: the determinant of an endomorphism `f : End R M` as a multiplicative homomorphism (if `M` does not have a finite `R`-basis, the result is `1` instead) * `linear_equiv.det`: the determinant of an isomorphism `f : M ≃ₗ[R] M` as a multiplicative homomorphism (if `M` does not have a finite `R`-basis, the result is `1` instead) ## Tags basis, det, determinant -/ noncomputable theory open_locale big_operators open_locale matrix open linear_map open submodule universes u v w open linear_map matrix set function variables {R : Type*} [comm_ring R] variables {M : Type*} [add_comm_group M] [module R M] variables {M' : Type*} [add_comm_group M'] [module R M'] variables {ι : Type*} [decidable_eq ι] [fintype ι] variables (e : basis ι R M) section conjugate variables {A : Type*} [comm_ring A] variables {m n : Type*} [fintype m] [fintype n] /-- If `R^m` and `R^n` are linearly equivalent, then `m` and `n` are also equivalent. -/ def equiv_of_pi_lequiv_pi {R : Type*} [comm_ring R] [is_domain R] (e : (m → R) ≃ₗ[R] (n → R)) : m ≃ n := basis.index_equiv (basis.of_equiv_fun e.symm) (pi.basis_fun _ _) namespace matrix /-- If `M` and `M'` are each other's inverse matrices, they are square matrices up to equivalence of types. -/ def index_equiv_of_inv [is_domain A] [decidable_eq m] [decidable_eq n] {M : matrix m n A} {M' : matrix n m A} (hMM' : M ⬝ M' = 1) (hM'M : M' ⬝ M = 1) : m ≃ n := equiv_of_pi_lequiv_pi (to_lin'_of_inv hMM' hM'M) lemma det_comm [decidable_eq n] (M N : matrix n n A) : det (M ⬝ N) = det (N ⬝ M) := by rw [det_mul, det_mul, mul_comm] /-- If there exists a two-sided inverse `M'` for `M` (indexed differently), then `det (N ⬝ M) = det (M ⬝ N)`. -/ lemma det_comm' [is_domain A] [decidable_eq m] [decidable_eq n] {M : matrix n m A} {N : matrix m n A} {M' : matrix m n A} (hMM' : M ⬝ M' = 1) (hM'M : M' ⬝ M = 1) : det (M ⬝ N) = det (N ⬝ M) := -- Although `m` and `n` are different a priori, we will show they have the same cardinality. -- This turns the problem into one for square matrices, which is easy. let e := index_equiv_of_inv hMM' hM'M in by rw [← det_minor_equiv_self e, ← minor_mul_equiv _ _ _ (equiv.refl n) _, det_comm, minor_mul_equiv, equiv.coe_refl, minor_id_id] /-- If `M'` is a two-sided inverse for `M` (indexed differently), `det (M ⬝ N ⬝ M') = det N`. -/ lemma det_conj [is_domain A] [decidable_eq m] [decidable_eq n] {M : matrix m n A} {M' : matrix n m A} {N : matrix n n A} (hMM' : M ⬝ M' = 1) (hM'M : M' ⬝ M = 1) : det (M ⬝ N ⬝ M') = det N := by rw [← det_comm' hM'M hMM', ← matrix.mul_assoc, hM'M, matrix.one_mul] end matrix end conjugate namespace linear_map /-! ### Determinant of a linear map -/ variables {A : Type*} [comm_ring A] [is_domain A] [module A M] variables {κ : Type*} [fintype κ] /-- The determinant of `linear_map.to_matrix` does not depend on the choice of basis. -/ lemma det_to_matrix_eq_det_to_matrix [decidable_eq κ] (b : basis ι A M) (c : basis κ A M) (f : M →ₗ[A] M) : det (linear_map.to_matrix b b f) = det (linear_map.to_matrix c c f) := by rw [← linear_map_to_matrix_mul_basis_to_matrix c b c, ← basis_to_matrix_mul_linear_map_to_matrix b c b, matrix.det_conj]; rw [basis.to_matrix_mul_to_matrix, basis.to_matrix_self] /-- The determinant of an endomorphism given a basis. See `linear_map.det` for a version that populates the basis non-computably. Although the `trunc (basis ι A M)` parameter makes it slightly more convenient to switch bases, there is no good way to generalize over universe parameters, so we can't fully state in `det_aux`'s type that it does not depend on the choice of basis. Instead you can use the `det_aux_def'` lemma, or avoid mentioning a basis at all using `linear_map.det`. -/ def det_aux : trunc (basis ι A M) → (M →ₗ[A] M) →* A := trunc.lift (λ b : basis ι A M, (det_monoid_hom).comp (to_matrix_alg_equiv b : (M →ₗ[A] M) →* matrix ι ι A)) (λ b c, monoid_hom.ext $ det_to_matrix_eq_det_to_matrix b c) /-- Unfold lemma for `det_aux`. See also `det_aux_def'` which allows you to vary the basis. -/ lemma det_aux_def (b : basis ι A M) (f : M →ₗ[A] M) : linear_map.det_aux (trunc.mk b) f = matrix.det (linear_map.to_matrix b b f) := rfl -- Discourage the elaborator from unfolding `det_aux` and producing a huge term. attribute [irreducible] linear_map.det_aux lemma det_aux_def' {ι' : Type*} [fintype ι'] [decidable_eq ι'] (tb : trunc $ basis ι A M) (b' : basis ι' A M) (f : M →ₗ[A] M) : linear_map.det_aux tb f = matrix.det (linear_map.to_matrix b' b' f) := by { apply trunc.induction_on tb, intro b, rw [det_aux_def, det_to_matrix_eq_det_to_matrix b b'] } @[simp] lemma det_aux_id (b : trunc $ basis ι A M) : linear_map.det_aux b (linear_map.id) = 1 := (linear_map.det_aux b).map_one @[simp] lemma det_aux_comp (b : trunc $ basis ι A M) (f g : M →ₗ[A] M) : linear_map.det_aux b (f.comp g) = linear_map.det_aux b f * linear_map.det_aux b g := (linear_map.det_aux b).map_mul f g section open_locale classical -- Discourage the elaborator from unfolding `det` and producing a huge term by marking it -- as irreducible. /-- The determinant of an endomorphism independent of basis. If there is no finite basis on `M`, the result is `1` instead. -/ @[irreducible] protected def det : (M →ₗ[A] M) →* A := if H : ∃ (s : finset M), nonempty (basis s A M) then linear_map.det_aux (trunc.mk H.some_spec.some) else 1 lemma coe_det [decidable_eq M] : ⇑(linear_map.det : (M →ₗ[A] M) →* A) = if H : ∃ (s : finset M), nonempty (basis s A M) then linear_map.det_aux (trunc.mk H.some_spec.some) else 1 := by { ext, unfold linear_map.det, split_ifs, { congr }, -- use the correct `decidable_eq` instance refl } end -- Auxiliary lemma, the `simp` normal form goes in the other direction -- (using `linear_map.det_to_matrix`) lemma det_eq_det_to_matrix_of_finset [decidable_eq M] {s : finset M} (b : basis s A M) (f : M →ₗ[A] M) : f.det = matrix.det (linear_map.to_matrix b b f) := have ∃ (s : finset M), nonempty (basis s A M), from ⟨s, ⟨b⟩⟩, by rw [linear_map.coe_det, dif_pos, det_aux_def' _ b]; assumption @[simp] lemma det_to_matrix (b : basis ι A M) (f : M →ₗ[A] M) : matrix.det (to_matrix b b f) = f.det := by { haveI := classical.dec_eq M, rw [det_eq_det_to_matrix_of_finset b.reindex_finset_range, det_to_matrix_eq_det_to_matrix b] } @[simp] lemma det_to_matrix' {ι : Type*} [fintype ι] [decidable_eq ι] (f : (ι → A) →ₗ[A] (ι → A)) : det f.to_matrix' = f.det := by simp [← to_matrix_eq_to_matrix'] /-- To show `P f.det` it suffices to consider `P (to_matrix _ _ f).det` and `P 1`. -/ @[elab_as_eliminator] lemma det_cases [decidable_eq M] {P : A → Prop} (f : M →ₗ[A] M) (hb : ∀ (s : finset M) (b : basis s A M), P (to_matrix b b f).det) (h1 : P 1) : P f.det := begin unfold linear_map.det, split_ifs with h, { convert hb _ h.some_spec.some, apply det_aux_def' }, { exact h1 } end @[simp] lemma det_comp (f g : M →ₗ[A] M) : (f.comp g).det = f.det * g.det := linear_map.det.map_mul f g @[simp] lemma det_id : (linear_map.id : M →ₗ[A] M).det = 1 := linear_map.det.map_one /-- Multiplying a map by a scalar `c` multiplies its determinant by `c ^ dim M`. -/ @[simp] lemma det_smul {𝕜 : Type*} [field 𝕜] {M : Type*} [add_comm_group M] [module 𝕜 M] (c : 𝕜) (f : M →ₗ[𝕜] M) : linear_map.det (c • f) = c ^ (finite_dimensional.finrank 𝕜 M) * linear_map.det f := begin by_cases H : ∃ (s : finset M), nonempty (basis s 𝕜 M), { haveI : finite_dimensional 𝕜 M, { rcases H with ⟨s, ⟨hs⟩⟩, exact finite_dimensional.of_finset_basis hs }, simp only [← det_to_matrix (finite_dimensional.fin_basis 𝕜 M), linear_equiv.map_smul, fintype.card_fin, det_smul] }, { classical, have : finite_dimensional.finrank 𝕜 M = 0 := finrank_eq_zero_of_not_exists_basis H, simp [coe_det, H, this] } end lemma det_zero' {ι : Type*} [fintype ι] [nonempty ι] (b : basis ι A M) : linear_map.det (0 : M →ₗ[A] M) = 0 := by { haveI := classical.dec_eq ι, rw [← det_to_matrix b, linear_equiv.map_zero, det_zero], assumption } /-- In a finite-dimensional vector space, the zero map has determinant `1` in dimension `0`, and `0` otherwise. We give a formula that also works in infinite dimension, where we define the determinant to be `1`. -/ @[simp] lemma det_zero {𝕜 : Type*} [field 𝕜] {M : Type*} [add_comm_group M] [module 𝕜 M] : linear_map.det (0 : M →ₗ[𝕜] M) = (0 : 𝕜) ^ (finite_dimensional.finrank 𝕜 M) := by simp only [← zero_smul 𝕜 (1 : M →ₗ[𝕜] M), det_smul, mul_one, monoid_hom.map_one] /-- Conjugating a linear map by a linear equiv does not change its determinant. -/ @[simp] lemma det_conj {N : Type*} [add_comm_group N] [module A N] (f : M →ₗ[A] M) (e : M ≃ₗ[A] N) : linear_map.det ((e : M →ₗ[A] N) ∘ₗ (f ∘ₗ (e.symm : N →ₗ[A] M))) = linear_map.det f := begin classical, by_cases H : ∃ (s : finset M), nonempty (basis s A M), { rcases H with ⟨s, ⟨b⟩⟩, rw [← det_to_matrix b f, ← det_to_matrix (b.map e), to_matrix_comp (b.map e) b (b.map e), to_matrix_comp (b.map e) b b, ← matrix.mul_assoc, matrix.det_conj], { rw [← to_matrix_comp, linear_equiv.comp_coe, e.symm_trans_self, linear_equiv.refl_to_linear_map, to_matrix_id] }, { rw [← to_matrix_comp, linear_equiv.comp_coe, e.self_trans_symm, linear_equiv.refl_to_linear_map, to_matrix_id] } }, { have H' : ¬ (∃ (t : finset N), nonempty (basis t A N)), { contrapose! H, rcases H with ⟨s, ⟨b⟩⟩, exact ⟨_, ⟨(b.map e.symm).reindex_finset_range⟩⟩ }, simp only [coe_det, H, H', pi.one_apply, dif_neg, not_false_iff] } end /-- If a linear map is invertible, so is its determinant. -/ lemma is_unit_det {A : Type*} [comm_ring A] [is_domain A] [module A M] (f : M →ₗ[A] M) (hf : is_unit f) : is_unit f.det := begin obtain ⟨g, hg⟩ : ∃ g, f.comp g = 1 := hf.exists_right_inv, have : linear_map.det f * linear_map.det g = 1, by simp only [← linear_map.det_comp, hg, monoid_hom.map_one], exact is_unit_of_mul_eq_one _ _ this, end /-- If a linear map has determinant different from `1`, then the space is finite-dimensional. -/ lemma finite_dimensional_of_det_ne_one {𝕜 : Type*} [field 𝕜] [module 𝕜 M] (f : M →ₗ[𝕜] M) (hf : f.det ≠ 1) : finite_dimensional 𝕜 M := begin by_cases H : ∃ (s : finset M), nonempty (basis s 𝕜 M), { rcases H with ⟨s, ⟨hs⟩⟩, exact finite_dimensional.of_finset_basis hs }, { classical, simp [linear_map.coe_det, H] at hf, exact hf.elim } end /-- If the determinant of a map vanishes, then the map is not onto. -/ lemma range_lt_top_of_det_eq_zero {𝕜 : Type*} [field 𝕜] [module 𝕜 M] {f : M →ₗ[𝕜] M} (hf : f.det = 0) : f.range < ⊤ := begin haveI : finite_dimensional 𝕜 M, by simp [f.finite_dimensional_of_det_ne_one, hf], contrapose hf, simp only [lt_top_iff_ne_top, not_not, ← is_unit_iff_range_eq_top] at hf, exact is_unit_iff_ne_zero.1 (f.is_unit_det hf) end /-- If the determinant of a map vanishes, then the map is not injective. -/ lemma bot_lt_ker_of_det_eq_zero {𝕜 : Type*} [field 𝕜] [module 𝕜 M] {f : M →ₗ[𝕜] M} (hf : f.det = 0) : ⊥ < f.ker := begin haveI : finite_dimensional 𝕜 M, by simp [f.finite_dimensional_of_det_ne_one, hf], contrapose hf, simp only [bot_lt_iff_ne_bot, not_not, ← is_unit_iff_ker_eq_bot] at hf, exact is_unit_iff_ne_zero.1 (f.is_unit_det hf) end end linear_map namespace linear_equiv variables [is_domain R] /-- On a `linear_equiv`, the domain of `linear_map.det` can be promoted to `Rˣ`. -/ protected def det : (M ≃ₗ[R] M) →* Rˣ := (units.map (linear_map.det : (M →ₗ[R] M) →* R)).comp (linear_map.general_linear_group.general_linear_equiv R M).symm.to_monoid_hom @[simp] lemma coe_det (f : M ≃ₗ[R] M) : ↑f.det = linear_map.det (f : M →ₗ[R] M) := rfl @[simp] lemma coe_inv_det (f : M ≃ₗ[R] M) : ↑(f.det⁻¹) = linear_map.det (f.symm : M →ₗ[R] M) := rfl @[simp] lemma det_refl : (linear_equiv.refl R M).det = 1 := units.ext $ linear_map.det_id @[simp] lemma det_trans (f g : M ≃ₗ[R] M) : (f.trans g).det = g.det * f.det := map_mul _ g f @[simp] lemma det_symm (f : M ≃ₗ[R] M) : f.symm.det = f.det⁻¹ := map_inv _ f /-- Conjugating a linear equiv by a linear equiv does not change its determinant. -/ @[simp] lemma det_conj (f : M ≃ₗ[R] M) (e : M ≃ₗ[R] M') : ((e.symm.trans f).trans e).det = f.det := by rw [←units.eq_iff, coe_det, coe_det, ←comp_coe, ←comp_coe, linear_map.det_conj] end linear_equiv /-- The determinants of a `linear_equiv` and its inverse multiply to 1. -/ @[simp] lemma linear_equiv.det_mul_det_symm {A : Type*} [comm_ring A] [is_domain A] [module A M] (f : M ≃ₗ[A] M) : (f : M →ₗ[A] M).det * (f.symm : M →ₗ[A] M).det = 1 := by simp [←linear_map.det_comp] /-- The determinants of a `linear_equiv` and its inverse multiply to 1. -/ @[simp] lemma linear_equiv.det_symm_mul_det {A : Type*} [comm_ring A] [is_domain A] [module A M] (f : M ≃ₗ[A] M) : (f.symm : M →ₗ[A] M).det * (f : M →ₗ[A] M).det = 1 := by simp [←linear_map.det_comp] -- Cannot be stated using `linear_map.det` because `f` is not an endomorphism. lemma linear_equiv.is_unit_det (f : M ≃ₗ[R] M') (v : basis ι R M) (v' : basis ι R M') : is_unit (linear_map.to_matrix v v' f).det := begin apply is_unit_det_of_left_inverse, simpa using (linear_map.to_matrix_comp v v' v f.symm f).symm end /-- Specialization of `linear_equiv.is_unit_det` -/ lemma linear_equiv.is_unit_det' {A : Type*} [comm_ring A] [is_domain A] [module A M] (f : M ≃ₗ[A] M) : is_unit (linear_map.det (f : M →ₗ[A] M)) := is_unit_of_mul_eq_one _ _ f.det_mul_det_symm /-- The determinant of `f.symm` is the inverse of that of `f` when `f` is a linear equiv. -/ lemma linear_equiv.det_coe_symm {𝕜 : Type*} [field 𝕜] [module 𝕜 M] (f : M ≃ₗ[𝕜] M) : (f.symm : M →ₗ[𝕜] M).det = (f : M →ₗ[𝕜] M).det ⁻¹ := by field_simp [is_unit.ne_zero f.is_unit_det'] /-- Builds a linear equivalence from a linear map whose determinant in some bases is a unit. -/ @[simps] def linear_equiv.of_is_unit_det {f : M →ₗ[R] M'} {v : basis ι R M} {v' : basis ι R M'} (h : is_unit (linear_map.to_matrix v v' f).det) : M ≃ₗ[R] M' := { to_fun := f, map_add' := f.map_add, map_smul' := f.map_smul, inv_fun := to_lin v' v (to_matrix v v' f)⁻¹, left_inv := λ x, calc to_lin v' v (to_matrix v v' f)⁻¹ (f x) = to_lin v v ((to_matrix v v' f)⁻¹ ⬝ to_matrix v v' f) x : by { rw [to_lin_mul v v' v, to_lin_to_matrix, linear_map.comp_apply] } ... = x : by simp [h], right_inv := λ x, calc f (to_lin v' v (to_matrix v v' f)⁻¹ x) = to_lin v' v' (to_matrix v v' f ⬝ (to_matrix v v' f)⁻¹) x : by { rw [to_lin_mul v' v v', linear_map.comp_apply, to_lin_to_matrix v v'] } ... = x : by simp [h] } @[simp] lemma linear_equiv.coe_of_is_unit_det {f : M →ₗ[R] M'} {v : basis ι R M} {v' : basis ι R M'} (h : is_unit (linear_map.to_matrix v v' f).det) : (linear_equiv.of_is_unit_det h : M →ₗ[R] M') = f := by { ext x, refl } /-- Builds a linear equivalence from a linear map on a finite-dimensional vector space whose determinant is nonzero. -/ @[reducible] def linear_map.equiv_of_det_ne_zero {𝕜 : Type*} [field 𝕜] {M : Type*} [add_comm_group M] [module 𝕜 M] [finite_dimensional 𝕜 M] (f : M →ₗ[𝕜] M) (hf : linear_map.det f ≠ 0) : M ≃ₗ[𝕜] M := have is_unit (linear_map.to_matrix (finite_dimensional.fin_basis 𝕜 M) (finite_dimensional.fin_basis 𝕜 M) f).det := by simp only [linear_map.det_to_matrix, is_unit_iff_ne_zero.2 hf], linear_equiv.of_is_unit_det this /-- The determinant of a family of vectors with respect to some basis, as an alternating multilinear map. -/ def basis.det : alternating_map R M R ι := { to_fun := λ v, det (e.to_matrix v), map_add' := begin intros v i x y, simp only [e.to_matrix_update, linear_equiv.map_add], apply det_update_column_add end, map_smul' := begin intros u i c x, simp only [e.to_matrix_update, algebra.id.smul_eq_mul, linear_equiv.map_smul], apply det_update_column_smul end, map_eq_zero_of_eq' := begin intros v i j h hij, rw [←function.update_eq_self i v, h, ←det_transpose, e.to_matrix_update, ←update_row_transpose, ←e.to_matrix_transpose_apply], apply det_zero_of_row_eq hij, rw [update_row_ne hij.symm, update_row_self], end } lemma basis.det_apply (v : ι → M) : e.det v = det (e.to_matrix v) := rfl lemma basis.det_self : e.det e = 1 := by simp [e.det_apply] /-- `basis.det` is not the zero map. -/ lemma basis.det_ne_zero [nontrivial R] : e.det ≠ 0 := λ h, by simpa [h] using e.det_self lemma is_basis_iff_det {v : ι → M} : linear_independent R v ∧ span R (set.range v) = ⊤ ↔ is_unit (e.det v) := begin split, { rintro ⟨hli, hspan⟩, set v' := basis.mk hli hspan with v'_eq, rw e.det_apply, convert linear_equiv.is_unit_det (linear_equiv.refl _ _) v' e using 2, ext i j, simp }, { intro h, rw [basis.det_apply, basis.to_matrix_eq_to_matrix_constr] at h, set v' := basis.map e (linear_equiv.of_is_unit_det h) with v'_def, have : ⇑ v' = v, { ext i, rw [v'_def, basis.map_apply, linear_equiv.of_is_unit_det_apply, e.constr_basis] }, rw ← this, exact ⟨v'.linear_independent, v'.span_eq⟩ }, end lemma basis.is_unit_det (e' : basis ι R M) : is_unit (e.det e') := (is_basis_iff_det e).mp ⟨e'.linear_independent, e'.span_eq⟩ /-- Any alternating map to `R` where `ι` has the cardinality of a basis equals the determinant map with respect to that basis, multiplied by the value of that alternating map on that basis. -/ lemma alternating_map.eq_smul_basis_det (f : alternating_map R M R ι) : f = f e • e.det := begin refine basis.ext_alternating e (λ i h, _), let σ : equiv.perm ι := equiv.of_bijective i (fintype.injective_iff_bijective.1 h), change f (e ∘ σ) = (f e • e.det) (e ∘ σ), simp [alternating_map.map_perm, basis.det_self] end @[simp] lemma alternating_map.map_basis_eq_zero_iff (f : alternating_map R M R ι) : f e = 0 ↔ f = 0 := ⟨λ h, by simpa [h] using f.eq_smul_basis_det e, λ h, h.symm ▸ alternating_map.zero_apply _⟩ lemma alternating_map.map_basis_ne_zero_iff (f : alternating_map R M R ι) : f e ≠ 0 ↔ f ≠ 0 := not_congr $ f.map_basis_eq_zero_iff e variables {A : Type*} [comm_ring A] [is_domain A] [module A M] @[simp] lemma basis.det_comp (e : basis ι A M) (f : M →ₗ[A] M) (v : ι → M) : e.det (f ∘ v) = f.det * e.det v := by { rw [basis.det_apply, basis.det_apply, ← f.det_to_matrix e, ← matrix.det_mul, e.to_matrix_eq_to_matrix_constr (f ∘ v), e.to_matrix_eq_to_matrix_constr v, ← to_matrix_comp, e.constr_comp] } lemma basis.det_reindex {ι' : Type*} [fintype ι'] [decidable_eq ι'] (b : basis ι R M) (v : ι' → M) (e : ι ≃ ι') : (b.reindex e).det v = b.det (v ∘ e) := by rw [basis.det_apply, basis.to_matrix_reindex', det_reindex_alg_equiv, basis.det_apply] lemma basis.det_reindex_symm {ι' : Type*} [fintype ι'] [decidable_eq ι'] (b : basis ι R M) (v : ι → M) (e : ι' ≃ ι) : (b.reindex e.symm).det (v ∘ e) = b.det v := by rw [basis.det_reindex, function.comp.assoc, e.self_comp_symm, function.comp.right_id] @[simp] lemma basis.det_map (b : basis ι R M) (f : M ≃ₗ[R] M') (v : ι → M') : (b.map f).det v = b.det (f.symm ∘ v) := by { rw [basis.det_apply, basis.to_matrix_map, basis.det_apply] } lemma basis.det_map' (b : basis ι R M) (f : M ≃ₗ[R] M') : (b.map f).det = b.det.comp_linear_map f.symm := alternating_map.ext $ b.det_map f @[simp] lemma pi.basis_fun_det : (pi.basis_fun R ι).det = matrix.det_row_alternating := begin ext M, rw [basis.det_apply, basis.coe_pi_basis_fun.to_matrix_eq_transpose, det_transpose], end /-- If we fix a background basis `e`, then for any other basis `v`, we can characterise the coordinates provided by `v` in terms of determinants relative to `e`. -/ lemma basis.det_smul_mk_coord_eq_det_update {v : ι → M} (hli : linear_independent R v) (hsp : span R (range v) = ⊤) (i : ι) : (e.det v) • (basis.mk hli hsp).coord i = e.det.to_multilinear_map.to_linear_map v i := begin apply (basis.mk hli hsp).ext, intros k, rcases eq_or_ne k i with rfl | hik; simp only [algebra.id.smul_eq_mul, basis.coe_mk, linear_map.smul_apply, linear_map.coe_mk, multilinear_map.to_linear_map_apply], { rw [basis.mk_coord_apply_eq, mul_one, update_eq_self], congr, }, { rw [basis.mk_coord_apply_ne hik, mul_zero, eq_comm], exact e.det.map_eq_zero_of_eq _ (by simp [hik, function.update_apply]) hik, }, end /-- The determinant of a basis constructed by `units_smul` is the product of the given units. -/ @[simp] lemma basis.det_units_smul (w : ι → Rˣ) : e.det (e.units_smul w) = ∏ i, w i := by simp [basis.det_apply] /-- The determinant of a basis constructed by `is_unit_smul` is the product of the given units. -/ @[simp] lemma basis.det_is_unit_smul {w : ι → R} (hw : ∀ i, is_unit (w i)) : e.det (e.is_unit_smul hw) = ∏ i, w i := e.det_units_smul _
9c868055e72a195ea762befdca1e1214c4c93b9f
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/G_delta.lean
623a07f49f51c9c308d26e2551f221cc44872214
[]
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,550
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.metric_space.emetric_space import Mathlib.PostPort universes u_1 u_4 u_2 namespace Mathlib /-! # `Gδ` sets In this file we define `Gδ` sets and prove their basic properties. ## Main definitions * `is_Gδ`: a set `s` is a `Gδ` set if it can be represented as an intersection of countably many open sets; * `residual`: the filter of residual sets. A set `s` is called *residual* if it includes a dense `Gδ` set. In a Baire space (e.g., in a complete (e)metric space), residual sets form a filter. For technical reasons, we define `residual` in any topological space but the definition agrees with the description above only in Baire spaces. ## Main results We prove that finite or countable intersections of Gδ sets is a Gδ set. We also prove that the continuity set of a function from a topological space to an (e)metric space is a Gδ set. ## Tags Gδ set, residual set -/ /-- A Gδ set is a countable intersection of open sets. -/ def is_Gδ {α : Type u_1} [topological_space α] (s : set α) := ∃ (T : set (set α)), (∀ (t : set α), t ∈ T → is_open t) ∧ set.countable T ∧ s = ⋂₀T /-- An open set is a Gδ set. -/ theorem is_open.is_Gδ {α : Type u_1} [topological_space α] {s : set α} (h : is_open s) : is_Gδ s := sorry theorem is_Gδ_univ {α : Type u_1} [topological_space α] : is_Gδ set.univ := is_open.is_Gδ is_open_univ theorem is_Gδ_bInter_of_open {α : Type u_1} {ι : Type u_4} [topological_space α] {I : set ι} (hI : set.countable I) {f : ι → set α} (hf : ∀ (i : ι), i ∈ I → is_open (f i)) : is_Gδ (set.Inter fun (i : ι) => set.Inter fun (H : i ∈ I) => f i) := sorry theorem is_Gδ_Inter_of_open {α : Type u_1} {ι : Type u_4} [topological_space α] [encodable ι] {f : ι → set α} (hf : ∀ (i : ι), is_open (f i)) : is_Gδ (set.Inter fun (i : ι) => f i) := sorry /-- A countable intersection of Gδ sets is a Gδ set. -/ theorem is_Gδ_sInter {α : Type u_1} [topological_space α] {S : set (set α)} (h : ∀ (s : set α), s ∈ S → is_Gδ s) (hS : set.countable S) : is_Gδ (⋂₀S) := sorry theorem is_Gδ_Inter {α : Type u_1} {ι : Type u_4} [topological_space α] [encodable ι] {s : ι → set α} (hs : ∀ (i : ι), is_Gδ (s i)) : is_Gδ (set.Inter fun (i : ι) => s i) := is_Gδ_sInter (iff.mpr set.forall_range_iff hs) (set.countable_range s) theorem is_Gδ_bInter {α : Type u_1} {ι : Type u_4} [topological_space α] {s : set ι} (hs : set.countable s) {t : (i : ι) → i ∈ s → set α} (ht : ∀ (i : ι) (H : i ∈ s), is_Gδ (t i H)) : is_Gδ (set.Inter fun (i : ι) => set.Inter fun (H : i ∈ s) => t i H) := sorry theorem is_Gδ.inter {α : Type u_1} [topological_space α] {s : set α} {t : set α} (hs : is_Gδ s) (ht : is_Gδ t) : is_Gδ (s ∩ t) := eq.mpr (id (Eq._oldrec (Eq.refl (is_Gδ (s ∩ t))) set.inter_eq_Inter)) (is_Gδ_Inter (iff.mpr bool.forall_bool { left := ht, right := hs })) /-- The union of two Gδ sets is a Gδ set. -/ theorem is_Gδ.union {α : Type u_1} [topological_space α] {s : set α} {t : set α} (hs : is_Gδ s) (ht : is_Gδ t) : is_Gδ (s ∪ t) := sorry theorem is_Gδ_set_of_continuous_at_of_countably_generated_uniformity {α : Type u_1} {β : Type u_2} [topological_space α] [uniform_space β] (hU : filter.is_countably_generated (uniformity β)) (f : α → β) : is_Gδ (set_of fun (x : α) => continuous_at f x) := sorry /-- The set of points where a function is continuous is a Gδ set. -/ theorem is_Gδ_set_of_continuous_at {α : Type u_1} {β : Type u_2} [topological_space α] [emetric_space β] (f : α → β) : is_Gδ (set_of fun (x : α) => continuous_at f x) := is_Gδ_set_of_continuous_at_of_countably_generated_uniformity emetric.uniformity_has_countable_basis f /-- A set `s` is called *residual* if it includes a dense `Gδ` set. If `α` is a Baire space (e.g., a complete metric space), then residual sets form a filter, see `mem_residual`. For technical reasons we define the filter `residual` in any topological space but in a non-Baire space it is not useful because it may contain some non-residual sets. -/ def residual (α : Type u_1) [topological_space α] : filter α := infi fun (t : set α) => infi fun (ht : is_Gδ t) => infi fun (ht' : dense t) => filter.principal t
19ee784cf1f0ba64f104de832fb3d1a920eb4f36
1fd908b06e3f9c1252cb2285ada1102623a67f72
/algebra/Group.lean
273c35ea4dd20514e0b4c14c3974e53b478f76f0
[ "Apache-2.0" ]
permissive
avigad/hott3
609a002849182721e7c7ae536d9f1e2956d6d4d3
f64750cd2de7a81e87d4828246d1369d59f16f43
refs/heads/master
1,629,027,243,322
1,510,946,717,000
1,510,946,717,000
103,570,461
0
0
null
1,505,415,620,000
1,505,415,620,000
null
UTF-8
Lean
false
false
1,220
lean
/- Copyright (c) 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad -/ import ..init .classes .group universes u v w hott_theory namespace hott /- section Groups: move -/ structure Group := (carrier : Type u) (op : carrier → carrier → carrier) (id : carrier) (inv : carrier → carrier) (is_group : is_group carrier op id inv) instance has_coe_to_sort_Group : has_coe_to_sort Group := ⟨Type u, λ G : Group.{u}, G.carrier⟩ instance is_group_Group (G : Group) : is_group (G.carrier) (G.op) (G.id) (G.inv) := G.is_group @[simp] def Group_right_inv (G : Group) := is_right_inv.right_inv (G.op) (G.inv) (G.id) section variable G : Group variables a b c : G local infix * := G.op local notation 1 := G.id local postfix ⁻¹ := G.inv /- doesn't need the underscores in the classical library-/ example : a * a⁻¹ * b = b := begin rwr [is_right_inv.right_inv (G.op) _ _, is_left_id.left_id (G.op) _ _ ] end --example : a * a⁻¹ * b = b := --begin -- rwr [Group_right_inv, Group_left_id] --end /- works in classical library example : a * a⁻¹ * b = b := by simp -/ end end hott
a6e499a84140b3ee49acdc3244328e4a7c7ccfa1
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/analysis/normed_space/basic.lean
121ac64fc285131f07348fbaaeafab2e04f40993
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
45,823
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl -/ import topology.instances.nnreal import topology.instances.complex import topology.algebra.module import topology.metric_space.antilipschitz /-! # Normed spaces -/ variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*} noncomputable theory open filter metric open_locale topological_space big_operators localized "notation f `→_{`:50 a `}`:0 b := filter.tendsto f (_root_.nhds a) (_root_.nhds b)" in filter /-- Auxiliary class, endowing a type `α` with a function `norm : α → ℝ`. This class is designed to be extended in more interesting classes specifying the properties of the norm. -/ class has_norm (α : Type*) := (norm : α → ℝ) export has_norm (norm) notation `∥`:1024 e:1 `∥`:1 := norm e section prio set_option default_priority 100 -- see Note [default priority] /-- A normed group is an additive group endowed with a norm for which `dist x y = ∥x - y∥` defines a metric space structure. -/ class normed_group (α : Type*) extends has_norm α, add_comm_group α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) end prio /-- Construct a normed group from a translation invariant distance -/ def normed_group.of_add_dist [has_norm α] [add_comm_group α] [metric_space α] (H1 : ∀ x:α, ∥x∥ = dist x 0) (H2 : ∀ x y z : α, dist x y ≤ dist (x + z) (y + z)) : normed_group α := { dist_eq := λ x y, begin rw H1, apply le_antisymm, { rw [sub_eq_add_neg, ← add_right_neg y], apply H2 }, { have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this } end } /-- Construct a normed group from a translation invariant distance -/ def normed_group.of_add_dist' [has_norm α] [add_comm_group α] [metric_space α] (H1 : ∀ x:α, ∥x∥ = dist x 0) (H2 : ∀ x y z : α, dist (x + z) (y + z) ≤ dist x y) : normed_group α := { dist_eq := λ x y, begin rw H1, apply le_antisymm, { have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this }, { rw [sub_eq_add_neg, ← add_right_neg y], apply H2 } end } /-- A normed group can be built from a norm that satisfies algebraic properties. This is formalised in this structure. -/ structure normed_group.core (α : Type*) [add_comm_group α] [has_norm α] : Prop := (norm_eq_zero_iff : ∀ x : α, ∥x∥ = 0 ↔ x = 0) (triangle : ∀ x y : α, ∥x + y∥ ≤ ∥x∥ + ∥y∥) (norm_neg : ∀ x : α, ∥-x∥ = ∥x∥) /-- Constructing a normed group from core properties of a norm, i.e., registering the distance and the metric space structure from the norm properties. -/ noncomputable def normed_group.of_core (α : Type*) [add_comm_group α] [has_norm α] (C : normed_group.core α) : normed_group α := { dist := λ x y, ∥x - y∥, dist_eq := assume x y, by refl, dist_self := assume x, (C.norm_eq_zero_iff (x - x)).mpr (show x - x = 0, by simp), eq_of_dist_eq_zero := assume x y h, show (x = y), from sub_eq_zero.mp $ (C.norm_eq_zero_iff (x - y)).mp h, dist_triangle := assume x y z, calc ∥x - z∥ = ∥x - y + (y - z)∥ : by rw sub_add_sub_cancel ... ≤ ∥x - y∥ + ∥y - z∥ : C.triangle _ _, dist_comm := assume x y, calc ∥x - y∥ = ∥ -(y - x)∥ : by simp ... = ∥y - x∥ : by { rw [C.norm_neg] } } section normed_group variables [normed_group α] [normed_group β] lemma dist_eq_norm (g h : α) : dist g h = ∥g - h∥ := normed_group.dist_eq _ _ @[simp] lemma dist_zero_right (g : α) : dist g 0 = ∥g∥ := by rw [dist_eq_norm, sub_zero] lemma norm_sub_rev (g h : α) : ∥g - h∥ = ∥h - g∥ := by simpa only [dist_eq_norm] using dist_comm g h @[simp] lemma norm_neg (g : α) : ∥-g∥ = ∥g∥ := by simpa using norm_sub_rev 0 g @[simp] lemma dist_add_left (g h₁ h₂ : α) : dist (g + h₁) (g + h₂) = dist h₁ h₂ := by simp [dist_eq_norm] @[simp] lemma dist_add_right (g₁ g₂ h : α) : dist (g₁ + h) (g₂ + h) = dist g₁ g₂ := by simp [dist_eq_norm] @[simp] lemma dist_neg_neg (g h : α) : dist (-g) (-h) = dist g h := by simp only [dist_eq_norm, neg_sub_neg, norm_sub_rev] @[simp] lemma dist_sub_left (g h₁ h₂ : α) : dist (g - h₁) (g - h₂) = dist h₁ h₂ := by simp only [sub_eq_add_neg, dist_add_left, dist_neg_neg] @[simp] lemma dist_sub_right (g₁ g₂ h : α) : dist (g₁ - h) (g₂ - h) = dist g₁ g₂ := dist_add_right _ _ _ /-- Triangle inequality for the norm. -/ lemma norm_add_le (g h : α) : ∥g + h∥ ≤ ∥g∥ + ∥h∥ := by simpa [dist_eq_norm] using dist_triangle g 0 (-h) lemma norm_add_le_of_le {g₁ g₂ : α} {n₁ n₂ : ℝ} (H₁ : ∥g₁∥ ≤ n₁) (H₂ : ∥g₂∥ ≤ n₂) : ∥g₁ + g₂∥ ≤ n₁ + n₂ := le_trans (norm_add_le g₁ g₂) (add_le_add H₁ H₂) lemma dist_add_add_le (g₁ g₂ h₁ h₂ : α) : dist (g₁ + g₂) (h₁ + h₂) ≤ dist g₁ h₁ + dist g₂ h₂ := by simpa only [dist_add_left, dist_add_right] using dist_triangle (g₁ + g₂) (h₁ + g₂) (h₁ + h₂) lemma dist_add_add_le_of_le {g₁ g₂ h₁ h₂ : α} {d₁ d₂ : ℝ} (H₁ : dist g₁ h₁ ≤ d₁) (H₂ : dist g₂ h₂ ≤ d₂) : dist (g₁ + g₂) (h₁ + h₂) ≤ d₁ + d₂ := le_trans (dist_add_add_le g₁ g₂ h₁ h₂) (add_le_add H₁ H₂) lemma dist_sub_sub_le (g₁ g₂ h₁ h₂ : α) : dist (g₁ - g₂) (h₁ - h₂) ≤ dist g₁ h₁ + dist g₂ h₂ := dist_neg_neg g₂ h₂ ▸ dist_add_add_le _ _ _ _ lemma dist_sub_sub_le_of_le {g₁ g₂ h₁ h₂ : α} {d₁ d₂ : ℝ} (H₁ : dist g₁ h₁ ≤ d₁) (H₂ : dist g₂ h₂ ≤ d₂) : dist (g₁ - g₂) (h₁ - h₂) ≤ d₁ + d₂ := le_trans (dist_sub_sub_le g₁ g₂ h₁ h₂) (add_le_add H₁ H₂) lemma abs_dist_sub_le_dist_add_add (g₁ g₂ h₁ h₂ : α) : abs (dist g₁ h₁ - dist g₂ h₂) ≤ dist (g₁ + g₂) (h₁ + h₂) := by simpa only [dist_add_left, dist_add_right, dist_comm h₂] using abs_dist_sub_le (g₁ + g₂) (h₁ + h₂) (h₁ + g₂) @[simp] lemma norm_nonneg (g : α) : 0 ≤ ∥g∥ := by { rw[←dist_zero_right], exact dist_nonneg } lemma norm_eq_zero {g : α} : ∥g∥ = 0 ↔ g = 0 := dist_zero_right g ▸ dist_eq_zero @[simp] lemma norm_zero : ∥(0:α)∥ = 0 := norm_eq_zero.2 rfl lemma norm_sum_le {β} : ∀(s : finset β) (f : β → α), ∥s.sum f∥ ≤ s.sum (λa, ∥ f a ∥) := finset.le_sum_of_subadditive norm norm_zero norm_add_le lemma norm_sum_le_of_le {β} (s : finset β) {f : β → α} {n : β → ℝ} (h : ∀ b ∈ s, ∥f b∥ ≤ n b) : ∥s.sum f∥ ≤ s.sum n := by { haveI := classical.dec_eq β, exact le_trans (norm_sum_le s f) (finset.sum_le_sum h) } lemma norm_pos_iff {g : α} : 0 < ∥ g ∥ ↔ g ≠ 0 := dist_zero_right g ▸ dist_pos lemma norm_le_zero_iff {g : α} : ∥g∥ ≤ 0 ↔ g = 0 := by { rw[←dist_zero_right], exact dist_le_zero } lemma norm_sub_le (g h : α) : ∥g - h∥ ≤ ∥g∥ + ∥h∥ := by simpa [dist_eq_norm] using dist_triangle g 0 h lemma norm_sub_le_of_le {g₁ g₂ : α} {n₁ n₂ : ℝ} (H₁ : ∥g₁∥ ≤ n₁) (H₂ : ∥g₂∥ ≤ n₂) : ∥g₁ - g₂∥ ≤ n₁ + n₂ := le_trans (norm_sub_le g₁ g₂) (add_le_add H₁ H₂) lemma dist_le_norm_add_norm (g h : α) : dist g h ≤ ∥g∥ + ∥h∥ := by { rw dist_eq_norm, apply norm_sub_le } lemma abs_norm_sub_norm_le (g h : α) : abs(∥g∥ - ∥h∥) ≤ ∥g - h∥ := by simpa [dist_eq_norm] using abs_dist_sub_le g h 0 lemma norm_sub_norm_le (g h : α) : ∥g∥ - ∥h∥ ≤ ∥g - h∥ := le_trans (le_abs_self _) (abs_norm_sub_norm_le g h) lemma dist_norm_norm_le (g h : α) : dist ∥g∥ ∥h∥ ≤ ∥g - h∥ := abs_norm_sub_norm_le g h lemma ball_0_eq (ε : ℝ) : ball (0:α) ε = {x | ∥x∥ < ε} := set.ext $ assume a, by simp lemma norm_le_of_mem_closed_ball {g h : α} {r : ℝ} (H : h ∈ closed_ball g r) : ∥h∥ ≤ ∥g∥ + r := calc ∥h∥ = ∥g + (h - g)∥ : by rw [add_sub_cancel'_right] ... ≤ ∥g∥ + ∥h - g∥ : norm_add_le _ _ ... ≤ ∥g∥ + r : by { apply add_le_add_left, rw ← dist_eq_norm, exact H } lemma norm_lt_of_mem_ball {g h : α} {r : ℝ} (H : h ∈ ball g r) : ∥h∥ < ∥g∥ + r := calc ∥h∥ = ∥g + (h - g)∥ : by rw [add_sub_cancel'_right] ... ≤ ∥g∥ + ∥h - g∥ : norm_add_le _ _ ... < ∥g∥ + r : by { apply add_lt_add_left, rw ← dist_eq_norm, exact H } theorem normed_group.tendsto_nhds_zero {f : γ → α} {l : filter γ} : tendsto f l (𝓝 0) ↔ ∀ ε > 0, ∀ᶠ x in l, ∥ f x ∥ < ε := metric.tendsto_nhds.trans $ by simp only [dist_zero_right] section nnnorm /-- Version of the norm taking values in nonnegative reals. -/ def nnnorm (a : α) : nnreal := ⟨norm a, norm_nonneg a⟩ @[simp] lemma coe_nnnorm (a : α) : (nnnorm a : ℝ) = norm a := rfl lemma nndist_eq_nnnorm (a b : α) : nndist a b = nnnorm (a - b) := nnreal.eq $ dist_eq_norm _ _ lemma nnnorm_eq_zero {a : α} : nnnorm a = 0 ↔ a = 0 := by simp only [nnreal.eq_iff.symm, nnreal.coe_zero, coe_nnnorm, norm_eq_zero] @[simp] lemma nnnorm_zero : nnnorm (0 : α) = 0 := nnreal.eq norm_zero lemma nnnorm_add_le (g h : α) : nnnorm (g + h) ≤ nnnorm g + nnnorm h := nnreal.coe_le_coe.2 $ norm_add_le g h @[simp] lemma nnnorm_neg (g : α) : nnnorm (-g) = nnnorm g := nnreal.eq $ norm_neg g lemma nndist_nnnorm_nnnorm_le (g h : α) : nndist (nnnorm g) (nnnorm h) ≤ nnnorm (g - h) := nnreal.coe_le_coe.2 $ dist_norm_norm_le g h lemma of_real_norm_eq_coe_nnnorm (x : β) : ennreal.of_real ∥x∥ = (nnnorm x : ennreal) := ennreal.of_real_eq_coe_nnreal _ lemma edist_eq_coe_nnnorm_sub (x y : β) : edist x y = (nnnorm (x - y) : ennreal) := by rw [edist_dist, dist_eq_norm, of_real_norm_eq_coe_nnnorm] lemma edist_eq_coe_nnnorm (x : β) : edist x 0 = (nnnorm x : ennreal) := by rw [edist_eq_coe_nnnorm_sub, _root_.sub_zero] lemma nndist_add_add_le (g₁ g₂ h₁ h₂ : α) : nndist (g₁ + g₂) (h₁ + h₂) ≤ nndist g₁ h₁ + nndist g₂ h₂ := nnreal.coe_le_coe.2 $ dist_add_add_le g₁ g₂ h₁ h₂ lemma edist_add_add_le (g₁ g₂ h₁ h₂ : α) : edist (g₁ + g₂) (h₁ + h₂) ≤ edist g₁ h₁ + edist g₂ h₂ := by { simp only [edist_nndist], norm_cast, apply nndist_add_add_le } lemma nnnorm_sum_le {β} : ∀(s : finset β) (f : β → α), nnnorm (s.sum f) ≤ s.sum (λa, nnnorm (f a)) := finset.le_sum_of_subadditive nnnorm nnnorm_zero nnnorm_add_le end nnnorm lemma lipschitz_with.neg {α : Type*} [emetric_space α] {K : nnreal} {f : α → β} (hf : lipschitz_with K f) : lipschitz_with K (λ x, -f x) := λ x y, by simpa only [edist_dist, dist_neg_neg] using hf x y lemma lipschitz_with.add {α : Type*} [emetric_space α] {Kf : nnreal} {f : α → β} (hf : lipschitz_with Kf f) {Kg : nnreal} {g : α → β} (hg : lipschitz_with Kg g) : lipschitz_with (Kf + Kg) (λ x, f x + g x) := λ x y, calc edist (f x + g x) (f y + g y) ≤ edist (f x) (f y) + edist (g x) (g y) : edist_add_add_le _ _ _ _ ... ≤ Kf * edist x y + Kg * edist x y : add_le_add' (hf x y) (hg x y) ... = (Kf + Kg) * edist x y : (add_mul _ _ _).symm lemma lipschitz_with.sub {α : Type*} [emetric_space α] {Kf : nnreal} {f : α → β} (hf : lipschitz_with Kf f) {Kg : nnreal} {g : α → β} (hg : lipschitz_with Kg g) : lipschitz_with (Kf + Kg) (λ x, f x - g x) := hf.add hg.neg lemma antilipschitz_with.add_lipschitz_with {α : Type*} [metric_space α] {Kf : nnreal} {f : α → β} (hf : antilipschitz_with Kf f) {Kg : nnreal} {g : α → β} (hg : lipschitz_with Kg g) (hK : Kg < Kf⁻¹) : antilipschitz_with (Kf⁻¹ - Kg)⁻¹ (λ x, f x + g x) := begin refine antilipschitz_with.of_le_mul_dist (λ x y, _), rw [nnreal.coe_inv, ← div_eq_inv_mul], apply le_div_of_mul_le (nnreal.coe_pos.2 $ nnreal.sub_pos.2 hK), rw [mul_comm, nnreal.coe_sub (le_of_lt hK), sub_mul], calc ↑Kf⁻¹ * dist x y - Kg * dist x y ≤ dist (f x) (f y) - dist (g x) (g y) : sub_le_sub (hf.mul_le_dist x y) (hg.dist_le_mul x y) ... ≤ _ : le_trans (le_abs_self _) (abs_dist_sub_le_dist_add_add _ _ _ _) end /-- A submodule of a normed group is also a normed group, with the restriction of the norm. As all instances can be inferred from the submodule `s`, they are put as implicit instead of typeclasses. -/ instance submodule.normed_group {𝕜 : Type*} {_ : ring 𝕜} {E : Type*} [normed_group E] {_ : module 𝕜 E} (s : submodule 𝕜 E) : normed_group s := { norm := λx, norm (x : E), dist_eq := λx y, dist_eq_norm (x : E) (y : E) } /-- normed group instance on the product of two normed groups, using the sup norm. -/ instance prod.normed_group : normed_group (α × β) := { norm := λx, max ∥x.1∥ ∥x.2∥, dist_eq := assume (x y : α × β), show max (dist x.1 y.1) (dist x.2 y.2) = (max ∥(x - y).1∥ ∥(x - y).2∥), by simp [dist_eq_norm] } lemma prod.norm_def (x : α × β) : ∥x∥ = (max ∥x.1∥ ∥x.2∥) := rfl lemma norm_fst_le (x : α × β) : ∥x.1∥ ≤ ∥x∥ := le_max_left _ _ lemma norm_snd_le (x : α × β) : ∥x.2∥ ≤ ∥x∥ := le_max_right _ _ lemma norm_prod_le_iff {x : α × β} {r : ℝ} : ∥x∥ ≤ r ↔ ∥x.1∥ ≤ r ∧ ∥x.2∥ ≤ r := max_le_iff /-- normed group instance on the product of finitely many normed groups, using the sup norm. -/ instance pi.normed_group {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] : normed_group (Πi, π i) := { norm := λf, ((finset.sup finset.univ (λ b, nnnorm (f b)) : nnreal) : ℝ), dist_eq := assume x y, congr_arg (coe : nnreal → ℝ) $ congr_arg (finset.sup finset.univ) $ funext $ assume a, show nndist (x a) (y a) = nnnorm (x a - y a), from nndist_eq_nnnorm _ _ } /-- The norm of an element in a product space is `≤ r` if and only if the norm of each component is. -/ lemma pi_norm_le_iff {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] {r : ℝ} (hr : 0 ≤ r) {x : Πi, π i} : ∥x∥ ≤ r ↔ ∀i, ∥x i∥ ≤ r := by { simp only [(dist_zero_right _).symm, dist_pi_le_iff hr], refl } lemma norm_le_pi_norm {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] (x : Πi, π i) (i : ι) : ∥x i∥ ≤ ∥x∥ := (pi_norm_le_iff (norm_nonneg x)).1 (le_refl _) i lemma tendsto_iff_norm_tendsto_zero {f : ι → β} {a : filter ι} {b : β} : tendsto f a (𝓝 b) ↔ tendsto (λ e, ∥ f e - b ∥) a (𝓝 0) := by rw tendsto_iff_dist_tendsto_zero ; simp only [(dist_eq_norm _ _).symm] lemma tendsto_zero_iff_norm_tendsto_zero {f : γ → β} {a : filter γ} : tendsto f a (𝓝 0) ↔ tendsto (λ e, ∥ f e ∥) a (𝓝 0) := have tendsto f a (𝓝 0) ↔ tendsto (λ e, ∥ f e - 0 ∥) a (𝓝 0) := tendsto_iff_norm_tendsto_zero, by simpa lemma lim_norm (x : α) : (λg:α, ∥g - x∥) →_{x} 0 := tendsto_iff_norm_tendsto_zero.1 (continuous_iff_continuous_at.1 continuous_id x) lemma lim_norm_zero : (λg:α, ∥g∥) →_{0} 0 := by simpa using lim_norm (0:α) lemma continuous_norm : continuous (λg:α, ∥g∥) := begin rw continuous_iff_continuous_at, intro x, rw [continuous_at, tendsto_iff_dist_tendsto_zero], exact squeeze_zero (λ t, abs_nonneg _) (λ t, abs_norm_sub_norm_le _ _) (lim_norm x) end lemma filter.tendsto.norm {β : Type*} {l : filter β} {f : β → α} {a : α} (h : tendsto f l (𝓝 a)) : tendsto (λ x, ∥f x∥) l (𝓝 ∥a∥) := tendsto.comp continuous_norm.continuous_at h lemma continuous_nnnorm : continuous (nnnorm : α → nnreal) := continuous_subtype_mk _ continuous_norm lemma filter.tendsto.nnnorm {β : Type*} {l : filter β} {f : β → α} {a : α} (h : tendsto f l (𝓝 a)) : tendsto (λ x, nnnorm (f x)) l (𝓝 (nnnorm a)) := tendsto.comp continuous_nnnorm.continuous_at h /-- If `∥y∥→∞`, then we can assume `y≠x` for any fixed `x`. -/ lemma eventually_ne_of_tendsto_norm_at_top {l : filter γ} {f : γ → α} (h : tendsto (λ y, ∥f y∥) l at_top) (x : α) : ∀ᶠ y in l, f y ≠ x := begin have : ∀ᶠ y in l, 1 + ∥x∥ ≤ ∥f y∥ := h (mem_at_top (1 + ∥x∥)), refine this.mono (λ y hy hxy, _), subst x, exact not_le_of_lt zero_lt_one (add_le_iff_nonpos_left.1 hy) end /-- A normed group is a uniform additive group, i.e., addition and subtraction are uniformly continuous. -/ @[priority 100] -- see Note [lower instance priority] instance normed_uniform_group : uniform_add_group α := begin refine ⟨metric.uniform_continuous_iff.2 $ assume ε hε, ⟨ε / 2, half_pos hε, assume a b h, _⟩⟩, rw [prod.dist_eq, max_lt_iff, dist_eq_norm, dist_eq_norm] at h, calc dist (a.1 - a.2) (b.1 - b.2) = ∥(a.1 - b.1) - (a.2 - b.2)∥ : by simp [dist_eq_norm, sub_eq_add_neg]; abel ... ≤ ∥a.1 - b.1∥ + ∥a.2 - b.2∥ : norm_sub_le _ _ ... < ε / 2 + ε / 2 : add_lt_add h.1 h.2 ... = ε : add_halves _ end @[priority 100] -- see Note [lower instance priority] instance normed_top_monoid : topological_add_monoid α := by apply_instance -- short-circuit type class inference @[priority 100] -- see Note [lower instance priority] instance normed_top_group : topological_add_group α := by apply_instance -- short-circuit type class inference end normed_group section normed_ring section prio set_option default_priority 100 -- see Note [default priority] /-- A normed ring is a ring endowed with a norm which satisfies the inequality `∥x y∥ ≤ ∥x∥ ∥y∥`. -/ class normed_ring (α : Type*) extends has_norm α, ring α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul : ∀ a b, norm (a * b) ≤ norm a * norm b) end prio @[priority 100] -- see Note [lower instance priority] instance normed_ring.to_normed_group [β : normed_ring α] : normed_group α := { ..β } lemma norm_mul_le {α : Type*} [normed_ring α] (a b : α) : (∥a*b∥) ≤ (∥a∥) * (∥b∥) := normed_ring.norm_mul _ _ lemma norm_pow_le {α : Type*} [normed_ring α] (a : α) : ∀ {n : ℕ}, 0 < n → ∥a^n∥ ≤ ∥a∥^n | 1 h := by simp | (n+2) h := le_trans (norm_mul_le a (a^(n+1))) (mul_le_mul (le_refl _) (norm_pow_le (nat.succ_pos _)) (norm_nonneg _) (norm_nonneg _)) /-- Normed ring structure on the product of two normed rings, using the sup norm. -/ instance prod.normed_ring [normed_ring α] [normed_ring β] : normed_ring (α × β) := { norm_mul := assume x y, calc ∥x * y∥ = ∥(x.1*y.1, x.2*y.2)∥ : rfl ... = (max ∥x.1*y.1∥ ∥x.2*y.2∥) : rfl ... ≤ (max (∥x.1∥*∥y.1∥) (∥x.2∥*∥y.2∥)) : max_le_max (norm_mul_le (x.1) (y.1)) (norm_mul_le (x.2) (y.2)) ... = (max (∥x.1∥*∥y.1∥) (∥y.2∥*∥x.2∥)) : by simp[mul_comm] ... ≤ (max (∥x.1∥) (∥x.2∥)) * (max (∥y.2∥) (∥y.1∥)) : by { apply max_mul_mul_le_max_mul_max; simp [norm_nonneg] } ... = (max (∥x.1∥) (∥x.2∥)) * (max (∥y.1∥) (∥y.2∥)) : by simp[max_comm] ... = (∥x∥*∥y∥) : rfl, ..prod.normed_group } end normed_ring @[priority 100] -- see Note [lower instance priority] instance normed_ring_top_monoid [normed_ring α] : topological_monoid α := ⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $ have ∀ e : α × α, e.fst * e.snd - x.fst * x.snd = e.fst * e.snd - e.fst * x.snd + (e.fst * x.snd - x.fst * x.snd), by intro; rw sub_add_sub_cancel, begin apply squeeze_zero, { intro, apply norm_nonneg }, { simp only [this], intro, apply norm_add_le }, { rw ←zero_add (0 : ℝ), apply tendsto.add, { apply squeeze_zero, { intro, apply norm_nonneg }, { intro t, show ∥t.fst * t.snd - t.fst * x.snd∥ ≤ ∥t.fst∥ * ∥t.snd - x.snd∥, rw ←mul_sub, apply norm_mul_le }, { rw ←mul_zero (∥x.fst∥), apply tendsto.mul, { apply continuous_iff_continuous_at.1, apply continuous_norm.comp continuous_fst }, { apply tendsto_iff_norm_tendsto_zero.1, apply continuous_iff_continuous_at.1, apply continuous_snd }}}, { apply squeeze_zero, { intro, apply norm_nonneg }, { intro t, show ∥t.fst * x.snd - x.fst * x.snd∥ ≤ ∥t.fst - x.fst∥ * ∥x.snd∥, rw ←sub_mul, apply norm_mul_le }, { rw ←zero_mul (∥x.snd∥), apply tendsto.mul, { apply tendsto_iff_norm_tendsto_zero.1, apply continuous_iff_continuous_at.1, apply continuous_fst }, { apply tendsto_const_nhds }}}} end ⟩ /-- A normed ring is a topological ring. -/ @[priority 100] -- see Note [lower instance priority] instance normed_top_ring [normed_ring α] : topological_ring α := ⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $ have ∀ e : α, -e - -x = -(e - x), by intro; simp, by simp only [this, norm_neg]; apply lim_norm ⟩ section prio set_option default_priority 100 -- see Note [default priority] /-- A normed field is a field with a norm satisfying ∥x y∥ = ∥x∥ ∥y∥. -/ class normed_field (α : Type*) extends has_norm α, field α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul' : ∀ a b, norm (a * b) = norm a * norm b) /-- A nondiscrete normed field is a normed field in which there is an element of norm different from `0` and `1`. This makes it possible to bring any element arbitrarily close to `0` by multiplication by the powers of any element, and thus to relate algebra and topology. -/ class nondiscrete_normed_field (α : Type*) extends normed_field α := (non_trivial : ∃x:α, 1<∥x∥) end prio @[priority 100] -- see Note [lower instance priority] instance normed_field.to_normed_ring [i : normed_field α] : normed_ring α := { norm_mul := by finish [i.norm_mul'], ..i } namespace normed_field @[simp] lemma norm_one {α : Type*} [normed_field α] : ∥(1 : α)∥ = 1 := have ∥(1 : α)∥ * ∥(1 : α)∥ = ∥(1 : α)∥ * 1, by calc ∥(1 : α)∥ * ∥(1 : α)∥ = ∥(1 : α) * (1 : α)∥ : by rw normed_field.norm_mul' ... = ∥(1 : α)∥ * 1 : by simp, eq_of_mul_eq_mul_left (ne_of_gt (norm_pos_iff.2 (by simp))) this @[simp] lemma norm_mul [normed_field α] (a b : α) : ∥a * b∥ = ∥a∥ * ∥b∥ := normed_field.norm_mul' a b instance normed_field.is_monoid_hom_norm [normed_field α] : is_monoid_hom (norm : α → ℝ) := { map_one := norm_one, map_mul := norm_mul } @[simp] lemma norm_pow [normed_field α] (a : α) : ∀ (n : ℕ), ∥a^n∥ = ∥a∥^n := is_monoid_hom.map_pow norm a @[simp] lemma norm_prod {β : Type*} [normed_field α] (s : finset β) (f : β → α) : ∥s.prod f∥ = s.prod (λb, ∥f b∥) := eq.symm (s.prod_hom norm) @[simp] lemma norm_div {α : Type*} [normed_field α] (a b : α) : ∥a/b∥ = ∥a∥/∥b∥ := begin classical, by_cases hb : b = 0, {simp [hb]}, apply eq_div_of_mul_eq, { apply ne_of_gt, apply norm_pos_iff.mpr hb }, { rw [←normed_field.norm_mul, div_mul_cancel _ hb] } end @[simp] lemma norm_inv {α : Type*} [normed_field α] (a : α) : ∥a⁻¹∥ = ∥a∥⁻¹ := by simp only [inv_eq_one_div, norm_div, norm_one] @[simp] lemma norm_fpow {α : Type*} [normed_field α] (a : α) : ∀n : ℤ, ∥a^n∥ = ∥a∥^n | (n : ℕ) := norm_pow a n | -[1+ n] := by simp [fpow_neg_succ_of_nat] lemma exists_one_lt_norm (α : Type*) [i : nondiscrete_normed_field α] : ∃x : α, 1 < ∥x∥ := i.non_trivial lemma exists_norm_lt_one (α : Type*) [nondiscrete_normed_field α] : ∃x : α, 0 < ∥x∥ ∧ ∥x∥ < 1 := begin rcases exists_one_lt_norm α with ⟨y, hy⟩, refine ⟨y⁻¹, _, _⟩, { simp only [inv_eq_zero, ne.def, norm_pos_iff], assume h, rw ← norm_eq_zero at h, rw h at hy, exact lt_irrefl _ (lt_trans zero_lt_one hy) }, { simp [inv_lt_one hy] } end lemma exists_lt_norm (α : Type*) [nondiscrete_normed_field α] (r : ℝ) : ∃ x : α, r < ∥x∥ := let ⟨w, hw⟩ := exists_one_lt_norm α in let ⟨n, hn⟩ := pow_unbounded_of_one_lt r hw in ⟨w^n, by rwa norm_pow⟩ lemma exists_norm_lt (α : Type*) [nondiscrete_normed_field α] {r : ℝ} (hr : 0 < r) : ∃ x : α, 0 < ∥x∥ ∧ ∥x∥ < r := let ⟨w, hw⟩ := exists_one_lt_norm α in let ⟨n, hle, hlt⟩ := exists_int_pow_near' hr hw in ⟨w^n, by { rw norm_fpow; exact fpow_pos_of_pos (lt_trans zero_lt_one hw) _}, by rwa norm_fpow⟩ lemma punctured_nhds_ne_bot {α : Type*} [nondiscrete_normed_field α] (x : α) : nhds_within x (-{x}) ≠ ⊥ := begin rw [← mem_closure_iff_nhds_within_ne_bot, metric.mem_closure_iff], rintros ε ε0, rcases normed_field.exists_norm_lt α ε0 with ⟨b, hb0, hbε⟩, refine ⟨x + b, mt (set.mem_singleton_iff.trans add_right_eq_self).1 $ norm_pos_iff.1 hb0, _⟩, rwa [dist_comm, dist_eq_norm, add_sub_cancel'], end lemma tendsto_inv [normed_field α] {r : α} (r0 : r ≠ 0) : tendsto (λq, q⁻¹) (𝓝 r) (𝓝 r⁻¹) := begin refine (nhds_basis_closed_ball.tendsto_iff nhds_basis_closed_ball).2 (λε εpos, _), let δ := min (ε/2 * ∥r∥^2) (∥r∥/2), have norm_r_pos : 0 < ∥r∥ := norm_pos_iff.mpr r0, have A : 0 < ε / 2 * ∥r∥ ^ 2 := mul_pos' (half_pos εpos) (pow_pos norm_r_pos 2), have δpos : 0 < δ, by simp [half_pos norm_r_pos, A], refine ⟨δ, δpos, λ x hx, _⟩, have rx : ∥r∥/2 ≤ ∥x∥ := calc ∥r∥/2 = ∥r∥ - ∥r∥/2 : by ring ... ≤ ∥r∥ - ∥r - x∥ : begin apply sub_le_sub (le_refl _), rw [← dist_eq_norm, dist_comm], exact le_trans hx (min_le_right _ _) end ... ≤ ∥r - (r - x)∥ : norm_sub_norm_le r (r - x) ... = ∥x∥ : by simp [sub_sub_cancel], have norm_x_pos : 0 < ∥x∥ := lt_of_lt_of_le (half_pos norm_r_pos) rx, have : x⁻¹ - r⁻¹ = (r - x) * x⁻¹ * r⁻¹, by rw [sub_mul, sub_mul, mul_inv_cancel (norm_pos_iff.mp norm_x_pos), one_mul, mul_comm, ← mul_assoc, inv_mul_cancel r0, one_mul], calc dist x⁻¹ r⁻¹ = ∥x⁻¹ - r⁻¹∥ : dist_eq_norm _ _ ... ≤ ∥r-x∥ * ∥x∥⁻¹ * ∥r∥⁻¹ : by rw [this, norm_mul, norm_mul, norm_inv, norm_inv] ... ≤ (ε/2 * ∥r∥^2) * (2 * ∥r∥⁻¹) * (∥r∥⁻¹) : begin apply_rules [mul_le_mul, inv_nonneg.2, le_of_lt A, norm_nonneg, inv_nonneg.2, mul_nonneg, (inv_le_inv norm_x_pos norm_r_pos).2, le_refl], show ∥r - x∥ ≤ ε / 2 * ∥r∥ ^ 2, by { rw [← dist_eq_norm, dist_comm], exact le_trans hx (min_le_left _ _) }, show ∥x∥⁻¹ ≤ 2 * ∥r∥⁻¹, { convert (inv_le_inv norm_x_pos (half_pos norm_r_pos)).2 rx, rw [inv_div, div_eq_inv_mul, mul_comm] }, show (0 : ℝ) ≤ 2, by norm_num end ... = ε * (∥r∥ * ∥r∥⁻¹)^2 : by { generalize : ∥r∥⁻¹ = u, ring } ... = ε : by { rw [mul_inv_cancel (ne.symm (ne_of_lt norm_r_pos))], simp } end lemma continuous_on_inv [normed_field α] : continuous_on (λ(x:α), x⁻¹) {x | x ≠ 0} := begin assume x hx, apply continuous_at.continuous_within_at, exact (tendsto_inv hx) end instance : normed_field ℝ := { norm := λ x, abs x, dist_eq := assume x y, rfl, norm_mul' := abs_mul } instance : nondiscrete_normed_field ℝ := { non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ } end normed_field /-- If a function converges to a nonzero value, its inverse converges to the inverse of this value. We use the name `tendsto.inv'` as `tendsto.inv` is already used in multiplicative topological groups. -/ lemma filter.tendsto.inv' [normed_field α] {l : filter β} {f : β → α} {y : α} (hy : y ≠ 0) (h : tendsto f l (𝓝 y)) : tendsto (λx, (f x)⁻¹) l (𝓝 y⁻¹) := (normed_field.tendsto_inv hy).comp h lemma filter.tendsto.div [normed_field α] {l : filter β} {f g : β → α} {x y : α} (hf : tendsto f l (𝓝 x)) (hg : tendsto g l (𝓝 y)) (hy : y ≠ 0) : tendsto (λa, f a / g a) l (𝓝 (x / y)) := hf.mul (hg.inv' hy) lemma filter.tendsto.div_const [normed_field α] {l : filter β} {f : β → α} {x y : α} (hf : tendsto f l (𝓝 x)) : tendsto (λa, f a / y) l (𝓝 (x / y)) := by { simp only [div_eq_inv_mul], exact tendsto_const_nhds.mul hf } /-- Continuity at a point of the result of dividing two functions continuous at that point, where the denominator is nonzero. -/ lemma continuous_at.div [topological_space α] [normed_field β] {f : α → β} {g : α → β} {x : α} (hf : continuous_at f x) (hg : continuous_at g x) (hnz : g x ≠ 0) : continuous_at (λ x, f x / g x) x := hf.div hg hnz lemma real.norm_eq_abs (r : ℝ) : norm r = abs r := rfl @[simp] lemma real.norm_two : ∥(2:ℝ)∥ = 2 := abs_of_pos (@two_pos ℝ _) @[simp] lemma norm_norm [normed_group α] (x : α) : ∥∥x∥∥ = ∥x∥ := by rw [real.norm_eq_abs, abs_of_nonneg (norm_nonneg _)] @[simp] lemma nnnorm_norm [normed_group α] (a : α) : nnnorm ∥a∥ = nnnorm a := by simp only [nnnorm, norm_norm] instance : normed_ring ℤ := { norm := λ n, ∥(n : ℝ)∥, norm_mul := λ m n, le_of_eq $ by simp only [norm, int.cast_mul, abs_mul], dist_eq := λ m n, by simp only [int.dist_eq, norm, int.cast_sub] } @[norm_cast] lemma int.norm_cast_real (m : ℤ) : ∥(m : ℝ)∥ = ∥m∥ := rfl instance : normed_field ℚ := { norm := λ r, ∥(r : ℝ)∥, norm_mul' := λ r₁ r₂, by simp only [norm, rat.cast_mul, abs_mul], dist_eq := λ r₁ r₂, by simp only [rat.dist_eq, norm, rat.cast_sub] } instance : nondiscrete_normed_field ℚ := { non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ } @[norm_cast, simp] lemma rat.norm_cast_real (r : ℚ) : ∥(r : ℝ)∥ = ∥r∥ := rfl @[norm_cast, simp] lemma int.norm_cast_rat (m : ℤ) : ∥(m : ℚ)∥ = ∥m∥ := by rw [← rat.norm_cast_real, ← int.norm_cast_real]; congr' 1; norm_cast section normed_space section prio set_option default_priority 100 -- see Note [default priority] -- see Note[vector space definition] for why we extend `module`. /-- A normed space over a normed field is a vector space endowed with a norm which satisfies the equality `∥c • x∥ = ∥c∥ ∥x∥`. We require only `∥c • x∥ ≤ ∥c∥ ∥x∥` in the definition, then prove `∥c • x∥ = ∥c∥ ∥x∥` in `norm_smul`. -/ class normed_space (α : Type*) (β : Type*) [normed_field α] [normed_group β] extends module α β := (norm_smul_le : ∀ (a:α) (b:β), ∥a • b∥ ≤ ∥a∥ * ∥b∥) end prio variables [normed_field α] [normed_group β] instance normed_field.to_normed_space : normed_space α α := { norm_smul_le := λ a b, le_of_eq (normed_field.norm_mul a b) } lemma norm_smul [normed_space α β] (s : α) (x : β) : ∥s • x∥ = ∥s∥ * ∥x∥ := begin classical, by_cases h : s = 0, { simp [h] }, { refine le_antisymm (normed_space.norm_smul_le s x) _, calc ∥s∥ * ∥x∥ = ∥s∥ * ∥s⁻¹ • s • x∥ : by rw [inv_smul_smul' h] ... ≤ ∥s∥ * (∥s⁻¹∥ * ∥s • x∥) : _ ... = ∥s • x∥ : _, exact mul_le_mul_of_nonneg_left (normed_space.norm_smul_le _ _) (norm_nonneg _), rw [normed_field.norm_inv, ← mul_assoc, mul_inv_cancel, one_mul], rwa [ne.def, norm_eq_zero] } end lemma dist_smul [normed_space α β] (s : α) (x y : β) : dist (s • x) (s • y) = ∥s∥ * dist x y := by simp only [dist_eq_norm, (norm_smul _ _).symm, smul_sub] lemma nnnorm_smul [normed_space α β] (s : α) (x : β) : nnnorm (s • x) = nnnorm s * nnnorm x := nnreal.eq $ norm_smul s x lemma nndist_smul [normed_space α β] (s : α) (x y : β) : nndist (s • x) (s • y) = nnnorm s * nndist x y := nnreal.eq $ dist_smul s x y variables {E : Type*} {F : Type*} [normed_group E] [normed_space α E] [normed_group F] [normed_space α F] @[priority 100] -- see Note [lower instance priority] instance normed_space.topological_vector_space : topological_vector_space α E := begin refine { continuous_smul := continuous_iff_continuous_at.2 $ λ p, tendsto_iff_norm_tendsto_zero.2 _ }, refine squeeze_zero (λ _, norm_nonneg _) _ _, { exact λ q, ∥q.1 - p.1∥ * ∥q.2∥ + ∥p.1∥ * ∥q.2 - p.2∥ }, { intro q, rw [← sub_add_sub_cancel, ← norm_smul, ← norm_smul, smul_sub, sub_smul], exact norm_add_le _ _ }, { conv { congr, skip, skip, congr, rw [← zero_add (0:ℝ)], congr, rw [← zero_mul ∥p.2∥], skip, rw [← mul_zero ∥p.1∥] }, exact ((tendsto_iff_norm_tendsto_zero.1 (continuous_fst.tendsto p)).mul (continuous_snd.tendsto p).norm).add (tendsto_const_nhds.mul (tendsto_iff_norm_tendsto_zero.1 (continuous_snd.tendsto p))) } end /-- In a normed space over a nondiscrete normed field, only `⊤` submodule has a nonempty interior. See also `submodule.eq_top_of_nonempty_interior'` for a `topological_module` version. -/ lemma submodule.eq_top_of_nonempty_interior {α E : Type*} [nondiscrete_normed_field α] [normed_group E] [normed_space α E] (s : submodule α E) (hs : (interior (s:set E)).nonempty) : s = ⊤ := begin refine s.eq_top_of_nonempty_interior' _ hs, simp only [is_unit_iff_ne_zero, @ne.def α, set.mem_singleton_iff.symm], exact normed_field.punctured_nhds_ne_bot _ end theorem closure_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : closure (ball x r) = closed_ball x r := begin refine set.subset.antisymm closure_ball_subset_closed_ball (λ y hy, _), have : continuous_within_at (λ c : ℝ, c • (y - x) + x) (set.Ico 0 1) 1 := ((continuous_id.smul continuous_const).add continuous_const).continuous_within_at, convert this.mem_closure _ _, { rw [one_smul, sub_add_cancel] }, { simp [closure_Ico (@zero_lt_one ℝ _), zero_le_one] }, { rintros c ⟨hc0, hc1⟩, rw [set.mem_preimage, mem_ball, dist_eq_norm, add_sub_cancel, norm_smul, real.norm_eq_abs, abs_of_nonneg hc0, mul_comm, ← mul_one r], rw [mem_closed_ball, dist_eq_norm] at hy, apply mul_lt_mul'; assumption } end theorem frontier_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : frontier (ball x r) = sphere x r := begin rw [frontier, closure_ball x hr, interior_eq_of_open is_open_ball], ext x, exact (@eq_iff_le_not_lt ℝ _ _ _).symm end theorem interior_closed_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : interior (closed_ball x r) = ball x r := begin refine set.subset.antisymm _ ball_subset_interior_closed_ball, intros y hy, rcases le_iff_lt_or_eq.1 (mem_closed_ball.1 $ interior_subset hy) with hr|rfl, { exact hr }, set f : ℝ → E := λ c : ℝ, c • (y - x) + x, suffices : f ⁻¹' closed_ball x (dist y x) ⊆ set.Icc (-1) 1, { have hfc : continuous f := (continuous_id.smul continuous_const).add continuous_const, have hf1 : (1:ℝ) ∈ f ⁻¹' (interior (closed_ball x $ dist y x)), by simpa [f], have h1 : (1:ℝ) ∈ interior (set.Icc (-1:ℝ) 1) := interior_mono this (preimage_interior_subset_interior_preimage hfc hf1), contrapose h1, simp }, intros c hc, rw [set.mem_Icc, ← abs_le, ← real.norm_eq_abs, ← mul_le_mul_right hr], simpa [f, dist_eq_norm, norm_smul] using hc end theorem interior_closed_ball' [normed_space ℝ E] (x : E) (r : ℝ) (hE : ∃ z : E, z ≠ 0) : interior (closed_ball x r) = ball x r := begin rcases lt_trichotomy r 0 with hr|rfl|hr, { simp [closed_ball_eq_empty_iff_neg.2 hr, ball_eq_empty_iff_nonpos.2 (le_of_lt hr)] }, { suffices : x ∉ interior {x}, { rw [ball_zero, closed_ball_zero, ← set.subset_empty_iff], intros y hy, obtain rfl : y = x := set.mem_singleton_iff.1 (interior_subset hy), exact this hy }, rw [← set.mem_compl_iff, ← closure_compl], rcases hE with ⟨z, hz⟩, suffices : (λ c : ℝ, x + c • z) 0 ∈ closure (-{x} : set E), by simpa only [zero_smul, add_zero] using this, have : (0:ℝ) ∈ closure (set.Ioi (0:ℝ)), by simp [closure_Ioi], refine (continuous_const.add (continuous_id.smul continuous_const)).continuous_within_at.mem_closure this _, intros c hc, simp [smul_eq_zero, hz, ne_of_gt hc] }, { exact interior_closed_ball x hr } end theorem frontier_closed_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : frontier (closed_ball x r) = sphere x r := by rw [frontier, closure_eq_of_is_closed is_closed_ball, interior_closed_ball x hr, closed_ball_diff_ball] theorem frontier_closed_ball' [normed_space ℝ E] (x : E) (r : ℝ) (hE : ∃ z : E, z ≠ 0) : frontier (closed_ball x r) = sphere x r := by rw [frontier, closure_eq_of_is_closed is_closed_ball, interior_closed_ball' x r hE, closed_ball_diff_ball] open normed_field /-- If there is a scalar `c` with `∥c∥>1`, then any element can be moved by scalar multiplication to any shell of width `∥c∥`. Also recap information on the norm of the rescaling element that shows up in applications. -/ lemma rescale_to_shell {c : α} (hc : 1 < ∥c∥) {ε : ℝ} (εpos : 0 < ε) {x : E} (hx : x ≠ 0) : ∃d:α, d ≠ 0 ∧ ∥d • x∥ ≤ ε ∧ (ε/∥c∥ ≤ ∥d • x∥) ∧ (∥d∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥) := begin have xεpos : 0 < ∥x∥/ε := div_pos_of_pos_of_pos (norm_pos_iff.2 hx) εpos, rcases exists_int_pow_near xεpos hc with ⟨n, hn⟩, have cpos : 0 < ∥c∥ := lt_trans (zero_lt_one : (0 :ℝ) < 1) hc, have cnpos : 0 < ∥c^(n+1)∥ := by { rw norm_fpow, exact lt_trans xεpos hn.2 }, refine ⟨(c^(n+1))⁻¹, _, _, _, _⟩, show (c ^ (n + 1))⁻¹ ≠ 0, by rwa [ne.def, inv_eq_zero, ← ne.def, ← norm_pos_iff], show ∥(c ^ (n + 1))⁻¹ • x∥ ≤ ε, { rw [norm_smul, norm_inv, ← div_eq_inv_mul, div_le_iff cnpos, mul_comm, norm_fpow], exact (div_le_iff εpos).1 (le_of_lt (hn.2)) }, show ε / ∥c∥ ≤ ∥(c ^ (n + 1))⁻¹ • x∥, { rw [div_le_iff cpos, norm_smul, norm_inv, norm_fpow, fpow_add (ne_of_gt cpos), fpow_one, mul_inv', mul_comm, ← mul_assoc, ← mul_assoc, mul_inv_cancel (ne_of_gt cpos), one_mul, ← div_eq_inv_mul, le_div_iff (fpow_pos_of_pos cpos _), mul_comm], exact (le_div_iff εpos).1 hn.1 }, show ∥(c ^ (n + 1))⁻¹∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥, { have : ε⁻¹ * ∥c∥ * ∥x∥ = ε⁻¹ * ∥x∥ * ∥c∥, by ring, rw [norm_inv, inv_inv', norm_fpow, fpow_add (ne_of_gt cpos), fpow_one, this, ← div_eq_inv_mul], exact mul_le_mul_of_nonneg_right hn.1 (norm_nonneg _) } end /-- The product of two normed spaces is a normed space, with the sup norm. -/ instance : normed_space α (E × F) := { norm_smul_le := λ s x, le_of_eq $ by simp [prod.norm_def, norm_smul, mul_max_of_nonneg], -- TODO: without the next two lines Lean unfolds `≤` to `real.le` add_smul := λ r x y, prod.ext (add_smul _ _ _) (add_smul _ _ _), smul_add := λ r x y, prod.ext (smul_add _ _ _) (smul_add _ _ _), ..prod.normed_group, ..prod.module } /-- The product of finitely many normed spaces is a normed space, with the sup norm. -/ instance pi.normed_space {E : ι → Type*} [fintype ι] [∀i, normed_group (E i)] [∀i, normed_space α (E i)] : normed_space α (Πi, E i) := { norm_smul_le := λ a f, le_of_eq $ show (↑(finset.sup finset.univ (λ (b : ι), nnnorm (a • f b))) : ℝ) = nnnorm a * ↑(finset.sup finset.univ (λ (b : ι), nnnorm (f b))), by simp only [(nnreal.coe_mul _ _).symm, nnreal.mul_finset_sup, nnnorm_smul] } /-- A subspace of a normed space is also a normed space, with the restriction of the norm. -/ instance submodule.normed_space {𝕜 : Type*} [normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] (s : submodule 𝕜 E) : normed_space 𝕜 s := { norm_smul_le := λc x, le_of_eq $ norm_smul c (x : E) } end normed_space section normed_algebra section prio set_option default_priority 100 -- see Note [default priority] /-- A normed algebra `𝕜'` over `𝕜` is an algebra endowed with a norm for which the embedding of `𝕜` in `𝕜'` is an isometry. -/ class normed_algebra (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜'] extends algebra 𝕜 𝕜' := (norm_algebra_map_eq : ∀x:𝕜, ∥algebra_map 𝕜 𝕜' x∥ = ∥x∥) end prio @[simp] lemma norm_algebra_map_eq {𝕜 : Type*} (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜'] [h : normed_algebra 𝕜 𝕜'] (x : 𝕜) : ∥algebra_map 𝕜 𝕜' x∥ = ∥x∥ := normed_algebra.norm_algebra_map_eq _ @[priority 100] instance to_normed_space (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜'] [h : normed_algebra 𝕜 𝕜'] : normed_space 𝕜 𝕜' := { norm_smul_le := λ s x, calc ∥s • x∥ = ∥((algebra_map 𝕜 𝕜') s) * x∥ : by { rw h.smul_def', refl } ... ≤ ∥algebra_map 𝕜 𝕜' s∥ * ∥x∥ : normed_ring.norm_mul _ _ ... = ∥s∥ * ∥x∥ : by rw norm_algebra_map_eq, ..h } end normed_algebra section restrict_scalars variables (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] {E : Type*} [normed_group E] [normed_space 𝕜' E] /-- `𝕜`-normed space structure induced by a `𝕜'`-normed space structure when `𝕜'` is a normed algebra over `𝕜`. Not registered as an instance as `𝕜'` can not be inferred. -/ def normed_space.restrict_scalars : normed_space 𝕜 E := { norm_smul_le := λc x, le_of_eq $ begin change ∥(algebra_map 𝕜 𝕜' c) • x∥ = ∥c∥ * ∥x∥, simp [norm_smul] end, ..module.restrict_scalars 𝕜 𝕜' E } end restrict_scalars section summable open_locale classical open finset filter variables [normed_group α] @[nolint ge_or_gt] -- see Note [nolint_ge] lemma cauchy_seq_finset_iff_vanishing_norm {f : ι → α} : cauchy_seq (λ s : finset ι, s.sum f) ↔ ∀ε > 0, ∃s:finset ι, ∀t, disjoint t s → ∥ t.sum f ∥ < ε := begin simp only [cauchy_seq_finset_iff_vanishing, metric.mem_nhds_iff, exists_imp_distrib], split, { assume h ε hε, refine h {x | ∥x∥ < ε} ε hε _, rw [ball_0_eq ε] }, { assume h s ε hε hs, rcases h ε hε with ⟨t, ht⟩, refine ⟨t, assume u hu, hs _⟩, rw [ball_0_eq], exact ht u hu } end @[nolint ge_or_gt] -- see Note [nolint_ge] lemma summable_iff_vanishing_norm [complete_space α] {f : ι → α} : summable f ↔ ∀ε > 0, ∃s:finset ι, ∀t, disjoint t s → ∥ t.sum f ∥ < ε := by rw [summable_iff_cauchy_seq_finset, cauchy_seq_finset_iff_vanishing_norm] lemma cauchy_seq_finset_of_norm_bounded {f : ι → α} (g : ι → ℝ) (hg : summable g) (h : ∀i, ∥f i∥ ≤ g i) : cauchy_seq (λ s : finset ι, s.sum f) := cauchy_seq_finset_iff_vanishing_norm.2 $ assume ε hε, let ⟨s, hs⟩ := summable_iff_vanishing_norm.1 hg ε hε in ⟨s, assume t ht, have ∥t.sum g∥ < ε := hs t ht, have nn : 0 ≤ t.sum g := finset.sum_nonneg (assume a _, le_trans (norm_nonneg _) (h a)), lt_of_le_of_lt (norm_sum_le_of_le t (λ i _, h i)) $ by rwa [real.norm_eq_abs, abs_of_nonneg nn] at this⟩ lemma cauchy_seq_finset_of_summable_norm {f : ι → α} (hf : summable (λa, ∥f a∥)) : cauchy_seq (λ s : finset ι, s.sum f) := cauchy_seq_finset_of_norm_bounded _ hf (assume i, le_refl _) /-- If a function `f` is summable in norm, and along some sequence of finsets exhausting the space its sum is converging to a limit `a`, then this holds along all finsets, i.e., `f` is summable with sum `a`. -/ lemma has_sum_of_subseq_of_summable {f : ι → α} (hf : summable (λa, ∥f a∥)) {s : β → finset ι} {p : filter β} (hp : p ≠ ⊥) (hs : tendsto s p at_top) {a : α} (ha : tendsto (λ b, ∑ i in s b, f i) p (𝓝 a)) : has_sum f a := tendsto_nhds_of_cauchy_seq_of_subseq (cauchy_seq_finset_of_summable_norm hf) hp hs ha /-- If `∑' i, ∥f i∥` is summable, then `∥(∑' i, f i)∥ ≤ (∑' i, ∥f i∥)`. Note that we do not assume that `∑' i, f i` is summable, and it might not be the case if `α` is not a complete space. -/ lemma norm_tsum_le_tsum_norm {f : ι → α} (hf : summable (λi, ∥f i∥)) : ∥(∑'i, f i)∥ ≤ (∑' i, ∥f i∥) := begin by_cases h : summable f, { have h₁ : tendsto (λs:finset ι, ∥s.sum f∥) at_top (𝓝 ∥(∑' i, f i)∥) := (continuous_norm.tendsto _).comp h.has_sum, have h₂ : tendsto (λs:finset ι, s.sum (λi, ∥f i∥)) at_top (𝓝 (∑' i, ∥f i∥)) := hf.has_sum, exact le_of_tendsto_of_tendsto' at_top_ne_bot h₁ h₂ (assume s, norm_sum_le _ _) }, { rw tsum_eq_zero_of_not_summable h, simp [tsum_nonneg] } end lemma has_sum_iff_tendsto_nat_of_summable_norm {f : ℕ → α} {a : α} (hf : summable (λi, ∥f i∥)) : has_sum f a ↔ tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) := ⟨λ h, h.tendsto_sum_nat, λ h, has_sum_of_subseq_of_summable hf at_top_ne_bot tendsto_finset_range h⟩ variable [complete_space α] lemma summable_of_norm_bounded {f : ι → α} (g : ι → ℝ) (hg : summable g) (h : ∀i, ∥f i∥ ≤ g i) : summable f := by { rw summable_iff_cauchy_seq_finset, exact cauchy_seq_finset_of_norm_bounded g hg h } lemma summable_of_nnnorm_bounded {f : ι → α} (g : ι → nnreal) (hg : summable g) (h : ∀i, nnnorm (f i) ≤ g i) : summable f := summable_of_norm_bounded (λ i, (g i : ℝ)) (nnreal.summable_coe.2 hg) (λ i, by exact_mod_cast h i) lemma summable_of_summable_norm {f : ι → α} (hf : summable (λa, ∥f a∥)) : summable f := summable_of_norm_bounded _ hf (assume i, le_refl _) lemma summable_of_summable_nnnorm {f : ι → α} (hf : summable (λa, nnnorm (f a))) : summable f := summable_of_nnnorm_bounded _ hf (assume i, le_refl _) end summable
3e50f7c2b6c184ecf7d69a83ac7d3cffc07304b1
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/data/prod.lean
05e039c031eee0a5e3f51e59bc217bd48b9df463
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
1,128
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura, Jeremy Avigad -/ prelude import init.logic universes u v section variables {α : Type u} {β : Type v} @[simp] lemma prod.mk.eta : ∀{p : α × β}, (p.1, p.2) = p | (a, b) := rfl instance [inhabited α] [inhabited β] : inhabited (prod α β) := ⟨(default, default)⟩ instance [h₁ : decidable_eq α] [h₂ : decidable_eq β] : decidable_eq (α × β) | (a, b) (a', b') := match (h₁ a a') with | (is_true e₁) := match (h₂ b b') with | (is_true e₂) := is_true (eq.rec_on e₁ (eq.rec_on e₂ rfl)) | (is_false n₂) := is_false (assume h, prod.no_confusion h (λ e₁' e₂', absurd e₂' n₂)) end | (is_false n₁) := is_false (assume h, prod.no_confusion h (λ e₁' e₂', absurd e₁' n₁)) end end def {u₁ u₂ v₁ v₂} prod.map {α₁ : Type u₁} {α₂ : Type u₂} {β₁ : Type v₁} {β₂ : Type v₂} (f : α₁ → α₂) (g : β₁ → β₂) (x : α₁ × β₁) : α₂ × β₂ := (f x.1, g x.2)
8b93ef52fad2b7b4c9427070be8396f8eb13bdbf
900ff83b8a995f83b07c2fa0715d52fa265c4b9e
/library/init/logic.lean
3fab1870f0f7704a7b960cc87070307ed40a162e
[ "Apache-2.0" ]
permissive
moritzbuhl/lean
b2ee98197f1c47255c647228c07c830b229ba766
89e98b56713c027afdf97ad96abd2d54b35a43d5
refs/heads/master
1,688,295,006,616
1,627,741,115,000
1,627,741,115,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
39,087
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Floris van Doorn -/ prelude import init.core universes u v w @[simp] lemma opt_param_eq (α : Sort u) (default : α) : opt_param α default = α := rfl @[inline] def id {α : Sort u} (a : α) : α := a def flip {α : Sort u} {β : Sort v} {φ : Sort w} (f : α → β → φ) : β → α → φ := λ b a, f a b /- implication -/ def implies (a b : Prop) := a → b /-- Implication `→` is transitive. If `P → Q` and `Q → R` then `P → R`. -/ @[trans] lemma implies.trans {p q r : Prop} (h₁ : implies p q) (h₂ : implies q r) : implies p r := assume hp, h₂ (h₁ hp) lemma trivial : true := ⟨⟩ /-- We can't have `a` and `¬a`, that would be absurd!-/ @[inline] def absurd {a : Prop} {b : Sort v} (h₁ : a) (h₂ : ¬a) : b := false.rec b (h₂ h₁) lemma not.intro {a : Prop} (h : a → false) : ¬ a := h /-- Modus tollens. If an implication is true, then so is its contrapositive. -/ lemma mt {a b : Prop} (h₁ : a → b) (h₂ : ¬b) : ¬a := assume ha : a, h₂ (h₁ ha) /- not -/ lemma not_false : ¬false := id def non_contradictory (a : Prop) : Prop := ¬¬a lemma non_contradictory_intro {a : Prop} (ha : a) : ¬¬a := assume hna : ¬a, absurd ha hna /- false -/ @[inline] def false.elim {C : Sort u} (h : false) : C := false.rec C h /- eq -/ -- proof irrelevance is built in lemma proof_irrel {a : Prop} (h₁ h₂ : a) : h₁ = h₂ := rfl @[simp] lemma id.def {α : Sort u} (a : α) : id a = a := rfl @[inline] def eq.mp {α β : Sort u} : (α = β) → α → β := eq.rec_on @[inline] def eq.mpr {α β : Sort u} : (α = β) → β → α := λ h₁ h₂, eq.rec_on (eq.symm h₁) h₂ @[elab_as_eliminator] lemma eq.substr {α : Sort u} {p : α → Prop} {a b : α} (h₁ : b = a) : p a → p b := eq.subst (eq.symm h₁) lemma congr {α : Sort u} {β : Sort v} {f₁ f₂ : α → β} {a₁ a₂ : α} (h₁ : f₁ = f₂) (h₂ : a₁ = a₂) : f₁ a₁ = f₂ a₂ := eq.subst h₁ (eq.subst h₂ rfl) lemma congr_fun {α : Sort u} {β : α → Sort v} {f g : Π x, β x} (h : f = g) (a : α) : f a = g a := eq.subst h (eq.refl (f a)) lemma congr_arg {α : Sort u} {β : Sort v} {a₁ a₂ : α} (f : α → β) : a₁ = a₂ → f a₁ = f a₂ := congr rfl lemma trans_rel_left {α : Sort u} {a b c : α} (r : α → α → Prop) (h₁ : r a b) (h₂ : b = c) : r a c := h₂ ▸ h₁ lemma trans_rel_right {α : Sort u} {a b c : α} (r : α → α → Prop) (h₁ : a = b) (h₂ : r b c) : r a c := h₁.symm ▸ h₂ lemma of_eq_true {p : Prop} (h : p = true) : p := h.symm ▸ trivial lemma not_of_eq_false {p : Prop} (h : p = false) : ¬p := assume hp, h ▸ hp @[inline] def cast {α β : Sort u} (h : α = β) (a : α) : β := eq.rec a h lemma cast_proof_irrel {α β : Sort u} (h₁ h₂ : α = β) (a : α) : cast h₁ a = cast h₂ a := rfl lemma cast_eq {α : Sort u} (h : α = α) (a : α) : cast h a = a := rfl /- ne -/ @[reducible] def ne {α : Sort u} (a b : α) := ¬(a = b) notation a ≠ b := ne a b @[simp] lemma ne.def {α : Sort u} (a b : α) : a ≠ b = ¬ (a = b) := rfl namespace ne variable {α : Sort u} variables {a b : α} lemma intro (h : a = b → false) : a ≠ b := h lemma elim (h : a ≠ b) : a = b → false := h lemma irrefl (h : a ≠ a) : false := h rfl lemma symm (h : a ≠ b) : b ≠ a := assume (h₁ : b = a), h (h₁.symm) end ne lemma false_of_ne {α : Sort u} {a : α} : a ≠ a → false := ne.irrefl section variables {p : Prop} lemma ne_false_of_self : p → p ≠ false := assume (hp : p) (heq : p = false), heq ▸ hp lemma ne_true_of_not : ¬p → p ≠ true := assume (hnp : ¬p) (heq : p = true), (heq ▸ hnp) trivial lemma true_ne_false : ¬true = false := ne_false_of_self trivial end attribute [refl] heq.refl section variables {α β φ : Sort u} {a a' : α} {b b' : β} {c : φ} def heq.elim {α : Sort u} {a : α} {p : α → Sort v} {b : α} (h₁ : a == b) : p a → p b := eq.rec_on (eq_of_heq h₁) lemma heq.subst {p : ∀ T : Sort u, T → Prop} : a == b → p α a → p β b := heq.rec_on @[symm] lemma heq.symm (h : a == b) : b == a := heq.rec_on h (heq.refl a) lemma heq_of_eq (h : a = a') : a == a' := eq.subst h (heq.refl a) @[trans] lemma heq.trans (h₁ : a == b) (h₂ : b == c) : a == c := heq.subst h₂ h₁ @[trans] lemma heq_of_heq_of_eq (h₁ : a == b) (h₂ : b = b') : a == b' := heq.trans h₁ (heq_of_eq h₂) @[trans] lemma heq_of_eq_of_heq (h₁ : a = a') (h₂ : a' == b) : a == b := heq.trans (heq_of_eq h₁) h₂ lemma type_eq_of_heq (h : a == b) : α = β := heq.rec_on h (eq.refl α) end lemma eq_rec_heq {α : Sort u} {φ : α → Sort v} : ∀ {a a' : α} (h : a = a') (p : φ a), (eq.rec_on h p : φ a') == p | a _ rfl p := heq.refl p lemma heq_of_eq_rec_left {α : Sort u} {φ : α → Sort v} : ∀ {a a' : α} {p₁ : φ a} {p₂ : φ a'} (e : a = a') (h₂ : (eq.rec_on e p₁ : φ a') = p₂), p₁ == p₂ | a _ p₁ p₂ rfl h := eq.rec_on h (heq.refl p₁) lemma heq_of_eq_rec_right {α : Sort u} {φ : α → Sort v} : ∀ {a a' : α} {p₁ : φ a} {p₂ : φ a'} (e : a' = a) (h₂ : p₁ = eq.rec_on e p₂), p₁ == p₂ | a _ p₁ p₂ rfl h := have p₁ = p₂, from h, this ▸ heq.refl p₁ lemma of_heq_true {a : Prop} (h : a == true) : a := of_eq_true (eq_of_heq h) lemma eq_rec_compose : ∀ {α β φ : Sort u} (p₁ : β = φ) (p₂ : α = β) (a : α), (eq.rec_on p₁ (eq.rec_on p₂ a : β) : φ) = eq.rec_on (eq.trans p₂ p₁) a | α _ _ rfl rfl a := rfl lemma cast_heq : ∀ {α β : Sort u} (h : α = β) (a : α), cast h a == a | α _ rfl a := heq.refl a /- and -/ notation a /\ b := and a b notation a ∧ b := and a b variables {a b c d : Prop} lemma and.elim (h₁ : a ∧ b) (h₂ : a → b → c) : c := and.rec h₂ h₁ lemma and.swap : a ∧ b → b ∧ a := assume ⟨ha, hb⟩, ⟨hb, ha⟩ lemma and.symm : a ∧ b → b ∧ a := and.swap /- or -/ notation a \/ b := or a b notation a ∨ b := or a b namespace or lemma elim (h₁ : a ∨ b) (h₂ : a → c) (h₃ : b → c) : c := or.rec h₂ h₃ h₁ end or lemma non_contradictory_em (a : Prop) : ¬¬(a ∨ ¬a) := assume not_em : ¬(a ∨ ¬a), have neg_a : ¬a, from assume pos_a : a, absurd (or.inl pos_a) not_em, absurd (or.inr neg_a) not_em lemma or.swap : a ∨ b → b ∨ a := or.rec or.inr or.inl lemma or.symm : a ∨ b → b ∨ a := or.swap /- xor -/ def xor (a b : Prop) := (a ∧ ¬ b) ∨ (b ∧ ¬ a) /- iff -/ /-- `iff P Q`, with notation `P ↔ Q`, is the proposition asserting that `P` and `Q` are equivalent, that is, have the same truth value. -/ structure iff (a b : Prop) : Prop := intro :: (mp : a → b) (mpr : b → a) notation a <-> b := iff a b notation a ↔ b := iff a b lemma iff.elim : ((a → b) → (b → a) → c) → (a ↔ b) → c := iff.rec attribute [recursor 5] iff.elim lemma iff.elim_left : (a ↔ b) → a → b := iff.mp lemma iff.elim_right : (a ↔ b) → b → a := iff.mpr lemma iff_iff_implies_and_implies (a b : Prop) : (a ↔ b) ↔ (a → b) ∧ (b → a) := iff.intro (λ h, and.intro h.mp h.mpr) (λ h, iff.intro h.left h.right) @[refl] lemma iff.refl (a : Prop) : a ↔ a := iff.intro (assume h, h) (assume h, h) lemma iff.rfl {a : Prop} : a ↔ a := iff.refl a @[trans] lemma iff.trans (h₁ : a ↔ b) (h₂ : b ↔ c) : a ↔ c := iff.intro (assume ha, iff.mp h₂ (iff.mp h₁ ha)) (assume hc, iff.mpr h₁ (iff.mpr h₂ hc)) @[symm] lemma iff.symm (h : a ↔ b) : b ↔ a := iff.intro (iff.elim_right h) (iff.elim_left h) lemma iff.comm : (a ↔ b) ↔ (b ↔ a) := iff.intro iff.symm iff.symm lemma eq.to_iff {a b : Prop} (h : a = b) : a ↔ b := eq.rec_on h iff.rfl lemma neq_of_not_iff {a b : Prop} : ¬(a ↔ b) → a ≠ b := λ h₁ h₂, have a ↔ b, from eq.subst h₂ (iff.refl a), absurd this h₁ lemma not_iff_not_of_iff (h₁ : a ↔ b) : ¬a ↔ ¬b := iff.intro (assume (hna : ¬ a) (hb : b), hna (iff.elim_right h₁ hb)) (assume (hnb : ¬ b) (ha : a), hnb (iff.elim_left h₁ ha)) lemma of_iff_true (h : a ↔ true) : a := iff.mp (iff.symm h) trivial lemma not_of_iff_false : (a ↔ false) → ¬a := iff.mp lemma iff_true_intro (h : a) : a ↔ true := iff.intro (λ hl, trivial) (λ hr, h) lemma iff_false_intro (h : ¬a) : a ↔ false := iff.intro h (false.rec a) lemma not_non_contradictory_iff_absurd (a : Prop) : ¬¬¬a ↔ ¬a := iff.intro (λ (hl : ¬¬¬a) (ha : a), hl (non_contradictory_intro ha)) absurd lemma imp_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a → b) ↔ (c → d) := iff.intro (λ hab hc, iff.mp h₂ (hab (iff.mpr h₁ hc))) (λ hcd ha, iff.mpr h₂ (hcd (iff.mp h₁ ha))) lemma imp_congr_ctx (h₁ : a ↔ c) (h₂ : c → (b ↔ d)) : (a → b) ↔ (c → d) := iff.intro (λ hab hc, have ha : a, from iff.mpr h₁ hc, have hb : b, from hab ha, iff.mp (h₂ hc) hb) (λ hcd ha, have hc : c, from iff.mp h₁ ha, have hd : d, from hcd hc, iff.mpr (h₂ hc) hd) lemma imp_congr_right (h : a → (b ↔ c)) : (a → b) ↔ (a → c) := iff.intro (assume hab ha, iff.elim_left (h ha) (hab ha)) (assume hab ha, iff.elim_right (h ha) (hab ha)) lemma not_not_intro (ha : a) : ¬¬a := assume hna : ¬a, hna ha lemma not_of_not_not_not (h : ¬¬¬a) : ¬a := λ ha, absurd (not_not_intro ha) h @[simp] lemma not_true : (¬ true) ↔ false := iff_false_intro (not_not_intro trivial) @[simp] lemma not_false_iff : (¬ false) ↔ true := iff_true_intro not_false @[congr] lemma not_congr (h : a ↔ b) : ¬a ↔ ¬b := iff.intro (λ h₁ h₂, h₁ (iff.mpr h h₂)) (λ h₁ h₂, h₁ (iff.mp h h₂)) lemma ne_self_iff_false {α : Sort u} (a : α) : (not (a = a)) ↔ false := iff.intro false_of_ne false.elim @[simp] lemma eq_self_iff_true {α : Sort u} (a : α) : (a = a) ↔ true := iff_true_intro rfl lemma heq_self_iff_true {α : Sort u} (a : α) : (a == a) ↔ true := iff_true_intro (heq.refl a) @[simp] lemma iff_not_self (a : Prop) : (a ↔ ¬a) ↔ false := iff_false_intro (λ h, have h' : ¬a, from (λ ha, (iff.mp h ha) ha), h' (iff.mpr h h')) @[simp] lemma not_iff_self (a : Prop) : (¬a ↔ a) ↔ false := iff_false_intro (λ h, have h' : ¬a, from (λ ha, (iff.mpr h ha) ha), h' (iff.mp h h')) lemma true_iff_false : (true ↔ false) ↔ false := iff_false_intro (λ h, iff.mp h trivial) lemma false_iff_true : (false ↔ true) ↔ false := iff_false_intro (λ h, iff.mpr h trivial) lemma false_of_true_iff_false : (true ↔ false) → false := assume h, iff.mp h trivial lemma false_of_true_eq_false : (true = false) → false := assume h, h ▸ trivial lemma true_eq_false_of_false : false → (true = false) := false.elim lemma eq_comm {α : Sort u} {a b : α} : a = b ↔ b = a := ⟨eq.symm, eq.symm⟩ /- and simp rules -/ lemma and.imp (hac : a → c) (hbd : b → d) : a ∧ b → c ∧ d := assume ⟨ha, hb⟩, ⟨hac ha, hbd hb⟩ lemma and_implies (hac : a → c) (hbd : b → d) : a ∧ b → c ∧ d := and.imp hac hbd @[congr] lemma and_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a ∧ b) ↔ (c ∧ d) := iff.intro (and.imp (iff.mp h₁) (iff.mp h₂)) (and.imp (iff.mpr h₁) (iff.mpr h₂)) lemma and_congr_right (h : a → (b ↔ c)) : (a ∧ b) ↔ (a ∧ c) := iff.intro (assume ⟨ha, hb⟩, ⟨ha, iff.elim_left (h ha) hb⟩) (assume ⟨ha, hc⟩, ⟨ha, iff.elim_right (h ha) hc⟩) lemma and.comm : a ∧ b ↔ b ∧ a := iff.intro and.swap and.swap lemma and_comm (a b : Prop) : a ∧ b ↔ b ∧ a := and.comm lemma and.assoc : (a ∧ b) ∧ c ↔ a ∧ (b ∧ c) := iff.intro (assume ⟨⟨ha, hb⟩, hc⟩, ⟨ha, ⟨hb, hc⟩⟩) (assume ⟨ha, ⟨hb, hc⟩⟩, ⟨⟨ha, hb⟩, hc⟩) lemma and_assoc (a b : Prop) : (a ∧ b) ∧ c ↔ a ∧ (b ∧ c) := and.assoc lemma and.left_comm : a ∧ (b ∧ c) ↔ b ∧ (a ∧ c) := iff.trans (iff.symm and.assoc) (iff.trans (and_congr and.comm (iff.refl c)) and.assoc) lemma and_iff_left {a b : Prop} (hb : b) : (a ∧ b) ↔ a := iff.intro and.left (λ ha, ⟨ha, hb⟩) lemma and_iff_right {a b : Prop} (ha : a) : (a ∧ b) ↔ b := iff.intro and.right (and.intro ha) @[simp] lemma and_true (a : Prop) : a ∧ true ↔ a := and_iff_left trivial @[simp] lemma true_and (a : Prop) : true ∧ a ↔ a := and_iff_right trivial @[simp] lemma and_false (a : Prop) : a ∧ false ↔ false := iff_false_intro and.right @[simp] lemma false_and (a : Prop) : false ∧ a ↔ false := iff_false_intro and.left @[simp] lemma not_and_self (a : Prop) : (¬a ∧ a) ↔ false := iff_false_intro (λ h, and.elim h (λ h₁ h₂, absurd h₂ h₁)) @[simp] lemma and_not_self (a : Prop) : (a ∧ ¬a) ↔ false := iff_false_intro (assume ⟨h₁, h₂⟩, absurd h₁ h₂) @[simp] lemma and_self (a : Prop) : a ∧ a ↔ a := iff.intro and.left (assume h, ⟨h, h⟩) /- or simp rules -/ lemma or.imp (h₂ : a → c) (h₃ : b → d) : a ∨ b → c ∨ d := or.rec (λ h, or.inl (h₂ h)) (λ h, or.inr (h₃ h)) lemma or.imp_left (h : a → b) : a ∨ c → b ∨ c := or.imp h id lemma or.imp_right (h : a → b) : c ∨ a → c ∨ b := or.imp id h @[congr] lemma or_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a ∨ b) ↔ (c ∨ d) := iff.intro (or.imp (iff.mp h₁) (iff.mp h₂)) (or.imp (iff.mpr h₁) (iff.mpr h₂)) lemma or.comm : a ∨ b ↔ b ∨ a := iff.intro or.swap or.swap lemma or_comm (a b : Prop) : a ∨ b ↔ b ∨ a := or.comm lemma or.assoc : (a ∨ b) ∨ c ↔ a ∨ (b ∨ c) := iff.intro (or.rec (or.imp_right or.inl) (λ h, or.inr (or.inr h))) (or.rec (λ h, or.inl (or.inl h)) (or.imp_left or.inr)) lemma or_assoc (a b : Prop) : (a ∨ b) ∨ c ↔ a ∨ (b ∨ c) := or.assoc lemma or.left_comm : a ∨ (b ∨ c) ↔ b ∨ (a ∨ c) := iff.trans (iff.symm or.assoc) (iff.trans (or_congr or.comm (iff.refl c)) or.assoc) theorem or_iff_right_of_imp (ha : a → b) : (a ∨ b) ↔ b := iff.intro (or.rec ha id) or.inr theorem or_iff_left_of_imp (hb : b → a) : (a ∨ b) ↔ a := iff.intro (or.rec id hb) or.inl @[simp] lemma or_true (a : Prop) : a ∨ true ↔ true := iff_true_intro (or.inr trivial) @[simp] lemma true_or (a : Prop) : true ∨ a ↔ true := iff_true_intro (or.inl trivial) @[simp] lemma or_false (a : Prop) : a ∨ false ↔ a := iff.intro (or.rec id false.elim) or.inl @[simp] lemma false_or (a : Prop) : false ∨ a ↔ a := iff.trans or.comm (or_false a) @[simp] lemma or_self (a : Prop) : a ∨ a ↔ a := iff.intro (or.rec id id) or.inl lemma not_or {a b : Prop} : ¬ a → ¬ b → ¬ (a ∨ b) | hna hnb (or.inl ha) := absurd ha hna | hna hnb (or.inr hb) := absurd hb hnb /- or resolution rulse -/ lemma or.resolve_left {a b : Prop} (h : a ∨ b) (na : ¬ a) : b := or.elim h (λ ha, absurd ha na) id lemma or.neg_resolve_left {a b : Prop} (h : ¬ a ∨ b) (ha : a) : b := or.elim h (λ na, absurd ha na) id lemma or.resolve_right {a b : Prop} (h : a ∨ b) (nb : ¬ b) : a := or.elim h id (λ hb, absurd hb nb) lemma or.neg_resolve_right {a b : Prop} (h : a ∨ ¬ b) (hb : b) : a := or.elim h id (λ nb, absurd hb nb) /- iff simp rules -/ @[simp] lemma iff_true (a : Prop) : (a ↔ true) ↔ a := iff.intro (assume h, iff.mpr h trivial) iff_true_intro @[simp] lemma true_iff (a : Prop) : (true ↔ a) ↔ a := iff.trans iff.comm (iff_true a) @[simp] lemma iff_false (a : Prop) : (a ↔ false) ↔ ¬ a := iff.intro iff.mp iff_false_intro @[simp] lemma false_iff (a : Prop) : (false ↔ a) ↔ ¬ a := iff.trans iff.comm (iff_false a) @[simp] lemma iff_self (a : Prop) : (a ↔ a) ↔ true := iff_true_intro iff.rfl @[congr] lemma iff_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a ↔ b) ↔ (c ↔ d) := (iff_iff_implies_and_implies a b).trans ((and_congr (imp_congr h₁ h₂) (imp_congr h₂ h₁)).trans (iff_iff_implies_and_implies c d).symm) /- implies simp rule -/ @[simp] lemma implies_true_iff (α : Sort u) : (α → true) ↔ true := iff.intro (λ h, trivial) (λ ha h, trivial) lemma false_implies_iff (a : Prop) : (false → a) ↔ true := iff.intro (λ h, trivial) (λ ha h, false.elim h) theorem true_implies_iff (α : Prop) : (true → α) ↔ α := iff.intro (λ h, h trivial) (λ h h', h) /-- The existential quantifier. To prove a goal of the form `⊢ ∃ x, p x`, you can provide a witness `y` with the tactic `existsi y`. If you are working in a project that depends on mathlib, then we recommend the `use` tactic instead. You'll then be left with the goal `⊢ p y`. To extract a witness `x` and proof `hx : p x` from a hypothesis `h : ∃ x, p x`, use the tactic `cases h with x hx`. See also the mathlib tactics `obtain` and `rcases`. -/ inductive Exists {α : Sort u} (p : α → Prop) : Prop | intro (w : α) (h : p w) : Exists attribute [intro] Exists.intro notation `exists` binders `, ` r:(scoped P, Exists P) := r notation `∃` binders `, ` r:(scoped P, Exists P) := r /- This is a `def`, so that it can be used as pattern in the equation compiler. -/ @[pattern] def exists.intro {α : Sort u} {p : α → Prop} (w : α) (h : p w) : ∃ x, p x := ⟨w, h⟩ lemma exists.elim {α : Sort u} {p : α → Prop} {b : Prop} (h₁ : ∃ x, p x) (h₂ : ∀ (a : α), p a → b) : b := Exists.rec h₂ h₁ /- exists unique -/ def exists_unique {α : Sort u} (p : α → Prop) := ∃ x, p x ∧ ∀ y, p y → y = x notation `∃!` binders `, ` r:(scoped P, exists_unique P) := r @[intro] lemma exists_unique.intro {α : Sort u} {p : α → Prop} (w : α) (h₁ : p w) (h₂ : ∀ y, p y → y = w) : ∃! x, p x := exists.intro w ⟨h₁, h₂⟩ attribute [recursor 4] lemma exists_unique.elim {α : Sort u} {p : α → Prop} {b : Prop} (h₂ : ∃! x, p x) (h₁ : ∀ x, p x → (∀ y, p y → y = x) → b) : b := exists.elim h₂ (λ w hw, h₁ w (and.left hw) (and.right hw)) lemma exists_unique_of_exists_of_unique {α : Sort u} {p : α → Prop} (hex : ∃ x, p x) (hunique : ∀ y₁ y₂, p y₁ → p y₂ → y₁ = y₂) : ∃! x, p x := exists.elim hex (λ x px, exists_unique.intro x px (assume y, assume : p y, hunique y x this px)) lemma exists_of_exists_unique {α : Sort u} {p : α → Prop} (h : ∃! x, p x) : ∃ x, p x := exists.elim h (λ x hx, ⟨x, and.left hx⟩) lemma unique_of_exists_unique {α : Sort u} {p : α → Prop} (h : ∃! x, p x) {y₁ y₂ : α} (py₁ : p y₁) (py₂ : p y₂) : y₁ = y₂ := exists_unique.elim h (assume x, assume : p x, assume unique : ∀ y, p y → y = x, show y₁ = y₂, from eq.trans (unique _ py₁) (eq.symm (unique _ py₂))) /- exists, forall, exists unique congruences -/ @[congr] lemma forall_congr {α : Sort u} {p q : α → Prop} (h : ∀ a, (p a ↔ q a)) : (∀ a, p a) ↔ ∀ a, q a := iff.intro (λ p a, iff.mp (h a) (p a)) (λ q a, iff.mpr (h a) (q a)) lemma exists_imp_exists {α : Sort u} {p q : α → Prop} (h : ∀ a, (p a → q a)) (p : ∃ a, p a) : ∃ a, q a := exists.elim p (λ a hp, ⟨a, h a hp⟩) @[congr] lemma exists_congr {α : Sort u} {p q : α → Prop} (h : ∀ a, (p a ↔ q a)) : (Exists p) ↔ ∃ a, q a := iff.intro (exists_imp_exists (λ a, iff.mp (h a))) (exists_imp_exists (λ a, iff.mpr (h a))) @[congr] lemma exists_unique_congr {α : Sort u} {p₁ p₂ : α → Prop} (h : ∀ x, p₁ x ↔ p₂ x) : (exists_unique p₁) ↔ (∃! x, p₂ x) := -- exists_congr (λ x, and_congr (h x) (forall_congr (λ y, imp_congr (h y) iff.rfl))) lemma forall_not_of_not_exists {α : Sort u} {p : α → Prop} : ¬(∃ x, p x) → (∀ x, ¬p x) := λ hne x hp, hne ⟨x, hp⟩ /- decidable -/ def decidable.to_bool (p : Prop) [h : decidable p] : bool := decidable.cases_on h (λ h₁, bool.ff) (λ h₂, bool.tt) export decidable (is_true is_false to_bool) @[simp] lemma to_bool_true_eq_tt (h : decidable true) : @to_bool true h = tt := decidable.cases_on h (λ h, false.elim (iff.mp not_true h)) (λ _, rfl) @[simp] lemma to_bool_false_eq_ff (h : decidable false) : @to_bool false h = ff := decidable.cases_on h (λ h, rfl) (λ h, false.elim h) instance decidable.true : decidable true := is_true trivial instance decidable.false : decidable false := is_false not_false -- We use "dependent" if-then-else to be able to communicate the if-then-else condition -- to the branches @[inline] def dite {α : Sort u} (c : Prop) [h : decidable c] : (c → α) → (¬ c → α) → α := λ t e, decidable.rec_on h e t /- if-then-else -/ @[inline] def ite {α : Sort u} (c : Prop) [h : decidable c] (t e : α) : α := decidable.rec_on h (λ hnc, e) (λ hc, t) namespace decidable variables {p q : Prop} def rec_on_true [h : decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} (h₃ : p) (h₄ : h₁ h₃) : decidable.rec_on h h₂ h₁ := decidable.rec_on h (λ h, false.rec _ (h h₃)) (λ h, h₄) def rec_on_false [h : decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} (h₃ : ¬p) (h₄ : h₂ h₃) : decidable.rec_on h h₂ h₁ := decidable.rec_on h (λ h, h₄) (λ h, false.rec _ (h₃ h)) def by_cases {q : Sort u} [φ : decidable p] : (p → q) → (¬p → q) → q := dite _ /-- Law of Excluded Middle. -/ lemma em (p : Prop) [decidable p] : p ∨ ¬p := by_cases or.inl or.inr lemma by_contradiction [decidable p] (h : ¬p → false) : p := if h₁ : p then h₁ else false.rec _ (h h₁) lemma of_not_not [decidable p] : ¬ ¬ p → p := λ hnn, by_contradiction (λ hn, absurd hn hnn) lemma not_not_iff (p) [decidable p] : (¬ ¬ p) ↔ p := iff.intro of_not_not not_not_intro lemma not_and_iff_or_not (p q : Prop) [d₁ : decidable p] [d₂ : decidable q] : ¬ (p ∧ q) ↔ ¬ p ∨ ¬ q := iff.intro (λ h, match d₁ with | is_true h₁ := match d₂ with | is_true h₂ := absurd (and.intro h₁ h₂) h | is_false h₂ := or.inr h₂ end | is_false h₁ := or.inl h₁ end) (λ h ⟨hp, hq⟩, or.elim h (λ h, h hp) (λ h, h hq)) lemma not_or_iff_and_not (p q) [d₁ : decidable p] [d₂ : decidable q] : ¬ (p ∨ q) ↔ ¬ p ∧ ¬ q := iff.intro (λ h, match d₁ with | is_true h₁ := false.elim $ h (or.inl h₁) | is_false h₁ := match d₂ with | is_true h₂ := false.elim $ h (or.inr h₂) | is_false h₂ := ⟨h₁, h₂⟩ end end) (λ ⟨np, nq⟩ h, or.elim h np nq) end decidable section variables {p q : Prop} def decidable_of_decidable_of_iff (hp : decidable p) (h : p ↔ q) : decidable q := if hp : p then is_true (iff.mp h hp) else is_false (iff.mp (not_iff_not_of_iff h) hp) def decidable_of_decidable_of_eq (hp : decidable p) (h : p = q) : decidable q := decidable_of_decidable_of_iff hp h.to_iff protected def or.by_cases [decidable p] [decidable q] {α : Sort u} (h : p ∨ q) (h₁ : p → α) (h₂ : q → α) : α := if hp : p then h₁ hp else if hq : q then h₂ hq else false.rec _ (or.elim h hp hq) end section variables {p q : Prop} instance [decidable p] [decidable q] : decidable (p ∧ q) := if hp : p then if hq : q then is_true ⟨hp, hq⟩ else is_false (assume h : p ∧ q, hq (and.right h)) else is_false (assume h : p ∧ q, hp (and.left h)) instance [decidable p] [decidable q] : decidable (p ∨ q) := if hp : p then is_true (or.inl hp) else if hq : q then is_true (or.inr hq) else is_false (or.rec hp hq) instance [decidable p] : decidable (¬p) := if hp : p then is_false (absurd hp) else is_true hp instance implies.decidable [decidable p] [decidable q] : decidable (p → q) := if hp : p then if hq : q then is_true (assume h, hq) else is_false (assume h : p → q, absurd (h hp) hq) else is_true (assume h, absurd h hp) instance [decidable p] [decidable q] : decidable (p ↔ q) := if hp : p then if hq : q then is_true ⟨λ_, hq, λ_, hp⟩ else is_false $ λh, hq (h.1 hp) else if hq : q then is_false $ λh, hp (h.2 hq) else is_true $ ⟨λh, absurd h hp, λh, absurd h hq⟩ instance [decidable p] [decidable q] : decidable (xor p q) := if hp : p then if hq : q then is_false (or.rec (λ ⟨_, h⟩, h hq : ¬(p ∧ ¬ q)) (λ ⟨_, h⟩, h hp : ¬(q ∧ ¬ p))) else is_true $ or.inl ⟨hp, hq⟩ else if hq : q then is_true $ or.inr ⟨hq, hp⟩ else is_false (or.rec (λ ⟨h, _⟩, hp h : ¬(p ∧ ¬ q)) (λ ⟨h, _⟩, hq h : ¬(q ∧ ¬ p))) instance exists_prop_decidable {p} (P : p → Prop) [Dp : decidable p] [DP : ∀ h, decidable (P h)] : decidable (∃ h, P h) := if h : p then decidable_of_decidable_of_iff (DP h) ⟨λ h2, ⟨h, h2⟩, λ⟨h', h2⟩, h2⟩ else is_false (mt (λ⟨h, _⟩, h) h) instance forall_prop_decidable {p} (P : p → Prop) [Dp : decidable p] [DP : ∀ h, decidable (P h)] : decidable (∀ h, P h) := if h : p then decidable_of_decidable_of_iff (DP h) ⟨λ h2 _, h2, λal, al h⟩ else is_true (λ h2, absurd h2 h) end instance {α : Sort u} [decidable_eq α] (a b : α) : decidable (a ≠ b) := implies.decidable lemma bool.ff_ne_tt : ff = tt → false . def is_dec_eq {α : Sort u} (p : α → α → bool) : Prop := ∀ ⦃x y : α⦄, p x y = tt → x = y def is_dec_refl {α : Sort u} (p : α → α → bool) : Prop := ∀ x, p x x = tt open decidable instance : decidable_eq bool | ff ff := is_true rfl | ff tt := is_false bool.ff_ne_tt | tt ff := is_false (ne.symm bool.ff_ne_tt) | tt tt := is_true rfl def decidable_eq_of_bool_pred {α : Sort u} {p : α → α → bool} (h₁ : is_dec_eq p) (h₂ : is_dec_refl p) : decidable_eq α := assume x y : α, if hp : p x y = tt then is_true (h₁ hp) else is_false (assume hxy : x = y, absurd (h₂ y) (@eq.rec_on _ _ (λ z, ¬p z y = tt) _ hxy hp)) lemma decidable_eq_inl_refl {α : Sort u} [h : decidable_eq α] (a : α) : h a a = is_true (eq.refl a) := match (h a a) with | (is_true e) := rfl | (is_false n) := absurd rfl n end lemma decidable_eq_inr_neg {α : Sort u} [h : decidable_eq α] {a b : α} : Π n : a ≠ b, h a b = is_false n := assume n, match (h a b) with | (is_true e) := absurd e n | (is_false n₁) := proof_irrel n n₁ ▸ eq.refl (is_false n) end /- inhabited -/ class inhabited (α : Sort u) := (default [] : α) export inhabited (default) @[inline, irreducible] def arbitrary (α : Sort u) [inhabited α] : α := default α instance prop.inhabited : inhabited Prop := ⟨true⟩ instance pi.inhabited (α : Sort u) {β : α → Sort v} [Π x, inhabited (β x)] : inhabited (Π x, β x) := ⟨λ a, default (β a)⟩ instance : inhabited bool := ⟨ff⟩ instance : inhabited true := ⟨trivial⟩ class inductive nonempty (α : Sort u) : Prop | intro (val : α) : nonempty protected lemma nonempty.elim {α : Sort u} {p : Prop} (h₁ : nonempty α) (h₂ : α → p) : p := nonempty.rec h₂ h₁ @[priority 100] instance nonempty_of_inhabited {α : Sort u} [inhabited α] : nonempty α := ⟨default α⟩ lemma nonempty_of_exists {α : Sort u} {p : α → Prop} : (∃ x, p x) → nonempty α | ⟨w, h⟩ := ⟨w⟩ /- subsingleton -/ class inductive subsingleton (α : Sort u) : Prop | intro (h : ∀ a b : α, a = b) : subsingleton protected lemma subsingleton.elim {α : Sort u} [h : subsingleton α] : ∀ (a b : α), a = b := subsingleton.rec (λ p, p) h protected lemma subsingleton.helim {α β : Sort u} [h : subsingleton α] (h : α = β) : ∀ (a : α) (b : β), a == b := eq.rec_on h (λ a b : α, heq_of_eq (subsingleton.elim a b)) instance subsingleton_prop (p : Prop) : subsingleton p := ⟨λ a b, proof_irrel a b⟩ instance (p : Prop) : subsingleton (decidable p) := subsingleton.intro (λ d₁, match d₁ with | (is_true t₁) := (λ d₂, match d₂ with | (is_true t₂) := eq.rec_on (proof_irrel t₁ t₂) rfl | (is_false f₂) := absurd t₁ f₂ end) | (is_false f₁) := (λ d₂, match d₂ with | (is_true t₂) := absurd t₂ f₁ | (is_false f₂) := eq.rec_on (proof_irrel f₁ f₂) rfl end) end) protected lemma rec_subsingleton {p : Prop} [h : decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} [h₃ : Π (h : p), subsingleton (h₁ h)] [h₄ : Π (h : ¬p), subsingleton (h₂ h)] : subsingleton (decidable.rec_on h h₂ h₁) := match h with | (is_true h) := h₃ h | (is_false h) := h₄ h end lemma if_pos {c : Prop} [h : decidable c] (hc : c) {α : Sort u} {t e : α} : (ite c t e) = t := match h with | (is_true hc) := rfl | (is_false hnc) := absurd hc hnc end lemma if_neg {c : Prop} [h : decidable c] (hnc : ¬c) {α : Sort u} {t e : α} : (ite c t e) = e := match h with | (is_true hc) := absurd hc hnc | (is_false hnc) := rfl end @[simp] lemma if_t_t (c : Prop) [h : decidable c] {α : Sort u} (t : α) : (ite c t t) = t := match h with | (is_true hc) := rfl | (is_false hnc) := rfl end lemma implies_of_if_pos {c t e : Prop} [decidable c] (h : ite c t e) : c → t := assume hc, eq.rec_on (if_pos hc : ite c t e = t) h lemma implies_of_if_neg {c t e : Prop} [decidable c] (h : ite c t e) : ¬c → e := assume hnc, eq.rec_on (if_neg hnc : ite c t e = e) h lemma if_ctx_congr {α : Sort u} {b c : Prop} [dec_b : decidable b] [dec_c : decidable c] {x y u v : α} (h_c : b ↔ c) (h_t : c → x = u) (h_e : ¬c → y = v) : ite b x y = ite c u v := match dec_b, dec_c with | (is_false h₁), (is_false h₂) := h_e h₂ | (is_true h₁), (is_true h₂) := h_t h₂ | (is_false h₁), (is_true h₂) := absurd h₂ (iff.mp (not_iff_not_of_iff h_c) h₁) | (is_true h₁), (is_false h₂) := absurd h₁ (iff.mpr (not_iff_not_of_iff h_c) h₂) end @[congr] lemma if_congr {α : Sort u} {b c : Prop} [dec_b : decidable b] [dec_c : decidable c] {x y u v : α} (h_c : b ↔ c) (h_t : x = u) (h_e : y = v) : ite b x y = ite c u v := @if_ctx_congr α b c dec_b dec_c x y u v h_c (λ h, h_t) (λ h, h_e) @[simp] lemma if_true {α : Sort u} {h : decidable true} (t e : α) : (@ite α true h t e) = t := if_pos trivial @[simp] lemma if_false {α : Sort u} {h : decidable false} (t e : α) : (@ite α false h t e) = e := if_neg not_false lemma if_ctx_congr_prop {b c x y u v : Prop} [dec_b : decidable b] [dec_c : decidable c] (h_c : b ↔ c) (h_t : c → (x ↔ u)) (h_e : ¬c → (y ↔ v)) : ite b x y ↔ ite c u v := match dec_b, dec_c with | (is_false h₁), (is_false h₂) := h_e h₂ | (is_true h₁), (is_true h₂) := h_t h₂ | (is_false h₁), (is_true h₂) := absurd h₂ (iff.mp (not_iff_not_of_iff h_c) h₁) | (is_true h₁), (is_false h₂) := absurd h₁ (iff.mpr (not_iff_not_of_iff h_c) h₂) end @[congr] lemma if_congr_prop {b c x y u v : Prop} [dec_b : decidable b] [dec_c : decidable c] (h_c : b ↔ c) (h_t : x ↔ u) (h_e : y ↔ v) : ite b x y ↔ ite c u v := if_ctx_congr_prop h_c (λ h, h_t) (λ h, h_e) lemma if_ctx_simp_congr_prop {b c x y u v : Prop} [dec_b : decidable b] (h_c : b ↔ c) (h_t : c → (x ↔ u)) (h_e : ¬c → (y ↔ v)) : ite b x y ↔ (@ite Prop c (decidable_of_decidable_of_iff dec_b h_c) u v) := @if_ctx_congr_prop b c x y u v dec_b (decidable_of_decidable_of_iff dec_b h_c) h_c h_t h_e @[congr] lemma if_simp_congr_prop {b c x y u v : Prop} [dec_b : decidable b] (h_c : b ↔ c) (h_t : x ↔ u) (h_e : y ↔ v) : ite b x y ↔ (@ite Prop c (decidable_of_decidable_of_iff dec_b h_c) u v) := @if_ctx_simp_congr_prop b c x y u v dec_b h_c (λ h, h_t) (λ h, h_e) @[simp] lemma dif_pos {c : Prop} [h : decidable c] (hc : c) {α : Sort u} {t : c → α} {e : ¬ c → α} : dite c t e = t hc := match h with | (is_true hc) := rfl | (is_false hnc) := absurd hc hnc end @[simp] lemma dif_neg {c : Prop} [h : decidable c] (hnc : ¬c) {α : Sort u} {t : c → α} {e : ¬ c → α} : dite c t e = e hnc := match h with | (is_true hc) := absurd hc hnc | (is_false hnc) := rfl end @[congr] lemma dif_ctx_congr {α : Sort u} {b c : Prop} [dec_b : decidable b] [dec_c : decidable c] {x : b → α} {u : c → α} {y : ¬b → α} {v : ¬c → α} (h_c : b ↔ c) (h_t : ∀ (h : c), x (iff.mpr h_c h) = u h) (h_e : ∀ (h : ¬c), y (iff.mpr (not_iff_not_of_iff h_c) h) = v h) : (@dite α b dec_b x y) = (@dite α c dec_c u v) := match dec_b, dec_c with | (is_false h₁), (is_false h₂) := h_e h₂ | (is_true h₁), (is_true h₂) := h_t h₂ | (is_false h₁), (is_true h₂) := absurd h₂ (iff.mp (not_iff_not_of_iff h_c) h₁) | (is_true h₁), (is_false h₂) := absurd h₁ (iff.mpr (not_iff_not_of_iff h_c) h₂) end lemma dif_ctx_simp_congr {α : Sort u} {b c : Prop} [dec_b : decidable b] {x : b → α} {u : c → α} {y : ¬b → α} {v : ¬c → α} (h_c : b ↔ c) (h_t : ∀ (h : c), x (iff.mpr h_c h) = u h) (h_e : ∀ (h : ¬c), y (iff.mpr (not_iff_not_of_iff h_c) h) = v h) : (@dite α b dec_b x y) = (@dite α c (decidable_of_decidable_of_iff dec_b h_c) u v) := @dif_ctx_congr α b c dec_b (decidable_of_decidable_of_iff dec_b h_c) x u y v h_c h_t h_e -- Remark: dite and ite are "defally equal" when we ignore the proofs. lemma dif_eq_if (c : Prop) [h : decidable c] {α : Sort u} (t : α) (e : α) : dite c (λ h, t) (λ h, e) = ite c t e := match h with | (is_true hc) := rfl | (is_false hnc) := rfl end instance {c t e : Prop} [d_c : decidable c] [d_t : decidable t] [d_e : decidable e] : decidable (if c then t else e) := match d_c with | (is_true hc) := d_t | (is_false hc) := d_e end instance {c : Prop} {t : c → Prop} {e : ¬c → Prop} [d_c : decidable c] [d_t : ∀ h, decidable (t h)] [d_e : ∀ h, decidable (e h)] : decidable (if h : c then t h else e h) := match d_c with | (is_true hc) := d_t hc | (is_false hc) := d_e hc end def as_true (c : Prop) [decidable c] : Prop := if c then true else false def as_false (c : Prop) [decidable c] : Prop := if c then false else true lemma of_as_true {c : Prop} [h₁ : decidable c] (h₂ : as_true c) : c := match h₁, h₂ with | (is_true h_c), h₂ := h_c | (is_false h_c), h₂ := false.elim h₂ end /-- Universe lifting operation -/ structure {r s} ulift (α : Type s) : Type (max s r) := up :: (down : α) namespace ulift /- Bijection between α and ulift.{v} α -/ lemma up_down {α : Type u} : ∀ (b : ulift.{v} α), up (down b) = b | (up a) := rfl lemma down_up {α : Type u} (a : α) : down (up.{v} a) = a := rfl end ulift /-- Universe lifting operation from Sort to Type -/ structure plift (α : Sort u) : Type u := up :: (down : α) namespace plift /- Bijection between α and plift α -/ lemma up_down {α : Sort u} : ∀ (b : plift α), up (down b) = b | (up a) := rfl lemma down_up {α : Sort u} (a : α) : down (up a) = a := rfl end plift /- Equalities for rewriting let-expressions -/ lemma let_value_eq {α : Sort u} {β : Sort v} {a₁ a₂ : α} (b : α → β) : a₁ = a₂ → (let x : α := a₁ in b x) = (let x : α := a₂ in b x) := λ h, eq.rec_on h rfl lemma let_value_heq {α : Sort v} {β : α → Sort u} {a₁ a₂ : α} (b : Π x : α, β x) : a₁ = a₂ → (let x : α := a₁ in b x) == (let x : α := a₂ in b x) := λ h, eq.rec_on h (heq.refl (b a₁)) lemma let_body_eq {α : Sort v} {β : α → Sort u} (a : α) {b₁ b₂ : Π x : α, β x} : (∀ x, b₁ x = b₂ x) → (let x : α := a in b₁ x) = (let x : α := a in b₂ x) := λ h, h a lemma let_eq {α : Sort v} {β : Sort u} {a₁ a₂ : α} {b₁ b₂ : α → β} : a₁ = a₂ → (∀ x, b₁ x = b₂ x) → (let x : α := a₁ in b₁ x) = (let x : α := a₂ in b₂ x) := λ h₁ h₂, eq.rec_on h₁ (h₂ a₁) section relation variables {α : Sort u} {β : Sort v} (r : β → β → Prop) local infix `≺`:50 := r def reflexive := ∀ x, x ≺ x def symmetric := ∀ ⦃x y⦄, x ≺ y → y ≺ x def transitive := ∀ ⦃x y z⦄, x ≺ y → y ≺ z → x ≺ z def equivalence := reflexive r ∧ symmetric r ∧ transitive r def total := ∀ x y, x ≺ y ∨ y ≺ x lemma mk_equivalence (rfl : reflexive r) (symm : symmetric r) (trans : transitive r) : equivalence r := ⟨rfl, symm, trans⟩ def irreflexive := ∀ x, ¬ x ≺ x def anti_symmetric := ∀ ⦃x y⦄, x ≺ y → y ≺ x → x = y def empty_relation := λ a₁ a₂ : α, false def subrelation (q r : β → β → Prop) := ∀ ⦃x y⦄, q x y → r x y def inv_image (f : α → β) : α → α → Prop := λ a₁ a₂, f a₁ ≺ f a₂ lemma inv_image.trans (f : α → β) (h : transitive r) : transitive (inv_image r f) := λ (a₁ a₂ a₃ : α) (h₁ : inv_image r f a₁ a₂) (h₂ : inv_image r f a₂ a₃), h h₁ h₂ lemma inv_image.irreflexive (f : α → β) (h : irreflexive r) : irreflexive (inv_image r f) := λ (a : α) (h₁ : inv_image r f a a), h (f a) h₁ inductive tc {α : Sort u} (r : α → α → Prop) : α → α → Prop | base : ∀ a b, r a b → tc a b | trans : ∀ a b c, tc a b → tc b c → tc a c end relation section binary variables {α : Type u} {β : Type v} variable f : α → α → α variable inv : α → α variable one : α local notation a * b := f a b local notation a ⁻¹ := inv a variable g : α → α → α local notation a + b := g a b def commutative := ∀ a b, a * b = b * a def associative := ∀ a b c, (a * b) * c = a * (b * c) def left_identity := ∀ a, one * a = a def right_identity := ∀ a, a * one = a def right_inverse := ∀ a, a * a⁻¹ = one def left_cancelative := ∀ a b c, a * b = a * c → b = c def right_cancelative := ∀ a b c, a * b = c * b → a = c def left_distributive := ∀ a b c, a * (b + c) = a * b + a * c def right_distributive := ∀ a b c, (a + b) * c = a * c + b * c def right_commutative (h : β → α → β) := ∀ b a₁ a₂, h (h b a₁) a₂ = h (h b a₂) a₁ def left_commutative (h : α → β → β) := ∀ a₁ a₂ b, h a₁ (h a₂ b) = h a₂ (h a₁ b) lemma left_comm : commutative f → associative f → left_commutative f := assume hcomm hassoc, assume a b c, calc a*(b*c) = (a*b)*c : eq.symm (hassoc a b c) ... = (b*a)*c : hcomm a b ▸ rfl ... = b*(a*c) : hassoc b a c lemma right_comm : commutative f → associative f → right_commutative f := assume hcomm hassoc, assume a b c, calc (a*b)*c = a*(b*c) : hassoc a b c ... = a*(c*b) : hcomm b c ▸ rfl ... = (a*c)*b : eq.symm (hassoc a c b) end binary
b7d3c778def94c77dc5789f8e0b2faf68361f8eb
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/archive/100-theorems-list/82_cubing_a_cube.lean
f1ab1f58186eb32e2ad4e8c42ea05939a1fee4d1
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
23,048
lean
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn -/ import data.real.basic import data.set.disjointed import data.set.intervals import set_theory.cardinal /-! Proof that a cube (in dimension n ≥ 3) cannot be cubed: There does not exist a partition of a cube into finitely many smaller cubes (at least two) of different sizes. We follow the proof described here: http://www.alaricstephen.com/main-featured/2017/9/28/cubing-a-cube-proof -/ open real set function fin noncomputable theory variable {n : ℕ} /-- Given three intervals `I, J, K` such that `J ⊂ I`, neither endpoint of `J` coincides with an endpoint of `I`, `¬ (K ⊆ J)` and `K` does not lie completely to the left nor completely to the right of `J`. Then `I ∩ K \ J` is nonempty. -/ lemma Ico_lemma {α} [decidable_linear_order α] {x₁ x₂ y₁ y₂ z₁ z₂ w : α} (h₁ : x₁ < y₁) (hy : y₁ < y₂) (h₂ : y₂ < x₂) (hz₁ : z₁ ≤ y₂) (hz₂ : y₁ ≤ z₂) (hw : w ∉ Ico y₁ y₂ ∧ w ∈ Ico z₁ z₂) : ∃w, w ∈ Ico x₁ x₂ ∧ w ∉ Ico y₁ y₂ ∧ w ∈ Ico z₁ z₂ := begin simp at hw, refine ⟨max x₁ (min w y₂), _, _, _⟩, { simp [le_refl, lt_trans h₁ (lt_trans hy h₂), h₂] }, { simp [lt_irrefl, not_le_of_lt h₁], intros, apply hw.1, assumption }, { simp [hw.2.1, hw.2.2, hz₁, lt_of_lt_of_le h₁ hz₂] at ⊢ } end /-- A (hyper)-cube (in standard orientation) is a vector `b` consisting of the bottom-left point of the cube, a width `w` and a proof that `w > 0`. We use functions from `fin n` to denote vectors. -/ structure cube (n : ℕ) : Type := (b : fin n → ℝ) -- bottom-left coordinate (w : ℝ) -- width (hw : 0 < w) namespace cube lemma hw' (c : cube n) : 0 ≤ c.w := le_of_lt c.hw /-- The j-th side of a cube is the half-open interval `[b j, b j + w)` -/ def side (c : cube n) (j : fin n) : set ℝ := Ico (c.b j) (c.b j + c.w) @[simp] lemma b_mem_side (c : cube n) (j : fin n) : c.b j ∈ c.side j := by simp [side, cube.hw, le_refl] def to_set (c : cube n) : set (fin n → ℝ) := { x | ∀j, x j ∈ side c j } def to_set_subset {c c' : cube n} : c.to_set ⊆ c'.to_set ↔ ∀j, c.side j ⊆ c'.side j := begin split, intros h j x hx, let f : fin n → ℝ := λ j', if j' = j then x else c.b j', have : f ∈ c.to_set, { intro j', by_cases hj' : j' = j; simp [f, hj', if_pos, if_neg, hx] }, convert h this j, { simp [f, if_pos] }, intros h f hf j, exact h j (hf j) end def to_set_disjoint {c c' : cube n} : disjoint c.to_set c'.to_set ↔ ∃j, disjoint (c.side j) (c'.side j) := begin split, intros h, classical, by_contra h', simp only [not_disjoint_iff, classical.skolem, not_exists] at h', cases h' with f hf, apply not_disjoint_iff.mpr ⟨f, _, _⟩ h; intro j, exact (hf j).1, exact (hf j).2, rintro ⟨j, hj⟩, rw [set.disjoint_iff], rintros f ⟨h1f, h2f⟩, apply not_disjoint_iff.mpr ⟨f j, h1f j, h2f j⟩ hj end lemma b_mem_to_set (c : cube n) : c.b ∈ c.to_set := by simp [to_set] protected def tail (c : cube (n+1)) : cube n := ⟨tail c.b, c.w, c.hw⟩ lemma side_tail (c : cube (n+1)) (j : fin n) : c.tail.side j = c.side j.succ := rfl def bottom (c : cube (n+1)) : set (fin (n+1) → ℝ) := { x | x 0 = c.b 0 ∧ tail x ∈ c.tail.to_set } lemma b_mem_bottom (c : cube (n+1)) : c.b ∈ c.bottom := by simp [bottom, to_set, side, cube.hw, le_refl, cube.tail] def xm (c : cube (n+1)) : ℝ := c.b 0 + c.w lemma b_lt_xm (c : cube (n+1)) : c.b 0 < c.xm := by simp [xm, hw] lemma b_ne_xm (c : cube (n+1)) : c.b 0 ≠ c.xm := ne_of_lt c.b_lt_xm def shift_up (c : cube (n+1)) : cube (n+1) := ⟨cons c.xm $ tail c.b, c.w, c.hw⟩ @[simp] lemma tail_shift_up (c : cube (n+1)) : c.shift_up.tail = c.tail := by simp [shift_up, cube.tail] @[simp] lemma head_shift_up (c : cube (n+1)) : c.shift_up.b 0 = c.xm := rfl def unit_cube : cube n := ⟨λ _, 0, 1, by norm_num⟩ @[simp] lemma side_unit_cube {j : fin n} : unit_cube.side j = Ico 0 1 := by norm_num [unit_cube, side] end cube open cube variables {ι : Type} [fintype ι] {cs : ι → cube (n+1)} {i i' : ι} /-- A finite family of (at least 2) cubes partitioning the unit cube with different sizes -/ def correct (cs : ι → cube n) : Prop := pairwise (disjoint on (cube.to_set ∘ cs)) ∧ (⋃(i : ι), (cs i).to_set) = unit_cube.to_set ∧ injective (cube.w ∘ cs) ∧ 2 ≤ cardinal.mk ι ∧ 3 ≤ n variable (h : correct cs) include h lemma to_set_subset_unit_cube {i} : (cs i).to_set ⊆ unit_cube.to_set := by { rw [←h.2.1], exact subset_Union _ i } lemma side_subset {i j} : (cs i).side j ⊆ Ico 0 1 := by { have := to_set_subset_unit_cube h, rw [to_set_subset] at this, convert this j, norm_num [unit_cube] } lemma zero_le_of_mem_side {i j x} (hx : x ∈ (cs i).side j) : 0 ≤ x := (side_subset h hx).1 lemma zero_le_of_mem {i p} (hp : p ∈ (cs i).to_set) (j) : 0 ≤ p j := zero_le_of_mem_side h (hp j) lemma zero_le_b {i j} : 0 ≤ (cs i).b j := zero_le_of_mem h (cs i).b_mem_to_set j lemma b_add_w_le_one {j} : (cs i).b j + (cs i).w ≤ 1 := by { have := side_subset h, rw [side, Ico_subset_Ico_iff] at this, convert this.2, simp [hw] } /-- The width of any cube in the partition cannot be 1. -/ lemma w_ne_one (i : ι) : (cs i).w ≠ 1 := begin intro hi, have := h.2.2.2.1, rw [cardinal.two_le_iff' i] at this, cases this with i' hi', let p := (cs i').b, have hp : p ∈ (cs i').to_set := (cs i').b_mem_to_set, have h2p : p ∈ (cs i).to_set, { intro j, split, transitivity (0 : ℝ), { rw [←add_le_add_iff_right (1 : ℝ)], convert b_add_w_le_one h, rw hi, rw zero_add }, apply zero_le_b h, apply lt_of_lt_of_le (side_subset h $ (cs i').b_mem_side j).2, simp [hi, zero_le_b h] }, apply not_disjoint_iff.mpr ⟨p, hp, h2p⟩, apply h.1, exact hi'.symm end /-- The top of a cube (which is the bottom of the cube shifted up by its width) must be covered by bottoms of (other) cubes in the family. -/ lemma shift_up_bottom_subset_bottoms (hc : (cs i).xm ≠ 1) : (cs i).shift_up.bottom ⊆ ⋃(i : ι), (cs i).bottom := begin intros p hp, cases hp with hp0 hps, rw [tail_shift_up] at hps, have : p ∈ (unit_cube : cube (n+1)).to_set, { simp only [to_set, forall_fin_succ, hp0, side_unit_cube, mem_set_of_eq, mem_Ico, head_shift_up], refine ⟨⟨_, _⟩, _⟩, { rw [←zero_add (0 : ℝ)], apply add_le_add, apply zero_le_b h, apply (cs i).hw' }, { exact lt_of_le_of_ne (b_add_w_le_one h) hc }, intro j, exact side_subset h (hps j) }, rw [←h.2.1] at this, rcases this with ⟨_, ⟨i', rfl⟩, hi'⟩, rw [mem_Union], use i', refine ⟨_, λ j, hi' j.succ⟩, have : i ≠ i', { rintro rfl, apply not_le_of_lt (hi' 0).2, rw [hp0], refl }, have := h.1 i i' this, rw [on_fun, to_set_disjoint, exists_fin_succ] at this, rcases this with h0|⟨j, hj⟩, rw [hp0], symmetry, apply eq_of_Ico_disjoint h0 (by simp [hw]) _, convert hi' 0, rw [hp0], refl, exfalso, apply not_disjoint_iff.mpr ⟨tail p j, hps j, hi' j.succ⟩ hj end omit h /-- A valley is a square on which cubes in the family of cubes are placed, so that the cubes completely cover the valley and none of those cubes is partially outside the square. We also require that no cube on it has the same size as the valley (so that there are at least two cubes on the valley). This is the main concept in the formalization. We prove that the smallest cube on a valley has another valley on the top of it, which gives an infinite sequence of cubes in the partition, which contradicts the finiteness. A valley is characterized by a cube `c` (which is not a cube in the family cs) by considering the bottom face of `c`. -/ def valley (cs : ι → cube (n+1)) (c : cube (n+1)) : Prop := c.bottom ⊆ (⋃(i : ι), (cs i).bottom) ∧ (∀i, (cs i).b 0 = c.b 0 → (∃x, x ∈ (cs i).tail.to_set ∩ c.tail.to_set) → (cs i).tail.to_set ⊆ c.tail.to_set) ∧ ∀(i : ι), (cs i).b 0 = c.b 0 → (cs i).w ≠ c.w variables {c : cube (n+1)} (v : valley cs c) /-- The bottom of the unit cube is a valley -/ lemma valley_unit_cube (h : correct cs) : valley cs unit_cube := begin refine ⟨_, _, _⟩, { intro v, simp [bottom], intros h0 hv, have : v ∈ (unit_cube : cube (n+1)).to_set, { dsimp [to_set], rw [forall_fin_succ, h0], split, norm_num [side, unit_cube], exact hv }, rw [←h.2.1] at this, rcases this with ⟨_, ⟨i, rfl⟩, hi⟩, use i, split, { apply le_antisymm, rw h0, exact zero_le_b h, exact (hi 0).1 }, intro j, exact hi _ }, { intros i hi h', rw to_set_subset, intro j, convert side_subset h, simp [side_tail] }, { intros i hi, exact w_ne_one h i } end /-- the cubes which lie in the valley `c` -/ def bcubes (cs : ι → cube (n+1)) (c : cube (n+1)) : set ι := { i : ι | (cs i).b 0 = c.b 0 ∧ (cs i).tail.to_set ⊆ c.tail.to_set } /-- A cube which lies on the boundary of a valley in dimension `j` -/ def on_boundary (hi : i ∈ bcubes cs c) (j : fin n) : Prop := c.b j.succ = (cs i).b j.succ ∨ (cs i).b j.succ + (cs i).w = c.b j.succ + c.w lemma tail_sub (hi : i ∈ bcubes cs c) : ∀j, (cs i).tail.side j ⊆ c.tail.side j := by { rw [←to_set_subset], exact hi.2 } lemma bottom_mem_side (hi : i ∈ bcubes cs c) : c.b 0 ∈ (cs i).side 0 := by { convert b_mem_side (cs i) _ using 1, rw hi.1 } lemma b_le_b (hi : i ∈ bcubes cs c) (j : fin n) : c.b j.succ ≤ (cs i).b j.succ := (tail_sub hi j $ b_mem_side _ _).1 lemma t_le_t (hi : i ∈ bcubes cs c) (j : fin n) : (cs i).b j.succ + (cs i).w ≤ c.b j.succ + c.w := begin have h' := tail_sub hi j, dsimp only [side] at h', rw [Ico_subset_Ico_iff] at h', exact h'.2, simp [hw] end include h v /-- Every cube in the valley must be smaller than it -/ lemma w_lt_w (hi : i ∈ bcubes cs c) : (cs i).w < c.w := begin apply lt_of_le_of_ne _ (v.2.2 i hi.1), have j : fin n := ⟨1, nat.le_of_succ_le_succ h.2.2.2.2⟩, rw [←add_le_add_iff_left ((cs i).b j.succ)], apply le_trans (t_le_t hi j), rw [add_le_add_iff_right], apply b_le_b hi, end open cardinal /-- There are at least two cubes in a valley -/ lemma two_le_mk_bcubes : 2 ≤ cardinal.mk (bcubes cs c) := begin rw [two_le_iff], rcases v.1 c.b_mem_bottom with ⟨_, ⟨i, rfl⟩, hi⟩, have h2i : i ∈ bcubes cs c := ⟨hi.1.symm, v.2.1 i hi.1.symm ⟨tail c.b, hi.2, λ j, c.b_mem_side j.succ⟩⟩, let j : fin (n+1) := ⟨2, h.2.2.2.2⟩, have hj : 0 ≠ j := by { simp only [fin.ext_iff, ne.def], contradiction }, let p : fin (n+1) → ℝ := λ j', if j' = j then c.b j + (cs i).w else c.b j', have hp : p ∈ c.bottom, { split, { simp only [bottom, p, if_neg hj] }, intro j', simp [tail, side_tail], by_cases hj' : j'.succ = j, { simp [p, -add_comm, if_pos, side, hj', hw', w_lt_w h v h2i] }, { simp [p, -add_comm, if_neg hj'] }}, rcases v.1 hp with ⟨_, ⟨i', rfl⟩, hi'⟩, have h2i' : i' ∈ bcubes cs c := ⟨hi'.1.symm, v.2.1 i' hi'.1.symm ⟨tail p, hi'.2, hp.2⟩⟩, refine ⟨⟨i, h2i⟩, ⟨i', h2i'⟩, _⟩, intro hii', cases congr_arg subtype.val hii', apply not_le_of_lt (hi'.2 ⟨1, nat.le_of_succ_le_succ h.2.2.2.2⟩).2, simp only [-add_comm, tail, cube.tail, p], rw [if_pos], simp [-add_comm], exact (hi.2 _).1, refl end /-- There is a cube in the valley -/ lemma nonempty_bcubes : (bcubes cs c).nonempty := begin rw [←set.ne_empty_iff_nonempty], intro h', have := two_le_mk_bcubes h v, rw h' at this, apply not_lt_of_le this, rw mk_emptyc, norm_cast, norm_num end /-- There is a smallest cube in the valley -/ lemma exists_mi : ∃(i : ι), i ∈ bcubes cs c ∧ ∀(i' ∈ bcubes cs c), (cs i).w ≤ (cs i').w := by simpa using (bcubes cs c).exists_min_image (λ i, (cs i).w) (finite.of_fintype _) (nonempty_bcubes h v) /-- We let `mi` be the (index for the) smallest cube in the valley `c` -/ def mi : ι := classical.some $ exists_mi h v variables {h v} lemma mi_mem_bcubes : mi h v ∈ bcubes cs c := (classical.some_spec $ exists_mi h v).1 lemma mi_minimal (hi : i ∈ bcubes cs c) : (cs $ mi h v).w ≤ (cs i).w := (classical.some_spec $ exists_mi h v).2 i hi lemma mi_strict_minimal (hii' : mi h v ≠ i) (hi : i ∈ bcubes cs c) : (cs $ mi h v).w < (cs i).w := by { apply lt_of_le_of_ne (mi_minimal hi), apply h.2.2.1.ne, apply hii' } /-- The top of `mi` cannot be 1, since there is a larger cube in the valley -/ lemma mi_xm_ne_one : (cs $ mi h v).xm ≠ 1 := begin apply ne_of_lt, rcases (two_le_iff' _).mp (two_le_mk_bcubes h v) with ⟨⟨i, hi⟩, h2i⟩, swap, exact ⟨mi h v, mi_mem_bcubes⟩, apply lt_of_lt_of_le _ (b_add_w_le_one h), exact i, exact 0, rw [xm, mi_mem_bcubes.1, hi.1, _root_.add_lt_add_iff_left], apply mi_strict_minimal _ hi, intro h', apply h2i, rw subtype.ext_iff_val, exact h' end /-- If `mi` lies on the boundary of the valley in dimension j, then this lemma expresses that all other cubes on the same boundary extend further from the boundary. More precisely, there is a j-th coordinate `x : ℝ` in the valley, but not in `mi`, such that every cube that shares a (particular) j-th coordinate with `mi` also contains j-th coordinate `x` -/ lemma smallest_on_boundary {j} (bi : on_boundary (mi_mem_bcubes : mi h v ∈ _) j) : ∃(x : ℝ), x ∈ c.side j.succ \ (cs $ mi h v).side j.succ ∧ ∀{{i'}} (hi' : i' ∈ bcubes cs c), i' ≠ mi h v → (cs $ mi h v).b j.succ ∈ (cs i').side j.succ → x ∈ (cs i').side j.succ := begin let i := mi h v, have hi : i ∈ bcubes cs c := mi_mem_bcubes, cases bi, { refine ⟨(cs i).b j.succ + (cs i).w, ⟨_, _⟩, _⟩, { simp [side, bi, hw', w_lt_w h v hi] }, { intro h', simpa [i, lt_irrefl] using h'.2 }, intros i' hi' i'_i h2i', split, apply le_trans h2i'.1, { simp [hw'] }, apply lt_of_lt_of_le (add_lt_add_left (mi_strict_minimal i'_i.symm hi') _), simp [bi.symm, b_le_b hi'] }, let s := bcubes cs c \ { i }, have hs : s.nonempty, { rcases (two_le_iff' (⟨i, hi⟩ : bcubes cs c)).mp (two_le_mk_bcubes h v) with ⟨⟨i', hi'⟩, h2i'⟩, refine ⟨i', hi', _⟩, simp only [mem_singleton_iff], intro h, apply h2i', simp [h] }, rcases set.exists_min_image s (w ∘ cs) (finite.of_fintype _) hs with ⟨i', ⟨hi', h2i'⟩, h3i'⟩, rw [mem_singleton_iff] at h2i', let x := c.b j.succ + c.w - (cs i').w, have hx : x < (cs i).b j.succ, { dsimp only [x], rw [←bi, add_sub_assoc, add_lt_iff_neg_left, sub_lt_zero], apply mi_strict_minimal (ne.symm h2i') hi' }, refine ⟨x, ⟨_, _⟩, _⟩, { simp only [side, x, -add_comm, -add_assoc, neg_lt_zero, hw, add_lt_iff_neg_left, and_true, mem_Ico, sub_eq_add_neg], rw [add_assoc, le_add_iff_nonneg_right, ←sub_eq_add_neg, sub_nonneg], apply le_of_lt (w_lt_w h v hi') }, { simp only [side, not_and_distrib, not_lt, add_comm, not_le, mem_Ico], left, exact hx }, intros i'' hi'' h2i'' h3i'', split, swap, apply lt_trans hx h3i''.2, simp only [x], rw [le_sub_iff_add_le], refine le_trans _ (t_le_t hi'' j), rw [add_le_add_iff_left], apply h3i' i'' ⟨hi'', _⟩, simp [mem_singleton, h2i''] end variables (h v) /-- `mi` cannot lie on the boundary of the valley. Otherwise, the cube adjacent to it in the `j`-th direction will intersect one of the neighbouring cubes on the same boundary as `mi`. -/ lemma mi_not_on_boundary (j : fin n) : ¬on_boundary (mi_mem_bcubes : mi h v ∈ _) j := begin let i := mi h v, have hi : i ∈ bcubes cs c := mi_mem_bcubes, rcases (two_le_iff' j).mp _ with ⟨j', hj'⟩, swap, { rw [mk_fin, ←nat.cast_two, nat_cast_le], apply nat.le_of_succ_le_succ h.2.2.2.2 }, intro hj, rcases smallest_on_boundary hj with ⟨x, ⟨hx, h2x⟩, h3x⟩, let p : fin (n+1) → ℝ := cons (c.b 0) (λ j₂, if j₂ = j then x else (cs i).b j₂.succ), have hp : p ∈ c.bottom, { simp [bottom, p, to_set, tail, side_tail], intro j₂, by_cases hj₂ : j₂ = j, simp [hj₂, hx], simp [hj₂], apply tail_sub hi, apply b_mem_side }, rcases v.1 hp with ⟨_, ⟨i', rfl⟩, hi'⟩, have h2i' : i' ∈ bcubes cs c := ⟨hi'.1.symm, v.2.1 i' hi'.1.symm ⟨tail p, hi'.2, hp.2⟩⟩, have i_i' : i ≠ i', { rintro rfl, simpa [p, side_tail, i, h2x] using hi'.2 j }, have : nonempty ↥((cs i').tail.side j' \ (cs i).tail.side j'), { apply nonempty_Ico_sdiff, apply mi_strict_minimal i_i' h2i', apply hw }, rcases this with ⟨⟨x', hx'⟩⟩, let p' : fin (n+1) → ℝ := cons (c.b 0) (λ j₂, if j₂ = j' then x' else (cs i).b j₂.succ), have hp' : p' ∈ c.bottom, { simp [bottom, p', to_set, tail, side_tail], intro j₂, by_cases hj₂ : j₂ = j', simp [hj₂], apply tail_sub h2i', apply hx'.1, simp [hj₂], apply tail_sub hi, apply b_mem_side }, rcases v.1 hp' with ⟨_, ⟨i'', rfl⟩, hi''⟩, have h2i'' : i'' ∈ bcubes cs c := ⟨hi''.1.symm, v.2.1 i'' hi''.1.symm ⟨tail p', hi''.2, hp'.2⟩⟩, have i'_i'' : i' ≠ i'', { rintro ⟨⟩, have : (cs i).b ∈ (cs i').to_set, { simp [to_set, forall_fin_succ, hi.1, bottom_mem_side h2i'], intro j₂, by_cases hj₂ : j₂ = j, simpa [side_tail, p', hj', hj₂] using hi''.2 j, simpa [hj₂] using hi'.2 j₂ }, apply not_disjoint_iff.mpr ⟨(cs i).b, (cs i).b_mem_to_set, this⟩ (h.1 i i' i_i') }, have i_i'' : i ≠ i'', { intro h, induction h, simpa [hx'.2] using hi''.2 j' }, apply not.elim _ (h.1 i' i'' i'_i''), simp only [on_fun, to_set_disjoint, not_disjoint_iff, forall_fin_succ, not_exists, comp_app], refine ⟨⟨c.b 0, bottom_mem_side h2i', bottom_mem_side h2i''⟩, _⟩, intro j₂, by_cases hj₂ : j₂ = j, { cases hj₂, refine ⟨x, _, _⟩, { convert hi'.2 j, simp [p] }, apply h3x h2i'' i_i''.symm, convert hi''.2 j, simp [p', hj'] }, by_cases h2j₂ : j₂ = j', { cases h2j₂, refine ⟨x', hx'.1, _⟩, convert hi''.2 j', simp }, refine ⟨(cs i).b j₂.succ, _, _⟩, { convert hi'.2 j₂, simp [hj₂] }, { convert hi''.2 j₂, simp [h2j₂] } end variables {h v} /-- The same result that `mi` cannot lie on the boundary of the valley written as inequalities. -/ lemma mi_not_on_boundary' (j : fin n) : c.tail.b j < (cs (mi h v)).tail.b j ∧ (cs (mi h v)).tail.b j + (cs (mi h v)).w < c.tail.b j + c.w := begin have := mi_not_on_boundary h v j, simp only [on_boundary, not_or_distrib] at this, cases this with h1 h2, split, apply lt_of_le_of_ne (b_le_b mi_mem_bcubes _) h1, apply lt_of_le_of_ne _ h2, apply ((Ico_subset_Ico_iff _).mp (tail_sub mi_mem_bcubes j)).2, simp [hw] end /-- The top of `mi` gives rise to a new valley, since the neighbouring cubes extend further upward than `mi`. -/ def valley_mi : valley cs ((cs (mi h v)).shift_up) := begin let i := mi h v, have hi : i ∈ bcubes cs c := mi_mem_bcubes, refine ⟨_, _, _⟩, { intro p, apply shift_up_bottom_subset_bottoms h mi_xm_ne_one }, { rintros i' hi' ⟨p2, hp2, h2p2⟩, simp only [head_shift_up] at hi', classical, by_contra h2i', rw [tail_shift_up] at h2p2, simp only [not_subset, tail_shift_up] at h2i', rcases h2i' with ⟨p1, hp1, h2p1⟩, have : ∃p3, p3 ∈ (cs i').tail.to_set ∧ p3 ∉ (cs i).tail.to_set ∧ p3 ∈ c.tail.to_set, { simp [to_set, not_forall] at h2p1, cases h2p1 with j hj, rcases Ico_lemma (mi_not_on_boundary' j).1 (by simp [hw]) (mi_not_on_boundary' j).2 (le_trans (hp2 j).1 $ le_of_lt (h2p2 j).2) (le_trans (h2p2 j).1 $ le_of_lt (hp2 j).2) ⟨hj, hp1 j⟩ with ⟨w, hw, h2w, h3w⟩, refine ⟨λ j', if j' = j then w else p2 j', _, _, _⟩, { intro j', by_cases h : j' = j, simp [if_pos h], convert h3w, simp [if_neg h], exact hp2 j' }, { simp [to_set, not_forall], use j, rw [if_pos rfl], convert h2w }, { intro j', by_cases h : j' = j, simp [if_pos h, side_tail], convert hw, simp [if_neg h], apply hi.2, apply h2p2 }}, rcases this with ⟨p3, h1p3, h2p3, h3p3⟩, let p := @cons n (λ_, ℝ) (c.b 0) p3, have hp : p ∈ c.bottom, { refine ⟨rfl, _⟩, rwa [tail_cons] }, rcases v.1 hp with ⟨_, ⟨i'', rfl⟩, hi''⟩, have h2i'' : i'' ∈ bcubes cs c, { use hi''.1.symm, apply v.2.1 i'' hi''.1.symm, use tail p, split, exact hi''.2, rw [tail_cons], exact h3p3 }, have h3i'' : (cs i).w < (cs i'').w, { apply mi_strict_minimal _ h2i'', rintro rfl, apply h2p3, convert hi''.2, rw [tail_cons] }, let p' := @cons n (λ_, ℝ) (cs i).xm p3, have hp' : p' ∈ (cs i').to_set, { simpa [to_set, forall_fin_succ, p', hi'.symm] using h1p3 }, have h2p' : p' ∈ (cs i'').to_set, { simp [to_set, forall_fin_succ, p'], refine ⟨_, by simpa [to_set, p] using hi''.2⟩, have : (cs i).b 0 = (cs i'').b 0, { by rw [hi.1, h2i''.1] }, simp [side, hw', xm, this, h3i''] }, apply not_disjoint_iff.mpr ⟨p', hp', h2p'⟩, apply h.1, rintro rfl, apply (cs i).b_ne_xm, rw [←hi', ←hi''.1, hi.1], refl }, { intros i' hi' h2i', dsimp [shift_up] at h2i', replace h2i' := h.2.2.1 h2i'.symm, induction h2i', exact b_ne_xm (cs i) hi' } end variables (h) omit v /-- We get a sequence of cubes whose size is decreasing -/ noncomputable def sequence_of_cubes : ℕ → { i : ι // valley cs ((cs i).shift_up) } | 0 := let v := valley_unit_cube h in ⟨mi h v, valley_mi⟩ | (k+1) := let v := (sequence_of_cubes k).2 in ⟨mi h v, valley_mi⟩ def decreasing_sequence (k : ℕ) : order_dual ℝ := (cs (sequence_of_cubes h k).1).w lemma strict_mono_sequence_of_cubes : strict_mono $ decreasing_sequence h := strict_mono.nat $ begin intro k, let v := (sequence_of_cubes h k).2, dsimp [decreasing_sequence, sequence_of_cubes], apply w_lt_w h v (mi_mem_bcubes : mi h v ∈ _), end omit h /-- The infinite sequence of cubes contradicts the finiteness of the family. -/ theorem not_correct : ¬correct cs := begin intro h, apply not_le_of_lt (lt_omega_iff_fintype.mpr ⟨_inst_1⟩), rw [omega, lift_id], fapply mk_le_of_injective, exact λ n, (sequence_of_cubes h n).1, intros n m hnm, apply strict_mono.injective (strict_mono_sequence_of_cubes h), dsimp only [decreasing_sequence], rw hnm end /-- A cube cannot be cubed. -/ theorem cannot_cube_a_cube : ∀{n : ℕ}, n ≥ 3 → -- In ℝ^n for n ≥ 3 ∀{ι : Type} [fintype ι] {cs : ι → cube n}, -- given a finite collection of (hyper)cubes 2 ≤ cardinal.mk ι → -- containing at least two elements pairwise (disjoint on (cube.to_set ∘ cs)) → -- which is pairwise disjoint (⋃(i : ι), (cs i).to_set) = unit_cube.to_set → -- whose union is the unit cube injective (cube.w ∘ cs) → -- such that the widths of all cubes are different false := -- then we can derive a contradiction begin intros n hn ι hι cs h1 h2 h3 h4, resetI, rcases n, cases hn, exact not_correct ⟨h2, h3, h4, h1, hn⟩ end
59bf73669a50732f1da331cf63525b47f9907137
94e33a31faa76775069b071adea97e86e218a8ee
/src/analysis/calculus/cont_diff.lean
857287bc40dcb9d7fe4c8cd1ca277166c6d45715
[ "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
149,259
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.calculus.mean_value import analysis.normed_space.multilinear import analysis.calculus.formal_multilinear_series import tactic.congrm /-! # Higher differentiability A function is `C^1` on a domain if it is differentiable there, and its derivative is continuous. By induction, it is `C^n` if it is `C^{n-1}` and its (n-1)-th derivative is `C^1` there or, equivalently, if it is `C^1` and its derivative is `C^{n-1}`. Finally, it is `C^∞` if it is `C^n` for all n. We formalize these notions by defining iteratively the `n+1`-th derivative of a function as the derivative of the `n`-th derivative. It is called `iterated_fderiv 𝕜 n f x` where `𝕜` is the field, `n` is the number of iterations, `f` is the function and `x` is the point, and it is given as an `n`-multilinear map. We also define a version `iterated_fderiv_within` relative to a domain, as well as predicates `cont_diff_within_at`, `cont_diff_at`, `cont_diff_on` and `cont_diff` saying that the function is `C^n` within a set at a point, at a point, on a set and on the whole space respectively. To avoid the issue of choice when choosing a derivative in sets where the derivative is not necessarily unique, `cont_diff_on` is not defined directly in terms of the regularity of the specific choice `iterated_fderiv_within 𝕜 n f s` inside `s`, but in terms of the existence of a nice sequence of derivatives, expressed with a predicate `has_ftaylor_series_up_to_on`. We prove basic properties of these notions. ## Main definitions and results Let `f : E → F` be a map between normed vector spaces over a nondiscrete normed field `𝕜`. * `has_ftaylor_series_up_to n f p`: expresses that the formal multilinear series `p` is a sequence of iterated derivatives of `f`, up to the `n`-th term (where `n` is a natural number or `∞`). * `has_ftaylor_series_up_to_on n f p s`: same thing, but inside a set `s`. The notion of derivative is now taken inside `s`. In particular, derivatives don't have to be unique. * `cont_diff 𝕜 n f`: expresses that `f` is `C^n`, i.e., it admits a Taylor series up to rank `n`. * `cont_diff_on 𝕜 n f s`: expresses that `f` is `C^n` in `s`. * `cont_diff_at 𝕜 n f x`: expresses that `f` is `C^n` around `x`. * `cont_diff_within_at 𝕜 n f s x`: expresses that `f` is `C^n` around `x` within the set `s`. * `iterated_fderiv_within 𝕜 n f s x` is an `n`-th derivative of `f` over the field `𝕜` on the set `s` at the point `x`. It is a continuous multilinear map from `E^n` to `F`, defined as a derivative within `s` of `iterated_fderiv_within 𝕜 (n-1) f s` if one exists, and `0` otherwise. * `iterated_fderiv 𝕜 n f x` is the `n`-th derivative of `f` over the field `𝕜` at the point `x`. It is a continuous multilinear map from `E^n` to `F`, defined as a derivative of `iterated_fderiv 𝕜 (n-1) f` if one exists, and `0` otherwise. In sets of unique differentiability, `cont_diff_on 𝕜 n f s` can be expressed in terms of the properties of `iterated_fderiv_within 𝕜 m f s` for `m ≤ n`. In the whole space, `cont_diff 𝕜 n f` can be expressed in terms of the properties of `iterated_fderiv 𝕜 m f` for `m ≤ n`. We also prove that the usual operations (addition, multiplication, difference, composition, and so on) preserve `C^n` functions. ## Implementation notes The definitions in this file are designed to work on any field `𝕜`. They are sometimes slightly more complicated than the naive definitions one would guess from the intuition over the real or complex numbers, but they are designed to circumvent the lack of gluing properties and partitions of unity in general. In the usual situations, they coincide with the usual definitions. ### Definition of `C^n` functions in domains One could define `C^n` functions in a domain `s` by fixing an arbitrary choice of derivatives (this is what we do with `iterated_fderiv_within`) and requiring that all these derivatives up to `n` are continuous. If the derivative is not unique, this could lead to strange behavior like two `C^n` functions `f` and `g` on `s` whose sum is not `C^n`. A better definition is thus to say that a function is `C^n` inside `s` if it admits a sequence of derivatives up to `n` inside `s`. This definition still has the problem that a function which is locally `C^n` would not need to be `C^n`, as different choices of sequences of derivatives around different points might possibly not be glued together to give a globally defined sequence of derivatives. (Note that this issue can not happen over reals, thanks to partition of unity, but the behavior over a general field is not so clear, and we want a definition for general fields). Also, there are locality problems for the order parameter: one could image a function which, for each `n`, has a nice sequence of derivatives up to order `n`, but they do not coincide for varying `n` and can therefore not be glued to give rise to an infinite sequence of derivatives. This would give a function which is `C^n` for all `n`, but not `C^∞`. We solve this issue by putting locality conditions in space and order in our definition of `cont_diff_within_at` and `cont_diff_on`. The resulting definition is slightly more complicated to work with (in fact not so much), but it gives rise to completely satisfactory theorems. For instance, with this definition, a real function which is `C^m` (but not better) on `(-1/m, 1/m)` for each natural `m` is by definition `C^∞` at `0`. There is another issue with the definition of `cont_diff_within_at 𝕜 n f s x`. We can require the existence and good behavior of derivatives up to order `n` on a neighborhood of `x` within `s`. However, this does not imply continuity or differentiability within `s` of the function at `x` when `x` does not belong to `s`. Therefore, we require such existence and good behavior on a neighborhood of `x` within `s ∪ {x}` (which appears as `insert x s` in this file). ### Side of the composition, and universe issues With a naïve direct definition, the `n`-th derivative of a function belongs to the space `E →L[𝕜] (E →L[𝕜] (E ... F)...)))` where there are n iterations of `E →L[𝕜]`. This space may also be seen as the space of continuous multilinear functions on `n` copies of `E` with values in `F`, by uncurrying. This is the point of view that is usually adopted in textbooks, and that we also use. This means that the definition and the first proofs are slightly involved, as one has to keep track of the uncurrying operation. The uncurrying can be done from the left or from the right, amounting to defining the `n+1`-th derivative either as the derivative of the `n`-th derivative, or as the `n`-th derivative of the derivative. For proofs, it would be more convenient to use the latter approach (from the right), as it means to prove things at the `n+1`-th step we only need to understand well enough the derivative in `E →L[𝕜] F` (contrary to the approach from the left, where one would need to know enough on the `n`-th derivative to deduce things on the `n+1`-th derivative). However, the definition from the right leads to a universe polymorphism problem: if we define `iterated_fderiv 𝕜 (n + 1) f x = iterated_fderiv 𝕜 n (fderiv 𝕜 f) x` by induction, we need to generalize over all spaces (as `f` and `fderiv 𝕜 f` don't take values in the same space). It is only possible to generalize over all spaces in some fixed universe in an inductive definition. For `f : E → F`, then `fderiv 𝕜 f` is a map `E → (E →L[𝕜] F)`. Therefore, the definition will only work if `F` and `E →L[𝕜] F` are in the same universe. This issue does not appear with the definition from the left, where one does not need to generalize over all spaces. Therefore, we use the definition from the left. This means some proofs later on become a little bit more complicated: to prove that a function is `C^n`, the most efficient approach is to exhibit a formula for its `n`-th derivative and prove it is continuous (contrary to the inductive approach where one would prove smoothness statements without giving a formula for the derivative). In the end, this approach is still satisfactory as it is good to have formulas for the iterated derivatives in various constructions. One point where we depart from this explicit approach is in the proof of smoothness of a composition: there is a formula for the `n`-th derivative of a composition (Faà di Bruno's formula), but it is very complicated and barely usable, while the inductive proof is very simple. Thus, we give the inductive proof. As explained above, it works by generalizing over the target space, hence it only works well if all spaces belong to the same universe. To get the general version, we lift things to a common universe using a trick. ### Variables management The textbook definitions and proofs use various identifications and abuse of notations, for instance when saying that the natural space in which the derivative lives, i.e., `E →L[𝕜] (E →L[𝕜] ( ... →L[𝕜] F))`, is the same as a space of multilinear maps. When doing things formally, we need to provide explicit maps for these identifications, and chase some diagrams to see everything is compatible with the identifications. In particular, one needs to check that taking the derivative and then doing the identification, or first doing the identification and then taking the derivative, gives the same result. The key point for this is that taking the derivative commutes with continuous linear equivalences. Therefore, we need to implement all our identifications with continuous linear equivs. ## Notations We use the notation `E [×n]→L[𝕜] F` for the space of continuous multilinear maps on `E^n` with values in `F`. This is the space in which the `n`-th derivative of a function from `E` to `F` lives. In this file, we denote `⊤ : with_top ℕ` with `∞`. ## Tags derivative, differentiability, higher derivative, `C^n`, multilinear, Taylor series, formal series -/ noncomputable theory open_locale classical big_operators nnreal local notation `∞` := (⊤ : with_top ℕ) universes u v w local attribute [instance, priority 1001] normed_group.to_add_comm_group normed_space.to_module' add_comm_group.to_add_comm_monoid open set fin filter open_locale topological_space 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] {X : Type*} [normed_group X] [normed_space 𝕜 X] {s s₁ t u : set E} {f f₁ : E → F} {g : F → G} {x : E} {c : F} {b : E × F → G} {m n : with_top ℕ} /-! ### Functions with a Taylor series on a domain -/ variable {p : E → formal_multilinear_series 𝕜 E F} /-- `has_ftaylor_series_up_to_on n f p s` registers the fact that `p 0 = f` and `p (m+1)` is a derivative of `p m` for `m < n`, and is continuous for `m ≤ n`. This is a predicate analogous to `has_fderiv_within_at` but for higher order derivatives. -/ structure has_ftaylor_series_up_to_on (n : with_top ℕ) (f : E → F) (p : E → formal_multilinear_series 𝕜 E F) (s : set E) : Prop := (zero_eq : ∀ x ∈ s, (p x 0).uncurry0 = f x) (fderiv_within : ∀ (m : ℕ) (hm : (m : with_top ℕ) < n), ∀ x ∈ s, has_fderiv_within_at (λ y, p y m) (p x m.succ).curry_left s x) (cont : ∀ (m : ℕ) (hm : (m : with_top ℕ) ≤ n), continuous_on (λ x, p x m) s) lemma has_ftaylor_series_up_to_on.zero_eq' (h : has_ftaylor_series_up_to_on n f p s) {x : E} (hx : x ∈ s) : p x 0 = (continuous_multilinear_curry_fin0 𝕜 E F).symm (f x) := by { rw ← h.zero_eq x hx, symmetry, exact continuous_multilinear_map.uncurry0_curry0 _ } /-- If two functions coincide on a set `s`, then a Taylor series for the first one is as well a Taylor series for the second one. -/ lemma has_ftaylor_series_up_to_on.congr (h : has_ftaylor_series_up_to_on n f p s) (h₁ : ∀ x ∈ s, f₁ x = f x) : has_ftaylor_series_up_to_on n f₁ p s := begin refine ⟨λ x hx, _, h.fderiv_within, h.cont⟩, rw h₁ x hx, exact h.zero_eq x hx end lemma has_ftaylor_series_up_to_on.mono (h : has_ftaylor_series_up_to_on n f p s) {t : set E} (hst : t ⊆ s) : has_ftaylor_series_up_to_on n f p t := ⟨λ x hx, h.zero_eq x (hst hx), λ m hm x hx, (h.fderiv_within m hm x (hst hx)).mono hst, λ m hm, (h.cont m hm).mono hst⟩ lemma has_ftaylor_series_up_to_on.of_le (h : has_ftaylor_series_up_to_on n f p s) (hmn : m ≤ n) : has_ftaylor_series_up_to_on m f p s := ⟨h.zero_eq, λ k hk x hx, h.fderiv_within k (lt_of_lt_of_le hk hmn) x hx, λ k hk, h.cont k (le_trans hk hmn)⟩ lemma has_ftaylor_series_up_to_on.continuous_on (h : has_ftaylor_series_up_to_on n f p s) : continuous_on f s := begin have := (h.cont 0 bot_le).congr (λ x hx, (h.zero_eq' hx).symm), rwa linear_isometry_equiv.comp_continuous_on_iff at this end lemma has_ftaylor_series_up_to_on_zero_iff : has_ftaylor_series_up_to_on 0 f p s ↔ continuous_on f s ∧ (∀ x ∈ s, (p x 0).uncurry0 = f x) := begin refine ⟨λ H, ⟨H.continuous_on, H.zero_eq⟩, λ H, ⟨H.2, λ m hm, false.elim (not_le.2 hm bot_le), _⟩⟩, assume m hm, obtain rfl : m = 0, by exact_mod_cast (hm.antisymm (zero_le _)), have : ∀ x ∈ s, p x 0 = (continuous_multilinear_curry_fin0 𝕜 E F).symm (f x), by { assume x hx, rw ← H.2 x hx, symmetry, exact continuous_multilinear_map.uncurry0_curry0 _ }, rw [continuous_on_congr this, linear_isometry_equiv.comp_continuous_on_iff], exact H.1 end lemma has_ftaylor_series_up_to_on_top_iff : (has_ftaylor_series_up_to_on ∞ f p s) ↔ (∀ (n : ℕ), has_ftaylor_series_up_to_on n f p s) := begin split, { assume H n, exact H.of_le le_top }, { assume H, split, { exact (H 0).zero_eq }, { assume m hm, apply (H m.succ).fderiv_within m (with_top.coe_lt_coe.2 (lt_add_one m)) }, { assume m hm, apply (H m).cont m le_rfl } } end /-- If a function has a Taylor series at order at least `1`, then the term of order `1` of this series is a derivative of `f`. -/ lemma has_ftaylor_series_up_to_on.has_fderiv_within_at (h : has_ftaylor_series_up_to_on n f p s) (hn : 1 ≤ n) (hx : x ∈ s) : has_fderiv_within_at f (continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) s x := begin have A : ∀ y ∈ s, f y = (continuous_multilinear_curry_fin0 𝕜 E F) (p y 0), { assume y hy, rw ← h.zero_eq y hy, refl }, suffices H : has_fderiv_within_at (λ y, continuous_multilinear_curry_fin0 𝕜 E F (p y 0)) (continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) s x, by exact H.congr A (A x hx), rw linear_isometry_equiv.comp_has_fderiv_within_at_iff', have : ((0 : ℕ) : with_top ℕ) < n := lt_of_lt_of_le (with_top.coe_lt_coe.2 nat.zero_lt_one) hn, convert h.fderiv_within _ this x hx, ext y v, change (p x 1) (snoc 0 y) = (p x 1) (cons y v), unfold_coes, congr' with i, rw unique.eq_default i, refl end lemma has_ftaylor_series_up_to_on.differentiable_on (h : has_ftaylor_series_up_to_on n f p s) (hn : 1 ≤ n) : differentiable_on 𝕜 f s := λ x hx, (h.has_fderiv_within_at hn hx).differentiable_within_at /-- If a function has a Taylor series at order at least `1` on a neighborhood of `x`, then the term of order `1` of this series is a derivative of `f` at `x`. -/ lemma has_ftaylor_series_up_to_on.has_fderiv_at (h : has_ftaylor_series_up_to_on n f p s) (hn : 1 ≤ n) (hx : s ∈ 𝓝 x) : has_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) x := (h.has_fderiv_within_at hn (mem_of_mem_nhds hx)).has_fderiv_at hx /-- If a function has a Taylor series at order at least `1` on a neighborhood of `x`, then in a neighborhood of `x`, the term of order `1` of this series is a derivative of `f`. -/ lemma has_ftaylor_series_up_to_on.eventually_has_fderiv_at (h : has_ftaylor_series_up_to_on n f p s) (hn : 1 ≤ n) (hx : s ∈ 𝓝 x) : ∀ᶠ y in 𝓝 x, has_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p y 1)) y := (eventually_eventually_nhds.2 hx).mono $ λ y hy, h.has_fderiv_at hn hy /-- If a function has a Taylor series at order at least `1` on a neighborhood of `x`, then it is differentiable at `x`. -/ lemma has_ftaylor_series_up_to_on.differentiable_at (h : has_ftaylor_series_up_to_on n f p s) (hn : 1 ≤ n) (hx : s ∈ 𝓝 x) : differentiable_at 𝕜 f x := (h.has_fderiv_at hn hx).differentiable_at /-- `p` is a Taylor series of `f` up to `n+1` if and only if `p` is a Taylor series up to `n`, and `p (n + 1)` is a derivative of `p n`. -/ theorem has_ftaylor_series_up_to_on_succ_iff_left {n : ℕ} : has_ftaylor_series_up_to_on (n + 1) f p s ↔ has_ftaylor_series_up_to_on n f p s ∧ (∀ x ∈ s, has_fderiv_within_at (λ y, p y n) (p x n.succ).curry_left s x) ∧ continuous_on (λ x, p x (n + 1)) s := begin split, { assume h, exact ⟨h.of_le (with_top.coe_le_coe.2 (nat.le_succ n)), h.fderiv_within _ (with_top.coe_lt_coe.2 (lt_add_one n)), h.cont (n + 1) le_rfl⟩ }, { assume h, split, { exact h.1.zero_eq }, { assume m hm, by_cases h' : m < n, { exact h.1.fderiv_within m (with_top.coe_lt_coe.2 h') }, { have : m = n := nat.eq_of_lt_succ_of_not_lt (with_top.coe_lt_coe.1 hm) h', rw this, exact h.2.1 } }, { assume m hm, by_cases h' : m ≤ n, { apply h.1.cont m (with_top.coe_le_coe.2 h') }, { have : m = (n + 1) := le_antisymm (with_top.coe_le_coe.1 hm) (not_le.1 h'), rw this, exact h.2.2 } } } end /-- `p` is a Taylor series of `f` up to `n+1` if and only if `p.shift` is a Taylor series up to `n` for `p 1`, which is a derivative of `f`. -/ theorem has_ftaylor_series_up_to_on_succ_iff_right {n : ℕ} : has_ftaylor_series_up_to_on ((n + 1) : ℕ) f p s ↔ (∀ x ∈ s, (p x 0).uncurry0 = f x) ∧ (∀ x ∈ s, has_fderiv_within_at (λ y, p y 0) (p x 1).curry_left s x) ∧ has_ftaylor_series_up_to_on n (λ x, continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) (λ x, (p x).shift) s := begin split, { assume H, refine ⟨H.zero_eq, H.fderiv_within 0 (with_top.coe_lt_coe.2 (nat.succ_pos n)), _⟩, split, { assume x hx, refl }, { assume m (hm : (m : with_top ℕ) < n) x (hx : x ∈ s), have A : (m.succ : with_top ℕ) < n.succ, by { rw with_top.coe_lt_coe at ⊢ hm, exact nat.lt_succ_iff.mpr hm }, change has_fderiv_within_at ((continuous_multilinear_curry_right_equiv' 𝕜 m E F).symm ∘ (λ (y : E), p y m.succ)) (p x m.succ.succ).curry_right.curry_left s x, rw linear_isometry_equiv.comp_has_fderiv_within_at_iff', convert H.fderiv_within _ A x hx, ext y v, change (p x m.succ.succ) (snoc (cons y (init v)) (v (last _))) = (p x (nat.succ (nat.succ m))) (cons y v), rw [← cons_snoc_eq_snoc_cons, snoc_init_self] }, { assume m (hm : (m : with_top ℕ) ≤ n), have A : (m.succ : with_top ℕ) ≤ n.succ, by { rw with_top.coe_le_coe at ⊢ hm, exact nat.pred_le_iff.mp hm }, change continuous_on ((continuous_multilinear_curry_right_equiv' 𝕜 m E F).symm ∘ (λ (y : E), p y m.succ)) s, rw linear_isometry_equiv.comp_continuous_on_iff, exact H.cont _ A } }, { rintros ⟨Hzero_eq, Hfderiv_zero, Htaylor⟩, split, { exact Hzero_eq }, { assume m (hm : (m : with_top ℕ) < n.succ) x (hx : x ∈ s), cases m, { exact Hfderiv_zero x hx }, { have A : (m : with_top ℕ) < n, by { rw with_top.coe_lt_coe at hm ⊢, exact nat.lt_of_succ_lt_succ hm }, have : has_fderiv_within_at ((continuous_multilinear_curry_right_equiv' 𝕜 m E F).symm ∘ (λ (y : E), p y m.succ)) ((p x).shift m.succ).curry_left s x := Htaylor.fderiv_within _ A x hx, rw linear_isometry_equiv.comp_has_fderiv_within_at_iff' at this, convert this, ext y v, change (p x (nat.succ (nat.succ m))) (cons y v) = (p x m.succ.succ) (snoc (cons y (init v)) (v (last _))), rw [← cons_snoc_eq_snoc_cons, snoc_init_self] } }, { assume m (hm : (m : with_top ℕ) ≤ n.succ), cases m, { have : differentiable_on 𝕜 (λ x, p x 0) s := λ x hx, (Hfderiv_zero x hx).differentiable_within_at, exact this.continuous_on }, { have A : (m : with_top ℕ) ≤ n, by { rw with_top.coe_le_coe at hm ⊢, exact nat.lt_succ_iff.mp hm }, have : continuous_on ((continuous_multilinear_curry_right_equiv' 𝕜 m E F).symm ∘ (λ (y : E), p y m.succ)) s := Htaylor.cont _ A, rwa linear_isometry_equiv.comp_continuous_on_iff at this } } } end /-! ### Smooth functions within a set around a point -/ variable (𝕜) /-- A function is continuously differentiable up to order `n` within a set `s` at a point `x` if it admits continuous derivatives up to order `n` in a neighborhood of `x` in `s ∪ {x}`. For `n = ∞`, we only require that this holds up to any finite order (where the neighborhood may depend on the finite order we consider). For instance, a real function which is `C^m` on `(-1/m, 1/m)` for each natural `m`, but not better, is `C^∞` at `0` within `univ`. -/ def cont_diff_within_at (n : with_top ℕ) (f : E → F) (s : set E) (x : E) := ∀ (m : ℕ), (m : with_top ℕ) ≤ n → ∃ u ∈ 𝓝[insert x s] x, ∃ p : E → formal_multilinear_series 𝕜 E F, has_ftaylor_series_up_to_on m f p u variable {𝕜} lemma cont_diff_within_at_nat {n : ℕ} : cont_diff_within_at 𝕜 n f s x ↔ ∃ u ∈ 𝓝[insert x s] x, ∃ p : E → formal_multilinear_series 𝕜 E F, has_ftaylor_series_up_to_on n f p u := ⟨λ H, H n le_rfl, λ ⟨u, hu, p, hp⟩ m hm, ⟨u, hu, p, hp.of_le hm⟩⟩ lemma cont_diff_within_at.of_le (h : cont_diff_within_at 𝕜 n f s x) (hmn : m ≤ n) : cont_diff_within_at 𝕜 m f s x := λ k hk, h k (le_trans hk hmn) lemma cont_diff_within_at_iff_forall_nat_le : cont_diff_within_at 𝕜 n f s x ↔ ∀ m : ℕ, ↑m ≤ n → cont_diff_within_at 𝕜 m f s x := ⟨λ H m hm, H.of_le hm, λ H m hm, H m hm _ le_rfl⟩ lemma cont_diff_within_at_top : cont_diff_within_at 𝕜 ∞ f s x ↔ ∀ (n : ℕ), cont_diff_within_at 𝕜 n f s x := cont_diff_within_at_iff_forall_nat_le.trans $ by simp only [forall_prop_of_true, le_top] lemma cont_diff_within_at.continuous_within_at (h : cont_diff_within_at 𝕜 n f s x) : continuous_within_at f s x := begin rcases h 0 bot_le with ⟨u, hu, p, H⟩, rw [mem_nhds_within_insert] at hu, exact (H.continuous_on.continuous_within_at hu.1).mono_of_mem hu.2 end lemma cont_diff_within_at.congr_of_eventually_eq (h : cont_diff_within_at 𝕜 n f s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : cont_diff_within_at 𝕜 n f₁ s x := λ m hm, let ⟨u, hu, p, H⟩ := h m hm in ⟨{x ∈ u | f₁ x = f x}, filter.inter_mem hu (mem_nhds_within_insert.2 ⟨hx, h₁⟩), p, (H.mono (sep_subset _ _)).congr (λ _, and.right)⟩ lemma cont_diff_within_at.congr_of_eventually_eq_insert (h : cont_diff_within_at 𝕜 n f s x) (h₁ : f₁ =ᶠ[𝓝[insert x s] x] f) : cont_diff_within_at 𝕜 n f₁ s x := h.congr_of_eventually_eq (nhds_within_mono x (subset_insert x s) h₁) (mem_of_mem_nhds_within (mem_insert x s) h₁ : _) lemma cont_diff_within_at.congr_of_eventually_eq' (h : cont_diff_within_at 𝕜 n f s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : x ∈ s) : cont_diff_within_at 𝕜 n f₁ s x := h.congr_of_eventually_eq h₁ $ h₁.self_of_nhds_within hx lemma filter.eventually_eq.cont_diff_within_at_iff (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : cont_diff_within_at 𝕜 n f₁ s x ↔ cont_diff_within_at 𝕜 n f s x := ⟨λ H, cont_diff_within_at.congr_of_eventually_eq H h₁.symm hx.symm, λ H, H.congr_of_eventually_eq h₁ hx⟩ lemma cont_diff_within_at.congr (h : cont_diff_within_at 𝕜 n f s x) (h₁ : ∀ y ∈ s, f₁ y = f y) (hx : f₁ x = f x) : cont_diff_within_at 𝕜 n f₁ s x := h.congr_of_eventually_eq (filter.eventually_eq_of_mem self_mem_nhds_within h₁) hx lemma cont_diff_within_at.congr' (h : cont_diff_within_at 𝕜 n f s x) (h₁ : ∀ y ∈ s, f₁ y = f y) (hx : x ∈ s) : cont_diff_within_at 𝕜 n f₁ s x := h.congr h₁ (h₁ _ hx) lemma cont_diff_within_at.mono_of_mem (h : cont_diff_within_at 𝕜 n f s x) {t : set E} (hst : s ∈ 𝓝[t] x) : cont_diff_within_at 𝕜 n f t x := begin assume m hm, rcases h m hm with ⟨u, hu, p, H⟩, exact ⟨u, nhds_within_le_of_mem (insert_mem_nhds_within_insert hst) hu, p, H⟩ end lemma cont_diff_within_at.mono (h : cont_diff_within_at 𝕜 n f s x) {t : set E} (hst : t ⊆ s) : cont_diff_within_at 𝕜 n f t x := h.mono_of_mem $ filter.mem_of_superset self_mem_nhds_within hst lemma cont_diff_within_at.congr_nhds (h : cont_diff_within_at 𝕜 n f s x) {t : set E} (hst : 𝓝[s] x = 𝓝[t] x) : cont_diff_within_at 𝕜 n f t x := h.mono_of_mem $ hst ▸ self_mem_nhds_within lemma cont_diff_within_at_congr_nhds {t : set E} (hst : 𝓝[s] x = 𝓝[t] x) : cont_diff_within_at 𝕜 n f s x ↔ cont_diff_within_at 𝕜 n f t x := ⟨λ h, h.congr_nhds hst, λ h, h.congr_nhds hst.symm⟩ lemma cont_diff_within_at_inter' (h : t ∈ 𝓝[s] x) : cont_diff_within_at 𝕜 n f (s ∩ t) x ↔ cont_diff_within_at 𝕜 n f s x := cont_diff_within_at_congr_nhds $ eq.symm $ nhds_within_restrict'' _ h lemma cont_diff_within_at_inter (h : t ∈ 𝓝 x) : cont_diff_within_at 𝕜 n f (s ∩ t) x ↔ cont_diff_within_at 𝕜 n f s x := cont_diff_within_at_inter' (mem_nhds_within_of_mem_nhds h) /-- If a function is `C^n` within a set at a point, with `n ≥ 1`, then it is differentiable within this set at this point. -/ lemma cont_diff_within_at.differentiable_within_at' (h : cont_diff_within_at 𝕜 n f s x) (hn : 1 ≤ n) : differentiable_within_at 𝕜 f (insert x s) x := begin rcases h 1 hn with ⟨u, hu, p, H⟩, rcases mem_nhds_within.1 hu with ⟨t, t_open, xt, tu⟩, rw inter_comm at tu, have := ((H.mono tu).differentiable_on le_rfl) x ⟨mem_insert x s, xt⟩, exact (differentiable_within_at_inter (is_open.mem_nhds t_open xt)).1 this, end lemma cont_diff_within_at.differentiable_within_at (h : cont_diff_within_at 𝕜 n f s x) (hn : 1 ≤ n) : differentiable_within_at 𝕜 f s x := (h.differentiable_within_at' hn).mono (subset_insert x s) /-- A function is `C^(n + 1)` on a domain iff locally, it has a derivative which is `C^n`. -/ theorem cont_diff_within_at_succ_iff_has_fderiv_within_at {n : ℕ} : cont_diff_within_at 𝕜 ((n + 1) : ℕ) f s x ↔ ∃ u ∈ 𝓝[insert x s] x, ∃ f' : E → (E →L[𝕜] F), (∀ x ∈ u, has_fderiv_within_at f (f' x) u x) ∧ (cont_diff_within_at 𝕜 n f' u x) := begin split, { assume h, rcases h n.succ le_rfl with ⟨u, hu, p, Hp⟩, refine ⟨u, hu, λ y, (continuous_multilinear_curry_fin1 𝕜 E F) (p y 1), λ y hy, Hp.has_fderiv_within_at (with_top.coe_le_coe.2 (nat.le_add_left 1 n)) hy, _⟩, assume m hm, refine ⟨u, _, λ (y : E), (p y).shift, _⟩, { convert self_mem_nhds_within, have : x ∈ insert x s, by simp, exact (insert_eq_of_mem (mem_of_mem_nhds_within this hu)) }, { rw has_ftaylor_series_up_to_on_succ_iff_right at Hp, exact Hp.2.2.of_le hm } }, { rintros ⟨u, hu, f', f'_eq_deriv, Hf'⟩, rw cont_diff_within_at_nat, rcases Hf' n le_rfl with ⟨v, hv, p', Hp'⟩, refine ⟨v ∩ u, _, λ x, (p' x).unshift (f x), _⟩, { apply filter.inter_mem _ hu, apply nhds_within_le_of_mem hu, exact nhds_within_mono _ (subset_insert x u) hv }, { rw has_ftaylor_series_up_to_on_succ_iff_right, refine ⟨λ y hy, rfl, λ y hy, _, _⟩, { change has_fderiv_within_at (λ z, (continuous_multilinear_curry_fin0 𝕜 E F).symm (f z)) ((formal_multilinear_series.unshift (p' y) (f y) 1).curry_left) (v ∩ u) y, rw linear_isometry_equiv.comp_has_fderiv_within_at_iff', convert (f'_eq_deriv y hy.2).mono (inter_subset_right v u), rw ← Hp'.zero_eq y hy.1, ext z, change ((p' y 0) (init (@cons 0 (λ i, E) z 0))) (@cons 0 (λ i, E) z 0 (last 0)) = ((p' y 0) 0) z, unfold_coes, congr }, { convert (Hp'.mono (inter_subset_left v u)).congr (λ x hx, Hp'.zero_eq x hx.1), { ext x y, change p' x 0 (init (@snoc 0 (λ i : fin 1, E) 0 y)) y = p' x 0 0 y, rw init_snoc }, { ext x k v y, change p' x k (init (@snoc k (λ i : fin k.succ, E) v y)) (@snoc k (λ i : fin k.succ, E) v y (last k)) = p' x k v y, rw [snoc_last, init_snoc] } } } } end /-- One direction of `cont_diff_within_at_succ_iff_has_fderiv_within_at`, but where all derivatives are taken within the same set. -/ lemma cont_diff_within_at.has_fderiv_within_at_nhds {n : ℕ} (hf : cont_diff_within_at 𝕜 (n + 1 : ℕ) f s x) : ∃ u ∈ 𝓝[insert x s] x, u ⊆ insert x s ∧ ∃ f' : E → E →L[𝕜] F, (∀ x ∈ u, has_fderiv_within_at f (f' x) s x) ∧ cont_diff_within_at 𝕜 n f' s x := begin obtain ⟨u, hu, f', huf', hf'⟩ := cont_diff_within_at_succ_iff_has_fderiv_within_at.mp hf, obtain ⟨w, hw, hxw, hwu⟩ := mem_nhds_within.mp hu, rw [inter_comm] at hwu, refine ⟨insert x s ∩ w, inter_mem_nhds_within _ (hw.mem_nhds hxw), inter_subset_left _ _, f', λ y hy, _, _⟩, { refine ((huf' y $ hwu hy).mono hwu).mono_of_mem _, refine mem_of_superset _ (inter_subset_inter_left _ (subset_insert _ _)), refine inter_mem_nhds_within _ (hw.mem_nhds hy.2) }, { exact hf'.mono_of_mem (nhds_within_mono _ (subset_insert _ _) hu) } end /-- A version of `cont_diff_within_at_succ_iff_has_fderiv_within_at` where all derivatives are taken within the same set. This lemma assumes `x ∈ s`. -/ lemma cont_diff_within_at_succ_iff_has_fderiv_within_at_of_mem {n : ℕ} (hx : x ∈ s) : cont_diff_within_at 𝕜 (n + 1 : ℕ) f s x ↔ ∃ u ∈ 𝓝[s] x, u ⊆ s ∧ ∃ f' : E → E →L[𝕜] F, (∀ x ∈ u, has_fderiv_within_at f (f' x) s x) ∧ cont_diff_within_at 𝕜 n f' s x := begin split, { intro hf, simpa only [insert_eq_of_mem hx] using hf.has_fderiv_within_at_nhds }, rw [cont_diff_within_at_succ_iff_has_fderiv_within_at, insert_eq_of_mem hx], rintro ⟨u, hu, hus, f', huf', hf'⟩, exact ⟨u, hu, f', λ y hy, (huf' y hy).mono hus, hf'.mono hus⟩ end /-! ### Smooth functions within a set -/ variable (𝕜) /-- A function is continuously differentiable up to `n` on `s` if, for any point `x` in `s`, it admits continuous derivatives up to order `n` on a neighborhood of `x` in `s`. For `n = ∞`, we only require that this holds up to any finite order (where the neighborhood may depend on the finite order we consider). -/ definition cont_diff_on (n : with_top ℕ) (f : E → F) (s : set E) := ∀ x ∈ s, cont_diff_within_at 𝕜 n f s x variable {𝕜} lemma cont_diff_on.cont_diff_within_at (h : cont_diff_on 𝕜 n f s) (hx : x ∈ s) : cont_diff_within_at 𝕜 n f s x := h x hx lemma cont_diff_within_at.cont_diff_on {m : ℕ} (hm : (m : with_top ℕ) ≤ n) (h : cont_diff_within_at 𝕜 n f s x) : ∃ u ∈ 𝓝[insert x s] x, u ⊆ insert x s ∧ cont_diff_on 𝕜 m f u := begin rcases h m hm with ⟨u, u_nhd, p, hp⟩, refine ⟨u ∩ insert x s, filter.inter_mem u_nhd self_mem_nhds_within, inter_subset_right _ _, _⟩, assume y hy m' hm', refine ⟨u ∩ insert x s, _, p, (hp.mono (inter_subset_left _ _)).of_le hm'⟩, convert self_mem_nhds_within, exact insert_eq_of_mem hy end protected lemma cont_diff_within_at.eventually {n : ℕ} (h : cont_diff_within_at 𝕜 n f s x) : ∀ᶠ y in 𝓝[insert x s] x, cont_diff_within_at 𝕜 n f s y := begin rcases h.cont_diff_on le_rfl with ⟨u, hu, hu_sub, hd⟩, have : ∀ᶠ (y : E) in 𝓝[insert x s] x, u ∈ 𝓝[insert x s] y ∧ y ∈ u, from (eventually_nhds_within_nhds_within.2 hu).and hu, refine this.mono (λ y hy, (hd y hy.2).mono_of_mem _), exact nhds_within_mono y (subset_insert _ _) hy.1 end lemma cont_diff_on.of_le (h : cont_diff_on 𝕜 n f s) (hmn : m ≤ n) : cont_diff_on 𝕜 m f s := λ x hx, (h x hx).of_le hmn lemma cont_diff_on_iff_forall_nat_le : cont_diff_on 𝕜 n f s ↔ ∀ m : ℕ, ↑m ≤ n → cont_diff_on 𝕜 m f s := ⟨λ H m hm, H.of_le hm, λ H x hx m hm, H m hm x hx m le_rfl⟩ lemma cont_diff_on_top : cont_diff_on 𝕜 ∞ f s ↔ ∀ (n : ℕ), cont_diff_on 𝕜 n f s := cont_diff_on_iff_forall_nat_le.trans $ by simp only [le_top, forall_prop_of_true] lemma cont_diff_on_all_iff_nat : (∀ n, cont_diff_on 𝕜 n f s) ↔ (∀ n : ℕ, cont_diff_on 𝕜 n f s) := begin refine ⟨λ H n, H n, _⟩, rintro H (_|n), exacts [cont_diff_on_top.2 H, H n] end lemma cont_diff_on.continuous_on (h : cont_diff_on 𝕜 n f s) : continuous_on f s := λ x hx, (h x hx).continuous_within_at lemma cont_diff_on.congr (h : cont_diff_on 𝕜 n f s) (h₁ : ∀ x ∈ s, f₁ x = f x) : cont_diff_on 𝕜 n f₁ s := λ x hx, (h x hx).congr h₁ (h₁ x hx) lemma cont_diff_on_congr (h₁ : ∀ x ∈ s, f₁ x = f x) : cont_diff_on 𝕜 n f₁ s ↔ cont_diff_on 𝕜 n f s := ⟨λ H, H.congr (λ x hx, (h₁ x hx).symm), λ H, H.congr h₁⟩ lemma cont_diff_on.mono (h : cont_diff_on 𝕜 n f s) {t : set E} (hst : t ⊆ s) : cont_diff_on 𝕜 n f t := λ x hx, (h x (hst hx)).mono hst lemma cont_diff_on.congr_mono (hf : cont_diff_on 𝕜 n f s) (h₁ : ∀ x ∈ s₁, f₁ x = f x) (hs : s₁ ⊆ s) : cont_diff_on 𝕜 n f₁ s₁ := (hf.mono hs).congr h₁ /-- If a function is `C^n` on a set with `n ≥ 1`, then it is differentiable there. -/ lemma cont_diff_on.differentiable_on (h : cont_diff_on 𝕜 n f s) (hn : 1 ≤ n) : differentiable_on 𝕜 f s := λ x hx, (h x hx).differentiable_within_at hn /-- If a function is `C^n` around each point in a set, then it is `C^n` on the set. -/ lemma cont_diff_on_of_locally_cont_diff_on (h : ∀ x ∈ s, ∃u, is_open u ∧ x ∈ u ∧ cont_diff_on 𝕜 n f (s ∩ u)) : cont_diff_on 𝕜 n f s := begin assume x xs, rcases h x xs with ⟨u, u_open, xu, hu⟩, apply (cont_diff_within_at_inter _).1 (hu x ⟨xs, xu⟩), exact is_open.mem_nhds u_open xu end /-- A function is `C^(n + 1)` on a domain iff locally, it has a derivative which is `C^n`. -/ theorem cont_diff_on_succ_iff_has_fderiv_within_at {n : ℕ} : cont_diff_on 𝕜 ((n + 1) : ℕ) f s ↔ ∀ x ∈ s, ∃ u ∈ 𝓝[insert x s] x, ∃ f' : E → (E →L[𝕜] F), (∀ x ∈ u, has_fderiv_within_at f (f' x) u x) ∧ (cont_diff_on 𝕜 n f' u) := begin split, { assume h x hx, rcases (h x hx) n.succ le_rfl with ⟨u, hu, p, Hp⟩, refine ⟨u, hu, λ y, (continuous_multilinear_curry_fin1 𝕜 E F) (p y 1), λ y hy, Hp.has_fderiv_within_at (with_top.coe_le_coe.2 (nat.le_add_left 1 n)) hy, _⟩, rw has_ftaylor_series_up_to_on_succ_iff_right at Hp, assume z hz m hm, refine ⟨u, _, λ (x : E), (p x).shift, Hp.2.2.of_le hm⟩, convert self_mem_nhds_within, exact insert_eq_of_mem hz, }, { assume h x hx, rw cont_diff_within_at_succ_iff_has_fderiv_within_at, rcases h x hx with ⟨u, u_nhbd, f', hu, hf'⟩, have : x ∈ u := mem_of_mem_nhds_within (mem_insert _ _) u_nhbd, exact ⟨u, u_nhbd, f', hu, hf' x this⟩ } end /-! ### Iterated derivative within a set -/ variable (𝕜) /-- The `n`-th derivative of a function along a set, defined inductively by saying that the `n+1`-th derivative of `f` is the derivative of the `n`-th derivative of `f` along this set, together with an uncurrying step to see it as a multilinear map in `n+1` variables.. -/ noncomputable def iterated_fderiv_within (n : ℕ) (f : E → F) (s : set E) : E → (E [×n]→L[𝕜] F) := nat.rec_on n (λ x, continuous_multilinear_map.curry0 𝕜 E (f x)) (λ n rec x, continuous_linear_map.uncurry_left (fderiv_within 𝕜 rec s x)) /-- Formal Taylor series associated to a function within a set. -/ def ftaylor_series_within (f : E → F) (s : set E) (x : E) : formal_multilinear_series 𝕜 E F := λ n, iterated_fderiv_within 𝕜 n f s x variable {𝕜} @[simp] lemma iterated_fderiv_within_zero_apply (m : (fin 0) → E) : (iterated_fderiv_within 𝕜 0 f s x : ((fin 0) → E) → F) m = f x := rfl lemma iterated_fderiv_within_zero_eq_comp : iterated_fderiv_within 𝕜 0 f s = (continuous_multilinear_curry_fin0 𝕜 E F).symm ∘ f := rfl lemma iterated_fderiv_within_succ_apply_left {n : ℕ} (m : fin (n + 1) → E): (iterated_fderiv_within 𝕜 (n + 1) f s x : (fin (n + 1) → E) → F) m = (fderiv_within 𝕜 (iterated_fderiv_within 𝕜 n f s) s x : E → (E [×n]→L[𝕜] F)) (m 0) (tail m) := rfl /-- Writing explicitly the `n+1`-th derivative as the composition of a currying linear equiv, and the derivative of the `n`-th derivative. -/ lemma iterated_fderiv_within_succ_eq_comp_left {n : ℕ} : iterated_fderiv_within 𝕜 (n + 1) f s = (continuous_multilinear_curry_left_equiv 𝕜 (λ(i : fin (n + 1)), E) F) ∘ (fderiv_within 𝕜 (iterated_fderiv_within 𝕜 n f s) s) := rfl theorem iterated_fderiv_within_succ_apply_right {n : ℕ} (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) (m : fin (n + 1) → E) : (iterated_fderiv_within 𝕜 (n + 1) f s x : (fin (n + 1) → E) → F) m = iterated_fderiv_within 𝕜 n (λy, fderiv_within 𝕜 f s y) s x (init m) (m (last n)) := begin induction n with n IH generalizing x, { rw [iterated_fderiv_within_succ_eq_comp_left, iterated_fderiv_within_zero_eq_comp, iterated_fderiv_within_zero_apply, function.comp_apply, linear_isometry_equiv.comp_fderiv_within _ (hs x hx)], refl }, { let I := continuous_multilinear_curry_right_equiv' 𝕜 n E F, have A : ∀ y ∈ s, iterated_fderiv_within 𝕜 n.succ f s y = (I ∘ (iterated_fderiv_within 𝕜 n (λy, fderiv_within 𝕜 f s y) s)) y, by { assume y hy, ext m, rw @IH m y hy, refl }, calc (iterated_fderiv_within 𝕜 (n+2) f s x : (fin (n+2) → E) → F) m = (fderiv_within 𝕜 (iterated_fderiv_within 𝕜 n.succ f s) s x : E → (E [×(n + 1)]→L[𝕜] F)) (m 0) (tail m) : rfl ... = (fderiv_within 𝕜 (I ∘ (iterated_fderiv_within 𝕜 n (fderiv_within 𝕜 f s) s)) s x : E → (E [×(n + 1)]→L[𝕜] F)) (m 0) (tail m) : by rw fderiv_within_congr (hs x hx) A (A x hx) ... = (I ∘ fderiv_within 𝕜 ((iterated_fderiv_within 𝕜 n (fderiv_within 𝕜 f s) s)) s x : E → (E [×(n + 1)]→L[𝕜] F)) (m 0) (tail m) : by { rw linear_isometry_equiv.comp_fderiv_within _ (hs x hx), refl } ... = (fderiv_within 𝕜 ((iterated_fderiv_within 𝕜 n (λ y, fderiv_within 𝕜 f s y) s)) s x : E → (E [×n]→L[𝕜] (E →L[𝕜] F))) (m 0) (init (tail m)) ((tail m) (last n)) : rfl ... = iterated_fderiv_within 𝕜 (nat.succ n) (λ y, fderiv_within 𝕜 f s y) s x (init m) (m (last (n + 1))) : by { rw [iterated_fderiv_within_succ_apply_left, tail_init_eq_init_tail], refl } } end /-- Writing explicitly the `n+1`-th derivative as the composition of a currying linear equiv, and the `n`-th derivative of the derivative. -/ lemma iterated_fderiv_within_succ_eq_comp_right {n : ℕ} (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) : iterated_fderiv_within 𝕜 (n + 1) f s x = ((continuous_multilinear_curry_right_equiv' 𝕜 n E F) ∘ (iterated_fderiv_within 𝕜 n (λy, fderiv_within 𝕜 f s y) s)) x := by { ext m, rw iterated_fderiv_within_succ_apply_right hs hx, refl } @[simp] lemma iterated_fderiv_within_one_apply (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) (m : (fin 1) → E) : (iterated_fderiv_within 𝕜 1 f s x : ((fin 1) → E) → F) m = (fderiv_within 𝕜 f s x : E → F) (m 0) := by { rw [iterated_fderiv_within_succ_apply_right hs hx, iterated_fderiv_within_zero_apply], refl } /-- If two functions coincide on a set `s` of unique differentiability, then their iterated differentials within this set coincide. -/ lemma iterated_fderiv_within_congr {n : ℕ} (hs : unique_diff_on 𝕜 s) (hL : ∀y∈s, f₁ y = f y) (hx : x ∈ s) : iterated_fderiv_within 𝕜 n f₁ s x = iterated_fderiv_within 𝕜 n f s x := begin induction n with n IH generalizing x, { ext m, simp [hL x hx] }, { have : fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f₁ s y) s x = fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f s y) s x := fderiv_within_congr (hs x hx) (λ y hy, IH hy) (IH hx), ext m, rw [iterated_fderiv_within_succ_apply_left, iterated_fderiv_within_succ_apply_left, this] } end /-- The iterated differential within a set `s` at a point `x` is not modified if one intersects `s` with an open set containing `x`. -/ lemma iterated_fderiv_within_inter_open {n : ℕ} (hu : is_open u) (hs : unique_diff_on 𝕜 (s ∩ u)) (hx : x ∈ s ∩ u) : iterated_fderiv_within 𝕜 n f (s ∩ u) x = iterated_fderiv_within 𝕜 n f s x := begin induction n with n IH generalizing x, { ext m, simp }, { have A : fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f (s ∩ u) y) (s ∩ u) x = fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f s y) (s ∩ u) x := fderiv_within_congr (hs x hx) (λ y hy, IH hy) (IH hx), have B : fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f s y) (s ∩ u) x = fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f s y) s x := fderiv_within_inter (is_open.mem_nhds hu hx.2) ((unique_diff_within_at_inter (is_open.mem_nhds hu hx.2)).1 (hs x hx)), ext m, rw [iterated_fderiv_within_succ_apply_left, iterated_fderiv_within_succ_apply_left, A, B] } end /-- The iterated differential within a set `s` at a point `x` is not modified if one intersects `s` with a neighborhood of `x` within `s`. -/ lemma iterated_fderiv_within_inter' {n : ℕ} (hu : u ∈ 𝓝[s] x) (hs : unique_diff_on 𝕜 s) (xs : x ∈ s) : iterated_fderiv_within 𝕜 n f (s ∩ u) x = iterated_fderiv_within 𝕜 n f s x := begin obtain ⟨v, v_open, xv, vu⟩ : ∃ v, is_open v ∧ x ∈ v ∧ v ∩ s ⊆ u := mem_nhds_within.1 hu, have A : (s ∩ u) ∩ v = s ∩ v, { apply subset.antisymm (inter_subset_inter (inter_subset_left _ _) (subset.refl _)), exact λ y ⟨ys, yv⟩, ⟨⟨ys, vu ⟨yv, ys⟩⟩, yv⟩ }, have : iterated_fderiv_within 𝕜 n f (s ∩ v) x = iterated_fderiv_within 𝕜 n f s x := iterated_fderiv_within_inter_open v_open (hs.inter v_open) ⟨xs, xv⟩, rw ← this, have : iterated_fderiv_within 𝕜 n f ((s ∩ u) ∩ v) x = iterated_fderiv_within 𝕜 n f (s ∩ u) x, { refine iterated_fderiv_within_inter_open v_open _ ⟨⟨xs, vu ⟨xv, xs⟩⟩, xv⟩, rw A, exact hs.inter v_open }, rw A at this, rw ← this end /-- The iterated differential within a set `s` at a point `x` is not modified if one intersects `s` with a neighborhood of `x`. -/ lemma iterated_fderiv_within_inter {n : ℕ} (hu : u ∈ 𝓝 x) (hs : unique_diff_on 𝕜 s) (xs : x ∈ s) : iterated_fderiv_within 𝕜 n f (s ∩ u) x = iterated_fderiv_within 𝕜 n f s x := iterated_fderiv_within_inter' (mem_nhds_within_of_mem_nhds hu) hs xs @[simp] lemma cont_diff_on_zero : cont_diff_on 𝕜 0 f s ↔ continuous_on f s := begin refine ⟨λ H, H.continuous_on, λ H, _⟩, assume x hx m hm, have : (m : with_top ℕ) = 0 := le_antisymm hm bot_le, rw this, refine ⟨insert x s, self_mem_nhds_within, ftaylor_series_within 𝕜 f s, _⟩, rw has_ftaylor_series_up_to_on_zero_iff, exact ⟨by rwa insert_eq_of_mem hx, λ x hx, by simp [ftaylor_series_within]⟩ end lemma cont_diff_within_at_zero (hx : x ∈ s) : cont_diff_within_at 𝕜 0 f s x ↔ ∃ u ∈ 𝓝[s] x, continuous_on f (s ∩ u) := begin split, { intros h, obtain ⟨u, H, p, hp⟩ := h 0 (by norm_num), refine ⟨u, _, _⟩, { simpa [hx] using H }, { simp only [with_top.coe_zero, has_ftaylor_series_up_to_on_zero_iff] at hp, exact hp.1.mono (inter_subset_right s u) } }, { rintros ⟨u, H, hu⟩, rw ← cont_diff_within_at_inter' H, have h' : x ∈ s ∩ u := ⟨hx, mem_of_mem_nhds_within hx H⟩, exact (cont_diff_on_zero.mpr hu).cont_diff_within_at h' } end /-- On a set with unique differentiability, any choice of iterated differential has to coincide with the one we have chosen in `iterated_fderiv_within 𝕜 m f s`. -/ theorem has_ftaylor_series_up_to_on.eq_ftaylor_series_of_unique_diff_on (h : has_ftaylor_series_up_to_on n f p s) {m : ℕ} (hmn : (m : with_top ℕ) ≤ n) (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) : p x m = iterated_fderiv_within 𝕜 m f s x := begin induction m with m IH generalizing x, { rw [h.zero_eq' hx, iterated_fderiv_within_zero_eq_comp] }, { have A : (m : with_top ℕ) < n := lt_of_lt_of_le (with_top.coe_lt_coe.2 (lt_add_one m)) hmn, have : has_fderiv_within_at (λ (y : E), iterated_fderiv_within 𝕜 m f s y) (continuous_multilinear_map.curry_left (p x (nat.succ m))) s x := (h.fderiv_within m A x hx).congr (λ y hy, (IH (le_of_lt A) hy).symm) (IH (le_of_lt A) hx).symm, rw [iterated_fderiv_within_succ_eq_comp_left, function.comp_apply, this.fderiv_within (hs x hx)], exact (continuous_multilinear_map.uncurry_curry_left _).symm } end /-- When a function is `C^n` in a set `s` of unique differentiability, it admits `ftaylor_series_within 𝕜 f s` as a Taylor series up to order `n` in `s`. -/ theorem cont_diff_on.ftaylor_series_within (h : cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) : has_ftaylor_series_up_to_on n f (ftaylor_series_within 𝕜 f s) s := begin split, { assume x hx, simp only [ftaylor_series_within, continuous_multilinear_map.uncurry0_apply, iterated_fderiv_within_zero_apply] }, { assume m hm x hx, rcases (h x hx) m.succ (with_top.add_one_le_of_lt hm) with ⟨u, hu, p, Hp⟩, rw insert_eq_of_mem hx at hu, rcases mem_nhds_within.1 hu with ⟨o, o_open, xo, ho⟩, rw inter_comm at ho, have : p x m.succ = ftaylor_series_within 𝕜 f s x m.succ, { change p x m.succ = iterated_fderiv_within 𝕜 m.succ f s x, rw ← iterated_fderiv_within_inter (is_open.mem_nhds o_open xo) hs hx, exact (Hp.mono ho).eq_ftaylor_series_of_unique_diff_on le_rfl (hs.inter o_open) ⟨hx, xo⟩ }, rw [← this, ← has_fderiv_within_at_inter (is_open.mem_nhds o_open xo)], have A : ∀ y ∈ s ∩ o, p y m = ftaylor_series_within 𝕜 f s y m, { rintros y ⟨hy, yo⟩, change p y m = iterated_fderiv_within 𝕜 m f s y, rw ← iterated_fderiv_within_inter (is_open.mem_nhds o_open yo) hs hy, exact (Hp.mono ho).eq_ftaylor_series_of_unique_diff_on (with_top.coe_le_coe.2 (nat.le_succ m)) (hs.inter o_open) ⟨hy, yo⟩ }, exact ((Hp.mono ho).fderiv_within m (with_top.coe_lt_coe.2 (lt_add_one m)) x ⟨hx, xo⟩).congr (λ y hy, (A y hy).symm) (A x ⟨hx, xo⟩).symm }, { assume m hm, apply continuous_on_of_locally_continuous_on, assume x hx, rcases h x hx m hm with ⟨u, hu, p, Hp⟩, rcases mem_nhds_within.1 hu with ⟨o, o_open, xo, ho⟩, rw insert_eq_of_mem hx at ho, rw inter_comm at ho, refine ⟨o, o_open, xo, _⟩, have A : ∀ y ∈ s ∩ o, p y m = ftaylor_series_within 𝕜 f s y m, { rintros y ⟨hy, yo⟩, change p y m = iterated_fderiv_within 𝕜 m f s y, rw ← iterated_fderiv_within_inter (is_open.mem_nhds o_open yo) hs hy, exact (Hp.mono ho).eq_ftaylor_series_of_unique_diff_on le_rfl (hs.inter o_open) ⟨hy, yo⟩ }, exact ((Hp.mono ho).cont m le_rfl).congr (λ y hy, (A y hy).symm) } end lemma cont_diff_on_of_continuous_on_differentiable_on (Hcont : ∀ (m : ℕ), (m : with_top ℕ) ≤ n → continuous_on (λ x, iterated_fderiv_within 𝕜 m f s x) s) (Hdiff : ∀ (m : ℕ), (m : with_top ℕ) < n → differentiable_on 𝕜 (λ x, iterated_fderiv_within 𝕜 m f s x) s) : cont_diff_on 𝕜 n f s := begin assume x hx m hm, rw insert_eq_of_mem hx, refine ⟨s, self_mem_nhds_within, ftaylor_series_within 𝕜 f s, _⟩, split, { assume y hy, simp only [ftaylor_series_within, continuous_multilinear_map.uncurry0_apply, iterated_fderiv_within_zero_apply] }, { assume k hk y hy, convert (Hdiff k (lt_of_lt_of_le hk hm) y hy).has_fderiv_within_at, simp only [ftaylor_series_within, iterated_fderiv_within_succ_eq_comp_left, continuous_linear_equiv.coe_apply, function.comp_app, coe_fn_coe_base], exact continuous_linear_map.curry_uncurry_left _ }, { assume k hk, exact Hcont k (le_trans hk hm) } end lemma cont_diff_on_of_differentiable_on (h : ∀(m : ℕ), (m : with_top ℕ) ≤ n → differentiable_on 𝕜 (iterated_fderiv_within 𝕜 m f s) s) : cont_diff_on 𝕜 n f s := cont_diff_on_of_continuous_on_differentiable_on (λ m hm, (h m hm).continuous_on) (λ m hm, (h m (le_of_lt hm))) lemma cont_diff_on.continuous_on_iterated_fderiv_within {m : ℕ} (h : cont_diff_on 𝕜 n f s) (hmn : (m : with_top ℕ) ≤ n) (hs : unique_diff_on 𝕜 s) : continuous_on (iterated_fderiv_within 𝕜 m f s) s := (h.ftaylor_series_within hs).cont m hmn lemma cont_diff_on.differentiable_on_iterated_fderiv_within {m : ℕ} (h : cont_diff_on 𝕜 n f s) (hmn : (m : with_top ℕ) < n) (hs : unique_diff_on 𝕜 s) : differentiable_on 𝕜 (iterated_fderiv_within 𝕜 m f s) s := λ x hx, ((h.ftaylor_series_within hs).fderiv_within m hmn x hx).differentiable_within_at lemma cont_diff_on_iff_continuous_on_differentiable_on (hs : unique_diff_on 𝕜 s) : cont_diff_on 𝕜 n f s ↔ (∀ (m : ℕ), (m : with_top ℕ) ≤ n → continuous_on (λ x, iterated_fderiv_within 𝕜 m f s x) s) ∧ (∀ (m : ℕ), (m : with_top ℕ) < n → differentiable_on 𝕜 (λ x, iterated_fderiv_within 𝕜 m f s x) s) := begin split, { assume h, split, { assume m hm, exact h.continuous_on_iterated_fderiv_within hm hs }, { assume m hm, exact h.differentiable_on_iterated_fderiv_within hm hs } }, { assume h, exact cont_diff_on_of_continuous_on_differentiable_on h.1 h.2 } end lemma cont_diff_on_succ_of_fderiv_within {n : ℕ} (hf : differentiable_on 𝕜 f s) (h : cont_diff_on 𝕜 n (λ y, fderiv_within 𝕜 f s y) s) : cont_diff_on 𝕜 ((n + 1) : ℕ) f s := begin intros x hx, rw [cont_diff_within_at_succ_iff_has_fderiv_within_at, insert_eq_of_mem hx], exact ⟨s, self_mem_nhds_within, fderiv_within 𝕜 f s, λ y hy, (hf y hy).has_fderiv_within_at, h x hx⟩ end /-- A function is `C^(n + 1)` on a domain with unique derivatives if and only if it is differentiable there, and its derivative (expressed with `fderiv_within`) is `C^n`. -/ theorem cont_diff_on_succ_iff_fderiv_within {n : ℕ} (hs : unique_diff_on 𝕜 s) : cont_diff_on 𝕜 ((n + 1) : ℕ) f s ↔ differentiable_on 𝕜 f s ∧ cont_diff_on 𝕜 n (λ y, fderiv_within 𝕜 f s y) s := begin refine ⟨λ H, _, λ h, cont_diff_on_succ_of_fderiv_within h.1 h.2⟩, refine ⟨H.differentiable_on (with_top.coe_le_coe.2 (nat.le_add_left 1 n)), λ x hx, _⟩, rcases cont_diff_within_at_succ_iff_has_fderiv_within_at.1 (H x hx) with ⟨u, hu, f', hff', hf'⟩, rcases mem_nhds_within.1 hu with ⟨o, o_open, xo, ho⟩, rw [inter_comm, insert_eq_of_mem hx] at ho, have := hf'.mono ho, rw cont_diff_within_at_inter' (mem_nhds_within_of_mem_nhds (is_open.mem_nhds o_open xo)) at this, apply this.congr_of_eventually_eq' _ hx, have : o ∩ s ∈ 𝓝[s] x := mem_nhds_within.2 ⟨o, o_open, xo, subset.refl _⟩, rw inter_comm at this, apply filter.eventually_eq_of_mem this (λ y hy, _), have A : fderiv_within 𝕜 f (s ∩ o) y = f' y := ((hff' y (ho hy)).mono ho).fderiv_within (hs.inter o_open y hy), rwa fderiv_within_inter (is_open.mem_nhds o_open hy.2) (hs y hy.1) at A end /-- A function is `C^(n + 1)` on an open domain if and only if it is differentiable there, and its derivative (expressed with `fderiv`) is `C^n`. -/ theorem cont_diff_on_succ_iff_fderiv_of_open {n : ℕ} (hs : is_open s) : cont_diff_on 𝕜 ((n + 1) : ℕ) f s ↔ differentiable_on 𝕜 f s ∧ cont_diff_on 𝕜 n (λ y, fderiv 𝕜 f y) s := begin rw cont_diff_on_succ_iff_fderiv_within hs.unique_diff_on, congrm _ ∧ _, apply cont_diff_on_congr, assume x hx, exact fderiv_within_of_open hs hx end /-- A function is `C^∞` on a domain with unique derivatives if and only if it is differentiable there, and its derivative (expressed with `fderiv_within`) is `C^∞`. -/ theorem cont_diff_on_top_iff_fderiv_within (hs : unique_diff_on 𝕜 s) : cont_diff_on 𝕜 ∞ f s ↔ differentiable_on 𝕜 f s ∧ cont_diff_on 𝕜 ∞ (λ y, fderiv_within 𝕜 f s y) s := begin split, { assume h, refine ⟨h.differentiable_on le_top, _⟩, apply cont_diff_on_top.2 (λ n, ((cont_diff_on_succ_iff_fderiv_within hs).1 _).2), exact h.of_le le_top }, { assume h, refine cont_diff_on_top.2 (λ n, _), have A : (n : with_top ℕ) ≤ ∞ := le_top, apply ((cont_diff_on_succ_iff_fderiv_within hs).2 ⟨h.1, h.2.of_le A⟩).of_le, exact with_top.coe_le_coe.2 (nat.le_succ n) } end /-- A function is `C^∞` on an open domain if and only if it is differentiable there, and its derivative (expressed with `fderiv`) is `C^∞`. -/ theorem cont_diff_on_top_iff_fderiv_of_open (hs : is_open s) : cont_diff_on 𝕜 ∞ f s ↔ differentiable_on 𝕜 f s ∧ cont_diff_on 𝕜 ∞ (λ y, fderiv 𝕜 f y) s := begin rw cont_diff_on_top_iff_fderiv_within hs.unique_diff_on, congrm _ ∧ _, apply cont_diff_on_congr, assume x hx, exact fderiv_within_of_open hs hx end lemma cont_diff_on.fderiv_within (hf : cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) (hmn : m + 1 ≤ n) : cont_diff_on 𝕜 m (λ y, fderiv_within 𝕜 f s y) s := begin cases m, { change ∞ + 1 ≤ n at hmn, have : n = ∞, by simpa using hmn, rw this at hf, exact ((cont_diff_on_top_iff_fderiv_within hs).1 hf).2 }, { change (m.succ : with_top ℕ) ≤ n at hmn, exact ((cont_diff_on_succ_iff_fderiv_within hs).1 (hf.of_le hmn)).2 } end lemma cont_diff_on.fderiv_of_open (hf : cont_diff_on 𝕜 n f s) (hs : is_open s) (hmn : m + 1 ≤ n) : cont_diff_on 𝕜 m (λ y, fderiv 𝕜 f y) s := (hf.fderiv_within hs.unique_diff_on hmn).congr (λ x hx, (fderiv_within_of_open hs hx).symm) lemma cont_diff_on.continuous_on_fderiv_within (h : cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) (hn : 1 ≤ n) : continuous_on (λ x, fderiv_within 𝕜 f s x) s := ((cont_diff_on_succ_iff_fderiv_within hs).1 (h.of_le hn)).2.continuous_on lemma cont_diff_on.continuous_on_fderiv_of_open (h : cont_diff_on 𝕜 n f s) (hs : is_open s) (hn : 1 ≤ n) : continuous_on (λ x, fderiv 𝕜 f x) s := ((cont_diff_on_succ_iff_fderiv_of_open hs).1 (h.of_le hn)).2.continuous_on lemma cont_diff_within_at.fderiv_within' (hf : cont_diff_within_at 𝕜 n f s x) (hs : ∀ᶠ y in 𝓝[insert x s] x, unique_diff_within_at 𝕜 s y) (hmn : m + 1 ≤ n) : cont_diff_within_at 𝕜 m (fderiv_within 𝕜 f s) s x := begin have : ∀ k : ℕ, (k + 1 : with_top ℕ) ≤ n → cont_diff_within_at 𝕜 k (fderiv_within 𝕜 f s) s x, { intros k hkn, obtain ⟨v, hv, -, f', hvf', hf'⟩ := (hf.of_le hkn).has_fderiv_within_at_nhds, apply hf'.congr_of_eventually_eq_insert, filter_upwards [hv, hs], exact λ y hy h2y, (hvf' y hy).fderiv_within h2y }, induction m using with_top.rec_top_coe, { obtain rfl := eq_top_iff.mpr hmn, rw [cont_diff_within_at_top], exact λ m, this m le_top }, exact this m hmn end lemma cont_diff_within_at.fderiv_within (hf : cont_diff_within_at 𝕜 n f s x) (hs : unique_diff_on 𝕜 s) (hmn : (m + 1 : with_top ℕ) ≤ n) (hxs : x ∈ s) : cont_diff_within_at 𝕜 m (fderiv_within 𝕜 f s) s x := hf.fderiv_within' (by { rw [insert_eq_of_mem hxs], exact eventually_of_mem self_mem_nhds_within hs}) hmn /-- If a function is at least `C^1`, its bundled derivative (mapping `(x, v)` to `Df(x) v`) is continuous. -/ lemma cont_diff_on.continuous_on_fderiv_within_apply (h : cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) (hn : 1 ≤ n) : continuous_on (λp : E × E, (fderiv_within 𝕜 f s p.1 : E → F) p.2) (s ×ˢ (univ : set E)) := begin have A : continuous (λq : (E →L[𝕜] F) × E, q.1 q.2) := is_bounded_bilinear_map_apply.continuous, have B : continuous_on (λp : E × E, (fderiv_within 𝕜 f s p.1, p.2)) (s ×ˢ (univ : set E)), { apply continuous_on.prod _ continuous_snd.continuous_on, exact continuous_on.comp (h.continuous_on_fderiv_within hs hn) continuous_fst.continuous_on (prod_subset_preimage_fst _ _) }, exact A.comp_continuous_on B end /-! ### Functions with a Taylor series on the whole space -/ /-- `has_ftaylor_series_up_to n f p` registers the fact that `p 0 = f` and `p (m+1)` is a derivative of `p m` for `m < n`, and is continuous for `m ≤ n`. This is a predicate analogous to `has_fderiv_at` but for higher order derivatives. -/ structure has_ftaylor_series_up_to (n : with_top ℕ) (f : E → F) (p : E → formal_multilinear_series 𝕜 E F) : Prop := (zero_eq : ∀ x, (p x 0).uncurry0 = f x) (fderiv : ∀ (m : ℕ) (hm : (m : with_top ℕ) < n), ∀ x, has_fderiv_at (λ y, p y m) (p x m.succ).curry_left x) (cont : ∀ (m : ℕ) (hm : (m : with_top ℕ) ≤ n), continuous (λ x, p x m)) lemma has_ftaylor_series_up_to.zero_eq' (h : has_ftaylor_series_up_to n f p) (x : E) : p x 0 = (continuous_multilinear_curry_fin0 𝕜 E F).symm (f x) := by { rw ← h.zero_eq x, symmetry, exact continuous_multilinear_map.uncurry0_curry0 _ } lemma has_ftaylor_series_up_to_on_univ_iff : has_ftaylor_series_up_to_on n f p univ ↔ has_ftaylor_series_up_to n f p := begin split, { assume H, split, { exact λ x, H.zero_eq x (mem_univ x) }, { assume m hm x, rw ← has_fderiv_within_at_univ, exact H.fderiv_within m hm x (mem_univ x) }, { assume m hm, rw continuous_iff_continuous_on_univ, exact H.cont m hm } }, { assume H, split, { exact λ x hx, H.zero_eq x }, { assume m hm x hx, rw has_fderiv_within_at_univ, exact H.fderiv m hm x }, { assume m hm, rw ← continuous_iff_continuous_on_univ, exact H.cont m hm } } end lemma has_ftaylor_series_up_to.has_ftaylor_series_up_to_on (h : has_ftaylor_series_up_to n f p) (s : set E) : has_ftaylor_series_up_to_on n f p s := (has_ftaylor_series_up_to_on_univ_iff.2 h).mono (subset_univ _) lemma has_ftaylor_series_up_to.of_le (h : has_ftaylor_series_up_to n f p) (hmn : m ≤ n) : has_ftaylor_series_up_to m f p := by { rw ← has_ftaylor_series_up_to_on_univ_iff at h ⊢, exact h.of_le hmn } lemma has_ftaylor_series_up_to.continuous (h : has_ftaylor_series_up_to n f p) : continuous f := begin rw ← has_ftaylor_series_up_to_on_univ_iff at h, rw continuous_iff_continuous_on_univ, exact h.continuous_on end lemma has_ftaylor_series_up_to_zero_iff : has_ftaylor_series_up_to 0 f p ↔ continuous f ∧ (∀ x, (p x 0).uncurry0 = f x) := by simp [has_ftaylor_series_up_to_on_univ_iff.symm, continuous_iff_continuous_on_univ, has_ftaylor_series_up_to_on_zero_iff] /-- If a function has a Taylor series at order at least `1`, then the term of order `1` of this series is a derivative of `f`. -/ lemma has_ftaylor_series_up_to.has_fderiv_at (h : has_ftaylor_series_up_to n f p) (hn : 1 ≤ n) (x : E) : has_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) x := begin rw [← has_fderiv_within_at_univ], exact (has_ftaylor_series_up_to_on_univ_iff.2 h).has_fderiv_within_at hn (mem_univ _) end lemma has_ftaylor_series_up_to.differentiable (h : has_ftaylor_series_up_to n f p) (hn : 1 ≤ n) : differentiable 𝕜 f := λ x, (h.has_fderiv_at hn x).differentiable_at /-- `p` is a Taylor series of `f` up to `n+1` if and only if `p.shift` is a Taylor series up to `n` for `p 1`, which is a derivative of `f`. -/ theorem has_ftaylor_series_up_to_succ_iff_right {n : ℕ} : has_ftaylor_series_up_to ((n + 1) : ℕ) f p ↔ (∀ x, (p x 0).uncurry0 = f x) ∧ (∀ x, has_fderiv_at (λ y, p y 0) (p x 1).curry_left x) ∧ has_ftaylor_series_up_to n (λ x, continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) (λ x, (p x).shift) := by simp only [has_ftaylor_series_up_to_on_succ_iff_right, ← has_ftaylor_series_up_to_on_univ_iff, mem_univ, forall_true_left, has_fderiv_within_at_univ] /-! ### Smooth functions at a point -/ variable (𝕜) /-- A function is continuously differentiable up to `n` at a point `x` if, for any integer `k ≤ n`, there is a neighborhood of `x` where `f` admits derivatives up to order `n`, which are continuous. -/ def cont_diff_at (n : with_top ℕ) (f : E → F) (x : E) := cont_diff_within_at 𝕜 n f univ x variable {𝕜} theorem cont_diff_within_at_univ : cont_diff_within_at 𝕜 n f univ x ↔ cont_diff_at 𝕜 n f x := iff.rfl lemma cont_diff_at_top : cont_diff_at 𝕜 ∞ f x ↔ ∀ (n : ℕ), cont_diff_at 𝕜 n f x := by simp [← cont_diff_within_at_univ, cont_diff_within_at_top] lemma cont_diff_at.cont_diff_within_at (h : cont_diff_at 𝕜 n f x) : cont_diff_within_at 𝕜 n f s x := h.mono (subset_univ _) lemma cont_diff_within_at.cont_diff_at (h : cont_diff_within_at 𝕜 n f s x) (hx : s ∈ 𝓝 x) : cont_diff_at 𝕜 n f x := by rwa [cont_diff_at, ← cont_diff_within_at_inter hx, univ_inter] lemma cont_diff_at.congr_of_eventually_eq (h : cont_diff_at 𝕜 n f x) (hg : f₁ =ᶠ[𝓝 x] f) : cont_diff_at 𝕜 n f₁ x := h.congr_of_eventually_eq' (by rwa nhds_within_univ) (mem_univ x) lemma cont_diff_at.of_le (h : cont_diff_at 𝕜 n f x) (hmn : m ≤ n) : cont_diff_at 𝕜 m f x := h.of_le hmn lemma cont_diff_at.continuous_at (h : cont_diff_at 𝕜 n f x) : continuous_at f x := by simpa [continuous_within_at_univ] using h.continuous_within_at /-- If a function is `C^n` with `n ≥ 1` at a point, then it is differentiable there. -/ lemma cont_diff_at.differentiable_at (h : cont_diff_at 𝕜 n f x) (hn : 1 ≤ n) : differentiable_at 𝕜 f x := by simpa [hn, differentiable_within_at_univ] using h.differentiable_within_at /-- A function is `C^(n + 1)` at a point iff locally, it has a derivative which is `C^n`. -/ theorem cont_diff_at_succ_iff_has_fderiv_at {n : ℕ} : cont_diff_at 𝕜 ((n + 1) : ℕ) f x ↔ (∃ f' : E → E →L[𝕜] F, (∃ u ∈ 𝓝 x, ∀ x ∈ u, has_fderiv_at f (f' x) x) ∧ cont_diff_at 𝕜 n f' x) := begin rw [← cont_diff_within_at_univ, cont_diff_within_at_succ_iff_has_fderiv_within_at], simp only [nhds_within_univ, exists_prop, mem_univ, insert_eq_of_mem], split, { rintros ⟨u, H, f', h_fderiv, h_cont_diff⟩, rcases mem_nhds_iff.mp H with ⟨t, htu, ht, hxt⟩, refine ⟨f', ⟨t, _⟩, h_cont_diff.cont_diff_at H⟩, refine ⟨mem_nhds_iff.mpr ⟨t, subset.rfl, ht, hxt⟩, _⟩, intros y hyt, refine (h_fderiv y (htu hyt)).has_fderiv_at _, exact mem_nhds_iff.mpr ⟨t, htu, ht, hyt⟩ }, { rintros ⟨f', ⟨u, H, h_fderiv⟩, h_cont_diff⟩, refine ⟨u, H, f', _, h_cont_diff.cont_diff_within_at⟩, intros x hxu, exact (h_fderiv x hxu).has_fderiv_within_at } end protected theorem cont_diff_at.eventually {n : ℕ} (h : cont_diff_at 𝕜 n f x) : ∀ᶠ y in 𝓝 x, cont_diff_at 𝕜 n f y := by simpa [nhds_within_univ] using h.eventually /-! ### Smooth functions -/ variable (𝕜) /-- A function is continuously differentiable up to `n` if it admits derivatives up to order `n`, which are continuous. Contrary to the case of definitions in domains (where derivatives might not be unique) we do not need to localize the definition in space or time. -/ definition cont_diff (n : with_top ℕ) (f : E → F) := ∃ p : E → formal_multilinear_series 𝕜 E F, has_ftaylor_series_up_to n f p variable {𝕜} theorem cont_diff_on_univ : cont_diff_on 𝕜 n f univ ↔ cont_diff 𝕜 n f := begin split, { assume H, use ftaylor_series_within 𝕜 f univ, rw ← has_ftaylor_series_up_to_on_univ_iff, exact H.ftaylor_series_within unique_diff_on_univ }, { rintros ⟨p, hp⟩ x hx m hm, exact ⟨univ, filter.univ_sets _, p, (hp.has_ftaylor_series_up_to_on univ).of_le hm⟩ } end lemma cont_diff_iff_cont_diff_at : cont_diff 𝕜 n f ↔ ∀ x, cont_diff_at 𝕜 n f x := by simp [← cont_diff_on_univ, cont_diff_on, cont_diff_at] lemma cont_diff.cont_diff_at (h : cont_diff 𝕜 n f) : cont_diff_at 𝕜 n f x := cont_diff_iff_cont_diff_at.1 h x lemma cont_diff.cont_diff_within_at (h : cont_diff 𝕜 n f) : cont_diff_within_at 𝕜 n f s x := h.cont_diff_at.cont_diff_within_at lemma cont_diff_top : cont_diff 𝕜 ∞ f ↔ ∀ (n : ℕ), cont_diff 𝕜 n f := by simp [cont_diff_on_univ.symm, cont_diff_on_top] lemma cont_diff_all_iff_nat : (∀ n, cont_diff 𝕜 n f) ↔ (∀ n : ℕ, cont_diff 𝕜 n f) := by simp only [← cont_diff_on_univ, cont_diff_on_all_iff_nat] lemma cont_diff.cont_diff_on (h : cont_diff 𝕜 n f) : cont_diff_on 𝕜 n f s := (cont_diff_on_univ.2 h).mono (subset_univ _) @[simp] lemma cont_diff_zero : cont_diff 𝕜 0 f ↔ continuous f := begin rw [← cont_diff_on_univ, continuous_iff_continuous_on_univ], exact cont_diff_on_zero end lemma cont_diff_at_zero : cont_diff_at 𝕜 0 f x ↔ ∃ u ∈ 𝓝 x, continuous_on f u := by { rw ← cont_diff_within_at_univ, simp [cont_diff_within_at_zero, nhds_within_univ] } theorem cont_diff_at_one_iff : cont_diff_at 𝕜 1 f x ↔ ∃ f' : E → (E →L[𝕜] F), ∃ u ∈ 𝓝 x, continuous_on f' u ∧ ∀ x ∈ u, has_fderiv_at f (f' x) x := by simp_rw [show (1 : with_top ℕ) = (0 + 1 : ℕ), from (zero_add 1).symm, cont_diff_at_succ_iff_has_fderiv_at, show ((0 : ℕ) : with_top ℕ) = 0, from rfl, cont_diff_at_zero, exists_mem_and_iff antitone_bforall antitone_continuous_on, and_comm] lemma cont_diff.of_le (h : cont_diff 𝕜 n f) (hmn : m ≤ n) : cont_diff 𝕜 m f := cont_diff_on_univ.1 $ (cont_diff_on_univ.2 h).of_le hmn lemma cont_diff.of_succ {n : ℕ} (h : cont_diff 𝕜 (n + 1) f) : cont_diff 𝕜 n f := h.of_le $ with_top.coe_le_coe.mpr le_self_add lemma cont_diff.one_of_succ {n : ℕ} (h : cont_diff 𝕜 (n + 1) f) : cont_diff 𝕜 1 f := h.of_le $ with_top.coe_le_coe.mpr le_add_self lemma cont_diff.continuous (h : cont_diff 𝕜 n f) : continuous f := cont_diff_zero.1 (h.of_le bot_le) /-- If a function is `C^n` with `n ≥ 1`, then it is differentiable. -/ lemma cont_diff.differentiable (h : cont_diff 𝕜 n f) (hn : 1 ≤ n) : differentiable 𝕜 f := differentiable_on_univ.1 $ (cont_diff_on_univ.2 h).differentiable_on hn /-! ### Iterated derivative -/ variable (𝕜) /-- The `n`-th derivative of a function, as a multilinear map, defined inductively. -/ noncomputable def iterated_fderiv (n : ℕ) (f : E → F) : E → (E [×n]→L[𝕜] F) := nat.rec_on n (λ x, continuous_multilinear_map.curry0 𝕜 E (f x)) (λ n rec x, continuous_linear_map.uncurry_left (fderiv 𝕜 rec x)) /-- Formal Taylor series associated to a function within a set. -/ def ftaylor_series (f : E → F) (x : E) : formal_multilinear_series 𝕜 E F := λ n, iterated_fderiv 𝕜 n f x variable {𝕜} @[simp] lemma iterated_fderiv_zero_apply (m : (fin 0) → E) : (iterated_fderiv 𝕜 0 f x : ((fin 0) → E) → F) m = f x := rfl lemma iterated_fderiv_zero_eq_comp : iterated_fderiv 𝕜 0 f = (continuous_multilinear_curry_fin0 𝕜 E F).symm ∘ f := rfl lemma iterated_fderiv_succ_apply_left {n : ℕ} (m : fin (n + 1) → E): (iterated_fderiv 𝕜 (n + 1) f x : (fin (n + 1) → E) → F) m = (fderiv 𝕜 (iterated_fderiv 𝕜 n f) x : E → (E [×n]→L[𝕜] F)) (m 0) (tail m) := rfl /-- Writing explicitly the `n+1`-th derivative as the composition of a currying linear equiv, and the derivative of the `n`-th derivative. -/ lemma iterated_fderiv_succ_eq_comp_left {n : ℕ} : iterated_fderiv 𝕜 (n + 1) f = (continuous_multilinear_curry_left_equiv 𝕜 (λ(i : fin (n + 1)), E) F) ∘ (fderiv 𝕜 (iterated_fderiv 𝕜 n f)) := rfl lemma iterated_fderiv_within_univ {n : ℕ} : iterated_fderiv_within 𝕜 n f univ = iterated_fderiv 𝕜 n f := begin induction n with n IH, { ext x, simp }, { ext x m, rw [iterated_fderiv_succ_apply_left, iterated_fderiv_within_succ_apply_left, IH, fderiv_within_univ] } end /-- In an open set, the iterated derivative within this set coincides with the global iterated derivative. -/ lemma iterated_fderiv_within_of_is_open (n : ℕ) (hs : is_open s) : eq_on (iterated_fderiv_within 𝕜 n f s) (iterated_fderiv 𝕜 n f) s := begin induction n with n IH, { assume x hx, ext1 m, simp only [iterated_fderiv_within_zero_apply, iterated_fderiv_zero_apply] }, { assume x hx, rw [iterated_fderiv_succ_eq_comp_left, iterated_fderiv_within_succ_eq_comp_left], dsimp, congr' 1, rw fderiv_within_of_open hs hx, apply filter.eventually_eq.fderiv_eq, filter_upwards [hs.mem_nhds hx], exact IH } end lemma ftaylor_series_within_univ : ftaylor_series_within 𝕜 f univ = ftaylor_series 𝕜 f := begin ext1 x, ext1 n, change iterated_fderiv_within 𝕜 n f univ x = iterated_fderiv 𝕜 n f x, rw iterated_fderiv_within_univ end theorem iterated_fderiv_succ_apply_right {n : ℕ} (m : fin (n + 1) → E) : (iterated_fderiv 𝕜 (n + 1) f x : (fin (n + 1) → E) → F) m = iterated_fderiv 𝕜 n (λy, fderiv 𝕜 f y) x (init m) (m (last n)) := begin rw [← iterated_fderiv_within_univ, ← iterated_fderiv_within_univ, ← fderiv_within_univ], exact iterated_fderiv_within_succ_apply_right unique_diff_on_univ (mem_univ _) _ end /-- Writing explicitly the `n+1`-th derivative as the composition of a currying linear equiv, and the `n`-th derivative of the derivative. -/ lemma iterated_fderiv_succ_eq_comp_right {n : ℕ} : iterated_fderiv 𝕜 (n + 1) f x = ((continuous_multilinear_curry_right_equiv' 𝕜 n E F) ∘ (iterated_fderiv 𝕜 n (λy, fderiv 𝕜 f y))) x := by { ext m, rw iterated_fderiv_succ_apply_right, refl } @[simp] lemma iterated_fderiv_one_apply (m : (fin 1) → E) : (iterated_fderiv 𝕜 1 f x : ((fin 1) → E) → F) m = (fderiv 𝕜 f x : E → F) (m 0) := by { rw [iterated_fderiv_succ_apply_right, iterated_fderiv_zero_apply], refl } /-- When a function is `C^n` in a set `s` of unique differentiability, it admits `ftaylor_series_within 𝕜 f s` as a Taylor series up to order `n` in `s`. -/ theorem cont_diff_on_iff_ftaylor_series : cont_diff 𝕜 n f ↔ has_ftaylor_series_up_to n f (ftaylor_series 𝕜 f) := begin split, { rw [← cont_diff_on_univ, ← has_ftaylor_series_up_to_on_univ_iff, ← ftaylor_series_within_univ], exact λ h, cont_diff_on.ftaylor_series_within h unique_diff_on_univ }, { assume h, exact ⟨ftaylor_series 𝕜 f, h⟩ } end lemma cont_diff_iff_continuous_differentiable : cont_diff 𝕜 n f ↔ (∀ (m : ℕ), (m : with_top ℕ) ≤ n → continuous (λ x, iterated_fderiv 𝕜 m f x)) ∧ (∀ (m : ℕ), (m : with_top ℕ) < n → differentiable 𝕜 (λ x, iterated_fderiv 𝕜 m f x)) := by simp [cont_diff_on_univ.symm, continuous_iff_continuous_on_univ, differentiable_on_univ.symm, iterated_fderiv_within_univ, cont_diff_on_iff_continuous_on_differentiable_on unique_diff_on_univ] lemma cont_diff_of_differentiable_iterated_fderiv (h : ∀(m : ℕ), (m : with_top ℕ) ≤ n → differentiable 𝕜 (iterated_fderiv 𝕜 m f)) : cont_diff 𝕜 n f := cont_diff_iff_continuous_differentiable.2 ⟨λ m hm, (h m hm).continuous, λ m hm, (h m (le_of_lt hm))⟩ /-- A function is `C^(n + 1)` if and only if it is differentiable, and its derivative (formulated in terms of `fderiv`) is `C^n`. -/ theorem cont_diff_succ_iff_fderiv {n : ℕ} : cont_diff 𝕜 ((n + 1) : ℕ) f ↔ differentiable 𝕜 f ∧ cont_diff 𝕜 n (λ y, fderiv 𝕜 f y) := by simp only [← cont_diff_on_univ, ← differentiable_on_univ, ← fderiv_within_univ, cont_diff_on_succ_iff_fderiv_within unique_diff_on_univ] theorem cont_diff_one_iff_fderiv : cont_diff 𝕜 1 f ↔ differentiable 𝕜 f ∧ continuous (fderiv 𝕜 f) := cont_diff_succ_iff_fderiv.trans $ iff.rfl.and cont_diff_zero /-- A function is `C^∞` if and only if it is differentiable, and its derivative (formulated in terms of `fderiv`) is `C^∞`. -/ theorem cont_diff_top_iff_fderiv : cont_diff 𝕜 ∞ f ↔ differentiable 𝕜 f ∧ cont_diff 𝕜 ∞ (λ y, fderiv 𝕜 f y) := begin simp [cont_diff_on_univ.symm, differentiable_on_univ.symm, fderiv_within_univ.symm, - fderiv_within_univ], rw cont_diff_on_top_iff_fderiv_within unique_diff_on_univ, end lemma cont_diff.continuous_fderiv (h : cont_diff 𝕜 n f) (hn : 1 ≤ n) : continuous (λ x, fderiv 𝕜 f x) := ((cont_diff_succ_iff_fderiv).1 (h.of_le hn)).2.continuous /-- If a function is at least `C^1`, its bundled derivative (mapping `(x, v)` to `Df(x) v`) is continuous. -/ lemma cont_diff.continuous_fderiv_apply (h : cont_diff 𝕜 n f) (hn : 1 ≤ n) : continuous (λp : E × E, (fderiv 𝕜 f p.1 : E → F) p.2) := begin have A : continuous (λq : (E →L[𝕜] F) × E, q.1 q.2) := is_bounded_bilinear_map_apply.continuous, have B : continuous (λp : E × E, (fderiv 𝕜 f p.1, p.2)), { apply continuous.prod_mk _ continuous_snd, exact continuous.comp (h.continuous_fderiv hn) continuous_fst }, exact A.comp B end /-! ### Constants -/ lemma iterated_fderiv_within_zero_fun {n : ℕ} : iterated_fderiv 𝕜 n (λ x : E, (0 : F)) = 0 := begin induction n with n IH, { ext m, simp }, { ext x m, rw [iterated_fderiv_succ_apply_left, IH], change (fderiv 𝕜 (λ (x : E), (0 : (E [×n]→L[𝕜] F))) x : E → (E [×n]→L[𝕜] F)) (m 0) (tail m) = _, rw fderiv_const, refl } end lemma cont_diff_zero_fun : cont_diff 𝕜 n (λ x : E, (0 : F)) := begin apply cont_diff_of_differentiable_iterated_fderiv (λm hm, _), rw iterated_fderiv_within_zero_fun, apply differentiable_const (0 : (E [×m]→L[𝕜] F)) end /-- Constants are `C^∞`. -/ lemma cont_diff_const {c : F} : cont_diff 𝕜 n (λx : E, c) := begin suffices h : cont_diff 𝕜 ∞ (λx : E, c), by exact h.of_le le_top, rw cont_diff_top_iff_fderiv, refine ⟨differentiable_const c, _⟩, rw fderiv_const, exact cont_diff_zero_fun end lemma cont_diff_on_const {c : F} {s : set E} : cont_diff_on 𝕜 n (λx : E, c) s := cont_diff_const.cont_diff_on lemma cont_diff_at_const {c : F} : cont_diff_at 𝕜 n (λx : E, c) x := cont_diff_const.cont_diff_at lemma cont_diff_within_at_const {c : F} : cont_diff_within_at 𝕜 n (λx : E, c) s x := cont_diff_at_const.cont_diff_within_at @[nontriviality] lemma cont_diff_of_subsingleton [subsingleton F] : cont_diff 𝕜 n f := by { rw [subsingleton.elim f (λ _, 0)], exact cont_diff_const } @[nontriviality] lemma cont_diff_at_of_subsingleton [subsingleton F] : cont_diff_at 𝕜 n f x := by { rw [subsingleton.elim f (λ _, 0)], exact cont_diff_at_const } @[nontriviality] lemma cont_diff_within_at_of_subsingleton [subsingleton F] : cont_diff_within_at 𝕜 n f s x := by { rw [subsingleton.elim f (λ _, 0)], exact cont_diff_within_at_const } @[nontriviality] lemma cont_diff_on_of_subsingleton [subsingleton F] : cont_diff_on 𝕜 n f s := by { rw [subsingleton.elim f (λ _, 0)], exact cont_diff_on_const } /-! ### Smoothness of linear functions -/ /-- Unbundled bounded linear functions are `C^∞`. -/ lemma is_bounded_linear_map.cont_diff (hf : is_bounded_linear_map 𝕜 f) : cont_diff 𝕜 n f := begin suffices h : cont_diff 𝕜 ∞ f, by exact h.of_le le_top, rw cont_diff_top_iff_fderiv, refine ⟨hf.differentiable, _⟩, simp_rw [hf.fderiv], exact cont_diff_const end lemma continuous_linear_map.cont_diff (f : E →L[𝕜] F) : cont_diff 𝕜 n f := f.is_bounded_linear_map.cont_diff lemma continuous_linear_equiv.cont_diff (f : E ≃L[𝕜] F) : cont_diff 𝕜 n f := (f : E →L[𝕜] F).cont_diff lemma linear_isometry.cont_diff (f : E →ₗᵢ[𝕜] F) : cont_diff 𝕜 n f := f.to_continuous_linear_map.cont_diff lemma linear_isometry_equiv.cont_diff (f : E ≃ₗᵢ[𝕜] F) : cont_diff 𝕜 n f := (f : E →L[𝕜] F).cont_diff /-- The identity is `C^∞`. -/ lemma cont_diff_id : cont_diff 𝕜 n (id : E → E) := is_bounded_linear_map.id.cont_diff lemma cont_diff_within_at_id {s x} : cont_diff_within_at 𝕜 n (id : E → E) s x := cont_diff_id.cont_diff_within_at lemma cont_diff_at_id {x} : cont_diff_at 𝕜 n (id : E → E) x := cont_diff_id.cont_diff_at lemma cont_diff_on_id {s} : cont_diff_on 𝕜 n (id : E → E) s := cont_diff_id.cont_diff_on /-- Bilinear functions are `C^∞`. -/ lemma is_bounded_bilinear_map.cont_diff (hb : is_bounded_bilinear_map 𝕜 b) : cont_diff 𝕜 n b := begin suffices h : cont_diff 𝕜 ∞ b, by exact h.of_le le_top, rw cont_diff_top_iff_fderiv, refine ⟨hb.differentiable, _⟩, simp [hb.fderiv], exact hb.is_bounded_linear_map_deriv.cont_diff end /-- If `f` admits a Taylor series `p` in a set `s`, and `g` is linear, then `g ∘ f` admits a Taylor series whose `k`-th term is given by `g ∘ (p k)`. -/ lemma has_ftaylor_series_up_to_on.continuous_linear_map_comp (g : F →L[𝕜] G) (hf : has_ftaylor_series_up_to_on n f p s) : has_ftaylor_series_up_to_on n (g ∘ f) (λ x k, g.comp_continuous_multilinear_map (p x k)) s := begin set L : Π m : ℕ, (E [×m]→L[𝕜] F) →L[𝕜] (E [×m]→L[𝕜] G) := λ m, continuous_linear_map.comp_continuous_multilinear_mapL 𝕜 (λ _, E) F G g, split, { exact λ x hx, congr_arg g (hf.zero_eq x hx) }, { intros m hm x hx, convert (L m).has_fderiv_at.comp_has_fderiv_within_at x (hf.fderiv_within m hm x hx) }, { intros m hm, convert (L m).continuous.comp_continuous_on (hf.cont m hm) } end /-- Composition by continuous linear maps on the left preserves `C^n` functions in a domain at a point. -/ lemma cont_diff_within_at.continuous_linear_map_comp (g : F →L[𝕜] G) (hf : cont_diff_within_at 𝕜 n f s x) : cont_diff_within_at 𝕜 n (g ∘ f) s x := begin assume m hm, rcases hf m hm with ⟨u, hu, p, hp⟩, exact ⟨u, hu, _, hp.continuous_linear_map_comp g⟩, end /-- Composition by continuous linear maps on the left preserves `C^n` functions in a domain at a point. -/ lemma cont_diff_at.continuous_linear_map_comp (g : F →L[𝕜] G) (hf : cont_diff_at 𝕜 n f x) : cont_diff_at 𝕜 n (g ∘ f) x := cont_diff_within_at.continuous_linear_map_comp g hf /-- Composition by continuous linear maps on the left preserves `C^n` functions on domains. -/ lemma cont_diff_on.continuous_linear_map_comp (g : F →L[𝕜] G) (hf : cont_diff_on 𝕜 n f s) : cont_diff_on 𝕜 n (g ∘ f) s := λ x hx, (hf x hx).continuous_linear_map_comp g /-- Composition by continuous linear maps on the left preserves `C^n` functions. -/ lemma cont_diff.continuous_linear_map_comp {f : E → F} (g : F →L[𝕜] G) (hf : cont_diff 𝕜 n f) : cont_diff 𝕜 n (λx, g (f x)) := cont_diff_on_univ.1 $ cont_diff_on.continuous_linear_map_comp _ (cont_diff_on_univ.2 hf) /-- Composition by continuous linear equivs on the left respects higher differentiability on domains. -/ lemma continuous_linear_equiv.comp_cont_diff_within_at_iff (e : F ≃L[𝕜] G) : cont_diff_within_at 𝕜 n (e ∘ f) s x ↔ cont_diff_within_at 𝕜 n f s x := ⟨λ H, by simpa only [(∘), e.symm.coe_coe, e.symm_apply_apply] using H.continuous_linear_map_comp (e.symm : G →L[𝕜] F), λ H, H.continuous_linear_map_comp (e : F →L[𝕜] G)⟩ /-- Composition by continuous linear equivs on the left respects higher differentiability on domains. -/ lemma continuous_linear_equiv.comp_cont_diff_on_iff (e : F ≃L[𝕜] G) : cont_diff_on 𝕜 n (e ∘ f) s ↔ cont_diff_on 𝕜 n f s := by simp [cont_diff_on, e.comp_cont_diff_within_at_iff] /-- If `f` admits a Taylor series `p` in a set `s`, and `g` is linear, then `f ∘ g` admits a Taylor series in `g ⁻¹' s`, whose `k`-th term is given by `p k (g v₁, ..., g vₖ)` . -/ lemma has_ftaylor_series_up_to_on.comp_continuous_linear_map (hf : has_ftaylor_series_up_to_on n f p s) (g : G →L[𝕜] E) : has_ftaylor_series_up_to_on n (f ∘ g) (λ x k, (p (g x) k).comp_continuous_linear_map (λ _, g)) (g ⁻¹' s) := begin let A : Π m : ℕ, (E [×m]→L[𝕜] F) → (G [×m]→L[𝕜] F) := λ m h, h.comp_continuous_linear_map (λ _, g), have hA : ∀ m, is_bounded_linear_map 𝕜 (A m) := λ m, is_bounded_linear_map_continuous_multilinear_map_comp_linear g, split, { assume x hx, simp only [(hf.zero_eq (g x) hx).symm, function.comp_app], change p (g x) 0 (λ (i : fin 0), g 0) = p (g x) 0 0, rw continuous_linear_map.map_zero, refl }, { assume m hm x hx, convert ((hA m).has_fderiv_at).comp_has_fderiv_within_at x ((hf.fderiv_within m hm (g x) hx).comp x (g.has_fderiv_within_at) (subset.refl _)), ext y v, change p (g x) (nat.succ m) (g ∘ (cons y v)) = p (g x) m.succ (cons (g y) (g ∘ v)), rw comp_cons }, { assume m hm, exact (hA m).continuous.comp_continuous_on ((hf.cont m hm).comp g.continuous.continuous_on (subset.refl _)) } end /-- Composition by continuous linear maps on the right preserves `C^n` functions at a point on a domain. -/ lemma cont_diff_within_at.comp_continuous_linear_map {x : G} (g : G →L[𝕜] E) (hf : cont_diff_within_at 𝕜 n f s (g x)) : cont_diff_within_at 𝕜 n (f ∘ g) (g ⁻¹' s) x := begin assume m hm, rcases hf m hm with ⟨u, hu, p, hp⟩, refine ⟨g ⁻¹' u, _, _, hp.comp_continuous_linear_map g⟩, apply continuous_within_at.preimage_mem_nhds_within', { exact g.continuous.continuous_within_at }, { apply nhds_within_mono (g x) _ hu, rw image_insert_eq, exact insert_subset_insert (image_preimage_subset g s) } end /-- Composition by continuous linear maps on the right preserves `C^n` functions on domains. -/ lemma cont_diff_on.comp_continuous_linear_map (hf : cont_diff_on 𝕜 n f s) (g : G →L[𝕜] E) : cont_diff_on 𝕜 n (f ∘ g) (g ⁻¹' s) := λ x hx, (hf (g x) hx).comp_continuous_linear_map g /-- Composition by continuous linear maps on the right preserves `C^n` functions. -/ lemma cont_diff.comp_continuous_linear_map {f : E → F} {g : G →L[𝕜] E} (hf : cont_diff 𝕜 n f) : cont_diff 𝕜 n (f ∘ g) := cont_diff_on_univ.1 $ cont_diff_on.comp_continuous_linear_map (cont_diff_on_univ.2 hf) _ /-- Composition by continuous linear equivs on the right respects higher differentiability at a point in a domain. -/ lemma continuous_linear_equiv.cont_diff_within_at_comp_iff (e : G ≃L[𝕜] E) : cont_diff_within_at 𝕜 n (f ∘ e) (e ⁻¹' s) (e.symm x) ↔ cont_diff_within_at 𝕜 n f s x := begin split, { assume H, simpa [← preimage_comp, (∘)] using H.comp_continuous_linear_map (e.symm : E →L[𝕜] G) }, { assume H, rw [← e.apply_symm_apply x, ← e.coe_coe] at H, exact H.comp_continuous_linear_map _ }, end /-- Composition by continuous linear equivs on the right respects higher differentiability on domains. -/ lemma continuous_linear_equiv.cont_diff_on_comp_iff (e : G ≃L[𝕜] E) : cont_diff_on 𝕜 n (f ∘ e) (e ⁻¹' s) ↔ cont_diff_on 𝕜 n f s := begin refine ⟨λ H, _, λ H, H.comp_continuous_linear_map (e : G →L[𝕜] E)⟩, have A : f = (f ∘ e) ∘ e.symm, by { ext y, simp only [function.comp_app], rw e.apply_symm_apply y }, have B : e.symm ⁻¹' (e ⁻¹' s) = s, by { rw [← preimage_comp, e.self_comp_symm], refl }, rw [A, ← B], exact H.comp_continuous_linear_map (e.symm : E →L[𝕜] G) end /-- If two functions `f` and `g` admit Taylor series `p` and `q` in a set `s`, then the cartesian product of `f` and `g` admits the cartesian product of `p` and `q` as a Taylor series. -/ lemma has_ftaylor_series_up_to_on.prod (hf : has_ftaylor_series_up_to_on n f p s) {g : E → G} {q : E → formal_multilinear_series 𝕜 E G} (hg : has_ftaylor_series_up_to_on n g q s) : has_ftaylor_series_up_to_on n (λ y, (f y, g y)) (λ y k, (p y k).prod (q y k)) s := begin set L := λ m, continuous_multilinear_map.prodL 𝕜 (λ i : fin m, E) F G, split, { assume x hx, rw [← hf.zero_eq x hx, ← hg.zero_eq x hx], refl }, { assume m hm x hx, convert (L m).has_fderiv_at.comp_has_fderiv_within_at x ((hf.fderiv_within m hm x hx).prod (hg.fderiv_within m hm x hx)) }, { assume m hm, exact (L m).continuous.comp_continuous_on ((hf.cont m hm).prod (hg.cont m hm)) } end /-- The cartesian product of `C^n` functions at a point in a domain is `C^n`. -/ lemma cont_diff_within_at.prod {s : set E} {f : E → F} {g : E → G} (hf : cont_diff_within_at 𝕜 n f s x) (hg : cont_diff_within_at 𝕜 n g s x) : cont_diff_within_at 𝕜 n (λx:E, (f x, g x)) s x := begin assume m hm, rcases hf m hm with ⟨u, hu, p, hp⟩, rcases hg m hm with ⟨v, hv, q, hq⟩, exact ⟨u ∩ v, filter.inter_mem hu hv, _, (hp.mono (inter_subset_left u v)).prod (hq.mono (inter_subset_right u v))⟩ end /-- The cartesian product of `C^n` functions on domains is `C^n`. -/ lemma cont_diff_on.prod {s : set E} {f : E → F} {g : E → G} (hf : cont_diff_on 𝕜 n f s) (hg : cont_diff_on 𝕜 n g s) : cont_diff_on 𝕜 n (λ x : E, (f x, g x)) s := λ x hx, (hf x hx).prod (hg x hx) /-- The cartesian product of `C^n` functions at a point is `C^n`. -/ lemma cont_diff_at.prod {f : E → F} {g : E → G} (hf : cont_diff_at 𝕜 n f x) (hg : cont_diff_at 𝕜 n g x) : cont_diff_at 𝕜 n (λ x : E, (f x, g x)) x := cont_diff_within_at_univ.1 $ cont_diff_within_at.prod (cont_diff_within_at_univ.2 hf) (cont_diff_within_at_univ.2 hg) /-- The cartesian product of `C^n` functions is `C^n`.-/ lemma cont_diff.prod {f : E → F} {g : E → G} (hf : cont_diff 𝕜 n f) (hg : cont_diff 𝕜 n g) : cont_diff 𝕜 n (λ x : E, (f x, g x)) := cont_diff_on_univ.1 $ cont_diff_on.prod (cont_diff_on_univ.2 hf) (cont_diff_on_univ.2 hg) /-! ### Composition of `C^n` functions We show that the composition of `C^n` functions is `C^n`. One way to prove it would be to write the `n`-th derivative of the composition (this is Faà di Bruno's formula) and check its continuity, but this is very painful. Instead, we go for a simple inductive proof. Assume it is done for `n`. Then, to check it for `n+1`, one needs to check that the derivative of `g ∘ f` is `C^n`, i.e., that `Dg(f x) ⬝ Df(x)` is `C^n`. The term `Dg (f x)` is the composition of two `C^n` functions, so it is `C^n` by the inductive assumption. The term `Df(x)` is also `C^n`. Then, the matrix multiplication is the application of a bilinear map (which is `C^∞`, and therefore `C^n`) to `x ↦ (Dg(f x), Df x)`. As the composition of two `C^n` maps, it is again `C^n`, and we are done. There is a subtlety in this argument: we apply the inductive assumption to functions on other Banach spaces. In maths, one would say: prove by induction over `n` that, for all `C^n` maps between all pairs of Banach spaces, their composition is `C^n`. In Lean, this is fine as long as the spaces stay in the same universe. This is not the case in the above argument: if `E` lives in universe `u` and `F` lives in universe `v`, then linear maps from `E` to `F` (to which the derivative of `f` belongs) is in universe `max u v`. If one could quantify over finitely many universes, the above proof would work fine, but this is not the case. One could still write the proof considering spaces in any universe in `u, v, w, max u v, max v w, max u v w`, but it would be extremely tedious and lead to a lot of duplication. Instead, we formulate the above proof when all spaces live in the same universe (where everything is fine), and then we deduce the general result by lifting all our spaces to a common universe. We use the trick that any space `H` is isomorphic through a continuous linear equiv to `continuous_multilinear_map (λ (i : fin 0), E × F × G) H` to change the universe level, and then argue that composing with such a linear equiv does not change the fact of being `C^n`, which we have already proved previously. -/ /-- Auxiliary lemma proving that the composition of `C^n` functions on domains is `C^n` when all spaces live in the same universe. Use instead `cont_diff_on.comp` which removes the universe assumption (but is deduced from this one). -/ private lemma cont_diff_on.comp_same_univ {Eu : Type u} [normed_group Eu] [normed_space 𝕜 Eu] {Fu : Type u} [normed_group Fu] [normed_space 𝕜 Fu] {Gu : Type u} [normed_group Gu] [normed_space 𝕜 Gu] {s : set Eu} {t : set Fu} {g : Fu → Gu} {f : Eu → Fu} (hg : cont_diff_on 𝕜 n g t) (hf : cont_diff_on 𝕜 n f s) (st : s ⊆ f ⁻¹' t) : cont_diff_on 𝕜 n (g ∘ f) s := begin unfreezingI { induction n using with_top.nat_induction with n IH Itop generalizing Eu Fu Gu }, { rw cont_diff_on_zero at hf hg ⊢, exact continuous_on.comp hg hf st }, { rw cont_diff_on_succ_iff_has_fderiv_within_at at hg ⊢, assume x hx, rcases (cont_diff_on_succ_iff_has_fderiv_within_at.1 hf) x hx with ⟨u, hu, f', hf', f'_diff⟩, rcases hg (f x) (st hx) with ⟨v, hv, g', hg', g'_diff⟩, rw insert_eq_of_mem hx at hu ⊢, have xu : x ∈ u := mem_of_mem_nhds_within hx hu, let w := s ∩ (u ∩ f⁻¹' v), have wv : w ⊆ f ⁻¹' v := λ y hy, hy.2.2, have wu : w ⊆ u := λ y hy, hy.2.1, have ws : w ⊆ s := λ y hy, hy.1, refine ⟨w, _, λ y, (g' (f y)).comp (f' y), _, _⟩, show w ∈ 𝓝[s] x, { apply filter.inter_mem self_mem_nhds_within, apply filter.inter_mem hu, apply continuous_within_at.preimage_mem_nhds_within', { rw ← continuous_within_at_inter' hu, exact (hf' x xu).differentiable_within_at.continuous_within_at.mono (inter_subset_right _ _) }, { apply nhds_within_mono _ _ hv, exact subset.trans (image_subset_iff.mpr st) (subset_insert (f x) t) } }, show ∀ y ∈ w, has_fderiv_within_at (g ∘ f) ((g' (f y)).comp (f' y)) w y, { rintros y ⟨ys, yu, yv⟩, exact (hg' (f y) yv).comp y ((hf' y yu).mono wu) wv }, show cont_diff_on 𝕜 n (λ y, (g' (f y)).comp (f' y)) w, { have A : cont_diff_on 𝕜 n (λ y, g' (f y)) w := IH g'_diff ((hf.of_le (with_top.coe_le_coe.2 (nat.le_succ n))).mono ws) wv, have B : cont_diff_on 𝕜 n f' w := f'_diff.mono wu, have C : cont_diff_on 𝕜 n (λ y, (g' (f y), f' y)) w := A.prod B, have D : cont_diff_on 𝕜 n (λ p : (Fu →L[𝕜] Gu) × (Eu →L[𝕜] Fu), p.1.comp p.2) univ := is_bounded_bilinear_map_comp.cont_diff.cont_diff_on, exact IH D C (subset_univ _) } }, { rw cont_diff_on_top at hf hg ⊢, exact λ n, Itop n (hg n) (hf n) st } end /-- The composition of `C^n` functions on domains is `C^n`. -/ lemma cont_diff_on.comp {s : set E} {t : set F} {g : F → G} {f : E → F} (hg : cont_diff_on 𝕜 n g t) (hf : cont_diff_on 𝕜 n f s) (st : s ⊆ f ⁻¹' t) : cont_diff_on 𝕜 n (g ∘ f) s := begin /- we lift all the spaces to a common universe, as we have already proved the result in this situation. For the lift, we use the trick that `H` is isomorphic through a continuous linear equiv to `continuous_multilinear_map 𝕜 (λ (i : fin 0), (E × F × G)) H`, and continuous linear equivs respect smoothness classes. -/ let Eu := continuous_multilinear_map 𝕜 (λ (i : fin 0), (E × F × G)) E, letI : normed_group Eu := by apply_instance, letI : normed_space 𝕜 Eu := by apply_instance, let Fu := continuous_multilinear_map 𝕜 (λ (i : fin 0), (E × F × G)) F, letI : normed_group Fu := by apply_instance, letI : normed_space 𝕜 Fu := by apply_instance, let Gu := continuous_multilinear_map 𝕜 (λ (i : fin 0), (E × F × G)) G, letI : normed_group Gu := by apply_instance, letI : normed_space 𝕜 Gu := by apply_instance, -- declare the isomorphisms let isoE : Eu ≃L[𝕜] E := continuous_multilinear_curry_fin0 𝕜 (E × F × G) E, let isoF : Fu ≃L[𝕜] F := continuous_multilinear_curry_fin0 𝕜 (E × F × G) F, let isoG : Gu ≃L[𝕜] G := continuous_multilinear_curry_fin0 𝕜 (E × F × G) G, -- lift the functions to the new spaces, check smoothness there, and then go back. let fu : Eu → Fu := (isoF.symm ∘ f) ∘ isoE, have fu_diff : cont_diff_on 𝕜 n fu (isoE ⁻¹' s), by rwa [isoE.cont_diff_on_comp_iff, isoF.symm.comp_cont_diff_on_iff], let gu : Fu → Gu := (isoG.symm ∘ g) ∘ isoF, have gu_diff : cont_diff_on 𝕜 n gu (isoF ⁻¹' t), by rwa [isoF.cont_diff_on_comp_iff, isoG.symm.comp_cont_diff_on_iff], have main : cont_diff_on 𝕜 n (gu ∘ fu) (isoE ⁻¹' s), { apply cont_diff_on.comp_same_univ gu_diff fu_diff, assume y hy, simp only [fu, continuous_linear_equiv.coe_apply, function.comp_app, mem_preimage], rw isoF.apply_symm_apply (f (isoE y)), exact st hy }, have : gu ∘ fu = (isoG.symm ∘ (g ∘ f)) ∘ isoE, { ext y, simp only [function.comp_apply, gu, fu], rw isoF.apply_symm_apply (f (isoE y)) }, rwa [this, isoE.cont_diff_on_comp_iff, isoG.symm.comp_cont_diff_on_iff] at main end /-- The composition of `C^n` functions on domains is `C^n`. -/ lemma cont_diff_on.comp' {s : set E} {t : set F} {g : F → G} {f : E → F} (hg : cont_diff_on 𝕜 n g t) (hf : cont_diff_on 𝕜 n f s) : cont_diff_on 𝕜 n (g ∘ f) (s ∩ f⁻¹' t) := hg.comp (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _) /-- The composition of a `C^n` function on a domain with a `C^n` function is `C^n`. -/ lemma cont_diff.comp_cont_diff_on {s : set E} {g : F → G} {f : E → F} (hg : cont_diff 𝕜 n g) (hf : cont_diff_on 𝕜 n f s) : cont_diff_on 𝕜 n (g ∘ f) s := (cont_diff_on_univ.2 hg).comp hf subset_preimage_univ /-- The composition of `C^n` functions is `C^n`. -/ lemma cont_diff.comp {g : F → G} {f : E → F} (hg : cont_diff 𝕜 n g) (hf : cont_diff 𝕜 n f) : cont_diff 𝕜 n (g ∘ f) := cont_diff_on_univ.1 $ cont_diff_on.comp (cont_diff_on_univ.2 hg) (cont_diff_on_univ.2 hf) (subset_univ _) /-- The composition of `C^n` functions at points in domains is `C^n`. -/ lemma cont_diff_within_at.comp {s : set E} {t : set F} {g : F → G} {f : E → F} (x : E) (hg : cont_diff_within_at 𝕜 n g t (f x)) (hf : cont_diff_within_at 𝕜 n f s x) (st : s ⊆ f ⁻¹' t) : cont_diff_within_at 𝕜 n (g ∘ f) s x := begin assume m hm, rcases hg.cont_diff_on hm with ⟨u, u_nhd, ut, hu⟩, rcases hf.cont_diff_on hm with ⟨v, v_nhd, vs, hv⟩, have xmem : x ∈ f ⁻¹' u ∩ v := ⟨(mem_of_mem_nhds_within (mem_insert (f x) _) u_nhd : _), mem_of_mem_nhds_within (mem_insert x s) v_nhd⟩, have : f ⁻¹' u ∈ 𝓝[insert x s] x, { apply hf.continuous_within_at.insert_self.preimage_mem_nhds_within', apply nhds_within_mono _ _ u_nhd, rw image_insert_eq, exact insert_subset_insert (image_subset_iff.mpr st) }, have Z := ((hu.comp (hv.mono (inter_subset_right (f ⁻¹' u) v)) (inter_subset_left _ _)) .cont_diff_within_at) xmem m le_rfl, have : 𝓝[f ⁻¹' u ∩ v] x = 𝓝[insert x s] x, { have A : f ⁻¹' u ∩ v = (insert x s) ∩ (f ⁻¹' u ∩ v), { apply subset.antisymm _ (inter_subset_right _ _), rintros y ⟨hy1, hy2⟩, simp [hy1, hy2, vs hy2] }, rw [A, ← nhds_within_restrict''], exact filter.inter_mem this v_nhd }, rwa [insert_eq_of_mem xmem, this] at Z, end /-- The composition of `C^n` functions at points in domains is `C^n`. -/ lemma cont_diff_within_at.comp' {s : set E} {t : set F} {g : F → G} {f : E → F} (x : E) (hg : cont_diff_within_at 𝕜 n g t (f x)) (hf : cont_diff_within_at 𝕜 n f s x) : cont_diff_within_at 𝕜 n (g ∘ f) (s ∩ f⁻¹' t) x := hg.comp x (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _) lemma cont_diff_at.comp_cont_diff_within_at {n} (x : E) (hg : cont_diff_at 𝕜 n g (f x)) (hf : cont_diff_within_at 𝕜 n f s x) : cont_diff_within_at 𝕜 n (g ∘ f) s x := hg.comp x hf (maps_to_univ _ _) /-- The composition of `C^n` functions at points is `C^n`. -/ lemma cont_diff_at.comp (x : E) (hg : cont_diff_at 𝕜 n g (f x)) (hf : cont_diff_at 𝕜 n f x) : cont_diff_at 𝕜 n (g ∘ f) x := hg.comp x hf subset_preimage_univ lemma cont_diff.comp_cont_diff_within_at {g : F → G} {f : E → F} (h : cont_diff 𝕜 n g) (hf : cont_diff_within_at 𝕜 n f t x) : cont_diff_within_at 𝕜 n (g ∘ f) t x := begin have : cont_diff_within_at 𝕜 n g univ (f x) := h.cont_diff_at.cont_diff_within_at, exact this.comp x hf (subset_univ _), end lemma cont_diff.comp_cont_diff_at {g : F → G} {f : E → F} (x : E) (hg : cont_diff 𝕜 n g) (hf : cont_diff_at 𝕜 n f x) : cont_diff_at 𝕜 n (g ∘ f) x := hg.comp_cont_diff_within_at hf /-! ### Smoothness of projections -/ /-- The first projection in a product is `C^∞`. -/ lemma cont_diff_fst : cont_diff 𝕜 n (prod.fst : E × F → E) := is_bounded_linear_map.cont_diff is_bounded_linear_map.fst /-- Postcomposing `f` with `prod.fst` is `C^n` -/ lemma cont_diff.fst {f : E → F × G} (hf : cont_diff 𝕜 n f) : cont_diff 𝕜 n (λ x, (f x).1) := cont_diff_fst.comp hf /-- Precomposing `f` with `prod.fst` is `C^n` -/ lemma cont_diff.fst' {f : E → G} (hf : cont_diff 𝕜 n f) : cont_diff 𝕜 n (λ x : E × F, f x.1) := hf.comp cont_diff_fst /-- The first projection on a domain in a product is `C^∞`. -/ lemma cont_diff_on_fst {s : set (E × F)} : cont_diff_on 𝕜 n (prod.fst : E × F → E) s := cont_diff.cont_diff_on cont_diff_fst lemma cont_diff_on.fst {f : E → F × G} {s : set E} (hf : cont_diff_on 𝕜 n f s) : cont_diff_on 𝕜 n (λ x, (f x).1) s := cont_diff_fst.comp_cont_diff_on hf /-- The first projection at a point in a product is `C^∞`. -/ lemma cont_diff_at_fst {p : E × F} : cont_diff_at 𝕜 n (prod.fst : E × F → E) p := cont_diff_fst.cont_diff_at /-- Postcomposing `f` with `prod.fst` is `C^n` at `(x, y)` -/ lemma cont_diff_at.fst {f : E → F × G} {x : E} (hf : cont_diff_at 𝕜 n f x) : cont_diff_at 𝕜 n (λ x, (f x).1) x := cont_diff_at_fst.comp x hf /-- Precomposing `f` with `prod.fst` is `C^n` at `(x, y)` -/ lemma cont_diff_at.fst' {f : E → G} {x : E} {y : F} (hf : cont_diff_at 𝕜 n f x) : cont_diff_at 𝕜 n (λ x : E × F, f x.1) (x, y) := cont_diff_at.comp (x, y) hf cont_diff_at_fst /-- Precomposing `f` with `prod.fst` is `C^n` at `x : E × F` -/ lemma cont_diff_at.fst'' {f : E → G} {x : E × F} (hf : cont_diff_at 𝕜 n f x.1) : cont_diff_at 𝕜 n (λ x : E × F, f x.1) x := hf.comp x cont_diff_at_fst /-- The first projection within a domain at a point in a product is `C^∞`. -/ lemma cont_diff_within_at_fst {s : set (E × F)} {p : E × F} : cont_diff_within_at 𝕜 n (prod.fst : E × F → E) s p := cont_diff_fst.cont_diff_within_at /-- The second projection in a product is `C^∞`. -/ lemma cont_diff_snd : cont_diff 𝕜 n (prod.snd : E × F → F) := is_bounded_linear_map.cont_diff is_bounded_linear_map.snd /-- Postcomposing `f` with `prod.snd` is `C^n` -/ lemma cont_diff.snd {f : E → F × G} (hf : cont_diff 𝕜 n f) : cont_diff 𝕜 n (λ x, (f x).2) := cont_diff_snd.comp hf /-- Precomposing `f` with `prod.snd` is `C^n` -/ lemma cont_diff.snd' {f : F → G} (hf : cont_diff 𝕜 n f) : cont_diff 𝕜 n (λ x : E × F, f x.2) := hf.comp cont_diff_snd /-- The second projection on a domain in a product is `C^∞`. -/ lemma cont_diff_on_snd {s : set (E × F)} : cont_diff_on 𝕜 n (prod.snd : E × F → F) s := cont_diff.cont_diff_on cont_diff_snd lemma cont_diff_on.snd {f : E → F × G} {s : set E} (hf : cont_diff_on 𝕜 n f s) : cont_diff_on 𝕜 n (λ x, (f x).2) s := cont_diff_snd.comp_cont_diff_on hf /-- The second projection at a point in a product is `C^∞`. -/ lemma cont_diff_at_snd {p : E × F} : cont_diff_at 𝕜 n (prod.snd : E × F → F) p := cont_diff_snd.cont_diff_at /-- Postcomposing `f` with `prod.snd` is `C^n` at `x` -/ lemma cont_diff_at.snd {f : E → F × G} {x : E} (hf : cont_diff_at 𝕜 n f x) : cont_diff_at 𝕜 n (λ x, (f x).2) x := cont_diff_at_snd.comp x hf /-- Precomposing `f` with `prod.snd` is `C^n` at `(x, y)` -/ lemma cont_diff_at.snd' {f : F → G} {x : E} {y : F} (hf : cont_diff_at 𝕜 n f y) : cont_diff_at 𝕜 n (λ x : E × F, f x.2) (x, y) := cont_diff_at.comp (x, y) hf cont_diff_at_snd /-- Precomposing `f` with `prod.snd` is `C^n` at `x : E × F` -/ lemma cont_diff_at.snd'' {f : F → G} {x : E × F} (hf : cont_diff_at 𝕜 n f x.2) : cont_diff_at 𝕜 n (λ x : E × F, f x.2) x := hf.comp x cont_diff_at_snd /-- The second projection within a domain at a point in a product is `C^∞`. -/ lemma cont_diff_within_at_snd {s : set (E × F)} {p : E × F} : cont_diff_within_at 𝕜 n (prod.snd : E × F → F) s p := cont_diff_snd.cont_diff_within_at section n_ary variables {E₁ E₂ E₃ E₄ : Type*} variables [normed_group E₁] [normed_group E₂] [normed_group E₃] [normed_group E₄] variables [normed_space 𝕜 E₁] [normed_space 𝕜 E₂] [normed_space 𝕜 E₃] [normed_space 𝕜 E₄] lemma cont_diff.comp₂ {g : E₁ × E₂ → G} {f₁ : F → E₁} {f₂ : F → E₂} (hg : cont_diff 𝕜 n g) (hf₁ : cont_diff 𝕜 n f₁) (hf₂ : cont_diff 𝕜 n f₂) : cont_diff 𝕜 n (λ x, g (f₁ x, f₂ x)) := hg.comp $ hf₁.prod hf₂ lemma cont_diff.comp₃ {g : E₁ × E₂ × E₃ → G} {f₁ : F → E₁} {f₂ : F → E₂} {f₃ : F → E₃} (hg : cont_diff 𝕜 n g) (hf₁ : cont_diff 𝕜 n f₁) (hf₂ : cont_diff 𝕜 n f₂) (hf₃ : cont_diff 𝕜 n f₃) : cont_diff 𝕜 n (λ x, g (f₁ x, f₂ x, f₃ x)) := hg.comp₂ hf₁ $ hf₂.prod hf₃ lemma cont_diff.comp_cont_diff_on₂ {g : E₁ × E₂ → G} {f₁ : F → E₁} {f₂ : F → E₂} {s : set F} (hg : cont_diff 𝕜 n g) (hf₁ : cont_diff_on 𝕜 n f₁ s) (hf₂ : cont_diff_on 𝕜 n f₂ s) : cont_diff_on 𝕜 n (λ x, g (f₁ x, f₂ x)) s := hg.comp_cont_diff_on $ hf₁.prod hf₂ lemma cont_diff.comp_cont_diff_on₃ {g : E₁ × E₂ × E₃ → G} {f₁ : F → E₁} {f₂ : F → E₂} {f₃ : F → E₃} {s : set F} (hg : cont_diff 𝕜 n g) (hf₁ : cont_diff_on 𝕜 n f₁ s) (hf₂ : cont_diff_on 𝕜 n f₂ s) (hf₃ : cont_diff_on 𝕜 n f₃ s) : cont_diff_on 𝕜 n (λ x, g (f₁ x, f₂ x, f₃ x)) s := hg.comp_cont_diff_on₂ hf₁ $ hf₂.prod hf₃ end n_ary /-- The natural equivalence `(E × F) × G ≃ E × (F × G)` is smooth. Warning: if you think you need this lemma, it is likely that you can simplify your proof by reformulating the lemma that you're applying next using the tips in Note [continuity lemma statement] -/ lemma cont_diff_prod_assoc : cont_diff 𝕜 ⊤ $ equiv.prod_assoc E F G := (linear_isometry_equiv.prod_assoc 𝕜 E F G).cont_diff /-- The natural equivalence `E × (F × G) ≃ (E × F) × G` is smooth. Warning: see remarks attached to `cont_diff_prod_assoc` -/ lemma cont_diff_prod_assoc_symm : cont_diff 𝕜 ⊤ $ (equiv.prod_assoc E F G).symm := (linear_isometry_equiv.prod_assoc 𝕜 E F G).symm.cont_diff /-! ### Bundled derivatives -/ /-- The bundled derivative of a `C^{n+1}` function is `C^n`. -/ lemma cont_diff_on_fderiv_within_apply {m n : with_top ℕ} {s : set E} {f : E → F} (hf : cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) (hmn : m + 1 ≤ n) : cont_diff_on 𝕜 m (λp : E × E, (fderiv_within 𝕜 f s p.1 : E →L[𝕜] F) p.2) (s ×ˢ (univ : set E)) := begin have A : cont_diff 𝕜 m (λp : (E →L[𝕜] F) × E, p.1 p.2), { apply is_bounded_bilinear_map.cont_diff, exact is_bounded_bilinear_map_apply }, have B : cont_diff_on 𝕜 m (λ (p : E × E), ((fderiv_within 𝕜 f s p.fst), p.snd)) (s ×ˢ univ), { apply cont_diff_on.prod _ _, { have I : cont_diff_on 𝕜 m (λ (x : E), fderiv_within 𝕜 f s x) s := hf.fderiv_within hs hmn, have J : cont_diff_on 𝕜 m (λ (x : E × E), x.1) (s ×ˢ univ) := cont_diff_fst.cont_diff_on, exact cont_diff_on.comp I J (prod_subset_preimage_fst _ _) }, { apply cont_diff.cont_diff_on _ , apply is_bounded_linear_map.snd.cont_diff } }, exact A.comp_cont_diff_on B end /-- The bundled derivative of a `C^{n+1}` function is `C^n`. -/ lemma cont_diff.cont_diff_fderiv_apply {f : E → F} (hf : cont_diff 𝕜 n f) (hmn : m + 1 ≤ n) : cont_diff 𝕜 m (λp : E × E, (fderiv 𝕜 f p.1 : E →L[𝕜] F) p.2) := begin rw ← cont_diff_on_univ at ⊢ hf, rw [← fderiv_within_univ, ← univ_prod_univ], exact cont_diff_on_fderiv_within_apply hf unique_diff_on_univ hmn end /-! ### Smoothness of functions `f : E → Π i, F' i` -/ section pi variables {ι ι' : Type*} [fintype ι] [fintype ι'] {F' : ι → Type*} [Π i, normed_group (F' i)] [Π i, normed_space 𝕜 (F' i)] {φ : Π i, E → F' i} {p' : Π i, E → formal_multilinear_series 𝕜 E (F' i)} {Φ : E → Π i, F' i} {P' : E → formal_multilinear_series 𝕜 E (Π i, F' i)} lemma has_ftaylor_series_up_to_on_pi : has_ftaylor_series_up_to_on n (λ x i, φ i x) (λ x m, continuous_multilinear_map.pi (λ i, p' i x m)) s ↔ ∀ i, has_ftaylor_series_up_to_on n (φ i) (p' i) s := begin set pr := @continuous_linear_map.proj 𝕜 _ ι F' _ _ _, letI : Π (m : ℕ) (i : ι), normed_space 𝕜 (E [×m]→L[𝕜] (F' i)) := λ m i, infer_instance, set L : Π m : ℕ, (Π i, E [×m]→L[𝕜] (F' i)) ≃ₗᵢ[𝕜] (E [×m]→L[𝕜] (Π i, F' i)) := λ m, continuous_multilinear_map.piₗᵢ _ _, refine ⟨λ h i, _, λ h, ⟨λ x hx, _, _, _⟩⟩, { convert h.continuous_linear_map_comp (pr i), ext, refl }, { ext1 i, exact (h i).zero_eq x hx }, { intros m hm x hx, have := has_fderiv_within_at_pi.2 (λ i, (h i).fderiv_within m hm x hx), convert (L m).has_fderiv_at.comp_has_fderiv_within_at x this }, { intros m hm, have := continuous_on_pi.2 (λ i, (h i).cont m hm), convert (L m).continuous.comp_continuous_on this } end @[simp] lemma has_ftaylor_series_up_to_on_pi' : has_ftaylor_series_up_to_on n Φ P' s ↔ ∀ i, has_ftaylor_series_up_to_on n (λ x, Φ x i) (λ x m, (@continuous_linear_map.proj 𝕜 _ ι F' _ _ _ i).comp_continuous_multilinear_map (P' x m)) s := by { convert has_ftaylor_series_up_to_on_pi, ext, refl } lemma cont_diff_within_at_pi : cont_diff_within_at 𝕜 n Φ s x ↔ ∀ i, cont_diff_within_at 𝕜 n (λ x, Φ x i) s x := begin set pr := @continuous_linear_map.proj 𝕜 _ ι F' _ _ _, refine ⟨λ h i, h.continuous_linear_map_comp (pr i), λ h m hm, _⟩, choose u hux p hp using λ i, h i m hm, exact ⟨⋂ i, u i, filter.Inter_mem.2 hux, _, has_ftaylor_series_up_to_on_pi.2 (λ i, (hp i).mono $ Inter_subset _ _)⟩, end lemma cont_diff_on_pi : cont_diff_on 𝕜 n Φ s ↔ ∀ i, cont_diff_on 𝕜 n (λ x, Φ x i) s := ⟨λ h i x hx, cont_diff_within_at_pi.1 (h x hx) _, λ h x hx, cont_diff_within_at_pi.2 (λ i, h i x hx)⟩ lemma cont_diff_at_pi : cont_diff_at 𝕜 n Φ x ↔ ∀ i, cont_diff_at 𝕜 n (λ x, Φ x i) x := cont_diff_within_at_pi lemma cont_diff_pi : cont_diff 𝕜 n Φ ↔ ∀ i, cont_diff 𝕜 n (λ x, Φ x i) := by simp only [← cont_diff_on_univ, cont_diff_on_pi] variables (𝕜 E) lemma cont_diff_apply (i : ι) : cont_diff 𝕜 n (λ (f : ι → E), f i) := cont_diff_pi.mp cont_diff_id i lemma cont_diff_apply_apply (i : ι) (j : ι') : cont_diff 𝕜 n (λ (f : ι → ι' → E), f i j) := cont_diff_pi.mp (cont_diff_apply 𝕜 (ι' → E) i) j variables {𝕜 E} end pi /-! ### Sum of two functions -/ /- The sum is smooth. -/ lemma cont_diff_add : cont_diff 𝕜 n (λp : F × F, p.1 + p.2) := (is_bounded_linear_map.fst.add is_bounded_linear_map.snd).cont_diff /-- The sum of two `C^n` functions within a set at a point is `C^n` within this set at this point. -/ lemma cont_diff_within_at.add {s : set E} {f g : E → F} (hf : cont_diff_within_at 𝕜 n f s x) (hg : cont_diff_within_at 𝕜 n g s x) : cont_diff_within_at 𝕜 n (λx, f x + g x) s x := cont_diff_add.cont_diff_within_at.comp x (hf.prod hg) subset_preimage_univ /-- The sum of two `C^n` functions at a point is `C^n` at this point. -/ lemma cont_diff_at.add {f g : E → F} (hf : cont_diff_at 𝕜 n f x) (hg : cont_diff_at 𝕜 n g x) : cont_diff_at 𝕜 n (λx, f x + g x) x := by rw [← cont_diff_within_at_univ] at *; exact hf.add hg /-- The sum of two `C^n`functions is `C^n`. -/ lemma cont_diff.add {f g : E → F} (hf : cont_diff 𝕜 n f) (hg : cont_diff 𝕜 n g) : cont_diff 𝕜 n (λx, f x + g x) := cont_diff_add.comp (hf.prod hg) /-- The sum of two `C^n` functions on a domain is `C^n`. -/ lemma cont_diff_on.add {s : set E} {f g : E → F} (hf : cont_diff_on 𝕜 n f s) (hg : cont_diff_on 𝕜 n g s) : cont_diff_on 𝕜 n (λx, f x + g x) s := λ x hx, (hf x hx).add (hg x hx) /-! ### Negative -/ /- The negative is smooth. -/ lemma cont_diff_neg : cont_diff 𝕜 n (λp : F, -p) := is_bounded_linear_map.id.neg.cont_diff /-- The negative of a `C^n` function within a domain at a point is `C^n` within this domain at this point. -/ lemma cont_diff_within_at.neg {s : set E} {f : E → F} (hf : cont_diff_within_at 𝕜 n f s x) : cont_diff_within_at 𝕜 n (λx, -f x) s x := cont_diff_neg.cont_diff_within_at.comp x hf subset_preimage_univ /-- The negative of a `C^n` function at a point is `C^n` at this point. -/ lemma cont_diff_at.neg {f : E → F} (hf : cont_diff_at 𝕜 n f x) : cont_diff_at 𝕜 n (λx, -f x) x := by rw ← cont_diff_within_at_univ at *; exact hf.neg /-- The negative of a `C^n`function is `C^n`. -/ lemma cont_diff.neg {f : E → F} (hf : cont_diff 𝕜 n f) : cont_diff 𝕜 n (λx, -f x) := cont_diff_neg.comp hf /-- The negative of a `C^n` function on a domain is `C^n`. -/ lemma cont_diff_on.neg {s : set E} {f : E → F} (hf : cont_diff_on 𝕜 n f s) : cont_diff_on 𝕜 n (λx, -f x) s := λ x hx, (hf x hx).neg /-! ### Subtraction -/ /-- The difference of two `C^n` functions within a set at a point is `C^n` within this set at this point. -/ lemma cont_diff_within_at.sub {s : set E} {f g : E → F} (hf : cont_diff_within_at 𝕜 n f s x) (hg : cont_diff_within_at 𝕜 n g s x) : cont_diff_within_at 𝕜 n (λx, f x - g x) s x := by simpa only [sub_eq_add_neg] using hf.add hg.neg /-- The difference of two `C^n` functions at a point is `C^n` at this point. -/ lemma cont_diff_at.sub {f g : E → F} (hf : cont_diff_at 𝕜 n f x) (hg : cont_diff_at 𝕜 n g x) : cont_diff_at 𝕜 n (λx, f x - g x) x := by simpa only [sub_eq_add_neg] using hf.add hg.neg /-- The difference of two `C^n` functions on a domain is `C^n`. -/ lemma cont_diff_on.sub {s : set E} {f g : E → F} (hf : cont_diff_on 𝕜 n f s) (hg : cont_diff_on 𝕜 n g s) : cont_diff_on 𝕜 n (λx, f x - g x) s := by simpa only [sub_eq_add_neg] using hf.add hg.neg /-- The difference of two `C^n` functions is `C^n`. -/ lemma cont_diff.sub {f g : E → F} (hf : cont_diff 𝕜 n f) (hg : cont_diff 𝕜 n g) : cont_diff 𝕜 n (λx, f x - g x) := by simpa only [sub_eq_add_neg] using hf.add hg.neg /-! ### Sum of finitely many functions -/ lemma cont_diff_within_at.sum {ι : Type*} {f : ι → E → F} {s : finset ι} {t : set E} {x : E} (h : ∀ i ∈ s, cont_diff_within_at 𝕜 n (λ x, f i x) t x) : cont_diff_within_at 𝕜 n (λ x, (∑ i in s, f i x)) t x := begin classical, induction s using finset.induction_on with i s is IH, { simp [cont_diff_within_at_const] }, { simp only [is, finset.sum_insert, not_false_iff], exact (h _ (finset.mem_insert_self i s)).add (IH (λ j hj, h _ (finset.mem_insert_of_mem hj))) } end lemma cont_diff_at.sum {ι : Type*} {f : ι → E → F} {s : finset ι} {x : E} (h : ∀ i ∈ s, cont_diff_at 𝕜 n (λ x, f i x) x) : cont_diff_at 𝕜 n (λ x, (∑ i in s, f i x)) x := by rw [← cont_diff_within_at_univ] at *; exact cont_diff_within_at.sum h lemma cont_diff_on.sum {ι : Type*} {f : ι → E → F} {s : finset ι} {t : set E} (h : ∀ i ∈ s, cont_diff_on 𝕜 n (λ x, f i x) t) : cont_diff_on 𝕜 n (λ x, (∑ i in s, f i x)) t := λ x hx, cont_diff_within_at.sum (λ i hi, h i hi x hx) lemma cont_diff.sum {ι : Type*} {f : ι → E → F} {s : finset ι} (h : ∀ i ∈ s, cont_diff 𝕜 n (λ x, f i x)) : cont_diff 𝕜 n (λ x, (∑ i in s, f i x)) := by simp [← cont_diff_on_univ] at *; exact cont_diff_on.sum h /-! ### Product of two functions -/ /- The product is smooth. -/ lemma cont_diff_mul : cont_diff 𝕜 n (λ p : 𝕜 × 𝕜, p.1 * p.2) := is_bounded_bilinear_map_mul.cont_diff /-- The product of two `C^n` functions within a set at a point is `C^n` within this set at this point. -/ lemma cont_diff_within_at.mul {s : set E} {f g : E → 𝕜} (hf : cont_diff_within_at 𝕜 n f s x) (hg : cont_diff_within_at 𝕜 n g s x) : cont_diff_within_at 𝕜 n (λ x, f x * g x) s x := cont_diff_mul.cont_diff_within_at.comp x (hf.prod hg) subset_preimage_univ /-- The product of two `C^n` functions at a point is `C^n` at this point. -/ lemma cont_diff_at.mul {f g : E → 𝕜} (hf : cont_diff_at 𝕜 n f x) (hg : cont_diff_at 𝕜 n g x) : cont_diff_at 𝕜 n (λ x, f x * g x) x := by rw [← cont_diff_within_at_univ] at *; exact hf.mul hg /-- The product of two `C^n` functions on a domain is `C^n`. -/ lemma cont_diff_on.mul {s : set E} {f g : E → 𝕜} (hf : cont_diff_on 𝕜 n f s) (hg : cont_diff_on 𝕜 n g s) : cont_diff_on 𝕜 n (λ x, f x * g x) s := λ x hx, (hf x hx).mul (hg x hx) /-- The product of two `C^n`functions is `C^n`. -/ lemma cont_diff.mul {f g : E → 𝕜} (hf : cont_diff 𝕜 n f) (hg : cont_diff 𝕜 n g) : cont_diff 𝕜 n (λ x, f x * g x) := cont_diff_mul.comp (hf.prod hg) lemma cont_diff_within_at.div_const {f : E → 𝕜} {n} {c : 𝕜} (hf : cont_diff_within_at 𝕜 n f s x) : cont_diff_within_at 𝕜 n (λ x, f x / c) s x := by simpa only [div_eq_mul_inv] using hf.mul cont_diff_within_at_const lemma cont_diff_at.div_const {f : E → 𝕜} {n} {c : 𝕜} (hf : cont_diff_at 𝕜 n f x) : cont_diff_at 𝕜 n (λ x, f x / c) x := by simpa only [div_eq_mul_inv] using hf.mul cont_diff_at_const lemma cont_diff_on.div_const {f : E → 𝕜} {n} {c : 𝕜} (hf : cont_diff_on 𝕜 n f s) : cont_diff_on 𝕜 n (λ x, f x / c) s := by simpa only [div_eq_mul_inv] using hf.mul cont_diff_on_const lemma cont_diff.div_const {f : E → 𝕜} {n} {c : 𝕜} (hf : cont_diff 𝕜 n f) : cont_diff 𝕜 n (λ x, f x / c) := by simpa only [div_eq_mul_inv] using hf.mul cont_diff_const lemma cont_diff.pow {f : E → 𝕜} (hf : cont_diff 𝕜 n f) : ∀ m : ℕ, cont_diff 𝕜 n (λ x, (f x) ^ m) | 0 := by simpa using cont_diff_const | (m + 1) := by simpa [pow_succ] using hf.mul (cont_diff.pow m) lemma cont_diff_at.pow {f : E → 𝕜} (hf : cont_diff_at 𝕜 n f x) (m : ℕ) : cont_diff_at 𝕜 n (λ y, f y ^ m) x := (cont_diff_id.pow m).cont_diff_at.comp x hf lemma cont_diff_within_at.pow {f : E → 𝕜} (hf : cont_diff_within_at 𝕜 n f s x) (m : ℕ) : cont_diff_within_at 𝕜 n (λ y, f y ^ m) s x := (cont_diff_id.pow m).cont_diff_at.comp_cont_diff_within_at x hf lemma cont_diff_on.pow {f : E → 𝕜} (hf : cont_diff_on 𝕜 n f s) (m : ℕ) : cont_diff_on 𝕜 n (λ y, f y ^ m) s := λ y hy, (hf y hy).pow m /-! ### Scalar multiplication -/ /- The scalar multiplication is smooth. -/ lemma cont_diff_smul : cont_diff 𝕜 n (λ p : 𝕜 × F, p.1 • p.2) := is_bounded_bilinear_map_smul.cont_diff /-- The scalar multiplication of two `C^n` functions within a set at a point is `C^n` within this set at this point. -/ lemma cont_diff_within_at.smul {s : set E} {f : E → 𝕜} {g : E → F} (hf : cont_diff_within_at 𝕜 n f s x) (hg : cont_diff_within_at 𝕜 n g s x) : cont_diff_within_at 𝕜 n (λ x, f x • g x) s x := cont_diff_smul.cont_diff_within_at.comp x (hf.prod hg) subset_preimage_univ /-- The scalar multiplication of two `C^n` functions at a point is `C^n` at this point. -/ lemma cont_diff_at.smul {f : E → 𝕜} {g : E → F} (hf : cont_diff_at 𝕜 n f x) (hg : cont_diff_at 𝕜 n g x) : cont_diff_at 𝕜 n (λ x, f x • g x) x := by rw [← cont_diff_within_at_univ] at *; exact hf.smul hg /-- The scalar multiplication of two `C^n` functions is `C^n`. -/ lemma cont_diff.smul {f : E → 𝕜} {g : E → F} (hf : cont_diff 𝕜 n f) (hg : cont_diff 𝕜 n g) : cont_diff 𝕜 n (λ x, f x • g x) := cont_diff_smul.comp (hf.prod hg) /-- The scalar multiplication of two `C^n` functions on a domain is `C^n`. -/ lemma cont_diff_on.smul {s : set E} {f : E → 𝕜} {g : E → F} (hf : cont_diff_on 𝕜 n f s) (hg : cont_diff_on 𝕜 n g s) : cont_diff_on 𝕜 n (λ x, f x • g x) s := λ x hx, (hf x hx).smul (hg x hx) /-! ### Cartesian product of two functions -/ section prod_map variables {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] variables {F' : Type*} [normed_group F'] [normed_space 𝕜 F'] /-- The product map of two `C^n` functions within a set at a point is `C^n` within the product set at the product point. -/ lemma cont_diff_within_at.prod_map' {s : set E} {t : set E'} {f : E → F} {g : E' → F'} {p : E × E'} (hf : cont_diff_within_at 𝕜 n f s p.1) (hg : cont_diff_within_at 𝕜 n g t p.2) : cont_diff_within_at 𝕜 n (prod.map f g) (s ×ˢ t) p := (hf.comp p cont_diff_within_at_fst (prod_subset_preimage_fst _ _)).prod (hg.comp p cont_diff_within_at_snd (prod_subset_preimage_snd _ _)) lemma cont_diff_within_at.prod_map {s : set E} {t : set E'} {f : E → F} {g : E' → F'} {x : E} {y : E'} (hf : cont_diff_within_at 𝕜 n f s x) (hg : cont_diff_within_at 𝕜 n g t y) : cont_diff_within_at 𝕜 n (prod.map f g) (s ×ˢ t) (x, y) := cont_diff_within_at.prod_map' hf hg /-- The product map of two `C^n` functions on a set is `C^n` on the product set. -/ lemma cont_diff_on.prod_map {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {F' : Type*} [normed_group F'] [normed_space 𝕜 F'] {s : set E} {t : set E'} {f : E → F} {g : E' → F'} (hf : cont_diff_on 𝕜 n f s) (hg : cont_diff_on 𝕜 n g t) : cont_diff_on 𝕜 n (prod.map f g) (s ×ˢ t) := (hf.comp cont_diff_on_fst (prod_subset_preimage_fst _ _)).prod (hg.comp (cont_diff_on_snd) (prod_subset_preimage_snd _ _)) /-- The product map of two `C^n` functions within a set at a point is `C^n` within the product set at the product point. -/ lemma cont_diff_at.prod_map {f : E → F} {g : E' → F'} {x : E} {y : E'} (hf : cont_diff_at 𝕜 n f x) (hg : cont_diff_at 𝕜 n g y) : cont_diff_at 𝕜 n (prod.map f g) (x, y) := begin rw cont_diff_at at *, convert hf.prod_map hg, simp only [univ_prod_univ] end /-- The product map of two `C^n` functions within a set at a point is `C^n` within the product set at the product point. -/ lemma cont_diff_at.prod_map' {f : E → F} {g : E' → F'} {p : E × E'} (hf : cont_diff_at 𝕜 n f p.1) (hg : cont_diff_at 𝕜 n g p.2) : cont_diff_at 𝕜 n (prod.map f g) p := begin rcases p, exact cont_diff_at.prod_map hf hg end /-- The product map of two `C^n` functions is `C^n`. -/ lemma cont_diff.prod_map {f : E → F} {g : E' → F'} (hf : cont_diff 𝕜 n f) (hg : cont_diff 𝕜 n g) : cont_diff 𝕜 n (prod.map f g) := begin rw cont_diff_iff_cont_diff_at at *, exact λ ⟨x, y⟩, (hf x).prod_map (hg y) end lemma cont_diff_prod_mk_left (f₀ : F) : cont_diff 𝕜 n (λ e : E, (e, f₀)) := cont_diff_id.prod cont_diff_const lemma cont_diff_prod_mk_right (e₀ : E) : cont_diff 𝕜 n (λ f : F, (e₀, f)) := cont_diff_const.prod cont_diff_id end prod_map lemma cont_diff.clm_comp {g : X → F →L[𝕜] G} {f : X → E →L[𝕜] F} (hg : cont_diff 𝕜 n g) (hf : cont_diff 𝕜 n f) : cont_diff 𝕜 n (λ x, (g x).comp (f x)) := is_bounded_bilinear_map_comp.cont_diff.comp₂ hg hf lemma cont_diff_on.clm_comp {g : X → F →L[𝕜] G} {f : X → E →L[𝕜] F} {s : set X} (hg : cont_diff_on 𝕜 n g s) (hf : cont_diff_on 𝕜 n f s) : cont_diff_on 𝕜 n (λ x, (g x).comp (f x)) s := is_bounded_bilinear_map_comp.cont_diff.comp_cont_diff_on₂ hg hf /-! ### Inversion in a complete normed algebra -/ section algebra_inverse variables (𝕜) {R : Type*} [normed_ring R] [normed_algebra 𝕜 R] open normed_ring continuous_linear_map ring /-- In a complete normed algebra, the operation of inversion is `C^n`, for all `n`, at each invertible element. The proof is by induction, bootstrapping using an identity expressing the derivative of inversion as a bilinear map of inversion itself. -/ lemma cont_diff_at_ring_inverse [complete_space R] (x : Rˣ) : cont_diff_at 𝕜 n ring.inverse (x : R) := begin induction n using with_top.nat_induction with n IH Itop, { intros m hm, refine ⟨{y : R | is_unit y}, _, _⟩, { simp [nhds_within_univ], exact x.nhds }, { use (ftaylor_series_within 𝕜 inverse univ), rw [le_antisymm hm bot_le, has_ftaylor_series_up_to_on_zero_iff], split, { rintros _ ⟨x', rfl⟩, exact (inverse_continuous_at x').continuous_within_at }, { simp [ftaylor_series_within] } } }, { apply cont_diff_at_succ_iff_has_fderiv_at.mpr, refine ⟨λ (x : R), - lmul_left_right 𝕜 R (inverse x) (inverse x), _, _⟩, { refine ⟨{y : R | is_unit y}, x.nhds, _⟩, rintros _ ⟨y, rfl⟩, rw [inverse_unit], exact has_fderiv_at_ring_inverse y }, { convert (lmul_left_right_is_bounded_bilinear 𝕜 R).cont_diff.neg.comp_cont_diff_at (x : R) (IH.prod IH) } }, { exact cont_diff_at_top.mpr Itop } end variables (𝕜) {𝕜' : Type*} [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] [complete_space 𝕜'] lemma cont_diff_at_inv {x : 𝕜'} (hx : x ≠ 0) {n} : cont_diff_at 𝕜 n has_inv.inv x := by simpa only [ring.inverse_eq_inv'] using cont_diff_at_ring_inverse 𝕜 (units.mk0 x hx) lemma cont_diff_on_inv {n} : cont_diff_on 𝕜 n (has_inv.inv : 𝕜' → 𝕜') {0}ᶜ := λ x hx, (cont_diff_at_inv 𝕜 hx).cont_diff_within_at variable {𝕜} -- TODO: the next few lemmas don't need `𝕜` or `𝕜'` to be complete -- A good way to show this is to generalize `cont_diff_at_ring_inverse` to the setting -- of a function `f` such that `∀ᶠ x in 𝓝 a, x * f x = 1`. lemma cont_diff_within_at.inv {f : E → 𝕜'} {n} (hf : cont_diff_within_at 𝕜 n f s x) (hx : f x ≠ 0) : cont_diff_within_at 𝕜 n (λ x, (f x)⁻¹) s x := (cont_diff_at_inv 𝕜 hx).comp_cont_diff_within_at x hf lemma cont_diff_on.inv {f : E → 𝕜'} {n} (hf : cont_diff_on 𝕜 n f s) (h : ∀ x ∈ s, f x ≠ 0) : cont_diff_on 𝕜 n (λ x, (f x)⁻¹) s := λ x hx, (hf.cont_diff_within_at hx).inv (h x hx) lemma cont_diff_at.inv {f : E → 𝕜'} {n} (hf : cont_diff_at 𝕜 n f x) (hx : f x ≠ 0) : cont_diff_at 𝕜 n (λ x, (f x)⁻¹) x := hf.inv hx lemma cont_diff.inv {f : E → 𝕜'} {n} (hf : cont_diff 𝕜 n f) (h : ∀ x, f x ≠ 0) : cont_diff 𝕜 n (λ x, (f x)⁻¹) := by { rw cont_diff_iff_cont_diff_at, exact λ x, hf.cont_diff_at.inv (h x) } -- TODO: generalize to `f g : E → 𝕜'` lemma cont_diff_within_at.div [complete_space 𝕜] {f g : E → 𝕜} {n} (hf : cont_diff_within_at 𝕜 n f s x) (hg : cont_diff_within_at 𝕜 n g s x) (hx : g x ≠ 0) : cont_diff_within_at 𝕜 n (λ x, f x / g x) s x := by simpa only [div_eq_mul_inv] using hf.mul (hg.inv hx) lemma cont_diff_on.div [complete_space 𝕜] {f g : E → 𝕜} {n} (hf : cont_diff_on 𝕜 n f s) (hg : cont_diff_on 𝕜 n g s) (h₀ : ∀ x ∈ s, g x ≠ 0) : cont_diff_on 𝕜 n (f / g) s := λ x hx, (hf x hx).div (hg x hx) (h₀ x hx) lemma cont_diff_at.div [complete_space 𝕜] {f g : E → 𝕜} {n} (hf : cont_diff_at 𝕜 n f x) (hg : cont_diff_at 𝕜 n g x) (hx : g x ≠ 0) : cont_diff_at 𝕜 n (λ x, f x / g x) x := hf.div hg hx lemma cont_diff.div [complete_space 𝕜] {f g : E → 𝕜} {n} (hf : cont_diff 𝕜 n f) (hg : cont_diff 𝕜 n g) (h0 : ∀ x, g x ≠ 0) : cont_diff 𝕜 n (λ x, f x / g x) := begin simp only [cont_diff_iff_cont_diff_at] at *, exact λ x, (hf x).div (hg x) (h0 x) end end algebra_inverse /-! ### Inversion of continuous linear maps between Banach spaces -/ section map_inverse open continuous_linear_map /-- At a continuous linear equivalence `e : E ≃L[𝕜] F` between Banach spaces, the operation of inversion is `C^n`, for all `n`. -/ lemma cont_diff_at_map_inverse [complete_space E] (e : E ≃L[𝕜] F) : cont_diff_at 𝕜 n inverse (e : E →L[𝕜] F) := begin nontriviality E, -- first, we use the lemma `to_ring_inverse` to rewrite in terms of `ring.inverse` in the ring -- `E →L[𝕜] E` let O₁ : (E →L[𝕜] E) → (F →L[𝕜] E) := λ f, f.comp (e.symm : (F →L[𝕜] E)), let O₂ : (E →L[𝕜] F) → (E →L[𝕜] E) := λ f, (e.symm : (F →L[𝕜] E)).comp f, have : continuous_linear_map.inverse = O₁ ∘ ring.inverse ∘ O₂ := funext (to_ring_inverse e), rw this, -- `O₁` and `O₂` are `cont_diff`, -- so we reduce to proving that `ring.inverse` is `cont_diff` have h₁ : cont_diff 𝕜 n O₁ := cont_diff_id.clm_comp cont_diff_const, have h₂ : cont_diff 𝕜 n O₂ := cont_diff_const.clm_comp cont_diff_id, refine h₁.cont_diff_at.comp _ (cont_diff_at.comp _ _ h₂.cont_diff_at), convert cont_diff_at_ring_inverse 𝕜 (1 : (E →L[𝕜] E)ˣ), simp [O₂, one_def] end end map_inverse section function_inverse open continuous_linear_map /-- If `f` is a local homeomorphism and the point `a` is in its target, and if `f` is `n` times continuously differentiable at `f.symm a`, and if the derivative at `f.symm a` is a continuous linear equivalence, then `f.symm` is `n` times continuously differentiable at the point `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem local_homeomorph.cont_diff_at_symm [complete_space E] (f : local_homeomorph E F) {f₀' : E ≃L[𝕜] F} {a : F} (ha : a ∈ f.target) (hf₀' : has_fderiv_at f (f₀' : E →L[𝕜] F) (f.symm a)) (hf : cont_diff_at 𝕜 n f (f.symm a)) : cont_diff_at 𝕜 n f.symm a := begin -- We prove this by induction on `n` induction n using with_top.nat_induction with n IH Itop, { rw cont_diff_at_zero, exact ⟨f.target, is_open.mem_nhds f.open_target ha, f.continuous_inv_fun⟩ }, { obtain ⟨f', ⟨u, hu, hff'⟩, hf'⟩ := cont_diff_at_succ_iff_has_fderiv_at.mp hf, apply cont_diff_at_succ_iff_has_fderiv_at.mpr, -- For showing `n.succ` times continuous differentiability (the main inductive step), it -- suffices to produce the derivative and show that it is `n` times continuously differentiable have eq_f₀' : f' (f.symm a) = f₀', { exact (hff' (f.symm a) (mem_of_mem_nhds hu)).unique hf₀' }, -- This follows by a bootstrapping formula expressing the derivative as a function of `f` itself refine ⟨inverse ∘ f' ∘ f.symm, _, _⟩, { -- We first check that the derivative of `f` is that formula have h_nhds : {y : E | ∃ (e : E ≃L[𝕜] F), ↑e = f' y} ∈ 𝓝 ((f.symm) a), { have hf₀' := f₀'.nhds, rw ← eq_f₀' at hf₀', exact hf'.continuous_at.preimage_mem_nhds hf₀' }, obtain ⟨t, htu, ht, htf⟩ := mem_nhds_iff.mp (filter.inter_mem hu h_nhds), use f.target ∩ (f.symm) ⁻¹' t, refine ⟨is_open.mem_nhds _ _, _⟩, { exact f.preimage_open_of_open_symm ht }, { exact mem_inter ha (mem_preimage.mpr htf) }, intros x hx, obtain ⟨hxu, e, he⟩ := htu hx.2, have h_deriv : has_fderiv_at f ↑e ((f.symm) x), { rw he, exact hff' (f.symm x) hxu }, convert f.has_fderiv_at_symm hx.1 h_deriv, simp [← he] }, { -- Then we check that the formula, being a composition of `cont_diff` pieces, is -- itself `cont_diff` have h_deriv₁ : cont_diff_at 𝕜 n inverse (f' (f.symm a)), { rw eq_f₀', exact cont_diff_at_map_inverse _ }, have h_deriv₂ : cont_diff_at 𝕜 n f.symm a, { refine IH (hf.of_le _), norm_cast, exact nat.le_succ n }, exact (h_deriv₁.comp _ hf').comp _ h_deriv₂ } }, { refine cont_diff_at_top.mpr _, intros n, exact Itop n (cont_diff_at_top.mp hf n) } end /-- If `f` is an `n` times continuously differentiable homeomorphism, and if the derivative of `f` at each point is a continuous linear equivalence, then `f.symm` is `n` times continuously differentiable. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem homeomorph.cont_diff_symm [complete_space E] (f : E ≃ₜ F) {f₀' : E → E ≃L[𝕜] F} (hf₀' : ∀ a, has_fderiv_at f (f₀' a : E →L[𝕜] F) a) (hf : cont_diff 𝕜 n (f : E → F)) : cont_diff 𝕜 n (f.symm : F → E) := cont_diff_iff_cont_diff_at.2 $ λ x, f.to_local_homeomorph.cont_diff_at_symm (mem_univ x) (hf₀' _) hf.cont_diff_at /-- Let `f` be a local homeomorphism of a nondiscrete normed field, let `a` be a point in its target. if `f` is `n` times continuously differentiable at `f.symm a`, and if the derivative at `f.symm a` is nonzero, then `f.symm` is `n` times continuously differentiable at the point `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem local_homeomorph.cont_diff_at_symm_deriv [complete_space 𝕜] (f : local_homeomorph 𝕜 𝕜) {f₀' a : 𝕜} (h₀ : f₀' ≠ 0) (ha : a ∈ f.target) (hf₀' : has_deriv_at f f₀' (f.symm a)) (hf : cont_diff_at 𝕜 n f (f.symm a)) : cont_diff_at 𝕜 n f.symm a := f.cont_diff_at_symm ha (hf₀'.has_fderiv_at_equiv h₀) hf /-- Let `f` be an `n` times continuously differentiable homeomorphism of a nondiscrete normed field. Suppose that the derivative of `f` is never equal to zero. Then `f.symm` is `n` times continuously differentiable. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem homeomorph.cont_diff_symm_deriv [complete_space 𝕜] (f : 𝕜 ≃ₜ 𝕜) {f' : 𝕜 → 𝕜} (h₀ : ∀ x, f' x ≠ 0) (hf' : ∀ x, has_deriv_at f (f' x) x) (hf : cont_diff 𝕜 n (f : 𝕜 → 𝕜)) : cont_diff 𝕜 n (f.symm : 𝕜 → 𝕜) := cont_diff_iff_cont_diff_at.2 $ λ x, f.to_local_homeomorph.cont_diff_at_symm_deriv (h₀ _) (mem_univ x) (hf' _) hf.cont_diff_at end function_inverse /-! ### Finite dimensional results -/ section finite_dimensional open function finite_dimensional variables [complete_space 𝕜] /-- A family of continuous linear maps is `C^n` on `s` if all its applications are. -/ lemma cont_diff_on_clm_apply {n : with_top ℕ} {f : E → F →L[𝕜] G} {s : set E} [finite_dimensional 𝕜 F] : cont_diff_on 𝕜 n f s ↔ ∀ y, cont_diff_on 𝕜 n (λ x, f x y) s := begin refine ⟨λ h y, (continuous_linear_map.apply 𝕜 G y).cont_diff.comp_cont_diff_on h, λ h, _⟩, let d := finrank 𝕜 F, have hd : d = finrank 𝕜 (fin d → 𝕜) := (finrank_fin_fun 𝕜).symm, let e₁ := continuous_linear_equiv.of_finrank_eq hd, let e₂ := (e₁.arrow_congr (1 : G ≃L[𝕜] G)).trans (continuous_linear_equiv.pi_ring (fin d)), rw [← comp.left_id f, ← e₂.symm_comp_self], exact e₂.symm.cont_diff.comp_cont_diff_on (cont_diff_on_pi.mpr (λ i, h _)) end lemma cont_diff_clm_apply {n : with_top ℕ} {f : E → F →L[𝕜] G} [finite_dimensional 𝕜 F] : cont_diff 𝕜 n f ↔ ∀ y, cont_diff 𝕜 n (λ x, f x y) := by simp_rw [← cont_diff_on_univ, cont_diff_on_clm_apply] /-- This is a useful lemma to prove that a certain operation preserves functions being `C^n`. When you do induction on `n`, this gives a useful characterization of a function being `C^(n+1)`, assuming you have already computed the derivative. The advantage of this version over `cont_diff_succ_iff_fderiv` is that both occurences of `cont_diff` are for functions with the same domain and codomain (`E` and `F`). This is not the case for `cont_diff_succ_iff_fderiv`, which often requires an inconvenient need to generalize `F`, which results in universe issues (see the discussion in the section of `cont_diff.comp`). This lemma avoids these universe issues, but only applies for finite dimensional `E`. -/ lemma cont_diff_succ_iff_fderiv_apply [finite_dimensional 𝕜 E] {n : ℕ} {f : E → F} : cont_diff 𝕜 ((n + 1) : ℕ) f ↔ differentiable 𝕜 f ∧ ∀ y, cont_diff 𝕜 n (λ x, fderiv 𝕜 f x y) := by rw [cont_diff_succ_iff_fderiv, cont_diff_clm_apply] lemma cont_diff_on_succ_of_fderiv_apply [finite_dimensional 𝕜 E] {n : ℕ} {f : E → F} {s : set E} (hf : differentiable_on 𝕜 f s) (h : ∀ y, cont_diff_on 𝕜 n (λ x, fderiv_within 𝕜 f s x y) s) : cont_diff_on 𝕜 ((n + 1) : ℕ) f s := cont_diff_on_succ_of_fderiv_within hf $ cont_diff_on_clm_apply.mpr h lemma cont_diff_on_succ_iff_fderiv_apply [finite_dimensional 𝕜 E] {n : ℕ} {f : E → F} {s : set E} (hs : unique_diff_on 𝕜 s) : cont_diff_on 𝕜 ((n + 1) : ℕ) f s ↔ differentiable_on 𝕜 f s ∧ ∀ y, cont_diff_on 𝕜 n (λ x, fderiv_within 𝕜 f s x y) s := by rw [cont_diff_on_succ_iff_fderiv_within hs, cont_diff_on_clm_apply] end finite_dimensional section real /-! ### Results over `ℝ` or `ℂ` The results in this section rely on the Mean Value Theorem, and therefore hold only over `ℝ` (and its extension fields such as `ℂ`). -/ variables {𝕂 : Type*} [is_R_or_C 𝕂] {E' : Type*} [normed_group E'] [normed_space 𝕂 E'] {F' : Type*} [normed_group F'] [normed_space 𝕂 F'] /-- If a function has a Taylor series at order at least 1, then at points in the interior of the domain of definition, the term of order 1 of this series is a strict derivative of `f`. -/ lemma has_ftaylor_series_up_to_on.has_strict_fderiv_at {s : set E'} {f : E' → F'} {x : E'} {p : E' → formal_multilinear_series 𝕂 E' F'} (hf : has_ftaylor_series_up_to_on n f p s) (hn : 1 ≤ n) (hs : s ∈ 𝓝 x) : has_strict_fderiv_at f ((continuous_multilinear_curry_fin1 𝕂 E' F') (p x 1)) x := has_strict_fderiv_at_of_has_fderiv_at_of_continuous_at (hf.eventually_has_fderiv_at hn hs) $ (continuous_multilinear_curry_fin1 𝕂 E' F').continuous_at.comp $ (hf.cont 1 hn).continuous_at hs /-- If a function is `C^n` with `1 ≤ n` around a point, and its derivative at that point is given to us as `f'`, then `f'` is also a strict derivative. -/ lemma cont_diff_at.has_strict_fderiv_at' {f : E' → F'} {f' : E' →L[𝕂] F'} {x : E'} (hf : cont_diff_at 𝕂 n f x) (hf' : has_fderiv_at f f' x) (hn : 1 ≤ n) : has_strict_fderiv_at f f' x := begin rcases hf 1 hn with ⟨u, H, p, hp⟩, simp only [nhds_within_univ, mem_univ, insert_eq_of_mem] at H, have := hp.has_strict_fderiv_at le_rfl H, rwa hf'.unique this.has_fderiv_at end /-- If a function is `C^n` with `1 ≤ n` around a point, and its derivative at that point is given to us as `f'`, then `f'` is also a strict derivative. -/ lemma cont_diff_at.has_strict_deriv_at' {f : 𝕂 → F'} {f' : F'} {x : 𝕂} (hf : cont_diff_at 𝕂 n f x) (hf' : has_deriv_at f f' x) (hn : 1 ≤ n) : has_strict_deriv_at f f' x := hf.has_strict_fderiv_at' hf' hn /-- If a function is `C^n` with `1 ≤ n` around a point, then the derivative of `f` at this point is also a strict derivative. -/ lemma cont_diff_at.has_strict_fderiv_at {f : E' → F'} {x : E'} (hf : cont_diff_at 𝕂 n f x) (hn : 1 ≤ n) : has_strict_fderiv_at f (fderiv 𝕂 f x) x := hf.has_strict_fderiv_at' (hf.differentiable_at hn).has_fderiv_at hn /-- If a function is `C^n` with `1 ≤ n` around a point, then the derivative of `f` at this point is also a strict derivative. -/ lemma cont_diff_at.has_strict_deriv_at {f : 𝕂 → F'} {x : 𝕂} (hf : cont_diff_at 𝕂 n f x) (hn : 1 ≤ n) : has_strict_deriv_at f (deriv f x) x := (hf.has_strict_fderiv_at hn).has_strict_deriv_at /-- If a function is `C^n` with `1 ≤ n`, then the derivative of `f` is also a strict derivative. -/ lemma cont_diff.has_strict_fderiv_at {f : E' → F'} {x : E'} (hf : cont_diff 𝕂 n f) (hn : 1 ≤ n) : has_strict_fderiv_at f (fderiv 𝕂 f x) x := hf.cont_diff_at.has_strict_fderiv_at hn /-- If a function is `C^n` with `1 ≤ n`, then the derivative of `f` is also a strict derivative. -/ lemma cont_diff.has_strict_deriv_at {f : 𝕂 → F'} {x : 𝕂} (hf : cont_diff 𝕂 n f) (hn : 1 ≤ n) : has_strict_deriv_at f (deriv f x) x := hf.cont_diff_at.has_strict_deriv_at hn /-- If `f` has a formal Taylor series `p` up to order `1` on `{x} ∪ s`, where `s` is a convex set, and `∥p x 1∥₊ < K`, then `f` is `K`-Lipschitz in a neighborhood of `x` within `s`. -/ lemma has_ftaylor_series_up_to_on.exists_lipschitz_on_with_of_nnnorm_lt {E F : Type*} [normed_group E] [normed_space ℝ E] [normed_group F] [normed_space ℝ F] {f : E → F} {p : E → formal_multilinear_series ℝ E F} {s : set E} {x : E} (hf : has_ftaylor_series_up_to_on 1 f p (insert x s)) (hs : convex ℝ s) (K : ℝ≥0) (hK : ∥p x 1∥₊ < K) : ∃ t ∈ 𝓝[s] x, lipschitz_on_with K f t := begin set f' := λ y, continuous_multilinear_curry_fin1 ℝ E F (p y 1), have hder : ∀ y ∈ s, has_fderiv_within_at f (f' y) s y, from λ y hy, (hf.has_fderiv_within_at le_rfl (subset_insert x s hy)).mono (subset_insert x s), have hcont : continuous_within_at f' s x, from (continuous_multilinear_curry_fin1 ℝ E F).continuous_at.comp_continuous_within_at ((hf.cont _ le_rfl _ (mem_insert _ _)).mono (subset_insert x s)), replace hK : ∥f' x∥₊ < K, by simpa only [linear_isometry_equiv.nnnorm_map], exact hs.exists_nhds_within_lipschitz_on_with_of_has_fderiv_within_at_of_nnnorm_lt (eventually_nhds_within_iff.2 $ eventually_of_forall hder) hcont K hK end /-- If `f` has a formal Taylor series `p` up to order `1` on `{x} ∪ s`, where `s` is a convex set, then `f` is Lipschitz in a neighborhood of `x` within `s`. -/ lemma has_ftaylor_series_up_to_on.exists_lipschitz_on_with {E F : Type*} [normed_group E] [normed_space ℝ E] [normed_group F] [normed_space ℝ F] {f : E → F} {p : E → formal_multilinear_series ℝ E F} {s : set E} {x : E} (hf : has_ftaylor_series_up_to_on 1 f p (insert x s)) (hs : convex ℝ s) : ∃ K (t ∈ 𝓝[s] x), lipschitz_on_with K f t := (exists_gt _).imp $ hf.exists_lipschitz_on_with_of_nnnorm_lt hs /-- If `f` is `C^1` within a conves set `s` at `x`, then it is Lipschitz on a neighborhood of `x` within `s`. -/ lemma cont_diff_within_at.exists_lipschitz_on_with {E F : Type*} [normed_group E] [normed_space ℝ E] [normed_group F] [normed_space ℝ F] {f : E → F} {s : set E} {x : E} (hf : cont_diff_within_at ℝ 1 f s x) (hs : convex ℝ s) : ∃ (K : ℝ≥0) (t ∈ 𝓝[s] x), lipschitz_on_with K f t := begin rcases hf 1 le_rfl with ⟨t, hst, p, hp⟩, rcases metric.mem_nhds_within_iff.mp hst with ⟨ε, ε0, hε⟩, replace hp : has_ftaylor_series_up_to_on 1 f p (metric.ball x ε ∩ insert x s) := hp.mono hε, clear hst hε t, rw [← insert_eq_of_mem (metric.mem_ball_self ε0), ← insert_inter_distrib] at hp, rcases hp.exists_lipschitz_on_with ((convex_ball _ _).inter hs) with ⟨K, t, hst, hft⟩, rw [inter_comm, ← nhds_within_restrict' _ (metric.ball_mem_nhds _ ε0)] at hst, exact ⟨K, t, hst, hft⟩ end /-- If `f` is `C^1` at `x` and `K > ∥fderiv 𝕂 f x∥`, then `f` is `K`-Lipschitz in a neighborhood of `x`. -/ lemma cont_diff_at.exists_lipschitz_on_with_of_nnnorm_lt {f : E' → F'} {x : E'} (hf : cont_diff_at 𝕂 1 f x) (K : ℝ≥0) (hK : ∥fderiv 𝕂 f x∥₊ < K) : ∃ t ∈ 𝓝 x, lipschitz_on_with K f t := (hf.has_strict_fderiv_at le_rfl).exists_lipschitz_on_with_of_nnnorm_lt K hK /-- If `f` is `C^1` at `x`, then `f` is Lipschitz in a neighborhood of `x`. -/ lemma cont_diff_at.exists_lipschitz_on_with {f : E' → F'} {x : E'} (hf : cont_diff_at 𝕂 1 f x) : ∃ K (t ∈ 𝓝 x), lipschitz_on_with K f t := (hf.has_strict_fderiv_at le_rfl).exists_lipschitz_on_with end real section deriv /-! ### One dimension All results up to now have been expressed in terms of the general Fréchet derivative `fderiv`. For maps defined on the field, the one-dimensional derivative `deriv` is often easier to use. In this paragraph, we reformulate some higher smoothness results in terms of `deriv`. -/ variables {f₂ : 𝕜 → F} {s₂ : set 𝕜} open continuous_linear_map (smul_right) /-- A function is `C^(n + 1)` on a domain with unique derivatives if and only if it is differentiable there, and its derivative (formulated with `deriv_within`) is `C^n`. -/ theorem cont_diff_on_succ_iff_deriv_within {n : ℕ} (hs : unique_diff_on 𝕜 s₂) : cont_diff_on 𝕜 ((n + 1) : ℕ) f₂ s₂ ↔ differentiable_on 𝕜 f₂ s₂ ∧ cont_diff_on 𝕜 n (deriv_within f₂ s₂) s₂ := begin rw cont_diff_on_succ_iff_fderiv_within hs, congr' 2, apply le_antisymm, { assume h, have : deriv_within f₂ s₂ = (λ u : 𝕜 →L[𝕜] F, u 1) ∘ (fderiv_within 𝕜 f₂ s₂), by { ext x, refl }, simp only [this], apply cont_diff.comp_cont_diff_on _ h, exact (is_bounded_bilinear_map_apply.is_bounded_linear_map_left _).cont_diff }, { assume h, have : fderiv_within 𝕜 f₂ s₂ = smul_right (1 : 𝕜 →L[𝕜] 𝕜) ∘ deriv_within f₂ s₂, by { ext x, simp [deriv_within] }, simp only [this], apply cont_diff.comp_cont_diff_on _ h, have : is_bounded_bilinear_map 𝕜 (λ _ : (𝕜 →L[𝕜] 𝕜) × F, _) := is_bounded_bilinear_map_smul_right, exact (this.is_bounded_linear_map_right _).cont_diff } end /-- A function is `C^(n + 1)` on an open domain if and only if it is differentiable there, and its derivative (formulated with `deriv`) is `C^n`. -/ theorem cont_diff_on_succ_iff_deriv_of_open {n : ℕ} (hs : is_open s₂) : cont_diff_on 𝕜 ((n + 1) : ℕ) f₂ s₂ ↔ differentiable_on 𝕜 f₂ s₂ ∧ cont_diff_on 𝕜 n (deriv f₂) s₂ := begin rw cont_diff_on_succ_iff_deriv_within hs.unique_diff_on, congrm _ ∧ _, apply cont_diff_on_congr, assume x hx, exact deriv_within_of_open hs hx end /-- A function is `C^∞` on a domain with unique derivatives if and only if it is differentiable there, and its derivative (formulated with `deriv_within`) is `C^∞`. -/ theorem cont_diff_on_top_iff_deriv_within (hs : unique_diff_on 𝕜 s₂) : cont_diff_on 𝕜 ∞ f₂ s₂ ↔ differentiable_on 𝕜 f₂ s₂ ∧ cont_diff_on 𝕜 ∞ (deriv_within f₂ s₂) s₂ := begin split, { assume h, refine ⟨h.differentiable_on le_top, _⟩, apply cont_diff_on_top.2 (λ n, ((cont_diff_on_succ_iff_deriv_within hs).1 _).2), exact h.of_le le_top }, { assume h, refine cont_diff_on_top.2 (λ n, _), have A : (n : with_top ℕ) ≤ ∞ := le_top, apply ((cont_diff_on_succ_iff_deriv_within hs).2 ⟨h.1, h.2.of_le A⟩).of_le, exact with_top.coe_le_coe.2 (nat.le_succ n) } end /-- A function is `C^∞` on an open domain if and only if it is differentiable there, and its derivative (formulated with `deriv`) is `C^∞`. -/ theorem cont_diff_on_top_iff_deriv_of_open (hs : is_open s₂) : cont_diff_on 𝕜 ∞ f₂ s₂ ↔ differentiable_on 𝕜 f₂ s₂ ∧ cont_diff_on 𝕜 ∞ (deriv f₂) s₂ := begin rw cont_diff_on_top_iff_deriv_within hs.unique_diff_on, congrm _ ∧ _, apply cont_diff_on_congr, assume x hx, exact deriv_within_of_open hs hx end lemma cont_diff_on.deriv_within (hf : cont_diff_on 𝕜 n f₂ s₂) (hs : unique_diff_on 𝕜 s₂) (hmn : m + 1 ≤ n) : cont_diff_on 𝕜 m (deriv_within f₂ s₂) s₂ := begin cases m, { change ∞ + 1 ≤ n at hmn, have : n = ∞, by simpa using hmn, rw this at hf, exact ((cont_diff_on_top_iff_deriv_within hs).1 hf).2 }, { change (m.succ : with_top ℕ) ≤ n at hmn, exact ((cont_diff_on_succ_iff_deriv_within hs).1 (hf.of_le hmn)).2 } end lemma cont_diff_on.deriv_of_open (hf : cont_diff_on 𝕜 n f₂ s₂) (hs : is_open s₂) (hmn : m + 1 ≤ n) : cont_diff_on 𝕜 m (deriv f₂) s₂ := (hf.deriv_within hs.unique_diff_on hmn).congr (λ x hx, (deriv_within_of_open hs hx).symm) lemma cont_diff_on.continuous_on_deriv_within (h : cont_diff_on 𝕜 n f₂ s₂) (hs : unique_diff_on 𝕜 s₂) (hn : 1 ≤ n) : continuous_on (deriv_within f₂ s₂) s₂ := ((cont_diff_on_succ_iff_deriv_within hs).1 (h.of_le hn)).2.continuous_on lemma cont_diff_on.continuous_on_deriv_of_open (h : cont_diff_on 𝕜 n f₂ s₂) (hs : is_open s₂) (hn : 1 ≤ n) : continuous_on (deriv f₂) s₂ := ((cont_diff_on_succ_iff_deriv_of_open hs).1 (h.of_le hn)).2.continuous_on /-- A function is `C^(n + 1)` if and only if it is differentiable, and its derivative (formulated in terms of `deriv`) is `C^n`. -/ theorem cont_diff_succ_iff_deriv {n : ℕ} : cont_diff 𝕜 ((n + 1) : ℕ) f₂ ↔ differentiable 𝕜 f₂ ∧ cont_diff 𝕜 n (deriv f₂) := by simp only [← cont_diff_on_univ, cont_diff_on_succ_iff_deriv_of_open, is_open_univ, differentiable_on_univ] theorem cont_diff_one_iff_deriv : cont_diff 𝕜 1 f₂ ↔ differentiable 𝕜 f₂ ∧ continuous (deriv f₂) := cont_diff_succ_iff_deriv.trans $ iff.rfl.and cont_diff_zero /-- A function is `C^∞` if and only if it is differentiable, and its derivative (formulated in terms of `deriv`) is `C^∞`. -/ theorem cont_diff_top_iff_deriv : cont_diff 𝕜 ∞ f₂ ↔ differentiable 𝕜 f₂ ∧ cont_diff 𝕜 ∞ (deriv f₂) := begin simp [cont_diff_on_univ.symm, differentiable_on_univ.symm, deriv_within_univ.symm, - deriv_within_univ], rw cont_diff_on_top_iff_deriv_within unique_diff_on_univ, end lemma cont_diff.continuous_deriv (h : cont_diff 𝕜 n f₂) (hn : 1 ≤ n) : continuous (deriv f₂) := (cont_diff_succ_iff_deriv.mp (h.of_le hn)).2.continuous end deriv section restrict_scalars /-! ### Restricting from `ℂ` to `ℝ`, or generally from `𝕜'` to `𝕜` If a function is `n` times continuously differentiable over `ℂ`, then it is `n` times continuously differentiable over `ℝ`. In this paragraph, we give variants of this statement, in the general situation where `ℂ` and `ℝ` are replaced respectively by `𝕜'` and `𝕜` where `𝕜'` is a normed algebra over `𝕜`. -/ variables (𝕜) {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] variables [normed_space 𝕜' E] [is_scalar_tower 𝕜 𝕜' E] variables [normed_space 𝕜' F] [is_scalar_tower 𝕜 𝕜' F] variables {p' : E → formal_multilinear_series 𝕜' E F} lemma has_ftaylor_series_up_to_on.restrict_scalars (h : has_ftaylor_series_up_to_on n f p' s) : has_ftaylor_series_up_to_on n f (λ x, (p' x).restrict_scalars 𝕜) s := { zero_eq := λ x hx, h.zero_eq x hx, fderiv_within := begin intros m hm x hx, convert ((continuous_multilinear_map.restrict_scalars_linear 𝕜).has_fderiv_at) .comp_has_fderiv_within_at _ ((h.fderiv_within m hm x hx).restrict_scalars 𝕜), end, cont := λ m hm, continuous_multilinear_map.continuous_restrict_scalars.comp_continuous_on (h.cont m hm) } lemma cont_diff_within_at.restrict_scalars (h : cont_diff_within_at 𝕜' n f s x) : cont_diff_within_at 𝕜 n f s x := begin intros m hm, rcases h m hm with ⟨u, u_mem, p', hp'⟩, exact ⟨u, u_mem, _, hp'.restrict_scalars _⟩ end lemma cont_diff_on.restrict_scalars (h : cont_diff_on 𝕜' n f s) : cont_diff_on 𝕜 n f s := λ x hx, (h x hx).restrict_scalars _ lemma cont_diff_at.restrict_scalars (h : cont_diff_at 𝕜' n f x) : cont_diff_at 𝕜 n f x := cont_diff_within_at_univ.1 $ h.cont_diff_within_at.restrict_scalars _ lemma cont_diff.restrict_scalars (h : cont_diff 𝕜' n f) : cont_diff 𝕜 n f := cont_diff_iff_cont_diff_at.2 $ λ x, h.cont_diff_at.restrict_scalars _ end restrict_scalars
dc267daa6fd9148ce414dabd81dbb6d136c49259
f09e92753b1d3d2eb3ce2cfb5288a7f5d1d4bd89
/src/adic_space.lean
12801ed63e4affb4567f4ea9e15f532ef060d446
[ "Apache-2.0" ]
permissive
PatrickMassot/lean-perfectoid-spaces
7f63c581db26461b5a92d968e7563247e96a5597
5f70b2020b3c6d508431192b18457fa988afa50d
refs/heads/master
1,625,797,721,782
1,547,308,357,000
1,547,309,364,000
136,658,414
0
1
Apache-2.0
1,528,486,100,000
1,528,486,100,000
null
UTF-8
Lean
false
false
2,259
lean
import for_mathlib.prime import for_mathlib.is_cover import analysis.topology.topological_structures import data.nat.prime import algebra.group_power -- import for_mathlib.presheaves import for_mathlib.topology import continuous_valuations import Spa import Huber_pair universe u open nat function --definition 𝓞_X (A : Huber_pair) : presheaf_of_rings (Spa A) := sorry -- it's a presheaf of complete topological rings on all opens (defined on rational opens -- first and then extended to all via proj limits) -- Wedhorn p75 -- most of that would not be in the adic_space file. --structure 𝓥pre := --(X : sorry) --(𝓞X : sorry) --(v : sorry) /- We denote by 𝓥pre the category of tuples X = (X, O X , (v x ) x∈X ), where (a) X is a topological space, (b) 𝓞_X is a presheaf of complete topological rings on X such that the stalk 𝓞_X,x of 𝓞_X (considered as a presheaf of rings) is a local ring, (c) v_x is an equivalence class of valuations on the stalk 𝓞_X,x such that supp(v_x) is the maximal ideal of 𝓞_X,x . Wedhorn p76 shows how Spa(A) gives an object of this for A a Huber pair -/ --definition affinoid_adic_space (A : Huber_pair) : 𝓥pre := sorry -- unwritten -- it's a full subcat of 𝓥pre class preadic_space (X : Type) extends topological_space X -- not logically necessary but should be easy instance (A : Huber_pair) : preadic_space (Spa A) := sorry -- attribute [class] _root_.is_open instance preadic_space_restriction {X : Type} [preadic_space X] {U : opens X} : preadic_space U := sorry -- unwritten class adic_space (X : Type) extends preadic_space X -- a preadic_space_equiv is just an isom in 𝓥pre, or an isomorphism of preadic spaces. -- is homeo in Lean yet? -- unwritten structure preadic_space_equiv (X Y : Type) [AX : preadic_space X] [AY : preadic_space Y] extends equiv X Y definition is_preadic_space_equiv (X Y : Type) [AX : preadic_space X] [AY : preadic_space Y] := nonempty (preadic_space_equiv X Y) definition preadic_space_pullback {X : Type} [preadic_space X] (U : set X) := {x : X // x ∈ U} instance pullback_is_preadic_space {X : Type} [preadic_space X] (U : set X) : preadic_space (preadic_space_pullback U) := sorry -- notation `is_open` := _root_.is_open
9509459345e6719744a372733b0df22ed266a949
98000ddc36f1ec26addea0df1853c69fa0e71d67
/segment.lean
f716d6793846b56c259890db6d251872ce53179d
[]
no_license
SCRK16/Intuitionism
50b7b5ed780a75c4ff1339c3d36f1133b8acdfe3
a3d9920ae056b39a66e37d1d0e03d246bca1e961
refs/heads/master
1,670,199,869,808
1,598,045,061,000
1,598,045,061,000
254,657,585
1
0
null
1,590,754,909,000
1,586,529,604,000
Lean
UTF-8
Lean
false
false
5,464
lean
/- This file defines rational segments 𝕊, here defined as a subtype of ℚ × ℚ Also defines relations on 𝕊, like ≤, ⊑ and ≈ -/ import data.rat import algebra.order /-- Rational segments 𝕊 Each s in 𝕊 is a pair of rational numbers (p, q) such that p ≤ q Rational segments can be interpreted as intervals, [p, q], with rational end points -/ def segment := {s : ℚ × ℚ // s.fst ≤ s.snd} notation `𝕊` := segment namespace segment def fst (s : 𝕊) : ℚ := (subtype.val s).fst def snd (s : 𝕊) : ℚ := (subtype.val s).snd def proper (s : 𝕊) : Prop := s.fst < s.snd def contained (s t : 𝕊) : Prop := t.fst ≤ s.fst ∧ s.snd ≤ t.snd infix `⊑`:50 := contained def proper_contained (s t : 𝕊) : Prop := t.fst < s.fst ∧ s.snd < t.snd infix `⊏`:50 := proper_contained def lt (s t : 𝕊) : Prop := s.snd < t.fst infix `<` := lt def le (s t : 𝕊) : Prop := s.fst ≤ t.snd infix `≤` := le def inclusion (q : ℚ) : 𝕊 := subtype.mk (q, q) begin refl, end @[instance] def has_zero : has_zero 𝕊 := { zero := inclusion 0 } def two_sided_inclusion (q : ℚ) (hq : q > 0) : 𝕊 := subtype.mk (-q, q) begin simp, rwa [neg_le_iff_add_nonneg, ← two_mul], apply rat.mul_nonneg, {-- need to prove: 0 ≤ 2 exact rat.le_def'.mpr trivial }, {-- need to prove: 0 ≤ q apply le_of_lt, rw ← gt_from_lt, exact hq, } end lemma two_sided_inclusion_contained {q₁ q₂ : ℚ} {hq₁ : q₁ > 0} {hq₂ : q₂ > 0} (h : q₁ ≤ q₂) : two_sided_inclusion q₁ hq₁ ⊑ two_sided_inclusion q₂ hq₂ := begin simp [two_sided_inclusion, contained, fst, snd, h], end @[trans] theorem contained_trans (s t v : 𝕊) (h₁ : s ⊑ t) (h₂ : t ⊑ v) : s ⊑ v := begin split, {-- need to prove: fst v ≤ fst s transitivity t.fst, exact h₂.elim_left, exact h₁.elim_left, }, {-- need to prove: snd s ≤ snd v transitivity t.snd, exact h₁.elim_right, exact h₂.elim_right, } end @[trans] theorem proper_contained_trans (s t v : 𝕊) (h₁ : s ⊏ t) (h₂ : t ⊏ v) : s ⊏ v := begin split, {-- need to prove: fst v < fst s transitivity t.fst, exact h₂.elim_left, exact h₁.elim_left, }, {-- need to prove: snd s < snd v transitivity t.snd, exact h₁.elim_right, exact h₂.elim_right, } end @[refl] theorem contained_refl (s : 𝕊) : s ⊑ s := begin split, refl, refl, end -- This lemma immediately follows from a similar statement about ℚ lemma le_iff_not_lt (s t : 𝕊) : s ≤ t ↔ ¬ t < s := begin split, {-- need to prove: s ≤ t → ¬ t < s intro h, apply not_lt_of_le, exact h, }, {-- need to prove: ¬ t < s → s ≤ t intro h, apply le_of_not_lt, exact h, } end lemma lt_iff_not_le (s t : 𝕊) : s < t ↔ ¬ t ≤ s := begin split, {-- need to prove: s < t → ¬ t ≤ s intro h, apply not_le_of_lt, exact h, }, {-- need to prove: ¬ t ≤ s → s < t intro h, apply lt_of_not_ge, rw ge_iff_le, exact h, } end @[trans] theorem lt_trans (s t v : 𝕊) (h₁ : s < t) (h₂ : t < v) : s < v := begin have ht := subtype.property t, have h₃ : s.snd < t.snd := lt_of_lt_of_le h₁ ht, rw segment.lt, transitivity t.snd, exact h₃, exact h₂, end @[refl] theorem le_refl (s : 𝕊) : s ≤ s := begin exact (subtype.property s), end /-- We say that two rational segments 'touch' if they partially cover eachother -/ def touches (s t : 𝕊) : Prop := s ≤ t ∧ t ≤ s infix `≈` := touches @[refl] theorem touches_refl (s : 𝕊) : s ≈ s := begin split, refl, refl, end @[symm] theorem touches_symm (s t : 𝕊) : s ≈ t ↔ t ≈ s := begin exact and.comm, end def add (s t : 𝕊) : 𝕊 := subtype.mk (s.fst + t.fst, s.snd + t.snd) begin apply add_le_add, exact subtype.property s, exact subtype.property t, end theorem add_assoc (s t v : 𝕊) : add (add s t) v = add s (add t v) := begin repeat {rw add}, rw subtype.mk_eq_mk, rw prod.mk.inj_iff, split, { repeat {rw fst}, rw add_assoc, rw add_left_inj, refl, }, { repeat {rw snd}, rw add_assoc, rw add_left_inj, refl, } end lemma fst_add_comm {s t : 𝕊} : fst (add s t) = fst s + fst t := rfl lemma snd_add_comm {s t : 𝕊} : snd (add s t) = snd s + snd t := rfl theorem add_comm (s t : 𝕊) : add s t = add t s := begin apply subtype.eq, simp [add], split, exact rat.add_comm (fst s) (fst t), exact rat.add_comm (snd s) (snd t), end -- We use this lemma in proving that addition on ℛ is well-defined lemma contained_bounds_le (s t : 𝕊) (h : s ⊑ t) : s.snd - s.fst ≤ t.snd - t.fst := begin apply sub_le_sub, exact h.elim_right, exact h.elim_left, end instance : add_comm_semigroup 𝕊 := { add := segment.add, add_assoc := segment.add_assoc, add_comm := segment.add_comm, } def neg (s : 𝕊) : 𝕊 := subtype.mk (-s.snd, -s.fst) begin simp, exact subtype.property s, end end segment
93fb96b7ab9826622db376d643c09b02ba2d0f19
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/data/real/irrational.lean
23006dd7830d70ba5454ba3b8509c8aaa7d3bab3
[ "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
8,231
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Yury Kudryashov. -/ import data.real.basic algebra.gcd_domain ring_theory.multiplicity tactic.alias /-! # Irrational real numbers In this file we define a predicate `irrational` on `ℝ`, prove that the `n`-th root of an integer number is irrational if it is not integer, and that `sqrt q` is irrational if and only if `rat.sqrt q * rat.sqrt q ≠ q ∧ 0 ≤ q`. We also provide dot-style constructors like `irrational.add_rat`, `irrational.rat_sub` etc. -/ open rat real multiplicity /-- A real number is irrational if it is not equal to any rational number. -/ def irrational (x : ℝ) := x ∉ set.range (coe : ℚ → ℝ) /-! ### Irrationality of roots of integer and rational numbers -/ /-- If `x^n`, `n > 0`, is integer and is not the `n`-th power of an integer, then `x` is irrational. -/ theorem irrational_nrt_of_notint_nrt {x : ℝ} (n : ℕ) (m : ℤ) (hxr : x ^ n = m) (hv : ¬ ∃ y : ℤ, x = y) (hnpos : 0 < n) : irrational x := begin rintros ⟨⟨N, D, P, C⟩, rfl⟩, rw [← cast_pow] at hxr, have c1 : ((D : ℤ) : ℝ) ≠ 0, { rw [int.cast_ne_zero, int.coe_nat_ne_zero], exact ne_of_gt P }, have c2 : ((D : ℤ) : ℝ) ^ n ≠ 0 := pow_ne_zero _ c1, rw [num_denom', cast_pow, cast_mk, div_pow, div_eq_iff_mul_eq c2, ← int.cast_pow, ← int.cast_pow, ← int.cast_mul, int.cast_inj] at hxr, have hdivn : ↑D ^ n ∣ N ^ n := dvd.intro_left m hxr, rw [← int.dvd_nat_abs, ← int.coe_nat_pow, int.coe_nat_dvd, int.nat_abs_pow, nat.pow_dvd_pow_iff hnpos] at hdivn, have hD : D = 1 := by rw [← nat.gcd_eq_right hdivn, C.gcd_eq_one], subst D, refine hv ⟨N, _⟩, rw [num_denom', int.coe_nat_one, mk_eq_div, int.cast_one, div_one, cast_coe_int] end /-- If `x^n = m` is an integer and `n` does not divide the `multiplicity p m`, then `x` is irrational. -/ theorem irrational_nrt_of_n_not_dvd_multiplicity {x : ℝ} (n : ℕ) {m : ℤ} (hm : m ≠ 0) (p : ℕ) [hp : nat.prime p] (hxr : x ^ n = m) (hv : (multiplicity (p : ℤ) m).get (finite_int_iff.2 ⟨hp.ne_one, hm⟩) % n ≠ 0) : irrational x := begin rcases nat.eq_zero_or_pos n with rfl | hnpos, { rw [eq_comm, pow_zero, ← int.cast_one, int.cast_inj] at hxr, simpa [hxr, multiplicity.one_right (mt is_unit_iff_dvd_one.1 (mt int.coe_nat_dvd.1 hp.not_dvd_one)), nat.zero_mod] using hv }, refine irrational_nrt_of_notint_nrt _ _ hxr _ hnpos, rintro ⟨y, rfl⟩, rw [← int.cast_pow, int.cast_inj] at hxr, subst m, have : y ≠ 0, { rintro rfl, rw zero_pow hnpos at hm, exact hm rfl }, erw [multiplicity.pow' (nat.prime_iff_prime_int.1 hp) (finite_int_iff.2 ⟨hp.ne_one, this⟩), nat.mul_mod_right] at hv, exact hv rfl end theorem irrational_sqrt_of_multiplicity_odd (m : ℤ) (hm : 0 < m) (p : ℕ) [hp : nat.prime p] (Hpv : (multiplicity (p : ℤ) m).get (finite_int_iff.2 ⟨hp.ne_one, (ne_of_lt hm).symm⟩) % 2 = 1) : irrational (sqrt m) := @irrational_nrt_of_n_not_dvd_multiplicity _ 2 _ (ne.symm (ne_of_lt hm)) p hp (sqr_sqrt (int.cast_nonneg.2 $ le_of_lt hm)) (by rw Hpv; exact one_ne_zero) theorem nat.prime.irrational_sqrt {p : ℕ} (hp : nat.prime p) : irrational (sqrt p) := @irrational_sqrt_of_multiplicity_odd p (int.coe_nat_pos.2 hp.pos) p hp $ by simp [multiplicity_self (mt is_unit_iff_dvd_one.1 (mt int.coe_nat_dvd.1 hp.not_dvd_one) : _)]; refl theorem irrational_sqrt_two : irrational (sqrt 2) := by simpa using nat.prime_two.irrational_sqrt theorem irrational_sqrt_rat_iff (q : ℚ) : irrational (sqrt q) ↔ rat.sqrt q * rat.sqrt q ≠ q ∧ 0 ≤ q := if H1 : rat.sqrt q * rat.sqrt q = q then iff_of_false (not_not_intro ⟨rat.sqrt q, by rw [← H1, cast_mul, sqrt_mul_self (cast_nonneg.2 $ rat.sqrt_nonneg q), sqrt_eq, abs_of_nonneg (rat.sqrt_nonneg q)]⟩) (λ h, h.1 H1) else if H2 : 0 ≤ q then iff_of_true (λ ⟨r, hr⟩, H1 $ (exists_mul_self _).1 ⟨r, by rwa [eq_comm, sqrt_eq_iff_mul_self_eq (cast_nonneg.2 H2), ← cast_mul, cast_inj] at hr; rw [← hr]; exact real.sqrt_nonneg _⟩) ⟨H1, H2⟩ else iff_of_false (not_not_intro ⟨0, by rw cast_zero; exact (sqrt_eq_zero_of_nonpos (rat.cast_nonpos.2 $ le_of_not_le H2)).symm⟩) (λ h, H2 h.2) instance (q : ℚ) : decidable (irrational (sqrt q)) := decidable_of_iff' _ (irrational_sqrt_rat_iff q) /-! ### Adding/subtracting/multiplying by rational numbers -/ lemma rat.not_irrational (q : ℚ) : ¬irrational q := λ h, h ⟨q, rfl⟩ namespace irrational variables (q : ℚ) {x y : ℝ} open_locale classical theorem add_cases : irrational (x + y) → irrational x ∨ irrational y := begin delta irrational, contrapose!, rintros ⟨⟨rx, rfl⟩, ⟨ry, rfl⟩⟩, exact ⟨rx + ry, cast_add rx ry⟩ end theorem of_rat_add (h : irrational (q + x)) : irrational x := h.add_cases.elim (λ h, absurd h q.not_irrational) id theorem rat_add (h : irrational x) : irrational (q + x) := of_rat_add (-q) $ by rwa [cast_neg, neg_add_cancel_left] theorem of_add_rat : irrational (x + q) → irrational x := add_comm ↑q x ▸ of_rat_add q theorem add_rat (h : irrational x) : irrational (x + q) := add_comm ↑q x ▸ h.rat_add q theorem of_neg (h : irrational (-x)) : irrational x := λ ⟨q, hx⟩, h ⟨-q, by rw [cast_neg, hx]⟩ protected theorem neg (h : irrational x) : irrational (-x) := of_neg $ by rwa neg_neg theorem sub_rat (h : irrational x) : irrational (x - q) := by simpa only [cast_neg] using h.add_rat (-q) theorem rat_sub (h : irrational x) : irrational (q - x) := h.neg.rat_add q theorem of_sub_rat (h : irrational (x - q)) : irrational x := of_add_rat (-q) $ by simpa only [cast_neg] theorem of_rat_sub (h : irrational (q - x)) : irrational x := (h.of_rat_add _).of_neg theorem mul_cases : irrational (x * y) → irrational x ∨ irrational y := begin delta irrational, contrapose!, rintros ⟨⟨rx, rfl⟩, ⟨ry, rfl⟩⟩, exact ⟨rx * ry, cast_mul rx ry⟩ end theorem of_mul_rat (h : irrational (x * q)) : irrational x := h.mul_cases.elim id (λ h, absurd h q.not_irrational) theorem mul_rat (h : irrational x) {q : ℚ} (hq : q ≠ 0) : irrational (x * q) := of_mul_rat q⁻¹ $ by rwa [mul_assoc, ← cast_mul, mul_inv_cancel hq, cast_one, mul_one] theorem of_rat_mul : irrational (q * x) → irrational x := mul_comm x q ▸ of_mul_rat q theorem rat_mul (h : irrational x) {q : ℚ} (hq : q ≠ 0) : irrational (q * x) := mul_comm x q ▸ h.mul_rat hq theorem of_mul_self (h : irrational (x * x)) : irrational x := h.mul_cases.elim id id theorem of_inv (h : irrational x⁻¹) : irrational x := λ ⟨q, hq⟩, h $ hq ▸ ⟨q⁻¹, q.cast_inv⟩ protected theorem inv (h : irrational x) : irrational x⁻¹ := of_inv $ by rwa inv_inv' theorem div_cases (h : irrational (x / y)) : irrational x ∨ irrational y := h.mul_cases.imp id of_inv theorem of_rat_div (h : irrational (q / x)) : irrational x := (h.of_rat_mul q).of_inv theorem of_one_div (h : irrational (1 / x)) : irrational x := of_rat_div 1 $ by rwa [cast_one] theorem of_pow : ∀ n : ℕ, irrational (x^n) → irrational x | 0 := λ h, (h ⟨1, cast_one⟩).elim | (n+1) := λ h, h.mul_cases.elim id (of_pow n) theorem of_fpow : ∀ m : ℤ, irrational (x^m) → irrational x | (n:ℕ) := of_pow n | -[1+n] := λ h, by { rw fpow_neg_succ_of_nat at h, exact h.of_inv.of_pow _ } end irrational section variables {q : ℚ} {x : ℝ} open irrational @[simp] theorem irrational_rat_add_iff : irrational (q + x) ↔ irrational x := ⟨of_rat_add q, rat_add q⟩ @[simp] theorem irrational_add_rat_iff : irrational (x + q) ↔ irrational x := ⟨of_add_rat q, add_rat q⟩ @[simp] theorem irrational_rat_sub_iff : irrational (q - x) ↔ irrational x := ⟨of_rat_sub q, rat_sub q⟩ @[simp] theorem irrational_sub_rat_iff : irrational (x - q) ↔ irrational x := ⟨of_sub_rat q, sub_rat q⟩ @[simp] theorem irrational_neg_iff : irrational (-x) ↔ irrational x := ⟨of_neg, irrational.neg⟩ @[simp] theorem irrational_inv_iff : irrational x⁻¹ ↔ irrational x := ⟨of_inv, irrational.inv⟩ end
b556605575d3c6dd2294b95f5421b3deda19efe3
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/polynomial/chebyshev.lean
568cf21e85310cbc913c8ef0d2c36b8164f90bb1
[ "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
10,818
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Julian Kuelshammer, Heather Macbeth -/ import data.polynomial.derivative import tactic.linear_combination /-! # Chebyshev polynomials The Chebyshev polynomials are two families of polynomials indexed by `ℕ`, with integral coefficients. ## Main definitions * `polynomial.chebyshev.T`: the Chebyshev polynomials of the first kind. * `polynomial.chebyshev.U`: the Chebyshev polynomials of the second kind. ## Main statements * The formal derivative of the Chebyshev polynomials of the first kind is a scalar multiple of the Chebyshev polynomials of the second kind. * `polynomial.chebyshev.mul_T`, the product of the `m`-th and `(m + k)`-th Chebyshev polynomials of the first kind is the sum of the `(2 * m + k)`-th and `k`-th Chebyshev polynomials of the first kind. * `polynomial.chebyshev.T_mul`, the `(m * n)`-th Chebyshev polynomial of the first kind is the composition of the `m`-th and `n`-th Chebyshev polynomials of the first kind. ## Implementation details Since Chebyshev polynomials have interesting behaviour over the complex numbers and modulo `p`, we define them to have coefficients in an arbitrary commutative ring, even though technically `ℤ` would suffice. The benefit of allowing arbitrary coefficient rings, is that the statements afterwards are clean, and do not have `map (int.cast_ring_hom R)` interfering all the time. ## References [Lionel Ponton, _Roots of the Chebyshev polynomials: A purely algebraic approach_] [ponton2020chebyshev] ## TODO * Redefine and/or relate the definition of Chebyshev polynomials to `linear_recurrence`. * Add explicit formula involving square roots for Chebyshev polynomials * Compute zeroes and extrema of Chebyshev polynomials. * Prove that the roots of the Chebyshev polynomials (except 0) are irrational. * Prove minimax properties of Chebyshev polynomials. -/ noncomputable theory namespace polynomial.chebyshev open polynomial open_locale polynomial variables (R S : Type*) [comm_ring R] [comm_ring S] /-- `T n` is the `n`-th Chebyshev polynomial of the first kind -/ noncomputable def T : ℕ → R[X] | 0 := 1 | 1 := X | (n + 2) := 2 * X * T (n + 1) - T n @[simp] lemma T_zero : T R 0 = 1 := rfl @[simp] lemma T_one : T R 1 = X := rfl @[simp] lemma T_add_two (n : ℕ) : T R (n + 2) = 2 * X * T R (n + 1) - T R n := by rw T lemma T_two : T R 2 = 2 * X ^ 2 - 1 := by simp only [T, sub_left_inj, sq, mul_assoc] lemma T_of_two_le (n : ℕ) (h : 2 ≤ n) : T R n = 2 * X * T R (n - 1) - T R (n - 2) := begin obtain ⟨n, rfl⟩ := nat.exists_eq_add_of_le h, rw add_comm, exact T_add_two R n end /-- `U n` is the `n`-th Chebyshev polynomial of the second kind -/ noncomputable def U : ℕ → R[X] | 0 := 1 | 1 := 2 * X | (n + 2) := 2 * X * U (n + 1) - U n @[simp] lemma U_zero : U R 0 = 1 := rfl @[simp] lemma U_one : U R 1 = 2 * X := rfl @[simp] lemma U_add_two (n : ℕ) : U R (n + 2) = 2 * X * U R (n + 1) - U R n := by rw U lemma U_two : U R 2 = 4 * X ^ 2 - 1 := by { simp only [U], ring, } lemma U_of_two_le (n : ℕ) (h : 2 ≤ n) : U R n = 2 * X * U R (n - 1) - U R (n - 2) := begin obtain ⟨n, rfl⟩ := nat.exists_eq_add_of_le h, rw add_comm, exact U_add_two R n end lemma U_eq_X_mul_U_add_T : ∀ n : ℕ, U R (n + 1) = X * U R n + T R (n + 1) | 0 := by { simp only [U_zero, U_one, T_one], ring } | 1 := by { simp only [U_one, T_two, U_two], ring } | (n + 2) := calc U R (n + 2 + 1) = 2 * X * (X * U R (n + 1) + T R (n + 2)) - (X * U R n + T R (n + 1)) : by simp only [U_add_two, U_eq_X_mul_U_add_T n, U_eq_X_mul_U_add_T (n + 1)] ... = X * (2 * X * U R (n + 1) - U R n) + (2 * X * T R (n + 2) - T R (n + 1)) : by ring ... = X * U R (n + 2) + T R (n + 2 + 1) : by simp only [U_add_two, T_add_two] lemma T_eq_U_sub_X_mul_U (n : ℕ) : T R (n + 1) = U R (n + 1) - X * U R n := by rw [U_eq_X_mul_U_add_T, add_comm (X * U R n), add_sub_cancel] lemma T_eq_X_mul_T_sub_pol_U : ∀ n : ℕ, T R (n + 2) = X * T R (n + 1) - (1 - X ^ 2) * U R n | 0 := by { simp only [T_one, T_two, U_zero], ring } | 1 := by { simp only [T_add_two, T_zero, T_add_two, U_one, T_one], ring } | (n + 2) := calc T R (n + 2 + 2) = 2 * X * T R (n + 2 + 1) - T R (n + 2) : T_add_two _ _ ... = 2 * X * (X * T R (n + 2) - (1 - X ^ 2) * U R (n + 1)) - (X * T R (n + 1) - (1 - X ^ 2) * U R n) : by simp only [T_eq_X_mul_T_sub_pol_U] ... = X * (2 * X * T R (n + 2) - T R (n + 1)) - (1 - X ^ 2) * (2 * X * U R (n + 1) - U R n) : by ring ... = X * T R (n + 2 + 1) - (1 - X ^ 2) * U R (n + 2) : by rw [T_add_two _ (n + 1), U_add_two] lemma one_sub_X_sq_mul_U_eq_pol_in_T (n : ℕ) : (1 - X ^ 2) * U R n = X * T R (n + 1) - T R (n + 2) := by rw [T_eq_X_mul_T_sub_pol_U, ←sub_add, sub_self, zero_add] variables {R S} @[simp] lemma map_T (f : R →+* S) : ∀ n : ℕ, map f (T R n) = T S n | 0 := by simp only [T_zero, polynomial.map_one] | 1 := by simp only [T_one, map_X] | (n + 2) := begin simp only [T_add_two, polynomial.map_mul, polynomial.map_sub, map_X, bit0, polynomial.map_add, polynomial.map_one], rw [map_T (n + 1), map_T n], end @[simp] lemma map_U (f : R →+* S) : ∀ n : ℕ, map f (U R n) = U S n | 0 := by simp only [U_zero, polynomial.map_one] | 1 := begin simp only [U_one, map_X, polynomial.map_mul, polynomial.map_add, polynomial.map_one], change map f (1 + 1) * X = 2 * X, simpa only [polynomial.map_add, polynomial.map_one] end | (n + 2) := begin simp only [U_add_two, polynomial.map_mul, polynomial.map_sub, map_X, bit0, polynomial.map_add, polynomial.map_one], rw [map_U (n + 1), map_U n], end lemma T_derivative_eq_U : ∀ n : ℕ, derivative (T R (n + 1)) = (n + 1) * U R n | 0 := by simp only [T_one, U_zero, derivative_X, nat.cast_zero, zero_add, mul_one] | 1 := by { simp only [T_two, U_one, derivative_sub, derivative_one, derivative_mul, derivative_X_pow, nat.cast_one, nat.cast_two], norm_num } | (n + 2) := calc derivative (T R (n + 2 + 1)) = 2 * T R (n + 2) + 2 * X * derivative (T R (n + 1 + 1)) - derivative (T R (n + 1)) : by simp only [T_add_two _ (n + 1), derivative_sub, derivative_mul, derivative_X, derivative_bit0, derivative_one, bit0_zero, zero_mul, zero_add, mul_one] ... = 2 * (U R (n + 1 + 1) - X * U R (n + 1)) + 2 * X * ((n + 1 + 1) * U R (n + 1)) - (n + 1) * U R n : by rw_mod_cast [T_derivative_eq_U, T_derivative_eq_U, T_eq_U_sub_X_mul_U] ... = (n + 1) * (2 * X * U R (n + 1) - U R n) + 2 * U R (n + 2) : by ring ... = (n + 1) * U R (n + 2) + 2 * U R (n + 2) : by rw U_add_two ... = (n + 2 + 1) * U R (n + 2) : by ring ... = (↑(n + 2) + 1) * U R (n + 2) : by norm_cast lemma one_sub_X_sq_mul_derivative_T_eq_poly_in_T (n : ℕ) : (1 - X ^ 2) * (derivative (T R (n + 1))) = (n + 1) * (T R n - X * T R (n+1)) := calc (1 - X ^ 2) * (derivative (T R (n + 1))) = (1 - X ^ 2) * ((n + 1) * U R n) : by rw T_derivative_eq_U ... = (n + 1) * ((1 - X ^ 2) * U R n) : by ring ... = (n + 1) * (X * T R (n + 1) - (2 * X * T R (n + 1) - T R n)) : by rw [one_sub_X_sq_mul_U_eq_pol_in_T, T_add_two] ... = (n + 1) * (T R n - X * T R (n + 1)) : by ring lemma add_one_mul_T_eq_poly_in_U (n : ℕ) : ((n : R[X]) + 1) * T R (n + 1) = X * U R n - (1 - X ^ 2) * derivative (U R n) := begin have h : derivative (T R (n + 2)) = (U R (n + 1) - X * U R n) + X * derivative (T R (n + 1)) + 2 * X * U R n - (1 - X ^ 2) * derivative (U R n), { conv_lhs { rw T_eq_X_mul_T_sub_pol_U }, simp only [derivative_sub, derivative_mul, derivative_X, derivative_one, derivative_X_pow, one_mul, T_derivative_eq_U], rw [T_eq_U_sub_X_mul_U, nat.cast_bit0, nat.cast_one], ring }, calc ((n : R[X]) + 1) * T R (n + 1) = ((n : R[X]) + 1 + 1) * (X * U R n + T R (n + 1)) - X * ((n + 1) * U R n) - (X * U R n + T R (n + 1)) : by ring ... = derivative (T R (n + 2)) - X * derivative (T R (n + 1)) - U R (n + 1) : by rw [←U_eq_X_mul_U_add_T, ←T_derivative_eq_U, ←nat.cast_one, ←nat.cast_add, nat.cast_one, ←T_derivative_eq_U (n + 1)] ... = (U R (n + 1) - X * U R n) + X * derivative (T R (n + 1)) + 2 * X * U R n - (1 - X ^ 2) * derivative (U R n) - X * derivative (T R (n + 1)) - U R (n + 1) : by rw h ... = X * U R n - (1 - X ^ 2) * derivative (U R n) : by ring, end variables (R) /-- The product of two Chebyshev polynomials is the sum of two other Chebyshev polynomials. -/ lemma mul_T : ∀ m k, 2 * T R m * T R (m + k) = T R (2 * m + k) + T R k | 0 := by simp [two_mul, add_mul] | 1 := by simp [add_comm] | (m + 2) := begin intros k, -- clean up the `T` nat indices in the goal suffices : 2 * T R (m + 2) * T R (m + k + 2) = T R (2 * m + k + 4) + T R k, { have h_nat₁ : 2 * (m + 2) + k = 2 * m + k + 4 := by ring, have h_nat₂ : m + 2 + k = m + k + 2 := by simp [add_comm, add_assoc], simpa [h_nat₁, h_nat₂] using this }, -- clean up the `T` nat indices in the inductive hypothesis applied to `m + 1` and -- `k + 1` have H₁ : 2 * T R (m + 1) * T R (m + k + 2) = T R (2 * m + k + 3) + T R (k + 1), { have h_nat₁ : m + 1 + (k + 1) = m + k + 2 := by ring, have h_nat₂ : 2 * (m + 1) + (k + 1) = 2 * m + k + 3 := by ring, simpa [h_nat₁, h_nat₂] using mul_T (m + 1) (k + 1) }, -- clean up the `T` nat indices in the inductive hypothesis applied to `m` and `k + 2` have H₂ : 2 * T R m * T R (m + k + 2) = T R (2 * m + k + 2) + T R (k + 2), { have h_nat₁ : 2 * m + (k + 2) = 2 * m + k + 2 := by simp [add_assoc], have h_nat₂ : m + (k + 2) = m + k + 2 := by simp [add_assoc], simpa [h_nat₁, h_nat₂] using mul_T m (k + 2) }, -- state the `T` recurrence relation for a few useful indices have h₁ := T_add_two R m, have h₂ := T_add_two R (2 * m + k + 2), have h₃ := T_add_two R k, -- the desired identity is an appropriate linear combination of H₁, H₂, h₁, h₂, h₃ linear_combination 2 * T R (m + k + 2) * h₁ + 2 * X * H₁ - H₂ - h₂ - h₃, end /-- The `(m * n)`-th Chebyshev polynomial is the composition of the `m`-th and `n`-th -/ lemma T_mul : ∀ m n, T R (m * n) = (T R m).comp (T R n) | 0 := by simp | 1 := by simp | (m + 2) := begin intros n, have : 2 * T R n * T R ((m + 1) * n) = T R ((m + 2) * n) + T R (m * n), { convert mul_T R n (m * n); ring }, simp [this, T_mul m, ← T_mul (m + 1)] end end polynomial.chebyshev
6853f1f5a44a1e5a3dc7d225238b9f2c22b51a1b
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/nat/gcd/big_operators.lean
3628d43b45b994e34549e0a82e981873596ac47e
[ "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,204
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.gcd.basic import algebra.big_operators.basic /-! # Lemmas about coprimality with big products. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. These lemmas are kept separate from `data.nat.gcd.basic` in order to minimize imports. -/ namespace nat open_locale big_operators /-- See `is_coprime.prod_left` for the corresponding lemma about `is_coprime` -/ lemma coprime_prod_left {ι : Type*} {x : ℕ} {s : ι → ℕ} {t : finset ι} : (∀ (i : ι), i ∈ t → coprime (s i) x) → coprime (∏ (i : ι) in t, s i) x := finset.prod_induction s (λ y, y.coprime x) (λ a b, coprime.mul) (by simp) /-- See `is_coprime.prod_right` for the corresponding lemma about `is_coprime` -/ lemma coprime_prod_right {ι : Type*} {x : ℕ} {s : ι → ℕ} {t : finset ι} : (∀ (i : ι), i ∈ t → coprime x (s i)) → coprime x (∏ (i : ι) in t, s i) := finset.prod_induction s (λ y, x.coprime y) (λ a b, coprime.mul_right) (by simp) end nat
024a53e571fd24b64c18246d6115b4f054b9101f
7c4610454cf55b49f0c3cdaeb6b856eb3249cb2d
/src/free_take_three.lean
5a15a7dfc7f51b1ef4f8161a5643d83a5a82c2d3
[]
no_license
101damnations/fg_over_pid
097be43e11c3680a3fd4b6de2265de393cf4d4ef
a1a587c455a54a802f6ff61b07bb033701e451a7
refs/heads/master
1,669,708,904,636
1,597,259,770,000
1,597,259,770,000
287,097,363
0
0
null
null
null
null
UTF-8
Lean
false
false
34,211
lean
import tactic general set_lemmas linear_algebra.basis new_free ring_theory.principal_ideal_domain torsion primes run_cmd tactic.skip open_locale classical variables {R : Type*} [integral_domain R] [is_principal_ideal_ring R] noncomputable def projection {ι : Type*} {M : Type*} [add_comm_group M] [module R M] (v : ι → M) (hv : is_basis R v) (a : ι) : linear_map R M M := { to_fun := λ x, x - hv.repr x a • v a, map_add' := λ x y, by {show (x + y) - hv.repr (x + y) a • v a = (x - _) + (y - _), rw linear_map.map_add, erw add_smul, abel, }, map_smul' := λ c x, by {show c • x - hv.repr (c • x) a • v a = c • (x - _), rw linear_map.map_smul, rw smul_sub, rw ←mul_smul, refl, } } theorem proj_mem {ι : Type*} {M : Type*} [add_comm_group M] [module R M] {s : set ι} {v : ι → M} (hv : is_basis R (v ∘ subtype.val : s → M)) {a : ι} (ha : a ∈ s) {x : M} : projection _ hv ⟨a, ha⟩ x ∈ submodule.span R (set.range (v ∘ subtype.val : (s \ {a} → M))) := begin show _ - _ ∈ _, conv {to_lhs, congr, rw ←hv.total_repr x}, cases classical.em ((⟨a, ha⟩ : s) ∈ (hv.repr x).support), rw finsupp.total_apply, unfold finsupp.sum, rw ←finset.insert_erase h, erw finset.sum_insert (finset.not_mem_erase (⟨a, ha⟩ : s) (hv.repr x).support), simp only [add_sub_cancel', function.comp_app], refine @submodule.sum_mem R M _ _ _ _ (submodule.span R (set.range (v ∘ subtype.val))) (((hv.repr) x).support.erase ⟨a, ha⟩) (λ (y : s), ((hv.repr) x) y • v y.val) _, intros y hy, dsimp, apply submodule.smul_mem (submodule.span R (set.range (v ∘ subtype.val))) _, apply submodule.subset_span, use y, rw set.mem_diff, split, exact y.2, intro hya, have hyan : y = ⟨a, ha⟩ := subtype.ext_iff.2 hya, exact (finset.ne_of_mem_erase hy) hyan, rw finsupp.not_mem_support_iff.1 h, rw zero_smul, rw sub_zero, refine @submodule.sum_mem R M _ _ _ _ (submodule.span R (set.range (v ∘ subtype.val))) (((hv.repr) x).support) (λ (y : s), ((hv.repr) x) y • v y.val) _, intros y hy, dsimp, apply submodule.smul_mem (submodule.span R (set.range (v ∘ subtype.val))) _, apply submodule.subset_span, use y, rw set.mem_diff, split, exact y.2, intro hya, have hyan : y = ⟨a, ha⟩ := subtype.ext_iff.2 hya, rw hyan at hy, exact h hy, end lemma proj_ker {ι : Type*} {M : Type*} [add_comm_group M] [module R M] {s : set ι} {v : ι → M} (hv : is_basis R (v ∘ subtype.val : s → M)) {a : ι} (ha : a ∈ s) : (projection _ hv ⟨a, ha⟩).ker = submodule.span R {v a} := begin ext, split, intro hx, rw linear_map.mem_ker at hx, erw sub_eq_zero at hx, rw submodule.mem_span_singleton, use hv.repr x ⟨a, ha⟩, exact hx.symm, intro hx, rw submodule.mem_span_singleton at hx, cases hx with r hr, rw linear_map.mem_ker, erw sub_eq_zero, rw ←hr, rw linear_map.map_smul, have := @is_basis.repr_eq_single _ _ _ _ _ _ _ hv ⟨a, ha⟩, have hh : hv.repr ((v ∘ subtype.val) (⟨a, ha⟩ : s)) (⟨a, ha⟩ : s) = (1 : R) := by rw this; exact finsupp.single_eq_same, simp only [finsupp.smul_apply, algebra.id.smul_eq_mul, function.comp_app], rw mul_comm, rw mul_smul, rw hh, rw one_smul, end lemma projective_of_has_basis {ι : Type*} {M : Type*} [add_comm_group M] [module R M] {v : ι → M} (hv : is_basis R v) : projective R M := begin intros _ _ _ _ _ _ _ _ hg, let F' := λ i : ι, classical.some (hg (f (v i))), let F := @is_basis.constr _ _ _ _ _ _ _ _inst_6 _ _inst_7 hv F', use F, have huh : ∀ i : ι, g (F $ v i) = f (v i) := by { intro i, rw constr_basis, exact classical.some_spec (hg (f $ v i))}, have : @linear_map.comp R M A B _ _ (@add_comm_group.to_add_comm_monoid A _inst_6) (@add_comm_group.to_add_comm_monoid B _inst_7_1) _ _ _ g F = f := @is_basis.ext _ _ _ _ _ _ _ _inst_7_1 _ _inst_7_2 (@linear_map.comp R M A B _ _ (@add_comm_group.to_add_comm_monoid A _inst_6) (@add_comm_group.to_add_comm_monoid B _inst_7_1) _ _ _ g F) f hv (λ x, huh x), intro x, rw ←this, refl, end lemma split_of_left_inv {M : Type*} [add_comm_group M] [module R M] (A : submodule R M) {B : Type*} [add_comm_group B] [module R B] (f : M →ₗ[R] B) (H : A.subtype.range = f.ker) (g : B →ₗ[R] M) (hfg : f.comp g = linear_map.id) (hf : f.range = ⊤) : A ⊓ g.range = ⊥ ∧ A ⊔ g.range = ⊤ := begin split, rw eq_bot_iff, intros x hx, refine (submodule.mem_bot R).2 _, cases hx.2 with y hy, have : f x = 0, by {rw ←linear_map.mem_ker, rw ←H, exact ⟨⟨x, hx.1⟩, trivial, rfl⟩}, rw ←hy.2 at this, rw ←linear_map.comp_apply at this, rw hfg at this, rw linear_map.id_apply at this, rw ←hy.2, rw this, rw g.map_zero, rw eq_top_iff, intros x _, apply submodule.mem_sup.2, clear a, use x - g (f x), split, rw ←submodule.range_subtype A, rw H, rw linear_map.mem_ker, rw linear_map.map_sub, show f x - f.comp g (f x) = 0, rw hfg, exact sub_self (f x), use g (f x), split, exact linear_map.mem_range.2 ⟨f x, rfl⟩, rw sub_add_cancel, end variables {ι : Type*} {M : Type*} (s : set ι) [fintype ι] [add_comm_group M] [module R M] (v : ι → M) (a : ι) variables (R) def wtf' (i : (s \ ({a} : set ι) : set ι)) : submodule.span R (set.range (v ∘ subtype.val : s \ {a} → M)) := subtype.mk ((v ∘ subtype.val) i) (submodule.subset_span $ set.mem_range_self i) variables {R} lemma is_basis_diff {n : ℕ} {ι : Type*} {M : Type*} {s : set ι} [fintype ι] (hs : fintype.card ↥s = nat.succ n) [add_comm_group M] [module R M] {v : ι → M} (hv : is_basis R (v ∘ subtype.val : s → M)) {a : ι} (ha : a ∈ s) : is_basis R (wtf' R s v a ∘ (subtype.val : (@set.univ (s \ ({a} : set ι) : set ι) : set _) → (s \ ({a} : set ι) : set ι))) := begin split, refine linear_independent.comp _ subtype.val subtype.val_injective, apply linear_independent_span, dsimp, cases hv with hv1 hv2, have := linear_independent.to_subtype_range hv1, have H := linear_independent.mono (show (set.range (v ∘ subtype.val : s \ {a} → M) ⊆ set.range (v ∘ subtype.val : s → M)), by {rw set.range_subset_iff, intro y, exact ⟨⟨(y : ι), set.diff_subset _ _ y.2⟩, rfl⟩}) this, refine linear_independent.of_subtype_range _ H, have hi := linear_independent.injective hv1, intros x y h, have hxy : (⟨(x : ι), set.diff_subset _ _ x.2⟩ : s) = (⟨(y : ι), set.diff_subset _ _ y.2⟩ : s) := hi (by simpa only [function.comp_app] using h), apply subtype.ext_iff.2, simpa only [] using hxy, refine linear_map.map_injective (submodule.ker_subtype _) _, rw submodule.map_subtype_top, rw ←submodule.span_image, rw ←set.range_comp, congr' 1, ext, split, rintro ⟨y, hy⟩, simp only [submodule.subtype_apply, function.comp_app, wtf'] at hy, rw ←hy, use y.1, refl, rintro ⟨y, hy⟩, rw ←hy, use y, simp only [wtf', submodule.subtype_apply, submodule.coe_mk, function.comp_app], end theorem free_subm0 (ι : Type*) [fintype ι] (s : set ι) (hs : fintype.card s = 0) (M : Type*) [add_comm_group M] [module R M] (v : ι → M) (hv : is_basis R (v ∘ (subtype.val : s → ι))) (S : submodule R M) : ∃ (t : set M), linear_independent R (λ x, x : t → M) ∧ submodule.span R (set.range (λ x, x : t → M)) = S := begin use ∅, split, exact linear_independent_empty R M, cases hv with hv1 hv2, have hs := fintype.card_eq_zero_iff.1 hs, erw subtype.range_coe_subtype, erw submodule.span_empty, suffices : ∀ x : M, x = 0, by {symmetry, rw eq_bot_iff, intros x hx, apply (submodule.mem_bot R).2, exact this (x : M)}, intro x, have : set.range (v ∘ (subtype.val : s → ι )) = ∅ := by {apply set.range_eq_empty.2, intro h, cases h with y hy, exact hs y }, rw this at hv2, rw submodule.span_empty at hv2, apply (submodule.mem_bot R).1, rw hv2, exact submodule.mem_top, end noncomputable def free_equiv {ι : Type*} (x : ι) {M : Type*} [add_comm_group M] [module R M] {v : ι → M} (hv : is_basis R (v ∘ (subtype.val : ({x}: set ι) → ι))) : linear_equiv R R M := equiv_of_is_basis (@is_basis_singleton_one ({x} : set ι) R (set.unique_singleton x) _) hv (equiv.refl _) lemma free_subm1 (ι : Type*) [fintype ι] (s : set ι) (hs : ¬ 1 < fintype.card s) (M : Type*) [add_comm_group M] [module R M] (v : ι → M) (hv : is_basis R (v ∘ (subtype.val : s → ι))) (S : submodule R M) : ∃ (t : set M), linear_independent R (λ x, x : t → M) ∧ submodule.span R (set.range (λ x, x : t → M)) = S := begin cases classical.em (S = ⊥), use ∅, split, exact linear_independent_empty _ _, rw h, simp, have : fintype.card s = 0 ∨ fintype.card s = 1 := by omega, cases this with hl hr, exact free_subm0 ι s hl M v hv S, cases fintype.card_eq_one_iff.1 hr with y hy, have hrange : set.range (v ∘ subtype.val) = {(v ∘ subtype.val) y} := by {rw ←set.image_univ, convert set.image_singleton, symmetry, rw ←set.univ_subset_iff, intros t ht, exact hy t,}, have hys : {(y : ι)} = s := by {ext a, split, intro ha, convert y.2, intro ha, exact subtype.ext_iff.1 (hy ⟨a, ha⟩)}, let Smap := S.map (@free_equiv R _ _ ι (y : ι) M _ _ v (hys.symm ▸ hv)).symm.to_linear_map, cases submodule.is_principal.principal Smap with c hc, let C := @free_equiv R _ _ ι (y : ι) M _ _ v (hys.symm ▸ hv) c, use {C}, have hCy : C ∈ submodule.span R {(v ∘ subtype.val) y} := by {rw ←hrange, rw hv.2, exact submodule.mem_top,}, cases submodule.mem_span_singleton.1 hCy with r hr, have hCS : S = submodule.span R {C} := by {simp only [Smap, C] at hc ⊢, rw ←set.image_singleton, erw submodule.span_image, rw ←hc, rw ←submodule.map_comp, symmetry, convert submodule.map_id S, ext z, exact linear_equiv.apply_symm_apply (@free_equiv R _ _ ι (y : ι) M _ _ v (hys.symm ▸ hv)) z,}, have hC0 : C ≠ 0 := λ hC0, by {rw hC0 at hCS, change S = submodule.span R (⊥ : submodule R M) at hCS, erw submodule.span_eq at hCS, exact h hCS}, have hr0 : r ≠ 0 := λ hr0, by {rw hr0 at hr, rw zero_smul at hr, apply hC0, exact hr.symm}, split, refine linear_independent.mono _ _, exact {r • v (y : ι)}, rw ←hr, rw set.singleton_subset_iff, exact set.mem_singleton _, have hry : {r • v (y : ι)} = set.range (λ m : s, r • (v ∘ subtype.val) m) := by {rw ←set.image_univ, erw ←@set.image_singleton _ _ (λ m : s, r • (v ∘ subtype.val) m) y, congr, exact set.eq_univ_of_forall hy}, rw hry, apply linear_independent.to_subtype_range, rw linear_independent_iff, have hv1 := linear_independent_iff.1 hv.1, intros l hl, let L : {x // x ∈ s} →₀ R := finsupp.map_range (λ m, r • m) (smul_zero r) l, have hvL := hv1 L (by {rw finsupp.total_apply at hl ⊢, unfold finsupp.sum, simp only [finsupp.map_range_apply], rw finset.sum_subset (finsupp.support_map_range), convert hl,dsimp, simp only [mul_comm r, mul_smul], refl, intros X hX hX0, have hm := finsupp.not_mem_support_iff.1 hX0, rw finsupp.map_range_apply at hm,rw hm, rw zero_smul, }), ext, rw finsupp.ext_iff at hvL, specialize hvL a, exact or.resolve_left (mul_eq_zero.1 hvL) hr0, convert hCS.symm, simp only [subtype.range_coe_subtype], refl, end lemma one_empty {n : ℕ} {ι : Type*} {M : Type*} {s : set ι} [hι : fintype ι] (hs : fintype.card ↥s = n.succ) [add_comm_group M] [module R M] {v : ι → M} (hv : is_basis R (v ∘ subtype.val : s → M)) {S : submodule R M} (h1 : 1 < fintype.card ↥s) {b : ι} (hb : b ∈ s) {t : set ↥(submodule.span R (set.range (v ∘ subtype.val : s \ {b} → M)))} (ht : linear_independent R (λ (x : t), (↑x : submodule.span R (set.range (v ∘ subtype.val : s \ {b} → M)))) ∧ submodule.span R (set.range (λ (x : ↥t), (↑x : submodule.span R (set.range (v ∘ subtype.val : s \ {b} → M))))) = submodule.map (linear_map.cod_restrict (submodule.span R (set.range (v ∘ subtype.val))) (projection (v ∘ subtype.val) hv ⟨b, hb⟩) (λ c, proj_mem hv hb)) S) {l : set ↥((projection (v ∘ subtype.val) hv ⟨b, hb⟩).ker)} (hl : linear_independent R (λ (x : ↥l), (↑x : (projection (v ∘ subtype.val) hv ⟨b, hb⟩).ker)) ∧ submodule.span R (set.range (λ (x : ↥l), (↑x : (projection (v ∘ subtype.val) hv ⟨b, hb⟩).ker))) = ((submodule.of_le $ @inf_le_right _ _ S (projection _ hv ⟨b, hb⟩).ker).range)) (h : l = ∅) : ∃ (t : set M), linear_independent R (λ (x : ↥t), (↑x : M)) ∧ submodule.span R (set.range (λ (x : ↥t), ↑x)) = S := begin use (submodule.span R (set.range (v ∘ subtype.val : s \ {b} → M))).subtype '' t, split, apply linear_independent.image_subtype, exact ht.1, simp only [disjoint_bot_right, submodule.ker_subtype], simp only [submodule.subtype_apply, subtype.range_coe_subtype], show submodule.span R ((submodule.span R (set.range (v ∘ subtype.val))).subtype '' t) = S, rw submodule.span_image, apply le_antisymm, rw submodule.map_le_iff_le_comap, intros y hy, simp only [submodule.mem_comap, submodule.subtype_apply], sorry, sorry, end theorem free_subm (ι : Type*) [fintype ι] (s : set ι) (n : ℕ) (hs : fintype.card s = n) (M : Type*) [add_comm_group M] [module R M] (v : ι → M) (hv : is_basis R (v ∘ (subtype.val : s → ι))) (S : submodule R M) : ∃ (t : set M), linear_independent R (λ x, x : t → M) ∧ submodule.span R (set.range (λ x, x : t → M)) = S := begin unfreezingI {revert ι M s, induction n using nat.case_strong_induction_on with n hn}, intros ι M s hι h0 inst inst' v hv S, exact @free_subm0 _ _ _ ι hι s h0 M inst inst' v hv S, intros ι M s hι hs _ _ v hv S, resetI, cases (classical.em (1 < fintype.card s)) with h1 h1, rcases fintype.card_pos_iff.1 (show 0 < fintype.card s, by omega) with ⟨b, hb⟩, rcases hn n (nat.le_refl n) (s \ ({b} : set ι) : set ι) (submodule.span R (set.range (v ∘ subtype.val : (s \ ({b} : set ι)) → M))) (set.univ) (by { apply (add_right_inj 1).1, rw add_comm 1 n, rw ←nat.succ_eq_add_one n, rw ← hs, erw univ_card'', rw add_comm, rw (card_insert' (s \ ({b} : set ι)) not_mem_diff_singleton).symm, congr, rw ←eq_insert_erase_of_mem s b hb, apply_instance, apply_instance}) (λ i, ⟨v i, submodule.subset_span $ set.mem_range_self i⟩) (by convert is_basis_diff hs hv hb) (S.map $ (projection _ hv ⟨b, hb⟩).cod_restrict (submodule.span R (set.range (v ∘ subtype.val : (s \ ({b} : set ι)) → M))) (λ c, proj_mem hv hb)) with ⟨t, ht⟩, rcases hn 1 (by omega) ({b} : set ι) (projection _ hv ⟨b, hb⟩).ker set.univ sorry (λ x, ⟨v x, by {rw proj_ker,apply submodule.subset_span,convert set.mem_singleton _, exact x.2.symm}⟩) (by {split, suffices : linear_independent R (v ∘ subtype.val : ({b} : set ι) → M), by { apply linear_independent.comp _ subtype.val subtype.val_injective, erw linear_independent_comp_subtype at this, rw linear_independent_iff,intros l hl, specialize this (finsupp.emb_domain (function.embedding.subtype ({b} : set ι)) l) (by {rw finsupp.mem_supported, rw finsupp.support_emb_domain, intros x hx, rcases finset.mem_map.1 hx with ⟨y, hym, hy⟩, rw ←hy, exact y.2}), rw finsupp.total_apply at hl, rw finsupp.total_emb_domain at this,rw finsupp.total_apply at this, simp only [function.comp_app] at this, change ((l.sum (λ (i : ({b} : set ι)) (c : R), c • v (↑i : ι)) = 0) → (finsupp.emb_domain (function.embedding.subtype ({b} : set ι)) l = 0)) at this, specialize this (by {rw subtype.ext_iff at hl,dsimp at hl,rw ←hl, show _ = submodule.subtype _ _, conv_rhs {rw ←finsupp.total_apply}, rw linear_map.map_finsupp_total, rw finsupp.total_apply, apply finset.sum_congr rfl, intros x hx, simp only [submodule.subtype_apply, submodule.coe_mk, function.comp_app], }), rw finsupp.ext_iff at this,ext,specialize this a,erw finsupp.emb_domain_apply at this, rw this,simp only [finsupp.zero_apply], }, have huh := linear_independent.to_subtype_range hv.1, have hm := linear_independent.mono (show set.range (v ∘ subtype.val : ({b} : set ι) → M) ⊆ set.range (v ∘ subtype.val : s → M), by {rw set.range_subset_iff, intro y, use b, exact hb, rw ←subtype.eta y y.2, simp only [function.comp_app, subtype.eta], exact congr_arg v y.2.symm, }) huh, apply linear_independent.of_subtype_range, intros c d hcd, rw subtype.ext_iff, rw (show (c : ι) = b, from c.2), symmetry, exact d.2, exact hm, apply linear_map.map_injective (projection _ hv ⟨b, hb⟩).ker.ker_subtype, rw submodule.map_subtype_top, rw ←submodule.span_image, symmetry, convert proj_ker hv hb, rw ←set.range_comp, ext m, split, rintro ⟨k, hk⟩, rw ← hk, show _ = _, simpa only [] using congr_arg v k.1.2, intro hm, use b, exact set.mem_singleton _, rw (show _ = _, from hm), refl, }) (submodule.of_le $ @inf_le_right _ _ S (projection _ hv ⟨b, hb⟩).ker).range with ⟨l, hl⟩, cases (classical.em (l = ∅)), exact one_empty hs hv h1 hb ht hl h, let V := (submodule.span R (set.range (v ∘ subtype.val : (s \ ({b} : set ι)) → M))).subtype '' t, let W := (projection (v ∘ subtype.val) hv ⟨b, hb⟩).ker.subtype '' l, use V ∪ W, refine union_is_basis_of_gen_compl S ((submodule.span R (set.range (v ∘ subtype.val : (s \ ({b} : set ι)) → M))).comap S.subtype) V (submodule.comap S.subtype $ linear_map.ker (projection (v ∘ subtype.val) hv ⟨b, hb⟩)) W _ _ _ _ _ _, rw submodule.map_comap_subtype, sorry, rw submodule.map_comap_subtype, sorry, refine linear_independent.image_subtype _ _, exact ht.1, sorry, refine linear_independent.image_subtype _ _, exact hl.1, sorry, rw ←submodule.comap_inf, rw eq_bot_iff, intros x hx, rw submodule.mem_bot, cases hx with hxl hxr, simp at hxr, sorry, sorry, exact free_subm1 ι s h1 M v hv S, end lemma tf_iff {M : Type*} [add_comm_group M] [module R M] : tors R M = ⊥ ↔ ∀ (x : M) (r : R), r • x = 0 → r = 0 ∨ x = 0 := begin split, intro h, rw eq_bot_iff at h, intros x r hx, cases (classical.em (r = 0)), left, assumption, right, exact (submodule.mem_bot R).1 (h ⟨r, h_1, hx⟩), intros h, rw eq_bot_iff, intros x hx, cases hx with r hr, exact (submodule.mem_bot R).2 (or.resolve_left (h x r hr.2) hr.1) end theorem fg_quotient {M : Type*} [add_comm_group M] [module R M] (S : submodule R M) (Hfg : S.fg) (A : submodule R S) : (⊤ : submodule R A.quotient).fg := @is_noetherian.noetherian _ _ _ _ _ (is_noetherian_of_quotient_of_noetherian R S A $ is_noetherian_of_fg_of_noetherian S Hfg) ⊤ lemma span_insert_zero_eq' {s : set M} : submodule.span R (insert (0 : M) s) = submodule.span R s := begin rw ←set.union_singleton, rw submodule.span_union, rw submodule.span_singleton_eq_bot.2 rfl, rw sup_bot_eq, end lemma card_pos_of_ne_bot {M : Type*} [add_comm_group M] [module R M] {s : finset M} {S : submodule R M} (h : S ≠ ⊥) (hs : submodule.span R (↑s : set M) = S) : 0 < (s.erase 0).card := begin rw nat.pos_iff_ne_zero, intro h0, rw finset.card_eq_zero at h0, cases classical.em ((0 : M) ∈ s) with hl hr, rw ←finset.insert_erase hl at hs, rw insert_to_set' at hs, rw span_insert_zero_eq' at hs, rw h0 at hs, erw submodule.span_empty at hs, exact h hs.symm, rw finset.erase_eq_of_not_mem hr at h0, rw h0 at hs, erw submodule.span_empty at hs, exact h hs.symm, end lemma subset_singleton' {c : M} {l : finset M} (h : l ⊆ {c}) : l = ∅ ∨ l = {c} := begin cases (finset.eq_empty_or_nonempty l), left, exact h_1, right, erw finset.eq_singleton_iff_unique_mem, cases h_1 with w hw, have := finset.mem_singleton.1 (h hw), rw ←this, split, exact hw, intros x hx, rw this, exact finset.mem_singleton.1 (h hx), end lemma single_of_singleton_support {α : Type*} {l : α →₀ R} {x : α} (h : l.support = {x}) : l = finsupp.single x (l x) := begin ext, cases classical.em (a = x), rw h_1, simp only [finsupp.single_eq_same], rw finsupp.not_mem_support_iff.1 (by rw h; exact finset.not_mem_singleton.2 h_1), rw finsupp.single_eq_of_ne (ne.symm h_1), end def WHY (s : finset M) : set M := @has_lift.lift _ _ finset.has_lift s noncomputable def finsupp_insert {s : finset M} {x : M} {l : (set.insert x (WHY s)) →₀ R} (hx : x ∉ s) (hl : l.2 (⟨x, set.mem_insert x (WHY s)⟩ : set.insert x (WHY s)) = 0) : WHY s →₀ R := { support := subtype_mk' (finset.image subtype.val l.support) (WHY s) (by {intros y hy, erw finset.mem_image at hy, rcases hy with ⟨z, hzm, hz⟩, rw ←hz, exact or.resolve_left z.2 (by {intro hzx, rw finsupp.mem_support_iff at hzm, apply hzm, rw ←hl, congr, rw subtype.ext_iff, exact hzx})}), to_fun := λ x, l ⟨x, set.subset_insert _ _ x.2⟩, mem_support_to_fun := λ y, by {split, intros h h0, erw finset.mem_image at h, rcases h with ⟨b, hmb, hb⟩, cases b with b1 b2, erw finset.mem_image at b2, rcases b2 with ⟨c, hmc, hc⟩, apply finsupp.mem_support_iff.1 hmc, rw ←subtype.eta c c.2, rw ←h0, congr' 1, rw subtype.mk_eq_mk, rw hc, rw ←hb, refl, intros h0, apply finset.mem_image.2, use (y : M), apply finset.mem_image.2, use ⟨y, set.subset_insert _ _ y.2⟩, split, exact finsupp.mem_support_iff.2 h0, refl, split, exact finset.mem_univ _, rw subtype.ext_iff, refl,} } lemma finsupp_insert_apply {s : finset M} {x : M} {l : (set.insert x (WHY s)) →₀ R} (hx : x ∉ s) (hl : l.2 (⟨x, set.mem_insert x (WHY s)⟩ : set.insert x (WHY s)) = 0) {y : M} (hy : y ∈ s) : finsupp_insert hx hl ⟨y, hy⟩ = l ⟨y, set.subset_insert _ _ hy⟩ := rfl lemma finsupp_insert_total {s : finset M} {x : M} {l : (set.insert x (WHY s)) →₀ R} (hx : x ∉ s) (hl : l.2 (⟨x, set.mem_insert x (WHY s)⟩ : set.insert x (WHY s)) = 0) : finsupp.total (WHY s) M R subtype.val (finsupp_insert hx hl) = finsupp.total (set.insert x (WHY s)) M R subtype.val l := begin rw finsupp.total_apply, rw finsupp.total_apply, unfold finsupp.sum, show (subtype_mk' _ _ _).sum (λ (z : WHY s), l ⟨z, set.subset_insert _ _ z.2⟩ • (z : M)) = _, sorry, end variables (ρ : finset M) (T : set M) instance fucksake2 (s : finset M) : fintype (WHY s) := finset_coe.fintype s noncomputable def dep_coeff_map {M : Type*} [add_comm_group M] [module R M] (s : finset M) (z : M) (h : ¬(finsupp.total (set.insert z (WHY s)) M R subtype.val).ker = ⊥) : (finsupp.total (set.insert z (WHY s)) M R subtype.val).ker := @classical.some (finsupp.total (set.insert z (WHY s)) M R subtype.val).ker (λ f, f ≠ 0) (by { have h' : ¬(finsupp.total (set.insert z (WHY s)) M R subtype.val).ker ≤ ⊥, from λ h', h (eq_bot_iff.2 h'), rcases submodule.not_le_iff_exists.1 h' with ⟨y, hym, hy⟩, use y,exact hym, intro hy0, rw subtype.ext_iff at hy0, exact hy hy0}) noncomputable def dep_coeff {M : Type*} [add_comm_group M] [module R M] (s : finset M) (z : M) (h : ¬(finsupp.total (set.insert z (WHY s)) M R subtype.val).ker = ⊥) : R := dep_coeff_map s z h ⟨z, (set.mem_insert z _)⟩ theorem dep_coeff_spec {M : Type*} [add_comm_group M] [module R M] (s : finset M) (z : M) (h : ¬(finsupp.total (set.insert z (WHY s)) M R subtype.val).ker = ⊥) : dep_coeff_map s z h ≠ 0 := @classical.some_spec (finsupp.total (set.insert z (WHY s)) M R subtype.val).ker (λ f, f ≠ 0) (by { have h' : ¬(finsupp.total (set.insert z (WHY s)) M R subtype.val).ker ≤ ⊥, from λ h', h (eq_bot_iff.2 h'), rcases submodule.not_le_iff_exists.1 h' with ⟨y, hym, hy⟩, use y, exact hym, intro hy0, rw subtype.ext_iff at hy0, exact hy hy0}) lemma prod_ne_zero {M : Type*} [add_comm_group M] [module R M] (Y s : finset M) (h : ∀ z : M, z ∈ Y \ s → ¬(finsupp.total (set.insert (z : M) (WHY s)) M R subtype.val).ker = ⊥) (hli : (finsupp.total (WHY s) M R subtype.val).ker = ⊥) : finset.prod (finset.image (λ w : (WHY (Y \ s)), dep_coeff s (w : M) $ h w w.2) (@finset.univ (WHY (Y \ s)) _)) id ≠ 0 := begin intro hr0, have hr := finset_prod_eq_zero_iff.1 hr0, rw finset.mem_image at hr, rcases hr with ⟨x, hxm, hx⟩, rw eq_bot_iff at hli, have H := classical.not_not.2 hli, apply H, rw submodule.not_le_iff_exists, let F := @finsupp_insert R _ _ _ _ _ s x (dep_coeff_map s x (h x x.2)) (finset.mem_sdiff.1 x.2).2 hx, use F, split, rw linear_map.mem_ker, erw finsupp_insert_total (finset.mem_sdiff.1 x.2).2 hx, have huh := (dep_coeff_map s (x : M) (h x x.2)).2, rw linear_map.mem_ker at huh, exact huh, intro hF0, apply dep_coeff_spec s (x : M) (h x x.2), rw submodule.mem_bot at hF0, rw subtype.ext_iff, rw submodule.coe_zero, ext, cases (set.mem_insert_iff.1 a.2), rw finsupp.zero_apply, rw ←hx, congr, rw subtype.ext_iff, exact h_1, have huh := finsupp.ext_iff.1 hF0 ⟨a, h_1⟩, rw finsupp_insert_apply at huh, rw subtype.coe_eta at huh, rw huh, refl, end lemma prod_smul_mem {M : Type*} [add_comm_group M] [module R M] (Y s : finset M) (h : ∀ z : M, z ∈ Y \ s → ¬(finsupp.total (set.insert (z : M) (WHY s)) M R subtype.val).ker = ⊥) (hli : (finsupp.total (WHY s) M R subtype.val).ker = ⊥) {y} (hy : y ∈ Y) : finset.prod (finset.image (λ w : (WHY (Y \ s)), dep_coeff s (w : M) $ h w w.2) (@finset.univ (WHY (Y \ s)) _)) id • y ∈ submodule.span R (↑s : set M) := begin sorry, end variables {r : R} (S : submodule R M) noncomputable def r_equiv (htf : ∀ (x : S) (r : R), r • x = 0 → r = 0 ∨ x = 0) (r : R) (hr : r ≠ 0) := linear_equiv.of_injective ((r • linear_map.id).comp S.subtype) (by { rw linear_map.ker_eq_bot', intros m hm, exact or.resolve_left (htf m r $ subtype.ext_iff.2 $ by {dsimp at hm, rw ←submodule.coe_smul at hm, rw ←@submodule.coe_zero _ _ _ _ _ S at hm, exact hm}) hr}) lemma equiv_apply (htf : ∀ (x : S) (r : R), r • x = 0 → r = 0 ∨ x = 0) (r : R) (hr : r ≠ 0) {x : S} : (r_equiv S htf r hr x : M) = r • x := rfl theorem free_of_tf (M : Type*) [add_comm_group M] [module R M] (S : submodule R M) (hfg : S.fg) (htf : ∀ (x : S) (r : R), r • x = 0 → r = 0 ∨ x = 0) : ∃ (t : set M), linear_independent R (λ x, x : t → M) ∧ submodule.span R (set.range (λ x, x : t → M)) = S := begin cases (classical.em (S = ⊥)), { use ∅, split, exact linear_independent_empty _ _, rw h, simp only [subtype.range_coe_subtype], exact submodule.span_empty}, cases hfg with X hX, set Y := X.erase 0, have hY : (↑Y : set M) ⊆ S := set.subset.trans (finset.erase_subset 0 X) (hX ▸ submodule.subset_span), set n := nat.find_greatest (λ n, ∃ s : finset M, s ⊆ Y ∧ linear_independent R (λ x, x : (WHY s) → M) ∧ s.card = n) Y.card, cases @nat.find_greatest_spec (λ n, ∃ s : finset M, s ⊆ Y ∧ linear_independent R (λ x, x : (WHY s) → M) ∧ s.card = n) _ Y.card ⟨1, nat.succ_le_of_lt $ card_pos_of_ne_bot h hX, by {cases finset.card_pos.1 (card_pos_of_ne_bot h hX) with c hc, use {c}, split, exact finset.singleton_subset_iff.2 hc, split, rw linear_independent_subtype, intros l hlm hl, cases subset_singleton ((finsupp.mem_supported _ _).1 hlm) with hl0 hlc, rw ←finsupp.support_eq_empty, exact hl0, rw single_of_singleton_support hlc at hl ⊢, rw finsupp.total_single at hl, rw finsupp.single_eq_zero, exact or.resolve_right (htf ⟨c, hY hc⟩ (l c) (subtype.ext_iff.2 $ hl)) (λ h0, (finset.mem_erase.1 hc).1 $ subtype.ext_iff.1 h0), exact finset.card_singleton _, }⟩ with s hs, cases (classical.em (∃ x, x ∈ Y \ s)), cases h_1 with z hz, have hnl : ∀ z, z ∈ Y \ s → ¬(linear_independent R $ (λ y, y : (set.insert z (WHY s) : set M) → M)) := λ x hx hnl, by {have huh := @nat.find_greatest_is_greatest (λ n, ∃ s : finset M, s ⊆ Y ∧ linear_independent R (λ x, x : (WHY s) → M) ∧ s.card = n) _ Y.card ⟨1, nat.succ_le_of_lt $ card_pos_of_ne_bot h hX, by {cases finset.card_pos.1 (card_pos_of_ne_bot h hX) with c hc, use {c}, split, exact finset.singleton_subset_iff.2 hc, split, rw linear_independent_subtype, intros l hlm hl, cases subset_singleton ((finsupp.mem_supported _ _).1 hlm) with hl0 hlc, rw ←finsupp.support_eq_empty, exact hl0, rw single_of_singleton_support hlc at hl ⊢, rw finsupp.total_single at hl, rw finsupp.single_eq_zero, exact or.resolve_right (htf ⟨c, hY hc⟩ (l c) (subtype.ext_iff.2 $ hl)) (λ h0, (finset.mem_erase.1 hc).1 $ subtype.ext_iff.1 h0), exact finset.card_singleton _, }⟩ n.succ (by {split, exact nat.lt_succ_self _, rw nat.succ_le_iff, simp only [n], erw ←hs.2.2, apply finset.card_lt_card, rw finset.ssubset_iff_of_subset, use x, rw ←finset.mem_sdiff, exact hx, exact hs.1}), exact huh ⟨(insert x s), by {split, rw finset.insert_subset,split, exact (finset.mem_sdiff.1 hx).1, exact hs.1, split, simp only [*, not_exists, set.diff_singleton_subset_iff, submodule.mem_coe, finset.coe_erase, not_and, finset.mem_sdiff, ne.def, set.insert_eq_of_mem, submodule.zero_mem, finset.mem_erase] at *, convert hnl, all_goals {try {exact finset.coe_insert _ _}}, rw finset.card_insert_of_not_mem, rw hs.2.2, exact (finset.mem_sdiff.1 hx).2, }⟩, }, unfold linear_independent at hnl, set r : R := finset.prod (finset.image (λ w : (↑(Y \ s) : set M), dep_coeff s (w : M) $ hnl w w.2) (@finset.univ (↑(Y \ s) : set M) _)) id, have hr0 : r ≠ 0 := prod_ne_zero Y s hnl hs.2.1, have hrX : ∀ x, x ∈ X → r • x ∈ submodule.span R (↑s : set M) := sorry, have hrS : ∀ x, x ∈ S → r • x ∈ submodule.span R (↑s : set M) := λ w hw, by {rw ←hX at hw, rw ←set.image_id (↑X : set M) at hw, rcases (finsupp.mem_span_iff_total R).1 hw with ⟨f, hfm, hf⟩, rw ←hf, rw finsupp.total_apply, rw finsupp.smul_sum, apply submodule.sum_mem (submodule.span R (↑s : set M)), intros c hc, dsimp, rw ←mul_smul, rw mul_comm, rw mul_smul, apply submodule.smul_mem (submodule.span R (↑s : set M)) (f c), exact hrX c (hfm hc) }, cases free_subm (↑s : set M) set.univ s.card (by { rw univ_card s, rw finset.card_univ, apply fintype.card_congr, symmetry, exact (equiv.set.univ _).symm, }) (submodule.span R (↑s : set M) : set M) (λ x, ⟨x, submodule.subset_span x.2⟩) ⟨sorry, sorry⟩ (submodule.comap (submodule.span R (↑s : set M)).subtype (submodule.map (r • linear_map.id) S)) with t ht, let T := (λ x, r • x)⁻¹' (subtype.val '' t), use T, split, simp only [], unfold linear_independent at *, rw eq_bot_iff at *, by_contradiction, rcases submodule.not_le_iff_exists.1 a with ⟨f, hfm, hf⟩, refine absurd ht.1 _, apply submodule.not_le_iff_exists.2, let sset : finset t := @finset.preimage _ _ (subtype.val ∘ subtype.val) (finset.image (λ x : T, r • (x : M)) f.1) sorry, let func : t → R := λ x, f.2 ⟨r • x, sorry⟩, let F : t →₀ R := ⟨sset, func, sorry⟩, use F, split, sorry, sorry, ext i, split, intro hmem, sorry, sorry, use (↑s : set M), split, exact hs.2.1, rw ←hX, have hsY : s = Y := le_antisymm hs.1 sorry, rw hsY, sorry, end theorem torsion_decomp {M : Type*} [add_comm_group M] [module R M] (S : submodule R M) (hfg : S.fg) : ∃ t : set S, linear_independent R (λ x, x : t → S) ∧ (tors R S) ⊓ (submodule.span R t) = ⊥ ∧ (tors R S) ⊔ (submodule.span R t) = ⊤ := begin cases free_of_tf (tors R S).quotient ⊤ (fg_quotient S hfg (tors R S)) (tf_iff.1 $ eq_bot_iff.2 $ λ b hb, by {have := eq_bot_iff.1 (tors_free_of_quotient R S), rcases hb with ⟨c, hc⟩, have h0 : c • (b : (tors R S).quotient) = 0 := by {rw ←submodule.coe_smul, rw ←@submodule.coe_zero R (tors R S).quotient _ _ _ ⊤, congr, exact hc.2 }, have ffs := this ⟨c, hc.1, h0⟩, rw submodule.mem_bot at ffs ⊢, rw subtype.ext_iff, rw ffs, refl} ) with t ht, cases (projective_of_has_basis ht S (tors R S).quotient linear_map.id (tors R S).mkq (λ x, quotient.induction_on' x $ λ y, ⟨y, rfl⟩)) with f hf, have HP := split_of_left_inv (tors R S) (tors R S).mkq (by {rw submodule.ker_mkq, rw submodule.range_subtype}) f (linear_map.ext hf) (submodule.range_mkq _), use (set.range ((f : _ → S) ∘ subtype.val : t → S)), split, apply linear_independent.to_subtype_range, apply linear_independent.restrict_of_comp_subtype, rw linear_independent_comp_subtype, intros l hlm hl, apply (linear_independent_subtype.1 ht.1 l hlm), rw finsupp.total_apply at *, apply f.to_add_monoid_hom.injective_iff.1 (function.left_inverse.injective hf), rw ←hl, erw (finset.sum_hom l.support f).symm, apply finset.sum_congr rfl, intros x hx, dsimp, rw linear_map.map_smul, convert HP, all_goals {rw ←set.image_univ, rw set.image_comp, rw submodule.span_image, show _ = (⊤ : submodule R (tors R S).quotient).map f, congr, convert ht.2, rw set.image_univ, refl}, end def tf_basis {M : Type*} [add_comm_group M] [module R M] (S : submodule R M) (hfg : S.fg) := classical.some (torsion_decomp S hfg) theorem tf_basis_is_basis {M : Type*} [add_comm_group M] [module R M] (S : submodule R M) (hfg : S.fg) : linear_independent R (λ x, x : tf_basis S hfg → S) := (classical.some_spec (torsion_decomp S hfg)).1 theorem disjoint_tors_tf {M : Type*} [add_comm_group M] [module R M] {S : submodule R M} (hfg : S.fg) : (tors R S) ⊓ (submodule.span R $ tf_basis S hfg) = ⊥ := (classical.some_spec (torsion_decomp S hfg)).2.1 theorem tors_tf_span {M : Type*} [add_comm_group M] [module R M] {S : submodule R M} (hfg : S.fg) : (tors R S) ⊔ (submodule.span R $ tf_basis S hfg) = ⊤ := (classical.some_spec (torsion_decomp S hfg)).2.2
49ec7fa333a50978a6d23bf08b883af1cab23ac3
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/lifting_properties/basic.lean
7c74c6abee1579841d082523e82c52cd1df53c65
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
4,573
lean
/- Copyright (c) 2021 Jakob Scholbach. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jakob Scholbach, Joël Riou -/ import category_theory.comm_sq /-! # Lifting properties > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the lifting property of two morphisms in a category and shows basic properties of this notion. ## Main results - `has_lifting_property`: the definition of the lifting property ## Tags lifting property @TODO : 1) define llp/rlp with respect to a `morphism_property` 2) retracts, direct/inverse images, (co)products, adjunctions -/ universe v namespace category_theory open category variables {C : Type*} [category C] {A B B' X Y Y' : C} (i : A ⟶ B) (i' : B ⟶ B') (p : X ⟶ Y) (p' : Y ⟶ Y') /-- `has_lifting_property i p` means that `i` has the left lifting property with respect to `p`, or equivalently that `p` has the right lifting property with respect to `i`. -/ class has_lifting_property : Prop := (sq_has_lift : ∀ {f : A ⟶ X} {g : B ⟶ Y} (sq : comm_sq f i p g), sq.has_lift) @[priority 100] instance sq_has_lift_of_has_lifting_property {f : A ⟶ X} {g : B ⟶ Y} (sq : comm_sq f i p g) [hip : has_lifting_property i p] : sq.has_lift := by apply hip.sq_has_lift namespace has_lifting_property variables {i p} lemma op (h : has_lifting_property i p) : has_lifting_property p.op i.op := ⟨λ f g sq, begin simp only [comm_sq.has_lift.iff_unop, quiver.hom.unop_op], apply_instance, end⟩ lemma unop {A B X Y : Cᵒᵖ} {i : A ⟶ B} {p : X ⟶ Y} (h : has_lifting_property i p) : has_lifting_property p.unop i.unop := ⟨λ f g sq, begin rw comm_sq.has_lift.iff_op, simp only [quiver.hom.op_unop], apply_instance, end⟩ lemma iff_op : has_lifting_property i p ↔ has_lifting_property p.op i.op := ⟨op, unop⟩ lemma iff_unop {A B X Y : Cᵒᵖ} (i : A ⟶ B) (p : X ⟶ Y) : has_lifting_property i p ↔ has_lifting_property p.unop i.unop := ⟨unop, op⟩ variables (i p) @[priority 100] instance of_left_iso [is_iso i] : has_lifting_property i p := ⟨λ f g sq, comm_sq.has_lift.mk' { l := inv i ≫ f, fac_left' := by simp only [is_iso.hom_inv_id_assoc], fac_right' := by simp only [sq.w, assoc, is_iso.inv_hom_id_assoc], }⟩ @[priority 100] instance of_right_iso [is_iso p] : has_lifting_property i p := ⟨λ f g sq, comm_sq.has_lift.mk' { l := g ≫ inv p, fac_left' := by simp only [← sq.w_assoc, is_iso.hom_inv_id, comp_id], fac_right' := by simp only [assoc, is_iso.inv_hom_id, comp_id], }⟩ instance of_comp_left [has_lifting_property i p] [has_lifting_property i' p] : has_lifting_property (i ≫ i') p := ⟨λ f g sq, begin have fac := sq.w, rw assoc at fac, exact comm_sq.has_lift.mk' { l := (comm_sq.mk (comm_sq.mk fac).fac_right).lift, fac_left' := by simp only [assoc, comm_sq.fac_left], fac_right' := by simp only [comm_sq.fac_right], }, end⟩ instance of_comp_right [has_lifting_property i p] [has_lifting_property i p'] : has_lifting_property i (p ≫ p') := ⟨λ f g sq, begin have fac := sq.w, rw ← assoc at fac, let sq₂ := (comm_sq.mk ((comm_sq.mk fac).fac_left.symm)).lift, exact comm_sq.has_lift.mk' { l := (comm_sq.mk ((comm_sq.mk fac).fac_left.symm)).lift, fac_left' := by simp only [comm_sq.fac_left], fac_right' := by simp only [comm_sq.fac_right_assoc, comm_sq.fac_right], }, end⟩ lemma of_arrow_iso_left {A B A' B' X Y : C} {i : A ⟶ B} {i' : A' ⟶ B'} (e : arrow.mk i ≅ arrow.mk i') (p : X ⟶ Y) [hip : has_lifting_property i p] : has_lifting_property i' p := by { rw arrow.iso_w' e, apply_instance, } lemma of_arrow_iso_right {A B X Y X' Y' : C} (i : A ⟶ B) {p : X ⟶ Y} {p' : X' ⟶ Y'} (e : arrow.mk p ≅ arrow.mk p') [hip : has_lifting_property i p] : has_lifting_property i p' := by { rw arrow.iso_w' e, apply_instance, } lemma iff_of_arrow_iso_left {A B A' B' X Y : C} {i : A ⟶ B} {i' : A' ⟶ B'} (e : arrow.mk i ≅ arrow.mk i') (p : X ⟶ Y) : has_lifting_property i p ↔ has_lifting_property i' p := by { split; introI, exacts [of_arrow_iso_left e p, of_arrow_iso_left e.symm p], } lemma iff_of_arrow_iso_right {A B X Y X' Y' : C} (i : A ⟶ B) {p : X ⟶ Y} {p' : X' ⟶ Y'} (e : arrow.mk p ≅ arrow.mk p') : has_lifting_property i p ↔ has_lifting_property i p' := by { split; introI, exacts [of_arrow_iso_right i e, of_arrow_iso_right i e.symm], } end has_lifting_property end category_theory
ad9390c8d38b5a89e7f4d0069f24e54806d9f883
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/data/complex/is_R_or_C.lean
edac3ec8e31bd463f3e581f11292fc4bba10a0ef
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
23,446
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 analysis.normed_space.basic import analysis.complex.basic /-! # `is_R_or_C`: a typeclass for ℝ or ℂ This file defines the typeclass `is_R_or_C` intended to have only two instances: ℝ and ℂ. It is meant for definitions and theorems which hold for both the real and the complex case, and in particular when the real case follows directly from the complex case by setting `re` to `id`, `im` to zero and so on. Its API follows closely that of ℂ. Possible applications include defining inner products and Hilbert spaces for both the real and complex case. One would produce the definitions and proof for an arbitrary field of this typeclass, which basically amounts to doing the complex case, and the two cases then fall out immediately from the two instances of the class. -/ /-- This typeclass captures properties shared by ℝ and ℂ, with an API that closely matches that of ℂ. -/ class is_R_or_C (K : Type*) [nondiscrete_normed_field K] [algebra ℝ K] := (re : K →+ ℝ) (im : K →+ ℝ) (conj : K →+* K) (I : K) -- Meant to be set to 0 for K=ℝ (of_real : ℝ → K) -- Meant to be id for K=ℝ and the coercion from ℝ for K=ℂ (I_re_ax : re I = 0) (I_mul_I_ax : I = 0 ∨ I * I = -1) (re_add_im_ax : ∀ (z : K), of_real (re z) + of_real (im z) * I = z) (smul_coe_mul_ax : ∀ (z : K) (r : ℝ), r • z = of_real r * z) (of_real_re_ax : ∀ r : ℝ, re (of_real r) = r) (of_real_im_ax : ∀ r : ℝ, im (of_real r) = 0) (mul_re_ax : ∀ z w : K, re (z * w) = re z * re w - im z * im w) (mul_im_ax : ∀ z w : K, im (z * w) = re z * im w + im z * re w) (conj_re_ax : ∀ z : K, re (conj z) = re z) (conj_im_ax : ∀ z : K, im (conj z) = -(im z)) (conj_I_ax : conj I = -I) (norm_sq_eq_def_ax : ∀ (z : K), ∥z∥^2 = (re z) * (re z) + (im z) * (im z)) (mul_im_I_ax : ∀ (z : K), (im z) * im I = im z) (inv_def_ax : ∀ (z : K), z⁻¹ = conj z * of_real ((∥z∥^2)⁻¹)) (div_I_ax : ∀ (z : K), z / I = -(z * I)) namespace is_R_or_C variables {K : Type*} [nondiscrete_normed_field K] [algebra ℝ K] [is_R_or_C K] local notation `𝓚` := @is_R_or_C.of_real K _ _ _ lemma of_real_alg : ∀ x : ℝ, 𝓚 x = x • (1 : K) := λ x, by rw [←mul_one (𝓚 x), smul_coe_mul_ax] @[simp] lemma re_add_im (z : K) : 𝓚 (re z) + 𝓚 (im z) * I = z := is_R_or_C.re_add_im_ax z @[simp] lemma of_real_re : ∀ r : ℝ, re (𝓚 r) = r := is_R_or_C.of_real_re_ax @[simp] lemma of_real_im : ∀ r : ℝ, im (𝓚 r) = 0 := is_R_or_C.of_real_im_ax @[simp] lemma mul_re : ∀ z w : K, re (z * w) = re z * re w - im z * im w := is_R_or_C.mul_re_ax @[simp] lemma mul_im : ∀ z w : K, im (z * w) = re z * im w + im z * re w := is_R_or_C.mul_im_ax theorem ext_iff : ∀ {z w : K}, z = w ↔ re z = re w ∧ im z = im w := λ z w, { mp := by { rintro rfl, cc }, mpr := by { rintro ⟨h₁,h₂⟩, rw [←re_add_im z, ←re_add_im w, h₁, h₂] } } theorem ext : ∀ {z w : K}, re z = re w → im z = im w → z = w := by { simp_rw ext_iff, cc } lemma zero_re : re (𝓚 0) = (0 : ℝ) := by simp only [of_real_re] @[simp] lemma zero_im : im (𝓚 0) = 0 := by rw [of_real_im] lemma of_real_zero : 𝓚 0 = 0 := by rw [of_real_alg, zero_smul] @[simp] lemma of_real_one : 𝓚 1 = 1 := by rw [of_real_alg, one_smul] @[simp] lemma one_re : re (1 : K) = 1 := by rw [←of_real_one, of_real_re] @[simp] lemma one_im : im (1 : K) = 0 := by rw [←of_real_one, of_real_im] @[simp] theorem of_real_inj {z w : ℝ} : 𝓚 z = 𝓚 w ↔ z = w := { mp := λ h, by { convert congr_arg re h; simp only [of_real_re] }, mpr := λ h, by rw h } @[simp] lemma bit0_re (z : K) : re (bit0 z) = bit0 (re z) := by simp [bit0] @[simp] lemma bit1_re (z : K) : re (bit1 z) = bit1 (re z) := by simp only [bit1, add_monoid_hom.map_add, bit0_re, add_right_inj, one_re] @[simp] lemma bit0_im (z : K) : im (bit0 z) = bit0 (im z) := by simp [bit0] @[simp] lemma bit1_im (z : K) : im (bit1 z) = bit0 (im z) := by simp only [bit1, add_right_eq_self, add_monoid_hom.map_add, bit0_im, one_im] @[simp] theorem of_real_eq_zero {z : ℝ} : 𝓚 z = 0 ↔ z = 0 := by rw [←of_real_zero]; exact of_real_inj @[simp] lemma of_real_add (r s : ℝ) : 𝓚 (r + s) = 𝓚 r + 𝓚 s := by apply (@is_R_or_C.ext_iff K _ _ _ (𝓚 (r + s)) (𝓚 r + 𝓚 s)).mpr; simp @[simp] lemma of_real_bit0 (r : ℝ) : 𝓚 (bit0 r : ℝ) = bit0 (𝓚 r) := ext_iff.2 $ by simp [bit0] @[simp] lemma of_real_bit1 (r : ℝ) : 𝓚 (bit1 r : ℝ) = bit1 (𝓚 r) := ext_iff.2 $ by simp [bit1] /- Note: This can be proven by `norm_num` once K is proven to be of characteristic zero below. -/ lemma two_ne_zero : (2 : K) ≠ 0 := begin intro h, rw [(show (2 : K) = 𝓚 2, by norm_num), ←of_real_zero, of_real_inj] at h, linarith, end @[simp] lemma of_real_neg (r : ℝ) : 𝓚 (-r : ℝ) = -(𝓚 r) := ext_iff.2 $ by simp @[simp] lemma of_real_mul (r s : ℝ) : 𝓚 (r * s : ℝ) = (𝓚 r) * (𝓚 s) := ext_iff.2 $ by simp lemma smul_re (r : ℝ) (z : K) : re ((𝓚 r) * z) = r * (re z) := by simp only [of_real_im, zero_mul, of_real_re, sub_zero, mul_re] lemma smul_im (r : ℝ) (z : K) : im ((𝓚 r) * z) = r * (im z) := by simp only [add_zero, of_real_im, zero_mul, of_real_re, mul_im] lemma smul_re' : ∀ (r : ℝ) (z : K), re (r • z) = r * (re z) := λ r z, by { rw [smul_coe_mul_ax], apply smul_re } lemma smul_im' : ∀ (r : ℝ) (z : K), im (r • z) = r * (im z) := λ r z, by { rw [smul_coe_mul_ax], apply smul_im } /-! ### The imaginary unit, `I` -/ /-- The imaginary unit. -/ @[simp] lemma I_re : re (I : K) = 0 := I_re_ax @[simp] lemma I_im (z : K) : im z * im (I : K) = im z := mul_im_I_ax z lemma I_mul_I : (I : K) = 0 ∨ (I : K) * I = -1 := I_mul_I_ax @[simp] lemma conj_re (z : K) : re (conj z) = re z := is_R_or_C.conj_re_ax z @[simp] lemma conj_im (z : K) : im (conj z) = -(im z) := is_R_or_C.conj_im_ax z @[simp] lemma conj_of_real (r : ℝ) : conj (𝓚 r) = (𝓚 r) := by { rw ext_iff, simp only [of_real_im, conj_im, eq_self_iff_true, conj_re, and_self, neg_zero] } @[simp] lemma conj_bit0 (z : K) : conj (bit0 z) = bit0 (conj z) := by simp [bit0, ext_iff] @[simp] lemma conj_bit1 (z : K) : conj (bit1 z) = bit1 (conj z) := by simp [bit0, ext_iff] @[simp] lemma conj_neg_I : conj (-I) = (I : K) := by simp [ext_iff] @[simp] lemma conj_conj (z : K) : conj (conj z) = z := by simp [ext_iff] lemma conj_involutive : @function.involutive K is_R_or_C.conj := conj_conj lemma conj_bijective : @function.bijective K K is_R_or_C.conj := conj_involutive.bijective lemma conj_inj (z w : K) : conj z = conj w ↔ z = w := conj_bijective.1.eq_iff @[simp] lemma conj_eq_zero {z : K} : conj z = 0 ↔ z = 0 := by simpa using @conj_inj K _ _ _ z 0 lemma eq_conj_iff_real {z : K} : conj z = z ↔ ∃ r : ℝ, z = (𝓚 r) := begin split, { intro h, suffices : im z = 0, { use (re z), rw ← add_zero (of_real _), convert (re_add_im z).symm, simp [this] }, contrapose! h, rw ← re_add_im z, simp only [conj_of_real, ring_hom.map_add, ring_hom.map_mul, conj_I_ax], rw [add_left_cancel_iff, ext_iff], simpa [neg_eq_iff_add_eq_zero, add_self_eq_zero] }, { rintros ⟨r, rfl⟩, apply conj_of_real } end lemma eq_conj_iff_re {z : K} : conj z = z ↔ 𝓚 (re z) = z := eq_conj_iff_real.trans ⟨by rintro ⟨r, rfl⟩; simp, λ h, ⟨_, h.symm⟩⟩ /-- The norm squared function. -/ def norm_sq (z : K) : ℝ := re z * re z + im z * im z lemma norm_sq_eq_def {z : K} : ∥z∥^2 = (re z) * (re z) + (im z) * (im z) := norm_sq_eq_def_ax z lemma norm_sq_eq_def' (z : K) : norm_sq z = ∥z∥^2 := by rw [norm_sq_eq_def, norm_sq] @[simp] lemma norm_sq_of_real (r : ℝ) : ∥𝓚 r∥^2 = r * r := by simp [norm_sq_eq_def] @[simp] lemma norm_sq_zero : norm_sq (0 : K) = 0 := by simp [norm_sq, pow_two] @[simp] lemma norm_sq_one : norm_sq (1 : K) = 1 := by simp [norm_sq] lemma norm_sq_nonneg (z : K) : 0 ≤ norm_sq z := add_nonneg (mul_self_nonneg _) (mul_self_nonneg _) @[simp] lemma norm_sq_eq_zero {z : K} : norm_sq z = 0 ↔ z = 0 := by { rw [norm_sq, ←norm_sq_eq_def], simp [pow_two] } @[simp] lemma norm_sq_pos {z : K} : 0 < norm_sq z ↔ z ≠ 0 := by rw [lt_iff_le_and_ne, ne, eq_comm]; simp [norm_sq_nonneg] @[simp] lemma norm_sq_neg (z : K) : norm_sq (-z) = norm_sq z := by simp [norm_sq] @[simp] lemma norm_sq_conj (z : K) : norm_sq (conj z) = norm_sq z := by simp [norm_sq] @[simp] lemma norm_sq_mul (z w : K) : norm_sq (z * w) = norm_sq z * norm_sq w := by simp [norm_sq, pow_two]; ring lemma norm_sq_add (z w : K) : norm_sq (z + w) = norm_sq z + norm_sq w + 2 * (re (z * conj w)) := by simp [norm_sq, pow_two]; ring lemma re_sq_le_norm_sq (z : K) : re z * re z ≤ norm_sq z := le_add_of_nonneg_right (mul_self_nonneg _) lemma im_sq_le_norm_sq (z : K) : im z * im z ≤ norm_sq z := le_add_of_nonneg_left (mul_self_nonneg _) theorem mul_conj (z : K) : z * conj z = 𝓚 (norm_sq z) := by simp [ext_iff, norm_sq, mul_comm, sub_eq_neg_add, add_comm] theorem add_conj (z : K) : z + conj z = 𝓚 (2 * re z) := by simp [ext_iff, two_mul] /-- The pseudo-coercion `of_real` as a `ring_hom`. -/ def of_real_hom : ℝ →+* K := ⟨of_real, of_real_one, of_real_mul, of_real_zero, of_real_add⟩ @[simp] lemma of_real_sub (r s : ℝ) : 𝓚 (r - s : ℝ) = 𝓚 r - 𝓚 s := ext_iff.2 $ by simp @[simp] lemma of_real_pow (r : ℝ) (n : ℕ) : 𝓚 (r ^ n : ℝ) = (𝓚 r) ^ n := by induction n; simp [*, of_real_mul, pow_succ] theorem sub_conj (z : K) : z - conj z = 𝓚 (2 * im z) * I := by simp [ext_iff, two_mul, sub_eq_add_neg, add_mul, mul_im_I_ax] lemma norm_sq_sub (z w : K) : norm_sq (z - w) = norm_sq z + norm_sq w - 2 * re (z * conj w) := by simp [-mul_re, norm_sq_add, add_comm, add_left_comm, sub_eq_add_neg] /-! ### Inversion -/ lemma inv_def {z : K} : z⁻¹ = conj z * of_real ((∥z∥^2)⁻¹) := inv_def_ax z @[simp] lemma inv_re (z : K) : re (z⁻¹) = re z / norm_sq z := by simp [inv_def, norm_sq_eq_def, norm_sq, division_def] @[simp] lemma inv_im (z : K) : im (z⁻¹) = im (-z) / norm_sq z := by simp [inv_def, norm_sq_eq_def, norm_sq, division_def] @[simp] lemma of_real_inv (r : ℝ) : 𝓚 (r⁻¹) = (𝓚 r)⁻¹ := begin rw ext_iff, by_cases r = 0, { simp [h] }, { simp; field_simp [h, norm_sq] }, end protected lemma inv_zero : (0⁻¹ : K) = 0 := by rw [← of_real_zero, ← of_real_inv, inv_zero] protected theorem mul_inv_cancel {z : K} (h : z ≠ 0) : z * z⁻¹ = 1 := by rw [inv_def, ←mul_assoc, mul_conj, ←of_real_mul, ←norm_sq_eq_def', mul_inv_cancel (mt norm_sq_eq_zero.1 h), of_real_one] lemma div_re (z w : K) : re (z / w) = re z * re w / norm_sq w + im z * im w / norm_sq w := by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg] lemma div_im (z w : K) : im (z / w) = im z * re w / norm_sq w - re z * im w / norm_sq w := by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg, add_comm] @[simp] lemma of_real_div (r s : ℝ) : 𝓚 (r / s : ℝ) = 𝓚 r / 𝓚 s := (@is_R_or_C.of_real_hom K _ _ _).map_div r s @[simp] lemma of_real_fpow (r : ℝ) (n : ℤ) : 𝓚 (r ^ n) = (𝓚 r) ^ n := (@is_R_or_C.of_real_hom K _ _ _).map_fpow r n lemma I_mul_I_of_nonzero : (I : K) ≠ 0 → (I : K) * I = -1 := by { have := I_mul_I_ax, tauto } @[simp] lemma div_I (z : K) : z / I = -(z * I) := begin by_cases h : (I : K) = 0, { simp [h] }, { field_simp [h], simp [mul_assoc, I_mul_I_of_nonzero h] } end @[simp] lemma inv_I : (I : K)⁻¹ = -I := by { by_cases h : (I : K) = 0; field_simp [h] } @[simp] lemma norm_sq_inv (z : K) : norm_sq z⁻¹ = (norm_sq z)⁻¹ := begin by_cases z = 0, { simp [h] }, { refine mul_right_cancel' (mt norm_sq_eq_zero.1 h) _, simp [h, ←norm_sq_mul], } end @[simp] lemma norm_sq_div (z w : K) : norm_sq (z / w) = norm_sq z / norm_sq w := by { rw [division_def, norm_sq_mul, norm_sq_inv], refl } /-! ### Cast lemmas -/ @[simp] theorem of_real_nat_cast (n : ℕ) : 𝓚 (n : ℝ) = n := of_real_hom.map_nat_cast n @[simp] lemma nat_cast_re (n : ℕ) : re (n : K) = n := by rw [← of_real_nat_cast, of_real_re] @[simp] lemma nat_cast_im (n : ℕ) : im (n : K) = 0 := by rw [← of_real_nat_cast, of_real_im] @[simp] theorem of_real_int_cast (n : ℤ) : 𝓚 (n : ℝ) = n := of_real_hom.map_int_cast n @[simp] lemma int_cast_re (n : ℤ) : re (n : K) = n := by rw [← of_real_int_cast, of_real_re] @[simp] lemma int_cast_im (n : ℤ) : im (n : K) = 0 := by rw [← of_real_int_cast, of_real_im] @[simp] theorem of_real_rat_cast (n : ℚ) : 𝓚 (n : ℝ) = n := (@is_R_or_C.of_real_hom K _ _ _).map_rat_cast n @[simp] lemma rat_cast_re (q : ℚ) : re (q : K) = q := by rw [← of_real_rat_cast, of_real_re] @[simp] lemma rat_cast_im (q : ℚ) : im (q : K) = 0 := by rw [← of_real_rat_cast, of_real_im] /-! ### Characteristic zero -/ /-- ℝ and ℂ are both of characteristic zero. Note: This is not registered as an instance to avoid having multiple instances on ℝ and ℂ. -/ lemma char_zero_R_or_C : char_zero K := add_group.char_zero_of_inj_zero $ λ n h, by rwa [← of_real_nat_cast, of_real_eq_zero, nat.cast_eq_zero] at h theorem re_eq_add_conj (z : K) : 𝓚 (re z) = (z + conj z) / 2 := by rw [add_conj]; simp; rw [mul_div_cancel_left (𝓚 (re z)) two_ne_zero] /-! ### Absolute value -/ /-- The complex absolute value function, defined as the square root of the norm squared. -/ @[pp_nodot] noncomputable def abs (z : K) : ℝ := (norm_sq z).sqrt local notation `abs'` := _root_.abs local notation `absK` := @abs K _ _ _ @[simp] lemma abs_of_real (r : ℝ) : absK (𝓚 r) = abs' r := by simp [abs, norm_sq, norm_sq_of_real, real.sqrt_mul_self_eq_abs] lemma abs_of_nonneg {r : ℝ} (h : 0 ≤ r) : absK (𝓚 r) = r := (abs_of_real _).trans (abs_of_nonneg h) lemma abs_of_nat (n : ℕ) : absK n = n := by { rw [← of_real_nat_cast], exact abs_of_nonneg (nat.cast_nonneg n) } lemma mul_self_abs (z : K) : abs z * abs z = norm_sq z := real.mul_self_sqrt (norm_sq_nonneg _) @[simp] lemma abs_zero : absK 0 = 0 := by simp [abs] @[simp] lemma abs_one : absK 1 = 1 := by simp [abs] @[simp] lemma abs_two : absK 2 = 2 := calc absK 2 = absK (𝓚 2) : by rw [of_real_bit0, of_real_one] ... = (2 : ℝ) : abs_of_nonneg (by norm_num) lemma abs_nonneg (z : K) : 0 ≤ absK z := real.sqrt_nonneg _ @[simp] lemma abs_eq_zero {z : K} : absK z = 0 ↔ z = 0 := (real.sqrt_eq_zero $ norm_sq_nonneg _).trans norm_sq_eq_zero lemma abs_ne_zero {z : K} : abs z ≠ 0 ↔ z ≠ 0 := not_congr abs_eq_zero @[simp] lemma abs_conj (z : K) : abs (conj z) = abs z := by simp [abs] @[simp] lemma abs_mul (z w : K) : abs (z * w) = abs z * abs w := by rw [abs, norm_sq_mul, real.sqrt_mul (norm_sq_nonneg _)]; refl lemma abs_re_le_abs (z : K) : abs' (re z) ≤ abs z := by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg (re z)) (abs_nonneg _), abs_mul_abs_self, mul_self_abs]; apply re_sq_le_norm_sq lemma abs_im_le_abs (z : K) : abs' (im z) ≤ abs z := by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg (im z)) (abs_nonneg _), abs_mul_abs_self, mul_self_abs]; apply im_sq_le_norm_sq lemma re_le_abs (z : K) : re z ≤ abs z := (abs_le.1 (abs_re_le_abs _)).2 lemma im_le_abs (z : K) : im z ≤ abs z := (abs_le.1 (abs_im_le_abs _)).2 lemma abs_add (z w : K) : abs (z + w) ≤ abs z + abs w := (mul_self_le_mul_self_iff (abs_nonneg _) (add_nonneg (abs_nonneg _) (abs_nonneg _))).2 $ begin rw [mul_self_abs, add_mul_self_eq, mul_self_abs, mul_self_abs, add_right_comm, norm_sq_add, add_le_add_iff_left, mul_assoc, mul_le_mul_left (@two_pos ℝ _)], simpa [-mul_re] using re_le_abs (z * conj w) end instance : is_absolute_value absK := { abv_nonneg := abs_nonneg, abv_eq_zero := λ _, abs_eq_zero, abv_add := abs_add, abv_mul := abs_mul } open is_absolute_value @[simp] lemma abs_abs (z : K) : abs' (abs z) = abs z := _root_.abs_of_nonneg (abs_nonneg _) @[simp] lemma abs_pos {z : K} : 0 < abs z ↔ z ≠ 0 := abv_pos abs @[simp] lemma abs_neg : ∀ z : K, abs (-z) = abs z := abv_neg abs lemma abs_sub : ∀ z w : K, abs (z - w) = abs (w - z) := abv_sub abs lemma abs_sub_le : ∀ a b c : K, abs (a - c) ≤ abs (a - b) + abs (b - c) := abv_sub_le abs @[simp] theorem abs_inv : ∀ z : K, abs z⁻¹ = (abs z)⁻¹ := abv_inv abs @[simp] theorem abs_div : ∀ z w : K, abs (z / w) = abs z / abs w := abv_div abs lemma abs_abs_sub_le_abs_sub : ∀ z w : K, abs' (abs z - abs w) ≤ abs (z - w) := abs_abv_sub_le_abv_sub abs lemma abs_re_div_abs_le_one (z : K) : abs' (re z / abs z) ≤ 1 := begin by_cases hz : z = 0, { simp [hz, zero_le_one] }, { simp_rw [_root_.abs_div, abs_abs, div_le_iff (abs_pos.2 hz), one_mul, abs_re_le_abs] } end lemma abs_im_div_abs_le_one (z : K) : abs' (im z / abs z) ≤ 1 := begin by_cases hz : z = 0, { simp [hz, zero_le_one] }, { simp_rw [_root_.abs_div, abs_abs, div_le_iff (abs_pos.2 hz), one_mul, abs_im_le_abs] } end @[simp] lemma abs_cast_nat (n : ℕ) : abs (n : K) = n := by rw [← of_real_nat_cast, abs_of_nonneg (nat.cast_nonneg n)] lemma norm_sq_eq_abs (x : K) : norm_sq x = abs x ^ 2 := by rw [abs, pow_two, real.mul_self_sqrt (norm_sq_nonneg _)] /-! ### Cauchy sequences -/ theorem is_cau_seq_re (f : cau_seq K abs) : is_cau_seq abs' (λ n, re (f n)) := λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij, lt_of_le_of_lt (by simpa using abs_re_le_abs (f j - f i)) (H _ ij) theorem is_cau_seq_im (f : cau_seq K abs) : is_cau_seq abs' (λ n, im (f n)) := λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij, lt_of_le_of_lt (by simpa using abs_im_le_abs (f j - f i)) (H _ ij) /-- The real part of a K Cauchy sequence, as a real Cauchy sequence. -/ noncomputable def cau_seq_re (f : cau_seq K abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_re f⟩ /-- The imaginary part of a K Cauchy sequence, as a real Cauchy sequence. -/ noncomputable def cau_seq_im (f : cau_seq K abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_im f⟩ lemma is_cau_seq_abs {f : ℕ → K} (hf : is_cau_seq abs f) : is_cau_seq abs' (abs ∘ f) := λ ε ε0, let ⟨i, hi⟩ := hf ε ε0 in ⟨i, λ j hj, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _) (hi j hj)⟩ end is_R_or_C section instances noncomputable instance real.is_R_or_C : is_R_or_C ℝ := { re := add_monoid_hom.id ℝ, im := 0, conj := ring_hom.id ℝ, I := 0, of_real := id, I_re_ax := by simp only [add_monoid_hom.map_zero], I_mul_I_ax := or.intro_left _ rfl, re_add_im_ax := λ z, by unfold_coes; simp [add_zero, id.def, mul_zero], smul_coe_mul_ax := λ z r, by simp only [algebra.id.smul_eq_mul, id.def], of_real_re_ax := λ r, by simp only [id.def, add_monoid_hom.id_apply], of_real_im_ax := λ r, by simp only [add_monoid_hom.zero_apply], mul_re_ax := λ z w, by simp only [sub_zero, mul_zero, add_monoid_hom.zero_apply, add_monoid_hom.id_apply], mul_im_ax := λ z w, by simp only [add_zero, zero_mul, mul_zero, add_monoid_hom.zero_apply], conj_re_ax := λ z, by simp only [ring_hom.id_apply], conj_im_ax := λ z, by simp only [neg_zero, add_monoid_hom.zero_apply], conj_I_ax := by simp only [ring_hom.map_zero, neg_zero], norm_sq_eq_def_ax := λ z, by simp only [pow_two, norm, ←abs_mul, abs_mul_self z, add_zero, mul_zero, add_monoid_hom.zero_apply, add_monoid_hom.id_apply], mul_im_I_ax := λ z, by simp only [mul_zero, add_monoid_hom.zero_apply], inv_def_ax := begin intro z, unfold_coes, have H : z ≠ 0 → 1 / z = z / (z * z) := λ h, calc 1 / z = 1 * (1 / z) : (one_mul (1 / z)).symm ... = (z / z) * (1 / z) : congr_arg (λ x, x * (1 / z)) (div_self h).symm ... = z / (z * z) : by field_simp, rcases lt_trichotomy z 0 with hlt|heq|hgt, { field_simp [norm, abs, max_eq_right_of_lt (show z < -z, by linarith), pow_two, mul_inv', ←H (ne_of_lt hlt)] }, { simp [heq] }, { field_simp [norm, abs, max_eq_left_of_lt (show -z < z, by linarith), pow_two, mul_inv', ←H (ne_of_gt hgt)] }, end, div_I_ax := λ z, by simp only [div_zero, mul_zero, neg_zero]} noncomputable instance complex.is_R_or_C : is_R_or_C ℂ := { re := ⟨complex.re, complex.zero_re, complex.add_re⟩, im := ⟨complex.im, complex.zero_im, complex.add_im⟩, conj := complex.conj, I := complex.I, of_real := coe, I_re_ax := by simp only [add_monoid_hom.coe_mk, complex.I_re], I_mul_I_ax := by simp only [complex.I_mul_I, eq_self_iff_true, or_true], re_add_im_ax := by simp only [forall_const, add_monoid_hom.coe_mk, complex.re_add_im, eq_self_iff_true], smul_coe_mul_ax := λ z r, rfl, of_real_re_ax := λ r, by simp only [add_monoid_hom.coe_mk, complex.of_real_re], of_real_im_ax := λ r, by simp only [add_monoid_hom.coe_mk, complex.of_real_im], mul_re_ax := λ z w, by simp only [complex.mul_re, add_monoid_hom.coe_mk], mul_im_ax := λ z w, by simp only [add_monoid_hom.coe_mk, complex.mul_im], conj_re_ax := λ z, by simp only [ring_hom.coe_mk, add_monoid_hom.coe_mk, complex.conj_re], conj_im_ax := λ z, by simp only [ring_hom.coe_mk, complex.conj_im, add_monoid_hom.coe_mk], conj_I_ax := by simp only [complex.conj_I, ring_hom.coe_mk], norm_sq_eq_def_ax := λ z, by simp only [←complex.norm_sq_eq_abs, ←complex.norm_sq, add_monoid_hom.coe_mk, complex.norm_eq_abs], mul_im_I_ax := λ z, by simp only [mul_one, add_monoid_hom.coe_mk, complex.I_im], inv_def_ax := λ z, by convert complex.inv_def z; exact (complex.norm_sq_eq_abs z).symm, div_I_ax := complex.div_I } end instances namespace is_R_or_C section cleanup_lemmas local notation `reR` := @is_R_or_C.re ℝ _ _ _ local notation `imR` := @is_R_or_C.im ℝ _ _ _ local notation `conjR` := @is_R_or_C.conj ℝ _ _ _ local notation `IR` := @is_R_or_C.I ℝ _ _ _ local notation `of_realR` := @is_R_or_C.of_real ℝ _ _ _ local notation `absR` := @is_R_or_C.abs ℝ _ _ _ local notation `norm_sqR` := @is_R_or_C.norm_sq ℝ _ _ _ local notation `reC` := @is_R_or_C.re ℂ _ _ _ local notation `imC` := @is_R_or_C.im ℂ _ _ _ local notation `conjC` := @is_R_or_C.conj ℂ _ _ _ local notation `IC` := @is_R_or_C.I ℂ _ _ _ local notation `of_realC` := @is_R_or_C.of_real ℂ _ _ _ local notation `absC` := @is_R_or_C.abs ℂ _ _ _ local notation `norm_sqC` := @is_R_or_C.norm_sq ℂ _ _ _ @[simp] lemma re_to_real {x : ℝ} : reR x = x := rfl @[simp] lemma im_to_real {x : ℝ} : imR x = 0 := rfl @[simp] lemma conj_to_real {x : ℝ} : conjR x = x := rfl @[simp] lemma I_to_real : IR = 0 := rfl @[simp] lemma of_real_to_real {x : ℝ} : of_realR x = x := rfl @[simp] lemma norm_sq_to_real {x : ℝ} : norm_sqR x = x*x := by simp [is_R_or_C.norm_sq] @[simp] lemma abs_to_real {x : ℝ} : absR x = _root_.abs x := by simp [is_R_or_C.abs, abs, real.sqrt_mul_self_eq_abs] @[simp] lemma re_to_complex {x : ℂ} : reC x = x.re := rfl @[simp] lemma im_to_complex {x : ℂ} : imC x = x.im := rfl @[simp] lemma conj_to_complex {x : ℂ} : conjC x = x.conj := rfl @[simp] lemma I_to_complex : IC = complex.I := rfl @[simp] lemma of_real_to_complex {x : ℝ} : of_realC x = x := rfl @[simp] lemma norm_sq_to_complex {x : ℂ} : norm_sqC x = complex.norm_sq x := by simp [is_R_or_C.norm_sq, complex.norm_sq] @[simp] lemma abs_to_complex {x : ℂ} : absC x = complex.abs x := by simp [is_R_or_C.abs, complex.abs] end cleanup_lemmas end is_R_or_C
17469e183342f4fd49401b0cb8334d5730a666d2
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/data/nat/prime.lean
89ce3d5085dd3105fdb00ca7bdcd654126c36080
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
23,328
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro -/ import data.nat.sqrt import data.nat.gcd import algebra.group_power import tactic.wlog /-! # Prime numbers This file deals with prime numbers: natural numbers `p ≥ 2` whose only divisors are `p` and `1`. ## Important declarations All the following declarations exist in the namespace `nat`. - `prime`: the predicate that expresses that a natural number `p` is prime - `primes`: the subtype of natural numbers that are prime - `min_fac n`: the minimal prime factor of a natural number `n ≠ 1` - `exists_infinite_primes`: Euclid's theorem that there exist infinitely many prime numbers - `factors n`: the prime factorization of `n` - `factors_unique`: uniqueness of the prime factorisation -/ open bool subtype namespace nat open decidable /-- `prime p` means that `p` is a prime number, that is, a natural number at least 2 whose only divisors are `p` and `1`. -/ @[pp_nodot] def prime (p : ℕ) := 2 ≤ p ∧ ∀ m ∣ p, m = 1 ∨ m = p theorem prime.two_le {p : ℕ} : prime p → 2 ≤ p := and.left theorem prime.one_lt {p : ℕ} : prime p → 1 < p := prime.two_le instance prime.one_lt' (p : ℕ) [hp : _root_.fact p.prime] : _root_.fact (1 < p) := hp.one_lt lemma prime.ne_one {p : ℕ} (hp : p.prime) : p ≠ 1 := ne.symm $ (ne_of_lt hp.one_lt) theorem prime_def_lt {p : ℕ} : prime p ↔ 2 ≤ p ∧ ∀ m < p, m ∣ p → m = 1 := and_congr_right $ λ p2, forall_congr $ λ m, ⟨λ h l d, (h d).resolve_right (ne_of_lt l), λ h d, (decidable.lt_or_eq_of_le $ le_of_dvd (le_of_succ_le p2) d).imp_left (λ l, h l d)⟩ theorem prime_def_lt' {p : ℕ} : prime p ↔ 2 ≤ p ∧ ∀ m, 2 ≤ m → m < p → ¬ m ∣ p := prime_def_lt.trans $ and_congr_right $ λ p2, forall_congr $ λ m, ⟨λ h m2 l d, not_lt_of_ge m2 ((h l d).symm ▸ dec_trivial), λ h l d, begin rcases m with _|_|m, { rw eq_zero_of_zero_dvd d at p2, revert p2, exact dec_trivial }, { refl }, { exact (h dec_trivial l).elim d } end⟩ theorem prime_def_le_sqrt {p : ℕ} : prime p ↔ 2 ≤ p ∧ ∀ m, 2 ≤ m → m ≤ sqrt p → ¬ m ∣ p := prime_def_lt'.trans $ and_congr_right $ λ p2, ⟨λ a m m2 l, a m m2 $ lt_of_le_of_lt l $ sqrt_lt_self p2, λ a, have ∀ {m k}, m ≤ k → 1 < m → p ≠ m * k, from λ m k mk m1 e, a m m1 (le_sqrt.2 (e.symm ▸ mul_le_mul_left m mk)) ⟨k, e⟩, λ m m2 l ⟨k, e⟩, begin cases (le_total m k) with mk km, { exact this mk m2 e }, { rw [mul_comm] at e, refine this km (lt_of_mul_lt_mul_right _ (zero_le m)) e, rwa [one_mul, ← e] } end⟩ /-- This instance is slower than the instance `decidable_prime` defined below, but has the advantage that it works in the kernel. If you need to prove that a particular number is prime, in any case you should not use `dec_trivial`, but rather `by norm_num`, which is much faster. -/ def decidable_prime_1 (p : ℕ) : decidable (prime p) := decidable_of_iff' _ prime_def_lt' local attribute [instance] decidable_prime_1 lemma prime.ne_zero {n : ℕ} (h : prime n) : n ≠ 0 := assume hn : n = 0, have h2 : ¬ prime 0, from dec_trivial, h2 (hn ▸ h) theorem prime.pos {p : ℕ} (pp : prime p) : 0 < p := lt_of_succ_lt pp.one_lt theorem not_prime_zero : ¬ prime 0 := dec_trivial theorem not_prime_one : ¬ prime 1 := dec_trivial theorem prime_two : prime 2 := dec_trivial theorem prime_three : prime 3 := dec_trivial theorem prime.pred_pos {p : ℕ} (pp : prime p) : 0 < pred p := lt_pred_iff.2 pp.one_lt theorem succ_pred_prime {p : ℕ} (pp : prime p) : succ (pred p) = p := succ_pred_eq_of_pos pp.pos theorem dvd_prime {p m : ℕ} (pp : prime p) : m ∣ p ↔ m = 1 ∨ m = p := ⟨λ d, pp.2 m d, λ h, h.elim (λ e, e.symm ▸ one_dvd _) (λ e, e.symm ▸ dvd_refl _)⟩ theorem dvd_prime_two_le {p m : ℕ} (pp : prime p) (H : 2 ≤ m) : m ∣ p ↔ m = p := (dvd_prime pp).trans $ or_iff_right_of_imp $ not.elim $ ne_of_gt H theorem prime_dvd_prime_iff_eq {p q : ℕ} (pp : p.prime) (qp : q.prime) : p ∣ q ↔ p = q := dvd_prime_two_le qp (prime.two_le pp) theorem prime.not_dvd_one {p : ℕ} (pp : prime p) : ¬ p ∣ 1 | d := (not_le_of_gt pp.one_lt) $ le_of_dvd dec_trivial d theorem not_prime_mul {a b : ℕ} (a1 : 1 < a) (b1 : 1 < b) : ¬ prime (a * b) := λ h, ne_of_lt (nat.mul_lt_mul_of_pos_left b1 (lt_of_succ_lt a1)) $ by simpa using (dvd_prime_two_le h a1).1 (dvd_mul_right _ _) section min_fac private lemma min_fac_lemma (n k : ℕ) (h : ¬ n < k * k) : sqrt n - k < sqrt n + 2 - k := (nat.sub_lt_sub_right_iff $ le_sqrt.2 $ le_of_not_gt h).2 $ nat.lt_add_of_pos_right dec_trivial def min_fac_aux (n : ℕ) : ℕ → ℕ | k := if h : n < k * k then n else if k ∣ n then k else have _, from min_fac_lemma n k h, min_fac_aux (k + 2) using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ k, sqrt n + 2 - k)⟩]} /-- Returns the smallest prime factor of `n ≠ 1`. -/ def min_fac : ℕ → ℕ | 0 := 2 | 1 := 1 | (n+2) := if 2 ∣ n then 2 else min_fac_aux (n + 2) 3 @[simp] theorem min_fac_zero : min_fac 0 = 2 := rfl @[simp] theorem min_fac_one : min_fac 1 = 1 := rfl theorem min_fac_eq : ∀ n, min_fac n = if 2 ∣ n then 2 else min_fac_aux n 3 | 0 := rfl | 1 := by simp [show 2≠1, from dec_trivial]; rw min_fac_aux; refl | (n+2) := have 2 ∣ n + 2 ↔ 2 ∣ n, from (nat.dvd_add_iff_left (by refl)).symm, by simp [min_fac, this]; congr private def min_fac_prop (n k : ℕ) := 2 ≤ k ∧ k ∣ n ∧ ∀ m, 2 ≤ m → m ∣ n → k ≤ m theorem min_fac_aux_has_prop {n : ℕ} (n2 : 2 ≤ n) (nd2 : ¬ 2 ∣ n) : ∀ k i, k = 2*i+3 → (∀ m, 2 ≤ m → m ∣ n → k ≤ m) → min_fac_prop n (min_fac_aux n k) | k := λ i e a, begin rw min_fac_aux, by_cases h : n < k*k; simp [h], { have pp : prime n := prime_def_le_sqrt.2 ⟨n2, λ m m2 l d, not_lt_of_ge l $ lt_of_lt_of_le (sqrt_lt.2 h) (a m m2 d)⟩, from ⟨n2, dvd_refl _, λ m m2 d, le_of_eq ((dvd_prime_two_le pp m2).1 d).symm⟩ }, have k2 : 2 ≤ k, { subst e, exact dec_trivial }, by_cases dk : k ∣ n; simp [dk], { exact ⟨k2, dk, a⟩ }, { refine have _, from min_fac_lemma n k h, min_fac_aux_has_prop (k+2) (i+1) (by simp [e, left_distrib]) (λ m m2 d, _), cases nat.eq_or_lt_of_le (a m m2 d) with me ml, { subst me, contradiction }, apply (nat.eq_or_lt_of_le ml).resolve_left, intro me, rw [← me, e] at d, change 2 * (i + 2) ∣ n at d, have := dvd_of_mul_right_dvd d, contradiction } end using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ k, sqrt n + 2 - k)⟩]} theorem min_fac_has_prop {n : ℕ} (n1 : n ≠ 1) : min_fac_prop n (min_fac n) := begin by_cases n0 : n = 0, {simp [n0, min_fac_prop, ge]}, have n2 : 2 ≤ n, { revert n0 n1, rcases n with _|_|_; exact dec_trivial }, simp [min_fac_eq], by_cases d2 : 2 ∣ n; simp [d2], { exact ⟨le_refl _, d2, λ k k2 d, k2⟩ }, { refine min_fac_aux_has_prop n2 d2 3 0 rfl (λ m m2 d, (nat.eq_or_lt_of_le m2).resolve_left (mt _ d2)), exact λ e, e.symm ▸ d } end theorem min_fac_dvd (n : ℕ) : min_fac n ∣ n := by by_cases n1 : n = 1; [exact n1.symm ▸ dec_trivial, exact (min_fac_has_prop n1).2.1] theorem min_fac_prime {n : ℕ} (n1 : n ≠ 1) : prime (min_fac n) := let ⟨f2, fd, a⟩ := min_fac_has_prop n1 in prime_def_lt'.2 ⟨f2, λ m m2 l d, not_le_of_gt l (a m m2 (dvd_trans d fd))⟩ theorem min_fac_le_of_dvd {n : ℕ} : ∀ {m : ℕ}, 2 ≤ m → m ∣ n → min_fac n ≤ m := by by_cases n1 : n = 1; [exact λ m m2 d, n1.symm ▸ le_trans dec_trivial m2, exact (min_fac_has_prop n1).2.2] theorem min_fac_pos (n : ℕ) : 0 < min_fac n := by by_cases n1 : n = 1; [exact n1.symm ▸ dec_trivial, exact (min_fac_prime n1).pos] theorem min_fac_le {n : ℕ} (H : 0 < n) : min_fac n ≤ n := le_of_dvd H (min_fac_dvd n) theorem prime_def_min_fac {p : ℕ} : prime p ↔ 2 ≤ p ∧ min_fac p = p := ⟨λ pp, ⟨pp.two_le, let ⟨f2, fd, a⟩ := min_fac_has_prop $ ne_of_gt pp.one_lt in ((dvd_prime pp).1 fd).resolve_left (ne_of_gt f2)⟩, λ ⟨p2, e⟩, e ▸ min_fac_prime (ne_of_gt p2)⟩ /-- This instance is faster in the virtual machine than `decidable_prime_1`, but slower in the kernel. If you need to prove that a particular number is prime, in any case you should not use `dec_trivial`, but rather `by norm_num`, which is much faster. -/ instance decidable_prime (p : ℕ) : decidable (prime p) := decidable_of_iff' _ prime_def_min_fac theorem not_prime_iff_min_fac_lt {n : ℕ} (n2 : 2 ≤ n) : ¬ prime n ↔ min_fac n < n := (not_congr $ prime_def_min_fac.trans $ and_iff_right n2).trans $ (lt_iff_le_and_ne.trans $ and_iff_right $ min_fac_le $ le_of_succ_le n2).symm lemma min_fac_le_div {n : ℕ} (pos : 0 < n) (np : ¬ prime n) : min_fac n ≤ n / min_fac n := match min_fac_dvd n with | ⟨0, h0⟩ := absurd pos $ by rw [h0, mul_zero]; exact dec_trivial | ⟨1, h1⟩ := begin rw mul_one at h1, rw [prime_def_min_fac, not_and_distrib, ← h1, eq_self_iff_true, not_true, or_false, not_le] at np, rw [le_antisymm (le_of_lt_succ np) (succ_le_of_lt pos), min_fac_one, nat.div_one] end | ⟨(x+2), hx⟩ := begin conv_rhs { congr, rw hx }, rw [nat.mul_div_cancel_left _ (min_fac_pos _)], exact min_fac_le_of_dvd dec_trivial ⟨min_fac n, by rwa mul_comm⟩ end end /-- The square of the smallest prime factor of a composite number `n` is at most `n`. -/ lemma min_fac_sq_le_self {n : ℕ} (w : 0 < n) (h : ¬ prime n) : (min_fac n)^2 ≤ n := have t : (min_fac n) ≤ (n/min_fac n) := min_fac_le_div w h, calc (min_fac n)^2 = (min_fac n) * (min_fac n) : pow_two (min_fac n) ... ≤ (n/min_fac n) * (min_fac n) : mul_le_mul_right (min_fac n) t ... ≤ n : div_mul_le_self n (min_fac n) @[simp] lemma min_fac_eq_one_iff {n : ℕ} : min_fac n = 1 ↔ n = 1 := begin split, { intro h, by_contradiction, have := min_fac_prime a, rw h at this, exact not_prime_one this, }, { rintro rfl, refl, } end @[simp] lemma min_fac_eq_two_iff (n : ℕ) : min_fac n = 2 ↔ 2 ∣ n := begin split, { intro h, convert min_fac_dvd _, rw h, }, { intro h, have ub := min_fac_le_of_dvd (le_refl 2) h, have lb := min_fac_pos n, -- If `interval_cases` and `norm_num` were already available here, -- this would be easy and pleasant. -- But they aren't, so it isn't. cases h : n.min_fac with m, { rw h at lb, cases lb, }, { cases m with m, { simp at h, subst h, cases h with n h, cases n; cases h, }, { cases m with m, { refl, }, { rw h at ub, cases ub with _ ub, cases ub with _ ub, cases ub, } } } } end end min_fac theorem exists_dvd_of_not_prime {n : ℕ} (n2 : 2 ≤ n) (np : ¬ prime n) : ∃ m, m ∣ n ∧ m ≠ 1 ∧ m ≠ n := ⟨min_fac n, min_fac_dvd _, ne_of_gt (min_fac_prime (ne_of_gt n2)).one_lt, ne_of_lt $ (not_prime_iff_min_fac_lt n2).1 np⟩ theorem exists_dvd_of_not_prime2 {n : ℕ} (n2 : 2 ≤ n) (np : ¬ prime n) : ∃ m, m ∣ n ∧ 2 ≤ m ∧ m < n := ⟨min_fac n, min_fac_dvd _, (min_fac_prime (ne_of_gt n2)).two_le, (not_prime_iff_min_fac_lt n2).1 np⟩ theorem exists_prime_and_dvd {n : ℕ} (n2 : 2 ≤ n) : ∃ p, prime p ∧ p ∣ n := ⟨min_fac n, min_fac_prime (ne_of_gt n2), min_fac_dvd _⟩ /-- Euclid's theorem. There exist infinitely many prime numbers. Here given in the form: for every `n`, there exists a prime number `p ≥ n`. -/ theorem exists_infinite_primes (n : ℕ) : ∃ p, n ≤ p ∧ prime p := let p := min_fac (fact n + 1) in have f1 : fact n + 1 ≠ 1, from ne_of_gt $ succ_lt_succ $ fact_pos _, have pp : prime p, from min_fac_prime f1, have np : n ≤ p, from le_of_not_ge $ λ h, have h₁ : p ∣ fact n, from dvd_fact (min_fac_pos _) h, have h₂ : p ∣ 1, from (nat.dvd_add_iff_right h₁).2 (min_fac_dvd _), pp.not_dvd_one h₂, ⟨p, np, pp⟩ lemma prime.eq_two_or_odd {p : ℕ} (hp : prime p) : p = 2 ∨ p % 2 = 1 := (nat.mod_two_eq_zero_or_one p).elim (λ h, or.inl ((hp.2 2 (dvd_of_mod_eq_zero h)).resolve_left dec_trivial).symm) or.inr theorem factors_lemma {k} : (k+2) / min_fac (k+2) < k+2 := div_lt_self dec_trivial (min_fac_prime dec_trivial).one_lt /-- `factors n` is the prime factorization of `n`, listed in increasing order. -/ def factors : ℕ → list ℕ | 0 := [] | 1 := [] | n@(k+2) := let m := min_fac n in have n / m < n := factors_lemma, m :: factors (n / m) lemma mem_factors : ∀ {n p}, p ∈ factors n → prime p | 0 := λ p, false.elim | 1 := λ p, false.elim | n@(k+2) := λ p h, let m := min_fac n in have n / m < n := factors_lemma, have h₁ : p = m ∨ p ∈ (factors (n / m)) := (list.mem_cons_iff _ _ _).1 h, or.cases_on h₁ (λ h₂, h₂.symm ▸ min_fac_prime dec_trivial) mem_factors lemma prod_factors : ∀ {n}, 0 < n → list.prod (factors n) = n | 0 := (lt_irrefl _).elim | 1 := λ h, rfl | n@(k+2) := λ h, let m := min_fac n in have n / m < n := factors_lemma, show list.prod (m :: factors (n / m)) = n, from have h₁ : 0 < n / m := nat.pos_of_ne_zero $ λ h, have n = 0 * m := (nat.div_eq_iff_eq_mul_left (min_fac_pos _) (min_fac_dvd _)).1 h, by rw zero_mul at this; exact (show k + 2 ≠ 0, from dec_trivial) this, by rw [list.prod_cons, prod_factors h₁, nat.mul_div_cancel' (min_fac_dvd _)] lemma factors_prime {p : ℕ} (hp : nat.prime p) : p.factors = [p] := begin have : p = (p - 2) + 2 := (nat.sub_eq_iff_eq_add hp.1).mp rfl, rw [this, nat.factors], simp only [eq.symm this], have : nat.min_fac p = p := (nat.prime_def_min_fac.mp hp).2, split, { exact this, }, { simp only [this, nat.factors, nat.div_self (nat.prime.pos hp)], }, end /-- `factors` can be constructed inductively by extracting `min_fac`, for sufficiently large `n`. -/ lemma factors_add_two (n : ℕ) : factors (n+2) = (min_fac (n+2)) :: (factors ((n+2) / (min_fac (n+2)))) := rfl theorem prime.coprime_iff_not_dvd {p n : ℕ} (pp : prime p) : coprime p n ↔ ¬ p ∣ n := ⟨λ co d, pp.not_dvd_one $ co.dvd_of_dvd_mul_left (by simp [d]), λ nd, coprime_of_dvd $ λ m m2 mp, ((dvd_prime_two_le pp m2).1 mp).symm ▸ nd⟩ theorem prime.dvd_iff_not_coprime {p n : ℕ} (pp : prime p) : p ∣ n ↔ ¬ coprime p n := iff_not_comm.2 pp.coprime_iff_not_dvd theorem prime.not_coprime_iff_dvd {m n : ℕ} : ¬ coprime m n ↔ ∃p, prime p ∧ p ∣ m ∧ p ∣ n := begin apply iff.intro, { intro h, exact ⟨min_fac (gcd m n), min_fac_prime h, (dvd.trans (min_fac_dvd (gcd m n)) (gcd_dvd_left m n)), (dvd.trans (min_fac_dvd (gcd m n)) (gcd_dvd_right m n))⟩ }, { intro h, cases h with p hp, apply nat.not_coprime_of_dvd_of_dvd (prime.one_lt hp.1) hp.2.1 hp.2.2 } end theorem prime.dvd_mul {p m n : ℕ} (pp : prime p) : p ∣ m * n ↔ p ∣ m ∨ p ∣ n := ⟨λ H, or_iff_not_imp_left.2 $ λ h, (pp.coprime_iff_not_dvd.2 h).dvd_of_dvd_mul_left H, or.rec (λ h, dvd_mul_of_dvd_left h _) (λ h, dvd_mul_of_dvd_right h _)⟩ theorem prime.not_dvd_mul {p m n : ℕ} (pp : prime p) (Hm : ¬ p ∣ m) (Hn : ¬ p ∣ n) : ¬ p ∣ m * n := mt pp.dvd_mul.1 $ by simp [Hm, Hn] theorem prime.dvd_of_dvd_pow {p m n : ℕ} (pp : prime p) (h : p ∣ m^n) : p ∣ m := by induction n with n IH; [exact pp.not_dvd_one.elim h, exact (pp.dvd_mul.1 h).elim IH id] lemma prime.pow_not_prime {x n : ℕ} (hn : 2 ≤ n) : ¬ (x ^ n).prime := λ hp, (hp.2 x $ dvd_trans ⟨x, nat.pow_two _⟩ (nat.pow_dvd_pow _ hn)).elim (λ hx1, hp.ne_one $ hx1.symm ▸ nat.one_pow _) (λ hxn, lt_irrefl x $ calc x = x ^ 1 : (nat.pow_one _).symm ... < x ^ n : nat.pow_right_strict_mono (hxn.symm ▸ hp.two_le) hn ... = x : hxn.symm) lemma prime.mul_eq_prime_pow_two_iff {x y p : ℕ} (hp : p.prime) (hx : x ≠ 1) (hy : y ≠ 1) : x * y = p ^ 2 ↔ x = p ∧ y = p := ⟨λ h, have pdvdxy : p ∣ x * y, by rw h; simp [nat.pow_two], begin wlog := hp.dvd_mul.1 pdvdxy using x y, cases case with a ha, have hap : a ∣ p, from ⟨y, by rwa [ha, nat.pow_two, mul_assoc, nat.mul_right_inj hp.pos, eq_comm] at h⟩, exact ((nat.dvd_prime hp).1 hap).elim (λ _, by clear_aux_decl; simp [*, nat.pow_two, nat.mul_right_inj hp.pos] at * {contextual := tt}) (λ _, by clear_aux_decl; simp [*, nat.pow_two, mul_comm, mul_assoc, nat.mul_right_inj hp.pos, nat.mul_right_eq_self_iff hp.pos] at * {contextual := tt}) end, λ ⟨h₁, h₂⟩, h₁.symm ▸ h₂.symm ▸ (nat.pow_two _).symm⟩ lemma prime.dvd_fact : ∀ {n p : ℕ} (hp : prime p), p ∣ n.fact ↔ p ≤ n | 0 p hp := iff_of_false hp.not_dvd_one (not_le_of_lt hp.pos) | (n+1) p hp := begin rw [fact_succ, hp.dvd_mul, prime.dvd_fact hp], exact ⟨λ h, h.elim (le_of_dvd (succ_pos _)) le_succ_of_le, λ h, (_root_.lt_or_eq_of_le h).elim (or.inr ∘ le_of_lt_succ) (λ h, or.inl $ by rw h)⟩ end theorem prime.coprime_pow_of_not_dvd {p m a : ℕ} (pp : prime p) (h : ¬ p ∣ a) : coprime a (p^m) := (pp.coprime_iff_not_dvd.2 h).symm.pow_right _ theorem coprime_primes {p q : ℕ} (pp : prime p) (pq : prime q) : coprime p q ↔ p ≠ q := pp.coprime_iff_not_dvd.trans $ not_congr $ dvd_prime_two_le pq pp.two_le theorem coprime_pow_primes {p q : ℕ} (n m : ℕ) (pp : prime p) (pq : prime q) (h : p ≠ q) : coprime (p^n) (q^m) := ((coprime_primes pp pq).2 h).pow _ _ theorem coprime_or_dvd_of_prime {p} (pp : prime p) (i : ℕ) : coprime p i ∨ p ∣ i := by rw [pp.dvd_iff_not_coprime]; apply em theorem dvd_prime_pow {p : ℕ} (pp : prime p) {m i : ℕ} : i ∣ (p^m) ↔ ∃ k ≤ m, i = p^k := begin induction m with m IH generalizing i, {simp [pow_succ, le_zero_iff] at *}, by_cases p ∣ i, { cases h with a e, subst e, rw [nat.pow_succ, mul_comm (p^m) p, nat.mul_dvd_mul_iff_left pp.pos, IH], split; intro h; rcases h with ⟨k, h, e⟩, { exact ⟨succ k, succ_le_succ h, by rw [mul_comm, e]; refl⟩ }, cases k with k, { apply pp.not_dvd_one.elim, simp at e, rw ← e, apply dvd_mul_right }, { refine ⟨k, le_of_succ_le_succ h, _⟩, rwa [mul_comm, nat.pow_succ, nat.mul_left_inj pp.pos] at e } }, { split; intro d, { rw (pp.coprime_pow_of_not_dvd h).eq_one_of_dvd d, exact ⟨0, zero_le _, rfl⟩ }, { rcases d with ⟨k, l, e⟩, rw e, exact pow_dvd_pow _ l } } end /-- If `p` is prime, and `a` doesn't divide `p^k`, but `a` does divide `p^(k+1)` then `a = p^(k+1)`. -/ lemma eq_prime_pow_of_dvd_least_prime_pow {a p k : ℕ} (pp : prime p) (h₁ : ¬(a ∣ p^k)) (h₂ : a ∣ p^(k+1)) : a = p^(k+1) := begin obtain ⟨l, ⟨h, rfl⟩⟩ := (dvd_prime_pow pp).1 h₂, congr, exact le_antisymm h (not_le.1 ((not_congr (pow_dvd_pow_iff_le_right (prime.one_lt pp))).1 h₁)), end section open list lemma mem_list_primes_of_dvd_prod {p : ℕ} (hp : prime p) : ∀ {l : list ℕ}, (∀ p ∈ l, prime p) → p ∣ prod l → p ∈ l | [] := λ h₁ h₂, absurd h₂ (prime.not_dvd_one hp) | (q :: l) := λ h₁ h₂, have h₃ : p ∣ q * prod l := @prod_cons _ _ l q ▸ h₂, have hq : prime q := h₁ q (mem_cons_self _ _), or.cases_on ((prime.dvd_mul hp).1 h₃) (λ h, by rw [prime.dvd_iff_not_coprime hp, coprime_primes hp hq, ne.def, not_not] at h; exact h ▸ mem_cons_self _ _) (λ h, have hl : ∀ p ∈ l, prime p := λ p hlp, h₁ p ((mem_cons_iff _ _ _).2 (or.inr hlp)), (mem_cons_iff _ _ _).2 (or.inr (mem_list_primes_of_dvd_prod hl h))) lemma mem_factors_iff_dvd {n p : ℕ} (hn : 0 < n) (hp : prime p) : p ∈ factors n ↔ p ∣ n := ⟨λ h, prod_factors hn ▸ list.dvd_prod h, λ h, mem_list_primes_of_dvd_prod hp (@mem_factors n) ((prod_factors hn).symm ▸ h)⟩ lemma perm_of_prod_eq_prod : ∀ {l₁ l₂ : list ℕ}, prod l₁ = prod l₂ → (∀ p ∈ l₁, prime p) → (∀ p ∈ l₂, prime p) → l₁ ~ l₂ | [] [] _ _ _ := perm.nil | [] (a :: l) h₁ h₂ h₃ := have ha : a ∣ 1 := @prod_nil ℕ _ ▸ h₁.symm ▸ (@prod_cons _ _ l a).symm ▸ dvd_mul_right _ _, absurd ha (prime.not_dvd_one (h₃ a (mem_cons_self _ _))) | (a :: l) [] h₁ h₂ h₃ := have ha : a ∣ 1 := @prod_nil ℕ _ ▸ h₁ ▸ (@prod_cons _ _ l a).symm ▸ dvd_mul_right _ _, absurd ha (prime.not_dvd_one (h₂ a (mem_cons_self _ _))) | (a :: l₁) (b :: l₂) h hl₁ hl₂ := have hl₁' : ∀ p ∈ l₁, prime p := λ p hp, hl₁ p (mem_cons_of_mem _ hp), have hl₂' : ∀ p ∈ (b :: l₂).erase a, prime p := λ p hp, hl₂ p (mem_of_mem_erase hp), have ha : a ∈ (b :: l₂) := mem_list_primes_of_dvd_prod (hl₁ a (mem_cons_self _ _)) hl₂ (h ▸ by rw prod_cons; exact dvd_mul_right _ _), have hb : b :: l₂ ~ a :: (b :: l₂).erase a := perm_cons_erase ha, have hl : prod l₁ = prod ((b :: l₂).erase a) := (nat.mul_right_inj (prime.pos (hl₁ a (mem_cons_self _ _)))).1 $ by rwa [← prod_cons, ← prod_cons, ← hb.prod_eq], perm.trans ((perm_of_prod_eq_prod hl hl₁' hl₂').cons _) hb.symm lemma factors_unique {n : ℕ} {l : list ℕ} (h₁ : prod l = n) (h₂ : ∀ p ∈ l, prime p) : l ~ factors n := have hn : 0 < n := nat.pos_of_ne_zero $ λ h, begin rw h at *, clear h, induction l with a l hi, { exact absurd h₁ dec_trivial }, { rw prod_cons at h₁, exact nat.mul_ne_zero (ne_of_lt (prime.pos (h₂ a (mem_cons_self _ _)))).symm (hi (λ p hp, h₂ p (mem_cons_of_mem _ hp))) h₁ } end, perm_of_prod_eq_prod (by rwa prod_factors hn) h₂ (@mem_factors _) end lemma succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul {p : ℕ} (p_prime : prime p) {m n k l : ℕ} (hpm : p ^ k ∣ m) (hpn : p ^ l ∣ n) (hpmn : p ^ (k+l+1) ∣ m*n) : p ^ (k+1) ∣ m ∨ p ^ (l+1) ∣ n := have hpd : p^(k+l) * p ∣ m*n, from hpmn, have hpd2 : p ∣ (m*n) / p ^ (k+l), from dvd_div_of_mul_dvd hpd, have hpd3 : p ∣ (m*n) / (p^k * p^l), by simpa [nat.pow_add] using hpd2, have hpd4 : p ∣ (m / p^k) * (n / p^l), by simpa [nat.div_mul_div hpm hpn] using hpd3, have hpd5 : p ∣ (m / p^k) ∨ p ∣ (n / p^l), from (prime.dvd_mul p_prime).1 hpd4, show p^k*p ∣ m ∨ p^l*p ∣ n, from hpd5.elim (assume : p ∣ m / p ^ k, or.inl $ mul_dvd_of_dvd_div hpm this) (assume : p ∣ n / p ^ l, or.inr $ mul_dvd_of_dvd_div hpn this) /-- The type of prime numbers -/ def primes := {p : ℕ // p.prime} namespace primes instance : has_repr nat.primes := ⟨λ p, repr p.val⟩ instance : inhabited primes := ⟨⟨2, prime_two⟩⟩ instance coe_nat : has_coe nat.primes ℕ := ⟨subtype.val⟩ theorem coe_nat_inj (p q : nat.primes) : (p : ℕ) = (q : ℕ) → p = q := λ h, subtype.eq h end primes instance monoid.prime_pow {α : Type*} [monoid α] : has_pow α primes := ⟨λ x p, x^p.val⟩ end nat
774abd556770b37bf3b5676538df68129699a7d4
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/metric_space/shrinking_lemma.lean
c0520d2a86de26446cf4d404a45a2d66fc497878
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
6,437
lean
/- Copyright (c) 2021 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import topology.metric_space.basic import topology.metric_space.emetric_paracompact import topology.shrinking_lemma /-! # Shrinking lemma in a proper metric space > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we prove a few versions of the shrinking lemma for coverings by balls in a proper (pseudo) metric space. ## Tags shrinking lemma, metric space -/ universes u v open set metric open_locale topology variables {α : Type u} {ι : Type v} [metric_space α] [proper_space α] {c : ι → α} variables {x : α} {r : ℝ} {s : set α} /-- Shrinking lemma for coverings by open balls in a proper metric space. A point-finite open cover of a closed subset of a proper metric space by open balls can be shrunk to a new cover by open balls so that each of the new balls has strictly smaller radius than the old one. This version assumes that `λ x, ball (c i) (r i)` is a locally finite covering and provides a covering indexed by the same type. -/ lemma exists_subset_Union_ball_radius_lt {r : ι → ℝ} (hs : is_closed s) (uf : ∀ x ∈ s, {i | x ∈ ball (c i) (r i)}.finite) (us : s ⊆ ⋃ i, ball (c i) (r i)) : ∃ r' : ι → ℝ, s ⊆ (⋃ i, ball (c i) (r' i)) ∧ ∀ i, r' i < r i := begin rcases exists_subset_Union_closed_subset hs (λ i, @is_open_ball _ _ (c i) (r i)) uf us with ⟨v, hsv, hvc, hcv⟩, have := λ i, exists_lt_subset_ball (hvc i) (hcv i), choose r' hlt hsub, exact ⟨r', hsv.trans $ Union_mono $ hsub, hlt⟩ end /-- Shrinking lemma for coverings by open balls in a proper metric space. A point-finite open cover of a proper metric space by open balls can be shrunk to a new cover by open balls so that each of the new balls has strictly smaller radius than the old one. -/ lemma exists_Union_ball_eq_radius_lt {r : ι → ℝ} (uf : ∀ x, {i | x ∈ ball (c i) (r i)}.finite) (uU : (⋃ i, ball (c i) (r i)) = univ) : ∃ r' : ι → ℝ, (⋃ i, ball (c i) (r' i)) = univ ∧ ∀ i, r' i < r i := let ⟨r', hU, hv⟩ := exists_subset_Union_ball_radius_lt is_closed_univ (λ x _, uf x) uU.ge in ⟨r', univ_subset_iff.1 hU, hv⟩ /-- Shrinking lemma for coverings by open balls in a proper metric space. A point-finite open cover of a closed subset of a proper metric space by nonempty open balls can be shrunk to a new cover by nonempty open balls so that each of the new balls has strictly smaller radius than the old one. -/ lemma exists_subset_Union_ball_radius_pos_lt {r : ι → ℝ} (hr : ∀ i, 0 < r i) (hs : is_closed s) (uf : ∀ x ∈ s, {i | x ∈ ball (c i) (r i)}.finite) (us : s ⊆ ⋃ i, ball (c i) (r i)) : ∃ r' : ι → ℝ, s ⊆ (⋃ i, ball (c i) (r' i)) ∧ ∀ i, r' i ∈ Ioo 0 (r i) := begin rcases exists_subset_Union_closed_subset hs (λ i, @is_open_ball _ _ (c i) (r i)) uf us with ⟨v, hsv, hvc, hcv⟩, have := λ i, exists_pos_lt_subset_ball (hr i) (hvc i) (hcv i), choose r' hlt hsub, exact ⟨r', hsv.trans $ Union_mono hsub, hlt⟩ end /-- Shrinking lemma for coverings by open balls in a proper metric space. A point-finite open cover of a proper metric space by nonempty open balls can be shrunk to a new cover by nonempty open balls so that each of the new balls has strictly smaller radius than the old one. -/ lemma exists_Union_ball_eq_radius_pos_lt {r : ι → ℝ} (hr : ∀ i, 0 < r i) (uf : ∀ x, {i | x ∈ ball (c i) (r i)}.finite) (uU : (⋃ i, ball (c i) (r i)) = univ) : ∃ r' : ι → ℝ, (⋃ i, ball (c i) (r' i)) = univ ∧ ∀ i, r' i ∈ Ioo 0 (r i) := let ⟨r', hU, hv⟩ := exists_subset_Union_ball_radius_pos_lt hr is_closed_univ (λ x _, uf x) uU.ge in ⟨r', univ_subset_iff.1 hU, hv⟩ /-- Let `R : α → ℝ` be a (possibly discontinuous) function on a proper metric space. Let `s` be a closed set in `α` such that `R` is positive on `s`. Then there exists a collection of pairs of balls `metric.ball (c i) (r i)`, `metric.ball (c i) (r' i)` such that * all centers belong to `s`; * for all `i` we have `0 < r i < r' i < R (c i)`; * the family of balls `metric.ball (c i) (r' i)` is locally finite; * the balls `metric.ball (c i) (r i)` cover `s`. This is a simple corollary of `refinement_of_locally_compact_sigma_compact_of_nhds_basis_set` and `exists_subset_Union_ball_radius_pos_lt`. -/ lemma exists_locally_finite_subset_Union_ball_radius_lt (hs : is_closed s) {R : α → ℝ} (hR : ∀ x ∈ s, 0 < R x) : ∃ (ι : Type u) (c : ι → α) (r r' : ι → ℝ), (∀ i, c i ∈ s ∧ 0 < r i ∧ r i < r' i ∧ r' i < R (c i)) ∧ locally_finite (λ i, ball (c i) (r' i)) ∧ s ⊆ ⋃ i, ball (c i) (r i) := begin have : ∀ x ∈ s, (𝓝 x).has_basis (λ r : ℝ, 0 < r ∧ r < R x) (λ r, ball x r), from λ x hx, nhds_basis_uniformity (uniformity_basis_dist_lt (hR x hx)), rcases refinement_of_locally_compact_sigma_compact_of_nhds_basis_set hs this with ⟨ι, c, r', hr', hsub', hfin⟩, rcases exists_subset_Union_ball_radius_pos_lt (λ i, (hr' i).2.1) hs (λ x hx, hfin.point_finite x) hsub' with ⟨r, hsub, hlt⟩, exact ⟨ι, c, r, r', λ i, ⟨(hr' i).1, (hlt i).1, (hlt i).2, (hr' i).2.2⟩, hfin, hsub⟩ end /-- Let `R : α → ℝ` be a (possibly discontinuous) positive function on a proper metric space. Then there exists a collection of pairs of balls `metric.ball (c i) (r i)`, `metric.ball (c i) (r' i)` such that * for all `i` we have `0 < r i < r' i < R (c i)`; * the family of balls `metric.ball (c i) (r' i)` is locally finite; * the balls `metric.ball (c i) (r i)` cover the whole space. This is a simple corollary of `refinement_of_locally_compact_sigma_compact_of_nhds_basis` and `exists_Union_ball_eq_radius_pos_lt` or `exists_locally_finite_subset_Union_ball_radius_lt`. -/ lemma exists_locally_finite_Union_eq_ball_radius_lt {R : α → ℝ} (hR : ∀ x, 0 < R x) : ∃ (ι : Type u) (c : ι → α) (r r' : ι → ℝ), (∀ i, 0 < r i ∧ r i < r' i ∧ r' i < R (c i)) ∧ locally_finite (λ i, ball (c i) (r' i)) ∧ (⋃ i, ball (c i) (r i)) = univ := let ⟨ι, c, r, r', hlt, hfin, hsub⟩ := exists_locally_finite_subset_Union_ball_radius_lt is_closed_univ (λ x _, hR x) in ⟨ι, c, r, r', λ i, (hlt i).2, hfin, univ_subset_iff.1 hsub⟩
29e370461d34a3e09b385eda6e51d4f01ceb5969
f3849be5d845a1cb97680f0bbbe03b85518312f0
/tests/lean/notation6.lean
e28228d8669a08cd1f16d7b1a8b32058553318c1
[ "Apache-2.0" ]
permissive
bjoeris/lean
0ed95125d762b17bfcb54dad1f9721f953f92eeb
4e496b78d5e73545fa4f9a807155113d8e6b0561
refs/heads/master
1,611,251,218,281
1,495,337,658,000
1,495,337,658,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
136
lean
-- open num notation `o` := (10:num) #check 11 constant f : num → num #check o + 1 #check f o + o + o #reduce 9 + (1:num) #reduce o+4
a56e1330b2ee9dae9a81e5f1285dbf6eb1104710
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/algebra/module/linear_map.lean
0dec041790d896b690534c497093eba3f3e779c6
[ "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
28,488
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro, Anne Baanen, Frédéric Dupuis, Heather Macbeth -/ import algebra.group.hom import algebra.module.basic import algebra.module.pi import algebra.group_action_hom import algebra.ring.comp_typeclasses /-! # (Semi)linear maps In this file we define * `linear_map σ M M₂`, `M →ₛₗ[σ] M₂` : a semilinear map between two `module`s. Here, `σ` is a `ring_hom` from `R` to `R₂` and an `f : M →ₛₗ[σ] M₂` satisfies `f (c • x) = (σ c) • (f x)`. We recover plain linear maps by choosing `σ` to be `ring_hom.id R`. This is denoted by `M →ₗ[R] M₂`. We also add the notation `M →ₗ⋆[R] M₂` for star-linear maps. * `is_linear_map R f` : predicate saying that `f : M → M₂` is a linear map. (Note that this was not generalized to semilinear maps.) We then provide `linear_map` with the following instances: * `linear_map.add_comm_monoid` and `linear_map.add_comm_group`: the elementwise addition structures corresponding to addition in the codomain * `linear_map.distrib_mul_action` and `linear_map.module`: the elementwise scalar action structures corresponding to applying the action in the codomain. * `module.End.semiring` and `module.End.ring`: the (semi)ring of endomorphisms formed by taking the additive structure above with composition as multiplication. ## Implementation notes To ensure that composition works smoothly for semilinear maps, we use the typeclasses `ring_hom_comp_triple`, `ring_hom_inv_pair` and `ring_hom_surjective` from `algebra/ring/comp_typeclasses`. ## Notation * Throughout the file, we denote regular linear maps by `fₗ`, `gₗ`, etc, and semilinear maps by `f`, `g`, etc. ## TODO * Parts of this file have not yet been generalized to semilinear maps (i.e. `compatible_smul`) ## Tags linear map -/ open function open_locale big_operators universes u u' v w x y z variables {R : Type*} {R₁ : Type*} {R₂ : Type*} {R₃ : Type*} variables {k : Type*} {S : Type*} {T : Type*} variables {M : Type*} {M₁ : Type*} {M₂ : Type*} {M₃ : Type*} variables {N₁ : Type*} {N₂ : Type*} {N₃ : Type*} {ι : Type*} /-- A map `f` between modules over a semiring is linear if it satisfies the two properties `f (x + y) = f x + f y` and `f (c • x) = c • f x`. The predicate `is_linear_map R f` asserts this property. A bundled version is available with `linear_map`, and should be favored over `is_linear_map` most of the time. -/ structure is_linear_map (R : Type u) {M : Type v} {M₂ : Type w} [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [module R M] [module R M₂] (f : M → M₂) : Prop := (map_add : ∀ x y, f (x + y) = f x + f y) (map_smul : ∀ (c : R) x, f (c • x) = c • f x) section set_option old_structure_cmd true /-- A map `f` between an `R`-module and an `S`-module over a ring homomorphism `σ : R →+* S` is semilinear if it satisfies the two properties `f (x + y) = f x + f y` and `f (c • x) = (σ c) • f x`. Elements of `linear_map σ M M₂` (available under the notation `M →ₛₗ[σ] M₂`) are bundled versions of such maps. For plain linear maps (i.e. for which `σ = ring_hom.id R`), the notation `M →ₗ[R] M₂` is available. An unbundled version of plain linear maps is available with the predicate `is_linear_map`, but it should be avoided most of the time. -/ structure linear_map {R : Type*} {S : Type*} [semiring R] [semiring S] (σ : R →+* S) (M : Type*) (M₂ : Type*) [add_comm_monoid M] [add_comm_monoid M₂] [module R M] [module S M₂] extends add_hom M M₂ := (map_smul' : ∀ (r : R) (x : M), to_fun (r • x) = (σ r) • to_fun x) end /-- The `add_hom` underlying a `linear_map`. -/ add_decl_doc linear_map.to_add_hom notation M ` →ₛₗ[`:25 σ:25 `] `:0 M₂:0 := linear_map σ M M₂ notation M ` →ₗ[`:25 R:25 `] `:0 M₂:0 := linear_map (ring_hom.id R) M M₂ notation M ` →ₗ⋆[`:25 R:25 `] `:0 M₂:0 := linear_map (@star_ring_aut R _ _ : R →+* R) M M₂ namespace linear_map section add_comm_monoid variables [semiring R] [semiring S] section variables [add_comm_monoid M] [add_comm_monoid M₁] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [add_comm_monoid N₁] [add_comm_monoid N₂] [add_comm_monoid N₃] variables [module R M] [module R M₂] [module S M₃] /-- The `distrib_mul_action_hom` underlying a `linear_map`. -/ def to_distrib_mul_action_hom (f : M →ₗ[R] M₂) : distrib_mul_action_hom R M M₂ := { map_zero' := zero_smul R (0 : M) ▸ zero_smul R (f.to_fun 0) ▸ f.map_smul' 0 0, ..f } instance {σ : R →+* S} : has_coe_to_fun (M →ₛₗ[σ] M₃) (λ _, M → M₃) := ⟨linear_map.to_fun⟩ initialize_simps_projections linear_map (to_fun → apply) @[simp] lemma coe_mk {σ : R →+* S} (f : M → M₃) (h₁ h₂) : ((linear_map.mk f h₁ h₂ : M →ₛₗ[σ] M₃) : M → M₃) = f := rfl /-- Identity map as a `linear_map` -/ def id : M →ₗ[R] M := { to_fun := id, ..distrib_mul_action_hom.id R } lemma id_apply (x : M) : @id R M _ _ _ x = x := rfl @[simp, norm_cast] lemma id_coe : ((linear_map.id : M →ₗ[R] M) : M → M) = _root_.id := by { ext x, refl } end section variables [add_comm_monoid M] [add_comm_monoid M₁] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [add_comm_monoid N₁] [add_comm_monoid N₂] [add_comm_monoid N₃] variables [module R M] [module R M₂] [module S M₃] variables (σ : R →+* S) variables (fₗ gₗ : M →ₗ[R] M₂) (f g : M →ₛₗ[σ] M₃) @[simp] lemma to_fun_eq_coe : f.to_fun = ⇑f := rfl theorem is_linear : is_linear_map R fₗ := ⟨fₗ.map_add', fₗ.map_smul'⟩ variables {fₗ gₗ f g σ} theorem coe_injective : @injective (M →ₛₗ[σ] M₃) (M → M₃) coe_fn := by rintro ⟨f, _⟩ ⟨g, _⟩ ⟨h⟩; congr @[ext] theorem ext (H : ∀ x, f x = g x) : f = g := coe_injective $ funext H protected lemma congr_arg : Π {x x' : M}, x = x' → f x = f x' | _ _ rfl := rfl /-- If two linear maps are equal, they are equal at each point. -/ protected lemma congr_fun (h : f = g) (x : M) : f x = g x := h ▸ rfl theorem ext_iff : f = g ↔ ∀ x, f x = g x := ⟨by { rintro rfl x, refl }, ext⟩ @[simp] lemma mk_coe (f : M →ₛₗ[σ] M₃) (h₁ h₂) : (linear_map.mk f h₁ h₂ : M →ₛₗ[σ] M₃) = f := ext $ λ _, rfl variables (fₗ gₗ f g) @[simp] lemma map_add (x y : M) : f (x + y) = f x + f y := f.map_add' x y @[simp] lemma map_smulₛₗ (c : R) (x : M) : f (c • x) = (σ c) • f x := f.map_smul' c x lemma map_smul (c : R) (x : M) : fₗ (c • x) = c • fₗ x := fₗ.map_smul' c x lemma map_smul_inv {σ' : S →+* R} [ring_hom_inv_pair σ σ'] (c : S) (x : M) : c • f x = f (σ' c • x) := by simp @[simp] lemma map_zero : f 0 = 0 := by { rw [←zero_smul R (0 : M), map_smulₛₗ], simp } @[simp] lemma map_eq_zero_iff (h : function.injective f) {x : M} : f x = 0 ↔ x = 0 := ⟨λ w, by { apply h, simp [w], }, λ w, by { subst w, simp, }⟩ variables (M M₂) /-- A typeclass for `has_scalar` structures which can be moved through a `linear_map`. This typeclass is generated automatically from a `is_scalar_tower` instance, but exists so that we can also add an instance for `add_comm_group.int_module`, allowing `z •` to be moved even if `R` does not support negation. -/ class compatible_smul (R S : Type*) [semiring S] [has_scalar R M] [module S M] [has_scalar R M₂] [module S M₂] := (map_smul : ∀ (fₗ : M →ₗ[S] M₂) (c : R) (x : M), fₗ (c • x) = c • fₗ x) variables {M M₂} @[priority 100] instance is_scalar_tower.compatible_smul {R S : Type*} [semiring S] [has_scalar R S] [has_scalar R M] [module S M] [is_scalar_tower R S M] [has_scalar R M₂] [module S M₂] [is_scalar_tower R S M₂] : compatible_smul M M₂ R S := ⟨λ fₗ c x, by rw [← smul_one_smul S c x, ← smul_one_smul S c (fₗ x), map_smul]⟩ @[simp, priority 900] lemma map_smul_of_tower {R S : Type*} [semiring S] [has_scalar R M] [module S M] [has_scalar R M₂] [module S M₂] [compatible_smul M M₂ R S] (fₗ : M →ₗ[S] M₂) (c : R) (x : M) : fₗ (c • x) = c • fₗ x := compatible_smul.map_smul fₗ c x /-- convert a linear map to an additive map -/ def to_add_monoid_hom : M →+ M₃ := { to_fun := f, map_zero' := f.map_zero, map_add' := f.map_add } @[simp] lemma to_add_monoid_hom_coe : ⇑f.to_add_monoid_hom = f := rfl section restrict_scalars variables (R) [module S M] [module S M₂] [compatible_smul M M₂ R S] /-- If `M` and `M₂` are both `R`-modules and `S`-modules and `R`-module structures are defined by an action of `R` on `S` (formally, we have two scalar towers), then any `S`-linear map from `M` to `M₂` is `R`-linear. See also `linear_map.map_smul_of_tower`. -/ @[simps] def restrict_scalars (fₗ : M →ₗ[S] M₂) : M →ₗ[R] M₂ := { to_fun := fₗ, map_add' := fₗ.map_add, map_smul' := fₗ.map_smul_of_tower } lemma restrict_scalars_injective : function.injective (restrict_scalars R : (M →ₗ[S] M₂) → (M →ₗ[R] M₂)) := λ fₗ gₗ h, ext (linear_map.congr_fun h : _) @[simp] lemma restrict_scalars_inj (fₗ gₗ : M →ₗ[S] M₂) : fₗ.restrict_scalars R = gₗ.restrict_scalars R ↔ fₗ = gₗ := (restrict_scalars_injective R).eq_iff end restrict_scalars variable {R} @[simp] lemma map_sum {ι} {t : finset ι} {g : ι → M} : f (∑ i in t, g i) = (∑ i in t, f (g i)) := f.to_add_monoid_hom.map_sum _ _ theorem to_add_monoid_hom_injective : function.injective (to_add_monoid_hom : (M →ₛₗ[σ] M₃) → (M →+ M₃)) := λ f g h, ext $ add_monoid_hom.congr_fun h /-- If two `σ`-linear maps from `R` are equal on `1`, then they are equal. -/ @[ext] theorem ext_ring {f g : R →ₛₗ[σ] M₃} (h : f 1 = g 1) : f = g := ext $ λ x, by rw [← mul_one x, ← smul_eq_mul, f.map_smulₛₗ, g.map_smulₛₗ, h] theorem ext_ring_iff {σ : R →+* R} {f g : R →ₛₗ[σ] M} : f = g ↔ f 1 = g 1 := ⟨λ h, h ▸ rfl, ext_ring⟩ end section variables [semiring R₁] [semiring R₂] [semiring R₃] variables [add_comm_monoid M] [add_comm_monoid M₁] [add_comm_monoid M₂] [add_comm_monoid M₃] variables {module_M₁ : module R₁ M₁} {module_M₂ : module R₂ M₂} {module_M₃ : module R₃ M₃} variables {σ₁₂ : R₁ →+* R₂} {σ₂₃ : R₂ →+* R₃} {σ₁₃ : R₁ →+* R₃} variables [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] variables (f : M₂ →ₛₗ[σ₂₃] M₃) (g : M₁ →ₛₗ[σ₁₂] M₂) include module_M₁ module_M₂ module_M₃ /-- Composition of two linear maps is a linear map -/ def comp : M₁ →ₛₗ[σ₁₃] M₃ := { to_fun := f ∘ g, map_add' := by simp only [map_add, forall_const, eq_self_iff_true, comp_app], map_smul' := λ r x, by rw [comp_app, map_smulₛₗ, map_smulₛₗ, ring_hom_comp_triple.comp_apply] } omit module_M₁ module_M₂ module_M₃ infixr ` ∘ₗ `:80 := @linear_map.comp _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ (ring_hom.id _) (ring_hom.id _) (ring_hom.id _) ring_hom_comp_triple.ids include σ₁₃ lemma comp_apply (x : M₁) : f.comp g x = f (g x) := rfl omit σ₁₃ include σ₁₃ @[simp, norm_cast] lemma coe_comp : (f.comp g : M₁ → M₃) = f ∘ g := rfl omit σ₁₃ @[simp] theorem comp_id : f.comp id = f := linear_map.ext $ λ x, rfl @[simp] theorem id_comp : id.comp f = f := linear_map.ext $ λ x, rfl end variables [add_comm_monoid M] [add_comm_monoid M₁] [add_comm_monoid M₂] [add_comm_monoid M₃] /-- If a function `g` is a left and right inverse of a linear map `f`, then `g` is linear itself. -/ def inverse [module R M] [module S M₂] {σ : R →+* S} {σ' : S →+* R} [ring_hom_inv_pair σ σ'] (f : M →ₛₗ[σ] M₂) (g : M₂ → M) (h₁ : left_inverse g f) (h₂ : right_inverse g f) : M₂ →ₛₗ[σ'] M := by dsimp [left_inverse, function.right_inverse] at h₁ h₂; exact { to_fun := g, map_add' := λ x y, by { rw [← h₁ (g (x + y)), ← h₁ (g x + g y)]; simp [h₂] }, map_smul' := λ a b, by { rw [← h₁ (g (a • b)), ← h₁ ((σ' a) • g b)], simp [h₂] } } end add_comm_monoid section add_comm_group variables [semiring R] [semiring S] [add_comm_group M] [add_comm_group M₂] variables {module_M : module R M} {module_M₂ : module S M₂} {σ : R →+* S} variables (f : M →ₛₗ[σ] M₂) @[simp] lemma map_neg (x : M) : f (- x) = - f x := f.to_add_monoid_hom.map_neg x @[simp] lemma map_sub (x y : M) : f (x - y) = f x - f y := f.to_add_monoid_hom.map_sub x y instance compatible_smul.int_module {S : Type*} [semiring S] [module S M] [module S M₂] : compatible_smul M M₂ ℤ S := ⟨λ fₗ c x, begin induction c using int.induction_on, case hz : { simp }, case hp : n ih { simp [add_smul, ih] }, case hn : n ih { simp [sub_smul, ih] } end⟩ instance compatible_smul.units {R S : Type*} [monoid R] [mul_action R M] [mul_action R M₂] [semiring S] [module S M] [module S M₂] [compatible_smul M M₂ R S] : compatible_smul M M₂ (units R) S := ⟨λ fₗ c x, (compatible_smul.map_smul fₗ (c : R) x : _)⟩ end add_comm_group end linear_map namespace module /-- `g : R →+* S` is `R`-linear when the module structure on `S` is `module.comp_hom S g` . -/ @[simps] def comp_hom.to_linear_map {R S : Type*} [semiring R] [semiring S] (g : R →+* S) : (by haveI := comp_hom S g; exact (R →ₗ[R] S)) := by exact { to_fun := (g : R → S), map_add' := g.map_add, map_smul' := g.map_mul } end module namespace distrib_mul_action_hom variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [module R M] [module R M₂] /-- A `distrib_mul_action_hom` between two modules is a linear map. -/ def to_linear_map (fₗ : M →+[R] M₂) : M →ₗ[R] M₂ := { ..fₗ } instance : has_coe (M →+[R] M₂) (M →ₗ[R] M₂) := ⟨to_linear_map⟩ @[simp] lemma to_linear_map_eq_coe (f : M →+[R] M₂) : f.to_linear_map = ↑f := rfl @[simp, norm_cast] lemma coe_to_linear_map (f : M →+[R] M₂) : ((f : M →ₗ[R] M₂) : M → M₂) = f := rfl lemma to_linear_map_injective {f g : M →+[R] M₂} (h : (f : M →ₗ[R] M₂) = (g : M →ₗ[R] M₂)) : f = g := by { ext m, exact linear_map.congr_fun h m, } end distrib_mul_action_hom namespace is_linear_map section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] variables [module R M] [module R M₂] include R /-- Convert an `is_linear_map` predicate to a `linear_map` -/ def mk' (f : M → M₂) (H : is_linear_map R f) : M →ₗ[R] M₂ := { to_fun := f, map_add' := H.1, map_smul' := H.2 } @[simp] theorem mk'_apply {f : M → M₂} (H : is_linear_map R f) (x : M) : mk' f H x = f x := rfl lemma is_linear_map_smul {R M : Type*} [comm_semiring R] [add_comm_monoid M] [module R M] (c : R) : is_linear_map R (λ (z : M), c • z) := begin refine is_linear_map.mk (smul_add c) _, intros _ _, simp only [smul_smul, mul_comm] end lemma is_linear_map_smul' {R M : Type*} [semiring R] [add_comm_monoid M] [module R M] (a : M) : is_linear_map R (λ (c : R), c • a) := is_linear_map.mk (λ x y, add_smul x y a) (λ x y, mul_smul x y a) variables {f : M → M₂} (lin : is_linear_map R f) include M M₂ lin lemma map_zero : f (0 : M) = (0 : M₂) := (lin.mk' f).map_zero end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] variables [module R M] [module R M₂] include R lemma is_linear_map_neg : is_linear_map R (λ (z : M), -z) := is_linear_map.mk neg_add (λ x y, (smul_neg x y).symm) variables {f : M → M₂} (lin : is_linear_map R f) include M M₂ lin lemma map_neg (x : M) : f (- x) = - f x := (lin.mk' f).map_neg x lemma map_sub (x y) : f (x - y) = f x - f y := (lin.mk' f).map_sub x y end add_comm_group end is_linear_map /-- Linear endomorphisms of a module, with associated ring structure `module.End.semiring` and algebra structure `module.End.algebra`. -/ abbreviation module.End (R : Type u) (M : Type v) [semiring R] [add_comm_monoid M] [module R M] := M →ₗ[R] M /-- Reinterpret an additive homomorphism as a `ℕ`-linear map. -/ def add_monoid_hom.to_nat_linear_map [add_comm_monoid M] [add_comm_monoid M₂] (f : M →+ M₂) : M →ₗ[ℕ] M₂ := { to_fun := f, map_add' := f.map_add, map_smul' := f.map_nat_module_smul } lemma add_monoid_hom.to_nat_linear_map_injective [add_comm_monoid M] [add_comm_monoid M₂] : function.injective (@add_monoid_hom.to_nat_linear_map M M₂ _ _) := by { intros f g h, ext, exact linear_map.congr_fun h x } /-- Reinterpret an additive homomorphism as a `ℤ`-linear map. -/ def add_monoid_hom.to_int_linear_map [add_comm_group M] [add_comm_group M₂] (f : M →+ M₂) : M →ₗ[ℤ] M₂ := { to_fun := f, map_add' := f.map_add, map_smul' := f.map_int_module_smul } lemma add_monoid_hom.to_int_linear_map_injective [add_comm_group M] [add_comm_group M₂] : function.injective (@add_monoid_hom.to_int_linear_map M M₂ _ _) := by { intros f g h, ext, exact linear_map.congr_fun h x } @[simp] lemma add_monoid_hom.coe_to_int_linear_map [add_comm_group M] [add_comm_group M₂] (f : M →+ M₂) : ⇑f.to_int_linear_map = f := rfl /-- Reinterpret an additive homomorphism as a `ℚ`-linear map. -/ def add_monoid_hom.to_rat_linear_map [add_comm_group M] [module ℚ M] [add_comm_group M₂] [module ℚ M₂] (f : M →+ M₂) : M →ₗ[ℚ] M₂ := { map_smul' := f.map_rat_module_smul, ..f } lemma add_monoid_hom.to_rat_linear_map_injective [add_comm_group M] [module ℚ M] [add_comm_group M₂] [module ℚ M₂] : function.injective (@add_monoid_hom.to_rat_linear_map M M₂ _ _ _ _) := by { intros f g h, ext, exact linear_map.congr_fun h x } @[simp] lemma add_monoid_hom.coe_to_rat_linear_map [add_comm_group M] [module ℚ M] [add_comm_group M₂] [module ℚ M₂] (f : M →+ M₂) : ⇑f.to_rat_linear_map = f := rfl namespace linear_map /-! ### Arithmetic on the codomain -/ section arithmetic variables [semiring R₁] [semiring R₂] [semiring R₃] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [add_comm_group N₁] [add_comm_group N₂] [add_comm_group N₃] variables [module R₁ M] [module R₂ M₂] [module R₃ M₃] variables [module R₁ N₁] [module R₂ N₂] [module R₃ N₃] variables {σ₁₂ : R₁ →+* R₂} {σ₂₃ : R₂ →+* R₃} {σ₁₃ : R₁ →+* R₃} [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] /-- The constant 0 map is linear. -/ instance : has_zero (M →ₛₗ[σ₁₂] M₂) := ⟨{ to_fun := 0, map_add' := by simp, map_smul' := by simp }⟩ @[simp] lemma zero_apply (x : M) : (0 : M →ₛₗ[σ₁₂] M₂) x = 0 := rfl @[simp] theorem comp_zero (g : M₂ →ₛₗ[σ₂₃] M₃) : (g.comp (0 : M →ₛₗ[σ₁₂] M₂) : M →ₛₗ[σ₁₃] M₃) = 0 := ext $ assume c, by rw [comp_apply, zero_apply, zero_apply, g.map_zero] @[simp] theorem zero_comp (f : M →ₛₗ[σ₁₂] M₂) : ((0 : M₂ →ₛₗ[σ₂₃] M₃).comp f : M →ₛₗ[σ₁₃] M₃) = 0 := rfl instance : inhabited (M →ₛₗ[σ₁₂] M₂) := ⟨0⟩ @[simp] lemma default_def : default (M →ₛₗ[σ₁₂] M₂) = 0 := rfl /-- The sum of two linear maps is linear. -/ instance : has_add (M →ₛₗ[σ₁₂] M₂) := ⟨λ f g, { to_fun := f + g, map_add' := by simp [add_comm, add_left_comm], map_smul' := by simp [smul_add] }⟩ @[simp] lemma add_apply (f g : M →ₛₗ[σ₁₂] M₂) (x : M) : (f + g) x = f x + g x := rfl lemma add_comp (f : M →ₛₗ[σ₁₂] M₂) (g h : M₂ →ₛₗ[σ₂₃] M₃) : ((h + g).comp f : M →ₛₗ[σ₁₃] M₃) = h.comp f + g.comp f := rfl lemma comp_add (f g : M →ₛₗ[σ₁₂] M₂) (h : M₂ →ₛₗ[σ₂₃] M₃) : (h.comp (f + g) : M →ₛₗ[σ₁₃] M₃) = h.comp f + h.comp g := ext $ λ _, h.map_add _ _ /-- The type of linear maps is an additive monoid. -/ instance : add_comm_monoid (M →ₛₗ[σ₁₂] M₂) := { zero := 0, add := (+), add_assoc := λ f g h, linear_map.ext $ λ x, add_assoc _ _ _, zero_add := λ f, linear_map.ext $ λ x, zero_add _, add_zero := λ f, linear_map.ext $ λ x, add_zero _, add_comm := λ f g, linear_map.ext $ λ x, add_comm _ _, nsmul := λ n f, { to_fun := λ x, n • (f x), map_add' := λ x y, by rw [f.map_add, smul_add], map_smul' := λ c x, begin rw [f.map_smulₛₗ], simp [smul_comm n (σ₁₂ c) (f x)], end }, nsmul_zero' := λ f, linear_map.ext $ λ x, add_comm_monoid.nsmul_zero' _, nsmul_succ' := λ n f, linear_map.ext $ λ x, add_comm_monoid.nsmul_succ' _ _ } /-- The negation of a linear map is linear. -/ instance : has_neg (M →ₛₗ[σ₁₂] N₂) := ⟨λ f, { to_fun := -f, map_add' := by simp [add_comm], map_smul' := by simp }⟩ @[simp] lemma neg_apply (f : M →ₛₗ[σ₁₂] N₂) (x : M) : (- f) x = - f x := rfl include σ₁₃ @[simp] lemma neg_comp (f : M →ₛₗ[σ₁₂] M₂) (g : M₂ →ₛₗ[σ₂₃] N₃) : (- g).comp f = - g.comp f := rfl @[simp] lemma comp_neg (f : M →ₛₗ[σ₁₂] N₂) (g : N₂ →ₛₗ[σ₂₃] N₃) : g.comp (- f) = - g.comp f := ext $ λ _, g.map_neg _ omit σ₁₃ /-- The negation of a linear map is linear. -/ instance : has_sub (M →ₛₗ[σ₁₂] N₂) := ⟨λ f g, { to_fun := f - g, map_add' := λ x y, by simp only [pi.sub_apply, map_add, add_sub_comm], map_smul' := λ r x, by simp [pi.sub_apply, map_smul, smul_sub] }⟩ @[simp] lemma sub_apply (f g : M →ₛₗ[σ₁₂] N₂) (x : M) : (f - g) x = f x - g x := rfl include σ₁₃ lemma sub_comp (f : M →ₛₗ[σ₁₂] M₂) (g h : M₂ →ₛₗ[σ₂₃] N₃) : (g - h).comp f = g.comp f - h.comp f := rfl lemma comp_sub (f g : M →ₛₗ[σ₁₂] N₂) (h : N₂ →ₛₗ[σ₂₃] N₃) : h.comp (g - f) = h.comp g - h.comp f := ext $ λ _, h.map_sub _ _ omit σ₁₃ /-- The type of linear maps is an additive group. -/ instance : add_comm_group (M →ₛₗ[σ₁₂] N₂) := { zero := 0, add := (+), neg := has_neg.neg, sub := has_sub.sub, sub_eq_add_neg := λ f g, linear_map.ext $ λ m, sub_eq_add_neg _ _, add_left_neg := λ f, linear_map.ext $ λ m, add_left_neg _, nsmul := λ n f, { to_fun := λ x, n • (f x), map_add' := λ x y, by rw [f.map_add, smul_add], map_smul' := λ c x, by rw [f.map_smulₛₗ, smul_comm n (σ₁₂ c) (f x)] }, zsmul := λ n f, { to_fun := λ x, n • (f x), map_add' := λ x y, by rw [f.map_add, smul_add], map_smul' := λ c x, by rw [f.map_smulₛₗ, smul_comm n (σ₁₂ c) (f x)] }, zsmul_zero' := λ a, linear_map.ext $ λ m, zero_smul _ _, zsmul_succ' := λ n a, linear_map.ext $ λ m, add_comm_group.zsmul_succ' n _, zsmul_neg' := λ n a, linear_map.ext $ λ m, add_comm_group.zsmul_neg' n _, .. linear_map.add_comm_monoid } end arithmetic -- TODO: generalize this section to semilinear maps where possible section actions variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [module R M] [module R M₂] [module R M₃] section has_scalar variables [monoid S] [distrib_mul_action S M₂] [smul_comm_class R S M₂] variables [monoid T] [distrib_mul_action T M₂] [smul_comm_class R T M₂] instance : has_scalar S (M →ₗ[R] M₂) := ⟨λ a f, { to_fun := a • f, map_add' := λ x y, by simp only [pi.smul_apply, f.map_add, smul_add], map_smul' := λ c x, by simp [pi.smul_apply, f.map_smul, smul_comm c] }⟩ @[simp] lemma smul_apply (a : S) (f : M →ₗ[R] M₂) (x : M) : (a • f) x = a • f x := rfl lemma coe_smul (a : S) (f : M →ₗ[R] M₂) : ⇑(a • f) = a • f := rfl instance [smul_comm_class S T M₂] : smul_comm_class S T (M →ₗ[R] M₂) := ⟨λ a b f, ext $ λ x, smul_comm _ _ _⟩ -- example application of this instance: if S -> T -> R are homomorphisms of commutative rings and -- M and M₂ are R-modules then the S-module and T-module structures on Hom_R(M,M₂) are compatible. instance [has_scalar S T] [is_scalar_tower S T M₂] : is_scalar_tower S T (M →ₗ[R] M₂) := { smul_assoc := λ _ _ _, ext $ λ _, smul_assoc _ _ _ } instance : distrib_mul_action S (M →ₗ[R] M₂) := { one_smul := λ f, ext $ λ _, one_smul _ _, mul_smul := λ c c' f, ext $ λ _, mul_smul _ _ _, smul_add := λ c f g, ext $ λ x, smul_add _ _ _, smul_zero := λ c, ext $ λ x, smul_zero _ } theorem smul_comp (a : S) (g : M₃ →ₗ[R] M₂) (f : M →ₗ[R] M₃) : (a • g).comp f = a • (g.comp f) := rfl theorem comp_smul [distrib_mul_action S M₃] [smul_comm_class R S M₃] [compatible_smul M₃ M₂ S R] (g : M₃ →ₗ[R] M₂) (a : S) (f : M →ₗ[R] M₃) : g.comp (a • f) = a • (g.comp f) := ext $ λ x, g.map_smul_of_tower _ _ end has_scalar section module variables [semiring S] [module S M₂] [smul_comm_class R S M₂] instance : module S (M →ₗ[R] M₂) := { add_smul := λ a b f, ext $ λ x, add_smul _ _ _, zero_smul := λ f, ext $ λ x, zero_smul _ _ } instance [no_zero_smul_divisors S M₂] : no_zero_smul_divisors S (M →ₗ[R] M₂) := coe_injective.no_zero_smul_divisors _ rfl coe_smul end module end actions /-! ### Monoid structure of endomorphisms Lemmas about `pow` such as `linear_map.pow_apply` appear in later files. -/ section endomorphisms variables [semiring R] [add_comm_monoid M] [add_comm_group N₁] [module R M] [module R N₁] instance : has_one (module.End R M) := ⟨linear_map.id⟩ instance : has_mul (module.End R M) := ⟨linear_map.comp⟩ lemma one_eq_id : (1 : module.End R M) = id := rfl lemma mul_eq_comp (f g : module.End R M) : f * g = f.comp g := rfl @[simp] lemma one_apply (x : M) : (1 : module.End R M) x = x := rfl @[simp] lemma mul_apply (f g : module.End R M) (x : M) : (f * g) x = f (g x) := rfl lemma coe_one : ⇑(1 : module.End R M) = _root_.id := rfl lemma coe_mul (f g : module.End R M) : ⇑(f * g) = f ∘ g := rfl instance _root_.module.End.monoid : monoid (module.End R M) := { mul := (*), one := (1 : M →ₗ[R] M), mul_assoc := λ f g h, linear_map.ext $ λ x, rfl, mul_one := comp_id, one_mul := id_comp } instance _root_.module.End.semiring : semiring (module.End R M) := { mul := (*), one := (1 : M →ₗ[R] M), zero := 0, add := (+), npow := @npow_rec _ ⟨(1 : M →ₗ[R] M)⟩ ⟨(*)⟩, mul_zero := comp_zero, zero_mul := zero_comp, left_distrib := λ f g h, comp_add _ _ _, right_distrib := λ f g h, add_comp _ _ _, .. _root_.module.End.monoid, .. linear_map.add_comm_monoid } instance _root_.module.End.ring : ring (module.End R N₁) := { ..module.End.semiring, ..linear_map.add_comm_group } section variables [monoid S] [distrib_mul_action S M] [smul_comm_class R S M] instance _root_.module.End.is_scalar_tower : is_scalar_tower S (module.End R M) (module.End R M) := ⟨smul_comp⟩ instance _root_.module.End.smul_comm_class [has_scalar S R] [is_scalar_tower S R M] : smul_comm_class S (module.End R M) (module.End R M) := ⟨λ s _ _, (comp_smul _ s _).symm⟩ instance _root_.module.End.smul_comm_class' [has_scalar S R] [is_scalar_tower S R M] : smul_comm_class (module.End R M) S (module.End R M) := smul_comm_class.symm _ _ _ end /-! ### Action by a module endomorphism. -/ /-- The tautological action by `module.End R M` (aka `M →ₗ[R] M`) on `M`. This generalizes `function.End.apply_mul_action`. -/ instance apply_module : module (module.End R M) M := { smul := ($), smul_zero := linear_map.map_zero, smul_add := linear_map.map_add, add_smul := linear_map.add_apply, zero_smul := (linear_map.zero_apply : ∀ m, (0 : M →ₗ[R] M) m = 0), one_smul := λ _, rfl, mul_smul := λ _ _ _, rfl } @[simp] protected lemma smul_def (f : module.End R M) (a : M) : f • a = f a := rfl /-- `linear_map.apply_module` is faithful. -/ instance apply_has_faithful_scalar : has_faithful_scalar (module.End R M) M := ⟨λ _ _, linear_map.ext⟩ instance apply_smul_comm_class : smul_comm_class R (module.End R M) M := { smul_comm := λ r e m, (e.map_smul r m).symm } instance apply_smul_comm_class' : smul_comm_class (module.End R M) R M := { smul_comm := linear_map.map_smul } end endomorphisms end linear_map
1e921f3dcbfe1a83de9667d388e49d9ea2eeac72
1d02a718c550dba762f0c3d2ad13d16a43649ca1
/src/well_formedness.lean
f1f0dfb727fe33d17140af6d25d266ad355ed15f
[ "Apache-2.0" ]
permissive
mhuisi/rc-correctness
48488dfbbe18e222399b0c5252d2803a9dd1be74
2b7878ac594ba285b0b5cdabe96f41c6e3bbcc87
refs/heads/master
1,590,988,773,033
1,585,334,858,000
1,585,334,858,000
190,653,803
0
1
null
null
null
null
UTF-8
Lean
false
false
2,306
lean
import type_system import data.multiset namespace rc_correctness open rc_correctness.expr open rc_correctness.fn_body open rc_correctness.lin_type inductive fn_body_wf (β : const → var → lin_type) (δ : program) : finset var → fn_body → Prop notation Γ ` ⊢ `:1 F := fn_body_wf Γ F | ret {Γ : finset var} {x : var} (x_def : x ∈ Γ) : Γ ⊢ ret x | let_const_app_full {Γ : finset var} {z : var} {c : const} {ys : list var} {F : fn_body} (ys_def : ys.to_finset ⊆ Γ) (arity_eq : ys.length = (δ c).ys.length) (z_used : z ∈ FV F) (z_undef : z ∉ Γ) (F_wf : insert z Γ ⊢ F) : Γ ⊢ (z ≔ c⟦ys…⟧; F) | let_const_app_part {Γ : finset var} {z : var} {c : const} {ys : list var} {F : fn_body} (ys_def : ys.to_finset ⊆ Γ) (no_𝔹_var : ∀ x : var, β c x ≠ 𝔹) (z_used : z ∈ FV F) (z_undef : z ∉ Γ) (F_wf : insert z Γ ⊢ F) : Γ ⊢ (z ≔ c⟦ys…, _⟧; F) | let_var_app {Γ : finset var} {z : var} {x y : var} {F : fn_body} (x_def : x ∈ Γ) (y_in_Γ : y ∈ Γ) (z_used : z ∈ FV F) (z_undef : z ∉ Γ) (F_wf : insert z Γ ⊢ F) : Γ ⊢ (z ≔ x⟦y⟧; F) | let_ctor {Γ : finset var} {z : var} (i : cnstr) {ys : list var} {F : fn_body} (ys_def : ys.to_finset ⊆ Γ) (z_used : z ∈ FV F) (z_undef : z ∉ Γ) (F_wf : insert z Γ ⊢ F) : Γ ⊢ (z ≔ ⟪ys⟫i; F) | let_proj {Γ : finset var} {z : var} {x : var} (i : cnstr) {F : fn_body} (x_def : x ∈ Γ) (z_used : z ∈ FV F) (z_undef : z ∉ Γ) (F_wf : insert z Γ ⊢ F) : Γ ⊢ (z ≔ x[i]; F) | «case» {Γ : finset var} {x : var} {Fs : list fn_body} (x_def : x ∈ Γ) (Fs_wf : ∀ F ∈ Fs, Γ ⊢ F) : Γ ⊢ (case x of Fs) notation β `; ` δ `; ` Γ ` ⊢ `:1 F := fn_body_wf β δ Γ F inductive const_wf (β : const → var → lin_type) (δ : program) : const → Prop notation `⊢ `:1 c := const_wf c | const {c : const} (F_wf : β; δ; (δ c).ys.to_finset ⊢ (δ c).F) (nd_ys : multiset.nodup (δ c).ys) : ⊢ c notation β `; ` δ ` ⊢ `:1 c := const_wf β δ c inductive program_wf (β : const → var → lin_type) : program → Prop notation `⊢ `:1 δ := program_wf δ | program {δ : program} (const_wf : ∀ c : const, β; δ ⊢ c) : ⊢ δ notation β ` ⊢ `:1 δ := program_wf β δ end rc_correctness
656706d1b7098702e2abc1e12e73694bcd070100
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/wfLean3Issue.lean
f65609d9b753a0adfe5cb6a10ebc9813d26ded52
[ "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
179
lean
def foo : Nat → Nat → Nat | 0, 0 => 1 | s+1, 0 => foo s 0 + 1 | 0, b+1 => foo 0 b + 1 | s+1, b+1 => foo (s+1) b + foo s (b+1) termination_by foo b s => (b, s)
97ee7e33635f8cd6eab5eda7744ecf8112a445c9
82e44445c70db0f03e30d7be725775f122d72f3e
/src/order/filter/at_top_bot.lean
7906c213750a031eb93c4c65d9c056a503f91c3e
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
61,834
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jeremy Avigad, Yury Kudryashov, Patrick Massot -/ import order.filter.bases import data.finset.preimage /-! # `at_top` and `at_bot` filters on preorded sets, monoids and groups. In this file we define the filters * `at_top`: corresponds to `n → +∞`; * `at_bot`: corresponds to `n → -∞`. Then we prove many lemmas like “if `f → +∞`, then `f ± c → +∞`”. -/ variables {ι ι' α β γ : Type*} open set open_locale classical filter big_operators namespace filter /-- `at_top` is the filter representing the limit `→ ∞` on an ordered set. It is generated by the collection of up-sets `{b | a ≤ b}`. (The preorder need not have a top element for this to be well defined, and indeed is trivial when a top element exists.) -/ def at_top [preorder α] : filter α := ⨅ a, 𝓟 (Ici a) /-- `at_bot` is the filter representing the limit `→ -∞` on an ordered set. It is generated by the collection of down-sets `{b | b ≤ a}`. (The preorder need not have a bottom element for this to be well defined, and indeed is trivial when a bottom element exists.) -/ def at_bot [preorder α] : filter α := ⨅ a, 𝓟 (Iic a) lemma mem_at_top [preorder α] (a : α) : {b : α | a ≤ b} ∈ @at_top α _ := mem_infi_sets a $ subset.refl _ lemma Ioi_mem_at_top [preorder α] [no_top_order α] (x : α) : Ioi x ∈ (at_top : filter α) := let ⟨z, hz⟩ := no_top x in mem_sets_of_superset (mem_at_top z) $ λ y h, lt_of_lt_of_le hz h lemma mem_at_bot [preorder α] (a : α) : {b : α | b ≤ a} ∈ @at_bot α _ := mem_infi_sets a $ subset.refl _ lemma Iio_mem_at_bot [preorder α] [no_bot_order α] (x : α) : Iio x ∈ (at_bot : filter α) := let ⟨z, hz⟩ := no_bot x in mem_sets_of_superset (mem_at_bot z) $ λ y h, lt_of_le_of_lt h hz lemma at_top_basis [nonempty α] [semilattice_sup α] : (@at_top α _).has_basis (λ _, true) Ici := has_basis_infi_principal (directed_of_sup $ λ a b, Ici_subset_Ici.2) lemma at_top_basis' [semilattice_sup α] (a : α) : (@at_top α _).has_basis (λ x, a ≤ x) Ici := ⟨λ t, (@at_top_basis α ⟨a⟩ _).mem_iff.trans ⟨λ ⟨x, _, hx⟩, ⟨x ⊔ a, le_sup_right, λ y hy, hx (le_trans le_sup_left hy)⟩, λ ⟨x, _, hx⟩, ⟨x, trivial, hx⟩⟩⟩ lemma at_bot_basis [nonempty α] [semilattice_inf α] : (@at_bot α _).has_basis (λ _, true) Iic := @at_top_basis (order_dual α) _ _ lemma at_bot_basis' [semilattice_inf α] (a : α) : (@at_bot α _).has_basis (λ x, x ≤ a) Iic := @at_top_basis' (order_dual α) _ _ @[instance] lemma at_top_ne_bot [nonempty α] [semilattice_sup α] : ne_bot (at_top : filter α) := at_top_basis.ne_bot_iff.2 $ λ a _, nonempty_Ici @[instance] lemma at_bot_ne_bot [nonempty α] [semilattice_inf α] : ne_bot (at_bot : filter α) := @at_top_ne_bot (order_dual α) _ _ @[simp] lemma mem_at_top_sets [nonempty α] [semilattice_sup α] {s : set α} : s ∈ (at_top : filter α) ↔ ∃a:α, ∀b≥a, b ∈ s := at_top_basis.mem_iff.trans $ exists_congr $ λ _, exists_const _ @[simp] lemma mem_at_bot_sets [nonempty α] [semilattice_inf α] {s : set α} : s ∈ (at_bot : filter α) ↔ ∃a:α, ∀b≤a, b ∈ s := @mem_at_top_sets (order_dual α) _ _ _ @[simp] lemma eventually_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} : (∀ᶠ x in at_top, p x) ↔ (∃ a, ∀ b ≥ a, p b) := mem_at_top_sets @[simp] lemma eventually_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop} : (∀ᶠ x in at_bot, p x) ↔ (∃ a, ∀ b ≤ a, p b) := mem_at_bot_sets lemma eventually_ge_at_top [preorder α] (a : α) : ∀ᶠ x in at_top, a ≤ x := mem_at_top a lemma eventually_le_at_bot [preorder α] (a : α) : ∀ᶠ x in at_bot, x ≤ a := mem_at_bot a lemma eventually_gt_at_top [preorder α] [no_top_order α] (a : α) : ∀ᶠ x in at_top, a < x := Ioi_mem_at_top a lemma eventually_lt_at_bot [preorder α] [no_bot_order α] (a : α) : ∀ᶠ x in at_bot, x < a := Iio_mem_at_bot a lemma at_top_basis_Ioi [nonempty α] [semilattice_sup α] [no_top_order α] : (@at_top α _).has_basis (λ _, true) Ioi := at_top_basis.to_has_basis (λ a ha, ⟨a, ha, Ioi_subset_Ici_self⟩) $ λ a ha, (no_top a).imp $ λ b hb, ⟨ha, Ici_subset_Ioi.2 hb⟩ lemma at_top_countable_basis [nonempty α] [semilattice_sup α] [encodable α] : has_countable_basis (at_top : filter α) (λ _, true) Ici := { countable := countable_encodable _, .. at_top_basis } lemma at_bot_countable_basis [nonempty α] [semilattice_inf α] [encodable α] : has_countable_basis (at_bot : filter α) (λ _, true) Iic := { countable := countable_encodable _, .. at_bot_basis } lemma is_countably_generated_at_top [nonempty α] [semilattice_sup α] [encodable α] : (at_top : filter $ α).is_countably_generated := at_top_countable_basis.is_countably_generated lemma is_countably_generated_at_bot [nonempty α] [semilattice_inf α] [encodable α] : (at_bot : filter $ α).is_countably_generated := at_bot_countable_basis.is_countably_generated lemma order_top.at_top_eq (α) [order_top α] : (at_top : filter α) = pure ⊤ := le_antisymm (le_pure_iff.2 $ (eventually_ge_at_top ⊤).mono $ λ b, top_unique) (le_infi $ λ b, le_principal_iff.2 le_top) lemma order_bot.at_bot_eq (α) [order_bot α] : (at_bot : filter α) = pure ⊥ := @order_top.at_top_eq (order_dual α) _ @[nontriviality] lemma subsingleton.at_top_eq (α) [subsingleton α] [preorder α] : (at_top : filter α) = ⊤ := begin refine top_unique (λ s hs x, _), letI : unique α := ⟨⟨x⟩, λ y, subsingleton.elim y x⟩, rw [at_top, infi_unique, unique.default_eq x, mem_principal_sets] at hs, exact hs left_mem_Ici end @[nontriviality] lemma subsingleton.at_bot_eq (α) [subsingleton α] [preorder α] : (at_bot : filter α) = ⊤ := @subsingleton.at_top_eq (order_dual α) _ _ lemma tendsto_at_top_pure [order_top α] (f : α → β) : tendsto f at_top (pure $ f ⊤) := (order_top.at_top_eq α).symm ▸ tendsto_pure_pure _ _ lemma tendsto_at_bot_pure [order_bot α] (f : α → β) : tendsto f at_bot (pure $ f ⊥) := @tendsto_at_top_pure (order_dual α) _ _ _ lemma eventually.exists_forall_of_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} (h : ∀ᶠ x in at_top, p x) : ∃ a, ∀ b ≥ a, p b := eventually_at_top.mp h lemma eventually.exists_forall_of_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop} (h : ∀ᶠ x in at_bot, p x) : ∃ a, ∀ b ≤ a, p b := eventually_at_bot.mp h lemma frequently_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} : (∃ᶠ x in at_top, p x) ↔ (∀ a, ∃ b ≥ a, p b) := by simp [at_top_basis.frequently_iff] lemma frequently_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop} : (∃ᶠ x in at_bot, p x) ↔ (∀ a, ∃ b ≤ a, p b) := @frequently_at_top (order_dual α) _ _ _ lemma frequently_at_top' [semilattice_sup α] [nonempty α] [no_top_order α] {p : α → Prop} : (∃ᶠ x in at_top, p x) ↔ (∀ a, ∃ b > a, p b) := by simp [at_top_basis_Ioi.frequently_iff] lemma frequently_at_bot' [semilattice_inf α] [nonempty α] [no_bot_order α] {p : α → Prop} : (∃ᶠ x in at_bot, p x) ↔ (∀ a, ∃ b < a, p b) := @frequently_at_top' (order_dual α) _ _ _ _ lemma frequently.forall_exists_of_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} (h : ∃ᶠ x in at_top, p x) : ∀ a, ∃ b ≥ a, p b := frequently_at_top.mp h lemma frequently.forall_exists_of_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop} (h : ∃ᶠ x in at_bot, p x) : ∀ a, ∃ b ≤ a, p b := frequently_at_bot.mp h lemma map_at_top_eq [nonempty α] [semilattice_sup α] {f : α → β} : at_top.map f = (⨅a, 𝓟 $ f '' {a' | a ≤ a'}) := (at_top_basis.map _).eq_infi lemma map_at_bot_eq [nonempty α] [semilattice_inf α] {f : α → β} : at_bot.map f = (⨅a, 𝓟 $ f '' {a' | a' ≤ a}) := @map_at_top_eq (order_dual α) _ _ _ _ lemma tendsto_at_top [preorder β] {m : α → β} {f : filter α} : tendsto m f at_top ↔ (∀b, ∀ᶠ a in f, b ≤ m a) := by simp only [at_top, tendsto_infi, tendsto_principal, mem_Ici] lemma tendsto_at_bot [preorder β] {m : α → β} {f : filter α} : tendsto m f at_bot ↔ (∀b, ∀ᶠ a in f, m a ≤ b) := @tendsto_at_top α (order_dual β) _ m f lemma tendsto_at_top_mono' [preorder β] (l : filter α) ⦃f₁ f₂ : α → β⦄ (h : f₁ ≤ᶠ[l] f₂) : tendsto f₁ l at_top → tendsto f₂ l at_top := assume h₁, tendsto_at_top.2 $ λ b, mp_sets (tendsto_at_top.1 h₁ b) (monotone_mem_sets (λ a ha ha₁, le_trans ha₁ ha) h) lemma tendsto_at_bot_mono' [preorder β] (l : filter α) ⦃f₁ f₂ : α → β⦄ (h : f₁ ≤ᶠ[l] f₂) : tendsto f₂ l at_bot → tendsto f₁ l at_bot := @tendsto_at_top_mono' _ (order_dual β) _ _ _ _ h lemma tendsto_at_top_mono [preorder β] {l : filter α} {f g : α → β} (h : ∀ n, f n ≤ g n) : tendsto f l at_top → tendsto g l at_top := tendsto_at_top_mono' l $ eventually_of_forall h lemma tendsto_at_bot_mono [preorder β] {l : filter α} {f g : α → β} (h : ∀ n, f n ≤ g n) : tendsto g l at_bot → tendsto f l at_bot := @tendsto_at_top_mono _ (order_dual β) _ _ _ _ h /-! ### Sequences -/ lemma inf_map_at_top_ne_bot_iff [semilattice_sup α] [nonempty α] {F : filter β} {u : α → β} : ne_bot (F ⊓ (map u at_top)) ↔ ∀ U ∈ F, ∀ N, ∃ n ≥ N, u n ∈ U := by simp_rw [inf_ne_bot_iff_frequently_left, frequently_map, frequently_at_top]; refl lemma inf_map_at_bot_ne_bot_iff [semilattice_inf α] [nonempty α] {F : filter β} {u : α → β} : ne_bot (F ⊓ (map u at_bot)) ↔ ∀ U ∈ F, ∀ N, ∃ n ≤ N, u n ∈ U := @inf_map_at_top_ne_bot_iff (order_dual α) _ _ _ _ _ lemma extraction_of_frequently_at_top' {P : ℕ → Prop} (h : ∀ N, ∃ n > N, P n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P (φ n) := begin choose u hu using h, cases forall_and_distrib.mp hu with hu hu', exact ⟨u ∘ (nat.rec 0 (λ n v, u v)), strict_mono.nat (λ n, hu _), λ n, hu' _⟩, end lemma extraction_of_frequently_at_top {P : ℕ → Prop} (h : ∃ᶠ n in at_top, P n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P (φ n) := begin rw frequently_at_top' at h, exact extraction_of_frequently_at_top' h, end lemma extraction_of_eventually_at_top {P : ℕ → Prop} (h : ∀ᶠ n in at_top, P n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P (φ n) := extraction_of_frequently_at_top h.frequently lemma extraction_forall_of_frequently {P : ℕ → ℕ → Prop} (h : ∀ n, ∃ᶠ k in at_top, P n k) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P n (φ n) := begin simp only [frequently_at_top'] at h, choose u hu hu' using h, use (λ n, nat.rec_on n (u 0 0) (λ n v, u (n+1) v) : ℕ → ℕ), split, { apply strict_mono.nat, intro n, apply hu }, { intros n, cases n ; simp [hu'] }, end lemma extraction_forall_of_eventually {P : ℕ → ℕ → Prop} (h : ∀ n, ∀ᶠ k in at_top, P n k) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P n (φ n) := extraction_forall_of_frequently (λ n, (h n).frequently) lemma extraction_forall_of_eventually' {P : ℕ → ℕ → Prop} (h : ∀ n, ∃ N, ∀ k ≥ N, P n k) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P n (φ n) := extraction_forall_of_eventually (by simp [eventually_at_top, h]) lemma exists_le_of_tendsto_at_top [semilattice_sup α] [preorder β] {u : α → β} (h : tendsto u at_top at_top) (a : α) (b : β) : ∃ a' ≥ a, b ≤ u a' := begin have : ∀ᶠ x in at_top, a ≤ x ∧ b ≤ u x := (eventually_ge_at_top a).and (h.eventually $ eventually_ge_at_top b), haveI : nonempty α := ⟨a⟩, rcases this.exists with ⟨a', ha, hb⟩, exact ⟨a', ha, hb⟩ end @[nolint ge_or_gt] -- see Note [nolint_ge] lemma exists_le_of_tendsto_at_bot [semilattice_sup α] [preorder β] {u : α → β} (h : tendsto u at_top at_bot) : ∀ a b, ∃ a' ≥ a, u a' ≤ b := @exists_le_of_tendsto_at_top _ (order_dual β) _ _ _ h lemma exists_lt_of_tendsto_at_top [semilattice_sup α] [preorder β] [no_top_order β] {u : α → β} (h : tendsto u at_top at_top) (a : α) (b : β) : ∃ a' ≥ a, b < u a' := begin cases no_top b with b' hb', rcases exists_le_of_tendsto_at_top h a b' with ⟨a', ha', ha''⟩, exact ⟨a', ha', lt_of_lt_of_le hb' ha''⟩ end @[nolint ge_or_gt] -- see Note [nolint_ge] lemma exists_lt_of_tendsto_at_bot [semilattice_sup α] [preorder β] [no_bot_order β] {u : α → β} (h : tendsto u at_top at_bot) : ∀ a b, ∃ a' ≥ a, u a' < b := @exists_lt_of_tendsto_at_top _ (order_dual β) _ _ _ _ h /-- If `u` is a sequence which is unbounded above, then after any point, it reaches a value strictly greater than all previous values. -/ lemma high_scores [linear_order β] [no_top_order β] {u : ℕ → β} (hu : tendsto u at_top at_top) : ∀ N, ∃ n ≥ N, ∀ k < n, u k < u n := begin intros N, let A := finset.image u (finset.range $ N+1), -- A = {u 0, ..., u N} have Ane : A.nonempty, from ⟨u 0, finset.mem_image_of_mem _ (finset.mem_range.mpr $ nat.zero_lt_succ _)⟩, let M := finset.max' A Ane, have ex : ∃ n ≥ N, M < u n, from exists_lt_of_tendsto_at_top hu _ _, obtain ⟨n, hnN, hnM, hn_min⟩ : ∃ n, N ≤ n ∧ M < u n ∧ ∀ k, N ≤ k → k < n → u k ≤ M, { use nat.find ex, rw ← and_assoc, split, { simpa using nat.find_spec ex }, { intros k hk hk', simpa [hk] using nat.find_min ex hk' } }, use [n, hnN], intros k hk, by_cases H : k ≤ N, { have : u k ∈ A, from finset.mem_image_of_mem _ (finset.mem_range.mpr $ nat.lt_succ_of_le H), have : u k ≤ M, from finset.le_max' A (u k) this, exact lt_of_le_of_lt this hnM }, { push_neg at H, calc u k ≤ M : hn_min k (le_of_lt H) hk ... < u n : hnM }, end /-- If `u` is a sequence which is unbounded below, then after any point, it reaches a value strictly smaller than all previous values. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma low_scores [linear_order β] [no_bot_order β] {u : ℕ → β} (hu : tendsto u at_top at_bot) : ∀ N, ∃ n ≥ N, ∀ k < n, u n < u k := @high_scores (order_dual β) _ _ _ hu /-- If `u` is a sequence which is unbounded above, then it `frequently` reaches a value strictly greater than all previous values. -/ lemma frequently_high_scores [linear_order β] [no_top_order β] {u : ℕ → β} (hu : tendsto u at_top at_top) : ∃ᶠ n in at_top, ∀ k < n, u k < u n := by simpa [frequently_at_top] using high_scores hu /-- If `u` is a sequence which is unbounded below, then it `frequently` reaches a value strictly smaller than all previous values. -/ lemma frequently_low_scores [linear_order β] [no_bot_order β] {u : ℕ → β} (hu : tendsto u at_top at_bot) : ∃ᶠ n in at_top, ∀ k < n, u n < u k := @frequently_high_scores (order_dual β) _ _ _ hu lemma strict_mono_subseq_of_tendsto_at_top {β : Type*} [linear_order β] [no_top_order β] {u : ℕ → β} (hu : tendsto u at_top at_top) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ strict_mono (u ∘ φ) := let ⟨φ, h, h'⟩ := extraction_of_frequently_at_top (frequently_high_scores hu) in ⟨φ, h, λ n m hnm, h' m _ (h hnm)⟩ lemma strict_mono_subseq_of_id_le {u : ℕ → ℕ} (hu : ∀ n, n ≤ u n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ strict_mono (u ∘ φ) := strict_mono_subseq_of_tendsto_at_top (tendsto_at_top_mono hu tendsto_id) lemma _root_.strict_mono.tendsto_at_top {φ : ℕ → ℕ} (h : strict_mono φ) : tendsto φ at_top at_top := tendsto_at_top_mono h.id_le tendsto_id section ordered_add_comm_monoid variables [ordered_add_comm_monoid β] {l : filter α} {f g : α → β} lemma tendsto_at_top_add_nonneg_left' (hf : ∀ᶠ x in l, 0 ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_mono' l (hf.mono (λ x, le_add_of_nonneg_left)) hg lemma tendsto_at_bot_add_nonpos_left' (hf : ∀ᶠ x in l, f x ≤ 0) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_nonneg_left' _ (order_dual β) _ _ _ _ hf hg lemma tendsto_at_top_add_nonneg_left (hf : ∀ x, 0 ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_nonneg_left' (eventually_of_forall hf) hg lemma tendsto_at_bot_add_nonpos_left (hf : ∀ x, f x ≤ 0) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_nonneg_left _ (order_dual β) _ _ _ _ hf hg lemma tendsto_at_top_add_nonneg_right' (hf : tendsto f l at_top) (hg : ∀ᶠ x in l, 0 ≤ g x) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_mono' l (monotone_mem_sets (λ x, le_add_of_nonneg_right) hg) hf lemma tendsto_at_bot_add_nonpos_right' (hf : tendsto f l at_bot) (hg : ∀ᶠ x in l, g x ≤ 0) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_nonneg_right' _ (order_dual β) _ _ _ _ hf hg lemma tendsto_at_top_add_nonneg_right (hf : tendsto f l at_top) (hg : ∀ x, 0 ≤ g x) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_nonneg_right' hf (eventually_of_forall hg) lemma tendsto_at_bot_add_nonpos_right (hf : tendsto f l at_bot) (hg : ∀ x, g x ≤ 0) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_nonneg_right _ (order_dual β) _ _ _ _ hf hg lemma tendsto_at_top_add (hf : tendsto f l at_top) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_nonneg_left' (tendsto_at_top.mp hf 0) hg lemma tendsto_at_bot_add (hf : tendsto f l at_bot) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add _ (order_dual β) _ _ _ _ hf hg lemma tendsto.nsmul_at_top (hf : tendsto f l at_top) {n : ℕ} (hn : 0 < n) : tendsto (λ x, n • f x) l at_top := tendsto_at_top.2 $ λ y, (tendsto_at_top.1 hf y).mp $ (tendsto_at_top.1 hf 0).mono $ λ x h₀ hy, calc y ≤ f x : hy ... = 1 • f x : (one_nsmul _).symm ... ≤ n • f x : nsmul_le_nsmul h₀ hn lemma tendsto.nsmul_at_bot (hf : tendsto f l at_bot) {n : ℕ} (hn : 0 < n) : tendsto (λ x, n • f x) l at_bot := @tendsto.nsmul_at_top α (order_dual β) _ l f hf n hn lemma tendsto_bit0_at_top : tendsto bit0 (at_top : filter β) at_top := tendsto_at_top_add tendsto_id tendsto_id lemma tendsto_bit0_at_bot : tendsto bit0 (at_bot : filter β) at_bot := tendsto_at_bot_add tendsto_id tendsto_id end ordered_add_comm_monoid section ordered_cancel_add_comm_monoid variables [ordered_cancel_add_comm_monoid β] {l : filter α} {f g : α → β} lemma tendsto_at_top_of_add_const_left (C : β) (hf : tendsto (λ x, C + f x) l at_top) : tendsto f l at_top := tendsto_at_top.2 $ assume b, (tendsto_at_top.1 hf (C + b)).mono (λ x, le_of_add_le_add_left) lemma tendsto_at_bot_of_add_const_left (C : β) (hf : tendsto (λ x, C + f x) l at_bot) : tendsto f l at_bot := @tendsto_at_top_of_add_const_left _ (order_dual β) _ _ _ C hf lemma tendsto_at_top_of_add_const_right (C : β) (hf : tendsto (λ x, f x + C) l at_top) : tendsto f l at_top := tendsto_at_top.2 $ assume b, (tendsto_at_top.1 hf (b + C)).mono (λ x, le_of_add_le_add_right) lemma tendsto_at_bot_of_add_const_right (C : β) (hf : tendsto (λ x, f x + C) l at_bot) : tendsto f l at_bot := @tendsto_at_top_of_add_const_right _ (order_dual β) _ _ _ C hf lemma tendsto_at_top_of_add_bdd_above_left' (C) (hC : ∀ᶠ x in l, f x ≤ C) (h : tendsto (λ x, f x + g x) l at_top) : tendsto g l at_top := tendsto_at_top_of_add_const_left C (tendsto_at_top_mono' l (hC.mono (λ x hx, add_le_add_right hx (g x))) h) lemma tendsto_at_bot_of_add_bdd_below_left' (C) (hC : ∀ᶠ x in l, C ≤ f x) (h : tendsto (λ x, f x + g x) l at_bot) : tendsto g l at_bot := @tendsto_at_top_of_add_bdd_above_left' _ (order_dual β) _ _ _ _ C hC h lemma tendsto_at_top_of_add_bdd_above_left (C) (hC : ∀ x, f x ≤ C) : tendsto (λ x, f x + g x) l at_top → tendsto g l at_top := tendsto_at_top_of_add_bdd_above_left' C (univ_mem_sets' hC) lemma tendsto_at_bot_of_add_bdd_below_left (C) (hC : ∀ x, C ≤ f x) : tendsto (λ x, f x + g x) l at_bot → tendsto g l at_bot := @tendsto_at_top_of_add_bdd_above_left _ (order_dual β) _ _ _ _ C hC lemma tendsto_at_top_of_add_bdd_above_right' (C) (hC : ∀ᶠ x in l, g x ≤ C) (h : tendsto (λ x, f x + g x) l at_top) : tendsto f l at_top := tendsto_at_top_of_add_const_right C (tendsto_at_top_mono' l (hC.mono (λ x hx, add_le_add_left hx (f x))) h) lemma tendsto_at_bot_of_add_bdd_below_right' (C) (hC : ∀ᶠ x in l, C ≤ g x) (h : tendsto (λ x, f x + g x) l at_bot) : tendsto f l at_bot := @tendsto_at_top_of_add_bdd_above_right' _ (order_dual β) _ _ _ _ C hC h lemma tendsto_at_top_of_add_bdd_above_right (C) (hC : ∀ x, g x ≤ C) : tendsto (λ x, f x + g x) l at_top → tendsto f l at_top := tendsto_at_top_of_add_bdd_above_right' C (univ_mem_sets' hC) lemma tendsto_at_bot_of_add_bdd_below_right (C) (hC : ∀ x, C ≤ g x) : tendsto (λ x, f x + g x) l at_bot → tendsto f l at_bot := @tendsto_at_top_of_add_bdd_above_right _ (order_dual β) _ _ _ _ C hC end ordered_cancel_add_comm_monoid section ordered_group variables [ordered_add_comm_group β] (l : filter α) {f g : α → β} lemma tendsto_at_top_add_left_of_le' (C : β) (hf : ∀ᶠ x in l, C ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := @tendsto_at_top_of_add_bdd_above_left' _ _ _ l (λ x, -(f x)) (λ x, f x + g x) (-C) (by simpa) (by simpa) lemma tendsto_at_bot_add_left_of_ge' (C : β) (hf : ∀ᶠ x in l, f x ≤ C) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_left_of_le' _ (order_dual β) _ _ _ _ C hf hg lemma tendsto_at_top_add_left_of_le (C : β) (hf : ∀ x, C ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_left_of_le' l C (univ_mem_sets' hf) hg lemma tendsto_at_bot_add_left_of_ge (C : β) (hf : ∀ x, f x ≤ C) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_left_of_le _ (order_dual β) _ _ _ _ C hf hg lemma tendsto_at_top_add_right_of_le' (C : β) (hf : tendsto f l at_top) (hg : ∀ᶠ x in l, C ≤ g x) : tendsto (λ x, f x + g x) l at_top := @tendsto_at_top_of_add_bdd_above_right' _ _ _ l (λ x, f x + g x) (λ x, -(g x)) (-C) (by simp [hg]) (by simp [hf]) lemma tendsto_at_bot_add_right_of_ge' (C : β) (hf : tendsto f l at_bot) (hg : ∀ᶠ x in l, g x ≤ C) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_right_of_le' _ (order_dual β) _ _ _ _ C hf hg lemma tendsto_at_top_add_right_of_le (C : β) (hf : tendsto f l at_top) (hg : ∀ x, C ≤ g x) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_right_of_le' l C hf (univ_mem_sets' hg) lemma tendsto_at_bot_add_right_of_ge (C : β) (hf : tendsto f l at_bot) (hg : ∀ x, g x ≤ C) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_right_of_le _ (order_dual β) _ _ _ _ C hf hg lemma tendsto_at_top_add_const_left (C : β) (hf : tendsto f l at_top) : tendsto (λ x, C + f x) l at_top := tendsto_at_top_add_left_of_le' l C (univ_mem_sets' $ λ _, le_refl C) hf lemma tendsto_at_bot_add_const_left (C : β) (hf : tendsto f l at_bot) : tendsto (λ x, C + f x) l at_bot := @tendsto_at_top_add_const_left _ (order_dual β) _ _ _ C hf lemma tendsto_at_top_add_const_right (C : β) (hf : tendsto f l at_top) : tendsto (λ x, f x + C) l at_top := tendsto_at_top_add_right_of_le' l C hf (univ_mem_sets' $ λ _, le_refl C) lemma tendsto_at_bot_add_const_right (C : β) (hf : tendsto f l at_bot) : tendsto (λ x, f x + C) l at_bot := @tendsto_at_top_add_const_right _ (order_dual β) _ _ _ C hf lemma tendsto_neg_at_top_at_bot : tendsto (has_neg.neg : β → β) at_top at_bot := begin simp only [tendsto_at_bot, neg_le], exact λ b, eventually_ge_at_top _ end lemma tendsto_neg_at_bot_at_top : tendsto (has_neg.neg : β → β) at_bot at_top := @tendsto_neg_at_top_at_bot (order_dual β) _ end ordered_group section ordered_semiring variables [ordered_semiring α] {l : filter β} {f g : β → α} lemma tendsto_bit1_at_top : tendsto bit1 (at_top : filter α) at_top := tendsto_at_top_add_nonneg_right tendsto_bit0_at_top (λ _, zero_le_one) lemma tendsto.at_top_mul_at_top (hf : tendsto f l at_top) (hg : tendsto g l at_top) : tendsto (λ x, f x * g x) l at_top := begin refine tendsto_at_top_mono' _ _ hg, filter_upwards [hg.eventually (eventually_ge_at_top 0), hf.eventually (eventually_ge_at_top 1)], exact λ x, le_mul_of_one_le_left end lemma tendsto_mul_self_at_top : tendsto (λ x : α, x * x) at_top at_top := tendsto_id.at_top_mul_at_top tendsto_id /-- The monomial function `x^n` tends to `+∞` at `+∞` for any positive natural `n`. A version for positive real powers exists as `tendsto_rpow_at_top`. -/ lemma tendsto_pow_at_top {n : ℕ} (hn : 1 ≤ n) : tendsto (λ x : α, x ^ n) at_top at_top := begin refine tendsto_at_top_mono' _ ((eventually_ge_at_top 1).mono $ λ x hx, _) tendsto_id, simpa only [pow_one] using pow_le_pow hx hn end end ordered_semiring lemma zero_pow_eventually_eq [monoid_with_zero α] : (λ n : ℕ, (0 : α) ^ n) =ᶠ[at_top] (λ n, 0) := eventually_at_top.2 ⟨1, λ n hn, zero_pow (zero_lt_one.trans_le hn)⟩ section ordered_ring variables [ordered_ring α] {l : filter β} {f g : β → α} lemma tendsto.at_top_mul_at_bot (hf : tendsto f l at_top) (hg : tendsto g l at_bot) : tendsto (λ x, f x * g x) l at_bot := have _ := (hf.at_top_mul_at_top $ tendsto_neg_at_bot_at_top.comp hg), by simpa only [(∘), neg_mul_eq_mul_neg, neg_neg] using tendsto_neg_at_top_at_bot.comp this lemma tendsto.at_bot_mul_at_top (hf : tendsto f l at_bot) (hg : tendsto g l at_top) : tendsto (λ x, f x * g x) l at_bot := have tendsto (λ x, (-f x) * g x) l at_top := ( (tendsto_neg_at_bot_at_top.comp hf).at_top_mul_at_top hg), by simpa only [(∘), neg_mul_eq_neg_mul, neg_neg] using tendsto_neg_at_top_at_bot.comp this lemma tendsto.at_bot_mul_at_bot (hf : tendsto f l at_bot) (hg : tendsto g l at_bot) : tendsto (λ x, f x * g x) l at_top := have tendsto (λ x, (-f x) * (-g x)) l at_top := (tendsto_neg_at_bot_at_top.comp hf).at_top_mul_at_top (tendsto_neg_at_bot_at_top.comp hg), by simpa only [neg_mul_neg] using this end ordered_ring section linear_ordered_add_comm_group variables [linear_ordered_add_comm_group α] /-- $\lim_{x\to+\infty}|x|=+\infty$ -/ lemma tendsto_abs_at_top_at_top : tendsto (abs : α → α) at_top at_top := tendsto_at_top_mono le_abs_self tendsto_id /-- $\lim_{x\to-\infty}|x|=+\infty$ -/ lemma tendsto_abs_at_bot_at_top : tendsto (abs : α → α) at_bot at_top := tendsto_at_top_mono neg_le_abs_self tendsto_neg_at_bot_at_top end linear_ordered_add_comm_group section linear_ordered_semiring variables [linear_ordered_semiring α] {l : filter β} {f : β → α} lemma tendsto.at_top_of_const_mul {c : α} (hc : 0 < c) (hf : tendsto (λ x, c * f x) l at_top) : tendsto f l at_top := tendsto_at_top.2 $ λ b, (tendsto_at_top.1 hf (c * b)).mono $ λ x hx, le_of_mul_le_mul_left hx hc lemma tendsto.at_top_of_mul_const {c : α} (hc : 0 < c) (hf : tendsto (λ x, f x * c) l at_top) : tendsto f l at_top := tendsto_at_top.2 $ λ b, (tendsto_at_top.1 hf (b * c)).mono $ λ x hx, le_of_mul_le_mul_right hx hc end linear_ordered_semiring lemma nonneg_of_eventually_pow_nonneg [linear_ordered_ring α] {a : α} (h : ∀ᶠ n in at_top, 0 ≤ a ^ (n : ℕ)) : 0 ≤ a := let ⟨n, hn⟩ := (tendsto_bit1_at_top.eventually h).exists in pow_bit1_nonneg_iff.1 hn section linear_ordered_field variables [linear_ordered_field α] {l : filter β} {f : β → α} {r : α} /-- If a function tends to infinity along a filter, then this function multiplied by a positive constant (on the left) also tends to infinity. For a version working in `ℕ` or `ℤ`, use `filter.tendsto.const_mul_at_top'` instead. -/ lemma tendsto.const_mul_at_top (hr : 0 < r) (hf : tendsto f l at_top) : tendsto (λx, r * f x) l at_top := tendsto.at_top_of_const_mul (inv_pos.2 hr) $ by simpa only [inv_mul_cancel_left' hr.ne'] /-- If a function tends to infinity along a filter, then this function multiplied by a positive constant (on the right) also tends to infinity. For a version working in `ℕ` or `ℤ`, use `filter.tendsto.at_top_mul_const'` instead. -/ lemma tendsto.at_top_mul_const (hr : 0 < r) (hf : tendsto f l at_top) : tendsto (λx, f x * r) l at_top := by simpa only [mul_comm] using hf.const_mul_at_top hr /-- If a function tends to infinity along a filter, then this function divided by a positive constant also tends to infinity. -/ lemma tendsto.at_top_div_const (hr : 0 < r) (hf : tendsto f l at_top) : tendsto (λx, f x / r) l at_top := by simpa only [div_eq_mul_inv] using hf.at_top_mul_const (inv_pos.2 hr) /-- If a function tends to infinity along a filter, then this function multiplied by a negative constant (on the left) tends to negative infinity. -/ lemma tendsto.neg_const_mul_at_top (hr : r < 0) (hf : tendsto f l at_top) : tendsto (λ x, r * f x) l at_bot := by simpa only [(∘), neg_mul_eq_neg_mul, neg_neg] using tendsto_neg_at_top_at_bot.comp (hf.const_mul_at_top (neg_pos.2 hr)) /-- If a function tends to infinity along a filter, then this function multiplied by a negative constant (on the right) tends to negative infinity. -/ lemma tendsto.at_top_mul_neg_const (hr : r < 0) (hf : tendsto f l at_top) : tendsto (λ x, f x * r) l at_bot := by simpa only [mul_comm] using hf.neg_const_mul_at_top hr /-- If a function tends to negative infinity along a filter, then this function multiplied by a positive constant (on the left) also tends to negative infinity. -/ lemma tendsto.const_mul_at_bot (hr : 0 < r) (hf : tendsto f l at_bot) : tendsto (λx, r * f x) l at_bot := by simpa only [(∘), neg_mul_eq_mul_neg, neg_neg] using tendsto_neg_at_top_at_bot.comp ((tendsto_neg_at_bot_at_top.comp hf).const_mul_at_top hr) /-- If a function tends to negative infinity along a filter, then this function multiplied by a positive constant (on the right) also tends to negative infinity. -/ lemma tendsto.at_bot_mul_const (hr : 0 < r) (hf : tendsto f l at_bot) : tendsto (λx, f x * r) l at_bot := by simpa only [mul_comm] using hf.const_mul_at_bot hr /-- If a function tends to negative infinity along a filter, then this function divided by a positive constant also tends to negative infinity. -/ lemma tendsto.at_bot_div_const (hr : 0 < r) (hf : tendsto f l at_bot) : tendsto (λx, f x / r) l at_bot := by simpa only [div_eq_mul_inv] using hf.at_bot_mul_const (inv_pos.2 hr) /-- If a function tends to negative infinity along a filter, then this function multiplied by a negative constant (on the left) tends to positive infinity. -/ lemma tendsto.neg_const_mul_at_bot (hr : r < 0) (hf : tendsto f l at_bot) : tendsto (λ x, r * f x) l at_top := by simpa only [(∘), neg_mul_eq_neg_mul, neg_neg] using tendsto_neg_at_bot_at_top.comp (hf.const_mul_at_bot (neg_pos.2 hr)) /-- If a function tends to negative infinity along a filter, then this function multiplied by a negative constant (on the right) tends to positive infinity. -/ lemma tendsto.at_bot_mul_neg_const (hr : r < 0) (hf : tendsto f l at_bot) : tendsto (λ x, f x * r) l at_top := by simpa only [mul_comm] using hf.neg_const_mul_at_bot hr lemma tendsto_const_mul_pow_at_top {c : α} {n : ℕ} (hn : 1 ≤ n) (hc : 0 < c) : tendsto (λ x, c * x^n) at_top at_top := tendsto.const_mul_at_top hc (tendsto_pow_at_top hn) lemma tendsto_const_mul_pow_at_top_iff (c : α) (n : ℕ) : tendsto (λ x, c * x^n) at_top at_top ↔ 1 ≤ n ∧ 0 < c := begin refine ⟨λ h, _, λ h, tendsto_const_mul_pow_at_top h.1 h.2⟩, simp only [tendsto_at_top, eventually_at_top] at h, have : 0 < c := let ⟨x, hx⟩ := h 1 in pos_of_mul_pos_right (lt_of_lt_of_le zero_lt_one (hx (max x 1) (le_max_left x 1))) (pow_nonneg (le_trans zero_le_one (le_max_right x 1)) n), refine ⟨nat.succ_le_iff.mp (lt_of_le_of_ne (zero_le n) (ne.symm (λ hn, _))), this⟩, obtain ⟨x, hx⟩ := h (c + 1), specialize hx x le_rfl, rw [hn, pow_zero, mul_one, add_le_iff_nonpos_right] at hx, exact absurd hx (not_le.mpr zero_lt_one), end lemma tendsto_neg_const_mul_pow_at_top {c : α} {n : ℕ} (hn : 1 ≤ n) (hc : c < 0) : tendsto (λ x, c * x^n) at_top at_bot := tendsto.neg_const_mul_at_top hc (tendsto_pow_at_top hn) lemma tendsto_neg_const_mul_pow_at_top_iff (c : α) (n : ℕ) : tendsto (λ x, c * x^n) at_top at_bot ↔ 1 ≤ n ∧ c < 0 := begin refine ⟨λ h, _, λ h, tendsto_neg_const_mul_pow_at_top h.1 h.2⟩, simp only [tendsto_at_bot, eventually_at_top] at h, have : c < 0 := let ⟨x, hx⟩ := h (-1) in neg_of_mul_neg_right (lt_of_le_of_lt (hx (max x 1) (le_max_left x 1)) (by simp [zero_lt_one])) (pow_nonneg (le_trans zero_le_one (le_max_right x 1)) n), refine ⟨nat.succ_le_iff.mp (lt_of_le_of_ne (zero_le n) (ne.symm (λ hn, _))), this⟩, obtain ⟨x, hx⟩ := h (c - 1), specialize hx x le_rfl, rw [hn, pow_zero, mul_one, le_sub, sub_self] at hx, exact absurd hx (not_le.mpr zero_lt_one), end end linear_ordered_field open_locale filter lemma tendsto_at_top' [nonempty α] [semilattice_sup α] {f : α → β} {l : filter β} : tendsto f at_top l ↔ (∀s ∈ l, ∃a, ∀b≥a, f b ∈ s) := by simp only [tendsto_def, mem_at_top_sets]; refl lemma tendsto_at_bot' [nonempty α] [semilattice_inf α] {f : α → β} {l : filter β} : tendsto f at_bot l ↔ (∀s ∈ l, ∃a, ∀b≤a, f b ∈ s) := @tendsto_at_top' (order_dual α) _ _ _ _ _ theorem tendsto_at_top_principal [nonempty β] [semilattice_sup β] {f : β → α} {s : set α} : tendsto f at_top (𝓟 s) ↔ ∃N, ∀n≥N, f n ∈ s := by rw [tendsto_iff_comap, comap_principal, le_principal_iff, mem_at_top_sets]; refl theorem tendsto_at_bot_principal [nonempty β] [semilattice_inf β] {f : β → α} {s : set α} : tendsto f at_bot (𝓟 s) ↔ ∃N, ∀n≤N, f n ∈ s := @tendsto_at_top_principal _ (order_dual β) _ _ _ _ /-- A function `f` grows to `+∞` independent of an order-preserving embedding `e`. -/ lemma tendsto_at_top_at_top [nonempty α] [semilattice_sup α] [preorder β] {f : α → β} : tendsto f at_top at_top ↔ ∀ b : β, ∃ i : α, ∀ a : α, i ≤ a → b ≤ f a := iff.trans tendsto_infi $ forall_congr $ assume b, tendsto_at_top_principal lemma tendsto_at_top_at_bot [nonempty α] [semilattice_sup α] [preorder β] {f : α → β} : tendsto f at_top at_bot ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), i ≤ a → f a ≤ b := @tendsto_at_top_at_top α (order_dual β) _ _ _ f lemma tendsto_at_bot_at_top [nonempty α] [semilattice_inf α] [preorder β] {f : α → β} : tendsto f at_bot at_top ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), a ≤ i → b ≤ f a := @tendsto_at_top_at_top (order_dual α) β _ _ _ f lemma tendsto_at_bot_at_bot [nonempty α] [semilattice_inf α] [preorder β] {f : α → β} : tendsto f at_bot at_bot ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), a ≤ i → f a ≤ b := @tendsto_at_top_at_top (order_dual α) (order_dual β) _ _ _ f lemma tendsto_at_top_at_top_of_monotone [preorder α] [preorder β] {f : α → β} (hf : monotone f) (h : ∀ b, ∃ a, b ≤ f a) : tendsto f at_top at_top := tendsto_infi.2 $ λ b, tendsto_principal.2 $ let ⟨a, ha⟩ := h b in mem_sets_of_superset (mem_at_top a) $ λ a' ha', le_trans ha (hf ha') lemma tendsto_at_bot_at_bot_of_monotone [preorder α] [preorder β] {f : α → β} (hf : monotone f) (h : ∀ b, ∃ a, f a ≤ b) : tendsto f at_bot at_bot := tendsto_infi.2 $ λ b, tendsto_principal.2 $ let ⟨a, ha⟩ := h b in mem_sets_of_superset (mem_at_bot a) $ λ a' ha', le_trans (hf ha') ha lemma tendsto_at_top_at_top_iff_of_monotone [nonempty α] [semilattice_sup α] [preorder β] {f : α → β} (hf : monotone f) : tendsto f at_top at_top ↔ ∀ b : β, ∃ a : α, b ≤ f a := tendsto_at_top_at_top.trans $ forall_congr $ λ b, exists_congr $ λ a, ⟨λ h, h a (le_refl a), λ h a' ha', le_trans h $ hf ha'⟩ lemma tendsto_at_bot_at_bot_iff_of_monotone [nonempty α] [semilattice_inf α] [preorder β] {f : α → β} (hf : monotone f) : tendsto f at_bot at_bot ↔ ∀ b : β, ∃ a : α, f a ≤ b := tendsto_at_bot_at_bot.trans $ forall_congr $ λ b, exists_congr $ λ a, ⟨λ h, h a (le_refl a), λ h a' ha', le_trans (hf ha') h⟩ alias tendsto_at_top_at_top_of_monotone ← monotone.tendsto_at_top_at_top alias tendsto_at_bot_at_bot_of_monotone ← monotone.tendsto_at_bot_at_bot alias tendsto_at_top_at_top_iff_of_monotone ← monotone.tendsto_at_top_at_top_iff alias tendsto_at_bot_at_bot_iff_of_monotone ← monotone.tendsto_at_bot_at_bot_iff lemma tendsto_at_top_embedding [preorder β] [preorder γ] {f : α → β} {e : β → γ} {l : filter α} (hm : ∀b₁ b₂, e b₁ ≤ e b₂ ↔ b₁ ≤ b₂) (hu : ∀c, ∃b, c ≤ e b) : tendsto (e ∘ f) l at_top ↔ tendsto f l at_top := begin refine ⟨_, (tendsto_at_top_at_top_of_monotone (λ b₁ b₂, (hm b₁ b₂).2) hu).comp⟩, rw [tendsto_at_top, tendsto_at_top], exact λ hc b, (hc (e b)).mono (λ a, (hm b (f a)).1) end /-- A function `f` goes to `-∞` independent of an order-preserving embedding `e`. -/ lemma tendsto_at_bot_embedding [preorder β] [preorder γ] {f : α → β} {e : β → γ} {l : filter α} (hm : ∀b₁ b₂, e b₁ ≤ e b₂ ↔ b₁ ≤ b₂) (hu : ∀c, ∃b, e b ≤ c) : tendsto (e ∘ f) l at_bot ↔ tendsto f l at_bot := @tendsto_at_top_embedding α (order_dual β) (order_dual γ) _ _ f e l (function.swap hm) hu lemma tendsto_finset_range : tendsto finset.range at_top at_top := finset.range_mono.tendsto_at_top_at_top finset.exists_nat_subset_range lemma at_top_finset_eq_infi : (at_top : filter $ finset α) = ⨅ x : α, 𝓟 (Ici {x}) := begin refine le_antisymm (le_infi (λ i, le_principal_iff.2 $ mem_at_top {i})) _, refine le_infi (λ s, le_principal_iff.2 $ mem_infi_iff.2 _), refine ⟨↑s, s.finite_to_set, _, λ i, mem_principal_self _, _⟩, simp only [subset_def, mem_Inter, set_coe.forall, mem_Ici, finset.le_iff_subset, finset.mem_singleton, finset.subset_iff, forall_eq], dsimp, exact λ t, id end /-- If `f` is a monotone sequence of `finset`s and each `x` belongs to one of `f n`, then `tendsto f at_top at_top`. -/ lemma tendsto_at_top_finset_of_monotone [preorder β] {f : β → finset α} (h : monotone f) (h' : ∀ x : α, ∃ n, x ∈ f n) : tendsto f at_top at_top := begin simp only [at_top_finset_eq_infi, tendsto_infi, tendsto_principal], intro a, rcases h' a with ⟨b, hb⟩, exact eventually.mono (mem_at_top b) (λ b' hb', le_trans (finset.singleton_subset_iff.2 hb) (h hb')), end alias tendsto_at_top_finset_of_monotone ← monotone.tendsto_at_top_finset lemma tendsto_finset_image_at_top_at_top {i : β → γ} {j : γ → β} (h : function.left_inverse j i) : tendsto (finset.image j) at_top at_top := (finset.image_mono j).tendsto_at_top_finset $ assume a, ⟨{i a}, by simp only [finset.image_singleton, h a, finset.mem_singleton]⟩ lemma tendsto_finset_preimage_at_top_at_top {f : α → β} (hf : function.injective f) : tendsto (λ s : finset β, s.preimage f (hf.inj_on _)) at_top at_top := (finset.monotone_preimage hf).tendsto_at_top_finset $ λ x, ⟨{f x}, finset.mem_preimage.2 $ finset.mem_singleton_self _⟩ lemma prod_at_top_at_top_eq {β₁ β₂ : Type*} [semilattice_sup β₁] [semilattice_sup β₂] : (at_top : filter β₁) ×ᶠ (at_top : filter β₂) = (at_top : filter (β₁ × β₂)) := begin casesI (is_empty_or_nonempty β₁).symm, casesI (is_empty_or_nonempty β₂).symm, { simp [at_top, prod_infi_left, prod_infi_right, infi_prod], exact infi_comm, }, { simp only [at_top.filter_eq_bot_of_is_empty, prod_bot] }, { simp only [at_top.filter_eq_bot_of_is_empty, bot_prod] }, end lemma prod_at_bot_at_bot_eq {β₁ β₂ : Type*} [semilattice_inf β₁] [semilattice_inf β₂] : (at_bot : filter β₁) ×ᶠ (at_bot : filter β₂) = (at_bot : filter (β₁ × β₂)) := @prod_at_top_at_top_eq (order_dual β₁) (order_dual β₂) _ _ lemma prod_map_at_top_eq {α₁ α₂ β₁ β₂ : Type*} [semilattice_sup β₁] [semilattice_sup β₂] (u₁ : β₁ → α₁) (u₂ : β₂ → α₂) : (map u₁ at_top) ×ᶠ (map u₂ at_top) = map (prod.map u₁ u₂) at_top := by rw [prod_map_map_eq, prod_at_top_at_top_eq, prod.map_def] lemma prod_map_at_bot_eq {α₁ α₂ β₁ β₂ : Type*} [semilattice_inf β₁] [semilattice_inf β₂] (u₁ : β₁ → α₁) (u₂ : β₂ → α₂) : (map u₁ at_bot) ×ᶠ (map u₂ at_bot) = map (prod.map u₁ u₂) at_bot := @prod_map_at_top_eq _ _ (order_dual β₁) (order_dual β₂) _ _ _ _ lemma tendsto.subseq_mem {F : filter α} {V : ℕ → set α} (h : ∀ n, V n ∈ F) {u : ℕ → α} (hu : tendsto u at_top F) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, u (φ n) ∈ V n := extraction_forall_of_eventually' (λ n, tendsto_at_top'.mp hu _ (h n) : ∀ n, ∃ N, ∀ k ≥ N, u k ∈ V n) lemma tendsto_at_bot_diagonal [semilattice_inf α] : tendsto (λ a : α, (a, a)) at_bot at_bot := by { rw ← prod_at_bot_at_bot_eq, exact tendsto_id.prod_mk tendsto_id } lemma tendsto_at_top_diagonal [semilattice_sup α] : tendsto (λ a : α, (a, a)) at_top at_top := by { rw ← prod_at_top_at_top_eq, exact tendsto_id.prod_mk tendsto_id } lemma tendsto.prod_map_prod_at_bot [semilattice_inf γ] {F : filter α} {G : filter β} {f : α → γ} {g : β → γ} (hf : tendsto f F at_bot) (hg : tendsto g G at_bot) : tendsto (prod.map f g) (F ×ᶠ G) at_bot := by { rw ← prod_at_bot_at_bot_eq, exact hf.prod_map hg, } lemma tendsto.prod_map_prod_at_top [semilattice_sup γ] {F : filter α} {G : filter β} {f : α → γ} {g : β → γ} (hf : tendsto f F at_top) (hg : tendsto g G at_top) : tendsto (prod.map f g) (F ×ᶠ G) at_top := by { rw ← prod_at_top_at_top_eq, exact hf.prod_map hg, } lemma tendsto.prod_at_bot [semilattice_inf α] [semilattice_inf γ] {f g : α → γ} (hf : tendsto f at_bot at_bot) (hg : tendsto g at_bot at_bot) : tendsto (prod.map f g) at_bot at_bot := by { rw ← prod_at_bot_at_bot_eq, exact hf.prod_map_prod_at_bot hg, } lemma tendsto.prod_at_top [semilattice_sup α] [semilattice_sup γ] {f g : α → γ} (hf : tendsto f at_top at_top) (hg : tendsto g at_top at_top) : tendsto (prod.map f g) at_top at_top := by { rw ← prod_at_top_at_top_eq, exact hf.prod_map_prod_at_top hg, } lemma eventually_at_bot_prod_self [semilattice_inf α] [nonempty α] {p : α × α → Prop} : (∀ᶠ x in at_bot, p x) ↔ (∃ a, ∀ k l, k ≤ a → l ≤ a → p (k, l)) := by simp [← prod_at_bot_at_bot_eq, at_bot_basis.prod_self.eventually_iff] lemma eventually_at_top_prod_self [semilattice_sup α] [nonempty α] {p : α × α → Prop} : (∀ᶠ x in at_top, p x) ↔ (∃ a, ∀ k l, a ≤ k → a ≤ l → p (k, l)) := by simp [← prod_at_top_at_top_eq, at_top_basis.prod_self.eventually_iff] lemma eventually_at_bot_prod_self' [semilattice_inf α] [nonempty α] {p : α × α → Prop} : (∀ᶠ x in at_bot, p x) ↔ (∃ a, ∀ k ≤ a, ∀ l ≤ a, p (k, l)) := begin rw filter.eventually_at_bot_prod_self, apply exists_congr, tauto, end lemma eventually_at_top_prod_self' [semilattice_sup α] [nonempty α] {p : α × α → Prop} : (∀ᶠ x in at_top, p x) ↔ (∃ a, ∀ k ≥ a, ∀ l ≥ a, p (k, l)) := begin rw filter.eventually_at_top_prod_self, apply exists_congr, tauto, end /-- A function `f` maps upwards closed sets (at_top sets) to upwards closed sets when it is a Galois insertion. The Galois "insertion" and "connection" is weakened to only require it to be an insertion and a connetion above `b'`. -/ lemma map_at_top_eq_of_gc [semilattice_sup α] [semilattice_sup β] {f : α → β} (g : β → α) (b' : β) (hf : monotone f) (gc : ∀a, ∀b≥b', f a ≤ b ↔ a ≤ g b) (hgi : ∀b≥b', b ≤ f (g b)) : map f at_top = at_top := begin refine le_antisymm (hf.tendsto_at_top_at_top $ λ b, ⟨g (b ⊔ b'), le_sup_left.trans $ hgi _ le_sup_right⟩) _, rw [@map_at_top_eq _ _ ⟨g b'⟩], refine le_infi (λ a, infi_le_of_le (f a ⊔ b') $ principal_mono.2 $ λ b hb, _), rw [mem_Ici, sup_le_iff] at hb, exact ⟨g b, (gc _ _ hb.2).1 hb.1, le_antisymm ((gc _ _ hb.2).2 (le_refl _)) (hgi _ hb.2)⟩ end lemma map_at_bot_eq_of_gc [semilattice_inf α] [semilattice_inf β] {f : α → β} (g : β → α) (b' : β) (hf : monotone f) (gc : ∀a, ∀b≤b', b ≤ f a ↔ g b ≤ a) (hgi : ∀b≤b', f (g b) ≤ b) : map f at_bot = at_bot := @map_at_top_eq_of_gc (order_dual α) (order_dual β) _ _ _ _ _ hf.order_dual gc hgi lemma map_coe_at_top_of_Ici_subset [semilattice_sup α] {a : α} {s : set α} (h : Ici a ⊆ s) : map (coe : s → α) at_top = at_top := begin have : directed (≥) (λ x : s, 𝓟 (Ici x)), { intros x y, use ⟨x ⊔ y ⊔ a, h le_sup_right⟩, simp only [ge_iff_le, principal_mono, Ici_subset_Ici, ← subtype.coe_le_coe, subtype.coe_mk], exact ⟨le_sup_left.trans le_sup_left, le_sup_right.trans le_sup_left⟩ }, haveI : nonempty s := ⟨⟨a, h le_rfl⟩⟩, simp only [le_antisymm_iff, at_top, le_infi_iff, le_principal_iff, mem_map, mem_set_of_eq, map_infi_eq this, map_principal], split, { intro x, refine mem_sets_of_superset (mem_infi_sets ⟨x ⊔ a, h le_sup_right⟩ (mem_principal_self _)) _, rintro _ ⟨y, hy, rfl⟩, exact le_trans le_sup_left (subtype.coe_le_coe.2 hy) }, { intro x, filter_upwards [mem_at_top (↑x ⊔ a)], intros b hb, exact ⟨⟨b, h $ le_sup_right.trans hb⟩, subtype.coe_le_coe.1 (le_sup_left.trans hb), rfl⟩ } end /-- The image of the filter `at_top` on `Ici a` under the coercion equals `at_top`. -/ @[simp] lemma map_coe_Ici_at_top [semilattice_sup α] (a : α) : map (coe : Ici a → α) at_top = at_top := map_coe_at_top_of_Ici_subset (subset.refl _) /-- The image of the filter `at_top` on `Ioi a` under the coercion equals `at_top`. -/ @[simp] lemma map_coe_Ioi_at_top [semilattice_sup α] [no_top_order α] (a : α) : map (coe : Ioi a → α) at_top = at_top := begin rcases no_top a with ⟨b, hb⟩, exact map_coe_at_top_of_Ici_subset (Ici_subset_Ioi.2 hb) end /-- The `at_top` filter for an open interval `Ioi a` comes from the `at_top` filter in the ambient order. -/ lemma at_top_Ioi_eq [semilattice_sup α] (a : α) : at_top = comap (coe : Ioi a → α) at_top := begin nontriviality, rcases nontrivial_iff_nonempty.1 ‹_› with ⟨b, hb⟩, rw [← map_coe_at_top_of_Ici_subset (Ici_subset_Ioi.2 hb), comap_map subtype.coe_injective] end /-- The `at_top` filter for an open interval `Ici a` comes from the `at_top` filter in the ambient order. -/ lemma at_top_Ici_eq [semilattice_sup α] (a : α) : at_top = comap (coe : Ici a → α) at_top := by rw [← map_coe_Ici_at_top a, comap_map subtype.coe_injective] /-- The `at_bot` filter for an open interval `Iio a` comes from the `at_bot` filter in the ambient order. -/ @[simp] lemma map_coe_Iio_at_bot [semilattice_inf α] [no_bot_order α] (a : α) : map (coe : Iio a → α) at_bot = at_bot := @map_coe_Ioi_at_top (order_dual α) _ _ _ /-- The `at_bot` filter for an open interval `Iio a` comes from the `at_bot` filter in the ambient order. -/ lemma at_bot_Iio_eq [semilattice_inf α] (a : α) : at_bot = comap (coe : Iio a → α) at_bot := @at_top_Ioi_eq (order_dual α) _ _ /-- The `at_bot` filter for an open interval `Iic a` comes from the `at_bot` filter in the ambient order. -/ @[simp] lemma map_coe_Iic_at_bot [semilattice_inf α] (a : α) : map (coe : Iic a → α) at_bot = at_bot := @map_coe_Ici_at_top (order_dual α) _ _ /-- The `at_bot` filter for an open interval `Iic a` comes from the `at_bot` filter in the ambient order. -/ lemma at_bot_Iic_eq [semilattice_inf α] (a : α) : at_bot = comap (coe : Iic a → α) at_bot := @at_top_Ici_eq (order_dual α) _ _ lemma tendsto_Ioi_at_top [semilattice_sup α] {a : α} {f : β → Ioi a} {l : filter β} : tendsto f l at_top ↔ tendsto (λ x, (f x : α)) l at_top := by rw [at_top_Ioi_eq, tendsto_comap_iff] lemma tendsto_Iio_at_bot [semilattice_inf α] {a : α} {f : β → Iio a} {l : filter β} : tendsto f l at_bot ↔ tendsto (λ x, (f x : α)) l at_bot := by rw [at_bot_Iio_eq, tendsto_comap_iff] lemma tendsto_Ici_at_top [semilattice_sup α] {a : α} {f : β → Ici a} {l : filter β} : tendsto f l at_top ↔ tendsto (λ x, (f x : α)) l at_top := by rw [at_top_Ici_eq, tendsto_comap_iff] lemma tendsto_Iic_at_bot [semilattice_inf α] {a : α} {f : β → Iic a} {l : filter β} : tendsto f l at_bot ↔ tendsto (λ x, (f x : α)) l at_bot := by rw [at_bot_Iic_eq, tendsto_comap_iff] @[simp] lemma tendsto_comp_coe_Ioi_at_top [semilattice_sup α] [no_top_order α] {a : α} {f : α → β} {l : filter β} : tendsto (λ x : Ioi a, f x) at_top l ↔ tendsto f at_top l := by rw [← map_coe_Ioi_at_top a, tendsto_map'_iff] @[simp] lemma tendsto_comp_coe_Ici_at_top [semilattice_sup α] {a : α} {f : α → β} {l : filter β} : tendsto (λ x : Ici a, f x) at_top l ↔ tendsto f at_top l := by rw [← map_coe_Ici_at_top a, tendsto_map'_iff] @[simp] lemma tendsto_comp_coe_Iio_at_bot [semilattice_inf α] [no_bot_order α] {a : α} {f : α → β} {l : filter β} : tendsto (λ x : Iio a, f x) at_bot l ↔ tendsto f at_bot l := by rw [← map_coe_Iio_at_bot a, tendsto_map'_iff] @[simp] lemma tendsto_comp_coe_Iic_at_bot [semilattice_inf α] {a : α} {f : α → β} {l : filter β} : tendsto (λ x : Iic a, f x) at_bot l ↔ tendsto f at_bot l := by rw [← map_coe_Iic_at_bot a, tendsto_map'_iff] lemma map_add_at_top_eq_nat (k : ℕ) : map (λa, a + k) at_top = at_top := map_at_top_eq_of_gc (λa, a - k) k (assume a b h, add_le_add_right h k) (assume a b h, (nat.le_sub_right_iff_add_le h).symm) (assume a h, by rw [nat.sub_add_cancel h]) lemma map_sub_at_top_eq_nat (k : ℕ) : map (λa, a - k) at_top = at_top := map_at_top_eq_of_gc (λa, a + k) 0 (assume a b h, nat.sub_le_sub_right h _) (assume a b _, nat.sub_le_right_iff_le_add) (assume b _, by rw [nat.add_sub_cancel]) lemma tendsto_add_at_top_nat (k : ℕ) : tendsto (λa, a + k) at_top at_top := le_of_eq (map_add_at_top_eq_nat k) lemma tendsto_sub_at_top_nat (k : ℕ) : tendsto (λa, a - k) at_top at_top := le_of_eq (map_sub_at_top_eq_nat k) lemma tendsto_add_at_top_iff_nat {f : ℕ → α} {l : filter α} (k : ℕ) : tendsto (λn, f (n + k)) at_top l ↔ tendsto f at_top l := show tendsto (f ∘ (λn, n + k)) at_top l ↔ tendsto f at_top l, by rw [← tendsto_map'_iff, map_add_at_top_eq_nat] lemma map_div_at_top_eq_nat (k : ℕ) (hk : 0 < k) : map (λa, a / k) at_top = at_top := map_at_top_eq_of_gc (λb, b * k + (k - 1)) 1 (assume a b h, nat.div_le_div_right h) (assume a b _, calc a / k ≤ b ↔ a / k < b + 1 : by rw [← nat.succ_eq_add_one, nat.lt_succ_iff] ... ↔ a < (b + 1) * k : nat.div_lt_iff_lt_mul _ _ hk ... ↔ _ : begin cases k, exact (lt_irrefl _ hk).elim, simp [mul_add, add_mul, nat.succ_add, nat.lt_succ_iff] end) (assume b _, calc b = (b * k) / k : by rw [nat.mul_div_cancel b hk] ... ≤ (b * k + (k - 1)) / k : nat.div_le_div_right $ nat.le_add_right _ _) /-- If `u` is a monotone function with linear ordered codomain and the range of `u` is not bounded above, then `tendsto u at_top at_top`. -/ lemma tendsto_at_top_at_top_of_monotone' [preorder ι] [linear_order α] {u : ι → α} (h : monotone u) (H : ¬bdd_above (range u)) : tendsto u at_top at_top := begin apply h.tendsto_at_top_at_top, intro b, rcases not_bdd_above_iff.1 H b with ⟨_, ⟨N, rfl⟩, hN⟩, exact ⟨N, le_of_lt hN⟩, end /-- If `u` is a monotone function with linear ordered codomain and the range of `u` is not bounded below, then `tendsto u at_bot at_bot`. -/ lemma tendsto_at_bot_at_bot_of_monotone' [preorder ι] [linear_order α] {u : ι → α} (h : monotone u) (H : ¬bdd_below (range u)) : tendsto u at_bot at_bot := @tendsto_at_top_at_top_of_monotone' (order_dual ι) (order_dual α) _ _ _ h.order_dual H lemma unbounded_of_tendsto_at_top [nonempty α] [semilattice_sup α] [preorder β] [no_top_order β] {f : α → β} (h : tendsto f at_top at_top) : ¬ bdd_above (range f) := begin rintros ⟨M, hM⟩, cases mem_at_top_sets.mp (h $ Ioi_mem_at_top M) with a ha, apply lt_irrefl M, calc M < f a : ha a (le_refl _) ... ≤ M : hM (set.mem_range_self a) end lemma unbounded_of_tendsto_at_bot [nonempty α] [semilattice_sup α] [preorder β] [no_bot_order β] {f : α → β} (h : tendsto f at_top at_bot) : ¬ bdd_below (range f) := @unbounded_of_tendsto_at_top _ (order_dual β) _ _ _ _ _ h lemma unbounded_of_tendsto_at_top' [nonempty α] [semilattice_inf α] [preorder β] [no_top_order β] {f : α → β} (h : tendsto f at_bot at_top) : ¬ bdd_above (range f) := @unbounded_of_tendsto_at_top (order_dual α) _ _ _ _ _ _ h lemma unbounded_of_tendsto_at_bot' [nonempty α] [semilattice_inf α] [preorder β] [no_bot_order β] {f : α → β} (h : tendsto f at_bot at_bot) : ¬ bdd_below (range f) := @unbounded_of_tendsto_at_top (order_dual α) (order_dual β) _ _ _ _ _ h /-- If a monotone function `u : ι → α` tends to `at_top` along *some* non-trivial filter `l`, then it tends to `at_top` along `at_top`. -/ lemma tendsto_at_top_of_monotone_of_filter [preorder ι] [preorder α] {l : filter ι} {u : ι → α} (h : monotone u) [ne_bot l] (hu : tendsto u l at_top) : tendsto u at_top at_top := h.tendsto_at_top_at_top $ λ b, (hu.eventually (mem_at_top b)).exists /-- If a monotone function `u : ι → α` tends to `at_bot` along *some* non-trivial filter `l`, then it tends to `at_bot` along `at_bot`. -/ lemma tendsto_at_bot_of_monotone_of_filter [preorder ι] [preorder α] {l : filter ι} {u : ι → α} (h : monotone u) [ne_bot l] (hu : tendsto u l at_bot) : tendsto u at_bot at_bot := @tendsto_at_top_of_monotone_of_filter (order_dual ι) (order_dual α) _ _ _ _ h.order_dual _ hu lemma tendsto_at_top_of_monotone_of_subseq [preorder ι] [preorder α] {u : ι → α} {φ : ι' → ι} (h : monotone u) {l : filter ι'} [ne_bot l] (H : tendsto (u ∘ φ) l at_top) : tendsto u at_top at_top := tendsto_at_top_of_monotone_of_filter h (tendsto_map' H) lemma tendsto_at_bot_of_monotone_of_subseq [preorder ι] [preorder α] {u : ι → α} {φ : ι' → ι} (h : monotone u) {l : filter ι'} [ne_bot l] (H : tendsto (u ∘ φ) l at_bot) : tendsto u at_bot at_bot := tendsto_at_bot_of_monotone_of_filter h (tendsto_map' H) /-- Let `f` and `g` be two maps to the same commutative monoid. This lemma gives a sufficient condition for comparison of the filter `at_top.map (λ s, ∏ b in s, f b)` with `at_top.map (λ s, ∏ b in s, g b)`. This is useful to compare the set of limit points of `Π b in s, f b` as `s → at_top` with the similar set for `g`. -/ @[to_additive] lemma map_at_top_finset_prod_le_of_prod_eq [comm_monoid α] {f : β → α} {g : γ → α} (h_eq : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ ∏ x in u', g x = ∏ b in v', f b) : at_top.map (λs:finset β, ∏ b in s, f b) ≤ at_top.map (λs:finset γ, ∏ x in s, g x) := by rw [map_at_top_eq, map_at_top_eq]; from (le_infi $ assume b, let ⟨v, hv⟩ := h_eq b in infi_le_of_le v $ by simp [set.image_subset_iff]; exact hv) lemma has_antimono_basis.tendsto [semilattice_sup ι] [nonempty ι] {l : filter α} {p : ι → Prop} {s : ι → set α} (hl : l.has_antimono_basis p s) {φ : ι → α} (h : ∀ i : ι, φ i ∈ s i) : tendsto φ at_top l := (at_top_basis.tendsto_iff hl.to_has_basis).2 $ assume i hi, ⟨i, trivial, λ j hij, hl.decreasing hi (hl.mono hij hi) hij (h j)⟩ namespace is_countably_generated /-- An abstract version of continuity of sequentially continuous functions on metric spaces: if a filter `k` is countably generated then `tendsto f k l` iff for every sequence `u` converging to `k`, `f ∘ u` tends to `l`. -/ lemma tendsto_iff_seq_tendsto {f : α → β} {k : filter α} {l : filter β} (hcb : k.is_countably_generated) : tendsto f k l ↔ (∀ x : ℕ → α, tendsto x at_top k → tendsto (f ∘ x) at_top l) := suffices (∀ x : ℕ → α, tendsto x at_top k → tendsto (f ∘ x) at_top l) → tendsto f k l, from ⟨by intros; apply tendsto.comp; assumption, by assumption⟩, begin rcases hcb.exists_antimono_basis with ⟨g, gbasis, gmon, -⟩, contrapose, simp only [not_forall, gbasis.tendsto_left_iff, exists_const, not_exists, not_imp], rintro ⟨B, hBl, hfBk⟩, choose x h using hfBk, use x, split, { exact (at_top_basis.tendsto_iff gbasis).2 (λ i _, ⟨i, trivial, λ j hj, gmon trivial trivial hj (h j).1⟩) }, { simp only [tendsto_at_top', (∘), not_forall, not_exists], use [B, hBl], intro i, use [i, (le_refl _)], apply (h i).right }, end lemma tendsto_of_seq_tendsto {f : α → β} {k : filter α} {l : filter β} (hcb : k.is_countably_generated) : (∀ x : ℕ → α, tendsto x at_top k → tendsto (f ∘ x) at_top l) → tendsto f k l := hcb.tendsto_iff_seq_tendsto.2 lemma subseq_tendsto {f : filter α} (hf : is_countably_generated f) {u : ℕ → α} (hx : ne_bot (f ⊓ map u at_top)) : ∃ (θ : ℕ → ℕ), (strict_mono θ) ∧ (tendsto (u ∘ θ) at_top f) := begin rcases hf.exists_antimono_basis with ⟨B, h⟩, have : ∀ N, ∃ n ≥ N, u n ∈ B N, from λ N, filter.inf_map_at_top_ne_bot_iff.mp hx _ (h.to_has_basis.mem_of_mem trivial) N, choose φ hφ using this, cases forall_and_distrib.mp hφ with φ_ge φ_in, have lim_uφ : tendsto (u ∘ φ) at_top f, from h.tendsto φ_in, have lim_φ : tendsto φ at_top at_top, from (tendsto_at_top_mono φ_ge tendsto_id), obtain ⟨ψ, hψ, hψφ⟩ : ∃ ψ : ℕ → ℕ, strict_mono ψ ∧ strict_mono (φ ∘ ψ), from strict_mono_subseq_of_tendsto_at_top lim_φ, exact ⟨φ ∘ ψ, hψφ, lim_uφ.comp hψ.tendsto_at_top⟩, end end is_countably_generated end filter open filter finset section variables {R : Type*} [linear_ordered_semiring R] lemma exists_lt_mul_self (a : R) : ∃ x ≥ 0, a < x * x := let ⟨x, hxa, hx0⟩ :=((tendsto_mul_self_at_top.eventually (eventually_gt_at_top a)).and (eventually_ge_at_top 0)).exists in ⟨x, hx0, hxa⟩ lemma exists_le_mul_self (a : R) : ∃ x ≥ 0, a ≤ x * x := let ⟨x, hx0, hxa⟩ := exists_lt_mul_self a in ⟨x, hx0, hxa.le⟩ end namespace order_iso variables [preorder α] [preorder β] @[simp] lemma comap_at_top (e : α ≃o β) : comap e at_top = at_top := by simp [at_top, ← e.surjective.infi_comp] @[simp] lemma comap_at_bot (e : α ≃o β) : comap e at_bot = at_bot := e.dual.comap_at_top @[simp] lemma map_at_top (e : α ≃o β) : map ⇑e at_top = at_top := by rw [← e.comap_at_top, map_comap_of_surjective e.surjective] @[simp] lemma map_at_bot (e : α ≃o β) : map ⇑e at_bot = at_bot := e.dual.map_at_top lemma tendsto_at_top (e : α ≃o β) : tendsto e at_top at_top := e.map_at_top.le lemma tendsto_at_bot (e : α ≃o β) : tendsto e at_bot at_bot := e.map_at_bot.le @[simp] lemma tendsto_at_top_iff {l : filter γ} {f : γ → α} (e : α ≃o β) : tendsto (λ x, e (f x)) l at_top ↔ tendsto f l at_top := by rw [← e.comap_at_top, tendsto_comap_iff] @[simp] lemma tendsto_at_bot_iff {l : filter γ} {f : γ → α} (e : α ≃o β) : tendsto (λ x, e (f x)) l at_bot ↔ tendsto f l at_bot := e.dual.tendsto_at_top_iff end order_iso /-- Let `g : γ → β` be an injective function and `f : β → α` be a function from the codomain of `g` to a commutative monoid. Suppose that `f x = 1` outside of the range of `g`. Then the filters `at_top.map (λ s, ∏ i in s, f (g i))` and `at_top.map (λ s, ∏ i in s, f i)` coincide. The additive version of this lemma is used to prove the equality `∑' x, f (g x) = ∑' y, f y` under the same assumptions.-/ @[to_additive] lemma function.injective.map_at_top_finset_prod_eq [comm_monoid α] {g : γ → β} (hg : function.injective g) {f : β → α} (hf : ∀ x ∉ set.range g, f x = 1) : map (λ s, ∏ i in s, f (g i)) at_top = map (λ s, ∏ i in s, f i) at_top := begin apply le_antisymm; refine map_at_top_finset_prod_le_of_prod_eq (λ s, _), { refine ⟨s.preimage g (hg.inj_on _), λ t ht, _⟩, refine ⟨t.image g ∪ s, finset.subset_union_right _ _, _⟩, rw [← finset.prod_image (hg.inj_on _)], refine (prod_subset (subset_union_left _ _) _).symm, simp only [finset.mem_union, finset.mem_image], refine λ y hy hyt, hf y (mt _ hyt), rintros ⟨x, rfl⟩, exact ⟨x, ht (finset.mem_preimage.2 $ hy.resolve_left hyt), rfl⟩ }, { refine ⟨s.image g, λ t ht, _⟩, simp only [← prod_preimage _ _ (hg.inj_on _) _ (λ x _, hf x)], exact ⟨_, (image_subset_iff_subset_preimage _).1 ht, rfl⟩ } end /-- Let `g : γ → β` be an injective function and `f : β → α` be a function from the codomain of `g` to an additive commutative monoid. Suppose that `f x = 0` outside of the range of `g`. Then the filters `at_top.map (λ s, ∑ i in s, f (g i))` and `at_top.map (λ s, ∑ i in s, f i)` coincide. This lemma is used to prove the equality `∑' x, f (g x) = ∑' y, f y` under the same assumptions.-/ add_decl_doc function.injective.map_at_top_finset_sum_eq
1b3caf9912f6147f21b6d6e3b4fd9c4b18fb4b48
0ec6b5eb2131429a4464b8e6c6f09897abba3de1
/src/Weil_group.lean
371d41b6f9a8d228359b8a4eb8867f3a7626300f
[]
no_license
kckennylau/local-langlands-abelian
ba1b86e9d956778cd28ac900ffec02b0f0ba172a
ee22666898357dab800a0432214a22c519ed26a9
refs/heads/master
1,584,671,060,846
1,545,151,246,000
1,545,151,246,000
137,111,892
8
0
null
null
null
null
UTF-8
Lean
false
false
3,002
lean
import analysis.topology.topological_structures import .abelianization .field_extensions attribute [instance] ring.to_add_comm_group universes u v w class local_field (α : Type u) extends topological_field α, t2_space α, locally_compact_space α := (ne_bot : to_topological_field.to_topological_space ≠ ⊤) -- very non-trivial def Artin_reciprocity (F : Type u) [local_field F] : topological_group_isomorphism (units F) (Hausdorff_abelianization (Gal (algebraic_closure F))) := sorry -- uses Haar measure instance finite_Galois_extension.to_local_field (F : Type u) [local_field F] (E : finite_Galois_extension F) : local_field E.S := { continuous_add := sorry, continuous_neg := sorry, continuous_mul := sorry, continuous_inv := sorry, t2 := sorry, local_compact_nhds := sorry, ne_bot := sorry, .. (sorry : topological_space E.S) } -- axiomatization due to Tate class Weil_group (F : Type u) [local_field F] (W : Type w) extends topological_space W, group W, topological_group W := (ϕ : W → Gal (algebraic_closure F)) (ϕ_hom : is_topological_group_hom ϕ) (ϕ_dense : closure (set.range ϕ) = set.univ) /-(r : Π E : finite_Galois_intermediate_extension F AC, topological_group_isomorphism (units E.S) (Hausdorff_abelianization (ϕ ⁻¹' (Gal.intermediate F AC E.S))))-/ -- plus 4 more axioms attribute [instance] Weil_group.ϕ_hom def induced_Weil_group (F : Type u) [local_field F] (W : Type w) [Weil_group F W] (E : finite_Galois_extension F) : set W := Weil_group.ϕ F ⁻¹' E.S.Gal set_option class.instance_max_depth 20 instance induced_Weil_group.normal (F : Type u) [local_field F] (W : Type w) [Weil_group F W] (E : finite_Galois_extension F) : normal_subgroup (induced_Weil_group F W E) := by letI := Gal_algebraic_closure.topological_space F; letI := Gal.group (algebraic_closure F); letI := Gal.topological_group F; from @is_group_hom.preimage_normal W (Gal (algebraic_closure F)) _ _inst_3 (Weil_group.ϕ F) (Weil_group.ϕ_hom F W).to_is_group_hom _ (Gal.normal _) def relative_Weil_group (F : Type u) [local_field F] (W : Type w) [Weil_group F W] (E : finite_Galois_extension F) : Type w := quotient_group.quotient (commutator_subgroup W (induced_Weil_group F W E)) instance relative_Weil_group.topological_space (F : Type u) [local_field F] (W : Type w) [Weil_group F W] (E : finite_Galois_extension F) : topological_space (relative_Weil_group F W E) := quotient_group.topological_space _ _ instance relative_Weil_group.group (F : Type u) [local_field F] (W : Type w) [Weil_group F W] (E : finite_Galois_extension F) : group (relative_Weil_group F W E) := quotient_group.group _ instance relative_Weil_group.topological_group (F : Type u) [local_field F] (W : Type w) [Weil_group F W] (E : finite_Galois_extension F) : topological_group (relative_Weil_group F W E) := quotient_group.topological_group _ _
784b5480cc9fda42a5f5d2998ac7f2260fc2580e
df561f413cfe0a88b1056655515399c546ff32a5
/7-advanced-multiplication-world/l3.lean
9b332488e458f809a468834fb6b237d045e24c8a
[]
no_license
nicholaspun/natural-number-game-solutions
31d5158415c6f582694680044c5c6469032c2a06
1e2aed86d2e76a3f4a275c6d99e795ad30cf6df0
refs/heads/main
1,675,123,625,012
1,607,633,548,000
1,607,633,548,000
318,933,860
3
1
null
null
null
null
UTF-8
Lean
false
false
200
lean
theorem mul_eq_zero_iff (a b : mynat): a * b = 0 ↔ a = 0 ∨ b = 0 := begin split, exact eq_zero_or_eq_zero_of_mul_eq_zero a b, intro h, cases h, rw h, exact zero_mul b, rw h, exact mul_zero a, end
69498f151ab4c3c7061d0ab19ad3c10fad6b07a2
5ee26964f602030578ef0159d46145dd2e357ba5
/src/perfectoid_space.lean
4ef54d64c3b1a48ad6db0a89ae133d335d2f329c
[ "Apache-2.0" ]
permissive
fpvandoorn/lean-perfectoid-spaces
569b4006fdfe491ca8b58dd817bb56138ada761f
06cec51438b168837fc6e9268945735037fd1db6
refs/heads/master
1,590,154,571,918
1,557,685,392,000
1,557,685,392,000
186,363,547
0
0
Apache-2.0
1,557,730,933,000
1,557,730,933,000
null
UTF-8
Lean
false
false
1,870
lean
/- Perfectoid Spaces by Kevin Buzzard, Johan Commelin, and Patrick Massot Definitions in this file follow Scholze's paper: Étale cohomology of diamonds, specifically Definition 3.1 and 3.19 -/ -- We import definitions of adic_space, preadic_space, Huber_pair, etc import prime import adic_space import Tate_ring import power_bounded section -- notation for the power bounded subring local postfix `ᵒ` : 66 := power_bounded_subring open power_bounded_subring topological_space function -- We fix a prime number p parameter (p : Prime) structure perfectoid_ring (R : Type) [Huber_ring R] extends Tate_ring R : Prop := (complete : is_complete_hausdorff R) (uniform : is_uniform R) (ramified : ∃ ϖ : pseudo_uniformizer R, ϖ^p ∣ p in Rᵒ) (Frobenius : surjective (Frob Rᵒ∕p)) /- CLVRS ("complete locally valued ringed space") is a category whose objects are topological spaces with a sheaf of complete topological rings and an equivalence class of valuation on each stalk, whose support is the unique maximal ideal of the stalk; in Wedhorn's notes this category is called 𝒱. A perfectoid space is an object of CLVRS which is locally isomorphic to Spa(A) with A a perfectoid ring. Note however that CLVRS is a full subcategory of the category `PreValuedRingedSpace` of topological spaces equipped with a presheaf of topological rings and a valuation on each stalk, so the isomorphism can be checked in PreValuedRingedSpace instead, which is what we do. -/ /-- Condition for an object of CLVRS to be perfectoid: every point should have an open neighbourhood isomorphic to Spa(A) for some perfectoid ring A.-/ def is_perfectoid (X : CLVRS) : Prop := ∀ x : X, ∃ (U : opens X) (A : Huber_pair) [perfectoid_ring A], (x ∈ U) ∧ (Spa A ≊ U) /-- The category of perfectoid spaces.-/ def PerfectoidSpace := {X : CLVRS // is_perfectoid X} end
e742b8fa748b981d846d79a1fc5f1024aca55eea
3fed20a6f59e2663e48ee3bfc33dbc79256b4a50
/src/soundness.lean
0d67b9d08a501ff9b5dba6c5ea66eba5a3cd66cf
[]
no_license
arademaker/alc-lean
575203dae75f466cc686831d8b0d230fc3c00ced
46d5b582d4272493a26d6d47c0bfa0622c52aae4
refs/heads/master
1,622,696,540,378
1,618,442,995,000
1,618,442,995,000
37,130,780
4
3
null
1,618,365,416,000
1,433,853,111,000
Lean
UTF-8
Lean
false
false
7,096
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura Define propositional calculus, valuation, provability, validity, prove soundness. This file is based on Floris van Doorn Coq files. Similar to soundness.lean, but defines Nc in Type. The idea is to be able to prove soundness using recursive equations. -/ open nat bool list decidable attribute [reducible] definition PropVar := nat inductive PropF | Var : PropVar → PropF | Bot : PropF | Conj : PropF → PropF → PropF | Disj : PropF → PropF → PropF | Impl : PropF → PropF → PropF namespace PropF notation `#`:max P:max := Var P local notation A ∨ B := Disj A B local notation A ∧ B := Conj A B local infixr ` ⇒ `:27 := Impl notation `⊥` := Bot def Neg (A) := A ⇒ ⊥ notation ~ A := Neg A def Top := ~⊥ notation `⊤` := Top def BiImpl (A B) := A ⇒ B ∧ B ⇒ A infixr `⇔`:27 := BiImpl def valuation := PropVar → bool def TrueQ (v : valuation) : PropF → bool | (# P) := v P | ⊥ := ff | (A ∨ B) := TrueQ A || TrueQ B | (A ∧ B) := TrueQ A && TrueQ B | (A ⇒ B) := bnot (TrueQ A) || TrueQ B attribute [reducible] def is_true (b : bool) := b = tt -- the valuation v satisfies a list of PropF, if forall (A : PropF) in Γ, -- (TrueQ v A) is tt (the Boolean true) def Satisfies (v) (Γ : list PropF) := ∀ A, A ∈ Γ → is_true (TrueQ v A) def Models (Γ A) := ∀ v, Satisfies v Γ → is_true (TrueQ v A) infix `⊨`:80 := Models def Valid (p) := [] ⊨ p reserve infix ` ⊢ `:26 /- Provability -/ inductive Nc : list PropF → PropF → Type infix ⊢ := Nc | Nax : ∀ Γ A, A ∈ Γ → Γ ⊢ A | ImpI : ∀ Γ A B, A::Γ ⊢ B → Γ ⊢ A ⇒ B | ImpE : ∀ Γ A B, Γ ⊢ A ⇒ B → Γ ⊢ A → Γ ⊢ B | BotC : ∀ Γ A, (~A)::Γ ⊢ ⊥ → Γ ⊢ A | AndI : ∀ Γ A B, Γ ⊢ A → Γ ⊢ B → Γ ⊢ A ∧ B | AndE₁ : ∀ Γ A B, Γ ⊢ A ∧ B → Γ ⊢ A | AndE₂ : ∀ Γ A B, Γ ⊢ A ∧ B → Γ ⊢ B | OrI₁ : ∀ Γ A B, Γ ⊢ A → Γ ⊢ A ∨ B | OrI₂ : ∀ Γ A B, Γ ⊢ B → Γ ⊢ A ∨ B | OrE : ∀ Γ A B C, Γ ⊢ A ∨ B → A::Γ ⊢ C → B::Γ ⊢ C → Γ ⊢ C infix ⊢ := Nc example (Γ : list PropF) : Γ ⊢ (#1 ∧ #2) → Γ ⊢ #1 := begin intro h, apply Nc.AndE₁ _ #1 #2, exact h, end example : [] ⊢ (#1 ∧ #2 ⇒ #1) := begin apply Nc.ImpI, have h0 := mem_cons_self (#1 ∧ #2) [], have h1 := Nc.Nax _ (#1 ∧ #2) h0, apply Nc.AndE₁ _ #1 #2, exact h1, end def Provable (A) := [] ⊢ A def Prop_Soundness := ∀ A, Provable A → Valid A def Prop_Completeness := ∀ A, Valid A → Provable A open Nc lemma weakening2 : ∀ {Γ A Δ}, Γ ⊢ A → Γ ⊆ Δ → Δ ⊢ A | ._ ._ Δ (Nax Γ A Hin) Hs := Nax _ _ (Hs Hin) | ._ .(A ⇒ B) Δ (ImpI Γ A B H) Hs := ImpI _ _ _ (weakening2 H (cons_subset_cons A Hs)) | ._ ._ Δ (ImpE Γ A B H₁ H₂) Hs := ImpE _ _ _ (weakening2 H₁ Hs) (weakening2 H₂ Hs) | ._ ._ Δ (BotC Γ A H) Hs := BotC _ _ (weakening2 H (cons_subset_cons (~A) Hs)) | ._ .(A ∧ B) Δ (AndI Γ A B H₁ H₂) Hs := AndI _ _ _ (weakening2 H₁ Hs) (weakening2 H₂ Hs) | ._ ._ Δ (AndE₁ Γ A B H) Hs := AndE₁ _ _ _ (weakening2 H Hs) | ._ ._ Δ (AndE₂ Γ A B H) Hs := AndE₂ _ _ _ (weakening2 H Hs) | ._ .(A ∨ B) Δ (OrI₁ Γ A B H) Hs := OrI₁ _ _ _ (weakening2 H Hs) | ._ .(A ∨ B) Δ (OrI₂ Γ A B H) Hs := OrI₂ _ _ _ (weakening2 H Hs) | ._ ._ Δ (OrE Γ A B C H₁ H₂ H₃) Hs := OrE _ _ _ _ (weakening2 H₁ Hs) (weakening2 H₂ (cons_subset_cons A Hs)) (weakening2 H₃ (cons_subset_cons B Hs)) lemma weakening : ∀ Γ Δ A, Γ ⊢ A → Γ++Δ ⊢ A := λ Γ Δ A H, weakening2 H (subset_append_left Γ Δ) lemma deduction : ∀ Γ A B, Γ ⊢ A ⇒ B → A::Γ ⊢ B := λ Γ A B H, ImpE _ _ _ (weakening2 H (subset_cons A Γ)) (Nax _ _ (mem_cons_self A Γ)) lemma prov_impl : ∀ A B, Provable (A ⇒ B) → ∀ Γ, Γ ⊢ A → Γ ⊢ B := λ A B Hp Γ Ha, have wHp : Γ ⊢ (A ⇒ B), from weakening _ _ _ Hp, ImpE _ _ _ wHp Ha lemma Satisfies_cons : ∀ {A Γ v}, Satisfies v Γ → is_true (TrueQ v A) → Satisfies v (A::Γ) := λ A Γ v s t B BinAG, or.elim BinAG (λ e : B = A, by rewrite e; exact t) (λ i : B ∈ Γ, s _ i) attribute [simp] is_true TrueQ theorem Soundness_general {v : valuation} : ∀ {A Γ}, Γ ⊢ A → Satisfies v Γ → is_true (TrueQ v A) | ._ ._ (Nax Γ A Hin) s := s _ Hin | .(A ⇒ B) ._ (ImpI Γ A B H) s := by_cases (λ t : is_true (TrueQ v A), have Satisfies v (A::Γ), from Satisfies_cons s t, have TrueQ v B = tt, from Soundness_general H this, by simp[*]) (λ f : ¬ is_true (TrueQ v A), have TrueQ v A = ff, by simp at f; simp[*], have bnot (TrueQ v A) = tt, by simp[*], by simp[*]) | ._ ._ (ImpE Γ A B H₁ H₂) s := have aux : TrueQ v A = tt, from Soundness_general H₂ s, have bnot (TrueQ v A) || TrueQ v B = tt, from Soundness_general H₁ s, by simp [aux] at this; simp[*] | ._ ._ (BotC Γ A H) s := by_contradiction (λ n : TrueQ v A ≠ tt, have TrueQ v A = ff, by {simp at n; simp[*]}, have TrueQ v (~A) = tt, begin change (bnot (TrueQ v A) || ff = tt), simp[*] end, have Satisfies v ((~A):: Γ), from Satisfies_cons s this, have TrueQ v ⊥ = tt, from Soundness_general H this, absurd this ff_ne_tt) | .(A ∧ B) ._ (AndI Γ A B H₁ H₂) s := have TrueQ v A = tt, from Soundness_general H₁ s, have TrueQ v B = tt, from Soundness_general H₂ s, by simp[*] | ._ ._ (AndE₁ Γ A B H) s := have TrueQ v (A ∧ B) = tt, from Soundness_general H s, by simp [TrueQ] at this; simp [*, is_true] | ._ ._ (AndE₂ Γ A B H) s := have TrueQ v (A ∧ B) = tt, from Soundness_general H s, by simp at this; simp[*] | .(A ∨ B) ._ (OrI₁ Γ A B H) s := have TrueQ v A = tt, from Soundness_general H s, by simp[*] | .(A ∨ B) ._ (OrI₂ Γ A B H) s := have TrueQ v B = tt, from Soundness_general H s, by simp[*] | ._ ._ (OrE Γ A B C H₁ H₂ H₃) s := have TrueQ v A || TrueQ v B = tt, from Soundness_general H₁ s, have or (TrueQ v A = tt) (TrueQ v B = tt), by simp at this; simp[*], or.elim this (λ At, have Satisfies v (A::Γ), from Satisfies_cons s At, Soundness_general H₂ this) (λ Bt, have Satisfies v (B::Γ), from Satisfies_cons s Bt, Soundness_general H₃ this) theorem Soundness : Prop_Soundness := λ A H v s, Soundness_general H s end PropF
399b9610dfb349492e6b26abefddcf9794bd0183
38bf3fd2bb651ab70511408fcf70e2029e2ba310
/src/data/equiv/local_equiv.lean
d4e976f0b1211d235ca40775565123847839a9e9
[ "Apache-2.0" ]
permissive
JaredCorduan/mathlib
130392594844f15dad65a9308c242551bae6cd2e
d5de80376088954d592a59326c14404f538050a1
refs/heads/master
1,595,862,206,333
1,570,816,457,000
1,570,816,457,000
209,134,499
0
0
Apache-2.0
1,568,746,811,000
1,568,746,811,000
null
UTF-8
Lean
false
false
21,796
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.basic /-! # Local equivalences This files defines equivalences between subsets of given types. An element `e` of `local_equiv α β` is made of two maps `e.to_fun` and `e.inv_fun` respectively from α to β and from β to α (just like equivs), which are inverse to each other on the subsets `e.source` and `e.target` of respectively α and β. They are designed in particular to define charts on manifolds. The main functionality is `e.trans f`, which composes the two local equivalences by restricting the source and target to the maximal set where the composition makes sense. Contrary to equivs, we do not register the coercion to functions and we use explicitly to_fun and inv_fun: coercions create numerous unification problems for manifolds. ## Main definitions `equiv.to_local_equiv`: associating a local equiv to an equiv, with source = target = univ `local_equiv.symm` : the inverse of a local equiv `local_equiv.trans` : the composition of two local equivs `local_equiv.refl` : the identity local equiv `local_equiv.of_set` : the identity on a set `s` `eq_on_source` : equivalence relation describing the "right" notion of equality for local equivs (see below in implementation notes) ## Implementation notes There are at least three possible implementations of local equivalences: * equivs on subtypes * pairs of functions taking values in `option α` and `option β`, equal to none where the local equivalence is not defined * pairs of functions defined everywhere, keeping the source and target as additional data Each of these implementations has pros and cons. * When dealing with subtypes, one still need to define additional API for composition and restriction of domains. Checking that one always belongs to the right subtype makes things very tedious, and leads quickly to DTT hell (as the subtype `u ∩ v` is not the "same" as `v ∩ u`, for instance). * With option-valued functions, the composition is very neat (it is just the usual composition, and the domain is restricted automatically). These are implemented in `pequiv.lean`. For manifolds, where one wants to discuss thoroughly the smoothness of the maps, this creates however a lot of overhead as one would need to extend all classes of smoothness to option-valued maps. * The local_equiv version as explained above is easier to use for manifolds. The drawback is that there is extra useless data (the values of `to_fun` and `inv_fun` outside of `source` and `target`). In particular, the equality notion between local equivs is not "the right one", i.e., coinciding source and target and equality there. Moreover, there are no local equivs in this sense between an empty type and a nonempty type. Since empty types are not that useful, and since one almost never needs to talk about equal local equivs, this is not an issue in practice. Still, we introduce an equivalence relation `eq_on_source` that captures this right notion of equality, and show that many properties are invariant under this equivalence relation. -/ open function set variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} /-- Local equivalence between subsets `source` and `target` of α and β respectively. The (global) maps `to_fun : α → β` and `inv_fun : β → α` map `source` to `target` and conversely, and are inverse to each other there. The values of `to_fun` outside of `source` and of `inv_fun` outside of `target` are irrelevant. -/ structure local_equiv (α : Type*) (β : Type*) := (to_fun : α → β) (inv_fun : β → α) (source : set α) (target : set β) (map_source : ∀{x}, x ∈ source → to_fun x ∈ target) (map_target : ∀{x}, x ∈ target → inv_fun x ∈ source) (left_inv : ∀{x}, x ∈ source → inv_fun (to_fun x) = x) (right_inv : ∀{x}, x ∈ target → to_fun (inv_fun x) = x) attribute [simp] local_equiv.left_inv local_equiv.right_inv /-- Associating a local_equiv to an equiv-/ def equiv.to_local_equiv (e : equiv α β) : local_equiv α β := { to_fun := e.to_fun, inv_fun := e.inv_fun, source := univ, target := univ, map_source := λx hx, mem_univ _, map_target := λy hy, mem_univ _, left_inv := λx hx, e.left_inv x, right_inv := λx hx, e.right_inv x } namespace local_equiv variables (e : local_equiv α β) (e' : local_equiv β γ) /-- Associating to a local_equiv an equiv between the source and the target -/ protected def to_equiv : equiv (e.source) (e.target) := { to_fun := λ⟨x, hx⟩, ⟨e.to_fun x, e.map_source hx⟩, inv_fun := λ⟨y, hy⟩, ⟨e.inv_fun y, e.map_target hy⟩, left_inv := λ⟨x, hx⟩, subtype.eq $ e.left_inv hx, right_inv := λ⟨y, hy⟩, subtype.eq $ e.right_inv hy } /-- The inverse of a local equiv -/ protected def symm : local_equiv β α := { to_fun := e.inv_fun, inv_fun := e.to_fun, source := e.target, target := e.source, map_source := e.map_target, map_target := e.map_source, left_inv := e.right_inv, right_inv := e.left_inv } @[simp] lemma symm_to_fun : e.symm.to_fun = e.inv_fun := rfl @[simp] lemma symm_inv_fun : e.symm.inv_fun = e.to_fun := rfl @[simp] lemma symm_source : e.symm.source = e.target := rfl @[simp] lemma symm_target : e.symm.target = e.source := rfl @[simp] lemma symm_symm : e.symm.symm = e := by { cases e, refl } /-- A local equiv induces a bijection between its source and target -/ lemma bij_on_source : bij_on e.to_fun e.source e.target := bij_on_of_inv_on e.map_source e.map_target ⟨e.left_inv, e.right_inv⟩ lemma image_eq_target_inter_inv_preimage {s : set α} (h : s ⊆ e.source) : e.to_fun '' s = e.target ∩ e.inv_fun ⁻¹' s := begin refine subset.antisymm (λx hx, _) (λx hx, _), { rcases (mem_image _ _ _).1 hx with ⟨y, ys, hy⟩, rw ← hy, split, { apply e.map_source, exact h ys }, { rwa [mem_preimage, e.left_inv (h ys)] } }, { rw ← e.right_inv hx.1, exact mem_image_of_mem _ hx.2 } end lemma inv_image_eq_source_inter_preimage {s : set β} (h : s ⊆ e.target) : e.inv_fun '' s = e.source ∩ e.to_fun ⁻¹' s := e.symm.image_eq_target_inter_inv_preimage h lemma source_inter_preimage_inv_preimage (s : set α) : e.source ∩ e.to_fun ⁻¹' (e.inv_fun ⁻¹' s) = e.source ∩ s := begin ext, split, { rintros ⟨hx, xs⟩, simp only [mem_preimage, hx, e.left_inv, mem_preimage] at xs, exact ⟨hx, xs⟩ }, { rintros ⟨hx, xs⟩, simp [hx, xs] } end lemma target_inter_inv_preimage_preimage (s : set β) : e.target ∩ e.inv_fun ⁻¹' (e.to_fun ⁻¹' s) = e.target ∩ s := e.symm.source_inter_preimage_inv_preimage _ lemma image_source_eq_target : e.to_fun '' e.source = e.target := image_eq_of_bij_on e.bij_on_source lemma source_subset_preimage_target : e.source ⊆ e.to_fun ⁻¹' e.target := λx hx, e.map_source hx lemma inv_image_target_eq_source : e.inv_fun '' e.target = e.source := image_eq_of_bij_on e.symm.bij_on_source lemma target_subset_preimage_source : e.target ⊆ e.inv_fun ⁻¹' e.source := λx hx, e.map_target hx /-- Two local equivs that have the same source, same to_fun and same inv_fun, coincide. -/ @[extensionality] protected lemma ext (e' : local_equiv α β) (h : ∀x, e.to_fun x = e'.to_fun x) (hsymm : ∀x, e.inv_fun x = e'.inv_fun x) (hs : e.source = e'.source) : e = e' := begin have A : e.to_fun = e'.to_fun, by { ext x, exact h x }, have B : e.inv_fun = e'.inv_fun, by { ext x, exact hsymm x }, have I : e.to_fun '' e.source = e.target := e.image_source_eq_target, have I' : e'.to_fun '' e'.source = e'.target := e'.image_source_eq_target, rw [A, hs, I'] at I, cases e; cases e', simp * at * end /-- Restricting a local equivalence to e.source ∩ s -/ protected def restr (s : set α) : local_equiv α β := { to_fun := e.to_fun, inv_fun := e.inv_fun, source := e.source ∩ s, target := e.target ∩ e.inv_fun⁻¹' s, map_source := λx hx, begin apply mem_inter, { apply e.map_source, exact hx.1 }, { rw [mem_preimage, e.left_inv], exact hx.2, exact hx.1 }, end, map_target := λy hy, begin apply mem_inter, { apply e.map_target, exact hy.1 }, { exact hy.2 }, end, left_inv := λx hx, e.left_inv hx.1, right_inv := λy hy, e.right_inv hy.1 } @[simp] lemma restr_to_fun (s : set α) : (e.restr s).to_fun = e.to_fun := rfl @[simp] lemma restr_inv_fun (s : set α) : (e.restr s).inv_fun = e.inv_fun := rfl @[simp] lemma restr_source (s : set α) : (e.restr s).source = e.source ∩ s := rfl @[simp] lemma restr_target (s : set α) : (e.restr s).target = e.target ∩ e.inv_fun ⁻¹' s := rfl lemma restr_eq_of_source_subset {e : local_equiv α β} {s : set α} (h : e.source ⊆ s) : e.restr s = e := local_equiv.ext _ _ (λ_, rfl) (λ_, rfl) (by simp [inter_eq_self_of_subset_left h]) @[simp] lemma restr_univ {e : local_equiv α β} : e.restr univ = e := restr_eq_of_source_subset (subset_univ _) /-- The identity local equiv -/ protected def refl (α : Type*) : local_equiv α α := (equiv.refl α).to_local_equiv @[simp] lemma refl_source : (local_equiv.refl α).source = univ := rfl @[simp] lemma refl_target : (local_equiv.refl α).target = univ := rfl @[simp] lemma refl_to_fun : (local_equiv.refl α).to_fun = id := rfl @[simp] lemma refl_inv_fun : (local_equiv.refl α).inv_fun = id := rfl @[simp] lemma refl_symm : (local_equiv.refl α).symm = local_equiv.refl α := rfl @[simp] lemma refl_restr_source (s : set α) : ((local_equiv.refl α).restr s).source = s := by simp @[simp] lemma refl_restr_target (s : set α) : ((local_equiv.refl α).restr s).target = s := by { change univ ∩ id⁻¹' s = s, simp } /-- The identity local equiv on a set `s` -/ def of_set (s : set α) : local_equiv α α := { to_fun := id, inv_fun := id, source := s, target := s, map_source := λx hx, hx, map_target := λx hx, hx, left_inv := λx hx, rfl, right_inv := λx hx, rfl } @[simp] lemma of_set_source (s : set α) : (local_equiv.of_set s).source = s := rfl @[simp] lemma of_set_target (s : set α) : (local_equiv.of_set s).target = s := rfl @[simp] lemma of_set_to_fun (s : set α) : (local_equiv.of_set s).to_fun = id := rfl @[simp] lemma of_set_inv_fun {s : set α} : (local_equiv.of_set s).inv_fun = id := rfl @[simp] lemma of_set_symm (s : set α) : (local_equiv.of_set s).symm = local_equiv.of_set s := rfl /-- Composing two local equivs if the target of the first coincides with the source of the second. -/ protected def trans' (e' : local_equiv β γ) (h : e.target = e'.source) : local_equiv α γ := { to_fun := e'.to_fun ∘ e.to_fun, inv_fun := e.inv_fun ∘ e'.inv_fun, source := e.source, target := e'.target, map_source := λx hx, begin apply e'.map_source, rw ← h, apply e.map_source hx end, map_target := λy hy, begin apply e.map_target, rw h, apply e'.map_target hy end, left_inv := λx hx, begin change e.inv_fun (e'.inv_fun (e'.to_fun (e.to_fun x))) = x, rw e'.left_inv, { exact e.left_inv hx }, { rw ← h, exact e.map_source hx } end, right_inv := λy hy, begin change e'.to_fun (e.to_fun (e.inv_fun (e'.inv_fun y))) = y, rw e.right_inv, { exact e'.right_inv hy }, { rw h, exact e'.map_target hy } end } /-- Composing two local equivs, by restricting to the maximal domain where their composition is well defined. -/ protected def trans : local_equiv α γ := local_equiv.trans' (e.symm.restr (e'.source)).symm (e'.restr (e.target)) (inter_comm _ _) @[simp] lemma trans_to_fun : (e.trans e').to_fun = e'.to_fun ∘ e.to_fun := rfl @[simp] lemma trans_apply (x : α) : (e.trans e').to_fun x = e'.to_fun (e.to_fun x) := rfl @[simp] lemma trans_inv_fun : (e.trans e').inv_fun = e.inv_fun ∘ e'.inv_fun := rfl @[simp] lemma trans_inv_apply (x : γ) : (e.trans e').inv_fun x = e.inv_fun (e'.inv_fun x) := 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.to_fun ⁻¹' e'.source := rfl lemma trans_source' : (e.trans e').source = e.source ∩ e.to_fun ⁻¹' (e.target ∩ e'.source) := begin symmetry, calc e.source ∩ e.to_fun ⁻¹' (e.target ∩ e'.source) = (e.source ∩ e.to_fun ⁻¹' (e.target)) ∩ e.to_fun ⁻¹' (e'.source) : by rw [preimage_inter, inter_assoc] ... = e.source ∩ e.to_fun ⁻¹' (e'.source) : by { congr' 1, apply inter_eq_self_of_subset_left e.source_subset_preimage_target } ... = (e.trans e').source : rfl end lemma trans_source'' : (e.trans e').source = e.inv_fun '' (e.target ∩ e'.source) := begin rw [e.trans_source', e.inv_image_eq_source_inter_preimage, inter_comm], exact inter_subset_left _ _, end lemma image_trans_source : e.to_fun '' (e.trans e').source = e.target ∩ e'.source := image_source_eq_target (local_equiv.symm (local_equiv.restr (local_equiv.symm e) (e'.source))) lemma trans_target : (e.trans e').target = e'.target ∩ e'.inv_fun ⁻¹' e.target := rfl lemma trans_target' : (e.trans e').target = e'.target ∩ e'.inv_fun ⁻¹' (e'.source ∩ e.target) := trans_source' e'.symm e.symm lemma trans_target'' : (e.trans e').target = e'.to_fun '' (e'.source ∩ e.target) := trans_source'' e'.symm e.symm lemma inv_image_trans_target : e'.inv_fun '' (e.trans e').target = e'.source ∩ e.target := image_trans_source e'.symm e.symm lemma trans_assoc (e'' : local_equiv γ δ) : (e.trans e').trans e'' = e.trans (e'.trans e'') := local_equiv.ext _ _ (λx, rfl) (λx, rfl) (by simp [trans_source, @preimage_comp α β γ, inter_assoc]) @[simp] lemma trans_refl : e.trans (local_equiv.refl β) = e := local_equiv.ext _ _ (λx, rfl) (λx, rfl) (by simp [trans_source]) @[simp] lemma refl_trans : (local_equiv.refl α).trans e = e := local_equiv.ext _ _ (λx, rfl) (λx, rfl) (by simp [trans_source, preimage_id]) lemma trans_refl_restr (s : set β) : e.trans ((local_equiv.refl β).restr s) = e.restr (e.to_fun ⁻¹' s) := local_equiv.ext _ _ (λx, rfl) (λx, rfl) (by simp [trans_source]) lemma trans_refl_restr' (s : set β) : e.trans ((local_equiv.refl β).restr s) = e.restr (e.source ∩ e.to_fun ⁻¹' s) := local_equiv.ext _ _ (λx, rfl) (λx, rfl) $ by { simp [trans_source], rw [← inter_assoc, inter_self] } lemma restr_trans (s : set α) : (e.restr s).trans e' = (e.trans e').restr s := local_equiv.ext _ _ (λx, rfl) (λx, rfl) $ by { simp [trans_source, inter_comm], rwa inter_assoc } /-- `eq_on_source e e'` means that `e` and `e'` have the same source, and coincide there. Then `e` and `e'` should really be considered the same local equiv. -/ def eq_on_source (e e' : local_equiv α β) : Prop := e.source = e'.source ∧ (∀x ∈ e.source, e.to_fun x = e'.to_fun x) /-- `eq_on_source` is an equivalence relation -/ instance eq_on_source_setoid : setoid (local_equiv α β) := { r := eq_on_source, iseqv := ⟨ λe, by simp [eq_on_source], λe e' h, by { simp [eq_on_source, h.1.symm], exact λx hx, (h.2 x hx).symm }, λe e' e'' h h', ⟨by rwa [← h'.1, ← h.1], λx hx, by { rw [← h'.2 x, h.2 x hx], rwa ← h.1 }⟩⟩ } lemma eq_on_source_refl : e ≈ e := setoid.refl _ /-- If two local equivs are equivalent, so are their inverses -/ lemma eq_on_source_symm {e e' : local_equiv α β} (h : e ≈ e') : e.symm ≈ e'.symm := begin have T : e.target = e'.target, { have : set.bij_on e'.to_fun e.source e.target := bij_on_of_eq_on h.2 e.bij_on_source, have A : e'.to_fun '' e.source = e.target := image_eq_of_bij_on this, rw [h.1, image_eq_of_bij_on e'.bij_on_source] at A, exact A.symm }, refine ⟨T, λx hx, _⟩, have xt : x ∈ e.target := hx, rw T at xt, have e's : e'.inv_fun x ∈ e.source, by { rw h.1, apply e'.map_target xt }, have A : e.to_fun (e.inv_fun x) = x := e.right_inv hx, have B : e.to_fun (e'.inv_fun x) = x, by { rw h.2, exact e'.right_inv xt, exact e's }, apply inj_on_of_bij_on e.bij_on_source (e.map_target hx) e's, rw [A, B] end /-- Two equivalent local equivs have the same source -/ lemma source_eq_of_eq_on_source {e e' : local_equiv α β} (h : e ≈ e') : e.source = e'.source := h.1 /-- Two equivalent local equivs have the same target -/ lemma target_eq_of_eq_on_source {e e' : local_equiv α β} (h : e ≈ e') : e.target = e'.target := (eq_on_source_symm h).1 /-- Two equivalent local equivs coincide on the source -/ lemma apply_eq_of_eq_on_source {e e' : local_equiv α β} (h : e ≈ e') {x : α} (hx : x ∈ e.source) : e.to_fun x = e'.to_fun x := h.2 x hx /-- Two equivalent local equivs have coinciding inverses on the target -/ lemma inv_apply_eq_of_eq_on_source {e e' : local_equiv α β} (h : e ≈ e') {x : β} (hx : x ∈ e.target) : e.inv_fun x = e'.inv_fun x := (eq_on_source_symm h).2 x hx /-- Composition of local equivs respects equivalence -/ lemma eq_on_source_trans {e e' : local_equiv α β} {f f' : local_equiv β γ} (he : e ≈ e') (hf : f ≈ f') : e.trans f ≈ e'.trans f' := begin split, { have : e.target = e'.target := (eq_on_source_symm he).1, rw [trans_source'', trans_source'', ← this, ← hf.1], exact image_eq_image_of_eq_on (λx hx, (eq_on_source_symm he).2 x hx.1) }, { assume x hx, rw trans_source at hx, simp [(he.2 x hx.1).symm, hf.2 _ hx.2] } end /-- Restriction of local equivs respects equivalence -/ lemma eq_on_source_restr {e e' : local_equiv α β} (he : e ≈ e') (s : set α) : e.restr s ≈ e'.restr s := begin split, { simp [he.1] }, { assume x hx, simp only [mem_inter_eq, restr_source] at hx, exact he.2 x hx.1 } end /-- Preimages are respected by equivalence -/ lemma eq_on_source_preimage {e e' : local_equiv α β} (he : e ≈ e') (s : set β) : e.source ∩ e.to_fun ⁻¹' s = e'.source ∩ e'.to_fun ⁻¹' s := begin ext x, simp only [mem_inter_eq, mem_preimage], split, { assume hx, rwa [apply_eq_of_eq_on_source (setoid.symm he), source_eq_of_eq_on_source (setoid.symm he)], rw source_eq_of_eq_on_source he at hx, exact hx.1 }, { assume hx, rwa [apply_eq_of_eq_on_source he, source_eq_of_eq_on_source he], rw source_eq_of_eq_on_source (setoid.symm he) at hx, exact hx.1 }, end /-- Composition of a local equiv and its inverse is equivalent to the restriction of the identity to the source -/ lemma trans_self_symm : e.trans e.symm ≈ local_equiv.of_set e.source := begin have A : (e.trans e.symm).source = e.source, by simp [trans_source, inter_eq_self_of_subset_left (source_subset_preimage_target _)], refine ⟨by simp [A], λx hx, _⟩, rw A at hx, simp [hx] end /-- Composition of the inverse of a local equiv and this local equiv is equivalent to the restriction of the identity to the target -/ lemma trans_symm_self : e.symm.trans e ≈ local_equiv.of_set e.target := trans_self_symm (e.symm) /-- Two equivalent local equivs are equal when the source and target are univ -/ lemma eq_of_eq_on_source_univ (e e' : local_equiv α β) (h : e ≈ e') (s : e.source = univ) (t : e.target = univ) : e = e' := begin apply local_equiv.ext _ _ (λx, _) (λx, _) h.1, { apply h.2 x, rw s, exact mem_univ _ }, { apply (eq_on_source_symm h).2 x, rw [symm_source, t], exact mem_univ _ } end section prod /-- The product of two local equivs, as a local equiv on the product. -/ def prod (e : local_equiv α β) (e' : local_equiv γ δ) : local_equiv (α × γ) (β × δ) := { source := set.prod e.source e'.source, target := set.prod e.target e'.target, to_fun := λp, (e.to_fun p.1, e'.to_fun p.2), inv_fun := λp, (e.inv_fun p.1, e'.inv_fun p.2), map_source := λp hp, by { simp at hp, simp [map_source, hp] }, map_target := λp hp, by { simp at hp, simp [map_target, hp] }, left_inv := λp hp, by { simp at hp, simp [hp] }, right_inv := λp hp, by { simp at hp, simp [hp] } } @[simp] lemma prod_source (e : local_equiv α β) (e' : local_equiv γ δ) : (e.prod e').source = set.prod e.source e'.source := rfl @[simp] lemma prod_target (e : local_equiv α β) (e' : local_equiv γ δ) : (e.prod e').target = set.prod e.target e'.target := rfl @[simp] lemma prod_to_fun (e : local_equiv α β) (e' : local_equiv γ δ) : (e.prod e').to_fun = (λp, (e.to_fun p.1, e'.to_fun p.2)) := rfl @[simp] lemma prod_inv_fun (e : local_equiv α β) (e' : local_equiv γ δ) : (e.prod e').inv_fun = (λp, (e.inv_fun p.1, e'.inv_fun p.2)) := rfl end prod end local_equiv namespace equiv /- equivs give rise to local_equiv. We set up simp lemmas to reduce most properties of the local equiv to that of the equiv. -/ variables (e : equiv α β) (e' : equiv β γ) @[simp] lemma to_local_equiv_to_fun : e.to_local_equiv.to_fun = e.to_fun := rfl @[simp] lemma to_local_equiv_inv_fun : e.to_local_equiv.inv_fun = e.inv_fun := rfl @[simp] lemma to_local_equiv_source : e.to_local_equiv.source = univ := rfl @[simp] lemma to_local_equiv_target : e.to_local_equiv.target = univ := rfl @[simp] lemma refl_to_local_equiv : (equiv.refl α).to_local_equiv = local_equiv.refl α := rfl @[simp] lemma symm_to_local_equiv : e.symm.to_local_equiv = e.to_local_equiv.symm := rfl @[simp] lemma trans_to_local_equiv : (e.trans e').to_local_equiv = e.to_local_equiv.trans e'.to_local_equiv := local_equiv.ext _ _ (λx, rfl) (λx, rfl) (by simp [local_equiv.trans_source, equiv.to_local_equiv]) end equiv
b3863dd499ad511005dcfe2c17ce4af91e4df9e6
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/normed/group/add_circle.lean
d62aa04e4c021e70ed124166171e0cd8abc720e2
[ "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,336
lean
/- Copyright (c) 2022 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import analysis.normed.group.quotient import topology.instances.add_circle /-! # The additive circle as a normed group > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We define the normed group structure on `add_circle p`, for `p : ℝ`. For example if `p = 1` then: `‖(x : add_circle 1)‖ = |x - round x|` for any `x : ℝ` (see `unit_add_circle.norm_eq`). ## Main definitions: * `add_circle.norm_eq`: a characterisation of the norm on `add_circle p` ## TODO * The fact `inner_product_geometry.angle (real.cos θ) (real.sin θ) = ‖(θ : real.angle)‖` -/ noncomputable theory open set int (hiding mem_zmultiples_iff) add_subgroup namespace add_circle variables (p : ℝ) instance : normed_add_comm_group (add_circle p) := add_subgroup.normed_add_comm_group_quotient _ @[simp] lemma norm_coe_mul (x : ℝ) (t : ℝ) : ‖(↑(t * x) : add_circle (t * p))‖ = |t| * ‖(x : add_circle p)‖ := begin have aux : ∀ {a b c : ℝ}, a ∈ zmultiples b → c * a ∈ zmultiples (c * b) := λ a b c h, by { simp only [mem_zmultiples_iff] at ⊢ h, obtain ⟨n, rfl⟩ := h, exact ⟨n, (mul_smul_comm n c b).symm⟩, }, rcases eq_or_ne t 0 with rfl | ht, { simp, }, have ht' : |t| ≠ 0 := (not_congr abs_eq_zero).mpr ht, simp only [quotient_norm_eq, real.norm_eq_abs], conv_rhs { rw [← smul_eq_mul, ← real.Inf_smul_of_nonneg (abs_nonneg t)], }, simp only [quotient_add_group.mk'_apply, quotient_add_group.eq_iff_sub_mem], congr' 1, ext z, rw mem_smul_set_iff_inv_smul_mem₀ ht', show (∃ y, y - t * x ∈ zmultiples (t * p) ∧ |y| = z) ↔ ∃w, w - x ∈ zmultiples p ∧ |w| = |t|⁻¹ * z, split, { rintros ⟨y, hy, rfl⟩, refine ⟨t⁻¹ * y, _, by rw [abs_mul, abs_inv]⟩, rw [← inv_mul_cancel_left₀ ht x, ← inv_mul_cancel_left₀ ht p, ← mul_sub], exact aux hy, }, { rintros ⟨w, hw, hw'⟩, refine ⟨t * w, _, by rw [← (eq_inv_mul_iff_mul_eq₀ ht').mp hw', abs_mul]⟩, rw ← mul_sub, exact aux hw, }, end lemma norm_neg_period (x : ℝ) : ‖(x : add_circle (-p))‖ = ‖(x : add_circle p)‖ := begin suffices : ‖(↑(-1 * x) : add_circle (-1 * p))‖ = ‖(x : add_circle p)‖, { rw [← this, neg_one_mul], simp, }, simp only [norm_coe_mul, abs_neg, abs_one, one_mul], end @[simp] lemma norm_eq_of_zero {x : ℝ} : ‖(x : add_circle (0 : ℝ))‖ = |x| := begin suffices : {y : ℝ | (y : add_circle (0 : ℝ)) = (x : add_circle (0 : ℝ)) } = { x }, { rw [quotient_norm_eq, this, image_singleton, real.norm_eq_abs, cInf_singleton], }, ext y, simp [quotient_add_group.eq_iff_sub_mem, mem_zmultiples_iff, sub_eq_zero], end lemma norm_eq {x : ℝ} : ‖(x : add_circle p)‖ = |x - round (p⁻¹ * x) * p| := begin suffices : ∀ (x : ℝ), ‖(x : add_circle (1 : ℝ))‖ = |x - round x|, { rcases eq_or_ne p 0 with rfl | hp, { simp, }, intros, have hx := norm_coe_mul p x p⁻¹, rw [abs_inv, eq_inv_mul_iff_mul_eq₀ ((not_congr abs_eq_zero).mpr hp)] at hx, rw [← hx, inv_mul_cancel hp, this, ← abs_mul, mul_sub, mul_inv_cancel_left₀ hp, mul_comm p], }, clear x p, intros, rw [quotient_norm_eq, abs_sub_round_eq_min], have h₁ : bdd_below (abs '' {m : ℝ | (m : add_circle (1 : ℝ)) = x}) := ⟨0, by simp [mem_lower_bounds]⟩, have h₂ : (abs '' {m : ℝ | (m : add_circle (1 : ℝ)) = x}).nonempty := ⟨|x|, ⟨x, rfl, rfl⟩⟩, apply le_antisymm, { simp only [le_min_iff, real.norm_eq_abs, cInf_le_iff h₁ h₂], intros b h, refine ⟨mem_lower_bounds.1 h _ ⟨fract x, _, abs_fract⟩, mem_lower_bounds.1 h _ ⟨fract x - 1, _, by rw [abs_sub_comm, abs_one_sub_fract]⟩⟩, { simp only [mem_set_of_eq, fract, sub_eq_self, quotient_add_group.coe_sub, quotient_add_group.eq_zero_iff, int_cast_mem_zmultiples_one], }, { simp only [mem_set_of_eq, fract, sub_eq_self, quotient_add_group.coe_sub, quotient_add_group.eq_zero_iff, int_cast_mem_zmultiples_one, sub_sub, (by norm_cast : (⌊x⌋ : ℝ) + 1 = (↑(⌊x⌋ + 1) : ℝ))], }, }, { simp only [quotient_add_group.mk'_apply, real.norm_eq_abs, le_cInf_iff h₁ h₂], rintros b' ⟨b, hb, rfl⟩, simp only [mem_set_of_eq, quotient_add_group.eq_iff_sub_mem, mem_zmultiples_iff, smul_one_eq_coe] at hb, obtain ⟨z, hz⟩ := hb, rw [(by { rw hz, abel, } : x = b - z), fract_sub_int, ← abs_sub_round_eq_min], convert round_le b 0, simp, }, end lemma norm_eq' (hp : 0 < p) {x : ℝ} : ‖(x : add_circle p)‖ = p * |(p⁻¹ * x) - round (p⁻¹ * x)| := begin conv_rhs { congr, rw ← abs_eq_self.mpr hp.le, }, rw [← abs_mul, mul_sub, mul_inv_cancel_left₀ hp.ne.symm, norm_eq, mul_comm p], end lemma norm_le_half_period {x : add_circle p} (hp : p ≠ 0) : ‖x‖ ≤ |p|/2 := begin obtain ⟨x⟩ := x, change ‖(x : add_circle p)‖ ≤ |p|/2, rw [norm_eq, ← mul_le_mul_left (abs_pos.mpr (inv_ne_zero hp)), ← abs_mul, mul_sub, mul_left_comm, ← mul_div_assoc, ← abs_mul, inv_mul_cancel hp, mul_one, abs_one], exact abs_sub_round (p⁻¹ * x), end @[simp] lemma norm_half_period_eq : ‖(↑(p/2) : add_circle p)‖ = |p|/2 := begin rcases eq_or_ne p 0 with rfl | hp, { simp, }, rw [norm_eq, ← mul_div_assoc, inv_mul_cancel hp, one_div, round_two_inv, algebra_map.coe_one, one_mul, (by linarith : p / 2 - p = -(p / 2)), abs_neg, abs_div, abs_two], end lemma norm_coe_eq_abs_iff {x : ℝ} (hp : p ≠ 0) : ‖(x : add_circle p)‖ = |x| ↔ |x| ≤ |p|/2 := begin refine ⟨λ hx, hx ▸ norm_le_half_period p hp, λ hx, _⟩, suffices : ∀ (p : ℝ), 0 < p → |x| ≤ p/2 → ‖(x : add_circle p)‖ = |x|, { rcases lt_trichotomy 0 p with hp | rfl | hp, { rw abs_eq_self.mpr hp.le at hx, exact this p hp hx, }, { contradiction, }, { rw ← norm_neg_period, rw abs_eq_neg_self.mpr hp.le at hx, exact this (-p) (neg_pos.mpr hp) hx, }, }, clear hx, intros p hp hx, rcases eq_or_ne x (p/2) with rfl | hx', { simp [abs_div, abs_two], }, suffices : round (p⁻¹ * x) = 0, { simp [norm_eq, this], }, rw round_eq_zero_iff, obtain ⟨hx₁, hx₂⟩ := abs_le.mp hx, replace hx₂ := ne.lt_of_le hx' hx₂, split, { rwa [← mul_le_mul_left hp, ← mul_assoc, mul_inv_cancel hp.ne.symm, one_mul, mul_neg, ← mul_div_assoc, mul_one], }, { rwa [← mul_lt_mul_left hp, ← mul_assoc, mul_inv_cancel hp.ne.symm, one_mul, ← mul_div_assoc, mul_one], }, end open metric lemma closed_ball_eq_univ_of_half_period_le (hp : p ≠ 0) (x : add_circle p) {ε : ℝ} (hε : |p|/2 ≤ ε) : closed_ball x ε = univ := eq_univ_iff_forall.mpr $ λ x, by simpa only [mem_closed_ball, dist_eq_norm] using (norm_le_half_period p hp).trans hε @[simp] lemma coe_real_preimage_closed_ball_period_zero (x ε : ℝ) : coe⁻¹' closed_ball (x : add_circle (0 : ℝ)) ε = closed_ball x ε := by { ext y; simp [dist_eq_norm, ← quotient_add_group.coe_sub], } lemma coe_real_preimage_closed_ball_eq_Union (x ε : ℝ) : coe⁻¹' closed_ball (x : add_circle p) ε = ⋃ (z : ℤ), closed_ball (x + z • p) ε := begin rcases eq_or_ne p 0 with rfl | hp, { simp [Union_const], }, ext y, simp only [dist_eq_norm, mem_preimage, mem_closed_ball, zsmul_eq_mul, mem_Union, real.norm_eq_abs, ← quotient_add_group.coe_sub, norm_eq, ← sub_sub], refine ⟨λ h, ⟨round (p⁻¹ * (y - x)), h⟩, _⟩, rintros ⟨n, hn⟩, rw [← mul_le_mul_left (abs_pos.mpr $ inv_ne_zero hp), ← abs_mul, mul_sub, mul_comm _ p, inv_mul_cancel_left₀ hp] at hn ⊢, exact (round_le (p⁻¹ * (y - x)) n).trans hn, end lemma coe_real_preimage_closed_ball_inter_eq {x ε : ℝ} (s : set ℝ) (hs : s ⊆ closed_ball x (|p|/2)) : coe⁻¹' closed_ball (x : add_circle p) ε ∩ s = if ε < |p|/2 then (closed_ball x ε) ∩ s else s := begin cases le_or_lt (|p|/2) ε with hε hε, { rcases eq_or_ne p 0 with rfl | hp, { simp only [abs_zero, zero_div] at hε, simp only [not_lt.mpr hε, coe_real_preimage_closed_ball_period_zero, abs_zero, zero_div, if_false, inter_eq_right_iff_subset], exact hs.trans (closed_ball_subset_closed_ball $ by simp [hε]), }, simp [closed_ball_eq_univ_of_half_period_le p hp ↑x hε, not_lt.mpr hε], }, { suffices : ∀ (z : ℤ), closed_ball (x + z • p) ε ∩ s = if z = 0 then closed_ball x ε ∩ s else ∅, { simp [-zsmul_eq_mul, ← quotient_add_group.coe_zero, coe_real_preimage_closed_ball_eq_Union, Union_inter, Union_ite, this, hε], }, intros z, simp only [real.closed_ball_eq_Icc, zero_sub, zero_add] at ⊢ hs, rcases eq_or_ne z 0 with rfl | hz, { simp, }, simp only [hz, zsmul_eq_mul, if_false, eq_empty_iff_forall_not_mem], rintros y ⟨⟨hy₁, hy₂⟩, hy₀⟩, obtain ⟨hy₃, hy₄⟩ := hs hy₀, rcases lt_trichotomy 0 p with hp | rfl | hp, { cases int.cast_le_neg_one_or_one_le_cast_of_ne_zero ℝ hz with hz' hz', { have : ↑z * p ≤ - p, nlinarith, linarith [abs_eq_self.mpr hp.le] }, { have : p ≤ ↑z * p, nlinarith, linarith [abs_eq_self.mpr hp.le] } }, { simp only [mul_zero, add_zero, abs_zero, zero_div] at hy₁ hy₂ hε, linarith }, { cases int.cast_le_neg_one_or_one_le_cast_of_ne_zero ℝ hz with hz' hz', { have : - p ≤ ↑z * p, nlinarith, linarith [abs_eq_neg_self.mpr hp.le] }, { have : ↑z * p ≤ p, nlinarith, linarith [abs_eq_neg_self.mpr hp.le] } } }, end section finite_order_points variables {p} [hp : fact (0 < p)] include hp lemma norm_div_nat_cast {m n : ℕ} : ‖(↑((↑m / ↑n) * p) : add_circle p)‖ = p * (↑(min (m % n) (n - m % n)) / n) := begin have : p⁻¹ * (↑m / ↑n * p) = ↑m / ↑n, { rw [mul_comm _ p, inv_mul_cancel_left₀ hp.out.ne.symm], }, rw [norm_eq' p hp.out, this, abs_sub_round_div_nat_cast_eq], end lemma exists_norm_eq_of_fin_add_order {u : add_circle p} (hu : is_of_fin_add_order u) : ∃ (k : ℕ), ‖u‖ = p * (k / add_order_of u) := begin let n := add_order_of u, change ∃ (k : ℕ), ‖u‖ = p * (k / n), obtain ⟨m, -, -, hm⟩ := exists_gcd_eq_one_of_is_of_fin_add_order hu, refine ⟨min (m % n) (n - m % n), _⟩, rw [← hm, norm_div_nat_cast], end lemma le_add_order_smul_norm_of_is_of_fin_add_order {u : add_circle p} (hu : is_of_fin_add_order u) (hu' : u ≠ 0) : p ≤ add_order_of u • ‖u‖ := begin obtain ⟨n, hn⟩ := exists_norm_eq_of_fin_add_order hu, replace hu : (add_order_of u : ℝ) ≠ 0, { norm_cast, exact (add_order_of_pos_iff.mpr hu).ne.symm }, conv_lhs { rw ← mul_one p, }, rw [hn, nsmul_eq_mul, ← mul_assoc, mul_comm _ p, mul_assoc, mul_div_cancel' _ hu, mul_le_mul_left hp.out, nat.one_le_cast, nat.one_le_iff_ne_zero], contrapose! hu', simpa only [hu', algebra_map.coe_zero, zero_div, mul_zero, norm_eq_zero] using hn, end end finite_order_points end add_circle namespace unit_add_circle lemma norm_eq {x : ℝ} : ‖(x : unit_add_circle)‖ = |x - round x| := by simp [add_circle.norm_eq] end unit_add_circle
62dc3eb327ab04cf86807ac3940aae048d8fb802
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/data/int/div.lean
a7e0f162eddeadf9c943e0501d4b7ab683a7691d
[ "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
29,579
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) attribute [instance, priority int.prio] definition int_has_div : 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 attribute [instance, priority int.prio] definition int_has_mod : 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 := have (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, have 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, have H3 : m + 1 ≤ n * k, from nat.succ_le_of_lt m_lt_nk, have 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 := have 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 attribute [instance] definition dvd.decidable_rel : 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 := have 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
e2d6049cdf5404c91dbddcc286c4e2b09247ca97
07f5f86b00fed90a419ccda4298d8b795a68f657
/library/data/rbmap/default.lean
cb58491751645667c9cbd3404c18db90afa31a13
[ "Apache-2.0" ]
permissive
VBaratham/lean
8ec5c3167b4835cfbcd7f25e2173d61ad9416b3a
450ca5834c1c35318e4b47d553bb9820c1b3eee7
refs/heads/master
1,629,649,471,814
1,512,060,373,000
1,512,060,469,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,974
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import data.rbtree universes u v namespace rbmap variables {α : Type u} {β : Type v} {lt : α → α → Prop} /- Auxiliary instances -/ private def rbmap_lt_is_swo {α : Type u} {β : Type v} {lt : α → α → Prop} [is_strict_weak_order α lt] : is_strict_weak_order (α × β) (rbmap_lt lt) := { irrefl := λ _, irrefl_of lt _, trans := λ _ _ _ h₁ h₂, trans_of lt h₁ h₂, incomp_trans := λ _ _ _ h₁ h₂, incomp_trans_of lt h₁ h₂ } private def rbmap_lt_dec {α : Type u} {β : Type v} {lt : α → α → Prop} [h : decidable_rel lt] : decidable_rel (@rbmap_lt α β lt) := λ a b, h a.1 b.1 local attribute [instance] rbmap_lt_is_swo rbmap_lt_dec /- Helper lemmas for reusing rbtree results. -/ private lemma to_rbtree_mem {k : α} {m : rbmap α β lt} : k ∈ m → ∃ v : β, rbtree.mem (k, v) m := begin cases m with n p; cases n; intros h, { exact false.elim h }, all_goals { existsi val.2, exact h } end private lemma eqv_entries_of_eqv_keys {k₁ k₂ : α} (v₁ v₂ : β) : k₁ ≈[lt] k₂ → (k₁, v₁) ≈[rbmap_lt lt] (k₂, v₂) := id private lemma eqv_keys_of_eqv_entries {k₁ k₂ : α} {v₁ v₂ : β} : (k₁, v₁) ≈[rbmap_lt lt] (k₂, v₂) → k₁ ≈[lt] k₂ := id private lemma eqv_entries [is_irrefl α lt] (k : α) (v₁ v₂ : β) : (k, v₁) ≈[rbmap_lt lt] (k, v₂) := and.intro (irrefl_of lt k) (irrefl_of lt k) private lemma to_rbmap_mem [is_strict_weak_order α lt] {k : α} {v : β} {m : rbmap α β lt} : rbtree.mem (k, v) m → k ∈ m := begin cases m with n p; cases n; intros h, { exact false.elim h }, { simp [has_mem.mem, rbmap.mem], exact @rbtree.mem_of_mem_of_eqv _ _ _ ⟨rbnode.red_node lchild val rchild, p⟩ _ _ h (eqv_entries _ _ _) }, { simp [has_mem.mem, rbmap.mem], exact @rbtree.mem_of_mem_of_eqv _ _ _ ⟨rbnode.black_node lchild val rchild, p⟩ _ _ h (eqv_entries _ _ _) } end private lemma to_rbtree_mem' [is_strict_weak_order α lt] {k : α} {m : rbmap α β lt} (v : β) : k ∈ m → rbtree.mem (k, v) m := begin intro h, cases to_rbtree_mem h with v' hm, apply rbtree.mem_of_mem_of_eqv hm, apply eqv_entries end lemma eq_some_of_to_value_eq_some {e : option (α × β)} {v : β} : to_value e = some v → ∃ k, e = some (k, v) := begin cases e; simp [to_value], { contradiction }, { cases a, simp, intro h, injection h, subst v, existsi fst, refl } end lemma eq_none_of_to_value_eq_none {e : option (α × β)} : to_value e = none → e = none := begin cases e; simp [to_value], { contradiction } end /- Lemmas -/ lemma not_mem_mk_rbmap : ∀ (k : α), k ∉ mk_rbmap α β lt := by simp [has_mem.mem, mk_rbmap, mk_rbtree, rbmap.mem] lemma not_mem_of_empty {m : rbmap α β lt} (k : α) : m.empty = tt → k ∉ m := by cases m with n p; cases n; simp [has_mem.mem, mk_rbmap, mk_rbtree, rbmap.mem, rbmap.empty, rbtree.empty] variables [decidable_rel lt] lemma not_mem_of_find_entry_none [is_strict_weak_order α lt] {k : α} {m : rbmap α β lt} : m.find_entry k = none → k ∉ m := begin cases m with t p, cases t; simp [find_entry], { intros, simp [has_mem.mem, rbmap.mem] }, all_goals { intro h, exact rbtree.not_mem_of_find_none h, } end lemma not_mem_of_find_none [is_strict_weak_order α lt] {k : α} {m : rbmap α β lt} : m.find k = none → k ∉ m := begin simp [find], intro h, have := eq_none_of_to_value_eq_none h, exact not_mem_of_find_entry_none this end lemma mem_of_find_entry_some [is_strict_weak_order α lt] {k₁ : α} {e : α × β} {m : rbmap α β lt} : m.find_entry k₁ = some e → k₁ ∈ m := begin cases m with t p, cases t; simp [find_entry], { intros, contradiction }, all_goals { intro h, exact rbtree.mem_of_find_some h } end lemma mem_of_find_some [is_strict_weak_order α lt] {k : α} {v : β} {m : rbmap α β lt} : m.find k = some v → k ∈ m := begin simp [find], intro h, have := eq_some_of_to_value_eq_some h, cases this with _ he, exact mem_of_find_entry_some he end lemma find_entry_eq_find_entry_of_eqv [is_strict_weak_order α lt] {m : rbmap α β lt} {k₁ k₂ : α} : k₁ ≈[lt] k₂ → m.find_entry k₁ = m.find_entry k₂ := begin intro h, cases m with t p, cases t; simp [find_entry], all_goals { apply rbtree.find_eq_find_of_eqv, apply eqv_entries_of_eqv_keys, assumption } end lemma find_eq_find_of_eqv [is_strict_weak_order α lt] {k₁ k₂ : α} (m : rbmap α β lt) : k₁ ≈[lt] k₂ → m.find k₁ = m.find k₂ := begin intro h, simp [find], apply congr_arg, apply find_entry_eq_find_entry_of_eqv, assumption end lemma find_entry_correct [is_strict_weak_order α lt] (k : α) (m : rbmap α β lt) : k ∈ m ↔ (∃ e, m.find_entry k = some e ∧ k ≈[lt] e.1) := begin apply iff.intro; cases m with t p, { intro h, have h := to_rbtree_mem h, cases h with v h₁, have hex := iff.mp (rbtree.find_correct _ _) h₁, cases hex with e h₂, existsi e, cases t; simp [find_entry] at ⊢ h₂, { simp [rbtree.find, rbnode.find] at h₂, cases h₂, contradiction }, { cases h₂ with h₂₁ h₂₂, split, { cases e, apply eqv_keys_of_eqv_entries h₂₁ }, { have := rbtree.find_eq_find_of_eqv ⟨rbnode.red_node lchild val rchild, p⟩ (eqv_entries k v val.snd), rw [←this], exact h₂₂ } }, { cases h₂ with h₂₁ h₂₂, split, { cases e, apply eqv_keys_of_eqv_entries h₂₁ }, { have := rbtree.find_eq_find_of_eqv ⟨rbnode.black_node lchild val rchild, p⟩ (eqv_entries k v val.snd), rw [←this], exact h₂₂ } } }, { intro h, cases h with e h, cases h with h₁ h₂, cases t; simp [find_entry] at h₁, { contradiction }, all_goals { exact to_rbmap_mem (rbtree.mem_of_find_some h₁) } } end lemma eqv_of_find_entry_some [is_strict_weak_order α lt] {k₁ k₂ : α} {v : β} {m : rbmap α β lt} : m.find_entry k₁ = some (k₂, v) → k₁ ≈[lt] k₂ := begin cases m with t p, cases t; simp [find_entry], { contradiction }, all_goals { intro h, exact eqv_keys_of_eqv_entries (rbtree.eqv_of_find_some h) } end lemma eq_of_find_entry_some [is_strict_total_order α lt] {k₁ k₂ : α} {v : β} {m : rbmap α β lt} : m.find_entry k₁ = some (k₂, v) → k₁ = k₂ := λ h, suffices k₁ ≈[lt] k₂, from eq_of_eqv_lt this, eqv_of_find_entry_some h lemma find_correct [is_strict_weak_order α lt] (k : α) (m : rbmap α β lt) : k ∈ m ↔ ∃ v, m.find k = some v := begin apply iff.intro, { intro h, have := iff.mp (find_entry_correct k m) h, cases this with e h, cases h with h₁ h₂, existsi e.2, simp [find, h₁, to_value] }, { intro h, cases h with v h, simp [find] at h, have h := eq_some_of_to_value_eq_some h, cases h with k' h, have heqv := eqv_of_find_entry_some h, exact iff.mpr (find_entry_correct k m) ⟨(k', v), ⟨h, heqv⟩⟩ } end lemma constains_correct [is_strict_weak_order α lt] (k : α) (m : rbmap α β lt) : k ∈ m ↔ m.contains k = tt := begin apply iff.intro, { intro h, have h := iff.mp (find_entry_correct k m) h, cases h with e h, cases h with h₁ h₂, simp [contains, h₁, option.is_some] }, { simp [contains], intro h, generalize he : find_entry m k = e, cases e, { simp [he, option.is_some] at h, contradiction }, { exact mem_of_find_entry_some he } } end lemma mem_of_mem_of_eqv [is_strict_weak_order α lt] {m : rbmap α β lt} {k₁ k₂ : α} : k₁ ∈ m → k₁ ≈[lt] k₂ → k₂ ∈ m := begin intros h₁ h₂, have h₁ := to_rbtree_mem h₁, cases h₁ with v h₁, exact to_rbmap_mem (rbtree.mem_of_mem_of_eqv h₁ (eqv_entries_of_eqv_keys v v h₂)) end lemma mem_insert_of_incomp [is_strict_weak_order α lt] {k₁ k₂ : α} (m : rbmap α β lt) (v : β) : (¬ lt k₁ k₂ ∧ ¬ lt k₂ k₁) → k₁ ∈ m.insert k₂ v := λ h, to_rbmap_mem (rbtree.mem_insert_of_incomp m (eqv_entries_of_eqv_keys v v h)) lemma mem_insert [is_strict_weak_order α lt] (k : α) (m : rbmap α β lt) (v : β) : k ∈ m.insert k v := to_rbmap_mem (rbtree.mem_insert (k, v) m) lemma mem_insert_of_equiv [is_strict_weak_order α lt] {k₁ k₂ : α} (m : rbmap α β lt) (v : β) : k₁ ≈[lt] k₂ → k₁ ∈ m.insert k₂ v := mem_insert_of_incomp m v lemma mem_insert_of_mem [is_strict_weak_order α lt] {k₁ : α} {m : rbmap α β lt} (k₂ : α) (v : β) : k₁ ∈ m → k₁ ∈ m.insert k₂ v := λ h, to_rbmap_mem (rbtree.mem_insert_of_mem (k₂, v) (to_rbtree_mem' v h)) lemma equiv_or_mem_of_mem_insert [is_strict_weak_order α lt] {k₁ k₂ : α} {v : β} {m : rbmap α β lt} : k₁ ∈ m.insert k₂ v → k₁ ≈[lt] k₂ ∨ k₁ ∈ m := λ h, or.elim (rbtree.equiv_or_mem_of_mem_insert (to_rbtree_mem' v h)) (λ h, or.inl (eqv_keys_of_eqv_entries h)) (λ h, or.inr (to_rbmap_mem h)) lemma incomp_or_mem_of_mem_ins [is_strict_weak_order α lt] {k₁ k₂ : α} {v : β} {m : rbmap α β lt} : k₁ ∈ m.insert k₂ v → (¬ lt k₁ k₂ ∧ ¬ lt k₂ k₁) ∨ k₁ ∈ m := equiv_or_mem_of_mem_insert lemma eq_or_mem_of_mem_ins [is_strict_total_order α lt] {k₁ k₂ : α} {v : β} {m : rbmap α β lt} : k₁ ∈ m.insert k₂ v → k₁ = k₂ ∨ k₁ ∈ m := λ h, suffices k₁ ≈[lt] k₂ ∨ k₁ ∈ m, by simp [eqv_lt_iff_eq] at this; assumption, incomp_or_mem_of_mem_ins h lemma find_entry_insert_of_eqv [is_strict_weak_order α lt] (m : rbmap α β lt) {k₁ k₂ : α} (v : β) : k₁ ≈[lt] k₂ → (m.insert k₁ v).find_entry k₂ = some (k₁, v) := begin intro h, generalize h₁ : m.insert k₁ v = m', cases m' with t p, cases t, { have := mem_insert k₁ m v, rw [h₁] at this, apply absurd this, apply not_mem_mk_rbmap }, all_goals { simp [find_entry], rw [←h₁, insert], apply rbtree.find_insert_of_eqv, apply eqv_entries_of_eqv_keys _ _ h } end lemma find_entry_insert [is_strict_weak_order α lt] (m : rbmap α β lt) (k : α) (v : β) : (m.insert k v).find_entry k = some (k, v) := find_entry_insert_of_eqv m v (refl k) lemma find_insert_of_eqv [is_strict_weak_order α lt] (m : rbmap α β lt) {k₁ k₂ : α} (v : β) : k₁ ≈[lt] k₂ → (m.insert k₁ v).find k₂ = some v := begin intro h, have := find_entry_insert_of_eqv m v h, simp [find, this, to_value] end lemma find_insert [is_strict_weak_order α lt] (m : rbmap α β lt) (k : α) (v : β) : (m.insert k v).find k = some v := find_insert_of_eqv m v (refl k) lemma find_entry_insert_of_disj [is_strict_weak_order α lt] {k₁ k₂ : α} (m : rbmap α β lt) (v : β) : lt k₁ k₂ ∨ lt k₂ k₁ → (m.insert k₁ v).find_entry k₂ = m.find_entry k₂ := begin intro h, have h' : ∀ {v₁ v₂ : β}, (rbmap_lt lt) (k₁, v₁) (k₂, v₂) ∨ (rbmap_lt lt) (k₂, v₂) (k₁, v₁) := λ _ _, h, generalize h₁ : m = m₁, generalize h₂ : insert m₁ k₁ v = m₂, rw [←h₁] at h₂ ⊢, rw [←h₂], cases m₁ with t₁ p₁; cases t₁; cases m₂ with t₂ p₂; cases t₂, { rw [h₂, h₁] }, twice { rw [h₂], conv { to_lhs, simp [find_entry] }, rw [←h₂, insert, rbtree.find_insert_of_disj _ h', h₁], refl }, any_goals { simp [insert] at h₂, exact absurd h₂ (rbtree.insert_ne_mk_rbtree m (k₁, v)) }, any_goals { rw [h₂, h₁], simp [find_entry], rw [←h₂, ←h₁, insert, rbtree.find_insert_of_disj _ h'], apply rbtree.find_eq_find_of_eqv, apply eqv_entries } end lemma find_entry_insert_of_not_eqv [is_strict_weak_order α lt] {k₁ k₂ : α} (m : rbmap α β lt) (v : β) : ¬ k₁ ≈[lt] k₂ → (m.insert k₁ v).find_entry k₂ = m.find_entry k₂ := begin intro hn, have he : lt k₁ k₂ ∨ lt k₂ k₁, { simp [strict_weak_order.equiv, decidable.not_and_iff_or_not, decidable.not_not_iff] at hn, assumption }, apply find_entry_insert_of_disj _ _ he end lemma find_entry_insert_of_ne [is_strict_total_order α lt] {k₁ k₂ : α} (m : rbmap α β lt) (v : β) : k₁ ≠ k₂ → (m.insert k₁ v).find_entry k₂ = m.find_entry k₂ := begin intro h, have : ¬ k₁ ≈[lt] k₂ := λ h', h (eq_of_eqv_lt h'), apply find_entry_insert_of_not_eqv _ _ this end lemma find_insert_of_disj [is_strict_weak_order α lt] {k₁ k₂ : α} (m : rbmap α β lt) (v : β) : lt k₁ k₂ ∨ lt k₂ k₁ → (m.insert k₁ v).find k₂ = m.find k₂ := begin intro h, have := find_entry_insert_of_disj m v h, simp [find, this] end lemma find_insert_of_not_eqv [is_strict_weak_order α lt] {k₁ k₂ : α} (m : rbmap α β lt) (v : β) : ¬ k₁ ≈[lt] k₂ → (m.insert k₁ v).find k₂ = m.find k₂ := begin intro h, have := find_entry_insert_of_not_eqv m v h, simp [find, this] end lemma find_insert_of_ne [is_strict_total_order α lt] {k₁ k₂ : α} (m : rbmap α β lt) (v : β) : k₁ ≠ k₂ → (m.insert k₁ v).find k₂ = m.find k₂ := begin intro h, have := find_entry_insert_of_ne m v h, simp [find, this] end lemma mem_of_min_eq [is_strict_total_order α lt] {k : α} {v : β} {m : rbmap α β lt} : m.min = some (k, v) → k ∈ m := λ h, to_rbmap_mem (rbtree.mem_of_min_eq h) lemma mem_of_max_eq [is_strict_total_order α lt] {k : α} {v : β} {m : rbmap α β lt} : m.max = some (k, v) → k ∈ m := λ h, to_rbmap_mem (rbtree.mem_of_max_eq h) lemma eq_leaf_of_min_eq_none [is_strict_weak_order α lt] {m : rbmap α β lt} : m.min = none → m = mk_rbmap α β lt := rbtree.eq_leaf_of_min_eq_none lemma eq_leaf_of_max_eq_none [is_strict_weak_order α lt] {m : rbmap α β lt} : m.max = none → m = mk_rbmap α β lt := rbtree.eq_leaf_of_max_eq_none lemma min_is_minimal [is_strict_weak_order α lt] {k : α} {v : β} {m : rbmap α β lt} : m.min = some (k, v) → ∀ {k'}, k' ∈ m → k ≈[lt] k' ∨ lt k k' := λ h k' hm, or.elim (rbtree.min_is_minimal h (to_rbtree_mem' v hm)) (λ h, or.inl (eqv_keys_of_eqv_entries h)) (λ h, or.inr h) lemma max_is_maximal [is_strict_weak_order α lt] {k : α} {v : β} {m : rbmap α β lt} : m.max = some (k, v) → ∀ {k'}, k' ∈ m → k ≈[lt] k' ∨ lt k' k := λ h k' hm, or.elim (rbtree.max_is_maximal h (to_rbtree_mem' v hm)) (λ h, or.inl (eqv_keys_of_eqv_entries h)) (λ h, or.inr h) lemma min_is_minimal_of_total [is_strict_total_order α lt] {k : α} {v : β} {m : rbmap α β lt} : m.min = some (k, v) → ∀ {k'}, k' ∈ m → k = k' ∨ lt k k' := λ h k' hm, match min_is_minimal h hm with | or.inl h := or.inl (eq_of_eqv_lt h) | or.inr h := or.inr h end lemma max_is_maximal_of_total [is_strict_total_order α lt] {k : α} {v : β} {m : rbmap α β lt} : m.max = some (k, v) → ∀ {k'}, k' ∈ m → k = k' ∨ lt k' k := λ h k' hm, match max_is_maximal h hm with | or.inl h := or.inl (eq_of_eqv_lt h) | or.inr h := or.inr h end end rbmap
68438d5ff5096bbe86724ad542ca730fcbdeff42
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/data/setoid/basic.lean
ff46d5ba341ddb52a588622ac5e1d62ec5fd43df
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
16,409
lean
/- Copyright (c) 2019 Amelia Livingston. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Amelia Livingston, Bryan Gin-ge Chen -/ import order.galois_connection /-! # Equivalence relations This file defines the complete lattice of equivalence relations on a type, results about the inductively defined equivalence closure of a binary relation, and the analogues of some isomorphism theorems for quotients of arbitrary types. ## Implementation notes The function `rel` and lemmas ending in ' make it easier to talk about different equivalence relations on the same type. The complete lattice instance for equivalence relations could have been defined by lifting the Galois insertion of equivalence relations on α into binary relations on α, and then using `complete_lattice.copy` to define a complete lattice instance with more appropriate definitional equalities (a similar example is `filter.complete_lattice` in `order/filter/basic.lean`). This does not save space, however, and is less clear. Partitions are not defined as a separate structure here; users are encouraged to reason about them using the existing `setoid` and its infrastructure. ## Tags setoid, equivalence, iseqv, relation, equivalence relation -/ variables {α : Type*} {β : Type*} /-- A version of `setoid.r` that takes the equivalence relation as an explicit argument. -/ def setoid.rel (r : setoid α) : α → α → Prop := @setoid.r _ r /-- A version of `quotient.eq'` compatible with `setoid.rel`, to make rewriting possible. -/ lemma quotient.eq_rel {r : setoid α} {x y} : ⟦x⟧ = ⟦y⟧ ↔ r.rel x y := quotient.eq' namespace setoid @[ext] lemma ext' {r s : setoid α} (H : ∀ a b, r.rel a b ↔ s.rel a b) : r = s := ext H lemma ext_iff {r s : setoid α} : r = s ↔ ∀ a b, r.rel a b ↔ s.rel a b := ⟨λ h a b, h ▸ iff.rfl, ext'⟩ /-- Two equivalence relations are equal iff their underlying binary operations are equal. -/ theorem eq_iff_rel_eq {r₁ r₂ : setoid α} : r₁ = r₂ ↔ r₁.rel = r₂.rel := ⟨λ h, h ▸ rfl, λ h, setoid.ext' $ λ x y, h ▸ iff.rfl⟩ /-- Defining `≤` for equivalence relations. -/ instance : has_le (setoid α) := ⟨λ r s, ∀ ⦃x y⦄, r.rel x y → s.rel x y⟩ theorem le_def {r s : setoid α} : r ≤ s ↔ ∀ {x y}, r.rel x y → s.rel x y := iff.rfl @[refl] lemma refl' (r : setoid α) (x) : r.rel x x := r.2.1 x @[symm] lemma symm' (r : setoid α) : ∀ {x y}, r.rel x y → r.rel y x := λ _ _ h, r.2.2.1 h @[trans] lemma trans' (r : setoid α) : ∀ {x y z}, r.rel x y → r.rel y z → r.rel x z := λ _ _ _ hx, r.2.2.2 hx /-- The kernel of a function is an equivalence relation. -/ def ker (f : α → β) : setoid α := ⟨λ x y, f x = f y, ⟨λ _, rfl, λ _ _ h, h.symm, λ _ _ _ h, h.trans⟩⟩ /-- The kernel of the quotient map induced by an equivalence relation r equals r. -/ @[simp] lemma ker_mk_eq (r : setoid α) : ker (@quotient.mk _ r) = r := ext' $ λ x y, quotient.eq lemma ker_def {f : α → β} {x y : α} : (ker f).rel x y ↔ f x = f y := iff.rfl /-- Given types `α`, `β`, the product of two equivalence relations `r` on `α` and `s` on `β`: `(x₁, x₂), (y₁, y₂) ∈ α × β` are related by `r.prod s` iff `x₁` is related to `y₁` by `r` and `x₂` is related to `y₂` by `s`. -/ protected def prod (r : setoid α) (s : setoid β) : setoid (α × β) := { r := λ x y, r.rel x.1 y.1 ∧ s.rel x.2 y.2, iseqv := ⟨λ x, ⟨r.refl' x.1, s.refl' x.2⟩, λ _ _ h, ⟨r.symm' h.1, s.symm' h.2⟩, λ _ _ _ h1 h2, ⟨r.trans' h1.1 h2.1, s.trans' h1.2 h2.2⟩⟩ } /-- The infimum of two equivalence relations. -/ instance : has_inf (setoid α) := ⟨λ r s, ⟨λ x y, r.rel x y ∧ s.rel x y, ⟨λ x, ⟨r.refl' x, s.refl' x⟩, λ _ _ h, ⟨r.symm' h.1, s.symm' h.2⟩, λ _ _ _ h1 h2, ⟨r.trans' h1.1 h2.1, s.trans' h1.2 h2.2⟩⟩⟩⟩ /-- The infimum of 2 equivalence relations r and s is the same relation as the infimum of the underlying binary operations. -/ lemma inf_def {r s : setoid α} : (r ⊓ s).rel = r.rel ⊓ s.rel := rfl theorem inf_iff_and {r s : setoid α} {x y} : (r ⊓ s).rel x y ↔ r.rel x y ∧ s.rel x y := iff.rfl /-- The infimum of a set of equivalence relations. -/ instance : has_Inf (setoid α) := ⟨λ S, ⟨λ x y, ∀ r ∈ S, rel r x y, ⟨λ x r hr, r.refl' x, λ _ _ h r hr, r.symm' $ h r hr, λ _ _ _ h1 h2 r hr, r.trans' (h1 r hr) $ h2 r hr⟩⟩⟩ /-- The underlying binary operation of the infimum of a set of equivalence relations is the infimum of the set's image under the map to the underlying binary operation. -/ theorem Inf_def {s : set (setoid α)} : (Inf s).rel = Inf (rel '' s) := by { ext, simp only [Inf_image, infi_apply, infi_Prop_eq], refl } instance : partial_order (setoid α) := { le := (≤), lt := λ r s, r ≤ s ∧ ¬s ≤ r, le_refl := λ _ _ _, id, le_trans := λ _ _ _ hr hs _ _ h, hs $ hr h, lt_iff_le_not_le := λ _ _, iff.rfl, le_antisymm := λ r s h1 h2, setoid.ext' $ λ x y, ⟨λ h, h1 h, λ h, h2 h⟩ } /-- The complete lattice of equivalence relations on a type, with bottom element `=` and top element the trivial equivalence relation. -/ instance complete_lattice : complete_lattice (setoid α) := { inf := has_inf.inf, inf_le_left := λ _ _ _ _ h, h.1, inf_le_right := λ _ _ _ _ h, h.2, le_inf := λ _ _ _ h1 h2 _ _ h, ⟨h1 h, h2 h⟩, top := ⟨λ _ _, true, ⟨λ _, trivial, λ _ _ h, h, λ _ _ _ h1 h2, h1⟩⟩, le_top := λ _ _ _ _, trivial, bot := ⟨(=), ⟨λ _, rfl, λ _ _ h, h.symm, λ _ _ _ h1 h2, h1.trans h2⟩⟩, bot_le := λ r x y h, h ▸ r.2.1 x, .. complete_lattice_of_Inf (setoid α) $ assume s, ⟨λ r hr x y h, h _ hr, λ r hr x y h r' hr', hr hr' h⟩ } /-- The inductively defined equivalence closure of a binary relation r is the infimum of the set of all equivalence relations containing r. -/ theorem eqv_gen_eq (r : α → α → Prop) : eqv_gen.setoid r = Inf {s : setoid α | ∀ ⦃x y⦄, r x y → s.rel x y} := le_antisymm (λ _ _ H, eqv_gen.rec (λ _ _ h _ hs, hs h) (refl' _) (λ _ _ _, symm' _) (λ _ _ _ _ _, trans' _) H) (Inf_le $ λ _ _ h, eqv_gen.rel _ _ h) /-- The supremum of two equivalence relations r and s is the equivalence closure of the binary relation `x is related to y by r or s`. -/ lemma sup_eq_eqv_gen (r s : setoid α) : r ⊔ s = eqv_gen.setoid (λ x y, r.rel x y ∨ s.rel x y) := begin rw eqv_gen_eq, apply congr_arg Inf, simp only [le_def, or_imp_distrib, ← forall_and_distrib] end /-- The supremum of 2 equivalence relations r and s is the equivalence closure of the supremum of the underlying binary operations. -/ lemma sup_def {r s : setoid α} : r ⊔ s = eqv_gen.setoid (r.rel ⊔ s.rel) := by rw sup_eq_eqv_gen; refl /-- The supremum of a set S of equivalence relations is the equivalence closure of the binary relation `there exists r ∈ S relating x and y`. -/ lemma Sup_eq_eqv_gen (S : set (setoid α)) : Sup S = eqv_gen.setoid (λ x y, ∃ r : setoid α, r ∈ S ∧ r.rel x y) := begin rw eqv_gen_eq, apply congr_arg Inf, simp only [upper_bounds, le_def, and_imp, exists_imp_distrib], ext, exact ⟨λ H x y r hr, H hr, λ H r hr x y, H r hr⟩ end /-- The supremum of a set of equivalence relations is the equivalence closure of the supremum of the set's image under the map to the underlying binary operation. -/ lemma Sup_def {s : set (setoid α)} : Sup s = eqv_gen.setoid (Sup (rel '' s)) := begin rw [Sup_eq_eqv_gen, Sup_image], congr, ext x y, simp only [supr_apply, supr_Prop_eq, exists_prop] end /-- The equivalence closure of an equivalence relation r is r. -/ @[simp] lemma eqv_gen_of_setoid (r : setoid α) : eqv_gen.setoid r.r = r := le_antisymm (by rw eqv_gen_eq; exact Inf_le (λ _ _, id)) eqv_gen.rel /-- Equivalence closure is idempotent. -/ @[simp] lemma eqv_gen_idem (r : α → α → Prop) : eqv_gen.setoid (eqv_gen.setoid r).rel = eqv_gen.setoid r := eqv_gen_of_setoid _ /-- The equivalence closure of a binary relation r is contained in any equivalence relation containing r. -/ theorem eqv_gen_le {r : α → α → Prop} {s : setoid α} (h : ∀ x y, r x y → s.rel x y) : eqv_gen.setoid r ≤ s := by rw eqv_gen_eq; exact Inf_le h /-- Equivalence closure of binary relations is monotonic. -/ theorem eqv_gen_mono {r s : α → α → Prop} (h : ∀ x y, r x y → s x y) : eqv_gen.setoid r ≤ eqv_gen.setoid s := eqv_gen_le $ λ _ _ hr, eqv_gen.rel _ _ $ h _ _ hr /-- There is a Galois insertion of equivalence relations on α into binary relations on α, with equivalence closure the lower adjoint. -/ def gi : @galois_insertion (α → α → Prop) (setoid α) _ _ eqv_gen.setoid rel := { choice := λ r h, eqv_gen.setoid r, gc := λ r s, ⟨λ H _ _ h, H $ eqv_gen.rel _ _ h, λ H, eqv_gen_of_setoid s ▸ eqv_gen_mono H⟩, le_l_u := λ x, (eqv_gen_of_setoid x).symm ▸ le_refl x, choice_eq := λ _ _, rfl } open function /-- A function from α to β is injective iff its kernel is the bottom element of the complete lattice of equivalence relations on α. -/ theorem injective_iff_ker_bot (f : α → β) : injective f ↔ ker f = ⊥ := (@eq_bot_iff (setoid α) _ (ker f)).symm /-- The elements related to x ∈ α by the kernel of f are those in the preimage of f(x) under f. -/ lemma ker_iff_mem_preimage {f : α → β} {x y} : (ker f).rel x y ↔ x ∈ f ⁻¹' {f y} := iff.rfl /-- Equivalence between functions `α → β` such that `r x y → f x = f y` and functions `quotient r → β`. -/ def lift_equiv (r : setoid α) : {f : α → β // r ≤ ker f} ≃ (quotient r → β) := { to_fun := λ f, quotient.lift (f : α → β) f.2, inv_fun := λ f, ⟨f ∘ quotient.mk, λ x y h, by simp [ker_def, quotient.sound h]⟩, left_inv := λ ⟨f, hf⟩, subtype.eq $ funext $ λ x, rfl, right_inv := λ f, funext $ λ x, quotient.induction_on' x $ λ x, rfl } /-- The uniqueness part of the universal property for quotients of an arbitrary type. -/ theorem lift_unique {r : setoid α} {f : α → β} (H : r ≤ ker f) (g : quotient r → β) (Hg : f = g ∘ quotient.mk) : quotient.lift f H = g := begin ext ⟨x⟩, erw [quotient.lift_beta f H, Hg], refl end /-- Given a map f from α to β, the natural map from the quotient of α by the kernel of f is injective. -/ lemma ker_lift_injective (f : α → β) : injective (@quotient.lift _ _ (ker f) f (λ _ _ h, h)) := λ x y, quotient.induction_on₂' x y $ λ a b h, quotient.sound' h /-- Given a map f from α to β, the kernel of f is the unique equivalence relation on α whose induced map from the quotient of α to β is injective. -/ lemma ker_eq_lift_of_injective {r : setoid α} (f : α → β) (H : ∀ x y, r.rel x y → f x = f y) (h : injective (quotient.lift f H)) : ker f = r := le_antisymm (λ x y hk, quotient.exact $ h $ show quotient.lift f H ⟦x⟧ = quotient.lift f H ⟦y⟧, from hk) H variables (r : setoid α) (f : α → β) /-- The first isomorphism theorem for sets: the quotient of α by the kernel of a function f bijects with f's image. -/ noncomputable def quotient_ker_equiv_range : quotient (ker f) ≃ set.range f := equiv.of_bijective (@quotient.lift _ (set.range f) (ker f) (λ x, ⟨f x, set.mem_range_self x⟩) $ λ _ _ h, subtype.ext_val h) ⟨λ x y h, ker_lift_injective f $ by rcases x; rcases y; injections, λ ⟨w, z, hz⟩, ⟨@quotient.mk _ (ker f) z, by rw quotient.lift_beta; exact subtype.ext_iff_val.2 hz⟩⟩ /-- The quotient of α by the kernel of a surjective function f bijects with f's codomain. -/ noncomputable def quotient_ker_equiv_of_surjective (hf : surjective f) : quotient (ker f) ≃ β := (quotient_ker_equiv_range f).trans $ equiv.subtype_univ_equiv hf variables {r f} /-- Given a function `f : α → β` and equivalence relation `r` on `α`, the equivalence closure of the relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `r`.' -/ def map (r : setoid α) (f : α → β) : setoid β := eqv_gen.setoid $ λ x y, ∃ a b, f a = x ∧ f b = y ∧ r.rel a b /-- Given a surjective function f whose kernel is contained in an equivalence relation r, the equivalence relation on f's codomain defined by x ≈ y ↔ the elements of f⁻¹(x) are related to the elements of f⁻¹(y) by r. -/ def map_of_surjective (r) (f : α → β) (h : ker f ≤ r) (hf : surjective f) : setoid β := ⟨λ x y, ∃ a b, f a = x ∧ f b = y ∧ r.rel a b, ⟨λ x, let ⟨y, hy⟩ := hf x in ⟨y, y, hy, hy, r.refl' y⟩, λ _ _ ⟨x, y, hx, hy, h⟩, ⟨y, x, hy, hx, r.symm' h⟩, λ _ _ _ ⟨x, y, hx, hy, h₁⟩ ⟨y', z, hy', hz, h₂⟩, ⟨x, z, hx, hz, r.trans' h₁ $ r.trans' (h $ by rwa ←hy' at hy) h₂⟩⟩⟩ /-- A special case of the equivalence closure of an equivalence relation r equalling r. -/ lemma map_of_surjective_eq_map (h : ker f ≤ r) (hf : surjective f) : map r f = map_of_surjective r f h hf := by rw ←eqv_gen_of_setoid (map_of_surjective r f h hf); refl /-- Given a function `f : α → β`, an equivalence relation `r` on `β` induces an equivalence relation on `α` defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `r`'. -/ def comap (f : α → β) (r : setoid β) : setoid α := ⟨λ x y, r.rel (f x) (f y), ⟨λ _, r.refl' _, λ _ _ h, r.symm' h, λ _ _ _ h1, r.trans' h1⟩⟩ /-- Given a map `f : N → M` and an equivalence relation `r` on `β`, the equivalence relation induced on `α` by `f` equals the kernel of `r`'s quotient map composed with `f`. -/ lemma comap_eq {f : α → β} {r : setoid β} : comap f r = ker (@quotient.mk _ r ∘ f) := ext $ λ x y, show _ ↔ ⟦_⟧ = ⟦_⟧, by rw quotient.eq; refl /-- The second isomorphism theorem for sets. -/ noncomputable def comap_quotient_equiv (f : α → β) (r : setoid β) : quotient (comap f r) ≃ set.range (@quotient.mk _ r ∘ f) := (quotient.congr_right $ ext_iff.1 comap_eq).trans $ quotient_ker_equiv_range $ quotient.mk ∘ f variables (r f) /-- The third isomorphism theorem for sets. -/ def quotient_quotient_equiv_quotient (s : setoid α) (h : r ≤ s) : quotient (ker (quot.map_right h)) ≃ quotient s := { to_fun := λ x, quotient.lift_on' x (λ w, quotient.lift_on' w (@quotient.mk _ s) $ λ x y H, quotient.sound $ h H) $ λ x y, quotient.induction_on₂' x y $ λ w z H, show @quot.mk _ _ _ = @quot.mk _ _ _, from H, inv_fun := λ x, quotient.lift_on' x (λ w, @quotient.mk _ (ker $ quot.map_right h) $ @quotient.mk _ r w) $ λ x y H, quotient.sound' $ show @quot.mk _ _ _ = @quot.mk _ _ _, from quotient.sound H, left_inv := λ x, quotient.induction_on' x $ λ y, quotient.induction_on' y $ λ w, by show ⟦_⟧ = _; refl, right_inv := λ x, quotient.induction_on' x $ λ y, by show ⟦_⟧ = _; refl } variables {r f} open quotient /-- Given an equivalence relation r on α, the order-preserving bijection between the set of equivalence relations containing r and the equivalence relations on the quotient of α by r. -/ def correspondence (r : setoid α) : ((≤) : {s // r ≤ s} → {s // r ≤ s} → Prop) ≃o ((≤) : setoid (quotient r) → setoid (quotient r) → Prop) := { to_fun := λ s, map_of_surjective s.1 quotient.mk ((ker_mk_eq r).symm ▸ s.2) exists_rep, inv_fun := λ s, ⟨comap quotient.mk s, λ x y h, show s.rel ⟦x⟧ ⟦y⟧, by rw eq_rel.2 h⟩, left_inv := λ s, subtype.ext_iff_val.2 $ ext' $ λ _ _, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in s.1.trans' (s.1.symm' $ s.2 $ eq_rel.1 hx) $ s.1.trans' H $ s.2 $ eq_rel.1 hy, λ h, ⟨_, _, rfl, rfl, h⟩⟩, right_inv := λ s, let Hm : ker quotient.mk ≤ comap quotient.mk s := λ x y h, show s.rel ⟦x⟧ ⟦y⟧, by rw (@eq_rel _ r x y).2 ((ker_mk_eq r) ▸ h) in ext' $ λ x y, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in hx ▸ hy ▸ H, quotient.induction_on₂ x y $ λ w z h, ⟨w, z, rfl, rfl, h⟩⟩, ord' := λ s t, ⟨λ h x y hs, let ⟨a, b, hx, hy, Hs⟩ := hs in ⟨a, b, hx, hy, h Hs⟩, λ h x y hs, let ⟨a, b, hx, hy, ht⟩ := h ⟨x, y, rfl, rfl, hs⟩ in t.1.trans' (t.1.symm' $ t.2 $ eq_rel.1 hx) $ t.1.trans' ht $ t.2 $ eq_rel.1 hy⟩ } end setoid
7a43e072b7d1f751b572c5aba73e0bd1cf136d72
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/linear_algebra/tensor_product_basis.lean
1f4e5cb7113f5dd69bb979bfb857407852ad189e
[ "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
1,582
lean
/- Copyright (c) 2021 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jakob von Raumer -/ import linear_algebra.finsupp_vector_space /-! # Bases and dimensionality of tensor products of modules These can not go into `linear_algebra.tensor_product` since they depend on `linear_algebra.finsupp_vector_space` which in turn imports `linear_algebra.tensor_product`. -/ noncomputable theory open set linear_map submodule section comm_ring variables {R : Type*} {M : Type*} {N : Type*} {ι : Type*} {κ : Type*} variables [comm_ring R] [add_comm_group M] [module R M] [add_comm_group N] [module R N] /-- If b : ι → M and c : κ → N are bases then so is λ i, b i.1 ⊗ₜ c i.2 : ι × κ → M ⊗ N. -/ def basis.tensor_product (b : basis ι R M) (c : basis κ R N) : basis (ι × κ) R (tensor_product R M N) := finsupp.basis_single_one.map ((tensor_product.congr b.repr c.repr).trans $ (finsupp_tensor_finsupp R _ _ _ _).trans $ finsupp.lcongr (equiv.refl _) (tensor_product.lid R R)).symm end comm_ring section field variables {K : Type*} (V W : Type*) variables [field K] [add_comm_group V] [module K V] [add_comm_group W] [module K W] /-- If `V` and `W` are finite dimensional `K` vector spaces, so is `V ⊗ W`. -/ instance finite_dimensional_tensor_product [finite_dimensional K V] [finite_dimensional K W] : finite_dimensional K (tensor_product K V W) := finite_dimensional.of_fintype_basis (basis.tensor_product (basis.of_vector_space K V) (basis.of_vector_space K W)) end field
1498f65552fb8e8b83f31a43518e49aad47a766b
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch5/ex0111.lean
a35f71d132ea33744519a4e2cc6df3cb51b3a424
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
151
lean
variables {p q : Prop} (hp : p) (hq : q) example : p ∧ q ∧ p := let hp := hp, hq := hq in begin apply and.intro hp, exact and.intro hq hp end
808a1e1d24405aee8dfe7554408fa449cff6f2b5
217bb195841a8be2d1b4edd2084d6b69ccd62f50
/library/init/data/int/basic.lean
7b3fe0c36e6b66a30aab77500650945c98f6d0dd
[ "Apache-2.0" ]
permissive
frank-lesser/lean4
717f56c9bacd5bf3a67542d2f5cea721d4743a30
79e2abe33f73162f773ea731265e456dbfe822f9
refs/heads/master
1,589,741,267,933
1,556,424,200,000
1,556,424,281,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,452
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura The integers, with addition, multiplication, and subtraction. -/ prelude import init.data.nat.basic init.data.list init.coe init.data.repr init.data.tostring open Nat /- the Type, coercions, and notation -/ inductive Int : Type | ofNat : Nat → Int | negSucc : Nat → Int attribute [extern cpp "lean::nat2int"] Int.ofNat attribute [extern cpp "lean::int_neg_succ_of_nat"] Int.negSucc instance : HasCoe Nat Int := ⟨Int.ofNat⟩ namespace Int protected def zero : Int := ofNat 0 protected def one : Int := ofNat 1 instance : HasZero Int := ⟨Int.zero⟩ instance : HasOne Int := ⟨Int.one⟩ def negOfNat : Nat → Int | 0 := 0 | (succ m) := negSucc m @[extern cpp "lean::int_neg"] protected def neg (n : @& Int) : Int := match n with | ofNat n := negOfNat n | negSucc n := succ n def subNatNat (m n : Nat) : Int := match (n - m : Nat) with | 0 := ofNat (m - n) -- m ≥ n | (succ k) := negSucc k @[extern cpp "lean::int_add"] protected def add (m n : @& Int) : Int := match m, n with | ofNat m, ofNat n := ofNat (m + n) | ofNat m, negSucc n := subNatNat m (succ n) | negSucc m, ofNat n := subNatNat n (succ m) | negSucc m, negSucc n := negSucc (m + n) @[extern cpp "lean::int_mul"] protected def mul (m n : @& Int) : Int := match m, n with | ofNat m, ofNat n := ofNat (m * n) | ofNat m, negSucc n := negOfNat (m * succ n) | negSucc m, ofNat n := negOfNat (succ m * n) | negSucc m, negSucc n := ofNat (succ m * succ n) instance : HasNeg Int := ⟨Int.neg⟩ instance : HasAdd Int := ⟨Int.add⟩ instance : HasMul Int := ⟨Int.mul⟩ @[extern cpp "lean::int_sub"] protected def sub (m n : @& Int) : Int := m + -n instance : HasSub Int := ⟨Int.sub⟩ inductive NonNeg : Int → Prop | mk (n : Nat) : NonNeg (ofNat n) protected def LessEq (a b : Int) : Prop := NonNeg (b - a) instance : HasLessEq Int := ⟨Int.LessEq⟩ protected def Less (a b : Int) : Prop := (a + 1) ≤ b instance : HasLess Int := ⟨Int.Less⟩ @[extern cpp "lean::int_dec_eq"] protected def decEq (a b : @& Int) : Decidable (a = b) := match a, b with | ofNat a, ofNat b := (match decEq a b with | isTrue h := isTrue $ h ▸ rfl | isFalse h := isFalse $ λ h', Int.noConfusion h' (λ h', absurd h' h)) | negSucc a, negSucc b := (match decEq a b with | isTrue h := isTrue $ h ▸ rfl | isFalse h := isFalse $ λ h', Int.noConfusion h' (λ h', absurd h' h)) | ofNat a, negSucc b := isFalse $ λ h, Int.noConfusion h | negSucc a, ofNat b := isFalse $ λ h, Int.noConfusion h instance Int.DecidableEq : DecidableEq Int := {decEq := Int.decEq} @[extern cpp "lean::int_dec_nonneg"] private def decNonneg (m : @& Int) : Decidable (NonNeg m) := match m with | ofNat m := isTrue $ NonNeg.mk m | negSucc m := isFalse $ λ h, match h with end @[extern cpp "lean::int_dec_le"] instance decLe (a b : @& Int) : Decidable (a ≤ b) := decNonneg _ @[extern cpp "lean::int_dec_lt"] instance decLt (a b : @& Int) : Decidable (a < b) := decNonneg _ @[extern cpp "lean::nat_abs"] def natAbs (m : @& Int) : Nat := match m with | ofNat m := m | negSucc m := m.succ protected def repr : Int → String | (ofNat m) := Nat.repr m | (negSucc m) := "-" ++ Nat.repr (succ m) instance : HasRepr Int := ⟨Int.repr⟩ instance : HasToString Int := ⟨Int.repr⟩ @[extern cpp "lean::int_div"] def div : (@& Int) → (@& Int) → Int | (ofNat m) (ofNat n) := ofNat (m / n) | (ofNat m) (negSucc n) := -ofNat (m / succ n) | (negSucc m) (ofNat n) := -ofNat (succ m / n) | (negSucc m) (negSucc n) := ofNat (succ m / succ n) @[extern cpp "lean::int_mod"] def mod : (@& Int) → (@& Int) → Int | (ofNat m) (ofNat n) := ofNat (m % n) | (ofNat m) (negSucc n) := ofNat (m % succ n) | (negSucc m) (ofNat n) := -ofNat (succ m % n) | (negSucc m) (negSucc n) := -ofNat (succ m % succ n) instance : HasDiv Int := ⟨Int.div⟩ instance : HasMod Int := ⟨Int.mod⟩ def toNat : Int → Nat | (ofNat n) := n | (negSucc n) := 0 def natMod (m n : Int) : Nat := (m % n).toNat end Int namespace String def toInt (s : String) : Int := if s.get 0 = '-' then - Int.ofNat (s.toSubstring.drop 1).toNat else Int.ofNat s.toNat def isInt (s : String) : Bool := if s.get 0 = '-' then (s.toSubstring.drop 1).isNat else s.isNat end String
48f29e0e7e9ce19b527214b128949e249acf0b91
08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4
/src/Lean/Elab/Term.lean
f03a9dd810f49c998fcb13eba74450fe2953e36c
[ "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", "Apache-2.0", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
gebner/lean4
d51c4922640a52a6f7426536ea669ef18a1d9af5
8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f
refs/heads/master
1,685,732,780,391
1,672,962,627,000
1,673,459,398,000
373,307,283
0
0
Apache-2.0
1,691,316,730,000
1,622,669,271,000
Lean
UTF-8
Lean
false
false
74,920
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Meta.AppBuilder import Lean.Meta.CollectMVars import Lean.Meta.Coe import Lean.Linter.Deprecated import Lean.Elab.Config import Lean.Elab.Level import Lean.Elab.DeclModifiers namespace Lean.Elab namespace Term /-- Saved context for postponed terms and tactics to be executed. -/ structure SavedContext where declName? : Option Name options : Options openDecls : List OpenDecl macroStack : MacroStack errToSorry : Bool levelNames : List Name /-- We use synthetic metavariables as placeholders for pending elaboration steps. -/ inductive SyntheticMVarKind where /-- Use typeclass resolution to synthesize value for metavariable. -/ | typeClass /-- Use coercion to synthesize value for the metavariable. if `f?` is `some f`, we produce an application type mismatch error message. Otherwise, if `header?` is `some header`, we generate the error `(header ++ "has type" ++ eType ++ "but it is expected to have type" ++ expectedType)` Otherwise, we generate the error `("type mismatch" ++ e ++ "has type" ++ eType ++ "but it is expected to have type" ++ expectedType)` -/ | coe (header? : Option String) (expectedType : Expr) (e : Expr) (f? : Option Expr) /-- Use tactic to synthesize value for metavariable. -/ | tactic (tacticCode : Syntax) (ctx : SavedContext) /-- Metavariable represents a hole whose elaboration has been postponed. -/ | postponed (ctx : SavedContext) deriving Inhabited instance : ToString SyntheticMVarKind where toString | .typeClass => "typeclass" | .coe .. => "coe" | .tactic .. => "tactic" | .postponed .. => "postponed" structure SyntheticMVarDecl where stx : Syntax kind : SyntheticMVarKind deriving Inhabited /-- We can optionally associate an error context with a metavariable (see `MVarErrorInfo`). We have three different kinds of error context. -/ inductive MVarErrorKind where /-- Metavariable for implicit arguments. `ctx` is the parent application. -/ | implicitArg (ctx : Expr) /-- Metavariable for explicit holes provided by the user (e.g., `_` and `?m`) -/ | hole /-- "Custom", `msgData` stores the additional error messages. -/ | custom (msgData : MessageData) deriving Inhabited instance : ToString MVarErrorKind where toString | .implicitArg _ => "implicitArg" | .hole => "hole" | .custom _ => "custom" /-- We can optionally associate an error context with metavariables. -/ structure MVarErrorInfo where mvarId : MVarId ref : Syntax kind : MVarErrorKind argName? : Option Name := none deriving Inhabited /-- Nested `let rec` expressions are eagerly lifted by the elaborator. We store the information necessary for performing the lifting here. -/ structure LetRecToLift where ref : Syntax fvarId : FVarId attrs : Array Attribute shortDeclName : Name declName : Name lctx : LocalContext localInstances : LocalInstances type : Expr val : Expr mvarId : MVarId deriving Inhabited /-- State of the `TermElabM` monad. -/ structure State where levelNames : List Name := [] syntheticMVars : MVarIdMap SyntheticMVarDecl := {} pendingMVars : List MVarId := {} mvarErrorInfos : MVarIdMap MVarErrorInfo := {} letRecsToLift : List LetRecToLift := [] deriving Inhabited end Term namespace Tactic /-- State of the `TacticM` monad. -/ structure State where goals : List MVarId deriving Inhabited /-- Snapshots are used to implement the `save` tactic. This tactic caches the state of the system, and allows us to "replay" expensive proofs efficiently. This is only relevant implementing the LSP server. -/ structure Snapshot where core : Core.State meta : Meta.State term : Term.State tactic : Tactic.State stx : Syntax /-- Key for the cache used to implement the `save` tactic. -/ structure CacheKey where mvarId : MVarId -- TODO: should include all goals pos : String.Pos deriving BEq, Hashable, Inhabited /-- Cache for the `save` tactic. -/ structure Cache where pre : PHashMap CacheKey Snapshot := {} post : PHashMap CacheKey Snapshot := {} deriving Inhabited end Tactic namespace Term structure Context where declName? : Option Name := none /-- Map `.auxDecl` local declarations used to encode recursive declarations to their full-names. -/ auxDeclToFullName : FVarIdMap Name := {} macroStack : MacroStack := [] /-- When `mayPostpone == true`, an elaboration function may interrupt its execution by throwing `Exception.postpone`. The function `elabTerm` catches this exception and creates fresh synthetic metavariable `?m`, stores `?m` in the list of pending synthetic metavariables, and returns `?m`. -/ mayPostpone : Bool := true /-- When `errToSorry` is set to true, the method `elabTerm` catches exceptions and converts them into synthetic `sorry`s. The implementation of choice nodes and overloaded symbols rely on the fact that when `errToSorry` is set to false for an elaboration function `F`, then `errToSorry` remains `false` for all elaboration functions invoked by `F`. That is, it is safe to transition `errToSorry` from `true` to `false`, but we must not set `errToSorry` to `true` when it is currently set to `false`. -/ errToSorry : Bool := true /-- When `autoBoundImplicit` is set to true, instead of producing an "unknown identifier" error for unbound variables, we generate an internal exception. This exception is caught at `elabBinders` and `elabTypeWithUnboldImplicit`. Both methods add implicit declarations for the unbound variable and try again. -/ autoBoundImplicit : Bool := false autoBoundImplicits : PArray Expr := {} /-- A name `n` is only eligible to be an auto implicit name if `autoBoundImplicitForbidden n = false`. We use this predicate to disallow `f` to be considered an auto implicit name in a definition such as ``` def f : f → Bool := fun _ => true ``` -/ autoBoundImplicitForbidden : Name → Bool := fun _ => false /-- Map from user name to internal unique name -/ sectionVars : NameMap Name := {} /-- Map from internal name to fvar -/ sectionFVars : NameMap Expr := {} /-- Enable/disable implicit lambdas feature. -/ implicitLambda : Bool := true /-- Noncomputable sections automatically add the `noncomputable` modifier to any declaration we cannot generate code for -/ isNoncomputableSection : Bool := false /-- When `true` we skip TC failures. We use this option when processing patterns -/ ignoreTCFailures : Bool := false /-- `true` when elaborating patterns. It affects how we elaborate named holes. -/ inPattern : Bool := false /-- Cache for the `save` tactic. It is only `some` in the LSP server. -/ tacticCache? : Option (IO.Ref Tactic.Cache) := none /-- If `true`, we store in the `Expr` the `Syntax` for recursive applications (i.e., applications of free variables tagged with `isAuxDecl`). We store the `Syntax` using `mkRecAppWithSyntax`. We use the `Syntax` object to produce better error messages at `Structural.lean` and `WF.lean`. -/ saveRecAppSyntax : Bool := true /-- If `holesAsSyntheticOpaque` is `true`, then we mark metavariables associated with `_`s as `synthethicOpaque` if they do not occur in patterns. This option is useful when elaborating terms in tactics such as `refine'` where we want holes there to become new goals. See issue #1681, we have `refine' (fun x => _) -/ holesAsSyntheticOpaque : Bool := false abbrev TermElabM := ReaderT Context $ StateRefT State MetaM abbrev TermElab := Syntax → Option Expr → TermElabM Expr /- Make the compiler generate specialized `pure`/`bind` so we do not have to optimize through the whole monad stack at every use site. May eventually be covered by `deriving`. -/ @[always_inline] instance : Monad TermElabM := let i := inferInstanceAs (Monad TermElabM) { pure := i.pure, bind := i.bind } open Meta instance : Inhabited (TermElabM α) where default := throw default /-- Backtrackable state for the `TermElabM` monad. -/ structure SavedState where meta : Meta.SavedState «elab» : State deriving Nonempty protected def saveState : TermElabM SavedState := return { meta := (← Meta.saveState), «elab» := (← get) } def SavedState.restore (s : SavedState) (restoreInfo : Bool := false) : TermElabM Unit := do let traceState ← getTraceState -- We never backtrack trace message let infoState ← getInfoState -- We also do not backtrack the info nodes when `restoreInfo == false` s.meta.restore set s.elab setTraceState traceState unless restoreInfo do setInfoState infoState instance : MonadBacktrack SavedState TermElabM where saveState := Term.saveState restoreState b := b.restore abbrev TermElabResult (α : Type) := EStateM.Result Exception SavedState α /-- Execute `x`, save resulting expression and new state. We remove any `Info` created by `x`. The info nodes are committed when we execute `applyResult`. We use `observing` to implement overloaded notation and decls. We want to save `Info` nodes for the chosen alternative. -/ def observing (x : TermElabM α) : TermElabM (TermElabResult α) := do let s ← saveState try let e ← x let sNew ← saveState s.restore (restoreInfo := true) return EStateM.Result.ok e sNew catch | ex@(.error ..) => let sNew ← saveState s.restore (restoreInfo := true) return .error ex sNew | ex@(.internal id _) => if id == postponeExceptionId then s.restore (restoreInfo := true) throw ex /-- Apply the result/exception and state captured with `observing`. We use this method to implement overloaded notation and symbols. -/ def applyResult (result : TermElabResult α) : TermElabM α := do match result with | .ok a r => r.restore (restoreInfo := true); return a | .error ex r => r.restore (restoreInfo := true); throw ex /-- Execute `x`, but keep state modifications only if `x` did not postpone. This method is useful to implement elaboration functions that cannot decide whether they need to postpone or not without updating the state. -/ def commitIfDidNotPostpone (x : TermElabM α) : TermElabM α := do -- We just reuse the implementation of `observing` and `applyResult`. let r ← observing x applyResult r /-- Return the universe level names explicitly provided by the user. -/ def getLevelNames : TermElabM (List Name) := return (← get).levelNames /-- Given a free variable `fvar`, return its declaration. This function panics if `fvar` is not a free variable. -/ def getFVarLocalDecl! (fvar : Expr) : TermElabM LocalDecl := do match (← getLCtx).find? fvar.fvarId! with | some d => pure d | none => unreachable! instance : AddErrorMessageContext TermElabM where add ref msg := do let ctx ← read let ref := getBetterRef ref ctx.macroStack let msg ← addMessageContext msg let msg ← addMacroStack msg ctx.macroStack pure (ref, msg) /-- Execute `x` but discard changes performed at `Term.State` and `Meta.State`. Recall that the `Environment` and `InfoState` are at `Core.State`. Thus, any updates to it will be preserved. This method is useful for performing computations where all metavariable must be resolved or discarded. The `InfoTree`s are not discarded, however, and wrapped in `InfoTree.Context` to store their metavariable context. -/ def withoutModifyingElabMetaStateWithInfo (x : TermElabM α) : TermElabM α := do let s ← get let sMeta ← getThe Meta.State try withSaveInfoContext x finally set s set sMeta /-- Execute `x` but discard changes performed to the state. However, the info trees and messages are not discarded. -/ private def withoutModifyingStateWithInfoAndMessagesImpl (x : TermElabM α) : TermElabM α := do let saved ← saveState try withSaveInfoContext x finally let saved := { saved with meta.core.infoState := (← getInfoState), meta.core.messages := (← getThe Core.State).messages } restoreState saved /-- Execute `x` without storing `Syntax` for recursive applications. See `saveRecAppSyntax` field at `Context`. -/ def withoutSavingRecAppSyntax (x : TermElabM α) : TermElabM α := withReader (fun ctx => { ctx with saveRecAppSyntax := false }) x unsafe def mkTermElabAttributeUnsafe (ref : Name) : IO (KeyedDeclsAttribute TermElab) := mkElabAttribute TermElab `builtin_term_elab `term_elab `Lean.Parser.Term `Lean.Elab.Term.TermElab "term" ref @[implemented_by mkTermElabAttributeUnsafe] opaque mkTermElabAttribute (ref : Name) : IO (KeyedDeclsAttribute TermElab) builtin_initialize termElabAttribute : KeyedDeclsAttribute TermElab ← mkTermElabAttribute decl_name% /-- Auxiliary datatatype for presenting a Lean lvalue modifier. We represent a unelaborated lvalue as a `Syntax` (or `Expr`) and `List LVal`. Example: `a.foo.1` is represented as the `Syntax` `a` and the list `[LVal.fieldName "foo", LVal.fieldIdx 1]`. -/ inductive LVal where | fieldIdx (ref : Syntax) (i : Nat) /-- Field `suffix?` is for producing better error messages because `x.y` may be a field access or a hierachical/composite name. `ref` is the syntax object representing the field. `targetStx` is the target object being accessed. -/ | fieldName (ref : Syntax) (name : String) (suffix? : Option Name) (targetStx : Syntax) def LVal.getRef : LVal → Syntax | .fieldIdx ref _ => ref | .fieldName ref .. => ref def LVal.isFieldName : LVal → Bool | .fieldName .. => true | _ => false instance : ToString LVal where toString | .fieldIdx _ i => toString i | .fieldName _ n .. => n /-- Return the name of the declaration being elaborated if available. -/ def getDeclName? : TermElabM (Option Name) := return (← read).declName? /-- Return the list of nested `let rec` declarations that need to be lifted. -/ def getLetRecsToLift : TermElabM (List LetRecToLift) := return (← get).letRecsToLift /-- Return the declaration of the given metavariable -/ def getMVarDecl (mvarId : MVarId) : TermElabM MetavarDecl := return (← getMCtx).getDecl mvarId /-- Execute `x` with `declName? := name`. See `getDeclName? -/ def withDeclName (name : Name) (x : TermElabM α) : TermElabM α := withReader (fun ctx => { ctx with declName? := name }) x /-- Update the universe level parameter names. -/ def setLevelNames (levelNames : List Name) : TermElabM Unit := modify fun s => { s with levelNames := levelNames } /-- Execute `x` using `levelNames` as the universe level parameter names. See `getLevelNames`. -/ def withLevelNames (levelNames : List Name) (x : TermElabM α) : TermElabM α := do let levelNamesSaved ← getLevelNames setLevelNames levelNames try x finally setLevelNames levelNamesSaved /-- Declare an auxiliary local declaration `shortDeclName : type` for elaborating recursive declaration `declName`, update the mapping `auxDeclToFullName`, and then execute `k`. -/ def withAuxDecl (shortDeclName : Name) (type : Expr) (declName : Name) (k : Expr → TermElabM α) : TermElabM α := withLocalDecl shortDeclName .default (kind := .auxDecl) type fun x => withReader (fun ctx => { ctx with auxDeclToFullName := ctx.auxDeclToFullName.insert x.fvarId! declName }) do k x def withoutErrToSorryImp (x : TermElabM α) : TermElabM α := withReader (fun ctx => { ctx with errToSorry := false }) x /-- Execute `x` without converting errors (i.e., exceptions) to `sorry` applications. Recall that when `errToSorry = true`, the method `elabTerm` catches exceptions and convert them into `sorry` applications. -/ def withoutErrToSorry [MonadFunctorT TermElabM m] : m α → m α := monadMap (m := TermElabM) withoutErrToSorryImp /-- For testing `TermElabM` methods. The #eval command will sign the error. -/ def throwErrorIfErrors : TermElabM Unit := do if (← MonadLog.hasErrors) then throwError "Error(s)" def traceAtCmdPos (cls : Name) (msg : Unit → MessageData) : TermElabM Unit := withRef Syntax.missing <| trace cls msg def ppGoal (mvarId : MVarId) : TermElabM Format := Meta.ppGoal mvarId open Level (LevelElabM) def liftLevelM (x : LevelElabM α) : TermElabM α := do let ctx ← read let mctx ← getMCtx let ngen ← getNGen let lvlCtx : Level.Context := { options := (← getOptions), ref := (← getRef), autoBoundImplicit := ctx.autoBoundImplicit } match (x lvlCtx).run { ngen := ngen, mctx := mctx, levelNames := (← getLevelNames) } with | .ok a newS => setMCtx newS.mctx; setNGen newS.ngen; setLevelNames newS.levelNames; pure a | .error ex _ => throw ex def elabLevel (stx : Syntax) : TermElabM Level := liftLevelM <| Level.elabLevel stx /-- Elaborate `x` with `stx` on the macro stack -/ def withMacroExpansion (beforeStx afterStx : Syntax) (x : TermElabM α) : TermElabM α := withMacroExpansionInfo beforeStx afterStx do withReader (fun ctx => { ctx with macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack }) x /-- Add the given metavariable to the list of pending synthetic metavariables. The method `synthesizeSyntheticMVars` is used to process the metavariables on this list. -/ def registerSyntheticMVar (stx : Syntax) (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := do modify fun s => { s with syntheticMVars := s.syntheticMVars.insert mvarId { stx, kind }, pendingMVars := mvarId :: s.pendingMVars } def registerSyntheticMVarWithCurrRef (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := do registerSyntheticMVar (← getRef) mvarId kind def registerMVarErrorInfo (mvarErrorInfo : MVarErrorInfo) : TermElabM Unit := modify fun s => { s with mvarErrorInfos := s.mvarErrorInfos.insert mvarErrorInfo.mvarId mvarErrorInfo } def registerMVarErrorHoleInfo (mvarId : MVarId) (ref : Syntax) : TermElabM Unit := registerMVarErrorInfo { mvarId, ref, kind := .hole } def registerMVarErrorImplicitArgInfo (mvarId : MVarId) (ref : Syntax) (app : Expr) : TermElabM Unit := do registerMVarErrorInfo { mvarId, ref, kind := .implicitArg app } def registerMVarErrorCustomInfo (mvarId : MVarId) (ref : Syntax) (msgData : MessageData) : TermElabM Unit := do registerMVarErrorInfo { mvarId, ref, kind := .custom msgData } def getMVarErrorInfo? (mvarId : MVarId) : TermElabM (Option MVarErrorInfo) := do return (← get).mvarErrorInfos.find? mvarId def registerCustomErrorIfMVar (e : Expr) (ref : Syntax) (msgData : MessageData) : TermElabM Unit := match e.getAppFn with | Expr.mvar mvarId => registerMVarErrorCustomInfo mvarId ref msgData | _ => pure () /-- Auxiliary method for reporting errors of the form "... contains metavariables ...". This kind of error is thrown, for example, at `Match.lean` where elaboration cannot continue if there are metavariables in patterns. We only want to log it if we haven't logged any error so far. -/ def throwMVarError (m : MessageData) : TermElabM α := do if (← MonadLog.hasErrors) then throwAbortTerm else throwError m def MVarErrorInfo.logError (mvarErrorInfo : MVarErrorInfo) (extraMsg? : Option MessageData) : TermElabM Unit := do match mvarErrorInfo.kind with | MVarErrorKind.implicitArg app => do let app ← instantiateMVars app let msg := addArgName "don't know how to synthesize implicit argument" let msg := msg ++ m!"{indentExpr app.setAppPPExplicitForExposingMVars}" ++ Format.line ++ "context:" ++ Format.line ++ MessageData.ofGoal mvarErrorInfo.mvarId logErrorAt mvarErrorInfo.ref (appendExtra msg) | MVarErrorKind.hole => do let msg := addArgName "don't know how to synthesize placeholder" " for argument" let msg := msg ++ Format.line ++ "context:" ++ Format.line ++ MessageData.ofGoal mvarErrorInfo.mvarId logErrorAt mvarErrorInfo.ref (MessageData.tagged `Elab.synthPlaceholder <| appendExtra msg) | MVarErrorKind.custom msg => logErrorAt mvarErrorInfo.ref (appendExtra msg) where /-- Append `mvarErrorInfo` argument name (if available) to the message. Remark: if the argument name contains macro scopes we do not append it. -/ addArgName (msg : MessageData) (extra : String := "") : MessageData := match mvarErrorInfo.argName? with | none => msg | some argName => if argName.hasMacroScopes then msg else msg ++ extra ++ m!" '{argName}'" appendExtra (msg : MessageData) : MessageData := match extraMsg? with | none => msg | some extraMsg => msg ++ extraMsg /-- Try to log errors for the unassigned metavariables `pendingMVarIds`. Return `true` if there were "unfilled holes", and we should "abort" declaration. TODO: try to fill "all" holes using synthetic "sorry's" Remark: We only log the "unfilled holes" as new errors if no error has been logged so far. -/ def logUnassignedUsingErrorInfos (pendingMVarIds : Array MVarId) (extraMsg? : Option MessageData := none) : TermElabM Bool := do if pendingMVarIds.isEmpty then return false else let hasOtherErrors ← MonadLog.hasErrors let mut hasNewErrors := false let mut alreadyVisited : MVarIdSet := {} let mut errors : Array MVarErrorInfo := #[] for (_, mvarErrorInfo) in (← get).mvarErrorInfos do let mvarId := mvarErrorInfo.mvarId unless alreadyVisited.contains mvarId do alreadyVisited := alreadyVisited.insert mvarId /- The metavariable `mvarErrorInfo.mvarId` may have been assigned or delayed assigned to another metavariable that is unassigned. -/ let mvarDeps ← getMVars (mkMVar mvarId) if mvarDeps.any pendingMVarIds.contains then do unless hasOtherErrors do errors := errors.push mvarErrorInfo hasNewErrors := true -- To sort the errors by position use -- let sortedErrors := errors.qsort fun e₁ e₂ => e₁.ref.getPos?.getD 0 < e₂.ref.getPos?.getD 0 for error in errors do error.mvarId.withContext do error.logError extraMsg? return hasNewErrors /-- Ensure metavariables registered using `registerMVarErrorInfos` (and used in the given declaration) have been assigned. -/ def ensureNoUnassignedMVars (decl : Declaration) : TermElabM Unit := do let pendingMVarIds ← getMVarsAtDecl decl if (← logUnassignedUsingErrorInfos pendingMVarIds) then throwAbortCommand /-- Execute `x` without allowing it to postpone elaboration tasks. That is, `tryPostpone` is a noop. -/ def withoutPostponing (x : TermElabM α) : TermElabM α := withReader (fun ctx => { ctx with mayPostpone := false }) x /-- Creates syntax for `(` <ident> `:` <type> `)` -/ def mkExplicitBinder (ident : Syntax) (type : Syntax) : Syntax := mkNode ``Lean.Parser.Term.explicitBinder #[mkAtom "(", mkNullNode #[ident], mkNullNode #[mkAtom ":", type], mkNullNode, mkAtom ")"] /-- Convert unassigned universe level metavariables into parameters. The new parameter names are fresh names of the form `u_i` with regard to `ctx.levelNames`, which is updated with the new names. -/ def levelMVarToParam (e : Expr) (except : LMVarId → Bool := fun _ => false) : TermElabM Expr := do let levelNames ← getLevelNames let r := (← getMCtx).levelMVarToParam (fun n => levelNames.elem n) except e `u 1 setLevelNames (levelNames ++ r.newParamNames.toList) setMCtx r.mctx return r.expr /-- Auxiliary method for creating fresh binder names. Do not confuse with the method for creating fresh free/meta variable ids. -/ def mkFreshBinderName [Monad m] [MonadQuotation m] : m Name := withFreshMacroScope <| MonadQuotation.addMacroScope `x /-- Auxiliary method for creating a `Syntax.ident` containing a fresh name. This method is intended for creating fresh binder names. It is just a thin layer on top of `mkFreshUserName`. -/ def mkFreshIdent [Monad m] [MonadQuotation m] (ref : Syntax) (canonical := false) : m Ident := return mkIdentFrom ref (← mkFreshBinderName) canonical private def applyAttributesCore (declName : Name) (attrs : Array Attribute) (applicationTime? : Option AttributeApplicationTime) : TermElabM Unit := for attr in attrs do withRef attr.stx do withLogging do let env ← getEnv match getAttributeImpl env attr.name with | Except.error errMsg => throwError errMsg | Except.ok attrImpl => let runAttr := attrImpl.add declName attr.stx attr.kind let runAttr := do -- not truly an elaborator, but a sensible target for go-to-definition let elaborator := attrImpl.ref if (← getInfoState).enabled && (← getEnv).contains elaborator then withInfoContext (mkInfo := return .ofCommandInfo { elaborator, stx := attr.stx }) do try runAttr finally if attr.stx[0].isIdent || attr.stx[0].isAtom then -- Add an additional node over the leading identifier if there is one to make it look more function-like. -- Do this last because we want user-created infos to take precedence pushInfoLeaf <| .ofCommandInfo { elaborator, stx := attr.stx[0] } else runAttr match applicationTime? with | none => runAttr | some applicationTime => if applicationTime == attrImpl.applicationTime then runAttr /-- Apply given attributes **at** a given application time -/ def applyAttributesAt (declName : Name) (attrs : Array Attribute) (applicationTime : AttributeApplicationTime) : TermElabM Unit := applyAttributesCore declName attrs applicationTime def applyAttributes (declName : Name) (attrs : Array Attribute) : TermElabM Unit := applyAttributesCore declName attrs none def mkTypeMismatchError (header? : Option String) (e : Expr) (eType : Expr) (expectedType : Expr) : TermElabM MessageData := do let header : MessageData := match header? with | some header => m!"{header} " | none => m!"type mismatch{indentExpr e}\n" return m!"{header}{← mkHasTypeButIsExpectedMsg eType expectedType}" def throwTypeMismatchError (header? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr := none) (extraMsg? : Option MessageData := none) : TermElabM α := do /- We ignore `extraMsg?` for now. In all our tests, it contained no useful information. It was always of the form: ``` failed to synthesize instance CoeT <eType> <e> <expectedType> ``` We should revisit this decision in the future and decide whether it may contain useful information or not. -/ let extraMsg := Format.nil /- let extraMsg : MessageData := match extraMsg? with | none => Format.nil | some extraMsg => Format.line ++ extraMsg; -/ match f? with | none => throwError "{← mkTypeMismatchError header? e eType expectedType}{extraMsg}" | some f => Meta.throwAppTypeMismatch f e def withoutMacroStackAtErr (x : TermElabM α) : TermElabM α := withTheReader Core.Context (fun (ctx : Core.Context) => { ctx with options := pp.macroStack.set ctx.options false }) x namespace ContainsPendingMVar abbrev M := MonadCacheT Expr Unit (OptionT MetaM) /-- See `containsPostponedTerm` -/ partial def visit (e : Expr) : M Unit := do checkCache e fun _ => do match e with | .forallE _ d b _ => visit d; visit b | .lam _ d b _ => visit d; visit b | .letE _ t v b _ => visit t; visit v; visit b | .app f a => visit f; visit a | .mdata _ b => visit b | .proj _ _ b => visit b | .fvar fvarId .. => match (← fvarId.getDecl) with | .cdecl .. => return () | .ldecl (value := v) .. => visit v | .mvar mvarId .. => let e' ← instantiateMVars e if e' != e then visit e' else match (← getDelayedMVarAssignment? mvarId) with | some d => visit (mkMVar d.mvarIdPending) | none => failure | _ => return () end ContainsPendingMVar /-- Return `true` if `e` contains a pending metavariable. Remark: it also visits let-declarations. -/ def containsPendingMVar (e : Expr) : MetaM Bool := do match (← ContainsPendingMVar.visit e |>.run.run) with | some _ => return false | none => return true /-- Try to synthesize metavariable using type class resolution. This method assumes the local context and local instances of `instMVar` coincide with the current local context and local instances. Return `true` if the instance was synthesized successfully, and `false` if the instance contains unassigned metavariables that are blocking the type class resolution procedure. Throw an exception if resolution or assignment irrevocably fails. -/ def synthesizeInstMVarCore (instMVar : MVarId) (maxResultSize? : Option Nat := none) : TermElabM Bool := do let instMVarDecl ← getMVarDecl instMVar let type := instMVarDecl.type let type ← instantiateMVars type let result ← trySynthInstance type maxResultSize? match result with | LOption.some val => if (← instMVar.isAssigned) then let oldVal ← instantiateMVars (mkMVar instMVar) unless (← isDefEq oldVal val) do if (← containsPendingMVar oldVal <||> containsPendingMVar val) then /- If `val` or `oldVal` contains metavariables directly or indirectly (e.g., in a let-declaration), we return `false` to indicate we should try again later. This is very course grain since the metavariable may not be responsible for the failure. We should refine the test in the future if needed. This check has been added to address dependencies between postponed metavariables. The following example demonstrates the issue fixed by this test. ``` structure Point where x : Nat y : Nat def Point.compute (p : Point) : Point := let p := { p with x := 1 } let p := { p with y := 0 } if (p.x - p.y) > p.x then p else p ``` The `isDefEq` test above fails for `Decidable (p.x - p.y ≤ p.x)` when the structure instance assigned to `p` has not been elaborated yet. -/ return false -- we will try again later let oldValType ← inferType oldVal let valType ← inferType val unless (← isDefEq oldValType valType) do throwError "synthesized type class instance type is not definitionally equal to expected type, synthesized{indentExpr val}\nhas type{indentExpr valType}\nexpected{indentExpr oldValType}" throwError "synthesized type class instance is not definitionally equal to expression inferred by typing rules, synthesized{indentExpr val}\ninferred{indentExpr oldVal}" else unless (← isDefEq (mkMVar instMVar) val) do throwError "failed to assign synthesized type class instance{indentExpr val}" return true | .undef => return false -- we will try later | .none => if (← read).ignoreTCFailures then return false else throwError "failed to synthesize instance{indentExpr type}" def mkCoe (expectedType : Expr) (e : Expr) (f? : Option Expr := none) (errorMsgHeader? : Option String := none) : TermElabM Expr := do trace[Elab.coe] "adding coercion for {e} : {← inferType e} =?= {expectedType}" try withoutMacroStackAtErr do match ← coerce? e expectedType with | .some eNew => return eNew | .none => failure | .undef => let mvarAux ← mkFreshExprMVar expectedType MetavarKind.syntheticOpaque registerSyntheticMVarWithCurrRef mvarAux.mvarId! (.coe errorMsgHeader? expectedType e f?) return mvarAux catch | .error _ msg => throwTypeMismatchError errorMsgHeader? expectedType (← inferType e) e f? msg | _ => throwTypeMismatchError errorMsgHeader? expectedType (← inferType e) e f? /-- If `expectedType?` is `some t`, then ensure `t` and `eType` are definitionally equal. If they are not, then try coercions. Argument `f?` is used only for generating error messages. -/ def ensureHasType (expectedType? : Option Expr) (e : Expr) (errorMsgHeader? : Option String := none) (f? : Option Expr := none) : TermElabM Expr := do let some expectedType := expectedType? | return e if (← isDefEq (← inferType e) expectedType) then return e else mkCoe expectedType e f? errorMsgHeader? /-- Create a synthetic sorry for the given expected type. If `expectedType? = none`, then a fresh metavariable is created to represent the type. -/ private def mkSyntheticSorryFor (expectedType? : Option Expr) : TermElabM Expr := do let expectedType ← match expectedType? with | none => mkFreshTypeMVar | some expectedType => pure expectedType mkSyntheticSorry expectedType /-- Log the given exception, and create an synthetic sorry for representing the failed elaboration step with exception `ex`. -/ def exceptionToSorry (ex : Exception) (expectedType? : Option Expr) : TermElabM Expr := do let syntheticSorry ← mkSyntheticSorryFor expectedType? logException ex pure syntheticSorry /-- If `mayPostpone == true`, throw `Expection.postpone`. -/ def tryPostpone : TermElabM Unit := do if (← read).mayPostpone then throwPostpone /-- Return `true` if `e` reduces (by unfolding only `[reducible]` declarations) to `?m ...` -/ def isMVarApp (e : Expr) : TermElabM Bool := return (← whnfR e).getAppFn.isMVar /-- If `mayPostpone == true` and `e`'s head is a metavariable, throw `Exception.postpone`. -/ def tryPostponeIfMVar (e : Expr) : TermElabM Unit := do if (← isMVarApp e) then tryPostpone /-- If `e? = some e`, then `tryPostponeIfMVar e`, otherwise it is just `tryPostpone`. -/ def tryPostponeIfNoneOrMVar (e? : Option Expr) : TermElabM Unit := match e? with | some e => tryPostponeIfMVar e | none => tryPostpone /-- Throws `Exception.postpone`, if `expectedType?` contains unassigned metavariables. It is a noop if `mayPostpone == false`. -/ def tryPostponeIfHasMVars? (expectedType? : Option Expr) : TermElabM (Option Expr) := do tryPostponeIfNoneOrMVar expectedType? let some expectedType := expectedType? | return none let expectedType ← instantiateMVars expectedType if expectedType.hasExprMVar then tryPostpone return none return some expectedType /-- Throws `Exception.postpone`, if `expectedType?` contains unassigned metavariables. If `mayPostpone == false`, it throws error `msg`. -/ def tryPostponeIfHasMVars (expectedType? : Option Expr) (msg : String) : TermElabM Expr := do let some expectedType ← tryPostponeIfHasMVars? expectedType? | throwError "{msg}, expected type contains metavariables{indentD expectedType?}" return expectedType /-- Save relevant context for term elaboration postponement. -/ def saveContext : TermElabM SavedContext := return { macroStack := (← read).macroStack declName? := (← read).declName? options := (← getOptions) openDecls := (← getOpenDecls) errToSorry := (← read).errToSorry levelNames := (← get).levelNames } /-- Execute `x` with the context saved using `saveContext`. -/ def withSavedContext (savedCtx : SavedContext) (x : TermElabM α) : TermElabM α := do withReader (fun ctx => { ctx with declName? := savedCtx.declName?, macroStack := savedCtx.macroStack, errToSorry := savedCtx.errToSorry }) <| withTheReader Core.Context (fun ctx => { ctx with options := savedCtx.options, openDecls := savedCtx.openDecls }) <| withLevelNames savedCtx.levelNames x /-- Delay the elaboration of `stx`, and return a fresh metavariable that works a placeholder. Remark: the caller is responsible for making sure the info tree is properly updated. This method is used only at `elabUsingElabFnsAux`. -/ private def postponeElabTermCore (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do trace[Elab.postpone] "{stx} : {expectedType?}" let mvar ← mkFreshExprMVar expectedType? MetavarKind.syntheticOpaque registerSyntheticMVar stx mvar.mvarId! (SyntheticMVarKind.postponed (← saveContext)) return mvar def getSyntheticMVarDecl? (mvarId : MVarId) : TermElabM (Option SyntheticMVarDecl) := return (← get).syntheticMVars.find? mvarId /-- Create an auxiliary annotation to make sure we create a `Info` even if `e` is a metavariable. See `mkTermInfo`. We use this functions because some elaboration functions elaborate subterms that may not be immediately part of the resulting term. Example: ``` let_mvar% ?m := b; wait_if_type_mvar% ?m; body ``` If the type of `b` is not known, then `wait_if_type_mvar% ?m; body` is postponed and just return a fresh metavariable `?n`. The elaborator for ``` let_mvar% ?m := b; wait_if_type_mvar% ?m; body ``` returns `mkSaveInfoAnnotation ?n` to make sure the info nodes created when elaborating `b` are "saved". This is a bit hackish, but elaborators like `let_mvar%` are rare. -/ def mkSaveInfoAnnotation (e : Expr) : Expr := if e.isMVar then mkAnnotation `save_info e else e def isSaveInfoAnnotation? (e : Expr) : Option Expr := annotation? `save_info e partial def removeSaveInfoAnnotation (e : Expr) : Expr := match isSaveInfoAnnotation? e with | some e => removeSaveInfoAnnotation e | _ => e /-- Return `some mvarId` if `e` corresponds to a hole that is going to be filled "later" by executing a tactic or resuming elaboration. We do not save `ofTermInfo` for this kind of node in the `InfoTree`. -/ def isTacticOrPostponedHole? (e : Expr) : TermElabM (Option MVarId) := do match e with | Expr.mvar mvarId => match (← getSyntheticMVarDecl? mvarId) with | some { kind := .tactic .., .. } => return mvarId | some { kind := .postponed .., .. } => return mvarId | _ => return none | _ => pure none def mkTermInfo (elaborator : Name) (stx : Syntax) (e : Expr) (expectedType? : Option Expr := none) (lctx? : Option LocalContext := none) (isBinder := false) : TermElabM (Sum Info MVarId) := do match (← isTacticOrPostponedHole? e) with | some mvarId => return Sum.inr mvarId | none => let e := removeSaveInfoAnnotation e return Sum.inl <| Info.ofTermInfo { elaborator, lctx := lctx?.getD (← getLCtx), expr := e, stx, expectedType?, isBinder } /-- Pushes a new leaf node to the info tree associating the expression `e` to the syntax `stx`. As a result, when the user hovers over `stx` they will see the type of `e`, and if `e` is a constant they will see the constant's doc string. * `expectedType?`: the expected type of `e` at the point of elaboration, if available * `lctx?`: the local context in which to interpret `e` (otherwise it will use `← getLCtx`) * `elaborator`: a declaration name used as an alternative target for go-to-definition * `isBinder`: if true, this will be treated as defining `e` (which should be a local constant) for the purpose of go-to-definition on local variables * `force`: In patterns, the effect of `addTermInfo` is usually suppressed and replaced by a `patternWithRef?` annotation which will be turned into a term info on the post-match-elaboration expression. This flag overrides that behavior and adds the term info immediately. (See https://github.com/leanprover/lean4/pull/1664.) -/ def addTermInfo (stx : Syntax) (e : Expr) (expectedType? : Option Expr := none) (lctx? : Option LocalContext := none) (elaborator := Name.anonymous) (isBinder := false) (force := false) : TermElabM Expr := do if (← read).inPattern && !force then return mkPatternWithRef e stx else withInfoContext' (pure ()) (fun _ => mkTermInfo elaborator stx e expectedType? lctx? isBinder) |> discard return e def addTermInfo' (stx : Syntax) (e : Expr) (expectedType? : Option Expr := none) (lctx? : Option LocalContext := none) (elaborator := Name.anonymous) (isBinder := false) : TermElabM Unit := discard <| addTermInfo stx e expectedType? lctx? elaborator isBinder def withInfoContext' (stx : Syntax) (x : TermElabM Expr) (mkInfo : Expr → TermElabM (Sum Info MVarId)) : TermElabM Expr := do if (← read).inPattern then let e ← x return mkPatternWithRef e stx else Elab.withInfoContext' x mkInfo /-- Postpone the elaboration of `stx`, return a metavariable that acts as a placeholder, and ensures the info tree is updated and a hole id is introduced. When `stx` is elaborated, new info nodes are created and attached to the new hole id in the info tree. -/ def postponeElabTerm (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do withInfoContext' stx (mkInfo := mkTermInfo .anonymous (expectedType? := expectedType?) stx) do postponeElabTermCore stx expectedType? /-- Helper function for `elabTerm` is tries the registered elaboration functions for `stxNode` kind until it finds one that supports the syntax or an error is found. -/ private def elabUsingElabFnsAux (s : SavedState) (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool) : List (KeyedDeclsAttribute.AttributeEntry TermElab) → TermElabM Expr | [] => do throwError "unexpected syntax{indentD stx}" | (elabFn::elabFns) => try -- record elaborator in info tree, but only when not backtracking to other elaborators (outer `try`) withInfoContext' stx (mkInfo := mkTermInfo elabFn.declName (expectedType? := expectedType?) stx) (try elabFn.value stx expectedType? catch ex => match ex with | .error .. => if (← read).errToSorry then exceptionToSorry ex expectedType? else throw ex | .internal id _ => if (← read).errToSorry && id == abortTermExceptionId then exceptionToSorry ex expectedType? else if id == unsupportedSyntaxExceptionId then throw ex -- to outer try else if catchExPostpone && id == postponeExceptionId then /- If `elab` threw `Exception.postpone`, we reset any state modifications. For example, we want to make sure pending synthetic metavariables created by `elab` before it threw `Exception.postpone` are discarded. Note that we are also discarding the messages created by `elab`. For example, consider the expression. `((f.x a1).x a2).x a3` Now, suppose the elaboration of `f.x a1` produces an `Exception.postpone`. Then, a new metavariable `?m` is created. Then, `?m.x a2` also throws `Exception.postpone` because the type of `?m` is not yet known. Then another, metavariable `?n` is created, and finally `?n.x a3` also throws `Exception.postpone`. If we did not restore the state, we would keep "dead" metavariables `?m` and `?n` on the pending synthetic metavariable list. This is wasteful because when we resume the elaboration of `((f.x a1).x a2).x a3`, we start it from scratch and new metavariables are created for the nested functions. -/ s.restore postponeElabTermCore stx expectedType? else throw ex) catch ex => match ex with | .internal id _ => if id == unsupportedSyntaxExceptionId then s.restore -- also removes the info tree created above elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns else throw ex | _ => throw ex private def elabUsingElabFns (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool) : TermElabM Expr := do let s ← saveState let k := stx.getKind match termElabAttribute.getEntries (← getEnv) k with | [] => throwError "elaboration function for '{k}' has not been implemented{indentD stx}" | elabFns => elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns instance : MonadMacroAdapter TermElabM where getCurrMacroScope := getCurrMacroScope getNextMacroScope := return (← getThe Core.State).nextMacroScope setNextMacroScope next := modifyThe Core.State fun s => { s with nextMacroScope := next } private def isExplicit (stx : Syntax) : Bool := match stx with | `(@$_) => true | _ => false private def isExplicitApp (stx : Syntax) : Bool := stx.getKind == ``Lean.Parser.Term.app && isExplicit stx[0] /-- Return true if `stx` if a lambda abstraction containing a `{}` or `[]` binder annotation. Example: `fun {α} (a : α) => a` -/ private def isLambdaWithImplicit (stx : Syntax) : Bool := match stx with | `(fun $binders* => $_) => binders.raw.any fun b => b.isOfKind ``Lean.Parser.Term.implicitBinder || b.isOfKind `Lean.Parser.Term.instBinder | _ => false private partial def dropTermParens : Syntax → Syntax := fun stx => match stx with | `(($stx)) => dropTermParens stx | _ => stx private def isHole (stx : Syntax) : Bool := match stx with | `(_) => true | `(? _) => true | `(? $_:ident) => true | _ => false private def isTacticBlock (stx : Syntax) : Bool := match stx with | `(by $_:tacticSeq) => true | _ => false private def isNoImplicitLambda (stx : Syntax) : Bool := match stx with | `(no_implicit_lambda% $_:term) => true | _ => false private def isTypeAscription (stx : Syntax) : Bool := match stx with | `(($_ : $_)) => true | _ => false def hasNoImplicitLambdaAnnotation (type : Expr) : Bool := annotation? `noImplicitLambda type |>.isSome def mkNoImplicitLambdaAnnotation (type : Expr) : Expr := if hasNoImplicitLambdaAnnotation type then type else mkAnnotation `noImplicitLambda type /-- Block usage of implicit lambdas if `stx` is `@f` or `@f arg1 ...` or `fun` with an implicit binder annotation. -/ def blockImplicitLambda (stx : Syntax) : Bool := let stx := dropTermParens stx -- TODO: make it extensible isExplicit stx || isExplicitApp stx || isLambdaWithImplicit stx || isHole stx || isTacticBlock stx || isNoImplicitLambda stx || isTypeAscription stx def resolveLocalName (n : Name) : TermElabM (Option (Expr × List String)) := do let lctx ← getLCtx let auxDeclToFullName := (← read).auxDeclToFullName let currNamespace ← getCurrNamespace let view := extractMacroScopes n /- Simple case. "Match" function for regular local declarations. -/ let matchLocalDecl? (localDecl : LocalDecl) (givenName : Name) : Option LocalDecl := do guard (localDecl.userName == givenName) return localDecl /- "Match" function for auxiliary declarations that correspond to recursive definitions being defined. This function is used in the first-pass. Note that we do not check for `localDecl.userName == givenName` in this pass as we do for regular local declarations. Reason: consider the following example ``` mutual inductive Foo | somefoo : Foo | bar : Bar → Foo → Foo inductive Bar | somebar : Bar| foobar : Foo → Bar → Bar end mutual private def Foo.toString : Foo → String | Foo.somefoo => go 2 ++ toString.go 2 ++ Foo.toString.go 2 | Foo.bar b f => toString f ++ Bar.toString b where go (x : Nat) := s!"foo {x}" private def _root_.Ex2.Bar.toString : Bar → String | Bar.somebar => "bar" | Bar.foobar f b => Foo.toString f ++ Bar.toString b end ``` In the example above, we have two local declarations named `toString` in the local context, and we want the `toString f` to be resolved to `Foo.toString f` -/ let matchAuxRecDecl? (localDecl : LocalDecl) (fullDeclName : Name) (givenNameView : MacroScopesView) : Option LocalDecl := do let fullDeclView := extractMacroScopes fullDeclName /- First cleanup private name annotations -/ let fullDeclView := { fullDeclView with name := (privateToUserName? fullDeclView.name).getD fullDeclView.name } let fullDeclName := fullDeclView.review let localDeclNameView := extractMacroScopes localDecl.userName /- If the current namespace is a prefix of the full declaration name, we use a relaxed matching test where we must satisfy the following conditions - The local declaration is a suffix of the given name. - The given name is a suffix of the full declaration. Recall the `let rec`/`where` declaration naming convention. For example, suppose we have ``` def Foo.Bla.f ... := ... go ... where go ... := ... ``` The current namespace is `Foo.Bla`, and the full name for `go` is `Foo.Bla.f.g`, but we want to refer to it using just `go`. It is also accepted to refer to it using `f.go`, `Bla.f.go`, etc. -/ if currNamespace.isPrefixOf fullDeclName then /- Relaxed mode that allows us to access `let rec` declarations using shorter names -/ guard (localDeclNameView.isSuffixOf givenNameView) guard (givenNameView.isSuffixOf fullDeclView) return localDecl else /- It is the standard algorithm we using at `resolveGlobalName` for processing namespaces. The current solution also has a limitation when using `def _root_` in a mutual block. The non `def _root_` declarations may update the namespace. See the following example: ``` mutual def Foo.f ... := ... def _root_.g ... := ... let rec h := ... ... end ``` `def Foo.f` updates the namespace. Then, even when processing `def _root_.g ...` the condition `currNamespace.isPrefixOf fullDeclName` does not hold. This is not a big problem because we are planning to modify how we handle the mutual block in the future. Note that we don't check for `localDecl.userName == givenName` here. -/ let rec go (ns : Name) : Option LocalDecl := do if { givenNameView with name := ns ++ givenNameView.name }.review == fullDeclName then return localDecl match ns with | .str pre .. => go pre | _ => failure return (← go currNamespace) /- Traverse the local context backwards looking for match `givenNameView`. If `skipAuxDecl` we ignore `auxDecl` local declarations. -/ let findLocalDecl? (givenNameView : MacroScopesView) (skipAuxDecl : Bool) : Option LocalDecl := let givenName := givenNameView.review let localDecl? := lctx.decls.findSomeRev? fun localDecl? => do let localDecl ← localDecl? if localDecl.isAuxDecl then guard (not skipAuxDecl) if let some fullDeclName := auxDeclToFullName.find? localDecl.fvarId then matchAuxRecDecl? localDecl fullDeclName givenNameView else matchLocalDecl? localDecl givenName else matchLocalDecl? localDecl givenName if localDecl?.isSome || skipAuxDecl then localDecl? else -- Search auxDecls again trying an exact match of the given name lctx.decls.findSomeRev? fun localDecl? => do let localDecl ← localDecl? guard localDecl.isAuxDecl matchLocalDecl? localDecl givenName /- We use the parameter `globalDeclFound` to decide whether we should skip auxiliary declarations or not. We set it to true if we found a global declaration `n` as we iterate over the `loop`. Without this workaround, we would not be able to elaborate example such as ``` def foo.aux := 1 def foo : Nat → Nat | n => foo.aux -- should not be interpreted as `(foo).bar` ``` See test `aStructPerfIssue.lean` for another example. We skip auxiliary declarations when `projs` is not empty and `globalDeclFound` is true. Remark: we did not use to have the `globalDeclFound` parameter. Without this extra check we failed to elaborate ``` example : Nat := let n := 0 n.succ + (m |>.succ) + m.succ where m := 1 ``` See issue #1850. -/ let rec loop (n : Name) (projs : List String) (globalDeclFound : Bool) := do let givenNameView := { view with name := n } let mut globalDeclFound := globalDeclFound unless globalDeclFound do let r ← resolveGlobalName givenNameView.review let r := r.filter fun (_, fieldList) => fieldList.isEmpty unless r.isEmpty do globalDeclFound := true match findLocalDecl? givenNameView (skipAuxDecl := globalDeclFound && not projs.isEmpty) with | some decl => return some (decl.toExpr, projs) | none => match n with | .str pre s => loop pre (s::projs) globalDeclFound | _ => return none loop view.name [] (globalDeclFound := false) /-- Return true iff `stx` is a `Syntax.ident`, and it is a local variable. -/ def isLocalIdent? (stx : Syntax) : TermElabM (Option Expr) := match stx with | Syntax.ident _ _ val _ => do let r? ← resolveLocalName val match r? with | some (fvar, []) => return some fvar | _ => return none | _ => return none inductive UseImplicitLambdaResult where | no | yes (expectedType : Expr) | postpone /-- Return normalized expected type if it is of the form `{a : α} → β` or `[a : α] → β` and `blockImplicitLambda stx` is not true, else return `none`. Remark: implicit lambdas are not triggered by the strict implicit binder annotation `{{a : α}} → β` -/ private def useImplicitLambda (stx : Syntax) (expectedType? : Option Expr) : TermElabM UseImplicitLambdaResult := do if blockImplicitLambda stx then return .no let some expectedType := expectedType? | return .no if hasNoImplicitLambdaAnnotation expectedType then return .no let expectedType ← whnfForall expectedType let .forallE _ _ _ c := expectedType | return .no unless c.isImplicit || c.isInstImplicit do return .no if let some x ← isLocalIdent? stx then if (← isMVarApp (← inferType x)) then /- If `stx` is a local variable without type information, then adding implicit lambdas makes elaboration fail. We should try to postpone elaboration until the type of the local variable becomes available, or disable implicit lambdas if we cannot postpone anymore. Here is an example where this special case is useful. ``` def foo2mk (_ : ∀ {α : Type} (a : α), a = a) : nat := 37 example (x) : foo2mk x = foo2mk x := rfl ``` The example about would fail without this special case. The expected type would be `(a : α✝) → a = a`, where `α✝` is a new free variable introduced by the implicit lambda. Now, let `?m` be the type of `x`. Then, the constraint `?m =?= (a : α✝) → a = a` cannot be solved using the assignment `?m := (a : α✝) → a = a` since `α✝` is not in the scope of `?m`. Note that, this workaround does not prevent the following example from failing. ``` example (x) : foo2mk (id x) = 37 := rfl ``` The user can write ``` example (x) : foo2mk (id @x) = 37 := rfl ``` -/ return .postpone return .yes expectedType private def decorateErrorMessageWithLambdaImplicitVars (ex : Exception) (impFVars : Array Expr) : TermElabM Exception := do match ex with | .error ref msg => if impFVars.isEmpty then return Exception.error ref msg else let mut msg := m!"{msg}\nthe following variables have been introduced by the implicit lambda feature" for impFVar in impFVars do let auxMsg := m!"{impFVar} : {← inferType impFVar}" let auxMsg ← addMessageContext auxMsg msg := m!"{msg}{indentD auxMsg}" msg := m!"{msg}\nyou can disable implict lambdas using `@` or writing a lambda expression with `\{}` or `[]` binder annotations." return Exception.error ref msg | _ => return ex private def elabImplicitLambdaAux (stx : Syntax) (catchExPostpone : Bool) (expectedType : Expr) (impFVars : Array Expr) : TermElabM Expr := do let body ← elabUsingElabFns stx expectedType catchExPostpone try let body ← ensureHasType expectedType body let r ← mkLambdaFVars impFVars body trace[Elab.implicitForall] r return r catch ex => throw (← decorateErrorMessageWithLambdaImplicitVars ex impFVars) private partial def elabImplicitLambda (stx : Syntax) (catchExPostpone : Bool) (type : Expr) : TermElabM Expr := loop type #[] where loop (type : Expr) (fvars : Array Expr) : TermElabM Expr := do match (← whnfForall type) with | .forallE n d b c => if c.isExplicit then elabImplicitLambdaAux stx catchExPostpone type fvars else withFreshMacroScope do let n ← MonadQuotation.addMacroScope n withLocalDecl n c d fun fvar => do let type := b.instantiate1 fvar loop type (fvars.push fvar) | _ => elabImplicitLambdaAux stx catchExPostpone type fvars /-- Main loop for `elabTerm` -/ private partial def elabTermAux (expectedType? : Option Expr) (catchExPostpone : Bool) (implicitLambda : Bool) : Syntax → TermElabM Expr | .missing => mkSyntheticSorryFor expectedType? | stx => withFreshMacroScope <| withIncRecDepth do withTraceNode `Elab.step (fun _ => return m!"expected type: {expectedType?}, term\n{stx}") do checkMaxHeartbeats "elaborator" let env ← getEnv let result ← match (← liftMacroM (expandMacroImpl? env stx)) with | some (decl, stxNew?) => let stxNew ← liftMacroM <| liftExcept stxNew? withInfoContext' stx (mkInfo := mkTermInfo decl (expectedType? := expectedType?) stx) <| withMacroExpansion stx stxNew <| withRef stxNew <| elabTermAux expectedType? catchExPostpone implicitLambda stxNew | _ => let useImplicitResult ← if implicitLambda && (← read).implicitLambda then useImplicitLambda stx expectedType? else pure .no match useImplicitResult with | .yes expectedType => elabImplicitLambda stx catchExPostpone expectedType | .no => elabUsingElabFns stx expectedType? catchExPostpone | .postpone => /- Try to postpone elaboration, and if we cannot postpone anymore disable implicit lambdas. See comment at `useImplicitLambda`. -/ if (← read).mayPostpone then if catchExPostpone then postponeElabTerm stx expectedType? else throwPostpone else elabUsingElabFns stx expectedType? catchExPostpone trace[Elab.step.result] result pure result /-- Store in the `InfoTree` that `e` is a "dot"-completion target. -/ def addDotCompletionInfo (stx : Syntax) (e : Expr) (expectedType? : Option Expr) (field? : Option Syntax := none) : TermElabM Unit := do addCompletionInfo <| CompletionInfo.dot { expr := e, stx, lctx := (← getLCtx), elaborator := .anonymous, expectedType? } (field? := field?) (expectedType? := expectedType?) /-- Main function for elaborating terms. It extracts the elaboration methods from the environment using the node kind. Recall that the environment has a mapping from `SyntaxNodeKind` to `TermElab` methods. It creates a fresh macro scope for executing the elaboration method. All unlogged trace messages produced by the elaboration method are logged using the position information at `stx`. If the elaboration method throws an `Exception.error` and `errToSorry == true`, the error is logged and a synthetic sorry expression is returned. If the elaboration throws `Exception.postpone` and `catchExPostpone == true`, a new synthetic metavariable of kind `SyntheticMVarKind.postponed` is created, registered, and returned. The option `catchExPostpone == false` is used to implement `resumeElabTerm` to prevent the creation of another synthetic metavariable when resuming the elaboration. If `implicitLambda == true`, then disable implicit lambdas feature for the given syntax, but not for its subterms. We use this flag to implement, for example, the `@` modifier. If `Context.implicitLambda == false`, then this parameter has no effect. -/ def elabTerm (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) (implicitLambda := true) : TermElabM Expr := withRef stx <| elabTermAux expectedType? catchExPostpone implicitLambda stx def elabTermEnsuringType (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) (implicitLambda := true) (errorMsgHeader? : Option String := none) : TermElabM Expr := do let e ← elabTerm stx expectedType? catchExPostpone implicitLambda withRef stx <| ensureHasType expectedType? e errorMsgHeader? /-- Execute `x` and return `some` if no new errors were recorded or exceptions was thrown. Otherwise, return `none` -/ def commitIfNoErrors? (x : TermElabM α) : TermElabM (Option α) := do let saved ← saveState Core.resetMessageLog try let a ← x if (← MonadLog.hasErrors) then restoreState saved return none else Core.setMessageLog (saved.meta.core.messages ++ (← Core.getMessageLog)) return a catch _ => restoreState saved return none /-- Adapt a syntax transformation to a regular, term-producing elaborator. -/ def adaptExpander (exp : Syntax → TermElabM Syntax) : TermElab := fun stx expectedType? => do let stx' ← exp stx withMacroExpansion stx stx' <| elabTerm stx' expectedType? /-- Create a new metavariable with the given type, and try to synthesize it. It type class resolution cannot be executed (e.g., it is stuck because of metavariables in `type`), register metavariable as a pending one. -/ def mkInstMVar (type : Expr) : TermElabM Expr := do let mvar ← mkFreshExprMVar type MetavarKind.synthetic let mvarId := mvar.mvarId! unless (← synthesizeInstMVarCore mvarId) do registerSyntheticMVarWithCurrRef mvarId SyntheticMVarKind.typeClass return mvar /-- Make sure `e` is a type by inferring its type and making sure it is a `Expr.sort` or is unifiable with `Expr.sort`, or can be coerced into one. -/ def ensureType (e : Expr) : TermElabM Expr := do if (← isType e) then return e else let eType ← inferType e let u ← mkFreshLevelMVar if (← isDefEq eType (mkSort u)) then return e else if let some coerced ← coerceToSort? e then return coerced else if (← instantiateMVars e).hasSyntheticSorry then throwAbortTerm throwError "type expected, got\n ({← instantiateMVars e} : {← instantiateMVars eType})" /-- Elaborate `stx` and ensure result is a type. -/ def elabType (stx : Syntax) : TermElabM Expr := do let u ← mkFreshLevelMVar let type ← elabTerm stx (mkSort u) withRef stx <| ensureType type /-- Enable auto-bound implicits, and execute `k` while catching auto bound implicit exceptions. When an exception is caught, a new local declaration is created, registered, and `k` is tried to be executed again. -/ partial def withAutoBoundImplicit (k : TermElabM α) : TermElabM α := do let flag := autoImplicit.get (← getOptions) if flag then withReader (fun ctx => { ctx with autoBoundImplicit := flag, autoBoundImplicits := {} }) do let rec loop (s : SavedState) : TermElabM α := do try k catch | ex => match isAutoBoundImplicitLocalException? ex with | some n => -- Restore state, declare `n`, and try again s.restore withLocalDecl n .implicit (← mkFreshTypeMVar) fun x => withReader (fun ctx => { ctx with autoBoundImplicits := ctx.autoBoundImplicits.push x } ) do loop (← saveState) | none => throw ex loop (← saveState) else k def withoutAutoBoundImplicit (k : TermElabM α) : TermElabM α := do withReader (fun ctx => { ctx with autoBoundImplicit := false, autoBoundImplicits := {} }) k partial def withAutoBoundImplicitForbiddenPred (p : Name → Bool) (x : TermElabM α) : TermElabM α := do withReader (fun ctx => { ctx with autoBoundImplicitForbidden := fun n => p n || ctx.autoBoundImplicitForbidden n }) x /-- Collect unassigned metavariables in `type` that are not already in `init` and not satisfying `except`. -/ partial def collectUnassignedMVars (type : Expr) (init : Array Expr := #[]) (except : MVarId → Bool := fun _ => false) : TermElabM (Array Expr) := do let mvarIds ← getMVars type if mvarIds.isEmpty then return init else go mvarIds.toList init where go (mvarIds : List MVarId) (result : Array Expr) : TermElabM (Array Expr) := do match mvarIds with | [] => return result | mvarId :: mvarIds => do if (← mvarId.isAssigned) then go mvarIds result else if result.contains (mkMVar mvarId) || except mvarId then go mvarIds result else let mvarType := (← getMVarDecl mvarId).type let mvarIdsNew ← getMVars mvarType let mvarIdsNew := mvarIdsNew.filter fun mvarId => !result.contains (mkMVar mvarId) if mvarIdsNew.isEmpty then go mvarIds (result.push (mkMVar mvarId)) else go (mvarIdsNew.toList ++ mvarId :: mvarIds) result /-- Return `autoBoundImplicits ++ xs` This methoid throws an error if a variable in `autoBoundImplicits` depends on some `x` in `xs`. The `autoBoundImplicits` may contain free variables created by the auto-implicit feature, and unassigned free variables. It avoids the hack used at `autoBoundImplicitsOld`. Remark: we cannot simply replace every occurrence of `addAutoBoundImplicitsOld` with this one because a particular use-case may not be able to handle the metavariables in the array being given to `k`. -/ def addAutoBoundImplicits (xs : Array Expr) : TermElabM (Array Expr) := do let autos := (← read).autoBoundImplicits go autos.toList #[] where go (todo : List Expr) (autos : Array Expr) : TermElabM (Array Expr) := do match todo with | [] => for auto in autos do if auto.isFVar then let localDecl ← auto.fvarId!.getDecl for x in xs do if (← localDeclDependsOn localDecl x.fvarId!) then throwError "invalid auto implicit argument '{auto}', it depends on explicitly provided argument '{x}'" return autos ++ xs | auto :: todo => let autos ← collectUnassignedMVars (← inferType auto) autos go todo (autos.push auto) /-- Similar to `autoBoundImplicits`, but immediately if the resulting array of expressions contains metavariables, it immediately use `mkForallFVars` + `forallBoundedTelescope` to convert them into free variables. The type `type` is modified during the process if type depends on `xs`. We use this method to simplify the conversion of code using `autoBoundImplicitsOld` to `autoBoundImplicits` -/ def addAutoBoundImplicits' (xs : Array Expr) (type : Expr) (k : Array Expr → Expr → TermElabM α) : TermElabM α := do let xs ← addAutoBoundImplicits xs if xs.all (·.isFVar) then k xs type else forallBoundedTelescope (← mkForallFVars xs type) xs.size fun xs type => k xs type def mkAuxName (suffix : Name) : TermElabM Name := do match (← read).declName? with | none => throwError "auxiliary declaration cannot be created when declaration name is not available" | some declName => Lean.mkAuxName (declName ++ suffix) 1 builtin_initialize registerTraceClass `Elab.letrec /-- Return true if mvarId is an auxiliary metavariable created for compiling `let rec` or it is delayed assigned to one. -/ def isLetRecAuxMVar (mvarId : MVarId) : TermElabM Bool := do trace[Elab.letrec] "mvarId: {mkMVar mvarId} letrecMVars: {(← get).letRecsToLift.map (mkMVar $ ·.mvarId)}" let mvarId ← getDelayedMVarRoot mvarId trace[Elab.letrec] "mvarId root: {mkMVar mvarId}" return (← get).letRecsToLift.any (·.mvarId == mvarId) /-- Create an `Expr.const` using the given name and explicit levels. Remark: fresh universe metavariables are created if the constant has more universe parameters than `explicitLevels`. -/ def mkConst (constName : Name) (explicitLevels : List Level := []) : TermElabM Expr := do let cinfo ← getConstInfo constName if explicitLevels.length > cinfo.levelParams.length then throwError "too many explicit universe levels for '{constName}'" else let numMissingLevels := cinfo.levelParams.length - explicitLevels.length let us ← mkFreshLevelMVars numMissingLevels return Lean.mkConst constName (explicitLevels ++ us) private def mkConsts (candidates : List (Name × List String)) (explicitLevels : List Level) : TermElabM (List (Expr × List String)) := do candidates.foldlM (init := []) fun result (declName, projs) => do -- TODO: better support for `mkConst` failure. We may want to cache the failures, and report them if all candidates fail. Linter.checkDeprecated declName -- TODO: check is occurring too early if there are multiple alternatives. Fix if it is not ok in practice let const ← mkConst declName explicitLevels return (const, projs) :: result def resolveName (stx : Syntax) (n : Name) (preresolved : List Syntax.Preresolved) (explicitLevels : List Level) (expectedType? : Option Expr := none) : TermElabM (List (Expr × List String)) := do addCompletionInfo <| CompletionInfo.id stx stx.getId (danglingDot := false) (← getLCtx) expectedType? if let some (e, projs) ← resolveLocalName n then unless explicitLevels.isEmpty do throwError "invalid use of explicit universe parameters, '{e}' is a local" return [(e, projs)] let preresolved := preresolved.filterMap fun | .decl n projs => some (n, projs) | _ => none -- check for section variable capture by a quotation let ctx ← read if let some (e, projs) := preresolved.findSome? fun (n, projs) => ctx.sectionFVars.find? n |>.map (·, projs) then return [(e, projs)] -- section variables should shadow global decls if preresolved.isEmpty then process (← resolveGlobalName n) else process preresolved where process (candidates : List (Name × List String)) : TermElabM (List (Expr × List String)) := do if candidates.isEmpty then if (← read).autoBoundImplicit && !(← read).autoBoundImplicitForbidden n && isValidAutoBoundImplicitName n (relaxedAutoImplicit.get (← getOptions)) then throwAutoBoundImplicitLocal n else throwError "unknown identifier '{Lean.mkConst n}'" mkConsts candidates explicitLevels /-- Similar to `resolveName`, but creates identifiers for the main part and each projection with position information derived from `ident`. Example: Assume resolveName `v.head.bla.boo` produces `(v.head, ["bla", "boo"])`, then this method produces `(v.head, id, [f₁, f₂])` where `id` is an identifier for `v.head`, and `f₁` and `f₂` are identifiers for fields `"bla"` and `"boo"`. -/ def resolveName' (ident : Syntax) (explicitLevels : List Level) (expectedType? : Option Expr := none) : TermElabM (List (Expr × Syntax × List Syntax)) := do match ident with | .ident _ _ n preresolved => let r ← resolveName ident n preresolved explicitLevels expectedType? r.mapM fun (c, fields) => do let ids := ident.identComponents (nFields? := fields.length) return (c, ids.head!, ids.tail!) | _ => throwError "identifier expected" def resolveId? (stx : Syntax) (kind := "term") (withInfo := false) : TermElabM (Option Expr) := match stx with | .ident _ _ val preresolved => do let rs ← try resolveName stx val preresolved [] catch _ => pure [] let rs := rs.filter fun ⟨_, projs⟩ => projs.isEmpty let fs := rs.map fun (f, _) => f match fs with | [] => return none | [f] => let f ← if withInfo then addTermInfo stx f else pure f return some f | _ => throwError "ambiguous {kind}, use fully qualified name, possible interpretations {fs}" | _ => throwError "identifier expected" def TermElabM.run (x : TermElabM α) (ctx : Context := {}) (s : State := {}) : MetaM (α × State) := withConfig setElabConfig (x ctx |>.run s) @[inline] def TermElabM.run' (x : TermElabM α) (ctx : Context := {}) (s : State := {}) : MetaM α := (·.1) <$> x.run ctx s def TermElabM.toIO (x : TermElabM α) (ctxCore : Core.Context) (sCore : Core.State) (ctxMeta : Meta.Context) (sMeta : Meta.State) (ctx : Context) (s : State) : IO (α × Core.State × Meta.State × State) := do let ((a, s), sCore, sMeta) ← (x.run ctx s).toIO ctxCore sCore ctxMeta sMeta return (a, sCore, sMeta, s) instance [MetaEval α] : MetaEval (TermElabM α) where eval env opts x _ := do let x : TermElabM α := do try x finally (← Core.getMessageLog).forM fun msg => do IO.println (← msg.toString) MetaEval.eval env opts (hideUnit := true) <| x.run' {} /-- Execute `x` and then tries to solve pending universe constraints. Note that, stuck constraints will not be discarded. -/ def universeConstraintsCheckpoint (x : TermElabM α) : TermElabM α := do let a ← x discard <| processPostponed (mayPostpone := true) (exceptionOnFailure := true) return a def expandDeclId (currNamespace : Name) (currLevelNames : List Name) (declId : Syntax) (modifiers : Modifiers) : TermElabM ExpandDeclIdResult := do let r ← Elab.expandDeclId currNamespace currLevelNames declId modifiers if (← read).sectionVars.contains r.shortName then throwError "invalid declaration name '{r.shortName}', there is a section variable with the same name" return r /-- Helper function for "embedding" an `Expr` in `Syntax`. It creates a named hole `?m` and immediately assigns `e` to it. Examples: ```lean let e := mkConst ``Nat.zero `(Nat.succ $(← exprToSyntax e)) ``` -/ def exprToSyntax (e : Expr) : TermElabM Term := withFreshMacroScope do let result ← `(?m) let eType ← inferType e let mvar ← elabTerm result eType mvar.mvarId!.assign e return result end Term open Term in def withoutModifyingStateWithInfoAndMessages [MonadControlT TermElabM m] [Monad m] (x : m α) : m α := do controlAt TermElabM fun runInBase => withoutModifyingStateWithInfoAndMessagesImpl <| runInBase x builtin_initialize registerTraceClass `Elab.postpone registerTraceClass `Elab.coe registerTraceClass `Elab.debug export Term (TermElabM) end Lean.Elab
b98c88e097ee2b95fbb43cd6a93c1c58d96c98cf
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/stage0/src/Lean/Meta/LevelDefEq.lean
3cbcca9e7d9ae0c037e53e5717d88d38371bb28c
[ "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
9,755
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Basic import Lean.Meta.InferType namespace Lean.Meta private partial def decAux? : Level → MetaM (Option Level) | Level.zero _ => return none | Level.param _ _ => return none | Level.mvar mvarId _ => do let mctx ← getMCtx match mctx.getLevelAssignment? mvarId with | some u => decAux? u | none => if (← isReadOnlyLevelMVar mvarId) then return none else let u ← mkFreshLevelMVar assignLevelMVar mvarId (mkLevelSucc u) return u | Level.succ u _ => return u | u => let process (u v : Level) : MetaM (Option Level) := do match (← decAux? u) with | none => return none | some u => do match (← decAux? v) with | none => return none | some v => return mkLevelMax' u v match u with | Level.max u v _ => process u v /- Remark: If `decAux? v` returns `some ...`, then `imax u v` is equivalent to `max u v`. -/ | Level.imax u v _ => process u v | _ => unreachable! def decLevel? (u : Level) : MetaM (Option Level) := do let mctx ← getMCtx match (← decAux? u) with | some v => return some v | none => do modify fun s => { s with mctx := mctx } return none def decLevel (u : Level) : MetaM Level := do match (← decLevel? u) with | some u => return u | none => throwError! "invalid universe level, {u} is not greater than 0" /- This method is useful for inferring universe level parameters for function that take arguments such as `{α : Type u}`. Recall that `Type u` is `Sort (u+1)` in Lean. Thus, given `α`, we must infer its universe level, and then decrement 1 to obtain `u`. -/ def getDecLevel (type : Expr) : MetaM Level := do decLevel (← getLevel type) /-- Return true iff `lvl` occurs in `max u_1 ... u_n` and `lvl != u_i` for all `i in [1, n]`. That is, `lvl` is a proper level subterm of some `u_i`. -/ private def strictOccursMax (lvl : Level) : Level → Bool | Level.max u v _ => visit u || visit v | _ => false where visit : Level → Bool | Level.max u v _ => visit u || visit v | u => u != lvl && lvl.occurs u /-- `mkMaxArgsDiff mvarId (max u_1 ... (mvar mvarId) ... u_n) v` => `max v u_1 ... u_n` -/ private def mkMaxArgsDiff (mvarId : MVarId) : Level → Level → Level | Level.max u v _, acc => mkMaxArgsDiff mvarId v <| mkMaxArgsDiff mvarId u acc | l@(Level.mvar id _), acc => if id != mvarId then mkLevelMax' acc l else acc | l, acc => mkLevelMax' acc l /-- Solve `?m =?= max ?m v` by creating a fresh metavariable `?n` and assigning `?m := max ?n v` -/ private def solveSelfMax (mvarId : MVarId) (v : Level) : MetaM Unit := do assert! v.isMax let n ← mkFreshLevelMVar assignLevelMVar mvarId <| mkMaxArgsDiff mvarId v n private def postponeIsLevelDefEq (lhs : Level) (rhs : Level) : MetaM Unit := modifyPostponed fun postponed => postponed.push { lhs := lhs, rhs := rhs } mutual private partial def solve (u v : Level) : MetaM LBool := do match u, v with | Level.mvar mvarId _, _ => if (← isReadOnlyLevelMVar mvarId) then return LBool.undef else if !u.occurs v then assignLevelMVar u.mvarId! v return LBool.true else if v.isMax && !strictOccursMax u v then solveSelfMax u.mvarId! v return LBool.true else return LBool.undef | Level.zero _, Level.max v₁ v₂ _ => Bool.toLBool <$> (isLevelDefEqAux levelZero v₁ <&&> isLevelDefEqAux levelZero v₂) | Level.zero _, Level.imax _ v₂ _ => Bool.toLBool <$> isLevelDefEqAux levelZero v₂ | Level.zero _, Level.succ .. => return LBool.false | Level.succ u _, v => if u.isMVar && u.occurs v then return LBool.undef else match (← Meta.decLevel? v) with | some v => Bool.toLBool <$> isLevelDefEqAux u v | none => return LBool.undef | _, _ => return LBool.undef partial def isLevelDefEqAux : Level → Level → MetaM Bool | Level.succ lhs _, Level.succ rhs _ => isLevelDefEqAux lhs rhs | lhs, rhs => do if lhs == rhs then return true else trace[Meta.isLevelDefEq.step]! "{lhs} =?= {rhs}" let lhs' ← instantiateLevelMVars lhs let lhs' := lhs'.normalize let rhs' ← instantiateLevelMVars rhs let rhs' := rhs'.normalize if lhs != lhs' || rhs != rhs' then isLevelDefEqAux lhs' rhs' else let r ← solve lhs rhs; if r != LBool.undef then return r == LBool.true else let r ← solve rhs lhs; if r != LBool.undef then return r == LBool.true else do let mctx ← getMCtx if !mctx.hasAssignableLevelMVar lhs && !mctx.hasAssignableLevelMVar rhs then let ctx ← read if ctx.config.isDefEqStuckEx && (lhs.isMVar || rhs.isMVar) then do trace[Meta.isLevelDefEq.stuck]! "{lhs} =?= {rhs}" Meta.throwIsDefEqStuck else return false else postponeIsLevelDefEq lhs rhs return true end def isListLevelDefEqAux : List Level → List Level → MetaM Bool | [], [] => return true | u::us, v::vs => isLevelDefEqAux u v <&&> isListLevelDefEqAux us vs | _, _ => return false private def getNumPostponed : MetaM Nat := do return (← getPostponed).size open Std (PersistentArray) private def getResetPostponed : MetaM (PersistentArray PostponedEntry) := do let ps ← getPostponed setPostponed {} return ps private def processPostponedStep : MetaM Bool := traceCtx `Meta.isLevelDefEq.postponed.step do let ps ← getResetPostponed for p in ps do unless (← isLevelDefEqAux p.lhs p.rhs) do return false return true private partial def processPostponed (mayPostpone : Bool := true) : MetaM Bool := do if (← getNumPostponed) == 0 then return true else traceCtx `Meta.isLevelDefEq.postponed do let rec loop : MetaM Bool := do let numPostponed ← getNumPostponed if numPostponed == 0 then return true else trace[Meta.isLevelDefEq.postponed]! "processing #{numPostponed} postponed is-def-eq level constraints" if !(← processPostponedStep) then return false else let numPostponed' ← getNumPostponed if numPostponed' == 0 then return true else if numPostponed' < numPostponed then loop else trace[Meta.isLevelDefEq.postponed]! "no progress solving pending is-def-eq level constraints" return mayPostpone loop private def restore (env : Environment) (mctx : MetavarContext) (postponed : PersistentArray PostponedEntry) : MetaM Unit := do setEnv env setMCtx mctx setPostponed postponed /-- `commitWhen x` executes `x` and process all postponed universe level constraints produced by `x`. We keep the modifications only if `processPostponed` return true and `x` returned `true`. Remark: postponed universe level constraints must be solved before returning. Otherwise, we don't know whether `x` really succeeded. -/ @[specialize] def commitWhen (x : MetaM Bool) (mayPostpone : Bool := true) : MetaM Bool := do let env ← getEnv let mctx ← getMCtx let postponed ← getResetPostponed try if (← x) then if (← processPostponed mayPostpone) then return true else restore env mctx postponed return false else restore env mctx postponed return false catch ex => restore env mctx postponed throw ex private def postponedToMessageData (ps : PersistentArray PostponedEntry) : MessageData := do let mut r := MessageData.nil for p in ps do r := m!"{r}\n{p.lhs} =?= {p.rhs}" return r @[specialize] def withoutPostponingUniverseConstraintsImp {α} (x : MetaM α) : MetaM α := do let postponed ← getResetPostponed try let a ← x unless (← processPostponed (mayPostpone := false)) do throwError! "stuck at solving universe constraints{MessageData.nestD (postponedToMessageData (← getPostponed))}" setPostponed postponed return a catch ex => setPostponed postponed throw ex @[inline] def withoutPostponingUniverseConstraints {α m} [MonadControlT MetaM m] [Monad m] : m α → m α := mapMetaM <| withoutPostponingUniverseConstraintsImp def isLevelDefEq (u v : Level) : MetaM Bool := traceCtx `Meta.isLevelDefEq do let b ← commitWhen (mayPostpone := true) <| Meta.isLevelDefEqAux u v trace[Meta.isLevelDefEq]! "{u} =?= {v} ... {if b then "success" else "failure"}" return b def isExprDefEq (t s : Expr) : MetaM Bool := traceCtx `Meta.isDefEq do let b ← commitWhen (mayPostpone := true) <| Meta.isExprDefEqAux t s trace[Meta.isDefEq]! "{t} =?= {s} ... {if b then "success" else "failure"}" return b abbrev isDefEq (t s : Expr) : MetaM Bool := isExprDefEq t s def isExprDefEqGuarded (a b : Expr) : MetaM Bool := do try isExprDefEq a b catch _ => return false abbrev isDefEqGuarded (t s : Expr) : MetaM Bool := isExprDefEqGuarded t s def isDefEqNoConstantApprox (t s : Expr) : MetaM Bool := approxDefEq <| isDefEq t s builtin_initialize registerTraceClass `Meta.isLevelDefEq registerTraceClass `Meta.isLevelDefEq.step registerTraceClass `Meta.isLevelDefEq.postponed end Lean.Meta
fd62eadec31f1579ee44de223baad0f062b6867a
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/algebra/group/prod.lean
283d967cfa26a9255c9b5b33eb520f312633402a
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
8,982
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot, Yury Kudryashov -/ import algebra.group.hom import data.prod /-! # Monoid, group etc structures on `M × N` In this file we define one-binop (`monoid`, `group` etc) structures on `M × N`. We also prove trivial `simp` lemmas, and define the following operations on `monoid_hom`s: * `fst M N : M × N →* M`, `snd M N : M × N →* N`: projections `prod.fst` and `prod.snd` as `monoid_hom`s; * `inl M N : M →* M × N`, `inr M N : N →* M × N`: inclusions of first/second monoid into the product; * `f.prod g : `M →* N × P`: sends `x` to `(f x, g x)`; * `f.coprod g : M × N →* P`: sends `(x, y)` to `f x * g y`; * `f.prod_map g : M × N → M' × N'`: `prod.map f g` as a `monoid_hom`, sends `(x, y)` to `(f x, g y)`. -/ variables {A : Type*} {B : Type*} {G : Type*} {H : Type*} {M : Type*} {N : Type*} {P : Type*} namespace prod @[to_additive] instance [has_mul M] [has_mul N] : has_mul (M × N) := ⟨λ p q, ⟨p.1 * q.1, p.2 * q.2⟩⟩ @[simp, to_additive] lemma fst_mul [has_mul M] [has_mul N] (p q : M × N) : (p * q).1 = p.1 * q.1 := rfl @[simp, to_additive] lemma snd_mul [has_mul M] [has_mul N] (p q : M × N) : (p * q).2 = p.2 * q.2 := rfl @[simp, to_additive] lemma mk_mul_mk [has_mul M] [has_mul N] (a₁ a₂ : M) (b₁ b₂ : N) : (a₁, b₁) * (a₂, b₂) = (a₁ * a₂, b₁ * b₂) := rfl @[to_additive] instance [has_one M] [has_one N] : has_one (M × N) := ⟨(1, 1)⟩ @[simp, to_additive] lemma fst_one [has_one M] [has_one N] : (1 : M × N).1 = 1 := rfl @[simp, to_additive] lemma snd_one [has_one M] [has_one N] : (1 : M × N).2 = 1 := rfl @[to_additive] lemma one_eq_mk [has_one M] [has_one N] : (1 : M × N) = (1, 1) := rfl @[simp, to_additive] lemma mk_eq_one [has_one M] [has_one N] {x : M} {y : N} : (x, y) = 1 ↔ x = 1 ∧ y = 1 := mk.inj_iff @[to_additive] lemma fst_mul_snd [monoid M] [monoid N] (p : M × N) : (p.fst, 1) * (1, p.snd) = p := ext (mul_one p.1) (one_mul p.2) @[to_additive] instance [has_inv M] [has_inv N] : has_inv (M × N) := ⟨λp, (p.1⁻¹, p.2⁻¹)⟩ @[simp, to_additive] lemma fst_inv [has_inv G] [has_inv H] (p : G × H) : (p⁻¹).1 = (p.1)⁻¹ := rfl @[simp, to_additive] lemma snd_inv [has_inv G] [has_inv H] (p : G × H) : (p⁻¹).2 = (p.2)⁻¹ := rfl @[simp, to_additive] lemma inv_mk [has_inv G] [has_inv H] (a : G) (b : H) : (a, b)⁻¹ = (a⁻¹, b⁻¹) := rfl @[to_additive add_semigroup] instance [semigroup M] [semigroup N] : semigroup (M × N) := { mul_assoc := assume a b c, mk.inj_iff.mpr ⟨mul_assoc _ _ _, mul_assoc _ _ _⟩, .. prod.has_mul } @[to_additive add_monoid] instance [monoid M] [monoid N] : monoid (M × N) := { one_mul := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨one_mul _, one_mul _⟩, mul_one := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨mul_one _, mul_one _⟩, .. prod.semigroup, .. prod.has_one } @[to_additive add_group] instance [group G] [group H] : group (G × H) := { mul_left_inv := assume a, mk.inj_iff.mpr ⟨mul_left_inv _, mul_left_inv _⟩, .. prod.monoid, .. prod.has_inv } @[simp] lemma fst_sub [add_group A] [add_group B] (a b : A × B) : (a - b).1 = a.1 - b.1 := rfl @[simp] lemma snd_sub [add_group A] [add_group B] (a b : A × B) : (a - b).2 = a.2 - b.2 := rfl @[simp] lemma mk_sub_mk [add_group A] [add_group B] (x₁ x₂ : A) (y₁ y₂ : B) : (x₁, y₁) - (x₂, y₂) = (x₁ - x₂, y₁ - y₂) := rfl @[to_additive add_comm_semigroup] instance [comm_semigroup G] [comm_semigroup H] : comm_semigroup (G × H) := { mul_comm := assume a b, mk.inj_iff.mpr ⟨mul_comm _ _, mul_comm _ _⟩, .. prod.semigroup } @[to_additive add_comm_monoid] instance [comm_monoid M] [comm_monoid N] : comm_monoid (M × N) := { .. prod.comm_semigroup, .. prod.monoid } @[to_additive add_comm_group] instance [comm_group G] [comm_group H] : comm_group (G × H) := { .. prod.comm_semigroup, .. prod.group } end prod namespace monoid_hom variables (M N) [monoid M] [monoid N] /-- Given monoids `M`, `N`, the natural projection homomorphism from `M × N` to `M`.-/ @[to_additive "Given additive monoids `A`, `B`, the natural projection homomorphism from `A × B` to `A`"] def fst : M × N →* M := ⟨prod.fst, rfl, λ _ _, rfl⟩ /-- Given monoids `M`, `N`, the natural projection homomorphism from `M × N` to `N`.-/ @[to_additive "Given additive monoids `A`, `B`, the natural projection homomorphism from `A × B` to `B`"] def snd : M × N →* N := ⟨prod.snd, rfl, λ _ _, rfl⟩ /-- Given monoids `M`, `N`, the natural inclusion homomorphism from `M` to `M × N`. -/ @[to_additive "Given additive monoids `A`, `B`, the natural inclusion homomorphism from `A` to `A × B`."] def inl : M →* M × N := ⟨λ x, (x, 1), rfl, λ _ _, prod.ext rfl (one_mul 1).symm⟩ /-- Given monoids `M`, `N`, the natural inclusion homomorphism from `N` to `M × N`. -/ @[to_additive "Given additive monoids `A`, `B`, the natural inclusion homomorphism from `B` to `A × B`."] def inr : N →* M × N := ⟨λ y, (1, y), rfl, λ _ _, prod.ext (one_mul 1).symm rfl⟩ variables {M N} @[simp, to_additive] lemma coe_fst : ⇑(fst M N) = prod.fst := rfl @[simp, to_additive] lemma coe_snd : ⇑(snd M N) = prod.snd := rfl @[simp, to_additive] lemma inl_apply (x) : inl M N x = (x, 1) := rfl @[simp, to_additive] lemma inr_apply (y) : inr M N y = (1, y) := rfl @[simp, to_additive] lemma fst_comp_inl : (fst M N).comp (inl M N) = id M := rfl @[simp, to_additive] lemma snd_comp_inl : (snd M N).comp (inl M N) = 1 := rfl @[simp, to_additive] lemma fst_comp_inr : (fst M N).comp (inr M N) = 1 := rfl @[simp, to_additive] lemma snd_comp_inr : (snd M N).comp (inr M N) = id N := rfl section prod variable [monoid P] /-- Combine two `monoid_hom`s `f : M →* N`, `g : M →* P` into `f.prod g : M →* N × P` given by `(f.prod g) x = (f x, g x)` -/ @[to_additive prod "Combine two `add_monoid_hom`s `f : M →+ N`, `g : M →+ P` into `f.prod g : M →+ N × P` given by `(f.prod g) x = (f x, g x)`"] protected def prod (f : M →* N) (g : M →* P) : M →* N × P := { to_fun := λ x, (f x, g x), map_one' := prod.ext f.map_one g.map_one, map_mul' := λ x y, prod.ext (f.map_mul x y) (g.map_mul x y) } @[simp, to_additive prod_apply] lemma prod_apply (f : M →* N) (g : M →* P) (x) : f.prod g x = (f x, g x) := rfl @[to_additive fst_comp_prod] lemma fst_comp_prod (f : M →* N) (g : M →* P) : (fst N P).comp (f.prod g) = f := ext $ λ x, rfl @[to_additive snd_comp_prod] lemma snd_comp_prod (f : M →* N) (g : M →* P) : (snd N P).comp (f.prod g) = g := ext $ λ x, rfl @[to_additive prod_unique] lemma prod_unique (f : M →* N × P) : ((fst N P).comp f).prod ((snd N P).comp f) = f := ext $ λ x, by simp only [prod_apply, coe_fst, coe_snd, comp_apply, prod.mk.eta] end prod section prod_map variables {M' : Type*} {N' : Type*} [monoid M'] [monoid N'] [monoid P] (f : M →* M') (g : N →* N') /-- `prod.map` as a `monoid_hom`. -/ @[to_additive prod_map "`prod.map` as an `add_monoid_hom`"] def prod_map : M × N →* M' × N' := (f.comp (fst M N)).prod (g.comp (snd M N)) @[to_additive prod_map_def] lemma prod_map_def : prod_map f g = (f.comp (fst M N)).prod (g.comp (snd M N)) := rfl -- TODO : use `rfl` once we redefine `prod.map` in stdlib @[simp, to_additive coe_prod_map] lemma coe_prod_map : ⇑(prod_map f g) = prod.map f g := funext $ λ ⟨x, y⟩, rfl @[to_additive prod_comp_prod_map] lemma prod_comp_prod_map (f : P →* M) (g : P →* N) (f' : M →* M') (g' : N →* N') : (f'.prod_map g').comp (f.prod g) = (f'.comp f).prod (g'.comp g) := rfl end prod_map section coprod variables [comm_monoid P] (f : M →* P) (g : N →* P) /-- Coproduct of two `monoid_hom`s with the same codomain: `f.coprod g (p : M × N) = f p.1 * g p.2`. -/ @[to_additive "Coproduct of two `add_monoid_hom`s with the same codomain: `f.coprod g (p : M × N) = f p.1 + g p.2`."] def coprod : M × N →* P := f.comp (fst M N) * g.comp (snd M N) @[simp, to_additive] lemma coprod_apply (p : M × N) : f.coprod g p = f p.1 * g p.2 := rfl @[simp, to_additive] lemma coprod_comp_inl : (f.coprod g).comp (inl M N) = f := ext $ λ x, by simp [coprod_apply] @[simp, to_additive] lemma coprod_comp_inr : (f.coprod g).comp (inr M N) = g := ext $ λ x, by simp [coprod_apply] @[simp, to_additive] lemma coprod_unique (f : M × N →* P) : (f.comp (inl M N)).coprod (f.comp (inr M N)) = f := ext $ λ x, by simp [coprod_apply, inl_apply, inr_apply, ← map_mul] @[simp, to_additive] lemma coprod_inl_inr {M N : Type*} [comm_monoid M] [comm_monoid N] : (inl M N).coprod (inr M N) = id (M × N) := coprod_unique (id $ M × N) lemma comp_coprod {Q : Type*} [comm_monoid Q] (h : P →* Q) (f : M →* P) (g : N →* P) : h.comp (f.coprod g) = (h.comp f).coprod (h.comp g) := ext $ λ x, by simp end coprod end monoid_hom
fe1d5b3400805476d6f5e29a23416d79ab047b53
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/option/defs.lean
ecc410e921e6eaff08533e86d5a11f28828f776f
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
7,098
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ /-! # Extra definitions on `option` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > https://github.com/leanprover-community/mathlib4/pull/504 > Any changes to this file require a corresponding PR to mathlib4. This file defines more operations involving `option α`. Lemmas about them are located in other files under `data.option.`. Other basic operations on `option` are defined in the core library. -/ namespace option variables {α : Type*} {β : Type*} attribute [inline] option.is_some option.is_none /-- An elimination principle for `option`. It is a nondependent version of `option.rec`. -/ @[simp] protected def elim (b : β) (f : α → β) : option α → β | (some a) := f a | none := b instance has_mem : has_mem α (option α) := ⟨λ a b, b = some a⟩ @[simp] theorem mem_def {a : α} {b : option α} : a ∈ b ↔ b = some a := iff.rfl lemma mem_iff {a : α} {b : option α} : a ∈ b ↔ b = a := iff.rfl theorem is_none_iff_eq_none {o : option α} : o.is_none = tt ↔ o = none := ⟨option.eq_none_of_is_none, λ e, e.symm ▸ rfl⟩ theorem some_inj {a b : α} : some a = some b ↔ a = b := by simp lemma mem_some_iff {α : Type*} {a b : α} : a ∈ some b ↔ b = a := by simp /-- `o = none` is decidable even if the wrapped type does not have decidable equality. This is not an instance because it is not definitionally equal to `option.decidable_eq`. Try to use `o.is_none` or `o.is_some` instead. -/ @[inline] def decidable_eq_none {o : option α} : decidable (o = none) := decidable_of_decidable_of_iff (bool.decidable_eq _ _) is_none_iff_eq_none instance decidable_forall_mem {p : α → Prop} [decidable_pred p] : ∀ o : option α, decidable (∀ a ∈ o, p a) | none := is_true (by simp [false_implies_iff]) | (some a) := if h : p a then is_true $ λ o e, some_inj.1 e ▸ h else is_false $ mt (λ H, H _ rfl) h instance decidable_exists_mem {p : α → Prop} [decidable_pred p] : ∀ o : option α, decidable (∃ a ∈ o, p a) | none := is_false (λ ⟨a, ⟨h, _⟩⟩, by cases h) | (some a) := if h : p a then is_true $ ⟨_, rfl, h⟩ else is_false $ λ ⟨_, ⟨rfl, hn⟩⟩, h hn /-- Inhabited `get` function. Returns `a` if the input is `some a`, otherwise returns `default`. -/ @[reducible] def iget [inhabited α] : option α → α | (some x) := x | none := default @[simp] theorem iget_some [inhabited α] {a : α} : (some a).iget = a := rfl /-- `guard p a` returns `some a` if `p a` holds, otherwise `none`. -/ def guard (p : α → Prop) [decidable_pred p] (a : α) : option α := if p a then some a else none /-- `filter p o` returns `some a` if `o` is `some a` and `p a` holds, otherwise `none`. -/ def filter (p : α → Prop) [decidable_pred p] (o : option α) : option α := o.bind (guard p) /-- Cast of `option` to `list `. Returns `[a]` if the input is `some a`, and `[]` if it is `none`. -/ def to_list : option α → list α | none := [] | (some a) := [a] @[simp] theorem mem_to_list {a : α} {o : option α} : a ∈ to_list o ↔ a ∈ o := by cases o; simp [to_list, eq_comm] /-- Two arguments failsafe function. Returns `f a b` if the inputs are `some a` and `some b`, and "does nothing" otherwise. -/ def lift_or_get (f : α → α → α) : option α → option α → option α | none none := none | (some a) none := some a -- get a | none (some b) := some b -- get b | (some a) (some b) := some (f a b) -- lift f instance lift_or_get_comm (f : α → α → α) [h : is_commutative α f] : is_commutative (option α) (lift_or_get f) := ⟨λ a b, by cases a; cases b; simp [lift_or_get, h.comm]⟩ instance lift_or_get_assoc (f : α → α → α) [h : is_associative α f] : is_associative (option α) (lift_or_get f) := ⟨λ a b c, by cases a; cases b; cases c; simp [lift_or_get, h.assoc]⟩ instance lift_or_get_idem (f : α → α → α) [h : is_idempotent α f] : is_idempotent (option α) (lift_or_get f) := ⟨λ a, by cases a; simp [lift_or_get, h.idempotent]⟩ instance lift_or_get_is_left_id (f : α → α → α) : is_left_id (option α) (lift_or_get f) none := ⟨λ a, by cases a; simp [lift_or_get]⟩ instance lift_or_get_is_right_id (f : α → α → α) : is_right_id (option α) (lift_or_get f) none := ⟨λ a, by cases a; simp [lift_or_get]⟩ /-- Lifts a relation `α → β → Prop` to a relation `option α → option β → Prop` by just adding `none ~ none`. -/ inductive rel (r : α → β → Prop) : option α → option β → Prop /-- If `a ~ b`, then `some a ~ some b` -/ | some {a b} : r a b → rel (some a) (some b) /-- `none ~ none` -/ | none : rel none none /-- Partial bind. If for some `x : option α`, `f : Π (a : α), a ∈ x → option β` is a partial function defined on `a : α` giving an `option β`, where `some a = x`, then `pbind x f h` is essentially the same as `bind x f` but is defined only when all `x = some a`, using the proof to apply `f`. -/ @[simp] def pbind : Π (x : option α), (Π (a : α), a ∈ x → option β) → option β | none _ := none | (some a) f := f a rfl /-- Partial map. If `f : Π a, p a → β` is a partial function defined on `a : α` satisfying `p`, then `pmap f x h` is essentially the same as `map f x` but is defined only when all members of `x` satisfy `p`, using the proof to apply `f`. -/ @[simp] def pmap {p : α → Prop} (f : Π (a : α), p a → β) : Π x : option α, (∀ a ∈ x, p a) → option β | none _ := none | (some a) H := some (f a (H a (mem_def.mpr rfl))) /-- Flatten an `option` of `option`, a specialization of `mjoin`. -/ @[simp] def join : option (option α) → option α := λ x, bind x id protected def {u v} traverse {F : Type u → Type v} [applicative F] {α β : Type*} (f : α → F β) : option α → F (option β) | none := pure none | (some x) := some <$> f x /- By analogy with `monad.sequence` in `init/category/combinators.lean`. -/ /-- If you maybe have a monadic computation in a `[monad m]` which produces a term of type `α`, then there is a naturally associated way to always perform a computation in `m` which maybe produces a result. -/ def {u v} maybe {m : Type u → Type v} [monad m] {α : Type u} : option (m α) → m (option α) | none := return none | (some fn) := some <$> fn /-- Map a monadic function `f : α → m β` over an `o : option α`, maybe producing a result. -/ def {u v w} mmap {m : Type u → Type v} [monad m] {α : Type w} {β : Type u} (f : α → m β) (o : option α) : m (option β) := (o.map f).maybe /-- A monadic analogue of `option.elim`. -/ def melim {α β : Type*} {m : Type* → Type*} [monad m] (y : m β) (z : α → m β) (x : m (option α)) : m β := x >>= option.elim y z /-- A monadic analogue of `option.get_or_else`. -/ def mget_or_else {α : Type*} {m : Type* → Type*} [monad m] (x : m (option α)) (y : m α) : m α := melim y pure x end option
9f8382a9ea62095d805a083ba0636251c9ce2b87
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/simpZetaFalse.lean
bc17452d54c9e3ae7855d0f34574f32284d7d9b6
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
892
lean
opaque f : Nat → Nat axiom f_eq (x : Nat) : f (f x) = x theorem ex1 (x : Nat) (h : f (f x) = x) : (let y := x*x; if f (f x) = x then 1 else y + 1) = 1 := by simp (config := { zeta := false }) only [h] trace_state simp #print ex1 -- uses let_congr theorem ex2 (x z : Nat) (h : f (f x) = x) (h' : z = x) : (let y := f (f x); y) = z := by simp (config := { zeta := false }) only [h] trace_state simp [h'] #print ex2 -- uses let_val_congr theorem ex3 (x z : Nat) : (let α := Nat; (fun x : α => 0 + x)) = id := by simp (config := { zeta := false }) trace_state -- should not simplify let body since `fun α : Nat => fun x : α => 0 + x` is not type correct simp [id] theorem ex4 (p : Prop) (h : p) : (let n := 10; fun x : { z : Nat // z < n } => x = x) = fun z => p := by simp (config := { zeta := false }) trace_state simp [h] #print ex4 -- uses let_body_congr
51ef2bfc84c3044087ee9b7f06693c333ee8a4a5
4bddde0d06fbd53be6f23d7f5899998e8f63410b
/src/tactic/iconfig/lib/tactic.lean
7b94b4c5266761e6b347c53d708895a8a728c121
[]
no_license
khoek/libiconfig
4816290a5862af14b07683b3d2663e8e62832ef4
6f55c50bc5d852d26ee5ee4c5b52b2cda2a852e5
refs/heads/master
1,586,109,683,212
1,559,567,916,000
1,559,567,916,000
157,085,466
0
1
null
1,559,567,917,000
1,541,945,134,000
Lean
UTF-8
Lean
false
false
207
lean
open tactic meta def get_goal : tactic expr := do gs ← get_goals, match gs with | [a] := return a | [] := fail "error: there are no goals" | _ := fail "error: there are too many goals" end
3d02ef4a5df67a117db8ae965cc0ccc03a551fda
c062f1c97fdef9ac746f08754e7d766fd6789aa9
/data/list/sort.lean
0dff5c4c239f0d21555f0595cdab11d553dc83e2
[]
no_license
emberian/library_dev
00c7a985b21bdebe912f4127a363f2874e1e7555
f3abd7db0238edc18a397540e361a1da2f51503c
refs/heads/master
1,624,153,474,804
1,490,147,180,000
1,490,147,180,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,489
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad Insertion sort and merge sort. -/ import .perm -- TODO(Jeremy): move this namespace nat theorem add_pos_left {m : ℕ} (h : m > 0) (n : ℕ) : m + n > 0 := calc m + n > 0 + n : nat.add_lt_add_right h n ... = n : nat.zero_add n ... ≥ 0 : zero_le n theorem add_pos_right (m : ℕ) {n : ℕ} (h : n > 0) : m + n > 0 := begin rw add_comm, exact add_pos_left h m end theorem add_pos_iff_pos_or_pos (m n : ℕ) : m + n > 0 ↔ m > 0 ∨ n > 0 := iff.intro begin intro h, cases m with m, {simp [zero_add] at h, exact or.inr h}, exact or.inl (succ_pos _) end begin intro h, cases h with mpos npos, { apply add_pos_left mpos }, apply add_pos_right _ npos end end nat namespace list section sorted universe variable uu variables {α : Type uu} (r : α → α → Prop) def sorted : list α → Prop | [] := true | (a :: l) := sorted l ∧ ∀ b ∈ l, r a b theorem sorted_nil : sorted r nil := trivial theorem sorted_singleton (a : α) : sorted r [a] := ⟨sorted_nil r, λ b h, absurd h (not_mem_nil b)⟩ theorem sorted_of_sorted_cons {a : α} {l : list α} (h : sorted r (a :: l)) : sorted r l := h^.left theorem forall_mem_rel_of_sorted_cons {a : α} {l : list α} (h : sorted r (a :: l)) : ∀ b ∈ l, r a b := h^.right theorem sorted_cons {a : α} {l : list α} (h₁ : sorted r l) (h₂ : ∀ b ∈ l, r a b) : sorted r (a :: l) := ⟨h₁, h₂⟩ end sorted /- sorting procedures -/ section sort universe variable uu parameters {α : Type uu} (r : α → α → Prop) [decidable_rel r] local infix `≼` : 50 := r /- insertion sort -/ section insertion_sort def ordered_insert (a : α) : list α → list α | [] := [a] | (b :: l) := if a ≼ b then a :: (b :: l) else b :: ordered_insert l --@[simp] --theorem ordered_insert_nil (a : α) : ordered_insert a [] = [a] := rfl --@[simp] --theorem ordered_insert_cons (a b : α) (l : list α) : -- ordered_insert a (b :: l) = if a ≼ b then a :: (b :: l) else b :: ordered_insert a l := --rfl def insertion_sort : list α → list α | [] := [] | (b :: l) := ordered_insert b (insertion_sort l) --attribute [simp] insertion_sort.equations.eqn_1 insertion_sort.equations.eqn_2 section correctness parameter [deceqα : decidable_eq α] include deceqα open perm -- TODO(Jeremy): anonymous type class parameters don't work well theorem count_ordered_insert_eq (b a : α) : ∀ l, count b (ordered_insert a l) = count b (a :: l) | [] := by simp [ordered_insert] | (c :: l) := if h : a ≼ c then begin unfold ordered_insert, simp [if_pos, h] end else by simp [ordered_insert, if_neg, h, count_cons', count_ordered_insert_eq] theorem mem_ordered_insert_iff (b a : α) (l : list α) : b ∈ ordered_insert a l ↔ b ∈ a :: l := begin repeat {rw mem_iff_count_pos}, simp [count_ordered_insert_eq] end theorem perm_insertion_sort : ∀ l : list α, insertion_sort l ~ l | [] := perm.nil | (b :: l) := perm_of_forall_count_eq (take a, by simp [insertion_sort, count_ordered_insert_eq, count_cons', count_eq_count_of_perm (perm_insertion_sort l) a]) section total_and_transitive variables (totr : total r) (transr : transitive r) include totr transr theorem sorted_ordered_insert (a : α) : ∀ l, sorted r l → sorted r (ordered_insert a l) | [] := assume h, sorted_singleton r a | (b :: l) := assume h, have sorted r l, from sorted_of_sorted_cons r h, have h₀ : ∀ c ∈ l, b ≼ c, from forall_mem_rel_of_sorted_cons r h, if h' : a ≼ b then begin simp [ordered_insert, if_pos, h'], have ∀ c ∈ b :: l, a ≼ c, from take c, suppose c ∈ b :: l, or.elim (eq_or_mem_of_mem_cons this) (suppose c = b, this^.symm ▸ ‹a ≼ b›) (suppose c ∈ l, transr ‹a ≼ b› (h₀ _ this)), show sorted r (a :: b :: l), from sorted_cons r h this end else have b ≼ a, from or.resolve_left (totr a b) h', begin simp [ordered_insert, if_neg, ‹¬ a ≼ b›], have h₁ : sorted r (ordered_insert r a l), from sorted_ordered_insert l ‹sorted r l›, have h₂ : ∀ c ∈ ordered_insert r a l, b ≼ c, from take c, suppose c ∈ ordered_insert r a l, have c ∈ a :: l, from (mem_ordered_insert_iff r c a l)^.mp this, or.elim (eq_or_mem_of_mem_cons this) (suppose c = a, begin rw this, exact ‹b ≼ a› end) (suppose c ∈ l, h₀ c this), show sorted r (b :: ordered_insert r a l), from sorted_cons r h₁ h₂ end theorem sorted_insert_sort : ∀ l, sorted r (insertion_sort l) | [] := sorted_nil r | (a :: l) := sorted_ordered_insert totr transr a _ (sorted_insert_sort l) end total_and_transitive end correctness end insertion_sort /- merge sort -/ section merge_sort -- TODO(Jeremy): observation: if instead we write (a :: (split l).1, b :: (split l).2), the -- equation compiler can't prove the third equation def split : list α → list α × list α | [] := ([], []) | [a] := ([a], []) | (a :: b :: l) := match split l with | (l₁, l₂) := (a :: l₁, b :: l₂) end -- TODO(Jeremy): the cases is needed because the internal split_match gets a pair private theorem split_cons_cons_aux (a b : α) (l : list α) : split (a :: b :: l) = match split l with | (l₁, l₂) := (a :: l₁, b :: l₂) end := rfl @[simp] theorem split_cons_cons (a b : α) (l : list α) : split (a :: b :: l) = (a :: (split l).1, b :: (split l).2) := begin rw [split_cons_cons_aux], cases split l, reflexivity end -- attribute [simp] split.equations.eqn_1 split.equations.eqn_2 split_cons_cons theorem length_split_fst_le : ∀ l : list α, length ((split l).1) ≤ length l | [] := nat.le_refl 0 | [a] := nat.le_refl 1 | (a :: b :: l) := begin simp [split_cons_cons], rw [add_comm], transitivity, { apply add_le_add_right (length_split_fst_le l) }, apply nat.le_succ end theorem length_split_snd_le : ∀ l : list α, length ((split l).2) ≤ length l | [] := nat.le_refl 0 | [a] := nat.zero_le 1 | (a :: b :: l) := begin simp, rw [add_comm], transitivity, { apply add_le_add_right (length_split_snd_le l) }, apply nat.le_succ end theorem length_split_cons_cons_fst_lt (a b : α) (l : list α) : length (split (a :: b :: l)).1 < length (a :: b :: l) := begin simp, rw [add_comm], exact add_lt_add_of_le_of_lt (length_split_fst_le l) (nat.le_refl _) end theorem length_split_cons_cons_snd_lt (a b : α) (l : list α) : length (split (a :: b :: l)).2 < length (a :: b :: l) := begin simp, rw [add_comm], exact add_lt_add_of_le_of_lt (length_split_snd_le l) (nat.le_refl _) end -- Do the well-founded recursion by hand, until the function definition system supports it. private def merge.F : Π p : list α × list α, (Π p₁ : list α × list α, length p₁.1 + length p₁.2 < length p.1 + length p.2 → list α) → list α | ([], l) f := l | (a :: l, []) f := a :: l | (a :: l, b :: l') f := if a ≼ b then a :: f (l, b :: l') begin simp, apply nat.le_refl end else b :: f (a :: l, l') begin simp, apply nat.le_refl end def merge := well_founded.fix (inv_image.wf _ nat.lt_wf) merge.F theorem merge.def (p : list α × list α) : merge p = merge.F p (λ p h, merge p) := well_founded.fix_eq (inv_image.wf _ nat.lt_wf) merge.F p @[simp] theorem merge.equations.eq_1 (l : list α) : merge ([], l) = l := begin rw merge.def, reflexivity end @[simp] theorem merge.equations.eq_2 (a : α) (l : list α) : merge (a :: l, []) = a :: l := begin rw merge.def, reflexivity end @[simp] theorem merge.equations.eq_3 (a b : α) (l l' : list α) : merge (a :: l, b :: l') = if a ≼ b then a :: merge (l, b :: l') else b :: merge (a :: l, l') := begin rw merge.def, reflexivity end private def merge_sort.F : Π l : list α, (Π l₁ : list α, length l₁ < length l → list α) → list α | [] f := [] | [a] f := [a] | (a :: b :: l) f := let p := split (a :: b :: l), l₁ := f p.1 (length_split_cons_cons_fst_lt a b l), l₂ := f p.2 (length_split_cons_cons_snd_lt a b l) in merge (l₁, l₂) def merge_sort := well_founded.fix (inv_image.wf _ nat.lt_wf) merge_sort.F theorem merge_sort.def (l : list α) : merge_sort l = merge_sort.F l (λ l h, merge_sort l) := well_founded.fix_eq (inv_image.wf _ nat.lt_wf) merge_sort.F l @[simp] theorem merge_sort.equations.eq_1 : merge_sort [] = [] := begin rw merge_sort.def, reflexivity end @[simp] theorem merge_sort.equations.eq_2 (a : α) : merge_sort [a] = [a] := begin rw merge_sort.def, reflexivity end @[simp] theorem merge_sort.equations.eq_3 (a b : α) (l : list α) : merge_sort (a :: b :: l) = let p := split (a :: b :: l) in merge (merge_sort p.1, merge_sort p.2) := begin rw merge_sort.def, reflexivity end section correctness parameter [deceqα : decidable_eq α] include deceqα -- TODO(Jeremy): note that simp has to be called twice in the beginning, to reduce projections theorem count_split (a : α) : ∀ l : list α, count a (split l).1 + count a (split l).2 = count a l | [] := rfl | [a] := rfl | (a :: b :: l) := begin simp, simp [count_cons'], rw [-count_split l], simp end private def count_merge.F (c : α) : Π p : list α × list α, (Π p₁ : list α × list α, length p₁.1 + length p₁.2 < length p.1 + length p.2 → count c (merge p₁) = count c p₁.1 + count c p₁.2) → count c (merge p) = count c p.1 + count c p.2 | ([], l) f := by simp | (a :: l, []) f := by simp | (a :: l, b :: l') f := if h : a ≼ b then begin note hrec := f (l, b :: l') begin simp, apply nat.le_refl end, simp [if_pos, h, count_cons', hrec] end else begin note hrec := f (a :: l, l') begin simp, apply nat.le_refl end, simp [if_neg, h, count_cons', hrec] end theorem count_merge (c : α) : ∀ p : list α × list α, count c (merge p) = count c p.1 + count c p.2 := well_founded.fix (inv_image.wf _ nat.lt_wf) (count_merge.F c) theorem mem_merge_iff (a : α) (p : list α × list α) : a ∈ merge p ↔ a ∈ p.1 ∨ a ∈ p.2 := begin repeat { rw mem_iff_count_pos }, simp [count_merge, nat.add_pos_iff_pos_or_pos] end private def perm_merge_sort.F : Π l : list α, (Π l₁ : list α, length l₁ < length l → merge_sort l₁ ~ l₁) → merge_sort l ~ l | [] f := perm.refl _ | [a] f := perm.refl _ | (a :: b :: l) f := perm.perm_of_forall_count_eq begin intro c, pose hrec₁ := perm.count_eq_count_of_perm (f _ (length_split_cons_cons_fst_lt a b l)) c, pose hrec₂ := perm.count_eq_count_of_perm (f _ (length_split_cons_cons_snd_lt a b l)) c, simp at hrec₁, simp at hrec₁, simp at hrec₂, simp at hrec₂, simp [hrec₁, hrec₂, count_merge, count_split, count_cons'] end theorem perm_merge_sort : ∀ l : list α, merge_sort l ~ l := well_founded.fix (inv_image.wf _ nat.lt_wf) perm_merge_sort.F section total_and_transitive variables (totr : total r) (transr : transitive r) include totr transr private def sorted_merge.F : Π p : list α × list α, (Π p₁ : list α × list α, length p₁.1 + length p₁.2 < length p.1 + length p.2 → (sorted r p₁.1 → sorted r p₁.2 → sorted r (merge p₁))) → sorted r p.1 → sorted r p.2 → sorted r (merge p) | ([], l) f h₁ h₂ := begin simp, exact h₂ end | (a :: l, []) f h₁ h₂ := begin simp, exact h₁ end | (a :: l, b :: l') f h₁ h₂ := have sorted r l, from sorted_of_sorted_cons r h₁, have sorted r l', from sorted_of_sorted_cons r h₂, have h₁₀ : ∀ c ∈ l, a ≼ c, from forall_mem_rel_of_sorted_cons r h₁, have h₂₀ : ∀ c ∈ l', b ≼ c, from forall_mem_rel_of_sorted_cons r h₂, if h : a ≼ b then begin note hrec := f (l, b :: l') begin simp, apply nat.le_refl end, simp [if_pos, h], have h₃ : sorted r (merge r (l, b :: l')), from hrec ‹sorted r l› h₂, have h₄ : ∀ c ∈ merge r (l, b :: l'), a ≼ c, begin intros c hc, rw mem_merge_iff at hc, exact or.elim hc (suppose c ∈ l, show a ≼ c, from h₁₀ c this) (suppose c ∈ b :: l', or.elim (eq_or_mem_of_mem_cons this) (suppose c = b, show a ≼ c, from this^.symm ▸ ‹a ≼ b›) (suppose c ∈ l', show a ≼ c, from transr ‹a ≼ b› (h₂₀ c this))) end, show sorted r (a :: merge r (l, b :: l')), from sorted_cons r h₃ h₄ end else have h' : b ≼ a, from or.resolve_left (totr a b) h, begin note hrec := f (a :: l, l') begin simp, apply nat.le_refl end, simp [if_neg, h], have h₃ : sorted r (merge r (a :: l, l')), from hrec h₁ ‹sorted r l'›, have h₄ : ∀ c ∈ merge r (a :: l, l'), b ≼ c, begin intros c hc, rw mem_merge_iff at hc, exact or.elim hc (suppose c ∈ a :: l, or.elim (eq_or_mem_of_mem_cons this) (suppose c = a, show b ≼ c, from this^.symm ▸ ‹b ≼ a›) (suppose c ∈ l, show b ≼ c, from transr ‹b ≼ a› (h₁₀ c this))) (suppose c ∈ l', show b ≼ c, from h₂₀ c this) end, show sorted r (b :: merge r (a :: l, l')), from sorted_cons r h₃ h₄ end theorem sorted_merge : Π {p : list α × list α}, sorted r p.1 → sorted r p.2 → sorted r (merge p) := well_founded.fix (inv_image.wf _ nat.lt_wf) (sorted_merge.F totr transr) private def sorted_merge_sort.F : Π l : list α, (Π l₁ : list α, length l₁ < length l → sorted r (merge_sort l₁)) → sorted r (merge_sort l) | [] f := sorted_nil r | [a] f := sorted_singleton r a | (a :: b :: l) f := begin simp, apply sorted_merge r totr transr, admit, admit -- { apply f, exact length_split_cons_cons_fst_lt a b l }, -- apply f, exact length_split_cons_cons_snd_lt a b l end theorem sorted_merge_sort : ∀ l : list α, sorted r (merge_sort l) := well_founded.fix (inv_image.wf _ nat.lt_wf) (sorted_merge_sort.F totr transr) end total_and_transitive end correctness end merge_sort end sort /- try them out! -/ --vm_eval insertion_sort (λ m n : ℕ, m ≤ n) [5, 27, 221, 95, 17, 43, 7, 2, 98, 567, 23, 12] --vm_eval merge_sort (λ m n : ℕ, m ≤ n) [5, 27, 221, 95, 17, 43, 7, 2, 98, 567, 23, 12] end list
76c081191ab209be2879390642f03d229fdc6c57
4727251e0cd73359b15b664c3170e5d754078599
/src/data/real/sqrt.lean
6b2e10cf95d464db92759e477a63697b8506320f
[ "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
12,923
lean
/- Copyright (c) 2020 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Floris van Doorn, Yury Kudryashov -/ import topology.algebra.order.monotone_continuity import topology.instances.nnreal import tactic.norm_cast /-! # Square root of a real number In this file we define * `nnreal.sqrt` to be the square root of a nonnegative real number. * `real.sqrt` to be the square root of a real number, defined to be zero on negative numbers. Then we prove some basic properties of these functions. ## Implementation notes We define `nnreal.sqrt` as the noncomputable inverse to the function `x ↦ x * x`. We use general theory of inverses of strictly monotone functions to prove that `nnreal.sqrt x` exists. As a side effect, `nnreal.sqrt` is a bundled `order_iso`, so for `nnreal` numbers we get continuity as well as theorems like `sqrt x ≤ y ↔ x * x ≤ y` for free. Then we define `real.sqrt x` to be `nnreal.sqrt (real.to_nnreal x)`. We also define a Cauchy sequence `real.sqrt_aux (f : cau_seq ℚ abs)` which converges to `sqrt (mk f)` but do not prove (yet) that this sequence actually converges to `sqrt (mk f)`. ## Tags square root -/ open set filter open_locale filter nnreal topological_space namespace nnreal variables {x y : ℝ≥0} /-- Square root of a nonnegative real number. -/ @[pp_nodot] noncomputable def sqrt : ℝ≥0 ≃o ℝ≥0 := order_iso.symm $ strict_mono.order_iso_of_surjective (λ x, x * x) (λ x y h, mul_self_lt_mul_self x.2 h) $ (continuous_id.mul continuous_id).surjective tendsto_mul_self_at_top $ by simp [order_bot.at_bot_eq] lemma sqrt_le_sqrt_iff : sqrt x ≤ sqrt y ↔ x ≤ y := sqrt.le_iff_le lemma sqrt_lt_sqrt_iff : sqrt x < sqrt y ↔ x < y := sqrt.lt_iff_lt lemma sqrt_eq_iff_sq_eq : sqrt x = y ↔ y * y = x := sqrt.to_equiv.apply_eq_iff_eq_symm_apply.trans eq_comm lemma sqrt_le_iff : sqrt x ≤ y ↔ x ≤ y * y := sqrt.to_galois_connection _ _ lemma le_sqrt_iff : x ≤ sqrt y ↔ x * x ≤ y := (sqrt.symm.to_galois_connection _ _).symm @[simp] lemma sqrt_eq_zero : sqrt x = 0 ↔ x = 0 := sqrt_eq_iff_sq_eq.trans $ by rw [eq_comm, zero_mul] @[simp] lemma sqrt_zero : sqrt 0 = 0 := sqrt_eq_zero.2 rfl @[simp] lemma sqrt_one : sqrt 1 = 1 := sqrt_eq_iff_sq_eq.2 $ mul_one 1 @[simp] lemma mul_self_sqrt (x : ℝ≥0) : sqrt x * sqrt x = x := sqrt.symm_apply_apply x @[simp] lemma sqrt_mul_self (x : ℝ≥0) : sqrt (x * x) = x := sqrt.apply_symm_apply x @[simp] lemma sq_sqrt (x : ℝ≥0) : (sqrt x)^2 = x := by rw [sq, mul_self_sqrt x] @[simp] lemma sqrt_sq (x : ℝ≥0) : sqrt (x^2) = x := by rw [sq, sqrt_mul_self x] lemma sqrt_mul (x y : ℝ≥0) : sqrt (x * y) = sqrt x * sqrt y := by rw [sqrt_eq_iff_sq_eq, mul_mul_mul_comm, mul_self_sqrt, mul_self_sqrt] /-- `nnreal.sqrt` as a `monoid_with_zero_hom`. -/ noncomputable def sqrt_hom : ℝ≥0 →*₀ ℝ≥0 := ⟨sqrt, sqrt_zero, sqrt_one, sqrt_mul⟩ lemma sqrt_inv (x : ℝ≥0) : sqrt (x⁻¹) = (sqrt x)⁻¹ := sqrt_hom.map_inv x lemma sqrt_div (x y : ℝ≥0) : sqrt (x / y) = sqrt x / sqrt y := sqrt_hom.map_div x y lemma continuous_sqrt : continuous sqrt := sqrt.continuous end nnreal namespace real /-- An auxiliary sequence of rational numbers that converges to `real.sqrt (mk f)`. Currently this sequence is not used in `mathlib`. -/ def sqrt_aux (f : cau_seq ℚ abs) : ℕ → ℚ | 0 := rat.mk_nat (f 0).num.to_nat.sqrt (f 0).denom.sqrt | (n + 1) := let s := sqrt_aux n in max 0 $ (s + f (n+1) / s) / 2 theorem sqrt_aux_nonneg (f : cau_seq ℚ abs) : ∀ i : ℕ, 0 ≤ sqrt_aux f i | 0 := by rw [sqrt_aux, rat.mk_nat_eq, rat.mk_eq_div]; apply div_nonneg; exact int.cast_nonneg.2 (int.of_nat_nonneg _) | (n + 1) := le_max_left _ _ /- TODO(Mario): finish the proof theorem sqrt_aux_converges (f : cau_seq ℚ abs) : ∃ h x, 0 ≤ x ∧ x * x = max 0 (mk f) ∧ mk ⟨sqrt_aux f, h⟩ = x := begin rcases sqrt_exists (le_max_left 0 (mk f)) with ⟨x, x0, hx⟩, suffices : ∃ h, mk ⟨sqrt_aux f, h⟩ = x, { exact this.imp (λ h e, ⟨x, x0, hx, e⟩) }, apply of_near, suffices : ∃ δ > 0, ∀ i, abs (↑(sqrt_aux f i) - x) < δ / 2 ^ i, { rcases this with ⟨δ, δ0, hδ⟩, intros } end -/ /-- The square root of a real number. This returns 0 for negative inputs. -/ @[pp_nodot] noncomputable def sqrt (x : ℝ) : ℝ := nnreal.sqrt (real.to_nnreal x) /-quotient.lift_on x (λ f, mk ⟨sqrt_aux f, (sqrt_aux_converges f).fst⟩) (λ f g e, begin rcases sqrt_aux_converges f with ⟨hf, x, x0, xf, xs⟩, rcases sqrt_aux_converges g with ⟨hg, y, y0, yg, ys⟩, refine xs.trans (eq.trans _ ys.symm), rw [← @mul_self_inj_of_nonneg ℝ _ x y x0 y0, xf, yg], congr' 1, exact quotient.sound e end)-/ variables {x y : ℝ} @[simp, norm_cast] lemma coe_sqrt {x : ℝ≥0} : (nnreal.sqrt x : ℝ) = real.sqrt x := by rw [real.sqrt, real.to_nnreal_coe] @[continuity] lemma continuous_sqrt : continuous sqrt := nnreal.continuous_coe.comp $ nnreal.sqrt.continuous.comp continuous_real_to_nnreal theorem sqrt_eq_zero_of_nonpos (h : x ≤ 0) : sqrt x = 0 := by simp [sqrt, real.to_nnreal_eq_zero.2 h] theorem sqrt_nonneg (x : ℝ) : 0 ≤ sqrt x := nnreal.coe_nonneg _ @[simp] theorem mul_self_sqrt (h : 0 ≤ x) : sqrt x * sqrt x = x := by rw [sqrt, ← nnreal.coe_mul, nnreal.mul_self_sqrt, real.coe_to_nnreal _ h] @[simp] theorem sqrt_mul_self (h : 0 ≤ x) : sqrt (x * x) = x := (mul_self_inj_of_nonneg (sqrt_nonneg _) h).1 (mul_self_sqrt (mul_self_nonneg _)) theorem sqrt_eq_cases : sqrt x = y ↔ y * y = x ∧ 0 ≤ y ∨ x < 0 ∧ y = 0 := begin split, { rintro rfl, cases le_or_lt 0 x with hle hlt, { exact or.inl ⟨mul_self_sqrt hle, sqrt_nonneg x⟩ }, { exact or.inr ⟨hlt, sqrt_eq_zero_of_nonpos hlt.le⟩ } }, { rintro (⟨rfl, hy⟩|⟨hx, rfl⟩), exacts [sqrt_mul_self hy, sqrt_eq_zero_of_nonpos hx.le] } end theorem sqrt_eq_iff_mul_self_eq (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x = y ↔ y * y = x := ⟨λ h, by rw [← h, mul_self_sqrt hx], λ h, by rw [← h, sqrt_mul_self hy]⟩ theorem sqrt_eq_iff_mul_self_eq_of_pos (h : 0 < y) : sqrt x = y ↔ y * y = x := by simp [sqrt_eq_cases, h.ne', h.le] @[simp] lemma sqrt_eq_one : sqrt x = 1 ↔ x = 1 := calc sqrt x = 1 ↔ 1 * 1 = x : sqrt_eq_iff_mul_self_eq_of_pos zero_lt_one ... ↔ x = 1 : by rw [eq_comm, mul_one] @[simp] theorem sq_sqrt (h : 0 ≤ x) : (sqrt x)^2 = x := by rw [sq, mul_self_sqrt h] @[simp] theorem sqrt_sq (h : 0 ≤ x) : sqrt (x ^ 2) = x := by rw [sq, sqrt_mul_self h] theorem sqrt_eq_iff_sq_eq (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x = y ↔ y ^ 2 = x := by rw [sq, sqrt_eq_iff_mul_self_eq hx hy] theorem sqrt_mul_self_eq_abs (x : ℝ) : sqrt (x * x) = |x| := by rw [← abs_mul_abs_self x, sqrt_mul_self (abs_nonneg _)] theorem sqrt_sq_eq_abs (x : ℝ) : sqrt (x ^ 2) = |x| := by rw [sq, sqrt_mul_self_eq_abs] @[simp] theorem sqrt_zero : sqrt 0 = 0 := by simp [sqrt] @[simp] theorem sqrt_one : sqrt 1 = 1 := by simp [sqrt] @[simp] theorem sqrt_le_sqrt_iff (hy : 0 ≤ y) : sqrt x ≤ sqrt y ↔ x ≤ y := by rw [sqrt, sqrt, nnreal.coe_le_coe, nnreal.sqrt_le_sqrt_iff, real.to_nnreal_le_to_nnreal_iff hy] @[simp] theorem sqrt_lt_sqrt_iff (hx : 0 ≤ x) : sqrt x < sqrt y ↔ x < y := lt_iff_lt_of_le_iff_le (sqrt_le_sqrt_iff hx) theorem sqrt_lt_sqrt_iff_of_pos (hy : 0 < y) : sqrt x < sqrt y ↔ x < y := by rw [sqrt, sqrt, nnreal.coe_lt_coe, nnreal.sqrt_lt_sqrt_iff, to_nnreal_lt_to_nnreal_iff hy] theorem sqrt_le_sqrt (h : x ≤ y) : sqrt x ≤ sqrt y := by { rw [sqrt, sqrt, nnreal.coe_le_coe, nnreal.sqrt_le_sqrt_iff], exact to_nnreal_le_to_nnreal h } theorem sqrt_lt_sqrt (hx : 0 ≤ x) (h : x < y) : sqrt x < sqrt y := (sqrt_lt_sqrt_iff hx).2 h theorem sqrt_le_left (hy : 0 ≤ y) : sqrt x ≤ y ↔ x ≤ y ^ 2 := by rw [sqrt, ← real.le_to_nnreal_iff_coe_le hy, nnreal.sqrt_le_iff, ← real.to_nnreal_mul hy, real.to_nnreal_le_to_nnreal_iff (mul_self_nonneg y), sq] theorem sqrt_le_iff : sqrt x ≤ y ↔ 0 ≤ y ∧ x ≤ y ^ 2 := begin rw [← and_iff_right_of_imp (λ h, (sqrt_nonneg x).trans h), and.congr_right_iff], exact sqrt_le_left end lemma sqrt_lt (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x < y ↔ x < y ^ 2 := by rw [←sqrt_lt_sqrt_iff hx, sqrt_sq hy] lemma sqrt_lt' (hy : 0 < y) : sqrt x < y ↔ x < y ^ 2 := by rw [←sqrt_lt_sqrt_iff_of_pos (pow_pos hy _), sqrt_sq hy.le] /- note: if you want to conclude `x ≤ sqrt y`, then use `le_sqrt_of_sq_le`. if you have `x > 0`, consider using `le_sqrt'` -/ theorem le_sqrt (hx : 0 ≤ x) (hy : 0 ≤ y) : x ≤ sqrt y ↔ x ^ 2 ≤ y := le_iff_le_iff_lt_iff_lt.2 $ sqrt_lt hy hx lemma le_sqrt' (hx : 0 < x) : x ≤ sqrt y ↔ x ^ 2 ≤ y := le_iff_le_iff_lt_iff_lt.2 $ sqrt_lt' hx theorem abs_le_sqrt (h : x^2 ≤ y) : |x| ≤ sqrt y := by rw ← sqrt_sq_eq_abs; exact sqrt_le_sqrt h theorem sq_le (h : 0 ≤ y) : x^2 ≤ y ↔ -sqrt y ≤ x ∧ x ≤ sqrt y := begin split, { simpa only [abs_le] using abs_le_sqrt }, { rw [← abs_le, ← sq_abs], exact (le_sqrt (abs_nonneg x) h).mp }, end theorem neg_sqrt_le_of_sq_le (h : x^2 ≤ y) : -sqrt y ≤ x := ((sq_le ((sq_nonneg x).trans h)).mp h).1 theorem le_sqrt_of_sq_le (h : x^2 ≤ y) : x ≤ sqrt y := ((sq_le ((sq_nonneg x).trans h)).mp h).2 @[simp] theorem sqrt_inj (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x = sqrt y ↔ x = y := by simp [le_antisymm_iff, hx, hy] @[simp] theorem sqrt_eq_zero (h : 0 ≤ x) : sqrt x = 0 ↔ x = 0 := by simpa using sqrt_inj h le_rfl theorem sqrt_eq_zero' : sqrt x = 0 ↔ x ≤ 0 := by rw [sqrt, nnreal.coe_eq_zero, nnreal.sqrt_eq_zero, real.to_nnreal_eq_zero] theorem sqrt_ne_zero (h : 0 ≤ x) : sqrt x ≠ 0 ↔ x ≠ 0 := by rw [not_iff_not, sqrt_eq_zero h] theorem sqrt_ne_zero' : sqrt x ≠ 0 ↔ 0 < x := by rw [← not_le, not_iff_not, sqrt_eq_zero'] @[simp] theorem sqrt_pos : 0 < sqrt x ↔ 0 < x := lt_iff_lt_of_le_iff_le (iff.trans (by simp [le_antisymm_iff, sqrt_nonneg]) sqrt_eq_zero') @[simp] theorem sqrt_mul (hx : 0 ≤ x) (y : ℝ) : sqrt (x * y) = sqrt x * sqrt y := by simp_rw [sqrt, ← nnreal.coe_mul, nnreal.coe_eq, real.to_nnreal_mul hx, nnreal.sqrt_mul] @[simp] theorem sqrt_mul' (x) {y : ℝ} (hy : 0 ≤ y) : sqrt (x * y) = sqrt x * sqrt y := by rw [mul_comm, sqrt_mul hy, mul_comm] @[simp] theorem sqrt_inv (x : ℝ) : sqrt x⁻¹ = (sqrt x)⁻¹ := by rw [sqrt, real.to_nnreal_inv, nnreal.sqrt_inv, nnreal.coe_inv, sqrt] @[simp] theorem sqrt_div (hx : 0 ≤ x) (y : ℝ) : sqrt (x / y) = sqrt x / sqrt y := by rw [division_def, sqrt_mul hx, sqrt_inv, division_def] @[simp] theorem div_sqrt : x / sqrt x = sqrt x := begin cases le_or_lt x 0, { rw [sqrt_eq_zero'.mpr h, div_zero] }, { rw [div_eq_iff (sqrt_ne_zero'.mpr h), mul_self_sqrt h.le] }, end theorem sqrt_div_self' : sqrt x / x = 1 / sqrt x := by rw [←div_sqrt, one_div_div, div_sqrt] theorem sqrt_div_self : sqrt x / x = (sqrt x)⁻¹ := by rw [sqrt_div_self', one_div] lemma lt_sqrt (hx : 0 ≤ x) : x < sqrt y ↔ x ^ 2 < y := by rw [←sqrt_lt_sqrt_iff (sq_nonneg _), sqrt_sq hx] lemma sq_lt : x^2 < y ↔ -sqrt y < x ∧ x < sqrt y := by rw [←abs_lt, ←sq_abs, lt_sqrt (abs_nonneg _)] theorem neg_sqrt_lt_of_sq_lt (h : x^2 < y) : -sqrt y < x := (sq_lt.mp h).1 theorem lt_sqrt_of_sq_lt (h : x^2 < y) : x < sqrt y := (sq_lt.mp h).2 /-- The natural square root is at most the real square root -/ lemma nat_sqrt_le_real_sqrt {a : ℕ} : ↑(nat.sqrt a) ≤ real.sqrt ↑a := begin rw real.le_sqrt (nat.cast_nonneg _) (nat.cast_nonneg _), norm_cast, exact nat.sqrt_le' a, end /-- The real square root is at most the natural square root plus one -/ lemma real_sqrt_le_nat_sqrt_succ {a : ℕ} : real.sqrt ↑a ≤ nat.sqrt a + 1 := begin rw real.sqrt_le_iff, split, { norm_cast, simp, }, { norm_cast, exact le_of_lt (nat.lt_succ_sqrt' a), }, end instance : star_ordered_ring ℝ := { nonneg_iff := λ r, by { refine ⟨λ hr, ⟨sqrt r, show r = sqrt r * sqrt r, by rw [←sqrt_mul hr, sqrt_mul_self hr]⟩, _⟩, rintros ⟨s, rfl⟩, exact mul_self_nonneg s }, ..real.ordered_add_comm_group } end real open real variables {α : Type*} lemma filter.tendsto.sqrt {f : α → ℝ} {l : filter α} {x : ℝ} (h : tendsto f l (𝓝 x)) : tendsto (λ x, sqrt (f x)) l (𝓝 (sqrt x)) := (continuous_sqrt.tendsto _).comp h variables [topological_space α] {f : α → ℝ} {s : set α} {x : α} lemma continuous_within_at.sqrt (h : continuous_within_at f s x) : continuous_within_at (λ x, sqrt (f x)) s x := h.sqrt lemma continuous_at.sqrt (h : continuous_at f x) : continuous_at (λ x, sqrt (f x)) x := h.sqrt lemma continuous_on.sqrt (h : continuous_on f s) : continuous_on (λ x, sqrt (f x)) s := λ x hx, (h x hx).sqrt @[continuity] lemma continuous.sqrt (h : continuous f) : continuous (λ x, sqrt (f x)) := continuous_sqrt.comp h
8a90d8ad85bbcf2da12d893ae11a820563e70d70
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/mk_has_reflect_instance.lean
148a4a509fa5f37b7e6977adfd685ec27f8def4e
[]
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
408
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich Helper tactic for constructing a has_reflect instance. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.meta.rec_util namespace Mathlib namespace tactic /- Retrieve the name of the type we are building a has_reflect instance for. -/
0d5a258191d1f40cbb72f1c5d902a224017a2e7f
9e90bb7eb4d1bde1805f9eb6187c333fdf09588a
/src/stump/stump_pac_lemmas.lean
fffff9630047478a86fd4a0616fc130f7902fe7c
[ "Apache-2.0" ]
permissive
alexjbest/stump-learnable
6311d0c3a1a1a0e65ce83edcbb3b4b7cecabb851
f8fd812fc646d2ece312ff6ffc2a19848ac76032
refs/heads/master
1,659,486,805,691
1,590,454,024,000
1,590,454,024,000
266,173,720
0
0
Apache-2.0
1,590,169,884,000
1,590,169,883,000
null
UTF-8
Lean
false
false
4,823
lean
/- Copyright © 2019, Oracle and/or its affiliates. All rights reserved. -/ import .setup_properties import .algorithm_properties local attribute [instance] classical.prop_decidable open set open measure_theory open well_founded namespace stump variables (μ: probability_measure ℍ) (target: ℍ) (n: ℕ) lemma partition: ∀ θ, θ > 0 → {x : ℍ | ∀ (a: ℍ) (b: bool), (a,b) = label target x → ite b a 0 < θ} = - Icc θ target := begin introv h1, apply ext, intros, unfold Icc, unfold label, unfold rle, simp, split; intros, { simp at *, intros, by_contradiction, simp at a_2, have FOO:= a x tt _ _, { simp at FOO, have BAR: ¬ (θ ≤ x), simp, assumption, contradiction, }, trivial, tidy, }, { by_cases (b = tt), { rw h at *, simp, rw a_2, by_contradiction, simp at a_4, have INEQ1 := a a_4, have INEQ2: ¬ (x > target), {simp,tidy,}, contradiction, }, { simp at h, rw h at *, simp at *, tidy, }, }, end lemma miss_prob: ∀ ε, ∀ θ: nnreal, θ > 0 → μ (Icc θ target) ≥ ε → μ {x : ℍ | ∀ (a: ℍ) (b: bool), (a,b) = label target x → ite b a 0 < θ} ≤ 1 - ε:= begin intros, rw partition, have STO := probability_measure.prob_comp μ (Icc θ target) _, have SWAP: μ (- Icc θ target) = 1 - μ (Icc θ target), { exact lc_nnreal (μ (-Icc θ target)) (μ (Icc θ target)) STO, }, rw SWAP, { apply nnreal_sub_trans, assumption, }, { apply is_closed.is_measurable, apply is_closed_Icc, }, assumption, end lemma all_missed: ∀ ε: nnreal, ∀ θ: nnreal, μ (Ioc θ target) ≤ ε → {S: vec ℍ n | error μ target (choose n (label_sample target n S)) > ε} ⊆ {S: vec ℍ n | ∀ (i: dfin (nat.succ n)), ∀ p = label target (kth_projn S i), (if p.snd then p.fst else 0) < θ} := begin intros, conv { congr, congr, funext, rw (error_interval_1 μ target (choose n (label_sample target n S)) (choose_property_1 target n S)), skip, skip, }, rw set_of_subset_set_of, intros, have QENI: not (μ (Ioc (choose n (label_sample target n a_1)) target) ≤ μ (Ioc θ target)), { simp, have BREAK_LEQ: μ (Ioc θ target) < ε ∨ μ (Ioc θ target) = ε, { exact lt_or_eq_of_le a, }, cases BREAK_LEQ, transitivity ε; try {assumption,}, rw BREAK_LEQ, assumption, }, by_cases (p.snd = tt), { have PROP := choose_property_2 target n a_1 i p _ h, { rw h, simp, have INEQ1 := error_mono_interval μ target _ _ PROP _, by_contradiction, simp at a_3, have INEQ2 := error_mono_interval μ target _ _ a_3 _, have INEQ: μ (Ioc (choose n (label_sample target n a_1)) target) ≤ μ (Ioc θ target), { transitivity (μ (Ioc p.fst target)); try {assumption}, }, clear INEQ1 INEQ2, contradiction, apply choose_property_3; try {assumption}, { dunfold label_sample, rw ← kth_projn_map_comm, assumption, }, apply choose_property_1, }, { dunfold label_sample, rw ← kth_projn_map_comm, assumption, }, }, { simp at h, rw h, simp, have INEQ1': 0 ≤ choose n (label_sample target n a_1), { apply choose_property_4, }, have INEQ1 := error_mono_interval μ target _ _ INEQ1' _, clear INEQ1', by_contradiction, simp at a_3, have GEN: θ ≤ 0, { exact le_of_eq a_3, }, have INEQ2 := error_mono_interval μ target _ _ GEN _, clear GEN, have INEQ: μ (Ioc (choose n (label_sample target n a_1)) target) ≤ μ (Ioc θ target), { transitivity (μ (Ioc 0 target)); try {assumption}, }, clear INEQ1 INEQ2, contradiction, tidy, apply choose_property_1, }, end lemma always_succeed: ∀ ε: nnreal, ε > 0 → ∀ n: ℕ, μ (Ioc 0 target) ≤ ε → ∀ S: vec ℍ n, error μ target (choose n (label_sample target n S)) ≤ ε := begin intros, transitivity (μ (Ioc 0 target)); try {assumption}, have HypIN := choose_property_1 target n S, have ERMONO := error_mono μ _ 0 (choose n (label_sample target n S)) _ HypIN, rw ← error_max, assumption, tidy, end end stump
e768e39093f2565dee3bb732152b03336a750d1b
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/bicategory/functor_bicategory.lean
a626b310d3ced5326656eb3a8e25c778ed1909aa
[ "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
2,880
lean
/- Copyright (c) 2022 Yuma Mizuno. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yuma Mizuno -/ import category_theory.bicategory.natural_transformation /-! # The bicategory of oplax functors between two bicategories > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Given bicategories `B` and `C`, we give a bicategory structure on `oplax_functor B C` whose * objects are oplax functors, * 1-morphisms are oplax natural transformations, and * 2-morphisms are modifications. -/ namespace category_theory open category bicategory open_locale bicategory universes w₁ w₂ v₁ v₂ u₁ u₂ variables {B : Type u₁} [bicategory.{w₁ v₁} B] {C : Type u₂} [bicategory.{w₂ v₂} C] variables {F G H I : oplax_functor B C} namespace oplax_nat_trans /-- Left whiskering of an oplax natural transformation and a modification. -/ @[simps] def whisker_left (η : F ⟶ G) {θ ι : G ⟶ H} (Γ : θ ⟶ ι) : η ≫ θ ⟶ η ≫ ι := { app := λ a, η.app a ◁ Γ.app a, naturality' := λ a b f, by { dsimp, rw [associator_inv_naturality_right_assoc, whisker_exchange_assoc], simp } } /-- Right whiskering of an oplax natural transformation and a modification. -/ @[simps] def whisker_right {η θ : F ⟶ G} (Γ : η ⟶ θ) (ι : G ⟶ H) : η ≫ ι ⟶ θ ≫ ι := { app := λ a, Γ.app a ▷ ι.app a, naturality' := λ a b f, by { dsimp, simp_rw [assoc, ←associator_inv_naturality_left, whisker_exchange_assoc], simp } } /-- Associator for the vertical composition of oplax natural transformations. -/ @[simps] def associator (η : F ⟶ G) (θ : G ⟶ H) (ι : H ⟶ I) : (η ≫ θ) ≫ ι ≅ η ≫ (θ ≫ ι) := modification_iso.of_components (λ a, α_ (η.app a) (θ.app a) (ι.app a)) (by tidy) /-- Left unitor for the vertical composition of oplax natural transformations. -/ @[simps] def left_unitor (η : F ⟶ G) : 𝟙 F ≫ η ≅ η := modification_iso.of_components (λ a, λ_ (η.app a)) (by tidy) /-- Right unitor for the vertical composition of oplax natural transformations. -/ @[simps] def right_unitor (η : F ⟶ G) : η ≫ 𝟙 G ≅ η := modification_iso.of_components (λ a, ρ_ (η.app a)) (by tidy) end oplax_nat_trans variables (B C) /-- A bicategory structure on the oplax functors between bicategories. -/ @[simps] instance oplax_functor.bicategory : bicategory (oplax_functor B C) := { whisker_left := λ F G H η _ _ Γ, oplax_nat_trans.whisker_left η Γ, whisker_right := λ F G H _ _ Γ η, oplax_nat_trans.whisker_right Γ η, associator := λ F G H I, oplax_nat_trans.associator, left_unitor := λ F G, oplax_nat_trans.left_unitor, right_unitor := λ F G, oplax_nat_trans.right_unitor, whisker_exchange' := by { intros, ext, apply whisker_exchange } } end category_theory
fbdc77a7e72a8e66fc14998ef12079c503f47ddd
b00eb947a9c4141624aa8919e94ce6dcd249ed70
/src/Lean/Server/InfoUtils.lean
80b814a30e37777bd05ceb91665f9255d75fbded
[ "Apache-2.0" ]
permissive
gebner/lean4-old
a4129a041af2d4d12afb3a8d4deedabde727719b
ee51cdfaf63ee313c914d83264f91f414a0e3b6e
refs/heads/master
1,683,628,606,745
1,622,651,300,000
1,622,654,405,000
142,608,821
1
0
null
null
null
null
UTF-8
Lean
false
false
8,145
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 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.before | ofFieldInfo i => i.stx | ofCompletionInfo i => i.stx 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.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 => if let (some pos, some tailPos) := (i.pos?, i.tailPos?) then if pos ≤ hoverPos ∧ hoverPos < tailPos then match i with | Info.ofTermInfo ti => !ti.expr.isSyntheticSorry && -- TODO: see if we can get rid of this #[identKind, strLitKind, charLitKind, numLitKind, scientificLitKind, nameLitKind, fieldIdxKind, interpolatedStrLitKind, interpolatedStrKind ].contains i.stx.getKind | Info.ofFieldInfo _ => true | _ => false else false else 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 let lctx ← match i with | Info.ofTermInfo i => i.lctx | Info.ofFieldInfo i => i.lctx | _ => return none ci.runMetaM lctx do match i with | Info.ofTermInfo ti => let tp ← Meta.inferType ti.expr let eFmt ← Meta.ppExpr ti.expr let tpFmt ← Meta.ppExpr tp let hoverFmt := f!"```lean {eFmt} : {tpFmt} ```" if let some n := ti.expr.constName? then if let some doc ← findDocString? n then return f!"{hoverFmt}\n***\n{doc}" return hoverFmt | Info.ofFieldInfo fi => let tp ← Meta.inferType fi.val let tpFmt ← Meta.ppExpr tp return f!"```lean {fi.name} : {tpFmt} ```" | _ => return none 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 => if let (some pos, some tailPos) := (i.pos?, i.tailPos?) then if pos ≤ hoverPos ∧ hoverPos < tailPos then match i with | Info.ofTermInfo ti => !ti.stx.isIdent || !headFns.contains pos | _ => false else false else 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
7415ef8f8cd4adc4cc4ab9729b337cf9f7fcea0a
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/ring_theory/adjoin/power_basis.lean
8ccf1904103ad79a87e2914fc582fb91471d8508
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
2,156
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import ring_theory.adjoin.basic import ring_theory.power_basis /-! # Power basis for `algebra.adjoin R {x}` This file defines the canonical power basis on `algebra.adjoin R {x}`, where `x` is an integral element over `R`. -/ variables {K S : Type*} [field K] [comm_ring S] [algebra K S] namespace algebra open polynomial open power_basis open_locale big_operators /-- The elements `1, x, ..., x ^ (d - 1)` for a basis for the `K`-module `K[x]`, where `d` is the degree of the minimal polynomial of `x`. -/ noncomputable def adjoin.power_basis_aux {x : S} (hx : _root_.is_integral K x) : basis (fin (minpoly K x).nat_degree) K (adjoin K ({x} : set S)) := begin have hST : function.injective (algebra_map (adjoin K ({x} : set S)) S) := subtype.coe_injective, have hx' : _root_.is_integral K (show adjoin K ({x} : set S), from ⟨x, subset_adjoin (set.mem_singleton x)⟩), { apply (is_integral_algebra_map_iff hST).mp, convert hx, apply_instance }, have minpoly_eq := minpoly.eq_of_algebra_map_eq hST hx' rfl, apply @basis.mk (fin (minpoly K x).nat_degree) _ (adjoin K {x}) (λ i, ⟨x, subset_adjoin (set.mem_singleton x)⟩ ^ (i : ℕ)), { have := hx'.linear_independent_pow, rwa minpoly_eq at this }, { rw _root_.eq_top_iff, rintros ⟨y, hy⟩ _, have := hx'.mem_span_pow, rw minpoly_eq at this, apply this, { rw [adjoin_singleton_eq_range] at hy, obtain ⟨f, rfl⟩ := (aeval x).mem_range.mp hy, use f, ext, exact (is_scalar_tower.algebra_map_aeval K (adjoin K {x}) S ⟨x, _⟩ _).symm } } end /-- The power basis `1, x, ..., x ^ (d - 1)` for `K[x]`, where `d` is the degree of the minimal polynomial of `x`. -/ noncomputable def adjoin.power_basis {x : S} (hx : _root_.is_integral K x) : power_basis K (adjoin K ({x} : set S)) := { gen := ⟨x, subset_adjoin (set.mem_singleton x)⟩, dim := (minpoly K x).nat_degree, basis := adjoin.power_basis_aux hx, basis_eq_pow := basis.mk_apply _ _ } end algebra
dcb2ba987205d62500563f9daa328e3241f1642d
01ae0d022f2e2fefdaaa898938c1ac1fbce3b3ab
/categories/universal/initial.lean
6751ffd3275cf0c44a9acc29250da574d198cd7d
[]
no_license
PatrickMassot/lean-category-theory
0f56a83464396a253c28a42dece16c93baf8ad74
ef239978e91f2e1c3b8e88b6e9c64c155dc56c99
refs/heads/master
1,629,739,187,316
1,512,422,659,000
1,512,422,659,000
113,098,786
0
0
null
1,512,424,022,000
1,512,424,022,000
null
UTF-8
Lean
false
false
2,846
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan, Scott Morrison import ..isomorphism import ..functor_categories import ..opposites open categories open categories.isomorphism namespace categories.initial structure InitialObject ( C : Category ) := (initial_object : C.Obj) (morphism_from_initial_object_to : ∀ Y : C.Obj, C.Hom initial_object Y) (uniqueness_of_morphisms_from_initial_object : ∀ Y : C.Obj, ∀ f g : C.Hom initial_object Y, f = g) attribute [applicable] InitialObject.morphism_from_initial_object_to attribute [applicable,ematch] InitialObject.uniqueness_of_morphisms_from_initial_object instance InitialObject_coercion_to_object { C : Category } : has_coe (InitialObject C) (C.Obj) := { coe := InitialObject.initial_object } structure is_initial { C : Category } ( X : C.Obj ) := (morphism_from_initial_object_to : ∀ Y : C.Obj, C.Hom X Y) (uniqueness_of_morphisms_from_initial_object : ∀ Y : C.Obj, ∀ f : C.Hom X Y, f = morphism_from_initial_object_to Y) -- We can't mark this as applicable, because that might generate goals that an object is initial! attribute [ematch] is_initial.uniqueness_of_morphisms_from_initial_object lemma InitialObjects_are_unique { C : Category } ( X Y : InitialObject C ) : Isomorphism C X Y := ♯ structure TerminalObject ( C : Category ) := (terminal_object : C.Obj) (morphism_to_terminal_object_from : ∀ Y : C.Obj, C.Hom Y terminal_object) (uniqueness_of_morphisms_to_terminal_object : ∀ Y : C.Obj, ∀ f g : C.Hom Y terminal_object, f = g) attribute [applicable] TerminalObject.morphism_to_terminal_object_from attribute [applicable,ematch] TerminalObject.uniqueness_of_morphisms_to_terminal_object instance TerminalObject_coercion_to_object { C : Category } : has_coe (TerminalObject C) (C.Obj) := { coe := TerminalObject.terminal_object } structure is_terminal { C : Category } ( X : C.Obj ) := (morphism_to_terminal_object_from : ∀ Y : C.Obj, C.Hom Y X) (uniqueness_of_morphisms_to_terminal_object : ∀ Y : C.Obj, ∀ f : C.Hom Y X, f = morphism_to_terminal_object_from Y) attribute [ematch] is_terminal.uniqueness_of_morphisms_to_terminal_object lemma TerminalObjects_are_unique { C : Category } ( X Y : TerminalObject C ) : Isomorphism C X Y := ♯ class ZeroObject ( C : Category ) := (zero_object : C.Obj) (is_initial : is_initial zero_object) (is_terminal : is_terminal zero_object) definition ZeroObject.zero_morphism { C : Category } ( Z : ZeroObject C ) ( X Y : C.Obj ) : C.Hom X Y := C.compose (Z.is_terminal.morphism_to_terminal_object_from X) (Z.is_initial.morphism_from_initial_object_to Y) end categories.initial
cfa8474dfeb7da91df8e5d19bc2ab14637d357ad
1e3a43e8ba59c6fe1c66775b6e833e721eaf1675
/src/data/real/nnreal.lean
826e2bc27608c4bf4a7d3ae127ae36727ea7eb7b
[ "Apache-2.0" ]
permissive
Sterrs/mathlib
ea6910847b8dfd18500486de9ab0ee35704a3f52
d9327e433804004aa1dc65091bbe0de1e5a08c5e
refs/heads/master
1,650,769,884,257
1,587,808,694,000
1,587,808,694,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,037
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin Nonnegative real numbers. -/ import data.real.basic noncomputable theory open_locale classical /-- Nonnegative real numbers. -/ def nnreal := {r : ℝ // 0 ≤ r} localized "notation ` ℝ≥0 ` := nnreal" in nnreal namespace nnreal instance : has_coe ℝ≥0 ℝ := ⟨subtype.val⟩ /- Simp lemma to put back `n.val` into the normal form given by the coercion. -/ @[simp] lemma val_eq_coe (n : nnreal) : n.val = n := rfl instance : can_lift ℝ nnreal := { coe := coe, cond := λ r, r ≥ 0, prf := λ x hx, ⟨⟨x, hx⟩, rfl⟩ } protected lemma eq {n m : ℝ≥0} : (n : ℝ) = (m : ℝ) → n = m := subtype.eq protected lemma eq_iff {n m : ℝ≥0} : (n : ℝ) = (m : ℝ) ↔ n = m := iff.intro nnreal.eq (congr_arg coe) lemma ne_iff {x y : ℝ≥0} : (x : ℝ) ≠ (y : ℝ) ↔ x ≠ y := not_iff_not_of_iff $ nnreal.eq_iff protected def of_real (r : ℝ) : ℝ≥0 := ⟨max r 0, le_max_right _ _⟩ lemma coe_of_real (r : ℝ) (hr : 0 ≤ r) : (nnreal.of_real r : ℝ) = r := max_eq_left hr lemma le_coe_of_real (r : ℝ) : r ≤ nnreal.of_real r := le_max_left r 0 lemma coe_nonneg (r : nnreal) : (0 : ℝ) ≤ r := r.2 @[norm_cast] theorem coe_mk (a : ℝ) (ha) : ((⟨a, ha⟩ : ℝ≥0) : ℝ) = a := rfl instance : has_zero ℝ≥0 := ⟨⟨0, le_refl 0⟩⟩ instance : has_one ℝ≥0 := ⟨⟨1, zero_le_one⟩⟩ instance : has_add ℝ≥0 := ⟨λa b, ⟨a + b, add_nonneg a.2 b.2⟩⟩ instance : has_sub ℝ≥0 := ⟨λa b, nnreal.of_real (a - b)⟩ instance : has_mul ℝ≥0 := ⟨λa b, ⟨a * b, mul_nonneg a.2 b.2⟩⟩ instance : has_inv ℝ≥0 := ⟨λa, ⟨(a.1)⁻¹, inv_nonneg.2 a.2⟩⟩ instance : has_div ℝ≥0 := ⟨λa b, ⟨a.1 / b.1, div_nonneg' a.2 b.2⟩⟩ instance : has_le ℝ≥0 := ⟨λ r s, (r:ℝ) ≤ s⟩ instance : has_bot ℝ≥0 := ⟨0⟩ instance : inhabited ℝ≥0 := ⟨0⟩ @[simp, norm_cast] protected lemma coe_eq {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) = r₂ ↔ r₁ = r₂ := subtype.ext.symm @[simp, norm_cast] protected lemma coe_zero : ((0 : ℝ≥0) : ℝ) = 0 := rfl @[simp, norm_cast] protected lemma coe_one : ((1 : ℝ≥0) : ℝ) = 1 := rfl @[simp, norm_cast] protected lemma coe_add (r₁ r₂ : ℝ≥0) : ((r₁ + r₂ : ℝ≥0) : ℝ) = r₁ + r₂ := rfl @[simp, norm_cast] protected lemma coe_mul (r₁ r₂ : ℝ≥0) : ((r₁ * r₂ : ℝ≥0) : ℝ) = r₁ * r₂ := rfl @[simp, norm_cast] protected lemma coe_div (r₁ r₂ : ℝ≥0) : ((r₁ / r₂ : ℝ≥0) : ℝ) = r₁ / r₂ := rfl @[simp, norm_cast] protected lemma coe_inv (r : ℝ≥0) : ((r⁻¹ : ℝ≥0) : ℝ) = r⁻¹ := rfl @[simp, norm_cast] protected lemma coe_bit0 (r : ℝ≥0) : ((bit0 r : ℝ≥0) : ℝ) = bit0 r := by unfold bit0; norm_cast @[simp, norm_cast] protected lemma coe_bit1 (r : ℝ≥0) : ((bit1 r : ℝ≥0) : ℝ) = bit1 r := by unfold bit1; norm_cast @[simp, norm_cast] protected lemma coe_sub {r₁ r₂ : ℝ≥0} (h : r₂ ≤ r₁) : ((r₁ - r₂ : ℝ≥0) : ℝ) = r₁ - r₂ := max_eq_left $ le_sub.2 $ by simp [show (r₂ : ℝ) ≤ r₁, from h] -- TODO: setup semifield! @[simp] protected lemma zero_div (r : ℝ≥0) : 0 / r = 0 := nnreal.eq (zero_div _) @[simp] protected lemma coe_eq_zero (r : ℝ≥0) : ↑r = (0 : ℝ) ↔ r = 0 := by norm_cast lemma coe_ne_zero {r : ℝ≥0} : (r : ℝ) ≠ 0 ↔ r ≠ 0 := by norm_cast instance : comm_semiring ℝ≥0 := begin refine { zero := 0, add := (+), one := 1, mul := (*), ..}; { intros; apply nnreal.eq; simp [mul_comm, mul_assoc, add_comm_monoid.add, left_distrib, right_distrib, add_comm_monoid.zero, add_comm, add_left_comm] } end instance : is_semiring_hom (coe : ℝ≥0 → ℝ) := by refine_struct {..}; intros; refl instance : comm_group_with_zero ℝ≥0 := { zero_ne_one := assume h, zero_ne_one $ nnreal.eq_iff.2 h, inv_zero := nnreal.eq $ inv_zero, mul_inv_cancel := assume x h, nnreal.eq $ mul_inv_cancel $ ne_iff.2 h, .. (by apply_instance : has_inv ℝ≥0), .. (_ : comm_semiring ℝ≥0), .. (_ : semiring ℝ≥0) } @[norm_cast] lemma coe_pow (r : ℝ≥0) (n : ℕ) : ((r^n : ℝ≥0) : ℝ) = r^n := is_monoid_hom.map_pow coe r n @[norm_cast] lemma coe_list_sum (l : list ℝ≥0) : ((l.sum : ℝ≥0) : ℝ) = (l.map coe).sum := eq.symm $ l.sum_hom coe @[norm_cast] lemma coe_list_prod (l : list ℝ≥0) : ((l.prod : ℝ≥0) : ℝ) = (l.map coe).prod := eq.symm $ l.prod_hom coe @[norm_cast] lemma coe_multiset_sum (s : multiset ℝ≥0) : ((s.sum : ℝ≥0) : ℝ) = (s.map coe).sum := eq.symm $ s.sum_hom coe @[norm_cast] lemma coe_multiset_prod (s : multiset ℝ≥0) : ((s.prod : ℝ≥0) : ℝ) = (s.map coe).prod := eq.symm $ s.prod_hom coe @[norm_cast] lemma coe_sum {α} {s : finset α} {f : α → ℝ≥0} : ↑(s.sum f) = s.sum (λa, (f a : ℝ)) := eq.symm $ s.sum_hom coe @[norm_cast] lemma coe_prod {α} {s : finset α} {f : α → ℝ≥0} : ↑(s.prod f) = s.prod (λa, (f a : ℝ)) := eq.symm $ s.prod_hom coe @[norm_cast] lemma smul_coe (r : ℝ≥0) (n : ℕ) : ↑(add_monoid.smul n r) = add_monoid.smul n (r:ℝ) := is_add_monoid_hom.map_smul coe r n @[simp, norm_cast] protected lemma coe_nat_cast (n : ℕ) : (↑(↑n : ℝ≥0) : ℝ) = n := (ring_hom.of (coe : ℝ≥0 → ℝ)).map_nat_cast n instance : decidable_linear_order ℝ≥0 := decidable_linear_order.lift (coe : ℝ≥0 → ℝ) subtype.val_injective (by apply_instance) @[norm_cast] protected lemma coe_le_coe {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) ≤ r₂ ↔ r₁ ≤ r₂ := iff.rfl @[norm_cast] protected lemma coe_lt_coe {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) < r₂ ↔ r₁ < r₂ := iff.rfl protected lemma coe_pos {r : ℝ≥0} : (0 : ℝ) < r ↔ 0 < r := iff.rfl protected lemma coe_mono : monotone (coe : ℝ≥0 → ℝ) := λ _ _, nnreal.coe_le_coe.2 protected lemma of_real_mono : monotone nnreal.of_real := λ x y h, max_le_max h (le_refl 0) @[simp] lemma of_real_coe {r : ℝ≥0} : nnreal.of_real r = r := nnreal.eq $ max_eq_left r.2 /-- `nnreal.of_real` and `coe : ℝ≥0 → ℝ` form a Galois insertion. -/ protected def gi : galois_insertion nnreal.of_real coe := galois_insertion.monotone_intro nnreal.coe_mono nnreal.of_real_mono le_coe_of_real (λ _, of_real_coe) instance : order_bot ℝ≥0 := { bot := ⊥, bot_le := assume ⟨a, h⟩, h, .. nnreal.decidable_linear_order } instance : canonically_ordered_add_monoid ℝ≥0 := { add_le_add_left := assume a b h c, @add_le_add_left ℝ _ a b h c, lt_of_add_lt_add_left := assume a b c, @lt_of_add_lt_add_left ℝ _ a b c, le_iff_exists_add := assume ⟨a, ha⟩ ⟨b, hb⟩, iff.intro (assume h : a ≤ b, ⟨⟨b - a, le_sub_iff_add_le.2 $ by simp [h]⟩, nnreal.eq $ show b = a + (b - a), by rw [add_sub_cancel'_right]⟩) (assume ⟨⟨c, hc⟩, eq⟩, eq.symm ▸ show a ≤ a + c, from (le_add_iff_nonneg_right a).2 hc), ..nnreal.comm_semiring, ..nnreal.order_bot, ..nnreal.decidable_linear_order } instance : distrib_lattice ℝ≥0 := by apply_instance instance : semilattice_inf_bot ℝ≥0 := { .. nnreal.order_bot, .. nnreal.distrib_lattice } instance : semilattice_sup_bot ℝ≥0 := { .. nnreal.order_bot, .. nnreal.distrib_lattice } instance : linear_ordered_semiring ℝ≥0 := { add_left_cancel := assume a b c h, nnreal.eq $ @add_left_cancel ℝ _ a b c (nnreal.eq_iff.2 h), add_right_cancel := assume a b c h, nnreal.eq $ @add_right_cancel ℝ _ a b c (nnreal.eq_iff.2 h), le_of_add_le_add_left := assume a b c, @le_of_add_le_add_left ℝ _ a b c, mul_lt_mul_of_pos_left := assume a b c, @mul_lt_mul_of_pos_left ℝ _ a b c, mul_lt_mul_of_pos_right := assume a b c, @mul_lt_mul_of_pos_right ℝ _ a b c, zero_lt_one := @zero_lt_one ℝ _, .. nnreal.decidable_linear_order, .. nnreal.canonically_ordered_add_monoid, .. nnreal.comm_semiring } instance : canonically_ordered_comm_semiring ℝ≥0 := { zero_ne_one := assume h, @zero_ne_one ℝ _ $ congr_arg subtype.val $ h, mul_eq_zero_iff := assume a b, nnreal.eq_iff.symm.trans $ mul_eq_zero.trans $ by simp, .. nnreal.linear_ordered_semiring, .. nnreal.canonically_ordered_add_monoid, .. nnreal.comm_semiring } instance : densely_ordered ℝ≥0 := ⟨assume a b (h : (a : ℝ) < b), let ⟨c, hac, hcb⟩ := dense h in ⟨⟨c, le_trans a.property $ le_of_lt $ hac⟩, hac, hcb⟩⟩ instance : no_top_order ℝ≥0 := ⟨assume a, let ⟨b, hb⟩ := no_top (a:ℝ) in ⟨⟨b, le_trans a.property $ le_of_lt $ hb⟩, hb⟩⟩ lemma bdd_above_coe {s : set ℝ≥0} : bdd_above ((coe : nnreal → ℝ) '' s) ↔ bdd_above s := iff.intro (assume ⟨b, hb⟩, ⟨nnreal.of_real b, assume ⟨y, hy⟩ hys, show y ≤ max b 0, from le_max_left_of_le $ hb $ set.mem_image_of_mem _ hys⟩) (assume ⟨b, hb⟩, ⟨b, assume y ⟨x, hx, eq⟩, eq ▸ hb hx⟩) lemma bdd_below_coe (s : set ℝ≥0) : bdd_below ((coe : nnreal → ℝ) '' s) := ⟨0, assume r ⟨q, _, eq⟩, eq ▸ q.2⟩ instance : has_Sup ℝ≥0 := ⟨λs, ⟨Sup ((coe : nnreal → ℝ) '' s), begin cases s.eq_empty_or_nonempty with h h, { simp [h, set.image_empty, real.Sup_empty] }, rcases h with ⟨⟨b, hb⟩, hbs⟩, by_cases h' : bdd_above s, { exact le_cSup_of_le (bdd_above_coe.2 h') (set.mem_image_of_mem _ hbs) hb }, { rw [real.Sup_of_not_bdd_above], rwa [bdd_above_coe] } end⟩⟩ instance : has_Inf ℝ≥0 := ⟨λs, ⟨Inf ((coe : nnreal → ℝ) '' s), begin cases s.eq_empty_or_nonempty with h h, { simp [h, set.image_empty, real.Inf_empty] }, exact le_cInf (h.image _) (assume r ⟨q, _, eq⟩, eq ▸ q.2) end⟩⟩ lemma coe_Sup (s : set nnreal) : (↑(Sup s) : ℝ) = Sup ((coe : nnreal → ℝ) '' s) := rfl lemma coe_Inf (s : set nnreal) : (↑(Inf s) : ℝ) = Inf ((coe : nnreal → ℝ) '' s) := rfl instance : conditionally_complete_linear_order_bot ℝ≥0 := { Sup := Sup, Inf := Inf, le_cSup := assume s a hs ha, le_cSup (bdd_above_coe.2 hs) (set.mem_image_of_mem _ ha), cSup_le := assume s a hs h,show Sup ((coe : nnreal → ℝ) '' s) ≤ a, from cSup_le (by simp [hs]) $ assume r ⟨b, hb, eq⟩, eq ▸ h hb, cInf_le := assume s a _ has, cInf_le (bdd_below_coe s) (set.mem_image_of_mem _ has), le_cInf := assume s a hs h, show (↑a : ℝ) ≤ Inf ((coe : nnreal → ℝ) '' s), from le_cInf (by simp [hs]) $ assume r ⟨b, hb, eq⟩, eq ▸ h hb, cSup_empty := nnreal.eq $ by simp [coe_Sup, real.Sup_empty]; refl, decidable_le := begin assume x y, apply classical.dec end, .. nnreal.linear_ordered_semiring, .. lattice_of_decidable_linear_order, .. nnreal.order_bot } instance : archimedean nnreal := ⟨ assume x y pos_y, let ⟨n, hr⟩ := archimedean.arch (x:ℝ) (pos_y : (0 : ℝ) < y) in ⟨n, show (x:ℝ) ≤ (add_monoid.smul n y : nnreal), by simp [*, smul_coe]⟩ ⟩ lemma le_of_forall_epsilon_le {a b : nnreal} (h : ∀ε, ε > 0 → a ≤ b + ε) : a ≤ b := le_of_forall_le_of_dense $ assume x hxb, begin rcases le_iff_exists_add.1 (le_of_lt hxb) with ⟨ε, rfl⟩, exact h _ ((lt_add_iff_pos_right b).1 hxb) end lemma lt_iff_exists_rat_btwn (a b : nnreal) : a < b ↔ (∃q:ℚ, 0 ≤ q ∧ a < nnreal.of_real q ∧ nnreal.of_real q < b) := iff.intro (assume (h : (↑a:ℝ) < (↑b:ℝ)), let ⟨q, haq, hqb⟩ := exists_rat_btwn h in have 0 ≤ (q : ℝ), from le_trans a.2 $ le_of_lt haq, ⟨q, rat.cast_nonneg.1 this, by simp [coe_of_real _ this, nnreal.coe_lt_coe.symm, haq, hqb]⟩) (assume ⟨q, _, haq, hqb⟩, lt_trans haq hqb) lemma bot_eq_zero : (⊥ : nnreal) = 0 := rfl lemma mul_sup (a b c : ℝ≥0) : a * (b ⊔ c) = (a * b) ⊔ (a * c) := begin cases le_total b c with h h, { simp [sup_eq_max, max_eq_right h, max_eq_right (mul_le_mul_of_nonneg_left h (zero_le a))] }, { simp [sup_eq_max, max_eq_left h, max_eq_left (mul_le_mul_of_nonneg_left h (zero_le a))] }, end lemma mul_finset_sup {α} {f : α → ℝ≥0} {s : finset α} (r : ℝ≥0) : r * s.sup f = s.sup (λa, r * f a) := begin refine s.induction_on _ _, { simp [bot_eq_zero] }, { assume a s has ih, simp [has, ih, mul_sup], } end @[simp, norm_cast] lemma coe_max (x y : nnreal) : ((max x y : nnreal) : ℝ) = max (x : ℝ) (y : ℝ) := by { delta max, split_ifs; refl } @[simp, norm_cast] lemma coe_min (x y : nnreal) : ((min x y : nnreal) : ℝ) = min (x : ℝ) (y : ℝ) := by { delta min, split_ifs; refl } section of_real @[simp] lemma zero_le_coe {q : nnreal} : 0 ≤ (q : ℝ) := q.2 @[simp] lemma of_real_zero : nnreal.of_real 0 = 0 := by simp [nnreal.of_real]; refl @[simp] lemma of_real_one : nnreal.of_real 1 = 1 := by simp [nnreal.of_real, max_eq_left (zero_le_one : (0 :ℝ) ≤ 1)]; refl @[simp] lemma of_real_pos {r : ℝ} : 0 < nnreal.of_real r ↔ 0 < r := by simp [nnreal.of_real, nnreal.coe_lt_coe.symm, lt_irrefl] @[simp] lemma of_real_eq_zero {r : ℝ} : nnreal.of_real r = 0 ↔ r ≤ 0 := by simpa [-of_real_pos] using (not_iff_not.2 (@of_real_pos r)) lemma of_real_of_nonpos {r : ℝ} : r ≤ 0 → nnreal.of_real r = 0 := of_real_eq_zero.2 @[simp] lemma of_real_le_of_real_iff {r p : ℝ} (hp : 0 ≤ p) : nnreal.of_real r ≤ nnreal.of_real p ↔ r ≤ p := by simp [nnreal.coe_le_coe.symm, nnreal.of_real, hp] @[simp] lemma of_real_lt_of_real_iff' {r p : ℝ} : nnreal.of_real r < nnreal.of_real p ↔ r < p ∧ 0 < p := by simp [nnreal.coe_lt_coe.symm, nnreal.of_real, lt_irrefl] lemma of_real_lt_of_real_iff {r p : ℝ} (h : 0 < p) : nnreal.of_real r < nnreal.of_real p ↔ r < p := of_real_lt_of_real_iff'.trans (and_iff_left h) lemma of_real_lt_of_real_iff_of_nonneg {r p : ℝ} (hr : 0 ≤ r) : nnreal.of_real r < nnreal.of_real p ↔ r < p := of_real_lt_of_real_iff'.trans ⟨and.left, λ h, ⟨h, lt_of_le_of_lt hr h⟩⟩ @[simp] lemma of_real_add {r p : ℝ} (hr : 0 ≤ r) (hp : 0 ≤ p) : nnreal.of_real (r + p) = nnreal.of_real r + nnreal.of_real p := nnreal.eq $ by simp [nnreal.of_real, hr, hp, add_nonneg] lemma of_real_add_of_real {r p : ℝ} (hr : 0 ≤ r) (hp : 0 ≤ p) : nnreal.of_real r + nnreal.of_real p = nnreal.of_real (r + p) := (of_real_add hr hp).symm lemma of_real_le_of_real {r p : ℝ} (h : r ≤ p) : nnreal.of_real r ≤ nnreal.of_real p := nnreal.of_real_mono h lemma of_real_add_le {r p : ℝ} : nnreal.of_real (r + p) ≤ nnreal.of_real r + nnreal.of_real p := nnreal.coe_le_coe.1 $ max_le (add_le_add (le_max_left _ _) (le_max_left _ _)) nnreal.zero_le_coe lemma of_real_le_iff_le_coe {r : ℝ} {p : nnreal} : nnreal.of_real r ≤ p ↔ r ≤ ↑p := nnreal.gi.gc r p lemma le_of_real_iff_coe_le {r : nnreal} {p : ℝ} (hp : p ≥ 0) : r ≤ nnreal.of_real p ↔ ↑r ≤ p := by rw [← nnreal.coe_le_coe, nnreal.coe_of_real p hp] lemma of_real_lt_iff_lt_coe {r : ℝ} {p : nnreal} (ha : r ≥ 0) : nnreal.of_real r < p ↔ r < ↑p := by rw [← nnreal.coe_lt_coe, nnreal.coe_of_real r ha] lemma lt_of_real_iff_coe_lt {r : nnreal} {p : ℝ} : r < nnreal.of_real p ↔ ↑r < p := begin cases le_total 0 p, { rw [← nnreal.coe_lt_coe, nnreal.coe_of_real p h] }, { rw [of_real_eq_zero.2 h], split, intro, have := not_lt_of_le (zero_le r), contradiction, intro rp, have : ¬(p ≤ 0) := not_le_of_lt (lt_of_le_of_lt (coe_nonneg _) rp), contradiction } end end of_real section mul lemma mul_eq_mul_left {a b c : nnreal} (h : a ≠ 0) : (a * b = a * c ↔ b = c) := begin rw [← nnreal.eq_iff, ← nnreal.eq_iff, nnreal.coe_mul, nnreal.coe_mul], split, { exact eq_of_mul_eq_mul_left (mt (@nnreal.eq_iff a 0).1 h) }, { assume h, rw [h] } end lemma of_real_mul {p q : ℝ} (hp : 0 ≤ p) : nnreal.of_real (p * q) = nnreal.of_real p * nnreal.of_real q := begin cases le_total 0 q with hq hq, { apply nnreal.eq, have := max_eq_left (mul_nonneg hp hq), simpa [nnreal.of_real, hp, hq, max_eq_left] }, { have hpq := mul_nonpos_of_nonneg_of_nonpos hp hq, rw [of_real_eq_zero.2 hq, of_real_eq_zero.2 hpq, mul_zero] } end @[field_simps] theorem mul_ne_zero' {a b : nnreal} (h₁ : a ≠ 0) (h₂ : b ≠ 0) : a * b ≠ 0 := mul_ne_zero'' h₁ h₂ end mul section sub lemma sub_def {r p : ℝ≥0} : r - p = nnreal.of_real (r - p) := rfl lemma sub_eq_zero {r p : ℝ≥0} (h : r ≤ p) : r - p = 0 := nnreal.eq $ max_eq_right $ sub_le_iff_le_add.2 $ by simpa [nnreal.coe_le_coe] using h @[simp] lemma sub_self {r : ℝ≥0} : r - r = 0 := sub_eq_zero $ le_refl r @[simp] lemma sub_zero {r : ℝ≥0} : r - 0 = r := by rw [sub_def, nnreal.coe_zero, sub_zero, nnreal.of_real_coe] lemma sub_pos {r p : ℝ≥0} : 0 < r - p ↔ p < r := of_real_pos.trans $ sub_pos.trans $ nnreal.coe_lt_coe protected lemma sub_lt_self {r p : nnreal} : 0 < r → 0 < p → r - p < r := assume hr hp, begin cases le_total r p, { rwa [sub_eq_zero h] }, { rw [← nnreal.coe_lt_coe, nnreal.coe_sub h], exact sub_lt_self _ hp } end @[simp] lemma sub_le_iff_le_add {r p q : nnreal} : r - p ≤ q ↔ r ≤ q + p := match le_total p r with | or.inl h := by rw [← nnreal.coe_le_coe, ← nnreal.coe_le_coe, nnreal.coe_sub h, nnreal.coe_add, sub_le_iff_le_add] | or.inr h := have r ≤ p + q, from le_add_right h, by simpa [nnreal.coe_le_coe, nnreal.coe_le_coe, sub_eq_zero h, add_comm] end @[simp] lemma sub_le_self {r p : ℝ≥0} : r - p ≤ r := sub_le_iff_le_add.2 $ le_add_right $ le_refl r lemma add_sub_cancel {r p : nnreal} : (p + r) - r = p := nnreal.eq $ by rw [nnreal.coe_sub, nnreal.coe_add, add_sub_cancel]; exact le_add_left (le_refl _) lemma add_sub_cancel' {r p : nnreal} : (r + p) - r = p := by rw [add_comm, add_sub_cancel] @[simp] lemma sub_add_cancel_of_le {a b : nnreal} (h : b ≤ a) : (a - b) + b = a := nnreal.eq $ by rw [nnreal.coe_add, nnreal.coe_sub h, sub_add_cancel] lemma sub_sub_cancel_of_le {r p : ℝ≥0} (h : r ≤ p) : p - (p - r) = r := by rw [nnreal.sub_def, nnreal.sub_def, nnreal.coe_of_real _ $ sub_nonneg.2 h, sub_sub_cancel, nnreal.of_real_coe] lemma lt_sub_iff_add_lt {p q r : nnreal} : p < q - r ↔ p + r < q := begin split, { assume H, have : (((q - r) : nnreal) : ℝ) = (q : ℝ) - (r : ℝ) := nnreal.coe_sub (le_of_lt (sub_pos.1 (lt_of_le_of_lt (zero_le _) H))), rwa [← nnreal.coe_lt_coe, this, lt_sub_iff_add_lt, ← nnreal.coe_add] at H }, { assume H, have : r ≤ q := le_trans (le_add_left (le_refl _)) (le_of_lt H), rwa [← nnreal.coe_lt_coe, nnreal.coe_sub this, lt_sub_iff_add_lt, ← nnreal.coe_add] } end end sub section inv lemma div_def {r p : nnreal} : r / p = r * p⁻¹ := rfl @[simp] lemma inv_zero : (0 : nnreal)⁻¹ = 0 := nnreal.eq inv_zero @[simp] lemma inv_eq_zero {r : nnreal} : (r : nnreal)⁻¹ = 0 ↔ r = 0 := inv_eq_zero @[simp] lemma inv_pos {r : nnreal} : 0 < r⁻¹ ↔ 0 < r := by simp [zero_lt_iff_ne_zero] lemma div_pos {r p : ℝ≥0} (hr : 0 < r) (hp : 0 < p) : 0 < r / p := mul_pos hr (inv_pos.2 hp) @[simp] lemma inv_one : (1:ℝ≥0)⁻¹ = 1 := nnreal.eq $ inv_one @[simp] lemma div_one {r : ℝ≥0} : r / 1 = r := by rw [div_def, inv_one, mul_one] protected lemma mul_inv {r p : ℝ≥0} : (r * p)⁻¹ = p⁻¹ * r⁻¹ := nnreal.eq $ mul_inv' _ _ protected lemma inv_pow {r : ℝ≥0} {n : ℕ} : (r^n)⁻¹ = (r⁻¹)^n := nnreal.eq $ by { push_cast, exact (inv_pow' _ _).symm } @[simp] lemma inv_mul_cancel {r : ℝ≥0} (h : r ≠ 0) : r⁻¹ * r = 1 := nnreal.eq $ inv_mul_cancel $ mt (@nnreal.eq_iff r 0).1 h @[simp] lemma mul_inv_cancel {r : ℝ≥0} (h : r ≠ 0) : r * r⁻¹ = 1 := by rw [mul_comm, inv_mul_cancel h] @[simp] lemma div_self {r : ℝ≥0} (h : r ≠ 0) : r / r = 1 := mul_inv_cancel h @[simp] lemma div_mul_cancel {r p : ℝ≥0} (h : p ≠ 0) : r / p * p = r := by rw [div_def, mul_assoc, inv_mul_cancel h, mul_one] @[simp] lemma mul_div_cancel {r p : ℝ≥0} (h : p ≠ 0) : r * p / p = r := by rw [div_def, mul_assoc, mul_inv_cancel h, mul_one] @[simp] lemma mul_div_cancel' {r p : ℝ≥0} (h : r ≠ 0) : r * (p / r) = p := by rw [mul_comm, div_mul_cancel h] @[simp] lemma inv_inv {r : ℝ≥0} : r⁻¹⁻¹ = r := nnreal.eq (inv_inv' _) @[simp] lemma inv_le {r p : ℝ≥0} (h : r ≠ 0) : r⁻¹ ≤ p ↔ 1 ≤ r * p := by rw [← mul_le_mul_left (zero_lt_iff_ne_zero.2 h), mul_inv_cancel h] lemma inv_le_of_le_mul {r p : ℝ≥0} (h : 1 ≤ r * p) : r⁻¹ ≤ p := by by_cases r = 0; simp [*, inv_le] @[simp] lemma le_inv_iff_mul_le {r p : ℝ≥0} (h : p ≠ 0) : (r ≤ p⁻¹ ↔ r * p ≤ 1) := by rw [← mul_le_mul_left (zero_lt_iff_ne_zero.2 h), mul_inv_cancel h, mul_comm] @[simp] lemma lt_inv_iff_mul_lt {r p : ℝ≥0} (h : p ≠ 0) : (r < p⁻¹ ↔ r * p < 1) := by rw [← mul_lt_mul_left (zero_lt_iff_ne_zero.2 h), mul_inv_cancel h, mul_comm] lemma mul_le_iff_le_inv {a b r : ℝ≥0} (hr : r ≠ 0) : r * a ≤ b ↔ a ≤ r⁻¹ * b := have 0 < r, from lt_of_le_of_ne (zero_le r) hr.symm, by rw [← @mul_le_mul_left _ _ a _ r this, ← mul_assoc, mul_inv_cancel hr, one_mul] lemma le_div_iff_mul_le {a b r : ℝ≥0} (hr : r ≠ 0) : a ≤ b / r ↔ a * r ≤ b := by rw [div_def, mul_comm, ← mul_le_iff_le_inv hr, mul_comm] lemma le_of_forall_lt_one_mul_lt {x y : ℝ≥0} (h : ∀a<1, a * x ≤ y) : x ≤ y := le_of_forall_ge_of_dense $ assume a ha, have hx : x ≠ 0 := zero_lt_iff_ne_zero.1 (lt_of_le_of_lt (zero_le _) ha), have hx' : x⁻¹ ≠ 0, by rwa [(≠), inv_eq_zero], have a * x⁻¹ < 1, by rwa [← lt_inv_iff_mul_lt hx', inv_inv], have (a * x⁻¹) * x ≤ y, from h _ this, by rwa [mul_assoc, inv_mul_cancel hx, mul_one] at this lemma div_add_div_same (a b c : ℝ≥0) : a / c + b / c = (a + b) / c := eq.symm $ right_distrib a b (c⁻¹) lemma half_pos {a : ℝ≥0} (h : 0 < a) : 0 < a / 2 := div_pos h zero_lt_two lemma add_halves (a : ℝ≥0) : a / 2 + a / 2 = a := nnreal.eq (add_halves a) lemma half_lt_self {a : ℝ≥0} (h : a ≠ 0) : a / 2 < a := by rw [← nnreal.coe_lt_coe, nnreal.coe_div]; exact half_lt_self (bot_lt_iff_ne_bot.2 h) lemma two_inv_lt_one : (2⁻¹:ℝ≥0) < 1 := by simpa [div_def] using half_lt_self zero_ne_one.symm lemma div_lt_iff {a b c : ℝ≥0} (hc : c ≠ 0) : b / c < a ↔ b < a * c := begin rw [← nnreal.coe_lt_coe, ← nnreal.coe_lt_coe, nnreal.coe_div, nnreal.coe_mul], exact div_lt_iff (zero_lt_iff_ne_zero.mpr hc) end lemma div_lt_one_of_lt {a b : ℝ≥0} (h : a < b) : a / b < 1 := begin rwa [div_lt_iff, one_mul], exact ne_of_gt (lt_of_le_of_lt (zero_le _) h) end @[field_simps] theorem div_pow {a b : ℝ≥0} (n : ℕ) : (a / b) ^ n = a ^ n / b ^ n := div_pow _ _ _ @[field_simps] lemma mul_div_assoc' (a b c : ℝ≥0) : a * (b / c) = (a * b) / c := by rw [div_def, div_def, mul_assoc] @[field_simps] lemma div_add_div (a : ℝ≥0) {b : ℝ≥0} (c : ℝ≥0) {d : ℝ≥0} (hb : b ≠ 0) (hd : d ≠ 0) : a / b + c / d = (a * d + b * c) / (b * d) := begin rw ← nnreal.eq_iff, simp only [nnreal.coe_add, nnreal.coe_div, nnreal.coe_mul], exact div_add_div _ _ (coe_ne_zero.2 hb) (coe_ne_zero.2 hd) end @[field_simps] lemma inv_eq_one_div (a : ℝ≥0) : a⁻¹ = 1/a := by rw [div_def, one_mul] @[field_simps] lemma div_mul_eq_mul_div (a b c : ℝ≥0) : (a / b) * c = (a * c) / b := by { rw [div_def, div_def], ac_refl } @[field_simps] lemma add_div' (a b c : ℝ≥0) (hc : c ≠ 0) : b + a / c = (b * c + a) / c := by simpa using div_add_div b a one_ne_zero hc @[field_simps] lemma div_add' (a b c : ℝ≥0) (hc : c ≠ 0) : a / c + b = (a + b * c) / c := by rwa [add_comm, add_div', add_comm] lemma one_div_eq_inv (a : ℝ≥0) : 1 / a = a⁻¹ := one_mul a⁻¹ lemma one_div_div (a b : ℝ≥0) : 1 / (a / b) = b / a := by { rw ← nnreal.eq_iff, simp [one_div_div] } lemma div_eq_mul_one_div (a b : ℝ≥0) : a / b = a * (1 / b) := by rw [div_def, div_def, one_mul] @[field_simps] lemma div_div_eq_mul_div (a b c : ℝ≥0) : a / (b / c) = (a * c) / b := by { rw ← nnreal.eq_iff, simp [div_div_eq_mul_div] } @[field_simps] lemma div_div_eq_div_mul (a b c : ℝ≥0) : (a / b) / c = a / (b * c) := by { rw ← nnreal.eq_iff, simp [div_div_eq_div_mul] } @[field_simps] lemma div_eq_div_iff {a b c d : ℝ≥0} (hb : b ≠ 0) (hd : d ≠ 0) : a / b = c / d ↔ a * d = c * b := div_eq_div_iff hb hd @[field_simps] lemma div_eq_iff {a b c : ℝ≥0} (hb : b ≠ 0) : a / b = c ↔ a = c * b := by simpa using @div_eq_div_iff a b c 1 hb one_ne_zero @[field_simps] lemma eq_div_iff {a b c : ℝ≥0} (hb : b ≠ 0) : c = a / b ↔ c * b = a := by simpa using @div_eq_div_iff c 1 a b one_ne_zero hb end inv section pow theorem pow_eq_zero {a : ℝ≥0} {n : ℕ} (h : a^n = 0) : a = 0 := begin rw ← nnreal.eq_iff, rw [← nnreal.eq_iff, coe_pow] at h, exact pow_eq_zero h end @[field_simps] theorem pow_ne_zero {a : ℝ≥0} (n : ℕ) (h : a ≠ 0) : a ^ n ≠ 0 := mt pow_eq_zero h end pow end nnreal
625942840fa43e641b79695315d693dd1edc1cd9
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/interactive/goTo.lean
aa27905360dad796ad82d361a26c3136ec0bc815
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
1,178
lean
import Lean.Elab structure Bar where structure Foo where foo₁ : Nat foo₂ : Nat bar : Bar def mkFoo₁ : Foo := { --v textDocument/definition foo₁ := 1 --^ textDocument/definition --v textDocument/declaration foo₂ := 2 --v textDocument/typeDefinition bar := ⟨⟩ } --v textDocument/definition #check (Bar) structure HandWrittenStruct where n : Nat -- def HandWrittenStruct.n := fun | mk n => n --v textDocument/definition def hws : HandWrittenStruct := { --v textDocument/definition n := 3 } --v textDocument/declaration def mkFoo₂ := mkFoo₁ syntax (name := elabTest) "test" : term @[termElab elabTest] def elabElabTest : Lean.Elab.Term.TermElab := fun _ _ => do let stx ← `(2) Lean.Elab.Term.elabTerm stx none --v textDocument/declaration #check test --^ textDocument/definition def Baz (α : Type) := α #check fun (b : Baz Nat) => b --^ textDocument/typeDefinition example : Nat := let a := 1 --v textDocument/definition a + b --^ textDocument/definition where b := 2 macro_rules | `(test) => `(3) #check test --^ textDocument/definition
936f81fcbc33bf91233cf18a461cd5529a1dc760
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/tests/lean/run/typeclass_diamond.lean
403a06a2a5f6832fced3df3301309d54ecb8c5a1
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
1,781
lean
class Top₁ (n : Nat) : Type := (u : Unit := ()) class Bot₁ (n : Nat) : Type := (u : Unit := ()) class Left₁ (n : Nat) : Type := (u : Unit := ()) class Right₁ (n : Nat) : Type := (u : Unit := ()) instance Bot₁Inst : Bot₁ Nat.zero := {} instance Left₁ToBot₁ (n : Nat) [Left₁ n] : Bot₁ n := {} instance Right₁ToBot₁ (n : Nat) [Right₁ n] : Bot₁ n := {} instance Top₁ToLeft₁ (n : Nat) [Top₁ n] : Left₁ n := {} instance Top₁ToRight₁ (n : Nat) [Top₁ n] : Right₁ n := {} instance Bot₁ToTopSucc (n : Nat) [Bot₁ n] : Top₁ n.succ := {} class Top₂ (n : Nat) : Type := (u : Unit := ()) class Bot₂ (n : Nat) : Type := (u : Unit := ()) class Left₂ (n : Nat) : Type := (u : Unit := ()) class Right₂ (n : Nat) : Type := (u : Unit := ()) instance Left₂ToBot₂ (n : Nat) [Left₂ n] : Bot₂ n := {} instance Right₂ToBot₂ (n : Nat) [Right₂ n] : Bot₂ n := {} instance Top₂ToLeft₂ (n : Nat) [Top₂ n] : Left₂ n := {} instance Top₂ToRight₂ (n : Nat) [Top₂ n] : Right₂ n := {} instance Bot₂ToTopSucc (n : Nat) [Bot₂ n] : Top₂ n.succ := {} class Top (n : Nat) : Type := (u : Unit := ()) instance Top₁ToTop (n : Nat) [Top₁ n] : Top n := {} instance Top₂ToTop (n : Nat) [Top₂ n] : Top n := {} set_option synthInstance.maxHeartbeats 500 #synth Top Nat.zero.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ def tst : Top Nat.zero.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ := inferInstance
5f81118d2e4c20859f0769b54035d0c107f07a59
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/category_theory/structured_arrow.lean
8e41515c83bbc4958f281b26cc4a4d5d376c9621
[ "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
11,718
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz, Scott Morrison -/ import category_theory.comma import category_theory.punit import category_theory.limits.shapes.terminal /-! # The category of "structured arrows" For `T : C ⥤ D`, a `T`-structured arrow with source `S : D` is just a morphism `S ⟶ T.obj Y`, for some `Y : D`. These form a category with morphisms `g : Y ⟶ Y'` making the obvious diagram commute. We prove that `𝟙 (T.obj Y)` is the initial object in `T`-structured objects with source `T.obj Y`. -/ namespace category_theory universes v₁ v₂ u₁ u₂ -- morphism levels before object levels. See note [category_theory universes]. variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] /-- The category of `T`-structured arrows with domain `S : D` (here `T : C ⥤ D`), has as its objects `D`-morphisms of the form `S ⟶ T Y`, for some `Y : C`, and morphisms `C`-morphisms `Y ⟶ Y'` making the obvious triangle commute. -/ @[derive category, nolint has_inhabited_instance] def structured_arrow (S : D) (T : C ⥤ D) := comma (functor.from_punit S) T namespace structured_arrow /-- The obvious projection functor from structured arrows. -/ @[simps] def proj (S : D) (T : C ⥤ D) : structured_arrow S T ⥤ C := comma.snd _ _ variables {S S' S'' : D} {Y Y' : C} {T : C ⥤ D} /-- Construct a structured arrow from a morphism. -/ def mk (f : S ⟶ T.obj Y) : structured_arrow S T := ⟨⟨⟩, Y, f⟩ @[simp] lemma mk_left (f : S ⟶ T.obj Y) : (mk f).left = punit.star := rfl @[simp] lemma mk_right (f : S ⟶ T.obj Y) : (mk f).right = Y := rfl @[simp] lemma mk_hom_eq_self (f : S ⟶ T.obj Y) : (mk f).hom = f := rfl @[simp, reassoc] lemma w {A B : structured_arrow S T} (f : A ⟶ B) : A.hom ≫ T.map f.right = B.hom := by { have := f.w; tidy } lemma eq_mk (f : structured_arrow S T) : f = mk f.hom := by { cases f, congr, ext, } /-- To construct a morphism of structured arrows, we need a morphism of the objects underlying the target, and to check that the triangle commutes. -/ @[simps] def hom_mk {f f' : structured_arrow S T} (g : f.right ⟶ f'.right) (w : f.hom ≫ T.map g = f'.hom) : f ⟶ f' := { left := eq_to_hom (by ext), right := g, w' := by { dsimp, simpa using w.symm, }, } /-- To construct an isomorphism of structured arrows, we need an isomorphism of the objects underlying the target, and to check that the triangle commutes. -/ @[simps] def iso_mk {f f' : structured_arrow S T} (g : f.right ≅ f'.right) (w : f.hom ≫ T.map g.hom = f'.hom) : f ≅ f' := comma.iso_mk (eq_to_iso (by ext)) g (by simpa using w.symm) /-- A morphism between source objects `S ⟶ S'` contravariantly induces a functor between structured arrows, `structured_arrow S' T ⥤ structured_arrow S T`. Ideally this would be described as a 2-functor from `D` (promoted to a 2-category with equations as 2-morphisms) to `Cat`. -/ @[simps] def map (f : S ⟶ S') : structured_arrow S' T ⥤ structured_arrow S T := comma.map_left _ ((functor.const _).map f) @[simp] lemma map_mk {f : S' ⟶ T.obj Y} (g : S ⟶ S') : (map g).obj (mk f) = mk (g ≫ f) := rfl @[simp] lemma map_id {f : structured_arrow S T} : (map (𝟙 S)).obj f = f := by { rw eq_mk f, simp, } @[simp] lemma map_comp {f : S ⟶ S'} {f' : S' ⟶ S''} {h : structured_arrow S'' T} : (map (f ≫ f')).obj h = (map f).obj ((map f').obj h) := by { rw eq_mk h, simp, } instance proj_reflects_iso : reflects_isomorphisms (proj S T) := { reflects := λ Y Z f t, by exactI ⟨⟨structured_arrow.hom_mk (inv ((proj S T).map f)) (by simp), by tidy⟩⟩ } open category_theory.limits /-- The identity structured arrow is initial. -/ def mk_id_initial [full T] [faithful T] : is_initial (mk (𝟙 (T.obj Y))) := { desc := λ c, hom_mk (T.preimage c.X.hom) (by { dsimp, simp, }), uniq' := λ c m _, begin ext, apply T.map_injective, simpa only [hom_mk_right, T.image_preimage, ←w m] using (category.id_comp _).symm, end } end structured_arrow /-- The category of `S`-costructured arrows with target `T : D` (here `S : C ⥤ D`), has as its objects `D`-morphisms of the form `S Y ⟶ T`, for some `Y : C`, and morphisms `C`-morphisms `Y ⟶ Y'` making the obvious triangle commute. -/ @[derive category, nolint has_inhabited_instance] def costructured_arrow (S : C ⥤ D) (T : D) := comma S (functor.from_punit T) namespace costructured_arrow /-- The obvious projection functor from costructured arrows. -/ @[simps] def proj (S : C ⥤ D) (T : D) : costructured_arrow S T ⥤ C := comma.fst _ _ variables {T T' T'' : D} {Y Y' : C} {S : C ⥤ D} /-- Construct a costructured arrow from a morphism. -/ def mk (f : S.obj Y ⟶ T) : costructured_arrow S T := ⟨Y, ⟨⟩, f⟩ @[simp] lemma mk_left (f : S.obj Y ⟶ T) : (mk f).left = Y := rfl @[simp] lemma mk_right (f : S.obj Y ⟶ T) : (mk f).right = punit.star := rfl @[simp] lemma mk_hom_eq_self (f : S.obj Y ⟶ T) : (mk f).hom = f := rfl @[simp, reassoc] lemma w {A B : costructured_arrow S T} (f : A ⟶ B) : S.map f.left ≫ B.hom = A.hom := by tidy lemma eq_mk (f : costructured_arrow S T) : f = mk f.hom := by { cases f, congr, ext, } /-- To construct a morphism of costructured arrows, we need a morphism of the objects underlying the source, and to check that the triangle commutes. -/ @[simps] def hom_mk {f f' : costructured_arrow S T} (g : f.left ⟶ f'.left) (w : S.map g ≫ f'.hom = f.hom) : f ⟶ f' := { left := g, right := eq_to_hom (by ext), w' := by simpa using w, } /-- To construct an isomorphism of costructured arrows, we need an isomorphism of the objects underlying the source, and to check that the triangle commutes. -/ @[simps] def iso_mk {f f' : costructured_arrow S T} (g : f.left ≅ f'.left) (w : S.map g.hom ≫ f'.hom = f.hom) : f ≅ f' := comma.iso_mk g (eq_to_iso (by ext)) (by simpa using w) /-- A morphism between target objects `T ⟶ T'` covariantly induces a functor between costructured arrows, `costructured_arrow S T ⥤ costructured_arrow S T'`. Ideally this would be described as a 2-functor from `D` (promoted to a 2-category with equations as 2-morphisms) to `Cat`. -/ @[simps] def map (f : T ⟶ T') : costructured_arrow S T ⥤ costructured_arrow S T' := comma.map_right _ ((functor.const _).map f) @[simp] lemma map_mk {f : S.obj Y ⟶ T} (g : T ⟶ T') : (map g).obj (mk f) = mk (f ≫ g) := rfl @[simp] lemma map_id {f : costructured_arrow S T} : (map (𝟙 T)).obj f = f := by { rw eq_mk f, simp, } @[simp] lemma map_comp {f : T ⟶ T'} {f' : T' ⟶ T''} {h : costructured_arrow S T} : (map (f ≫ f')).obj h = (map f').obj ((map f).obj h) := by { rw eq_mk h, simp, } instance proj_reflects_iso : reflects_isomorphisms (proj S T) := { reflects := λ Y Z f t, by exactI ⟨⟨costructured_arrow.hom_mk (inv ((proj S T).map f)) (by simp), by tidy⟩⟩ } open category_theory.limits /-- The identity costructured arrow is terminal. -/ def mk_id_terminal [full S] [faithful S] : is_terminal (mk (𝟙 (S.obj Y))) := { lift := λ c, hom_mk (S.preimage c.X.hom) (by { dsimp, simp, }), uniq' := begin rintros c m -, ext, apply S.map_injective, simpa only [hom_mk_left, S.image_preimage, ←w m] using (category.comp_id _).symm, end } end costructured_arrow open opposite namespace structured_arrow /-- For a functor `F : C ⥤ D` and an object `d : D`, we obtain a contravariant functor from the category of structured arrows `d ⟶ F.obj c` to the category of costructured arrows `F.op.obj c ⟶ (op d)`. -/ @[simps] def to_costructured_arrow (F : C ⥤ D) (d : D) : (structured_arrow d F)ᵒᵖ ⥤ costructured_arrow F.op (op d) := { obj := λ X, @costructured_arrow.mk _ _ _ _ _ (op X.unop.right) F.op X.unop.hom.op, map := λ X Y f, costructured_arrow.hom_mk (f.unop.right.op) begin dsimp, rw [← op_comp, ← f.unop.w, functor.const.obj_map], erw category.id_comp, end } /-- For a functor `F : C ⥤ D` and an object `d : D`, we obtain a contravariant functor from the category of structured arrows `op d ⟶ F.op.obj c` to the category of costructured arrows `F.obj c ⟶ d`. -/ @[simps] def to_costructured_arrow' (F : C ⥤ D) (d : D) : (structured_arrow (op d) F.op)ᵒᵖ ⥤ costructured_arrow F d := { obj := λ X, @costructured_arrow.mk _ _ _ _ _ (unop X.unop.right) F X.unop.hom.unop, map := λ X Y f, costructured_arrow.hom_mk f.unop.right.unop begin dsimp, rw [← quiver.hom.unop_op (F.map (quiver.hom.unop f.unop.right)), ← unop_comp, ← F.op_map, ← f.unop.w, functor.const.obj_map], erw category.id_comp, end } end structured_arrow namespace costructured_arrow /-- For a functor `F : C ⥤ D` and an object `d : D`, we obtain a contravariant functor from the category of costructured arrows `F.obj c ⟶ d` to the category of structured arrows `op d ⟶ F.op.obj c`. -/ @[simps] def to_structured_arrow (F : C ⥤ D) (d : D) : (costructured_arrow F d)ᵒᵖ ⥤ structured_arrow (op d) F.op := { obj := λ X, @structured_arrow.mk _ _ _ _ _ (op X.unop.left) F.op X.unop.hom.op, map := λ X Y f, structured_arrow.hom_mk f.unop.left.op begin dsimp, rw [← op_comp, f.unop.w, functor.const.obj_map], erw category.comp_id, end } /-- For a functor `F : C ⥤ D` and an object `d : D`, we obtain a contravariant functor from the category of costructured arrows `F.op.obj c ⟶ op d` to the category of structured arrows `d ⟶ F.obj c`. -/ @[simps] def to_structured_arrow' (F : C ⥤ D) (d : D) : (costructured_arrow F.op (op d))ᵒᵖ ⥤ structured_arrow d F := { obj := λ X, @structured_arrow.mk _ _ _ _ _ (unop X.unop.left) F X.unop.hom.unop, map := λ X Y f, structured_arrow.hom_mk (f.unop.left.unop) begin dsimp, rw [← quiver.hom.unop_op (F.map f.unop.left.unop), ← unop_comp, ← F.op_map, f.unop.w, functor.const.obj_map], erw category.comp_id, end } end costructured_arrow /-- For a functor `F : C ⥤ D` and an object `d : D`, the category of structured arrows `d ⟶ F.obj c` is contravariantly equivalent to the category of costructured arrows `F.op.obj c ⟶ op d`. -/ def structured_arrow_op_equivalence (F : C ⥤ D) (d : D) : (structured_arrow d F)ᵒᵖ ≌ costructured_arrow F.op (op d) := equivalence.mk (structured_arrow.to_costructured_arrow F d) (costructured_arrow.to_structured_arrow' F d).right_op (nat_iso.of_components (λ X, (@structured_arrow.iso_mk _ _ _ _ _ _ (structured_arrow.mk (unop X).hom) (unop X) (iso.refl _) (by tidy)).op) (λ X Y f, quiver.hom.unop_inj $ begin ext, dsimp, simp end)) (nat_iso.of_components (λ X, @costructured_arrow.iso_mk _ _ _ _ _ _ (costructured_arrow.mk X.hom) X (iso.refl _) (by tidy)) (λ X Y f, begin ext, dsimp, simp end)) /-- For a functor `F : C ⥤ D` and an object `d : D`, the category of costructured arrows `F.obj c ⟶ d` is contravariantly equivalent to the category of structured arrows `op d ⟶ F.op.obj c`. -/ def costructured_arrow_op_equivalence (F : C ⥤ D) (d : D) : (costructured_arrow F d)ᵒᵖ ≌ structured_arrow (op d) F.op := equivalence.mk (costructured_arrow.to_structured_arrow F d) (structured_arrow.to_costructured_arrow' F d).right_op (nat_iso.of_components (λ X, (@costructured_arrow.iso_mk _ _ _ _ _ _ (costructured_arrow.mk (unop X).hom) (unop X) (iso.refl _) (by tidy)).op) (λ X Y f, quiver.hom.unop_inj $ begin ext, dsimp, simp end)) (nat_iso.of_components (λ X, @structured_arrow.iso_mk _ _ _ _ _ _ (structured_arrow.mk X.hom) X (iso.refl _) (by tidy)) (λ X Y f, begin ext, dsimp, simp end)) end category_theory
d24014f73c8fc2274180cc911e9ee413c4bc4b80
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/testing/slim_check/functions.lean
b70e3757746c6f3941315a87a8e39c4736580cb9
[ "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
19,546
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.list.sigma import data.int.range import data.finsupp.defs import data.finsupp.to_dfinsupp import tactic.pretty_cases import testing.slim_check.sampleable import testing.slim_check.testable /-! ## `slim_check`: generators for functions This file defines `sampleable` instances for `α → β` functions and `ℤ → ℤ` injective functions. Functions are generated by creating a list of pairs and one more value using the list as a lookup table and resorting to the additional value when a value is not found in the table. Injective functions are generated by creating a list of numbers and a permutation of that list. The permutation insures that every input is mapped to a unique output. When an input is not found in the list the input itself is used as an output. Injective functions `f : α → α` could be generated easily instead of `ℤ → ℤ` by generating a `list α`, removing duplicates and creating a permutations. One has to be careful when generating the domain to make if vast enough that, when generating arguments to apply `f` to, they argument should be likely to lie in the domain of `f`. This is the reason that injective functions `f : ℤ → ℤ` are generated by fixing the domain to the range `[-2*size .. -2*size]`, with `size` the size parameter of the `gen` monad. Much of the machinery provided in this file is applicable to generate injective functions of type `α → α` and new instances should be easy to define. Other classes of functions such as monotone functions can generated using similar techniques. For monotone functions, generating two lists, sorting them and matching them should suffice, with appropriate default values. Some care must be taken for shrinking such functions to make sure their defining property is invariant through shrinking. Injective functions are an example of how complicated it can get. -/ universes u v w variables {α : Type u} {β : Type v} {γ : Sort w} namespace slim_check /-- Data structure specifying a total function using a list of pairs and a default value returned when the input is not in the domain of the partial function. `with_default f y` encodes `x ↦ f x` when `x ∈ f` and `x ↦ y` otherwise. We use `Σ` to encode mappings instead of `×` because we rely on the association list API defined in `data.list.sigma`. -/ inductive total_function (α : Type u) (β : Type v) : Type (max u v) | with_default : list (Σ _ : α, β) → β → total_function instance total_function.inhabited [inhabited β] : inhabited (total_function α β) := ⟨ total_function.with_default ∅ default ⟩ namespace total_function /-- Apply a total function to an argument. -/ def apply [decidable_eq α] : total_function α β → α → β | (total_function.with_default m y) x := (m.lookup x).get_or_else y /-- Implementation of `has_repr (total_function α β)`. Creates a string for a given `finmap` and output, `x₀ ↦ y₀, .. xₙ ↦ yₙ` for each of the entries. The brackets are provided by the calling function. -/ def repr_aux [has_repr α] [has_repr β] (m : list (Σ _ : α, β)) : string := string.join $ list.qsort (λ x y, x < y) (m.map $ λ x, sformat!"{repr $ sigma.fst x} ↦ {repr $ sigma.snd x}, ") /-- Produce a string for a given `total_function`. The output is of the form `[x₀ ↦ f x₀, .. xₙ ↦ f xₙ, _ ↦ y]`. -/ protected def repr [has_repr α] [has_repr β] : total_function α β → string | (total_function.with_default m y) := sformat!"[{repr_aux m}_ ↦ {has_repr.repr y}]" instance (α : Type u) (β : Type v) [has_repr α] [has_repr β] : has_repr (total_function α β) := ⟨ total_function.repr ⟩ /-- Create a `finmap` from a list of pairs. -/ def list.to_finmap' (xs : list (α × β)) : list (Σ _ : α, β) := xs.map prod.to_sigma section variables [sampleable α] [sampleable β] /-- Redefine `sizeof` to follow the structure of `sampleable` instances. -/ def total.sizeof : total_function α β → ℕ | ⟨m, x⟩ := 1 + @sizeof _ sampleable.wf m + sizeof x @[priority 2000] instance : has_sizeof (total_function α β) := ⟨ total.sizeof ⟩ variables [decidable_eq α] /-- Shrink a total function by shrinking the lists that represent it. -/ protected def shrink : shrink_fn (total_function α β) | ⟨m, x⟩ := (sampleable.shrink (m, x)).map $ λ ⟨⟨m', x'⟩, h⟩, ⟨⟨list.dedupkeys m', x'⟩, lt_of_le_of_lt (by unfold_wf; refine @list.sizeof_dedupkeys _ _ _ (@sampleable.wf _ _) _) h ⟩ variables [has_repr α] [has_repr β] instance pi.sampleable_ext : sampleable_ext (α → β) := { proxy_repr := total_function α β, interp := total_function.apply, sample := do { xs ← (sampleable.sample (list (α × β)) : gen ((list (α × β)))), ⟨x⟩ ← (uliftable.up $ sample β : gen (ulift.{max u v} β)), pure $ total_function.with_default (list.to_finmap' xs) x }, shrink := total_function.shrink } end section finsupp variables [has_zero β] /-- Map a total_function to one whose default value is zero so that it represents a finsupp. -/ @[simp] def zero_default : total_function α β → total_function α β | (with_default A y) := with_default A 0 variables [decidable_eq α] [decidable_eq β] /-- The support of a zero default `total_function`. -/ @[simp] def zero_default_supp : total_function α β → finset α | (with_default A y) := list.to_finset $ (A.dedupkeys.filter (λ ab, sigma.snd ab ≠ 0)).map sigma.fst /-- Create a finitely supported function from a total function by taking the default value to zero. -/ def apply_finsupp (tf : total_function α β) : α →₀ β := { support := zero_default_supp tf, to_fun := tf.zero_default.apply, mem_support_to_fun := begin intro a, rcases tf with ⟨A, y⟩, simp only [apply, zero_default_supp, list.mem_map, list.mem_filter, exists_and_distrib_right, list.mem_to_finset, exists_eq_right, sigma.exists, ne.def, zero_default], split, { rintro ⟨od, hval, hod⟩, have := list.mem_lookup (list.nodupkeys_dedupkeys A) hval, rw (_ : list.lookup a A = od), { simpa, }, { simpa [list.lookup_dedupkeys, with_top.some_eq_coe], }, }, { intro h, use (A.lookup a).get_or_else (0 : β), rw ← list.lookup_dedupkeys at h ⊢, simp only [h, ←list.mem_lookup_iff A.nodupkeys_dedupkeys, and_true, not_false_iff, option.mem_def], cases list.lookup a A.dedupkeys, { simpa using h, }, { simp, }, } end } variables [sampleable α] [sampleable β] instance finsupp.sampleable_ext [has_repr α] [has_repr β] : sampleable_ext (α →₀ β) := { proxy_repr := total_function α β, interp := total_function.apply_finsupp, sample := (do xs ← (sampleable.sample (list (α × β)) : gen (list (α × β))), ⟨x⟩ ← (uliftable.up $ sample β : gen (ulift.{max u v} β)), pure $ total_function.with_default (list.to_finmap' xs) x), shrink := total_function.shrink } -- TODO: support a non-constant codomain type instance dfinsupp.sampleable_ext [has_repr α] [has_repr β] : sampleable_ext (Π₀ a : α, β) := { proxy_repr := total_function α β, interp := finsupp.to_dfinsupp ∘ total_function.apply_finsupp, sample := (do xs ← (sampleable.sample (list (α × β)) : gen (list (α × β))), ⟨x⟩ ← (uliftable.up $ sample β : gen (ulift.{max u v} β)), pure $ total_function.with_default (list.to_finmap' xs) x), shrink := total_function.shrink } end finsupp section sampleable_ext open sampleable_ext @[priority 2000] instance pi_pred.sampleable_ext [sampleable_ext (α → bool)] : sampleable_ext.{u+1} (α → Prop) := { proxy_repr := proxy_repr (α → bool), interp := λ m x, interp (α → bool) m x, sample := sample (α → bool), shrink := shrink } @[priority 2000] instance pi_uncurry.sampleable_ext [sampleable_ext (α × β → γ)] : sampleable_ext.{imax (u+1) (v+1) w} (α → β → γ) := { proxy_repr := proxy_repr (α × β → γ), interp := λ m x y, interp (α × β → γ) m (x, y), sample := sample (α × β → γ), shrink := shrink } end sampleable_ext end total_function /-- Data structure specifying a total function using a list of pairs and a default value returned when the input is not in the domain of the partial function. `map_to_self f` encodes `x ↦ f x` when `x ∈ f` and `x ↦ x`, i.e. `x` to itself, otherwise. We use `Σ` to encode mappings instead of `×` because we rely on the association list API defined in `data.list.sigma`. -/ inductive injective_function (α : Type u) : Type u | map_to_self (xs : list (Σ _ : α, α)) : xs.map sigma.fst ~ xs.map sigma.snd → list.nodup (xs.map sigma.snd) → injective_function instance : inhabited (injective_function α) := ⟨ ⟨ [], list.perm.nil, list.nodup_nil ⟩ ⟩ namespace injective_function /-- Apply a total function to an argument. -/ def apply [decidable_eq α] : injective_function α → α → α | (injective_function.map_to_self m _ _) x := (m.lookup x).get_or_else x /-- Produce a string for a given `total_function`. The output is of the form `[x₀ ↦ f x₀, .. xₙ ↦ f xₙ, x ↦ x]`. Unlike for `total_function`, the default value is not a constant but the identity function. -/ protected def repr [has_repr α] : injective_function α → string | (injective_function.map_to_self m _ _) := sformat!"[{total_function.repr_aux m}x ↦ x]" instance (α : Type u) [has_repr α] : has_repr (injective_function α) := ⟨ injective_function.repr ⟩ /-- Interpret a list of pairs as a total function, defaulting to the identity function when no entries are found for a given function -/ def list.apply_id [decidable_eq α] (xs : list (α × α)) (x : α) : α := ((xs.map prod.to_sigma).lookup x).get_or_else x @[simp] lemma list.apply_id_cons [decidable_eq α] (xs : list (α × α)) (x y z : α) : list.apply_id ((y, z) :: xs) x = if y = x then z else list.apply_id xs x := by simp only [list.apply_id, list.lookup, eq_rec_constant, prod.to_sigma, list.map]; split_ifs; refl open function _root_.list _root_.prod (to_sigma) open _root_.nat lemma list.apply_id_zip_eq [decidable_eq α] {xs ys : list α} (h₀ : list.nodup xs) (h₁ : xs.length = ys.length) (x y : α) (i : ℕ) (h₂ : xs.nth i = some x) : list.apply_id.{u} (xs.zip ys) x = y ↔ ys.nth i = some y := begin induction xs generalizing ys i, case list.nil : ys i h₁ h₂ { cases h₂ }, case list.cons : x' xs xs_ih ys i h₁ h₂ { cases i, { injection h₂ with h₀ h₁, subst h₀, cases ys, { cases h₁ }, { simp only [list.apply_id, to_sigma, option.get_or_else_some, nth, lookup_cons_eq, zip_cons_cons, list.map], } }, { cases ys, { cases h₁ }, { cases h₀ with _ _ h₀ h₁, simp only [nth, zip_cons_cons, list.apply_id_cons] at h₂ ⊢, rw if_neg, { apply xs_ih; solve_by_elim [succ.inj] }, { apply h₀, apply nth_mem h₂ } } } } end lemma apply_id_mem_iff [decidable_eq α] {xs ys : list α} (h₀ : list.nodup xs) (h₁ : xs ~ ys) (x : α) : list.apply_id.{u} (xs.zip ys) x ∈ ys ↔ x ∈ xs := begin simp only [list.apply_id], cases h₃ : (lookup x (map prod.to_sigma (xs.zip ys))), { dsimp [option.get_or_else], rw h₁.mem_iff }, { have h₂ : ys.nodup := h₁.nodup_iff.1 h₀, replace h₁ : xs.length = ys.length := h₁.length_eq, dsimp, induction xs generalizing ys, case list.nil : ys h₃ h₂ h₁ { contradiction }, case list.cons : x' xs xs_ih ys h₃ h₂ h₁ { cases ys with y ys, { cases h₃ }, dsimp [lookup] at h₃, split_ifs at h₃, { subst x', subst val, simp only [mem_cons_iff, true_or, eq_self_iff_true], }, { cases h₀ with _ _ h₀ h₅, cases h₂ with _ _ h₂ h₄, have h₆ := nat.succ.inj h₁, specialize @xs_ih h₅ ys h₃ h₄ h₆, simp only [ne.symm h, xs_ih, mem_cons_iff, false_or], suffices : val ∈ ys, tauto!, erw [← option.mem_def, mem_lookup_iff] at h₃, simp only [to_sigma, mem_map, heq_iff_eq, prod.exists] at h₃, rcases h₃ with ⟨a, b, h₃, h₄, h₅⟩, subst a, subst b, apply (mem_zip h₃).2, simp only [nodupkeys, keys, comp, prod.fst_to_sigma, map_map], rwa map_fst_zip _ _ (le_of_eq h₆) } } } end lemma list.apply_id_eq_self [decidable_eq α] {xs ys : list α} (x : α) : x ∉ xs → list.apply_id.{u} (xs.zip ys) x = x := begin intro h, dsimp [list.apply_id], rw lookup_eq_none.2, refl, simp only [keys, not_exists, to_sigma, exists_and_distrib_right, exists_eq_right, mem_map, comp_app, map_map, prod.exists], intros y hy, exact h (mem_zip hy).1, end lemma apply_id_injective [decidable_eq α] {xs ys : list α} (h₀ : list.nodup xs) (h₁ : xs ~ ys) : injective.{u+1 u+1} (list.apply_id (xs.zip ys)) := begin intros x y h, by_cases hx : x ∈ xs; by_cases hy : y ∈ xs, { rw mem_iff_nth at hx hy, cases hx with i hx, cases hy with j hy, suffices : some x = some y, { injection this }, have h₂ := h₁.length_eq, rw [list.apply_id_zip_eq h₀ h₂ _ _ _ hx] at h, rw [← hx, ← hy], congr, apply nth_injective _ (h₁.nodup_iff.1 h₀), { symmetry, rw h, rw ← list.apply_id_zip_eq; assumption }, { rw ← h₁.length_eq, rw nth_eq_some at hx, cases hx with hx hx', exact hx } }, { rw ← apply_id_mem_iff h₀ h₁ at hx hy, rw h at hx, contradiction, }, { rw ← apply_id_mem_iff h₀ h₁ at hx hy, rw h at hx, contradiction, }, { rwa [list.apply_id_eq_self, list.apply_id_eq_self] at h; assumption }, end open total_function (list.to_finmap') open sampleable /-- Remove a slice of length `m` at index `n` in a list and a permutation, maintaining the property that it is a permutation. -/ def perm.slice [decidable_eq α] (n m : ℕ) : (Σ' xs ys : list α, xs ~ ys ∧ ys.nodup) → (Σ' xs ys : list α, xs ~ ys ∧ ys.nodup) | ⟨xs, ys, h, h'⟩ := let xs' := list.slice n m xs in have h₀ : xs' ~ ys.inter xs', from perm.slice_inter _ _ h h', ⟨xs', ys.inter xs', h₀, h'.inter _⟩ /-- A lazy list, in decreasing order, of sizes that should be sliced off a list of length `n` -/ def slice_sizes : ℕ → lazy_list ℕ+ | n := if h : 0 < n then have n / 2 < n, from div_lt_self h dec_trivial, lazy_list.cons ⟨_, h⟩ (slice_sizes $ n / 2) else lazy_list.nil /-- Shrink a permutation of a list, slicing a segment in the middle. The sizes of the slice being removed start at `n` (with `n` the length of the list) and then `n / 2`, then `n / 4`, etc down to 1. The slices will be taken at index `0`, `n / k`, `2n / k`, `3n / k`, etc. -/ protected def shrink_perm {α : Type} [decidable_eq α] [has_sizeof α] : shrink_fn (Σ' xs ys : list α, xs ~ ys ∧ ys.nodup) | xs := do let k := xs.1.length, n ← slice_sizes k, i ← lazy_list.of_list $ list.fin_range $ k / n, have ↑i * ↑n < xs.1.length, from nat.lt_of_div_lt_div (lt_of_le_of_lt (by simp only [nat.mul_div_cancel, gt_iff_lt, fin.val_eq_coe, pnat.pos]) i.2), pure ⟨perm.slice (i*n) n xs, by rcases xs with ⟨a,b,c,d⟩; dsimp [sizeof_lt]; unfold_wf; simp only [perm.slice]; unfold_wf; apply list.sizeof_slice_lt _ _ n.2 _ this⟩ instance [has_sizeof α] : has_sizeof (injective_function α) := ⟨ λ ⟨xs,_,_⟩, sizeof (xs.map sigma.fst) ⟩ /-- Shrink an injective function slicing a segment in the middle of the domain and removing the corresponding elements in the codomain, hence maintaining the property that one is a permutation of the other. -/ protected def shrink {α : Type} [has_sizeof α] [decidable_eq α] : shrink_fn (injective_function α) | ⟨xs, h₀, h₁⟩ := do ⟨⟨xs', ys', h₀, h₁⟩, h₂⟩ ← injective_function.shrink_perm ⟨_, _, h₀, h₁⟩, have h₃ : xs'.length ≤ ys'.length, from le_of_eq (perm.length_eq h₀), have h₄ : ys'.length ≤ xs'.length, from le_of_eq (perm.length_eq h₀.symm), pure ⟨⟨(list.zip xs' ys').map prod.to_sigma, by simp only [comp, map_fst_zip, map_snd_zip, *, prod.fst_to_sigma, prod.snd_to_sigma, map_map], by simp only [comp, map_snd_zip, *, prod.snd_to_sigma, map_map] ⟩, by revert h₂; dsimp [sizeof_lt]; unfold_wf; simp only [has_sizeof._match_1, map_map, comp, map_fst_zip, *, prod.fst_to_sigma]; unfold_wf; intro h₂; convert h₂ ⟩ /-- Create an injective function from one list and a permutation of that list. -/ protected def mk (xs ys : list α) (h : xs ~ ys) (h' : ys.nodup) : injective_function α := have h₀ : xs.length ≤ ys.length, from le_of_eq h.length_eq, have h₁ : ys.length ≤ xs.length, from le_of_eq h.length_eq.symm, injective_function.map_to_self (list.to_finmap' (xs.zip ys)) (by { simp only [list.to_finmap', comp, map_fst_zip, map_snd_zip, *, prod.fst_to_sigma, prod.snd_to_sigma, map_map] }) (by { simp only [list.to_finmap', comp, map_snd_zip, *, prod.snd_to_sigma, map_map] }) protected lemma injective [decidable_eq α] (f : injective_function α) : injective (apply f) := begin cases f with xs hperm hnodup, generalize h₀ : map sigma.fst xs = xs₀, generalize h₁ : xs.map (@id ((Σ _ : α, α) → α) $ @sigma.snd α (λ _ : α, α)) = xs₁, dsimp [id] at h₁, have hxs : xs = total_function.list.to_finmap' (xs₀.zip xs₁), { rw [← h₀, ← h₁, list.to_finmap'], clear h₀ h₁ xs₀ xs₁ hperm hnodup, induction xs, case list.nil { simp only [zip_nil_right, map_nil] }, case list.cons : xs_hd xs_tl xs_ih { simp only [true_and, to_sigma, eq_self_iff_true, sigma.eta, zip_cons_cons, list.map], exact xs_ih }, }, revert hperm hnodup, rw hxs, intros, apply apply_id_injective, { rwa [← h₀, hxs, hperm.nodup_iff], }, { rwa [← hxs, h₀, h₁] at hperm, }, end instance pi_injective.sampleable_ext : sampleable_ext { f : ℤ → ℤ // function.injective f } := { proxy_repr := injective_function ℤ, interp := λ f, ⟨ apply f, f.injective ⟩, sample := gen.sized $ λ sz, do { let xs' := int.range (-(2*sz+2)) (2*sz + 2), ys ← gen.permutation_of xs', have Hinj : injective (λ (r : ℕ), -(2*sz + 2 : ℤ) + ↑r), from λ x y h, int.coe_nat_inj (add_right_injective _ h), let r : injective_function ℤ := injective_function.mk.{0} xs' ys.1 ys.2 (ys.2.nodup_iff.1 $ (nodup_range _).map Hinj) in pure r }, shrink := @injective_function.shrink ℤ _ _ } end injective_function open function instance injective.testable (f : α → β) [I : testable (named_binder "x" $ ∀ x : α, named_binder "y" $ ∀ y : α, named_binder "H" $ f x = f y → x = y)] : testable (injective f) := I instance monotone.testable [preorder α] [preorder β] (f : α → β) [I : testable (named_binder "x" $ ∀ x : α, named_binder "y" $ ∀ y : α, named_binder "H" $ x ≤ y → f x ≤ f y)] : testable (monotone f) := I instance antitone.testable [preorder α] [preorder β] (f : α → β) [I : testable (named_binder "x" $ ∀ x : α, named_binder "y" $ ∀ y : α, named_binder "H" $ x ≤ y → f y ≤ f x)] : testable (antitone f) := I end slim_check
4482d0a4e07d207fdf21c1f747128e6abf0f5b83
9028d228ac200bbefe3a711342514dd4e4458bff
/src/category_theory/limits/cofinal.lean
f7ed570f2358e4c1ddda36a43d0c68cfcd5e3654
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,566
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.punit import category_theory.comma import category_theory.is_connected import category_theory.limits.yoneda import category_theory.limits.types /-! # Cofinal functors A functor `F : C ⥤ D` is cofinal if for every `d : D`, the comma category of morphisms `d ⟶ F.obj c` is connected. We prove the following three statements are equivalent: 1. `F : C ⥤ D` is cofinal. 2. Every functor `G : D ⥤ E` has a colimit if and only if `F ⋙ G` does, and these colimits are isomorphic via `colimit.pre G F`. 3. `colimit (F ⋙ coyoneda.obj (op d)) ≅ punit`. Starting at 1. we show (in `cocones_equiv`) that the categories of cocones over `G : D ⥤ E` and over `F ⋙ G` are equivalent. (In fact, via an equivalence which does not change the cocone point.) This readily implies 2., as `comp_has_colimit`, `has_colimit_of_comp`, and `colimit_iso`. From 2. we can specialize to `G = coyoneda.obj (op d)` to obtain 3., as `colimit_comp_coyoneda_iso`. From 3., we prove 1. directly in `cofinal_of_colimit_comp_coyoneda_iso_punit`. We also show these conditions imply: 4. Every functor `H : Dᵒᵖ ⥤ E` has a limit if and only if `F.op ⋙ H` does, and these limits are isomorphic via `limit.pre H F.op`. ## Naming There is some discrepancy in the literature about naming; some say 'final' instead of 'cofinal'. The explanation for this is that the 'co' prefix here is *not* the usual category-theoretic one indicating duality, but rather indicating the sense of "along with". While the trend seems to be towards using 'final', for now we go with the bulk of the literature and use 'cofinal'. ## References * https://stacks.math.columbia.edu/tag/09WN * https://ncatlab.org/nlab/show/final+functor * Borceux, Handbook of Categorical Algebra I, Section 2.11. (Note he reverses the roles of definition and main result relative to here!) -/ noncomputable theory universes v u namespace category_theory open opposite open category_theory.limits variables {C : Type v} [small_category C] variables {D : Type v} [small_category D] /-- A functor `F : C ⥤ D` is cofinal if for every `d : D`, the comma category of morphisms `d ⟶ F.obj c` is connected. See https://stacks.math.columbia.edu/tag/04E6 -/ def cofinal (F : C ⥤ D) : Prop := ∀ (d : D), is_connected (comma (functor.from_punit d) F) attribute [class] cofinal instance (F : C ⥤ D) [ℱ : cofinal F] (d : D) : is_connected (comma (functor.from_punit d) F) := ℱ d namespace cofinal variables (F : C ⥤ D) [cofinal F] instance (d : D) : nonempty (comma (functor.from_punit d) F) := (‹cofinal F› d).is_nonempty variables {E : Type u} [category.{v} E] (G : D ⥤ E) /-- When `F : C ⥤ D` is cofinal, we denote by `lift F d` an arbitrary choice of object in `C` such that there exists a morphism `d ⟶ F.obj (lift F d)`. -/ def lift (d : D) : C := (classical.arbitrary (comma (functor.from_punit d) F)).right /-- When `F : C ⥤ D` is cofinal, we denote by `hom_to_lift` an arbitrary choice of morphism `d ⟶ F.obj (lift F d)`. -/ def hom_to_lift (d : D) : d ⟶ F.obj (lift F d) := (classical.arbitrary (comma (functor.from_punit d) F)).hom /-- We provide an induction principle for reasoning about `lift` and `hom_to_lift`. We want to perform some construction (usually just a proof) about the particular choices `lift F d` and `hom_to_lift F d`, it suffices to perform that construction for some other pair of choices (denoted `X₀ : C` and `k₀ : d ⟶ F.obj X₀` below), and to show that how to transport such a construction *both* directions along a morphism between such choices. -/ lemma induction {d : D} (Z : Π (X : C) (k : d ⟶ F.obj X), Prop) (h₁ : Π X₁ X₂ (k₁ : d ⟶ F.obj X₁) (k₂ : d ⟶ F.obj X₂) (f : X₁ ⟶ X₂), (k₁ ≫ F.map f = k₂) → Z X₁ k₁ → Z X₂ k₂) (h₂ : Π X₁ X₂ (k₁ : d ⟶ F.obj X₁) (k₂ : d ⟶ F.obj X₂) (f : X₁ ⟶ X₂), (k₁ ≫ F.map f = k₂) → Z X₂ k₂ → Z X₁ k₁) {X₀ : C} {k₀ : d ⟶ F.obj X₀} (z : Z X₀ k₀) : Z (lift F d) (hom_to_lift F d) := begin apply nonempty.some, apply @is_preconnected_induction _ _ _ (λ (Y : comma (functor.from_punit d) F), Z Y.right Y.hom) _ _ { right := X₀, hom := k₀, } z, { intros, fapply h₁ _ _ _ _ f.right _ a, convert f.w.symm, dsimp, simp, }, { intros, fapply h₂ _ _ _ _ f.right _ a, convert f.w.symm, dsimp, simp, }, end variables {F G} /-- Given a cocone over `F ⋙ G`, we can construct a `cocone G` with the same cocone point. -/ @[simps] def extend_cocone : cocone (F ⋙ G) ⥤ cocone G := { obj := λ c, { X := c.X, ι := { app := λ X, G.map (hom_to_lift F X) ≫ c.ι.app (lift F X), naturality' := λ X Y f, begin dsimp, simp, -- This would be true if we'd chosen `lift F X` to be `lift F Y` -- and `hom_to_lift F X` to be `f ≫ hom_to_lift F Y`. apply induction F (λ Z k, G.map f ≫ G.map (hom_to_lift F Y) ≫ c.ι.app (lift F Y) = G.map k ≫ c.ι.app Z), { intros Z₁ Z₂ k₁ k₂ g a z, rw [←a, functor.map_comp, category.assoc, ←functor.comp_map, c.w, z], }, { intros Z₁ Z₂ k₁ k₂ g a z, rw [←a, functor.map_comp, category.assoc, ←functor.comp_map, c.w] at z, rw z, }, { rw [←functor.map_comp_assoc], }, end } }, map := λ X Y f, { hom := f.hom, } } @[simp] lemma colimit_cocone_comp_aux (s : cocone (F ⋙ G)) (j : C) : G.map (hom_to_lift F (F.obj j)) ≫ s.ι.app (lift F (F.obj j)) = s.ι.app j := begin -- This point is that this would be true if we took `lift (F.obj j)` to just be `j` -- and `hom_to_lift (F.obj j)` to be `𝟙 (F.obj j)`. apply induction F (λ X k, G.map k ≫ s.ι.app X = (s.ι.app j : _)), { intros j₁ j₂ k₁ k₂ f w h, rw ←w, rw ← s.w f at h, simpa using h, }, { intros j₁ j₂ k₁ k₂ f w h, rw ←w at h, rw ← s.w f, simpa using h, }, { exact s.w (𝟙 _), }, end variables {H : Dᵒᵖ ⥤ E} /-- An auxilliary construction for `extend_cone`, moving `op` around. -/ @[simps] def extend_cone_cone_to_cocone {F : C ⥤ D} {H : Dᵒᵖ ⥤ E} (c : cone (F.op ⋙ H)) : cocone (F ⋙ H.right_op) := { X := op c.X, ι := { app := λ j, (c.π.app (op j)).op, naturality' := λ j j' f, begin apply has_hom.hom.unop_inj, dsimp, simp only [category.id_comp], exact c.w f.op, end }} /-- An auxilliary construction for `extend_cone`, moving `op` around. -/ @[simps] def extend_cone_cocone_to_cone (c : cocone H.right_op) : cone H := { X := unop c.X, π := { app := λ j, (c.ι.app (unop j)).unop, naturality' := λ j j' f, begin apply has_hom.hom.op_inj, dsimp, simp only [category.comp_id], exact (c.w f.unop).symm, end }} /-- Given a cone over `F.op ⋙ H`, we can construct a `cone H` with the same cone point. -/ @[simps] def extend_cone : cone (F.op ⋙ H) ⥤ cone H := { obj := λ c, extend_cone_cocone_to_cone (extend_cocone.obj (extend_cone_cone_to_cocone c)), map := λ X Y f, { hom := f.hom, } } @[simp] lemma limit_cone_comp_aux (s : cone (F.op ⋙ H)) (j : Cᵒᵖ) : s.π.app (op (lift F (F.obj (unop j)))) ≫ H.map (hom_to_lift F (F.obj (unop j))).op = s.π.app j := begin apply has_hom.hom.op_inj, exact colimit_cocone_comp_aux (extend_cone_cone_to_cocone s) (unop j) end variables (F G H) /-- If `F` is cofinal, the category of cocones on `F ⋙ G` is equivalent to the category of cocones on `G`, for any `G : D ⥤ E`. -/ @[simps] def cocones_equiv : cocone (F ⋙ G) ≌ cocone G := { functor := extend_cocone, inverse := cocones.whiskering F, unit_iso := nat_iso.of_components (λ c, cocones.ext (iso.refl _) (by tidy)) (by tidy), counit_iso := nat_iso.of_components (λ c, cocones.ext (iso.refl _) (by tidy)) (by tidy), }. /-- If `F` is cofinal, the category of cones on `F.op ⋙ H` is equivalent to the category of cones on `H`, for any `H : Dᵒᵖ ⥤ E`. -/ @[simps] def cones_equiv : cone (F.op ⋙ H) ≌ cone H := { functor := extend_cone, inverse := cones.whiskering F.op, unit_iso := nat_iso.of_components (λ c, cones.ext (iso.refl _) (by tidy)) (by tidy), counit_iso := nat_iso.of_components (λ c, cones.ext (iso.refl _) (by tidy)) (by tidy), }. -- We could have done this purely formally in terms of `cocones_equiv`, -- without having defined `extend_cone` at all, -- but it comes at the cost of moving a *lot* of opposites around: -- (((cones.functoriality_equivalence _ (op_op_equivalence E)).symm.trans -- ((((cocone_equivalence_op_cone_op _).symm.trans -- (cocones_equiv F (unop_unop _ ⋙ H.op))).trans -- (cocone_equivalence_op_cone_op _)).unop)).trans -- (cones.functoriality_equivalence _ (op_op_equivalence E))).trans -- (cones.postcompose_equivalence (nat_iso.of_components (λ X, iso.refl _) (by tidy) : -- H ≅ (unop_unop D ⋙ H.op).op ⋙ (op_op_equivalence E).functor)).symm variables {G H} /-- When `F : C ⥤ D` is cofinal, and `t : cocone G` for some `G : D ⥤ E`, `t.whisker F` is a colimit cocone exactly when `t` is. -/ def is_colimit_whisker_equiv (t : cocone G) : is_colimit (t.whisker F) ≃ is_colimit t := is_colimit.of_cocone_equiv (cocones_equiv F G).symm /-- When `F : C ⥤ D` is cofinal, and `t : cone H` for some `H : Dᵒᵖ ⥤ E`, `t.whisker F.op` is a limit cone exactly when `t` is. -/ def is_limit_whisker_equiv (t : cone H) : is_limit (t.whisker F.op) ≃ is_limit t := is_limit.of_cone_equiv (cones_equiv F H).symm /-- When `F` is cofinal, and `t : cocone (F ⋙ G)`, `extend_cocone.obj t` is a colimit coconne exactly when `t` is. -/ def is_colimit_extend_cocone_equiv (t : cocone (F ⋙ G)) : is_colimit (extend_cocone.obj t) ≃ is_colimit t := is_colimit.of_cocone_equiv (cocones_equiv F G) /-- When `F` is cofinal, and `t : cone (F.op ⋙ H)`, `extend_cone.obj t` is a limit conne exactly when `t` is. -/ def is_limit_extend_cone_equiv (t : cone (F.op ⋙ H)) : is_limit (extend_cone.obj t) ≃ is_limit t := is_limit.of_cone_equiv (cones_equiv F H) /-- Given a colimit cocone over `G : D ⥤ E` we can construct a colimit cocone over `F ⋙ G`. -/ @[simps] def colimit_cocone_comp (t : colimit_cocone G) : colimit_cocone (F ⋙ G) := { cocone := _, is_colimit := (is_colimit_whisker_equiv F _).symm (t.is_colimit) } /-- Given a limit cone over `H : Dᵒᵖ ⥤ E` we can construct a limit cone over `F.op ⋙ H`. -/ @[simps] def limit_cone_comp (t : limit_cone H) : limit_cone (F.op ⋙ H) := { cone := _, is_limit := (is_limit_whisker_equiv F _).symm (t.is_limit) } @[priority 100] instance comp_has_colimit [has_colimit G] : has_colimit (F ⋙ G) := has_colimit.mk (colimit_cocone_comp F (get_colimit_cocone G)) @[priority 100] instance comp_has_limit [has_limit H] : has_limit (F.op ⋙ H) := has_limit.mk (limit_cone_comp F (get_limit_cone H)) lemma colimit_pre_is_iso_aux {t : cocone G} (P : is_colimit t) : ((is_colimit_whisker_equiv F _).symm P).desc (t.whisker F) = 𝟙 t.X := begin dsimp [is_colimit_whisker_equiv], apply P.hom_ext, intro j, dsimp, simp, end instance colimit_pre_is_iso [has_colimit G] : is_iso (colimit.pre G F) := begin rw colimit.pre_eq (colimit_cocone_comp F (get_colimit_cocone G)) (get_colimit_cocone G), erw colimit_pre_is_iso_aux, dsimp, apply_instance, end lemma limit_pre_is_iso_aux {t : cone H} (P : is_limit t) : ((is_limit_whisker_equiv F _).symm P).lift (t.whisker F.op) = 𝟙 t.X := begin dsimp [is_limit_whisker_equiv], apply P.hom_ext, intro j, simp, refl, end instance limit_pre_is_iso [has_limit H] : is_iso (limit.pre H F.op) := begin rw limit.pre_eq (limit_cone_comp F (get_limit_cone H)) (get_limit_cone H), erw limit_pre_is_iso_aux, dsimp, apply_instance, end section variables (G H) /-- When `F : C ⥤ D` is cofinal, and `G : D ⥤ E` has a colimit, then `F ⋙ G` has a colimit also and `colimit (F ⋙ G) ≅ colimit G` https://stacks.math.columbia.edu/tag/04E7 -/ def colimit_iso [has_colimit G] : colimit (F ⋙ G) ≅ colimit G := as_iso (colimit.pre G F) /-- When `F : C ⥤ D` is cofinal, and `H : Dᵒᵖ ⥤ E` has a limit, then `F.op ⋙ H` has a limit also and `limit (F.op ⋙ H) ≅ limit H` https://stacks.math.columbia.edu/tag/04E7 -/ def limit_iso [has_limit H] : limit (F.op ⋙ H) ≅ limit H := (as_iso (limit.pre H F.op)).symm end /-- Given a colimit cocone over `F ⋙ G` we can construct a colimit cocone over `G`. -/ @[simps] def colimit_cocone_of_comp (t : colimit_cocone (F ⋙ G)) : colimit_cocone G := { cocone := extend_cocone.obj t.cocone, is_colimit := (is_colimit_extend_cocone_equiv F _).symm (t.is_colimit), } /-- Given a limit cone over `F.op ⋙ H` we can construct a limit cone over `H`. -/ @[simps] def limit_cone_of_comp (t : limit_cone (F.op ⋙ H)) : limit_cone H := { cone := extend_cone.obj t.cone, is_limit := (is_limit_extend_cone_equiv F _).symm (t.is_limit), } /-- When `F` is cofinal, and `F ⋙ G` has a colimit, then `G` has a colimit also. We can't make this an instance, because `F` is not determined by the goal. (Even if this weren't a problem, it would cause a loop with `comp_has_colimit`.) -/ lemma has_colimit_of_comp [has_colimit (F ⋙ G)] : has_colimit G := has_colimit.mk (colimit_cocone_of_comp F (get_colimit_cocone (F ⋙ G))) /-- When `F` is cofinal, and `F.op ⋙ H` has a limit, then `H` has a limit also. We can't make this an instance, because `F` is not determined by the goal. (Even if this weren't a problem, it would cause a loop with `comp_has_limit`.) -/ lemma has_limit_of_comp [has_limit (F.op ⋙ H)] : has_limit H := has_limit.mk (limit_cone_of_comp F (get_limit_cone (F.op ⋙ H))) section local attribute [instance] has_colimit_of_comp has_limit_of_comp /-- When `F` is cofinal, and `F ⋙ G` has a colimit, then `G` has a colimit also and `colimit (F ⋙ G) ≅ colimit G` https://stacks.math.columbia.edu/tag/04E7 -/ def colimit_iso' [has_colimit (F ⋙ G)] : colimit (F ⋙ G) ≅ colimit G := as_iso (colimit.pre G F) /-- When `F` is cofinal, and `F.op ⋙ H` has a limit, then `H` has a limit also and `limit (F.op ⋙ H) ≅ limit H` https://stacks.math.columbia.edu/tag/04E7 -/ def limit_iso' [has_limit (F.op ⋙ H)] : limit (F.op ⋙ H) ≅ limit H := (as_iso (limit.pre H F.op)).symm end /-- If the universal morphism `colimit (F ⋙ coyoneda.obj (op d)) ⟶ colimit (coyoneda.obj (op d))` is an isomorphism (as it always is when `F` is cofinal), then `colimit (F ⋙ coyoneda.obj (op d)) ≅ punit` (simply because `colimit (coyoneda.obj (op d)) ≅ punit`). -/ def colimit_comp_coyoneda_iso (d : D) [is_iso (colimit.pre (coyoneda.obj (op d)) F)] : colimit (F ⋙ coyoneda.obj (op d)) ≅ punit := as_iso (colimit.pre (coyoneda.obj (op d)) F) ≪≫ coyoneda.colimit_coyoneda_iso (op d) lemma zigzag_of_eqv_gen_quot_rel {F : C ⥤ D} {d : D} {f₁ f₂ : Σ X, d ⟶ F.obj X} (t : eqv_gen (types.quot.rel (F ⋙ coyoneda.obj (op d))) f₁ f₂) : zigzag ({left := punit.star, right := f₁.1, hom := f₁.2} : comma (functor.from_punit d) F) {left := punit.star, right := f₂.1, hom := f₂.2} := begin induction t, case eqv_gen.rel : x y r { obtain ⟨f, w⟩ := r, fconstructor, swap 2, fconstructor, left, fsplit, exact { right := f, } }, case eqv_gen.refl { fconstructor, }, case eqv_gen.symm : x y h ih { apply zigzag_symmetric, exact ih, }, case eqv_gen.trans : x y z h₁ h₂ ih₁ ih₂ { apply relation.refl_trans_gen.trans, exact ih₁, exact ih₂, } end /-- If `colimit (F ⋙ coyoneda.obj (op d)) ≅ punit` for all `d : D`, then `F` is cofinal. -/ lemma cofinal_of_colimit_comp_coyoneda_iso_punit (I : Π d, colimit (F ⋙ coyoneda.obj (op d)) ≅ punit) : cofinal F := λ d, begin haveI : nonempty (comma (functor.from_punit d) F) := by { have := (I d).inv punit.star, obtain ⟨j, y, rfl⟩ := limits.types.jointly_surjective' this, exact ⟨{right := j, hom := y}⟩, }, apply zigzag_is_connected, rintros ⟨⟨⟩,X₁,f₁⟩ ⟨⟨⟩,X₂,f₂⟩, dsimp at *, let y₁ := colimit.ι (F ⋙ coyoneda.obj (op d)) X₁ f₁, let y₂ := colimit.ι (F ⋙ coyoneda.obj (op d)) X₂ f₂, have e : y₁ = y₂, { apply (I d).to_equiv.injective, ext, }, have t := types.colimit_eq e, clear e y₁ y₂, exact zigzag_of_eqv_gen_quot_rel t, end end cofinal end category_theory
f1c2d1d10bd72de861a56103e24cecca7a7a8852
4fa161becb8ce7378a709f5992a594764699e268
/src/algebra/continued_fractions/basic.lean
0b583b592dc2a2a01d42f985f04c08f77b3ab400
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
13,337
lean
/- Copyright (c) 2019 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import data.seq.seq import algebra.field /-! # Basic Definitions/Theorems for Continued Fractions ## Summary We define generalised, simple, and regular continued fractions and functions to evaluate their convergents. We follow the naming conventions from Wikipedia and [wall2018analytic], Chapter 1. ## Main definitions 1. Generalised continued fractions (gcfs) 2. Simple continued fractions (scfs) 3. (Regular) continued fractions ((r)cfs) 4. Computation of convergents using the recurrence relation in `convergents`. 5. Computation of convergents by directly evaluating the fraction described by the gcf in `convergents'`. ## Implementation notes 1. The most commonly used kind of continued fractions in the literature are regular continued fractions. We hence just call them `continued_fractions` in the library. 2. We use sequences from `data.seq` to encode potentially infinite sequences. ## References - <https://en.wikipedia.org/wiki/Generalized_continued_fraction> - [Wall, H.S., *Analytic Theory of Continued Fractions*][wall2018analytic] ## Tags numerics, number theory, approximations, fractions -/ -- Fix a carrier `α`. variable (α : Type*) /-- We collect a partial numerator `aᵢ` and partial denominator `bᵢ` in a pair `⟨aᵢ,bᵢ⟩`. -/ @[derive inhabited] protected structure generalized_continued_fraction.pair := (a : α) (b : α) /- Interlude: define some expected coercions and instances. -/ namespace generalized_continued_fraction.pair open generalized_continued_fraction as gcf /-- Make a gcf.pair printable. -/ instance [has_repr α] : has_repr (gcf.pair α) := ⟨λ p, "(a : " ++ (repr p.a) ++ ", b : " ++ (repr p.b) ++ ")"⟩ section coe /-! Interlude: define some expected coercions. -/ /- Fix another type `β` and assume `α` can be converted to `β`. -/ variables {α} {β : Type*} [has_coe α β] /-- Coerce a pair by elementwise coercion. -/ instance has_coe_to_generalized_continued_fraction_pair : has_coe (gcf.pair α) (gcf.pair β) := ⟨λ ⟨a, b⟩, ⟨(a : β), (b : β)⟩⟩ @[simp, norm_cast] lemma coe_to_generalized_continued_fraction_pair {a b : α} : (↑(gcf.pair.mk a b) : gcf.pair β) = gcf.pair.mk (a : β) (b : β) := rfl end coe end generalized_continued_fraction.pair /-- A *generalised continued fraction* (gcf) is a potentially infinite expression of the form a₀ h + --------------------------- a₁ b₀ + -------------------- a₂ b₁ + -------------- a₃ b₂ + -------- b₃ + ... where `h` is called the *head term* or *integer part*, the `aᵢ` are called the *partial numerators* and the `bᵢ` the *partial denominators* of the gcf. We store the sequence of partial numerators and denominators in a sequence of generalized_continued_fraction.pairs `s`. For convenience, one often writes `[h; (a₀, b₀), (a₁, b₁), (a₂, b₂),...]`. -/ structure generalized_continued_fraction := (h : α) (s : seq $ generalized_continued_fraction.pair α) variable {α} namespace generalized_continued_fraction open generalized_continued_fraction as gcf /-- Constructs a generalized continued fraction without fractional part. -/ def of_integer (a : α) : gcf α := ⟨a, seq.nil⟩ instance [inhabited α] : inhabited (gcf α) := ⟨of_integer (default _)⟩ /-- Returns the sequence of partial numerators `aᵢ` of `g`. -/ def partial_numerators (g : gcf α) : seq α := g.s.map gcf.pair.a /-- Returns the sequence of partial denominators `bᵢ` of `g`. -/ def partial_denominators (g : gcf α) : seq α := g.s.map gcf.pair.b /-- A gcf terminated at position `n` if its sequence terminates at position `n`. -/ def terminated_at (g : gcf α) (n : ℕ) : Prop := g.s.terminated_at n /-- It is decidable whether a gcf terminated at a given position. -/ instance terminated_at_decidable (g : gcf α) (n : ℕ) : decidable (g.terminated_at n) := by { unfold terminated_at, apply_instance } /-- A gcf terminates if its sequence terminates. -/ def terminates (g : gcf α) : Prop := g.s.terminates section coe /-! Interlude: define some expected coercions. -/ -- Fix another type `β` and assume `α` can be converted to `β`. variables {β : Type*} [has_coe α β] /-- Coerce a sequence by elementwise coercion. -/ def seq.coe_to_seq : has_coe (seq α) (seq β) := ⟨seq.map (λ a, (a : β))⟩ local attribute [instance] seq.coe_to_seq /-- Coerce a gcf by elementwise coercion. -/ instance has_coe_to_generalized_continued_fraction : has_coe (gcf α) (gcf β) := ⟨λ ⟨h, s⟩, ⟨(h : β), (s : seq $ gcf.pair β)⟩⟩ @[simp, norm_cast] lemma coe_to_generalized_continued_fraction {g : gcf α} : (↑(g : gcf α) : gcf β) = ⟨(g.h : β), (g.s : seq $ gcf.pair β)⟩ := by { cases g, refl } end coe end generalized_continued_fraction /-- A generalized continued fraction is a *simple continued fraction* if all partial numerators are equal to one. 1 h + --------------------------- 1 b₀ + -------------------- 1 b₁ + -------------- 1 b₂ + -------- b₃ + ... -/ def generalized_continued_fraction.is_simple_continued_fraction (g : generalized_continued_fraction α) [has_one α] : Prop := ∀ (n : ℕ) (aₙ : α), g.partial_numerators.nth n = some aₙ → aₙ = 1 variable (α) /-- A *simple continued fraction* (scf) is a generalized continued fraction (gcf) whose partial numerators are equal to one. 1 h + --------------------------- 1 b₀ + -------------------- 1 b₁ + -------------- 1 b₂ + -------- b₃ + ... For convenience, one often writes `[h; b₀, b₁, b₂,...]`. It is encoded as the subtype of gcfs that satisfy `generalized_continued_fraction.is_simple_continued_fraction`. -/ def simple_continued_fraction [has_one α] := {g : generalized_continued_fraction α // g.is_simple_continued_fraction} variable {α} /- Interlude: define some expected coercions. -/ namespace simple_continued_fraction open generalized_continued_fraction as gcf open simple_continued_fraction as scf variable [has_one α] /-- Constructs a simple continued fraction without fractional part. -/ def of_integer (a : α) : scf α := ⟨gcf.of_integer a, λ n aₙ h, by cases h⟩ instance : inhabited (scf α) := ⟨of_integer 1⟩ /-- Lift a scf to a gcf using the inclusion map. -/ instance has_coe_to_generalized_continued_fraction : has_coe (scf α) (gcf α) := by {unfold scf, apply_instance} @[simp, norm_cast] lemma coe_to_generalized_continued_fraction {s : scf α} : (↑s : gcf α) = s.val := rfl end simple_continued_fraction /-- A simple continued fraction is a *(regular) continued fraction* ((r)cf) if all partial denominators `bᵢ` are positive, i.e. `0 < bᵢ`. -/ def simple_continued_fraction.is_regular_continued_fraction [has_one α] [has_zero α] [has_lt α] (s : simple_continued_fraction α) : Prop := ∀ (n : ℕ) (bₙ : α), (↑s : generalized_continued_fraction α).partial_denominators.nth n = some bₙ → 0 < bₙ variable (α) /-- A *(regular) continued fraction* ((r)cf) is a simple continued fraction (scf) whose partial denominators are all positive. It is the subtype of scfs that satisfy `simple_continued_fraction.is_regular_continued_fraction`. -/ def continued_fraction [has_one α] [has_zero α] [has_lt α] := {s : simple_continued_fraction α // s.is_regular_continued_fraction} variable {α} /- Interlude: define some expected coercions. -/ namespace continued_fraction open generalized_continued_fraction as gcf open simple_continued_fraction as scf open continued_fraction as cf variables [has_one α] [has_zero α] [has_lt α] /-- Constructs a continued fraction without fractional part. -/ def of_integer (a : α) : cf α := ⟨scf.of_integer a, λ n bₙ h, by cases h⟩ instance : inhabited (cf α) := ⟨of_integer 0⟩ /-- Lift a cf to a scf using the inclusion map. -/ instance has_coe_to_simple_continued_fraction : has_coe (cf α) (scf α) := by {unfold cf, apply_instance} @[simp, norm_cast] lemma coe_to_simple_continued_fraction {c : cf α} : (↑c : scf α) = c.val := rfl /-- Lift a cf to a scf using the inclusion map. -/ instance has_coe_to_generalized_continued_fraction : has_coe (cf α) (gcf α) := ⟨λ c, ↑(↑c : scf α)⟩ @[simp, norm_cast squash] lemma coe_to_generalized_continued_fraction {c : cf α} : (↑c : gcf α) = c.val := rfl end continued_fraction /- We now define how to compute the convergents of a gcf. There are two standard ways to do this: directly evaluating the (infinite) fraction described by the gcf or using a recurrence relation. For (r)cfs, these computations are equivalent as shown in `algebra.continued_fractions.convergents_equiv`. -/ namespace generalized_continued_fraction open generalized_continued_fraction as gcf -- Fix a division ring for the computations. variables {K : Type*} [division_ring K] /- We start with the definition of the recurrence relation. Given a gcf `g`, for all `n ≥ 1`, we define - `A₋₁ = 1, A₀ = h, Aₙ = bₙ₋₁ * Aₙ₋₁ + aₙ₋₁ * Aₙ₋₂`, and - `B₋₁ = 0, B₀ = 1, Bₙ = bₙ₋₁ * Bₙ₋₁ + aₙ₋₁ * Bₙ₋₂`. `Aₙ, `Bₙ` are called the *nth continuants*, Aₙ the *nth numerator*, and `Bₙ` the *nth denominator* of `g`. The *nth convergent* of `g` is given by `Aₙ / Bₙ`. -/ /-- Returns the next numerator `Aₙ = bₙ₋₁ * Aₙ₋₁ + aₙ₋₁ * Aₙ₋₂`, where `predA` is `Aₙ₋₁`, `ppredA` is `Aₙ₋₂`, `a` is `aₙ₋₁`, and `b` is `bₙ₋₁`. -/ def next_numerator (a b ppredA predA : K) : K := b * predA + a * ppredA /-- Returns the next denominator `Bₙ = bₙ₋₁ * Bₙ₋₁ + aₙ₋₁ * Bₙ₋₂``, where `predB` is `Bₙ₋₁` and `ppredB` is `Bₙ₋₂`, `a` is `aₙ₋₁`, and `b` is `bₙ₋₁`. -/ def next_denominator (aₙ bₙ ppredB predB : K) : K := bₙ * predB + aₙ * ppredB /-- Returns the next continuants `⟨Aₙ, Bₙ⟩` using `next_numerator` and `next_denominator`, where `pred` is `⟨Aₙ₋₁, Bₙ₋₁⟩`, `ppred` is `⟨Aₙ₋₂, Bₙ₋₂⟩`, `a` is `aₙ₋₁`, and `b` is `bₙ₋₁`. -/ def next_continuants (a b : K) (ppred pred : gcf.pair K) : gcf.pair K := ⟨next_numerator a b ppred.a pred.a, next_denominator a b ppred.b pred.b⟩ /-- Returns the continuants `⟨Aₙ₋₁, Bₙ₋₁⟩` of `g`. -/ def continuants_aux (g : gcf K) : stream (gcf.pair K) | 0 := ⟨1, 0⟩ | 1 := ⟨g.h, 1⟩ | (n + 2) := match g.s.nth n with | none := continuants_aux (n + 1) | some gp := next_continuants gp.a gp.b (continuants_aux n) (continuants_aux $ n + 1) end /-- Returns the continuants `⟨Aₙ, Bₙ⟩` of `g`. -/ def continuants (g : gcf K) : stream (gcf.pair K) := g.continuants_aux.tail /-- Returns the numerators `Aₙ` of `g`. -/ def numerators (g : gcf K) : stream K := g.continuants.map gcf.pair.a /-- Returns the denominators `Bₙ` of `g`. -/ def denominators (g : gcf K) : stream K := g.continuants.map gcf.pair.b /-- Returns the convergents `Aₙ / Bₙ` of `g`, where `Aₙ, Bₙ` are the nth continuants of `g`. -/ def convergents (g : gcf K) : stream K := λ (n : ℕ), (g.numerators n) / (g.denominators n) /-- Returns the approximation of the fraction described by the given sequence up to a given position n. For example, `convergents'_aux [(1, 2), (3, 4), (5, 6)] 2 = 1 / (2 + 3 / 4)` and `convergents'_aux [(1, 2), (3, 4), (5, 6)] 0 = 0`. -/ def convergents'_aux : seq (gcf.pair K) → ℕ → K | s 0 := 0 | s (n + 1) := match s.head with | none := 0 | some gp := gp.a / (gp.b + convergents'_aux s.tail n) end /-- Returns the convergents of `g` by evaluating the fraction described by `g` up to a given position `n`. For example, `convergents' [9; (1, 2), (3, 4), (5, 6)] 2 = 9 + 1 / (2 + 3 / 4)` and `convergents' [9; (1, 2), (3, 4), (5, 6)] 0 = 9` -/ def convergents' (g : gcf K) (n : ℕ) : K := g.h + convergents'_aux g.s n end generalized_continued_fraction -- Now, some basic, general theorems namespace generalized_continued_fraction open generalized_continued_fraction as gcf /-- Two gcfs `g` and `g'` are equal if and only if their components are equal. -/ protected lemma ext_iff {g g' : gcf α} : g = g' ↔ g.h = g'.h ∧ g.s = g'.s := by { cases g, cases g', simp } @[ext] protected lemma ext {g g' : gcf α} (hyp : g.h = g'.h ∧ g.s = g'.s) : g = g' := generalized_continued_fraction.ext_iff.elim_right hyp end generalized_continued_fraction
4d19d271661be3a6f78574cae9c9add585524a15
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/over_subst.lean
aac82d69d1088aaef364b6aa7303a3fd9b56a5cc
[ "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
803
lean
namespace experiment namespace nat constant nat : Type.{1} constant add : nat → nat → nat constant le : nat → nat → Prop constant one : nat infixl (name := nat.add) `+` := add infix (name := nat.le) `≤` := le axiom add_assoc (a b c : nat) : (a + b) + c = a + (b + c) axiom add_le_left {a b : nat} (H : a ≤ b) (c : nat) : c + a ≤ c + b end nat namespace int constant int : Type.{1} constant add : int → int → int constant le : int → int → Prop constant one1 : int infixl (name := int.add) `+` := add infix (name := int.le) `≤` := le axiom add_assoc (a b c : int) : (a + b) + c = a + (b + c) axiom add_le_left {a b : int} (H : a ≤ b) (c : int) : c + a ≤ c + b noncomputable definition lt (a b : int) := a + one1 ≤ b infix (name := int.lt) `<` := lt end int end experiment
cdb39ef2e6170e19b437c9d7ed26771749f0670f
471bedbd023d35c9d078c2f936dd577ace7f5813
/library/init/propext.lean
45c46027f17bccc9f25802c420a773e2b20952cd
[ "Apache-2.0" ]
permissive
lambdaxymox/lean
e06f0fa503666df827edd9867d7f49ca017aae64
fc13c8c72a15dab71a2c2b31410c2cadc3526bd7
refs/heads/master
1,666,785,407,985
1,666,153,673,000
1,666,153,673,000
310,165,986
0
0
Apache-2.0
1,604,542,096,000
1,604,542,095,000
null
UTF-8
Lean
false
false
1,113
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.logic constant propext {a b : Prop} : (a ↔ b) → a = b /- Additional congruence lemmas. -/ universes u v lemma forall_congr_eq {a : Sort u} {p q : a → Prop} (h : ∀ x, p x = q x) : (∀ x, p x) = ∀ x, q x := propext (forall_congr (λ a, (h a).to_iff)) lemma imp_congr_eq {a b c d : Prop} (h₁ : a = c) (h₂ : b = d) : (a → b) = (c → d) := propext (imp_congr h₁.to_iff h₂.to_iff) lemma imp_congr_ctx_eq {a b c d : Prop} (h₁ : a = c) (h₂ : c → (b = d)) : (a → b) = (c → d) := propext (imp_congr_ctx h₁.to_iff (λ hc, (h₂ hc).to_iff)) lemma eq_true_intro {a : Prop} (h : a) : a = true := propext (iff_true_intro h) lemma eq_false_intro {a : Prop} (h : ¬a) : a = false := propext (iff_false_intro h) theorem iff.to_eq {a b : Prop} (h : a ↔ b) : a = b := propext h theorem iff_eq_eq {a b : Prop} : (a ↔ b) = (a = b) := propext (iff.intro (assume h, iff.to_eq h) (assume h, h.to_iff))
713660a01aaa5a2bb766e7a2f65a3d6b05726199
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/src/Lean/Compiler/IR/EmitC.lean
4ede1d8a0fed6ec076cd7409bf70d1db9a475b10
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,083
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.Runtime import Lean.Compiler.NameMangling import Lean.Compiler.ExportAttr import Lean.Compiler.InitAttr import Lean.Compiler.IR.CompilerM import Lean.Compiler.IR.EmitUtil import Lean.Compiler.IR.NormIds import Lean.Compiler.IR.SimpCase import Lean.Compiler.IR.Boxing namespace Lean.IR.EmitC open ExplicitBoxing (requiresBoxedVersion mkBoxedName isBoxedName) def leanMainFn := "_lean_main" structure Context := (env : Environment) (modName : Name) (jpMap : JPParamsMap := {}) (mainFn : FunId := arbitrary _) (mainParams : Array Param := #[]) abbrev M := ReaderT Context (EStateM String String) def getEnv : M Environment := Context.env <$> read def getModName : M Name := Context.modName <$> read def getDecl (n : Name) : M Decl := do let env ← getEnv match findEnvDecl env n with | some d => pure d | none => throw s!"unknown declaration '{n}'" @[inline] def emit {α : Type} [ToString α] (a : α) : M Unit := modify fun out => out ++ toString a @[inline] def emitLn {α : Type} [ToString α] (a : α) : M Unit := do emit a; emit "\n" def emitLns {α : Type} [ToString α] (as : List α) : M Unit := as.forM fun a => emitLn a def argToCString (x : Arg) : String := match x with | Arg.var x => toString x | _ => "lean_box(0)" def emitArg (x : Arg) : M Unit := emit (argToCString x) def toCType : IRType → String | IRType.float => "double" | IRType.uint8 => "uint8_t" | IRType.uint16 => "uint16_t" | IRType.uint32 => "uint32_t" | IRType.uint64 => "uint64_t" | IRType.usize => "size_t" | IRType.object => "lean_object*" | IRType.tobject => "lean_object*" | IRType.irrelevant => "lean_object*" | IRType.struct _ _ => panic! "not implemented yet" | IRType.union _ _ => panic! "not implemented yet" def throwInvalidExportName {α : Type} (n : Name) : M α := throw s!"invalid export name '{n}'" def toCName (n : Name) : M String := do let env ← getEnv; -- TODO: we should support simple export names only match getExportNameFor env n with | some (Name.str Name.anonymous s _) => pure s | some _ => throwInvalidExportName n | none => if n == `main then pure leanMainFn else pure n.mangle def emitCName (n : Name) : M Unit := toCName n >>= emit def toCInitName (n : Name) : M String := do let env ← getEnv; -- TODO: we should support simple export names only match getExportNameFor env n with | some (Name.str Name.anonymous s _) => pure $ "_init_" ++ s | some _ => throwInvalidExportName n | none => pure ("_init_" ++ n.mangle) def emitCInitName (n : Name) : M Unit := toCInitName n >>= emit def emitFnDeclAux (decl : Decl) (cppBaseName : String) (addExternForConsts : Bool) : M Unit := do let ps := decl.params let env ← getEnv if ps.isEmpty && addExternForConsts then emit "extern " emit (toCType decl.resultType ++ " " ++ cppBaseName) unless ps.isEmpty do emit "(" -- We omit irrelevant parameters for extern constants let ps := if isExternC env decl.name then ps.filter (fun p => !p.ty.isIrrelevant) else ps if ps.size > closureMaxArgs && isBoxedName decl.name then emit "lean_object**" else ps.size.forM fun i => do if i > 0 then emit ", " emit (toCType ps[i].ty) emit ")" emitLn ";" def emitFnDecl (decl : Decl) (addExternForConsts : Bool) : M Unit := do let cppBaseName ← toCName decl.name emitFnDeclAux decl cppBaseName addExternForConsts def emitExternDeclAux (decl : Decl) (cNameStr : String) : M Unit := do let cName := Name.mkSimple cNameStr let env ← getEnv let extC := isExternC env decl.name emitFnDeclAux decl cNameStr (!extC) def emitFnDecls : M Unit := do let env ← getEnv let decls := getDecls env let modDecls : NameSet := decls.foldl (fun s d => s.insert d.name) {} let usedDecls : NameSet := decls.foldl (fun s d => collectUsedDecls env d (s.insert d.name)) {} let usedDecls := usedDecls.toList usedDecls.forM fun n => do let decl ← getDecl n; match getExternNameFor env `c decl.name with | some cName => emitExternDeclAux decl cName | none => emitFnDecl decl (!modDecls.contains n) def emitMainFn : M Unit := do let d ← getDecl `main match d with | Decl.fdecl f xs t b => do unless xs.size == 2 || xs.size == 1 do throw "invalid main function, incorrect arity when generating code" let env ← getEnv let usesLeanAPI := usesModuleFrom env `Lean if usesLeanAPI then emitLn "void lean_initialize();" else emitLn "void lean_initialize_runtime_module();"; emitLn " #if defined(WIN32) || defined(_WIN32) #include <windows.h> #endif int main(int argc, char ** argv) { #if defined(WIN32) || defined(_WIN32) SetErrorMode(SEM_FAILCRITICALERRORS); #endif lean_object* in; lean_object* res;"; if usesLeanAPI then emitLn "lean_initialize();" else emitLn "lean_initialize_runtime_module();" let modName ← getModName emitLn ("res = " ++ mkModuleInitializationFunctionName modName ++ "(lean_io_mk_world());") emitLns ["lean_io_mark_end_initialization();", "if (lean_io_result_is_ok(res)) {", "lean_dec_ref(res);", "lean_init_task_manager();"]; if xs.size == 2 then emitLns ["in = lean_box(0);", "int i = argc;", "while (i > 1) {", " lean_object* n;", " i--;", " n = lean_alloc_ctor(1,2,0); lean_ctor_set(n, 0, lean_mk_string(argv[i])); lean_ctor_set(n, 1, in);", " in = n;", "}"] emitLn ("res = " ++ leanMainFn ++ "(in, lean_io_mk_world());") else emitLn ("res = " ++ leanMainFn ++ "(lean_io_mk_world());") emitLn "}" emitLns ["if (lean_io_result_is_ok(res)) {", " int ret = lean_unbox(lean_io_result_get_value(res));", " lean_dec_ref(res);", " return ret;", "} else {", " lean_io_result_show_error(res);", " lean_dec_ref(res);", " return 1;", "}"] emitLn "}" | other => throw "function declaration expected" def hasMainFn : M Bool := do let env ← getEnv let decls := getDecls env pure $ decls.any (fun d => d.name == `main) def emitMainFnIfNeeded : M Unit := do if (← hasMainFn) then emitMainFn def emitFileHeader : M Unit := do let env ← getEnv let modName ← getModName emitLn "// Lean compiler output" emitLn ("// Module: " ++ toString modName) emit "// Imports:" env.imports.forM fun m => emit (" " ++ toString m) emitLn "" emitLn "#include <lean/lean.h>" emitLns [ "#if defined(__clang__)", "#pragma clang diagnostic ignored \"-Wunused-parameter\"", "#pragma clang diagnostic ignored \"-Wunused-label\"", "#elif defined(__GNUC__) && !defined(__CLANG__)", "#pragma GCC diagnostic ignored \"-Wunused-parameter\"", "#pragma GCC diagnostic ignored \"-Wunused-label\"", "#pragma GCC diagnostic ignored \"-Wunused-but-set-variable\"", "#endif", "#ifdef __cplusplus", "extern \"C\" {", "#endif" ] def emitFileFooter : M Unit := emitLns [ "#ifdef __cplusplus", "}", "#endif" ] def throwUnknownVar {α : Type} (x : VarId) : M α := throw s!"unknown variable '{x}'" def getJPParams (j : JoinPointId) : M (Array Param) := do let ctx ← read; match ctx.jpMap.find? j with | some ps => pure ps | none => throw "unknown join point" def declareVar (x : VarId) (t : IRType) : M Unit := do emit (toCType t); emit " "; emit x; emit "; " def declareParams (ps : Array Param) : M Unit := ps.forM fun p => declareVar p.x p.ty partial def declareVars : FnBody → Bool → M Bool | e@(FnBody.vdecl x t _ b), d => do let ctx ← read if isTailCallTo ctx.mainFn e then pure d else declareVar x t; declareVars b true | FnBody.jdecl j xs _ b, d => do declareParams xs; declareVars b (d || xs.size > 0) | e, d => if e.isTerminal then pure d else declareVars e.body d def emitTag (x : VarId) (xType : IRType) : M Unit := do if xType.isObj then do emit "lean_obj_tag("; emit x; emit ")" else emit x def isIf (alts : Array Alt) : Option (Nat × FnBody × FnBody) := if alts.size != 2 then none else match alts[0] with | Alt.ctor c b => some (c.cidx, b, alts[1].body) | _ => none def emitInc (x : VarId) (n : Nat) (checkRef : Bool) : M Unit := do emit $ if checkRef then (if n == 1 then "lean_inc" else "lean_inc_n") else (if n == 1 then "lean_inc_ref" else "lean_inc_ref_n") emit "("; emit x if n != 1 then emit ", "; emit n emitLn ");" def emitDec (x : VarId) (n : Nat) (checkRef : Bool) : M Unit := do emit (if checkRef then "lean_dec" else "lean_dec_ref"); emit "("; emit x; if n != 1 then emit ", "; emit n emitLn ");" def emitDel (x : VarId) : M Unit := do emit "lean_free_object("; emit x; emitLn ");" def emitSetTag (x : VarId) (i : Nat) : M Unit := do emit "lean_ctor_set_tag("; emit x; emit ", "; emit i; emitLn ");" def emitSet (x : VarId) (i : Nat) (y : Arg) : M Unit := do emit "lean_ctor_set("; emit x; emit ", "; emit i; emit ", "; emitArg y; emitLn ");" def emitOffset (n : Nat) (offset : Nat) : M Unit := do if n > 0 then emit "sizeof(void*)*"; emit n; if offset > 0 then emit " + "; emit offset else emit offset def emitUSet (x : VarId) (n : Nat) (y : VarId) : M Unit := do emit "lean_ctor_set_usize("; emit x; emit ", "; emit n; emit ", "; emit y; emitLn ");" def emitSSet (x : VarId) (n : Nat) (offset : Nat) (y : VarId) (t : IRType) : M Unit := do match t with | IRType.float => emit "lean_ctor_set_float" | IRType.uint8 => emit "lean_ctor_set_uint8" | IRType.uint16 => emit "lean_ctor_set_uint16" | IRType.uint32 => emit "lean_ctor_set_uint32" | IRType.uint64 => emit "lean_ctor_set_uint64" | _ => throw "invalid instruction"; emit "("; emit x; emit ", "; emitOffset n offset; emit ", "; emit y; emitLn ");" def emitJmp (j : JoinPointId) (xs : Array Arg) : M Unit := do let ps ← getJPParams j unless xs.size == ps.size do throw "invalid goto" xs.size.forM fun i => do let p := ps[i] let x := xs[i] emit p.x; emit " = "; emitArg x; emitLn ";" emit "goto "; emit j; emitLn ";" def emitLhs (z : VarId) : M Unit := do emit z; emit " = " def emitArgs (ys : Array Arg) : M Unit := ys.size.forM fun i => do if i > 0 then emit ", " emitArg ys[i] def emitCtorScalarSize (usize : Nat) (ssize : Nat) : M Unit := do if usize == 0 then emit ssize else if ssize == 0 then emit "sizeof(size_t)*"; emit usize else emit "sizeof(size_t)*"; emit usize; emit " + "; emit ssize def emitAllocCtor (c : CtorInfo) : M Unit := do emit "lean_alloc_ctor("; emit c.cidx; emit ", "; emit c.size; emit ", "; emitCtorScalarSize c.usize c.ssize; emitLn ");" def emitCtorSetArgs (z : VarId) (ys : Array Arg) : M Unit := ys.size.forM fun i => do emit "lean_ctor_set("; emit z; emit ", "; emit i; emit ", "; emitArg ys[i]; emitLn ");" def emitCtor (z : VarId) (c : CtorInfo) (ys : Array Arg) : M Unit := do emitLhs z; if c.size == 0 && c.usize == 0 && c.ssize == 0 then do emit "lean_box("; emit c.cidx; emitLn ");" else do emitAllocCtor c; emitCtorSetArgs z ys def emitReset (z : VarId) (n : Nat) (x : VarId) : M Unit := do emit "if (lean_is_exclusive("; emit x; emitLn ")) {"; n.forM fun i => do emit " lean_ctor_release("; emit x; emit ", "; emit i; emitLn ");" emit " "; emitLhs z; emit x; emitLn ";"; emitLn "} else {"; emit " lean_dec_ref("; emit x; emitLn ");"; emit " "; emitLhs z; emitLn "lean_box(0);"; emitLn "}" def emitReuse (z : VarId) (x : VarId) (c : CtorInfo) (updtHeader : Bool) (ys : Array Arg) : M Unit := do emit "if (lean_is_scalar("; emit x; emitLn ")) {"; emit " "; emitLhs z; emitAllocCtor c; emitLn "} else {"; emit " "; emitLhs z; emit x; emitLn ";"; if updtHeader then emit " lean_ctor_set_tag("; emit z; emit ", "; emit c.cidx; emitLn ");" emitLn "}"; emitCtorSetArgs z ys def emitProj (z : VarId) (i : Nat) (x : VarId) : M Unit := do emitLhs z; emit "lean_ctor_get("; emit x; emit ", "; emit i; emitLn ");" def emitUProj (z : VarId) (i : Nat) (x : VarId) : M Unit := do emitLhs z; emit "lean_ctor_get_usize("; emit x; emit ", "; emit i; emitLn ");" def emitSProj (z : VarId) (t : IRType) (n offset : Nat) (x : VarId) : M Unit := do emitLhs z; match t with | IRType.float => emit "lean_ctor_get_float" | IRType.uint8 => emit "lean_ctor_get_uint8" | IRType.uint16 => emit "lean_ctor_get_uint16" | IRType.uint32 => emit "lean_ctor_get_uint32" | IRType.uint64 => emit "lean_ctor_get_uint64" | _ => throw "invalid instruction" emit "("; emit x; emit ", "; emitOffset n offset; emitLn ");" def toStringArgs (ys : Array Arg) : List String := ys.toList.map argToCString def emitSimpleExternalCall (f : String) (ps : Array Param) (ys : Array Arg) : M Unit := do emit f; emit "(" -- We must remove irrelevant arguments to extern calls. ys.size.foldM (fun i (first : Bool) => if ps[i].ty.isIrrelevant then pure first else do unless first do emit ", " emitArg ys[i] pure false) true emitLn ");" pure () def emitExternCall (f : FunId) (ps : Array Param) (extData : ExternAttrData) (ys : Array Arg) : M Unit := match getExternEntryFor extData `c with | some (ExternEntry.standard _ extFn) => emitSimpleExternalCall extFn ps ys | some (ExternEntry.inline _ pat) => do emit (expandExternPattern pat (toStringArgs ys)); emitLn ";" | some (ExternEntry.foreign _ extFn) => emitSimpleExternalCall extFn ps ys | _ => throw s!"failed to emit extern application '{f}'" def emitFullApp (z : VarId) (f : FunId) (ys : Array Arg) : M Unit := do emitLhs z let decl ← getDecl f match decl with | Decl.extern _ ps _ extData => emitExternCall f ps extData ys | _ => emitCName f if ys.size > 0 then emit "("; emitArgs ys; emit ")" emitLn ";" def emitPartialApp (z : VarId) (f : FunId) (ys : Array Arg) : M Unit := do let decl ← getDecl f let arity := decl.params.size; emitLhs z; emit "lean_alloc_closure((void*)("; emitCName f; emit "), "; emit arity; emit ", "; emit ys.size; emitLn ");"; ys.size.forM fun i => do let y := ys[i] emit "lean_closure_set("; emit z; emit ", "; emit i; emit ", "; emitArg y; emitLn ");" def emitApp (z : VarId) (f : VarId) (ys : Array Arg) : M Unit := if ys.size > closureMaxArgs then do emit "{ lean_object* _aargs[] = {"; emitArgs ys; emitLn "};"; emitLhs z; emit "lean_apply_m("; emit f; emit ", "; emit ys.size; emitLn ", _aargs); }" else do emitLhs z; emit "lean_apply_"; emit ys.size; emit "("; emit f; emit ", "; emitArgs ys; emitLn ");" def emitBoxFn (xType : IRType) : M Unit := match xType with | IRType.usize => emit "lean_box_usize" | IRType.uint32 => emit "lean_box_uint32" | IRType.uint64 => emit "lean_box_uint64" | IRType.float => emit "lean_box_float" | other => emit "lean_box" def emitBox (z : VarId) (x : VarId) (xType : IRType) : M Unit := do emitLhs z; emitBoxFn xType; emit "("; emit x; emitLn ");" def emitUnbox (z : VarId) (t : IRType) (x : VarId) : M Unit := do emitLhs z; match t with | IRType.usize => emit "lean_unbox_usize" | IRType.uint32 => emit "lean_unbox_uint32" | IRType.uint64 => emit "lean_unbox_uint64" | IRType.float => emit "lean_unbox_float" | other => emit "lean_unbox"; emit "("; emit x; emitLn ");" def emitIsShared (z : VarId) (x : VarId) : M Unit := do emitLhs z; emit "!lean_is_exclusive("; emit x; emitLn ");" def emitIsTaggedPtr (z : VarId) (x : VarId) : M Unit := do emitLhs z; emit "!lean_is_scalar("; emit x; emitLn ");" def toHexDigit (c : Nat) : String := String.singleton c.digitChar def quoteString (s : String) : String := let q := "\""; let q := s.foldl (fun q c => q ++ if c == '\n' then "\\n" else if c == '\n' then "\\t" else if c == '\\' then "\\\\" else if c == '\"' then "\\\"" else if c.toNat <= 31 then "\\x" ++ toHexDigit (c.toNat / 16) ++ toHexDigit (c.toNat % 16) -- TODO(Leo): we should use `\unnnn` for escaping unicode characters. else String.singleton c) q; q ++ "\"" def emitNumLit (t : IRType) (v : Nat) : M Unit := do if t.isObj then if v < uint32Sz then emit "lean_unsigned_to_nat("; emit v; emit "u)" else emit "lean_cstr_to_nat(\""; emit v; emit "\")" else emit v def emitLit (z : VarId) (t : IRType) (v : LitVal) : M Unit := do emitLhs z; match v with | LitVal.num v => emitNumLit t v; emitLn ";" | LitVal.str v => emit "lean_mk_string("; emit (quoteString v); emitLn ");" def emitVDecl (z : VarId) (t : IRType) (v : Expr) : M Unit := match v with | Expr.ctor c ys => emitCtor z c ys | Expr.reset n x => emitReset z n x | Expr.reuse x c u ys => emitReuse z x c u ys | Expr.proj i x => emitProj z i x | Expr.uproj i x => emitUProj z i x | Expr.sproj n o x => emitSProj z t n o x | Expr.fap c ys => emitFullApp z c ys | Expr.pap c ys => emitPartialApp z c ys | Expr.ap x ys => emitApp z x ys | Expr.box t x => emitBox z x t | Expr.unbox x => emitUnbox z t x | Expr.isShared x => emitIsShared z x | Expr.isTaggedPtr x => emitIsTaggedPtr z x | Expr.lit v => emitLit z t v def isTailCall (x : VarId) (v : Expr) (b : FnBody) : M Bool := do let ctx ← read; match v, b with | Expr.fap f _, FnBody.ret (Arg.var y) => pure $ f == ctx.mainFn && x == y | _, _ => pure false def paramEqArg (p : Param) (x : Arg) : Bool := match x with | Arg.var x => p.x == x | _ => false /- Given `[p_0, ..., p_{n-1}]`, `[y_0, ..., y_{n-1}]`, representing the assignments ``` p_0 := y_0, ... p_{n-1} := y_{n-1} ``` Return true iff we have `(i, j)` where `j > i`, and `y_j == p_i`. That is, we have ``` p_i := y_i, ... p_j := p_i, -- p_i was overwritten above ``` -/ def overwriteParam (ps : Array Param) (ys : Array Arg) : Bool := let n := ps.size; n.any $ fun i => let p := ps[i] (i+1, n).anyI fun j => paramEqArg p ys[j] def emitTailCall (v : Expr) : M Unit := match v with | Expr.fap _ ys => do let ctx ← read let ps := ctx.mainParams unless ps.size == ys.size do throw "invalid tail call" if overwriteParam ps ys then emitLn "{" ps.size.forM fun i => do let p := ps[i] let y := ys[i] unless paramEqArg p y do emit (toCType p.ty); emit " _tmp_"; emit i; emit " = "; emitArg y; emitLn ";" ps.size.forM fun i => do let p := ps[i] let y := ys[i] unless paramEqArg p y do emit p.x; emit " = _tmp_"; emit i; emitLn ";" emitLn "}" else ys.size.forM fun i => do let p := ps[i] let y := ys[i] unless paramEqArg p y do emit p.x; emit " = "; emitArg y; emitLn ";" emitLn "goto _start;" | _ => throw "bug at emitTailCall" mutual partial def emitIf (x : VarId) (xType : IRType) (tag : Nat) (t : FnBody) (e : FnBody) : M Unit := do emit "if ("; emitTag x xType; emit " == "; emit tag; emitLn ")"; emitFnBody t; emitLn "else"; emitFnBody e partial def emitCase (x : VarId) (xType : IRType) (alts : Array Alt) : M Unit := match isIf alts with | some (tag, t, e) => emitIf x xType tag t e | _ => do emit "switch ("; emitTag x xType; emitLn ") {"; let alts := ensureHasDefault alts; alts.forM fun alt => do match alt with | Alt.ctor c b => emit "case "; emit c.cidx; emitLn ":"; emitFnBody b | Alt.default b => emitLn "default: "; emitFnBody b emitLn "}" partial def emitBlock (b : FnBody) : M Unit := do match b with | FnBody.jdecl j xs v b => emitBlock b | d@(FnBody.vdecl x t v b) => let ctx ← read if isTailCallTo ctx.mainFn d then emitTailCall v else emitVDecl x t v emitBlock b | FnBody.inc x n c p b => unless p do emitInc x n c emitBlock b | FnBody.dec x n c p b => unless p do emitDec x n c emitBlock b | FnBody.del x b => emitDel x; emitBlock b | FnBody.setTag x i b => emitSetTag x i; emitBlock b | FnBody.set x i y b => emitSet x i y; emitBlock b | FnBody.uset x i y b => emitUSet x i y; emitBlock b | FnBody.sset x i o y t b => emitSSet x i o y t; emitBlock b | FnBody.mdata _ b => emitBlock b | FnBody.ret x => emit "return "; emitArg x; emitLn ";" | FnBody.case _ x xType alts => emitCase x xType alts | FnBody.jmp j xs => emitJmp j xs | FnBody.unreachable => emitLn "lean_panic_unreachable();" partial def emitJPs : FnBody → M Unit | FnBody.jdecl j xs v b => do emit j; emitLn ":"; emitFnBody v; emitJPs b | e => do unless e.isTerminal do emitJPs e.body partial def emitFnBody (b : FnBody) : M Unit := do emitLn "{" let declared ← declareVars b false if declared then emitLn "" emitBlock b emitJPs b emitLn "}" end def emitDeclAux (d : Decl) : M Unit := do let env ← getEnv let (vMap, jpMap) := mkVarJPMaps d withReader (fun ctx => { ctx with jpMap := jpMap }) do unless hasInitAttr env d.name do match d with | Decl.fdecl f xs t b => let baseName ← toCName f; if xs.size == 0 then emit "static " emit (toCType t); emit " "; if xs.size > 0 then emit baseName; emit "("; if xs.size > closureMaxArgs && isBoxedName d.name then emit "lean_object** _args" else xs.size.forM fun i => do if i > 0 then emit ", " let x := xs[i] emit (toCType x.ty); emit " "; emit x.x emit ")" else emit ("_init_" ++ baseName ++ "()") emitLn " {"; if xs.size > closureMaxArgs && isBoxedName d.name then xs.size.forM fun i => do let x := xs[i] emit "lean_object* "; emit x.x; emit " = _args["; emit i; emitLn "];" emitLn "_start:"; withReader (fun ctx => { ctx with mainFn := f, mainParams := xs }) (emitFnBody b); emitLn "}" | _ => pure () def emitDecl (d : Decl) : M Unit := do let d := d.normalizeIds; -- ensure we don't have gaps in the variable indices try emitDeclAux d catch err => throw s!"{err}\ncompiling:\n{d}" def emitFns : M Unit := do let env ← getEnv; let decls := getDecls env; decls.reverse.forM emitDecl def emitMarkPersistent (d : Decl) (n : Name) : M Unit := do if d.resultType.isObj then emit "lean_mark_persistent(" emitCName n emitLn ");" def emitDeclInit (d : Decl) : M Unit := do let env ← getEnv let n := d.name if isIOUnitInitFn env n then emit "res = "; emitCName n; emitLn "(lean_io_mk_world());" emitLn "if (lean_io_result_is_error(res)) return res;" emitLn "lean_dec_ref(res);" else if d.params.size == 0 then match getInitFnNameFor? env d.name with | some initFn => emit "res = "; emitCName initFn; emitLn "(lean_io_mk_world());" emitLn "if (lean_io_result_is_error(res)) return res;" emitCName n; emitLn " = lean_io_result_get_value(res);" emitMarkPersistent d n emitLn "lean_dec_ref(res);" | _ => emitCName n; emit " = "; emitCInitName n; emitLn "();"; emitMarkPersistent d n def emitInitFn : M Unit := do let env ← getEnv let modName ← getModName env.imports.forM fun imp => emitLn ("lean_object* " ++ mkModuleInitializationFunctionName imp.module ++ "(lean_object*);") emitLns [ "static bool _G_initialized = false;", "lean_object* " ++ mkModuleInitializationFunctionName modName ++ "(lean_object* w) {", "lean_object * res;", "if (_G_initialized) return lean_io_result_mk_ok(lean_box(0));", "_G_initialized = true;" ] env.imports.forM fun imp => emitLns [ "res = " ++ mkModuleInitializationFunctionName imp.module ++ "(lean_io_mk_world());", "if (lean_io_result_is_error(res)) return res;", "lean_dec_ref(res);"] let decls := getDecls env decls.reverse.forM emitDeclInit emitLns ["return lean_io_result_mk_ok(lean_box(0));", "}"] def main : M Unit := do emitFileHeader emitFnDecls emitFns emitInitFn emitMainFnIfNeeded emitFileFooter end EmitC @[export lean_ir_emit_c] def emitC (env : Environment) (modName : Name) : Except String String := match (EmitC.main { env := env, modName := modName }).run "" with | EStateM.Result.ok _ s => Except.ok s | EStateM.Result.error err _ => Except.error err end Lean.IR
76bb2f5de017edb8f58770277929641a2db919c3
07c6143268cfb72beccd1cc35735d424ebcb187b
/src/data/fintype/basic.lean
d784025c687499ebf4bb89d7b340a7e662e0207a
[ "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
39,398
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Finite types. -/ import data.finset data.array.lemmas logic.unique import tactic.wlog universes u v variables {α : Type*} {β : Type*} {γ : Type*} /-- `fintype α` means that `α` is finite, i.e. there are only finitely many distinct elements of type `α`. The evidence of this is a finset `elems` (a list up to permutation without duplicates), together with a proof that everything of type `α` is in the list. -/ class fintype (α : Type*) := (elems [] : finset α) (complete : ∀ x : α, x ∈ elems) namespace finset variable [fintype α] /-- `univ` is the universal finite set of type `finset α` implied from the assumption `fintype α`. -/ def univ : finset α := fintype.elems α @[simp] theorem mem_univ (x : α) : x ∈ (univ : finset α) := fintype.complete x @[simp] theorem mem_univ_val : ∀ x, x ∈ (univ : finset α).1 := mem_univ @[simp] lemma coe_univ : ↑(univ : finset α) = (set.univ : set α) := by ext; simp theorem subset_univ (s : finset α) : s ⊆ univ := λ a _, mem_univ a theorem eq_univ_iff_forall {s : finset α} : s = univ ↔ ∀ x, x ∈ s := by simp [ext] @[simp] lemma piecewise_univ [∀i : α, decidable (i ∈ (univ : finset α))] {δ : α → Sort*} (f g : Πi, δ i) : univ.piecewise f g = f := by { ext i, simp [piecewise] } end finset open finset function namespace fintype instance decidable_pi_fintype {α} {β : α → Type*} [∀a, decidable_eq (β a)] [fintype α] : decidable_eq (Πa, β a) := assume f g, decidable_of_iff (∀ a ∈ fintype.elems α, f a = g a) (by simp [function.funext_iff, fintype.complete]) instance decidable_forall_fintype {p : α → Prop} [decidable_pred p] [fintype α] : decidable (∀ a, p a) := decidable_of_iff (∀ a ∈ @univ α _, p a) (by simp) instance decidable_exists_fintype {p : α → Prop} [decidable_pred p] [fintype α] : decidable (∃ a, p a) := decidable_of_iff (∃ a ∈ @univ α _, p a) (by simp) instance decidable_eq_equiv_fintype [decidable_eq β] [fintype α] : decidable_eq (α ≃ β) := λ a b, decidable_of_iff (a.1 = b.1) ⟨λ h, equiv.ext _ _ (congr_fun h), congr_arg _⟩ instance decidable_injective_fintype [decidable_eq α] [decidable_eq β] [fintype α] : decidable_pred (injective : (α → β) → Prop) := λ x, by unfold injective; apply_instance instance decidable_surjective_fintype [decidable_eq β] [fintype α] [fintype β] : decidable_pred (surjective : (α → β) → Prop) := λ x, by unfold surjective; apply_instance instance decidable_bijective_fintype [decidable_eq α] [decidable_eq β] [fintype α] [fintype β] : decidable_pred (bijective : (α → β) → Prop) := λ x, by unfold bijective; apply_instance instance decidable_left_inverse_fintype [decidable_eq α] [fintype α] (f : α → β) (g : β → α) : decidable (function.right_inverse f g) := show decidable (∀ x, g (f x) = x), by apply_instance instance decidable_right_inverse_fintype [decidable_eq β] [fintype β] (f : α → β) (g : β → α) : decidable (function.left_inverse f g) := show decidable (∀ x, f (g x) = x), by apply_instance /-- Construct a proof of `fintype α` from a universal multiset -/ def of_multiset [decidable_eq α] (s : multiset α) (H : ∀ x : α, x ∈ s) : fintype α := ⟨s.to_finset, by simpa using H⟩ /-- Construct a proof of `fintype α` from a universal list -/ def of_list [decidable_eq α] (l : list α) (H : ∀ x : α, x ∈ l) : fintype α := ⟨l.to_finset, by simpa using H⟩ theorem exists_univ_list (α) [fintype α] : ∃ l : list α, l.nodup ∧ ∀ x : α, x ∈ l := let ⟨l, e⟩ := quotient.exists_rep (@univ α _).1 in by have := and.intro univ.2 mem_univ_val; exact ⟨_, by rwa ← e at this⟩ /-- `card α` is the number of elements in `α`, defined when `α` is a fintype. -/ def card (α) [fintype α] : ℕ := (@univ α _).card /-- If `l` lists all the elements of `α` without duplicates, then `α ≃ fin (l.length)`. -/ def equiv_fin_of_forall_mem_list {α} [decidable_eq α] {l : list α} (h : ∀ x:α, x ∈ l) (nd : l.nodup) : α ≃ fin (l.length) := ⟨λ a, ⟨_, list.index_of_lt_length.2 (h a)⟩, λ i, l.nth_le i.1 i.2, λ a, by simp, λ ⟨i, h⟩, fin.eq_of_veq $ list.nodup_iff_nth_le_inj.1 nd _ _ (list.index_of_lt_length.2 (list.nth_le_mem _ _ _)) h $ by simp⟩ /-- There is (computably) a bijection between `α` and `fin n` where `n = card α`. Since it is not unique, and depends on which permutation of the universe list is used, the bijection is wrapped in `trunc` to preserve computability. -/ def equiv_fin (α) [fintype α] [decidable_eq α] : trunc (α ≃ fin (card α)) := by unfold card finset.card; exact quot.rec_on_subsingleton (@univ α _).1 (λ l (h : ∀ x:α, x ∈ l) (nd : l.nodup), trunc.mk (equiv_fin_of_forall_mem_list h nd)) mem_univ_val univ.2 theorem exists_equiv_fin (α) [fintype α] : ∃ n, nonempty (α ≃ fin n) := by haveI := classical.dec_eq α; exact ⟨card α, nonempty_of_trunc (equiv_fin α)⟩ /-- Given a linearly ordered fintype `α` of cardinal `k`, the equiv `mono_equiv_of_fin α h` is the increasing bijection between `fin k` and `α`. Here, `h` is a proof that the cardinality of `s` is `k`. We use this instead of a map `fin s.card → α` to avoid casting issues in further uses of this function. -/ noncomputable def mono_equiv_of_fin (α) [fintype α] [decidable_linear_order α] {k : ℕ} (h : fintype.card α = k) : fin k ≃ α := have A : bijective (mono_of_fin univ h) := begin apply set.bijective_iff_bij_on_univ.2, rw ← @coe_univ α _, exact mono_of_fin_bij_on (univ : finset α) h end, equiv.of_bijective A instance (α : Type*) : subsingleton (fintype α) := ⟨λ ⟨s₁, h₁⟩ ⟨s₂, h₂⟩, by congr; simp [finset.ext, h₁, h₂]⟩ protected def subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : fintype {x // p x} := ⟨⟨multiset.pmap subtype.mk s.1 (λ x, (H x).1), multiset.nodup_pmap (λ a _ b _, congr_arg subtype.val) s.2⟩, λ ⟨x, px⟩, multiset.mem_pmap.2 ⟨x, (H x).2 px, rfl⟩⟩ theorem subtype_card {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : @card {x // p x} (fintype.subtype s H) = s.card := multiset.card_pmap _ _ _ theorem card_of_subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) [fintype {x // p x}] : card {x // p x} = s.card := by rw ← subtype_card s H; congr /-- Construct a fintype from a finset with the same elements. -/ def of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : fintype p := fintype.subtype s H @[simp] theorem card_of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : @fintype.card p (of_finset s H) = s.card := fintype.subtype_card s H theorem card_of_finset' {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) [fintype p] : fintype.card p = s.card := by rw ← card_of_finset s H; congr /-- If `f : α → β` is a bijection and `α` is a fintype, then `β` is also a fintype. -/ def of_bijective [fintype α] (f : α → β) (H : function.bijective f) : fintype β := ⟨univ.map ⟨f, H.1⟩, λ b, let ⟨a, e⟩ := H.2 b in e ▸ mem_map_of_mem _ (mem_univ _)⟩ /-- If `f : α → β` is a surjection and `α` is a fintype, then `β` is also a fintype. -/ def of_surjective [fintype α] [decidable_eq β] (f : α → β) (H : function.surjective f) : fintype β := ⟨univ.image f, λ b, let ⟨a, e⟩ := H b in e ▸ mem_image_of_mem _ (mem_univ _)⟩ noncomputable def of_injective [fintype β] (f : α → β) (H : function.injective f) : fintype α := by letI := classical.dec; exact if hα : nonempty α then by letI := classical.inhabited_of_nonempty hα; exact of_surjective (inv_fun f) (inv_fun_surjective H) else ⟨∅, λ x, (hα ⟨x⟩).elim⟩ /-- If `f : α ≃ β` and `α` is a fintype, then `β` is also a fintype. -/ def of_equiv (α : Type*) [fintype α] (f : α ≃ β) : fintype β := of_bijective _ f.bijective theorem of_equiv_card [fintype α] (f : α ≃ β) : @card β (of_equiv α f) = card α := multiset.card_map _ _ theorem card_congr {α β} [fintype α] [fintype β] (f : α ≃ β) : card α = card β := by rw ← of_equiv_card f; congr theorem card_eq {α β} [F : fintype α] [G : fintype β] : card α = card β ↔ nonempty (α ≃ β) := ⟨λ h, ⟨by classical; calc α ≃ fin (card α) : trunc.out (equiv_fin α) ... ≃ fin (card β) : by rw h ... ≃ β : (trunc.out (equiv_fin β)).symm⟩, λ ⟨f⟩, card_congr f⟩ def of_subsingleton (a : α) [subsingleton α] : fintype α := ⟨finset.singleton a, λ b, finset.mem_singleton.2 (subsingleton.elim _ _)⟩ @[simp] theorem univ_of_subsingleton (a : α) [subsingleton α] : @univ _ (of_subsingleton a) = finset.singleton a := rfl @[simp] theorem card_of_subsingleton (a : α) [subsingleton α] : @fintype.card _ (of_subsingleton a) = 1 := rfl end fintype namespace set /-- Construct a finset enumerating a set `s`, given a `fintype` instance. -/ def to_finset (s : set α) [fintype s] : finset α := ⟨(@finset.univ s _).1.map subtype.val, multiset.nodup_map (λ a b, subtype.eq) finset.univ.2⟩ @[simp] theorem mem_to_finset {s : set α} [fintype s] {a : α} : a ∈ s.to_finset ↔ a ∈ s := by simp [to_finset] @[simp] theorem mem_to_finset_val {s : set α} [fintype s] {a : α} : a ∈ s.to_finset.1 ↔ a ∈ s := mem_to_finset end set lemma finset.card_univ [fintype α] : (finset.univ : finset α).card = fintype.card α := rfl lemma finset.card_univ_diff [fintype α] [decidable_eq α] (s : finset α) : (finset.univ \ s).card = fintype.card α - s.card := finset.card_sdiff (subset_univ s) instance (n : ℕ) : fintype (fin n) := ⟨⟨list.fin_range n, list.nodup_fin_range n⟩, list.mem_fin_range⟩ @[simp] theorem fintype.card_fin (n : ℕ) : fintype.card (fin n) = n := list.length_fin_range n @[simp] lemma finset.card_fin (n : ℕ) : finset.card (finset.univ : finset (fin n)) = n := by rw [finset.card_univ, fintype.card_fin] lemma fin.univ_succ (n : ℕ) : (univ : finset (fin $ n+1)) = insert 0 (univ.image fin.succ) := begin ext m, simp only [mem_univ, mem_insert, true_iff, mem_image, exists_prop], exact fin.cases (or.inl rfl) (λ i, or.inr ⟨i, trivial, rfl⟩) m end lemma fin.univ_cast_succ (n : ℕ) : (univ : finset (fin $ n+1)) = insert (fin.last n) (univ.image fin.cast_succ) := begin ext m, simp only [mem_univ, mem_insert, true_iff, mem_image, exists_prop, true_and], by_cases h : m.val < n, { right, use fin.cast_lt m h, rw fin.cast_succ_cast_lt }, { left, exact fin.eq_last_of_not_lt h } end /-- Any increasing map between `fin k` and a finset of cardinality `k` has to coincide with the increasing bijection `mono_of_fin s h`. -/ lemma finset.mono_of_fin_unique' [decidable_linear_order α] {s : finset α} {k : ℕ} (h : s.card = k) {f : fin k → α} (fmap : set.maps_to f set.univ ↑s) (hmono : strict_mono f) : f = s.mono_of_fin h := begin have finj : set.inj_on f set.univ := hmono.injective.inj_on _, apply mono_of_fin_unique h (set.bij_on.mk fmap finj (λ y hy, _)) hmono, simp only [set.image_univ, set.mem_range], rcases surj_on_of_inj_on_of_card_le (λ i (hi : i ∈ finset.univ), f i) (λ i hi, fmap (set.mem_univ i)) (λ i j hi hj hij, finj (set.mem_univ i) (set.mem_univ j) hij) (by simp [h]) y hy with ⟨x, _, hx⟩, exact ⟨x, hx.symm⟩ end @[instance, priority 10] def unique.fintype {α : Type*} [unique α] : fintype α := ⟨finset.singleton (default α), λ x, by rw [unique.eq_default x]; simp⟩ @[simp] lemma univ_unique {α : Type*} [unique α] [f : fintype α] : @finset.univ α _ = {default α} := by rw [subsingleton.elim f (@unique.fintype α _)]; refl instance : fintype empty := ⟨∅, empty.rec _⟩ @[simp] theorem fintype.univ_empty : @univ empty _ = ∅ := rfl @[simp] theorem fintype.card_empty : fintype.card empty = 0 := rfl instance : fintype pempty := ⟨∅, pempty.rec _⟩ @[simp] theorem fintype.univ_pempty : @univ pempty _ = ∅ := rfl @[simp] theorem fintype.card_pempty : fintype.card pempty = 0 := rfl instance : fintype unit := fintype.of_subsingleton () theorem fintype.univ_unit : @univ unit _ = {()} := rfl theorem fintype.card_unit : fintype.card unit = 1 := rfl instance : fintype punit := fintype.of_subsingleton punit.star @[simp] theorem fintype.univ_punit : @univ punit _ = {punit.star} := rfl @[simp] theorem fintype.card_punit : fintype.card punit = 1 := rfl instance : fintype bool := ⟨⟨tt::ff::0, by simp⟩, λ x, by cases x; simp⟩ @[simp] theorem fintype.univ_bool : @univ bool _ = {ff, tt} := rfl instance units_int.fintype : fintype (units ℤ) := ⟨{1, -1}, λ x, by cases int.units_eq_one_or x; simp *⟩ instance additive.fintype : Π [fintype α], fintype (additive α) := id instance multiplicative.fintype : Π [fintype α], fintype (multiplicative α) := id @[simp] theorem fintype.card_units_int : fintype.card (units ℤ) = 2 := rfl noncomputable instance [monoid α] [fintype α] : fintype (units α) := by classical; exact fintype.of_injective units.val units.ext @[simp] theorem fintype.card_bool : fintype.card bool = 2 := rfl def finset.insert_none (s : finset α) : finset (option α) := ⟨none :: s.1.map some, multiset.nodup_cons.2 ⟨by simp, multiset.nodup_map (λ a b, option.some.inj) s.2⟩⟩ @[simp] theorem finset.mem_insert_none {s : finset α} : ∀ {o : option α}, o ∈ s.insert_none ↔ ∀ a ∈ o, a ∈ s | none := iff_of_true (multiset.mem_cons_self _ _) (λ a h, by cases h) | (some a) := multiset.mem_cons.trans $ by simp; refl theorem finset.some_mem_insert_none {s : finset α} {a : α} : some a ∈ s.insert_none ↔ a ∈ s := by simp instance {α : Type*} [fintype α] : fintype (option α) := ⟨univ.insert_none, λ a, by simp⟩ @[simp] theorem fintype.card_option {α : Type*} [fintype α] : fintype.card (option α) = fintype.card α + 1 := (multiset.card_cons _ _).trans (by rw multiset.card_map; refl) instance {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype (sigma β) := ⟨univ.sigma (λ _, univ), λ ⟨a, b⟩, by simp⟩ instance (α β : Type*) [fintype α] [fintype β] : fintype (α × β) := ⟨univ.product univ, λ ⟨a, b⟩, by simp⟩ @[simp] theorem fintype.card_prod (α β : Type*) [fintype α] [fintype β] : fintype.card (α × β) = fintype.card α * fintype.card β := card_product _ _ def fintype.fintype_prod_left {α β} [decidable_eq α] [fintype (α × β)] [nonempty β] : fintype α := ⟨(fintype.elems (α × β)).image prod.fst, assume a, let ⟨b⟩ := ‹nonempty β› in by simp; exact ⟨b, fintype.complete _⟩⟩ def fintype.fintype_prod_right {α β} [decidable_eq β] [fintype (α × β)] [nonempty α] : fintype β := ⟨(fintype.elems (α × β)).image prod.snd, assume b, let ⟨a⟩ := ‹nonempty α› in by simp; exact ⟨a, fintype.complete _⟩⟩ instance (α : Type*) [fintype α] : fintype (ulift α) := fintype.of_equiv _ equiv.ulift.symm @[simp] theorem fintype.card_ulift (α : Type*) [fintype α] : fintype.card (ulift α) = fintype.card α := fintype.of_equiv_card _ instance (α : Type u) (β : Type v) [fintype α] [fintype β] : fintype (α ⊕ β) := @fintype.of_equiv _ _ (@sigma.fintype _ (λ b, cond b (ulift α) (ulift.{(max u v) v} β)) _ (λ b, by cases b; apply ulift.fintype)) ((equiv.sum_equiv_sigma_bool _ _).symm.trans (equiv.sum_congr equiv.ulift equiv.ulift)) lemma fintype.card_le_of_injective [fintype α] [fintype β] (f : α → β) (hf : function.injective f) : fintype.card α ≤ fintype.card β := by haveI := classical.prop_decidable; exact finset.card_le_card_of_inj_on f (λ _ _, finset.mem_univ _) (λ _ _ _ _ h, hf h) lemma fintype.card_eq_one_iff [fintype α] : fintype.card α = 1 ↔ (∃ x : α, ∀ y, y = x) := by rw [← fintype.card_unit, fintype.card_eq]; exact ⟨λ ⟨a⟩, ⟨a.symm (), λ y, a.injective (subsingleton.elim _ _)⟩, λ ⟨x, hx⟩, ⟨⟨λ _, (), λ _, x, λ _, (hx _).trans (hx _).symm, λ _, subsingleton.elim _ _⟩⟩⟩ lemma fintype.card_eq_zero_iff [fintype α] : fintype.card α = 0 ↔ (α → false) := ⟨λ h a, have e : α ≃ empty := classical.choice (fintype.card_eq.1 (by simp [h])), (e a).elim, λ h, have e : α ≃ empty := ⟨λ a, (h a).elim, λ a, a.elim, λ a, (h a).elim, λ a, a.elim⟩, by simp [fintype.card_congr e]⟩ lemma fintype.card_pos_iff [fintype α] : 0 < fintype.card α ↔ nonempty α := ⟨λ h, classical.by_contradiction (λ h₁, have fintype.card α = 0 := fintype.card_eq_zero_iff.2 (λ a, h₁ ⟨a⟩), lt_irrefl 0 $ by rwa this at h), λ ⟨a⟩, nat.pos_of_ne_zero (mt fintype.card_eq_zero_iff.1 (λ h, h a))⟩ lemma fintype.card_le_one_iff [fintype α] : fintype.card α ≤ 1 ↔ (∀ a b : α, a = b) := let n := fintype.card α in have hn : n = fintype.card α := rfl, match n, hn with | 0 := λ ha, ⟨λ h, λ a, (fintype.card_eq_zero_iff.1 ha.symm a).elim, λ _, ha ▸ nat.le_succ _⟩ | 1 := λ ha, ⟨λ h, λ a b, let ⟨x, hx⟩ := fintype.card_eq_one_iff.1 ha.symm in by rw [hx a, hx b], λ _, ha ▸ le_refl _⟩ | (n+2) := λ ha, ⟨λ h, by rw ← ha at h; exact absurd h dec_trivial, (λ h, fintype.card_unit ▸ fintype.card_le_of_injective (λ _, ()) (λ _ _ _, h _ _))⟩ end lemma fintype.exists_ne_of_one_lt_card [fintype α] (h : 1 < fintype.card α) (a : α) : ∃ b : α, b ≠ a := let ⟨b, hb⟩ := classical.not_forall.1 (mt fintype.card_le_one_iff.2 (not_le_of_gt h)) in let ⟨c, hc⟩ := classical.not_forall.1 hb in by haveI := classical.dec_eq α; exact if hba : b = a then ⟨c, by cc⟩ else ⟨b, hba⟩ lemma fintype.injective_iff_surjective [fintype α] {f : α → α} : injective f ↔ surjective f := by haveI := classical.prop_decidable; exact have ∀ {f : α → α}, injective f → surjective f, from λ f hinj x, have h₁ : image f univ = univ := eq_of_subset_of_card_le (subset_univ _) ((card_image_of_injective univ hinj).symm ▸ le_refl _), have h₂ : x ∈ image f univ := h₁.symm ▸ mem_univ _, exists_of_bex (mem_image.1 h₂), ⟨this, λ hsurj, injective_of_has_left_inverse ⟨surj_inv hsurj, left_inverse_of_surjective_of_right_inverse (this (injective_surj_inv _)) (right_inverse_surj_inv _)⟩⟩ lemma fintype.injective_iff_bijective [fintype α] {f : α → α} : injective f ↔ bijective f := by simp [bijective, fintype.injective_iff_surjective] lemma fintype.surjective_iff_bijective [fintype α] {f : α → α} : surjective f ↔ bijective f := by simp [bijective, fintype.injective_iff_surjective] lemma fintype.injective_iff_surjective_of_equiv [fintype α] {f : α → β} (e : α ≃ β) : injective f ↔ surjective f := have injective (e.symm ∘ f) ↔ surjective (e.symm ∘ f), from fintype.injective_iff_surjective, ⟨λ hinj, by simpa [function.comp] using surjective_comp e.surjective (this.1 (injective_comp e.symm.injective hinj)), λ hsurj, by simpa [function.comp] using injective_comp e.injective (this.2 (surjective_comp e.symm.surjective hsurj))⟩ lemma fintype.coe_image_univ [fintype α] [decidable_eq β] {f : α → β} : ↑(finset.image f finset.univ) = set.range f := by { ext x, simp } instance list.subtype.fintype [decidable_eq α] (l : list α) : fintype {x // x ∈ l} := fintype.of_list l.attach l.mem_attach instance multiset.subtype.fintype [decidable_eq α] (s : multiset α) : fintype {x // x ∈ s} := fintype.of_multiset s.attach s.mem_attach instance finset.subtype.fintype (s : finset α) : fintype {x // x ∈ s} := ⟨s.attach, s.mem_attach⟩ instance finset_coe.fintype (s : finset α) : fintype (↑s : set α) := finset.subtype.fintype s @[simp] lemma fintype.card_coe (s : finset α) : fintype.card (↑s : set α) = s.card := card_attach lemma finset.card_le_one_iff {s : finset α} : s.card ≤ 1 ↔ ∀ {x y}, x ∈ s → y ∈ s → x = y := begin let t : set α := ↑s, letI : fintype t := finset_coe.fintype s, have : fintype.card t = s.card := fintype.card_coe s, rw [← this, fintype.card_le_one_iff], split, { assume H x y hx hy, exact subtype.mk.inj (H ⟨x, hx⟩ ⟨y, hy⟩) }, { assume H x y, exact subtype.eq (H x.2 y.2) } end lemma finset.one_lt_card_iff {s : finset α} : 1 < s.card ↔ ∃ x y, (x ∈ s) ∧ (y ∈ s) ∧ x ≠ y := begin classical, rw ← not_iff_not, push_neg, simpa [classical.or_iff_not_imp_left] using finset.card_le_one_iff end instance plift.fintype (p : Prop) [decidable p] : fintype (plift p) := ⟨if h : p then finset.singleton ⟨h⟩ else ∅, λ ⟨h⟩, by simp [h]⟩ instance Prop.fintype : fintype Prop := ⟨⟨true::false::0, by simp [true_ne_false]⟩, classical.cases (by simp) (by simp)⟩ def set_fintype {α} [fintype α] (s : set α) [decidable_pred s] : fintype s := fintype.subtype (univ.filter (∈ s)) (by simp) namespace fintype variables [fintype α] [decidable_eq α] {δ : α → Type*} /-- Given for all `a : α` a finset `t a` of `δ a`, then one can define the finset `fintype.pi_finset t` of all functions taking values in `t a` for all `a`. This is the analogue of `finset.pi` where the base finset is `univ` (but formally they are not the same, as there is an additional condition `i ∈ finset.univ` in the `finset.pi` definition). -/ def pi_finset (t : Πa, finset (δ a)) : finset (Πa, δ a) := (finset.univ.pi t).map ⟨λ f a, f a (mem_univ a), λ _ _, by simp [function.funext_iff]⟩ @[simp] lemma mem_pi_finset {t : Πa, finset (δ a)} {f : Πa, δ a} : f ∈ pi_finset t ↔ (∀a, f a ∈ t a) := begin split, { simp only [pi_finset, mem_map, and_imp, forall_prop_of_true, exists_prop, mem_univ, exists_imp_distrib, mem_pi], assume g hg hgf a, rw ← hgf, exact hg a }, { simp only [pi_finset, mem_map, forall_prop_of_true, exists_prop, mem_univ, mem_pi], assume hf, exact ⟨λ a ha, f a, hf, rfl⟩ } end lemma pi_finset_subset (t₁ t₂ : Πa, finset (δ a)) (h : ∀ a, t₁ a ⊆ t₂ a) : pi_finset t₁ ⊆ pi_finset t₂ := λ g hg, mem_pi_finset.2 $ λ a, h a $ mem_pi_finset.1 hg a lemma pi_finset_disjoint_of_disjoint [∀ a, decidable_eq (δ a)] (t₁ t₂ : Πa, finset (δ a)) {a : α} (h : disjoint (t₁ a) (t₂ a)) : disjoint (pi_finset t₁) (pi_finset t₂) := disjoint_iff_ne.2 $ λ f₁ hf₁ f₂ hf₂ eq₁₂, disjoint_iff_ne.1 h (f₁ a) (mem_pi_finset.1 hf₁ a) (f₂ a) (mem_pi_finset.1 hf₂ a) (congr_fun eq₁₂ a) end fintype /-! ### pi -/ /-- A dependent product of fintypes, indexed by a fintype, is a fintype. -/ instance pi.fintype {α : Type*} {β : α → Type*} [decidable_eq α] [fintype α] [∀a, fintype (β a)] : fintype (Πa, β a) := ⟨fintype.pi_finset (λ _, univ), by simp⟩ @[simp] lemma fintype.pi_finset_univ {α : Type*} {β : α → Type*} [decidable_eq α] [fintype α] [∀a, fintype (β a)] : fintype.pi_finset (λ a : α, (finset.univ : finset (β a))) = (finset.univ : finset (Π a, β a)) := rfl instance d_array.fintype {n : ℕ} {α : fin n → Type*} [∀n, fintype (α n)] : fintype (d_array n α) := fintype.of_equiv _ (equiv.d_array_equiv_fin _).symm instance array.fintype {n : ℕ} {α : Type*} [fintype α] : fintype (array n α) := d_array.fintype instance vector.fintype {α : Type*} [fintype α] {n : ℕ} : fintype (vector α n) := fintype.of_equiv _ (equiv.vector_equiv_fin _ _).symm instance quotient.fintype [fintype α] (s : setoid α) [decidable_rel ((≈) : α → α → Prop)] : fintype (quotient s) := fintype.of_surjective quotient.mk (λ x, quotient.induction_on x (λ x, ⟨x, rfl⟩)) instance finset.fintype [fintype α] : fintype (finset α) := ⟨univ.powerset, λ x, finset.mem_powerset.2 (finset.subset_univ _)⟩ @[simp] lemma fintype.card_finset [fintype α] : fintype.card (finset α) = 2 ^ (fintype.card α) := finset.card_powerset finset.univ instance subtype.fintype (p : α → Prop) [decidable_pred p] [fintype α] : fintype {x // p x} := set_fintype _ theorem fintype.card_subtype_le [fintype α] (p : α → Prop) [decidable_pred p] : fintype.card {x // p x} ≤ fintype.card α := by rw fintype.subtype_card; exact card_le_of_subset (subset_univ _) theorem fintype.card_subtype_lt [fintype α] {p : α → Prop} [decidable_pred p] {x : α} (hx : ¬ p x) : fintype.card {x // p x} < fintype.card α := by rw [fintype.subtype_card]; exact finset.card_lt_card ⟨subset_univ _, classical.not_forall.2 ⟨x, by simp [*, set.mem_def]⟩⟩ instance psigma.fintype {α : Type*} {β : α → Type*} [fintype α] [∀ a, fintype (β a)] : fintype (Σ' a, β a) := fintype.of_equiv _ (equiv.psigma_equiv_sigma _).symm instance psigma.fintype_prop_left {α : Prop} {β : α → Type*} [decidable α] [∀ a, fintype (β a)] : fintype (Σ' a, β a) := if h : α then fintype.of_equiv (β h) ⟨λ x, ⟨h, x⟩, psigma.snd, λ _, rfl, λ ⟨_, _⟩, rfl⟩ else ⟨∅, λ x, h x.1⟩ instance psigma.fintype_prop_right {α : Type*} {β : α → Prop} [∀ a, decidable (β a)] [fintype α] : fintype (Σ' a, β a) := fintype.of_equiv {a // β a} ⟨λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, rfl, λ ⟨x, y⟩, rfl⟩ instance psigma.fintype_prop_prop {α : Prop} {β : α → Prop} [decidable α] [∀ a, decidable (β a)] : fintype (Σ' a, β a) := if h : ∃ a, β a then ⟨{⟨h.fst, h.snd⟩}, λ ⟨_, _⟩, by simp⟩ else ⟨∅, λ ⟨x, y⟩, h ⟨x, y⟩⟩ instance set.fintype [decidable_eq α] [fintype α] : fintype (set α) := pi.fintype instance pfun_fintype (p : Prop) [decidable p] (α : p → Type*) [Π hp, fintype (α hp)] : fintype (Π hp : p, α hp) := if hp : p then fintype.of_equiv (α hp) ⟨λ a _, a, λ f, f hp, λ _, rfl, λ _, rfl⟩ else ⟨singleton (λ h, (hp h).elim), by simp [hp, function.funext_iff]⟩ def quotient.fin_choice_aux {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : ∀ (l : list ι), (∀ i ∈ l, quotient (S i)) → @quotient (Π i ∈ l, α i) (by apply_instance) | [] f := ⟦λ i, false.elim⟧ | (i::l) f := begin refine quotient.lift_on₂ (f i (list.mem_cons_self _ _)) (quotient.fin_choice_aux l (λ j h, f j (list.mem_cons_of_mem _ h))) _ _, exact λ a l, ⟦λ j h, if e : j = i then by rw e; exact a else l _ (h.resolve_left e)⟧, refine λ a₁ l₁ a₂ l₂ h₁ h₂, quotient.sound (λ j h, _), by_cases e : j = i; simp [e], { subst j, exact h₁ }, { exact h₂ _ _ } end theorem quotient.fin_choice_aux_eq {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : ∀ (l : list ι) (f : ∀ i ∈ l, α i), quotient.fin_choice_aux l (λ i h, ⟦f i h⟧) = ⟦f⟧ | [] f := quotient.sound (λ i h, h.elim) | (i::l) f := begin simp [quotient.fin_choice_aux, quotient.fin_choice_aux_eq l], refine quotient.sound (λ j h, _), by_cases e : j = i; simp [e], subst j, refl end def quotient.fin_choice {ι : Type*} [fintype ι] [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] (f : ∀ i, quotient (S i)) : @quotient (Π i, α i) (by apply_instance) := quotient.lift_on (@quotient.rec_on _ _ (λ l : multiset ι, @quotient (Π i ∈ l, α i) (by apply_instance)) finset.univ.1 (λ l, quotient.fin_choice_aux l (λ i _, f i)) (λ a b h, begin have := λ a, quotient.fin_choice_aux_eq a (λ i h, quotient.out (f i)), simp [quotient.out_eq] at this, simp [this], let g := λ a:multiset ι, ⟦λ (i : ι) (h : i ∈ a), quotient.out (f i)⟧, refine eq_of_heq ((eq_rec_heq _ _).trans (_ : g a == g b)), congr' 1, exact quotient.sound h, end)) (λ f, ⟦λ i, f i (finset.mem_univ _)⟧) (λ a b h, quotient.sound $ λ i, h _ _) theorem quotient.fin_choice_eq {ι : Type*} [fintype ι] [decidable_eq ι] {α : ι → Type*} [∀ i, setoid (α i)] (f : ∀ i, α i) : quotient.fin_choice (λ i, ⟦f i⟧) = ⟦f⟧ := begin let q, swap, change quotient.lift_on q _ _ = _, have : q = ⟦λ i h, f i⟧, { dsimp [q], exact quotient.induction_on (@finset.univ ι _).1 (λ l, quotient.fin_choice_aux_eq _ _) }, simp [this], exact setoid.refl _ end section equiv open list equiv equiv.perm variables [decidable_eq α] [decidable_eq β] def perms_of_list : list α → list (perm α) | [] := [1] | (a :: l) := perms_of_list l ++ l.bind (λ b, (perms_of_list l).map (λ f, swap a b * f)) lemma length_perms_of_list : ∀ l : list α, length (perms_of_list l) = l.length.fact | [] := rfl | (a :: l) := begin rw [length_cons, nat.fact_succ], simp [perms_of_list, length_bind, length_perms_of_list, function.comp, nat.succ_mul], cc end lemma mem_perms_of_list_of_mem : ∀ {l : list α} {f : perm α} (h : ∀ x, f x ≠ x → x ∈ l), f ∈ perms_of_list l | [] f h := list.mem_singleton.2 $ equiv.ext _ _$ λ x, by simp [imp_false, *] at * | (a::l) f h := if hfa : f a = a then mem_append_left _ $ mem_perms_of_list_of_mem (λ x hx, mem_of_ne_of_mem (λ h, by rw h at hx; exact hx hfa) (h x hx)) else have hfa' : f (f a) ≠ f a, from mt (λ h, f.injective h) hfa, have ∀ (x : α), (swap a (f a) * f) x ≠ x → x ∈ l, from λ x hx, have hxa : x ≠ a, from λ h, by simpa [h, mul_apply] using hx, have hfxa : f x ≠ f a, from mt (λ h, f.injective h) hxa, list.mem_of_ne_of_mem hxa (h x (λ h, by simp [h, mul_apply, swap_apply_def] at hx; split_ifs at hx; cc)), suffices f ∈ perms_of_list l ∨ ∃ (b : α), b ∈ l ∧ ∃ g : perm α, g ∈ perms_of_list l ∧ swap a b * g = f, by simpa [perms_of_list], (@or_iff_not_imp_left _ _ (classical.prop_decidable _)).2 (λ hfl, ⟨f a, if hffa : f (f a) = a then mem_of_ne_of_mem hfa (h _ (mt (λ h, f.injective h) hfa)) else this _ $ by simp [mul_apply, swap_apply_def]; split_ifs; cc, ⟨swap a (f a) * f, mem_perms_of_list_of_mem this, by rw [← mul_assoc, mul_def (swap a (f a)) (swap a (f a)), swap_swap, ← equiv.perm.one_def, one_mul]⟩⟩) lemma mem_of_mem_perms_of_list : ∀ {l : list α} {f : perm α}, f ∈ perms_of_list l → ∀ {x}, f x ≠ x → x ∈ l | [] f h := have f = 1 := by simpa [perms_of_list] using h, by rw this; simp | (a::l) f h := (mem_append.1 h).elim (λ h x hx, mem_cons_of_mem _ (mem_of_mem_perms_of_list h hx)) (λ h x hx, let ⟨y, hy, hy'⟩ := list.mem_bind.1 h in let ⟨g, hg₁, hg₂⟩ := list.mem_map.1 hy' in if hxa : x = a then by simp [hxa] else if hxy : x = y then mem_cons_of_mem _ $ by rwa hxy else mem_cons_of_mem _ $ mem_of_mem_perms_of_list hg₁ $ by rw [eq_inv_mul_iff_mul_eq.2 hg₂, mul_apply, swap_inv, swap_apply_def]; split_ifs; cc) lemma mem_perms_of_list_iff {l : list α} {f : perm α} : f ∈ perms_of_list l ↔ ∀ {x}, f x ≠ x → x ∈ l := ⟨mem_of_mem_perms_of_list, mem_perms_of_list_of_mem⟩ lemma nodup_perms_of_list : ∀ {l : list α} (hl : l.nodup), (perms_of_list l).nodup | [] hl := by simp [perms_of_list] | (a::l) hl := have hl' : l.nodup, from nodup_of_nodup_cons hl, have hln' : (perms_of_list l).nodup, from nodup_perms_of_list hl', have hmeml : ∀ {f : perm α}, f ∈ perms_of_list l → f a = a, from λ f hf, not_not.1 (mt (mem_of_mem_perms_of_list hf) (nodup_cons.1 hl).1), by rw [perms_of_list, list.nodup_append, list.nodup_bind, pairwise_iff_nth_le]; exact ⟨hln', ⟨λ _ _, nodup_map (λ _ _, (mul_left_inj _).1) hln', λ i j hj hij x hx₁ hx₂, let ⟨f, hf⟩ := list.mem_map.1 hx₁ in let ⟨g, hg⟩ := list.mem_map.1 hx₂ in have hix : x a = nth_le l i (lt_trans hij hj), by rw [← hf.2, mul_apply, hmeml hf.1, swap_apply_left], have hiy : x a = nth_le l j hj, by rw [← hg.2, mul_apply, hmeml hg.1, swap_apply_left], absurd (hf.2.trans (hg.2.symm)) $ λ h, ne_of_lt hij $ nodup_iff_nth_le_inj.1 hl' i j (lt_trans hij hj) hj $ by rw [← hix, hiy]⟩, λ f hf₁ hf₂, let ⟨x, hx, hx'⟩ := list.mem_bind.1 hf₂ in let ⟨g, hg⟩ := list.mem_map.1 hx' in have hgxa : g⁻¹ x = a, from f.injective $ by rw [hmeml hf₁, ← hg.2]; simp, have hxa : x ≠ a, from λ h, (list.nodup_cons.1 hl).1 (h ▸ hx), (list.nodup_cons.1 hl).1 $ hgxa ▸ mem_of_mem_perms_of_list hg.1 (by rwa [apply_inv_self, hgxa])⟩ def perms_of_finset (s : finset α) : finset (perm α) := quotient.hrec_on s.1 (λ l hl, ⟨perms_of_list l, nodup_perms_of_list hl⟩) (λ a b hab, hfunext (congr_arg _ (quotient.sound hab)) (λ ha hb _, heq_of_eq $ finset.ext.2 $ by simp [mem_perms_of_list_iff,mem_of_perm hab])) s.2 lemma mem_perms_of_finset_iff : ∀ {s : finset α} {f : perm α}, f ∈ perms_of_finset s ↔ ∀ {x}, f x ≠ x → x ∈ s := by rintros ⟨⟨l⟩, hs⟩ f; exact mem_perms_of_list_iff lemma card_perms_of_finset : ∀ (s : finset α), (perms_of_finset s).card = s.card.fact := by rintros ⟨⟨l⟩, hs⟩; exact length_perms_of_list l def fintype_perm [fintype α] : fintype (perm α) := ⟨perms_of_finset (@finset.univ α _), by simp [mem_perms_of_finset_iff]⟩ instance [fintype α] [fintype β] : fintype (α ≃ β) := if h : fintype.card β = fintype.card α then trunc.rec_on_subsingleton (fintype.equiv_fin α) (λ eα, trunc.rec_on_subsingleton (fintype.equiv_fin β) (λ eβ, @fintype.of_equiv _ (perm α) fintype_perm (equiv_congr (equiv.refl α) (eα.trans (eq.rec_on h eβ.symm)) : (α ≃ α) ≃ (α ≃ β)))) else ⟨∅, λ x, false.elim (h (fintype.card_eq.2 ⟨x.symm⟩))⟩ lemma fintype.card_perm [fintype α] : fintype.card (perm α) = (fintype.card α).fact := subsingleton.elim (@fintype_perm α _ _) (@equiv.fintype α α _ _ _ _) ▸ card_perms_of_finset _ lemma fintype.card_equiv [fintype α] [fintype β] (e : α ≃ β) : fintype.card (α ≃ β) = (fintype.card α).fact := fintype.card_congr (equiv_congr (equiv.refl α) e) ▸ fintype.card_perm lemma univ_eq_singleton_of_card_one {α} [fintype α] (x : α) (h : fintype.card α = 1) : (univ : finset α) = finset.singleton x := begin apply symm, apply eq_of_subset_of_card_le (subset_univ (finset.singleton x)), apply le_of_eq, simp [h, finset.card_univ] end end equiv namespace fintype section choose open fintype open equiv variables [fintype α] [decidable_eq α] (p : α → Prop) [decidable_pred p] def choose_x (hp : ∃! a : α, p a) : {a // p a} := ⟨finset.choose p univ (by simp; exact hp), finset.choose_property _ _ _⟩ def choose (hp : ∃! a, p a) : α := choose_x p hp lemma choose_spec (hp : ∃! a, p a) : p (choose p hp) := (choose_x p hp).property end choose section bijection_inverse open function variables [fintype α] [decidable_eq α] variables [fintype β] [decidable_eq β] variables {f : α → β} /-- ` `bij_inv f` is the unique inverse to a bijection `f`. This acts as a computable alternative to `function.inv_fun`. -/ def bij_inv (f_bij : bijective f) (b : β) : α := fintype.choose (λ a, f a = b) begin rcases f_bij.right b with ⟨a', fa_eq_b⟩, rw ← fa_eq_b, exact ⟨a', ⟨rfl, (λ a h, f_bij.left h)⟩⟩ end lemma left_inverse_bij_inv (f_bij : bijective f) : left_inverse (bij_inv f_bij) f := λ a, f_bij.left (choose_spec (λ a', f a' = f a) _) lemma right_inverse_bij_inv (f_bij : bijective f) : right_inverse (bij_inv f_bij) f := λ b, choose_spec (λ a', f a' = b) _ lemma bijective_bij_inv (f_bij : bijective f) : bijective (bij_inv f_bij) := ⟨injective_of_left_inverse (right_inverse_bij_inv _), surjective_of_has_right_inverse ⟨f, left_inverse_bij_inv _⟩⟩ end bijection_inverse lemma well_founded_of_trans_of_irrefl [fintype α] (r : α → α → Prop) [is_trans α r] [is_irrefl α r] : well_founded r := by classical; exact have ∀ x y, r x y → (univ.filter (λ z, r z x)).card < (univ.filter (λ z, r z y)).card, from λ x y hxy, finset.card_lt_card $ by simp only [finset.lt_iff_ssubset.symm, lt_iff_le_not_le, finset.le_iff_subset, finset.subset_iff, mem_filter, true_and, mem_univ, hxy]; exact ⟨λ z hzx, trans hzx hxy, not_forall_of_exists_not ⟨x, not_imp.2 ⟨hxy, irrefl x⟩⟩⟩, subrelation.wf this (measure_wf _) lemma preorder.well_founded [fintype α] [preorder α] : well_founded ((<) : α → α → Prop) := well_founded_of_trans_of_irrefl _ @[instance, priority 10] lemma linear_order.is_well_order [fintype α] [linear_order α] : is_well_order α (<) := { wf := preorder.well_founded } end fintype class infinite (α : Type*) : Prop := (not_fintype : fintype α → false) @[simp] lemma not_nonempty_fintype {α : Type*} : ¬nonempty (fintype α) ↔ infinite α := ⟨λf, ⟨λ x, f ⟨x⟩⟩, λ⟨f⟩ ⟨x⟩, f x⟩ namespace infinite lemma exists_not_mem_finset [infinite α] (s : finset α) : ∃ x, x ∉ s := classical.not_forall.1 $ λ h, not_fintype ⟨s, h⟩ @[priority 100] -- see Note [lower instance priority] instance nonempty (α : Type*) [infinite α] : nonempty α := nonempty_of_exists (exists_not_mem_finset (∅ : finset α)) lemma of_injective [infinite β] (f : β → α) (hf : injective f) : infinite α := ⟨λ I, by exactI not_fintype (fintype.of_injective f hf)⟩ lemma of_surjective [infinite β] (f : α → β) (hf : surjective f) : infinite α := ⟨λ I, by classical; exactI not_fintype (fintype.of_surjective f hf)⟩ private noncomputable def nat_embedding_aux (α : Type*) [infinite α] : ℕ → α | n := by letI := classical.dec_eq α; exact classical.some (exists_not_mem_finset ((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux m) (λ _, multiset.mem_range.1)).to_finset) private lemma nat_embedding_aux_injective (α : Type*) [infinite α] : function.injective (nat_embedding_aux α) := begin assume m n h, letI := classical.dec_eq α, wlog hmlen : m ≤ n using m n, by_contradiction hmn, have hmn : m < n, from lt_of_le_of_ne hmlen hmn, refine (classical.some_spec (exists_not_mem_finset ((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux α m) (λ _, multiset.mem_range.1)).to_finset)) _, refine multiset.mem_to_finset.2 (multiset.mem_pmap.2 ⟨m, multiset.mem_range.2 hmn, _⟩), rw [h, nat_embedding_aux] end noncomputable def nat_embedding (α : Type*) [infinite α] : ℕ ↪ α := ⟨_, nat_embedding_aux_injective α⟩ end infinite lemma not_injective_infinite_fintype [infinite α] [fintype β] (f : α → β) : ¬ injective f := assume (hf : injective f), have H : fintype α := fintype.of_injective f hf, infinite.not_fintype H lemma not_surjective_fintype_infinite [fintype α] [infinite β] (f : α → β) : ¬ surjective f := assume (hf : surjective f), have H : infinite α := infinite.of_surjective f hf, @infinite.not_fintype _ H infer_instance instance nat.infinite : infinite ℕ := ⟨λ ⟨s, hs⟩, finset.not_mem_range_self $ s.subset_range_sup_succ (hs _)⟩ instance int.infinite : infinite ℤ := infinite.of_injective int.of_nat (λ _ _, int.of_nat_inj)
6e3cea968abbcaa0d3d07b755f85ba3c2174bab5
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/algebra/constructions.lean
1d4aa52d818f3f51c00b1845d5f59fcec0e998b1
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
4,882
lean
/- Copyright (c) 2021 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nicolò Cavalleri -/ import topology.homeomorph /-! # Topological space structure on the opposite monoid and on the units group > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we define `topological_space` structure on `Mᵐᵒᵖ`, `Mᵃᵒᵖ`, `Mˣ`, and `add_units M`. This file does not import definitions of a topological monoid and/or a continuous multiplicative action, so we postpone the proofs of `has_continuous_mul Mᵐᵒᵖ` etc till we have these definitions. ## Tags topological space, opposite monoid, units -/ variables {M X : Type*} open filter open_locale topology namespace mul_opposite /-- Put the same topological space structure on the opposite monoid as on the original space. -/ @[to_additive "Put the same topological space structure on the opposite monoid as on the original space."] instance [topological_space M] : topological_space Mᵐᵒᵖ := topological_space.induced (unop : Mᵐᵒᵖ → M) ‹_› variables [topological_space M] @[continuity, to_additive] lemma continuous_unop : continuous (unop : Mᵐᵒᵖ → M) := continuous_induced_dom @[continuity, to_additive] lemma continuous_op : continuous (op : M → Mᵐᵒᵖ) := continuous_induced_rng.2 continuous_id /-- `mul_opposite.op` as a homeomorphism. -/ @[to_additive "`add_opposite.op` as a homeomorphism.", simps] def op_homeomorph : M ≃ₜ Mᵐᵒᵖ := { to_equiv := op_equiv, continuous_to_fun := continuous_op, continuous_inv_fun := continuous_unop } @[to_additive] instance [t2_space M] : t2_space Mᵐᵒᵖ := op_homeomorph.symm.embedding.t2_space @[simp, to_additive] lemma map_op_nhds (x : M) : map (op : M → Mᵐᵒᵖ) (𝓝 x) = 𝓝 (op x) := op_homeomorph.map_nhds_eq x @[simp, to_additive] lemma map_unop_nhds (x : Mᵐᵒᵖ) : map (unop : Mᵐᵒᵖ → M) (𝓝 x) = 𝓝 (unop x) := op_homeomorph.symm.map_nhds_eq x @[simp, to_additive] lemma comap_op_nhds (x : Mᵐᵒᵖ) : comap (op : M → Mᵐᵒᵖ) (𝓝 x) = 𝓝 (unop x) := op_homeomorph.comap_nhds_eq x @[simp, to_additive] lemma comap_unop_nhds (x : M) : comap (unop : Mᵐᵒᵖ → M) (𝓝 x) = 𝓝 (op x) := op_homeomorph.symm.comap_nhds_eq x end mul_opposite namespace units open mul_opposite variables [topological_space M] [monoid M] [topological_space X] /-- The units of a monoid are equipped with a topology, via the embedding into `M × M`. -/ @[to_additive "The additive units of a monoid are equipped with a topology, via the embedding into `M × M`."] instance : topological_space Mˣ := prod.topological_space.induced (embed_product M) @[to_additive] lemma inducing_embed_product : inducing (embed_product M) := ⟨rfl⟩ @[to_additive] lemma embedding_embed_product : embedding (embed_product M) := ⟨inducing_embed_product, embed_product_injective M⟩ @[to_additive] lemma topology_eq_inf : units.topological_space = topological_space.induced (coe : Mˣ → M) ‹_› ⊓ topological_space.induced (λ u, ↑u⁻¹ : Mˣ → M) ‹_› := by simp only [inducing_embed_product.1, prod.topological_space, induced_inf, mul_opposite.topological_space, induced_compose]; refl /-- An auxiliary lemma that can be used to prove that coercion `Mˣ → M` is a topological embedding. Use `units.coe_embedding₀`, `units.coe_embedding`, or `to_units_homeomorph` instead. -/ @[to_additive "An auxiliary lemma that can be used to prove that coercion `add_units M → M` is a topological embedding. Use `add_units.coe_embedding` or `to_add_units_homeomorph` instead."] lemma embedding_coe_mk {M : Type*} [division_monoid M] [topological_space M] (h : continuous_on has_inv.inv {x : M | is_unit x}) : embedding (coe : Mˣ → M) := begin refine ⟨⟨_⟩, ext⟩, rw [topology_eq_inf, inf_eq_left, ← continuous_iff_le_induced, continuous_iff_continuous_at], intros u s hs, simp only [coe_inv, nhds_induced, filter.mem_map] at hs ⊢, exact ⟨_, mem_inf_principal.1 (h u u.is_unit hs), λ u' hu', hu' u'.is_unit⟩ end @[to_additive] lemma continuous_embed_product : continuous (embed_product M) := continuous_induced_dom @[to_additive] lemma continuous_coe : continuous (coe : Mˣ → M) := (@continuous_embed_product M _ _).fst @[to_additive] protected lemma continuous_iff {f : X → Mˣ} : continuous f ↔ continuous (coe ∘ f : X → M) ∧ continuous (λ x, ↑(f x)⁻¹ : X → M) := by simp only [inducing_embed_product.continuous_iff, embed_product_apply, (∘), continuous_prod_mk, op_homeomorph.symm.inducing.continuous_iff, op_homeomorph_symm_apply, unop_op] @[to_additive] lemma continuous_coe_inv : continuous (λ u, ↑u⁻¹ : Mˣ → M) := (units.continuous_iff.1 continuous_id).2 end units
fbdc2d3aad292d8a6eb452f2eca72dcaa295dec8
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/blast_cc10.lean
6fd059d097655e9fff82870c69cb3b68107e9c08
[ "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
100
lean
set_option blast.strategy "cc" definition t1 (a b : nat) : (a = b ↔ a = b) := by blast print t1
6d95e06c58932671be3ed4e72dd0eed429b1cb38
8cb37a089cdb4af3af9d8bf1002b417e407a8e9e
/tests/lean/run/my_tac_class.lean
189adb073201371ffde86ba0b14a048d86e4f9db
[ "Apache-2.0" ]
permissive
kbuzzard/lean
ae3c3db4bb462d750dbf7419b28bafb3ec983ef7
ed1788fd674bb8991acffc8fca585ec746711928
refs/heads/master
1,620,983,366,617
1,618,937,600,000
1,618,937,600,000
359,886,396
1
0
Apache-2.0
1,618,936,987,000
1,618,936,987,000
null
UTF-8
Lean
false
false
1,853
lean
meta def mytac := state_t nat tactic section local attribute [reducible] mytac meta instance : monad mytac := by apply_instance meta instance : monad_state nat mytac := by apply_instance meta instance : has_monad_lift tactic mytac := by apply_instance end meta instance (α : Type) : has_coe (tactic α) (mytac α) := ⟨monad_lift⟩ namespace mytac meta def step {α : Type} (t : mytac α) : mytac unit := t >> return () meta def istep {α : Type} (line0 col0 line col : nat) (t : mytac α) : mytac unit := ⟨λ v s, result.cases_on (@scope_trace _ line col (λ_, t.run v s)) (λ ⟨a, v⟩ new_s, result.success ((), v) new_s) (λ opt_msg_thunk e new_s, match opt_msg_thunk with | some msg_thunk := let msg := λ _ : unit, msg_thunk () ++ format.line ++ to_fmt "value: " ++ to_fmt v ++ format.line ++ to_fmt "state:" ++ format.line ++ new_s^.to_format in interaction_monad.result.exception (some msg) (some ⟨line, col⟩) new_s | none := interaction_monad.silent_fail new_s end)⟩ meta instance : interactive.executor mytac := { config_type := unit, execute_with := λ _ tac, tac.run 0 >> return () } meta def save_info (p : pos) : mytac unit := do v ← get, s ← tactic.read, tactic.save_info_thunk p (λ _, to_fmt "Custom state: " ++ to_fmt v ++ format.line ++ tactic_state.to_format s) namespace interactive meta def intros : mytac unit := tactic.intros >> return () meta def constructor : mytac unit := tactic.constructor >> return () meta def trace (s : string) : mytac unit := tactic.trace s meta def assumption : mytac unit := tactic.assumption meta def inc : mytac punit := modify (+1) end interactive end mytac example (p q : Prop) : p → q → p ∧ q := begin [mytac] intros, inc, trace "test", constructor, inc, assumption, assumption end
84347fd82a541663f1b70a2ca574eb96e7d206fe
01f6b345a06ece970e589d4bbc68ee8b9b2cf58a
/src/spectral_norm_unique.lean
7b04c198f77c4ee9beec1fe1fc5eb39fedaa1281
[]
no_license
mariainesdff/norm_extensions_journal_submission
6077acb98a7200de4553e653d81d54fb5d2314c8
d396130660935464fbc683f9aaf37fff8a890baa
refs/heads/master
1,686,685,693,347
1,684,065,115,000
1,684,065,115,000
603,823,641
0
0
null
null
null
null
UTF-8
Lean
false
false
12,842
lean
/- Copyright (c) 2023 María Inés de Frutos-Fernández. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: María Inés de Frutos-Fernández -/ import pow_mult_faithful import seminorm_from_const import spectral_norm /-! # Unique norm extension theorem Let `K` be a field complete with respect to a nontrivial nonarchimedean multiplicative norm and `L/K` be an algebraic extension. We show that the spectral norm on `L` is a nonarchimedean multiplicative norm, and any power-multiplicative `K`-algebra norm on `L` coincides with the spectral norm. More over, if `L/K` is finite, then `L` is a complete space. This result is [BGR, Theorem 3.2.4/2]. ## Main Definitions * `spectral_mul_alg_norm` : the spectral norm is a multiplicative `K`-algebra norm on `L`. ## Main Results * `spectral_norm_unique'` : any power-multiplicative `K`-algebra norm on `L` coincides with the spectral norm. * `spectral_norm_is_mul` : the spectral norm on `L` is multiplicative. * `spectral_norm_complete_space` : if `L/K` is finite dimensional, then `L` is a complete space with respect to topology induced by the spectral norm. ## References * [S. Bosch, U. Güntzer, R. Remmert, *Non-Archimedean Analysis*][bosch-guntzer-remmert] ## Tags spectral, spectral norm, unique, seminorm, norm, nonarchimedean -/ noncomputable theory open_locale nnreal variables {K : Type*} [nontrivially_normed_field K] {L : Type*} [field L] [algebra K L] (h_alg : algebra.is_algebraic K L) /--If `K` is a field complete with respect to a nontrivial nonarchimedean multiplicative norm and `L/K` is an algebraic extension, then any power-multiplicative `K`-algebra norm on `L` coincides with the spectral norm. -/ lemma spectral_norm_unique' [complete_space K] {f : algebra_norm K L} (hf_pm : is_pow_mul f) (hna : is_nonarchimedean (norm : K → ℝ)) : f = spectral_alg_norm h_alg hna := begin apply eq_of_pow_mult_faithful f hf_pm _ (spectral_alg_norm_is_pow_mul h_alg hna), intro x, set E : Type* := id K⟮x⟯ with hEdef, letI hE : field E := (by rw [hEdef, id.def] ; apply_instance), letI : algebra K E := K⟮x⟯.algebra, set id1 : K⟮x⟯ →ₗ[K] E := { to_fun := id, map_add' := λ x y, rfl, map_smul' := λ r x, rfl, }, set id2 : E →ₗ[K] K⟮x⟯ := { to_fun := id, map_add' := λ x y, rfl, map_smul' := λ r x, rfl }, set hs_norm : ring_norm E := { to_fun := (λ y : E, spectral_norm K L (id2 y : L)), map_zero' := by rw [map_zero, subfield.coe_zero, spectral_norm_zero], add_le' := λ a b, by simp only [← spectral_alg_norm_def h_alg hna, subfield.coe_add]; exact map_add_le_add _ _ _, neg' := λ a, by simp only [← spectral_alg_norm_def h_alg hna, subfield.coe_neg, map_neg, map_neg_eq_map], mul_le' := λ a b, by simp only [← spectral_alg_norm_def h_alg hna, subfield.coe_mul]; exact map_mul_le_mul _ _ _, eq_zero_of_map_eq_zero' := λ a ha, begin simp only [←spectral_alg_norm_def h_alg hna, linear_map.coe_mk, id.def, map_eq_zero_iff_eq_zero, algebra_map.lift_map_eq_zero_iff] at ha, exact ha end }, letI n1 : normed_ring E := norm_to_normed_ring hs_norm, letI N1 : normed_space K E := { norm_smul_le := λ k y, begin change (spectral_alg_norm h_alg hna (id2 (k • y) : L) : ℝ) ≤ ‖ k ‖ * spectral_alg_norm h_alg hna (id2 y : L), simp only [linear_map.coe_mk, id.def, intermediate_field.coe_smul, map_smul_eq_mul], end, ..K⟮x⟯.algebra }, set hf_norm : ring_norm K⟮x⟯ := { to_fun := λ y, f((algebra_map K⟮x⟯ L) y), map_zero' := map_zero _, add_le' := λ a b, map_add_le_add _ _ _, neg' := λ y, by { simp only [map_neg, map_neg_eq_map] }, mul_le' := λ a b, map_mul_le_mul _ _ _, eq_zero_of_map_eq_zero' := λ a ha, begin simp only [map_eq_zero_iff_eq_zero, map_eq_zero] at ha, exact ha end }, letI n2 : normed_ring K⟮x⟯ := norm_to_normed_ring hf_norm, letI N2 : normed_space K K⟮x⟯ := { norm_smul_le := λ k y, begin change (f ((algebra_map K⟮x⟯ L) (k • y)) : ℝ) ≤ ‖ k ‖ * f (algebra_map K⟮x⟯ L y), have : (algebra_map ↥K⟮x⟯ L) (k • y) = k • (algebra_map ↥K⟮x⟯ L y), { rw [← is_scalar_tower.algebra_map_smul K⟮x⟯ k y, smul_eq_mul, map_mul, ← is_scalar_tower.algebra_map_apply K ↥K⟮x⟯ L, algebra.smul_def] }, rw [ this, map_smul_eq_mul], end, ..K⟮x⟯.algebra }, haveI hKx_fin : finite_dimensional K ↥K⟮x⟯ := intermediate_field.adjoin.finite_dimensional (is_algebraic_iff_is_integral.mp (h_alg x)), haveI : finite_dimensional K E := hKx_fin, set Id1 : K⟮x⟯ →L[K] E := ⟨id1, id1.continuous_of_finite_dimensional⟩ with hId1, set Id2 : E →L[K] K⟮x⟯ := ⟨id2, id2.continuous_of_finite_dimensional⟩ with hId2, have hC1 : ∃ (C1 : ℝ), 0 < C1 ∧ ∀ (y : K⟮x⟯), ‖ id1 y ‖ ≤ C1 * ‖ y ‖ := Id1.is_bounded_linear_map.bound, have hC2 : ∃ (C2 : ℝ), 0 < C2 ∧ ∀ (y : E), ‖ id2 y ‖ ≤ C2 * ‖ y ‖ := Id2.is_bounded_linear_map.bound, obtain ⟨C1, hC1_pos, hC1⟩ := hC1, obtain ⟨C2, hC2_pos, hC2⟩ := hC2, use [C2, C1, hC2_pos, hC1_pos], rw forall_and_distrib, split, { intro y, exact hC2 ⟨y, (intermediate_field.algebra_adjoin_le_adjoin K _) y.2⟩ }, { intro y, exact hC1 ⟨y, (intermediate_field.algebra_adjoin_le_adjoin K _) y.2⟩ }, end /-- If `K` is a field complete with respect to a nontrivial nonarchimedean multiplicative norm and `L/K` is an algebraic extension, then any multiplicative ring norm on `L` extending the norm on `K` coincides with the spectral norm. -/ lemma spectral_norm_unique_field_norm_ext [complete_space K] (h_alg : algebra.is_algebraic K L) {f : mul_ring_norm L} (hf_ext : function_extends (norm : K → ℝ) f) (hna : is_nonarchimedean (norm : K → ℝ)) (x : L) : f x = spectral_norm K L x := begin set g : algebra_norm K L := { smul' := λ k x, by simp only [mul_ring_norm.to_fun_eq_coe, algebra.smul_def, map_mul, hf_ext k], mul_le' := λ x y, by simp only [mul_ring_norm.to_fun_eq_coe, map_mul_le_mul], ..f }, have hg_pow : is_pow_mul g := mul_ring_norm.is_pow_mul _, have hgx : f x = g x := rfl, rw [hgx, spectral_norm_unique' h_alg hg_pow hna], refl, end /-- `seminorm_from_const` can be regarded as an algebra norm, when one assumes that `(spectral_alg_norm h_alg hna).to_ring_seminorm 1 ≤ 1` and `0 ≠ spectral_alg_norm h_alg hna x` for some `x : L` -/ def alg_norm_from_const (hna : is_nonarchimedean (norm : K → ℝ)) (h1 : (spectral_alg_norm h_alg hna).to_ring_seminorm 1 ≤ 1) {x : L} (hx : 0 ≠ spectral_alg_norm h_alg hna x) : algebra_norm K L := { smul' := λ k y, begin have h_mul : ∀ (y : L), spectral_norm K L ((algebra_map K L k) * y) = spectral_norm K L (algebra_map K L k) * spectral_norm K L y, { intro y, rw [spectral_norm_extends, ← algebra.smul_def, ← spectral_alg_norm_def h_alg hna, map_smul_eq_mul _ _ _], refl, }, have h : spectral_norm K L (algebra_map K L k) = seminorm_from_const' h1 hx (spectral_norm_is_pow_mul h_alg hna) (algebra_map K L k), { rw seminorm_from_const_apply_of_is_mul h1 hx _ h_mul, refl, }, simp only [ring_norm.to_fun_eq_coe, seminorm_from_const_ring_norm_of_field_def], rw [← spectral_norm_extends k, algebra.smul_def, h], exact seminorm_from_const_is_mul_of_is_mul _ _ _ h_mul _, end, ..(seminorm_from_const_ring_norm_of_field h1 hx.symm (spectral_alg_norm_is_pow_mul h_alg hna)) } lemma alg_norm_from_const_def (hna : is_nonarchimedean (norm : K → ℝ)) (h1 : (spectral_alg_norm h_alg hna).to_ring_seminorm 1 ≤ 1) {x y : L} (hx : 0 ≠ spectral_alg_norm h_alg hna x) : alg_norm_from_const h_alg hna h1 hx y = seminorm_from_const h1 hx (spectral_norm_is_pow_mul h_alg hna) y := rfl /--If `K` is a field complete with respect to a nontrivial nonarchimedean multiplicative norm and `L/K` is an algebraic extension, then the spectral norm on `L` is multiplicative. -/ lemma spectral_norm_is_mul [complete_space K] (hna : is_nonarchimedean (norm : K → ℝ)) (x y : L) : spectral_alg_norm h_alg hna (x * y) = spectral_alg_norm h_alg hna x * spectral_alg_norm h_alg hna y := begin by_cases hx : spectral_alg_norm h_alg hna x = 0, { rw [hx, zero_mul], rw [map_eq_zero_iff_eq_zero] at hx ⊢, rw [hx, zero_mul], }, { have hf1 : (spectral_alg_norm h_alg hna).to_ring_seminorm 1 ≤ 1 := spectral_alg_norm_is_norm_le_one_class h_alg hna, set f : algebra_norm K L := alg_norm_from_const h_alg hna hf1 (ne.symm hx) with hf, have hf_pow : is_pow_mul f := seminorm_from_const_is_pow_mul hf1 (ne.symm hx) (spectral_norm_is_pow_mul h_alg hna), have hf_na : is_nonarchimedean f := seminorm_from_const_is_nonarchimedean _ _ _ (spectral_norm_is_nonarchimedean h_alg hna), rw [← spectral_norm_unique' h_alg hf_pow, hf], simp only [alg_norm_from_const_def], exact seminorm_from_const_c_is_mul _ _ _ _, } end /-- The spectral norm is a multiplicative `K`-algebra norm on `L`.-/ def spectral_mul_alg_norm [complete_space K] (hna : is_nonarchimedean (norm : K → ℝ)) : mul_algebra_norm K L := { map_one' := spectral_alg_norm_is_norm_one_class h_alg hna, map_mul' := spectral_norm_is_mul h_alg hna, ..spectral_alg_norm h_alg hna } lemma spectral_mul_ring_norm_def [complete_space K] (hna : is_nonarchimedean (norm : K → ℝ)) (x : L) : spectral_mul_alg_norm h_alg hna x = spectral_norm K L x := rfl /-- `L` with the spectral norm is a `normed_field`. -/ def spectral_norm_to_normed_field [complete_space K] (h_alg : algebra.is_algebraic K L) (h : is_nonarchimedean (norm : K → ℝ)) : normed_field L := { norm := λ (x : L), (spectral_norm K L x : ℝ), dist := λ (x y : L), (spectral_norm K L (x - y) : ℝ), dist_self := λ x, by { simp only [sub_self, spectral_norm_zero] }, dist_comm := λ x y, by { simp only [dist], rw [← neg_sub, spectral_norm_neg h_alg h] }, dist_triangle := λ x y z, begin simp only [dist_eq_norm], rw ← sub_add_sub_cancel x y z, exact add_le_of_is_nonarchimedean spectral_norm_nonneg (spectral_norm_is_nonarchimedean h_alg h) _ _, end, eq_of_dist_eq_zero := λ x y hxy, begin simp only [← spectral_mul_ring_norm_def h_alg h] at hxy, rw ← sub_eq_zero, exact mul_algebra_norm.eq_zero_of_map_eq_zero' _ _ hxy, end, dist_eq := λ x y, by refl, norm_mul' := λ x y, by simp only [← spectral_mul_ring_norm_def h_alg h]; exact map_mul _ _ _, ..(infer_instance : field L) } /-- `L` with the spectral norm is a `normed_add_comm_group`. -/ def spectral_norm_to_normed_add_comm_group [complete_space K] (h_alg : algebra.is_algebraic K L) (h : is_nonarchimedean (norm : K → ℝ)) : normed_add_comm_group L := begin haveI : normed_field L := spectral_norm_to_normed_field h_alg h, apply_instance, end /-- `L` with the spectral norm is a `seminormed_add_comm_group`. -/ def spectral_norm_to_seminormed_add_comm_group [complete_space K] (h_alg : algebra.is_algebraic K L) (h : is_nonarchimedean (norm : K → ℝ)) : seminormed_add_comm_group L := begin haveI : normed_field L := spectral_norm_to_normed_field h_alg h, apply_instance, end /-- `L` with the spectral norm is a `normed_space` over `K`. -/ def spectral_norm_to_normed_space [complete_space K] (h_alg : algebra.is_algebraic K L) (h : is_nonarchimedean (norm : K → ℝ)) : @normed_space K L _ (spectral_norm_to_seminormed_add_comm_group h_alg h) := { norm_smul_le := λ r x, begin change spectral_alg_norm h_alg h (r • x) ≤ ‖ r ‖*(spectral_alg_norm h_alg h x), exact le_of_eq (map_smul_eq_mul _ _ _), end, ..(infer_instance : module K L) } /-- The metric space structure on `L` induced by the spectral norm. -/ def ms [complete_space K] (h : is_nonarchimedean (norm : K → ℝ)) : metric_space L := (spectral_norm_to_normed_field h_alg h).to_metric_space /-- The uniform space structure on `L` induced by the spectral norm. -/ def us [complete_space K] (h : is_nonarchimedean (norm : K → ℝ)) : uniform_space L := (ms h_alg h).to_uniform_space -- normed_field.to_uniform_space /-- If `L/K` is finite dimensional, then `L` is a complete space with respect to topology induced by the spectral norm. -/ @[priority 100] instance spectral_norm_complete_space [complete_space K] (h : is_nonarchimedean (norm : K → ℝ)) [h_fin : finite_dimensional K L] : @complete_space L (us h_alg h) := @finite_dimensional.complete K _ L (spectral_norm_to_normed_add_comm_group h_alg h) (spectral_norm_to_normed_space h_alg h) _ h_fin
20731c7e3137587a357dee34069fbcf82a8fe4ff
4727251e0cd73359b15b664c3170e5d754078599
/src/logic/is_empty.lean
8c91c08fd2aab8327003214e1651e8c13c102353
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
4,902
lean
/- Copyright (c) 2021 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import logic.function.basic import tactic.protected /-! # Types that are empty In this file we define a typeclass `is_empty`, which expresses that a type has no elements. ## Main declaration * `is_empty`: a typeclass that expresses that a type is empty. -/ variables {α β γ : Sort*} /-- `is_empty α` expresses that `α` is empty. -/ @[protect_proj] class is_empty (α : Sort*) : Prop := (false : α → false) instance : is_empty empty := ⟨empty.elim⟩ instance : is_empty pempty := ⟨pempty.elim⟩ instance : is_empty false := ⟨id⟩ instance : is_empty (fin 0) := ⟨λ n, nat.not_lt_zero n.1 n.2⟩ protected lemma function.is_empty [is_empty β] (f : α → β) : is_empty α := ⟨λ x, is_empty.false (f x)⟩ instance {p : α → Sort*} [h : nonempty α] [∀ x, is_empty (p x)] : is_empty (Π x, p x) := h.elim $ λ x, function.is_empty $ function.eval x instance pprod.is_empty_left [is_empty α] : is_empty (pprod α β) := function.is_empty pprod.fst instance pprod.is_empty_right [is_empty β] : is_empty (pprod α β) := function.is_empty pprod.snd instance prod.is_empty_left {α β} [is_empty α] : is_empty (α × β) := function.is_empty prod.fst instance prod.is_empty_right {α β} [is_empty β] : is_empty (α × β) := function.is_empty prod.snd instance [is_empty α] [is_empty β] : is_empty (psum α β) := ⟨λ x, psum.rec is_empty.false is_empty.false x⟩ instance {α β} [is_empty α] [is_empty β] : is_empty (α ⊕ β) := ⟨λ x, sum.rec is_empty.false is_empty.false x⟩ /-- subtypes of an empty type are empty -/ instance [is_empty α] (p : α → Prop) : is_empty (subtype p) := ⟨λ x, is_empty.false x.1⟩ /-- subtypes by an all-false predicate are false. -/ lemma subtype.is_empty_of_false {p : α → Prop} (hp : ∀ a, ¬(p a)) : is_empty (subtype p) := ⟨λ x, hp _ x.2⟩ /-- subtypes by false are false. -/ instance subtype.is_empty_false : is_empty {a : α // false} := subtype.is_empty_of_false (λ a, id) /- Test that `pi.is_empty` finds this instance. -/ example [h : nonempty α] [is_empty β] : is_empty (α → β) := by apply_instance /-- Eliminate out of a type that `is_empty` (without using projection notation). -/ @[elab_as_eliminator] def is_empty_elim [is_empty α] {p : α → Sort*} (a : α) : p a := (is_empty.false a).elim lemma is_empty_iff : is_empty α ↔ α → false := ⟨@is_empty.false α, is_empty.mk⟩ namespace is_empty open function /-- Eliminate out of a type that `is_empty` (using projection notation). -/ protected def elim (h : is_empty α) {p : α → Sort*} (a : α) : p a := is_empty_elim a /-- Non-dependent version of `is_empty.elim`. Helpful if the elaborator cannot elaborate `h.elim a` correctly. -/ protected def elim' {β : Sort*} (h : is_empty α) (a : α) : β := h.elim a protected lemma prop_iff {p : Prop} : is_empty p ↔ ¬ p := is_empty_iff variables [is_empty α] lemma forall_iff {p : α → Prop} : (∀ a, p a) ↔ true := iff_true_intro is_empty_elim lemma exists_iff {p : α → Prop} : (∃ a, p a) ↔ false := iff_false_intro $ λ ⟨x, hx⟩, is_empty.false x @[priority 100] -- see Note [lower instance priority] instance : subsingleton α := ⟨is_empty_elim⟩ end is_empty @[simp] lemma not_nonempty_iff : ¬ nonempty α ↔ is_empty α := ⟨λ h, ⟨λ x, h ⟨x⟩⟩, λ h1 h2, h2.elim h1.elim⟩ @[simp] lemma not_is_empty_iff : ¬ is_empty α ↔ nonempty α := not_iff_comm.mp not_nonempty_iff @[simp] lemma is_empty_pi {π : α → Sort*} : is_empty (Π a, π a) ↔ ∃ a, is_empty (π a) := by simp only [← not_nonempty_iff, classical.nonempty_pi, not_forall] @[simp] lemma is_empty_prod {α β : Type*} : is_empty (α × β) ↔ is_empty α ∨ is_empty β := by simp only [← not_nonempty_iff, nonempty_prod, not_and_distrib] @[simp] lemma is_empty_pprod : is_empty (pprod α β) ↔ is_empty α ∨ is_empty β := by simp only [← not_nonempty_iff, nonempty_pprod, not_and_distrib] @[simp] lemma is_empty_sum {α β} : is_empty (α ⊕ β) ↔ is_empty α ∧ is_empty β := by simp only [← not_nonempty_iff, nonempty_sum, not_or_distrib] @[simp] lemma is_empty_psum {α β} : is_empty (psum α β) ↔ is_empty α ∧ is_empty β := by simp only [← not_nonempty_iff, nonempty_psum, not_or_distrib] variables (α) lemma is_empty_or_nonempty : is_empty α ∨ nonempty α := (em $ is_empty α).elim or.inl $ or.inr ∘ not_is_empty_iff.mp @[simp] lemma not_is_empty_of_nonempty [h : nonempty α] : ¬ is_empty α := not_is_empty_iff.mpr h variable {α} lemma function.extend_of_empty [is_empty α] (f : α → β) (g : α → γ) (h : β → γ) : function.extend f g h = h := funext $ λ x, function.extend_apply' _ _ _ $ λ ⟨a, h⟩, is_empty_elim a
1b74a5a53c55c36b831b8eed10041effa6a993ff
a2ee6a66690e8da666951cac0c243d42db11f9f3
/src/algebra/group/with_one.lean
f1b3b0e087172294486c0fc9c9f9df54bec0ced9
[ "Apache-2.0" ]
permissive
shyamalschandra/mathlib
6d414d7c334bf383e764336843f065bd14c44273
ca679acad147870b2c5087d90fe3550f107dea49
refs/heads/master
1,671,730,354,335
1,601,883,576,000
1,601,883,576,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,858
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johan Commelin -/ import algebra.ring.basic universes u v variable {α : Type u} /-- Add an extra element `1` to a type -/ @[to_additive "Add an extra element `0` to a type"] def with_one (α) := option α namespace with_one @[to_additive] instance : monad with_one := option.monad @[to_additive] instance : has_one (with_one α) := ⟨none⟩ @[to_additive] instance : inhabited (with_one α) := ⟨1⟩ @[to_additive] instance [nonempty α] : nontrivial (with_one α) := option.nontrivial @[to_additive] instance : has_coe_t α (with_one α) := ⟨some⟩ @[to_additive] lemma some_eq_coe {a : α} : (some a : with_one α) = ↑a := rfl @[simp, to_additive] lemma coe_ne_one {a : α} : (a : with_one α) ≠ (1 : with_one α) := option.some_ne_none a @[simp, to_additive] lemma one_ne_coe {a : α} : (1 : with_one α) ≠ a := coe_ne_one.symm @[to_additive] lemma ne_one_iff_exists {x : with_one α} : x ≠ 1 ↔ ∃ (a : α), ↑a = x := option.ne_none_iff_exists @[to_additive] lemma coe_inj {a b : α} : (a : with_one α) = b ↔ a = b := option.some_inj @[elab_as_eliminator, to_additive] protected lemma cases_on {P : with_one α → Prop} : ∀ (x : with_one α), P 1 → (∀ a : α, P a) → P x := option.cases_on @[to_additive] instance [has_mul α] : has_mul (with_one α) := { mul := option.lift_or_get (*) } @[to_additive] instance [semigroup α] : monoid (with_one α) := { mul_assoc := (option.lift_or_get_assoc _).1, one_mul := (option.lift_or_get_is_left_id _).1, mul_one := (option.lift_or_get_is_right_id _).1, ..with_one.has_one, ..with_one.has_mul } @[to_additive] instance [comm_semigroup α] : comm_monoid (with_one α) := { mul_comm := (option.lift_or_get_comm _).1, ..with_one.monoid } section lift variables [semigroup α] {β : Type v} [monoid β] /-- Lift a semigroup homomorphism `f` to a bundled monoid homorphism. We have no bundled semigroup homomorphisms, so this function takes `∀ x y, f (x * y) = f x * f y` as an explicit argument. -/ @[to_additive "Lift an add_semigroup homomorphism `f` to a bundled add_monoid homorphism. We have no bundled add_semigroup homomorphisms, so this function takes `∀ x y, f (x + y) = f x + f y` as an explicit argument."] def lift (f : α → β) (hf : ∀ x y, f (x * y) = f x * f y) : (with_one α) →* β := { to_fun := λ x, option.cases_on x 1 f, map_one' := rfl, map_mul' := λ x y, with_one.cases_on x (by { rw one_mul, exact (one_mul _).symm }) $ λ x, with_one.cases_on y (by { rw mul_one, exact (mul_one _).symm }) $ λ y, hf x y } variables (f : α → β) (hf : ∀ x y, f (x * y) = f x * f y) @[simp, to_additive] lemma lift_coe (x : α) : lift f hf x = f x := rfl @[simp, to_additive] lemma lift_one : lift f hf 1 = 1 := rfl @[to_additive] theorem lift_unique (f : with_one α →* β) : f = lift (f ∘ coe) (λ x y, f.map_mul x y) := monoid_hom.ext $ λ x, with_one.cases_on x f.map_one $ λ x, rfl end lift section map variables {β : Type v} [semigroup α] [semigroup β] /-- Given a multiplicative map from `α → β` returns a monoid homomorphism from `with_one α` to `with_one β` -/ @[to_additive "Given an additive map from `α → β` returns an add_monoid homomorphism from `with_zero α` to `with_zero β`"] def map (f : α → β) (hf : ∀ x y, f (x * y) = f x * f y) : with_one α →* with_one β := lift (coe ∘ f) (λ x y, coe_inj.2 $ hf x y) end map attribute [irreducible] with_one @[simp, norm_cast, to_additive] lemma coe_mul [has_mul α] (a b : α) : ((a * b : α) : with_one α) = a * b := rfl end with_one namespace with_zero instance [one : has_one α] : has_one (with_zero α) := { ..one } lemma coe_one [has_one α] : ((1 : α) : with_zero α) = 1 := rfl instance [has_mul α] : mul_zero_class (with_zero α) := { mul := λ o₁ o₂, o₁.bind (λ a, option.map (λ b, a * b) o₂), zero_mul := λ a, rfl, mul_zero := λ a, by cases a; refl, ..with_zero.has_zero } @[simp, norm_cast] lemma coe_mul {α : Type u} [has_mul α] {a b : α} : ((a * b : α) : with_zero α) = a * b := rfl @[simp] lemma zero_mul {α : Type u} [has_mul α] (a : with_zero α) : 0 * a = 0 := rfl @[simp] lemma mul_zero {α : Type u} [has_mul α] (a : with_zero α) : a * 0 = 0 := by cases a; refl instance [semigroup α] : semigroup (with_zero α) := { mul_assoc := λ a b c, match a, b, c with | none, _, _ := rfl | some a, none, _ := rfl | some a, some b, none := rfl | some a, some b, some c := congr_arg some (mul_assoc _ _ _) end, ..with_zero.mul_zero_class } instance [comm_semigroup α] : comm_semigroup (with_zero α) := { mul_comm := λ a b, match a, b with | none, _ := (mul_zero _).symm | some a, none := rfl | some a, some b := congr_arg some (mul_comm _ _) end, ..with_zero.semigroup } instance [monoid α] : monoid_with_zero (with_zero α) := { one_mul := λ a, match a with | none := rfl | some a := congr_arg some $ one_mul _ end, mul_one := λ a, match a with | none := rfl | some a := congr_arg some $ mul_one _ end, ..with_zero.mul_zero_class, ..with_zero.has_one, ..with_zero.semigroup } instance [comm_monoid α] : comm_monoid_with_zero (with_zero α) := { ..with_zero.monoid_with_zero, ..with_zero.comm_semigroup } /-- Given an inverse operation on `α` there is an inverse operation on `with_zero α` sending `0` to `0`-/ definition inv [has_inv α] (x : with_zero α) : with_zero α := do a ← x, return a⁻¹ instance [has_inv α] : has_inv (with_zero α) := ⟨with_zero.inv⟩ @[simp, norm_cast] lemma coe_inv [has_inv α] (a : α) : ((a⁻¹ : α) : with_zero α) = a⁻¹ := rfl @[simp] lemma inv_zero [has_inv α] : (0 : with_zero α)⁻¹ = 0 := rfl section group variables [group α] @[simp] lemma inv_one : (1 : with_zero α)⁻¹ = 1 := show ((1⁻¹ : α) : with_zero α) = 1, by simp [coe_one] /-- A division operation on `with_zero α` when `α` has an inverse operation -/ definition div (x y : with_zero α) : with_zero α := x * y⁻¹ instance : has_div (with_zero α) := ⟨with_zero.div⟩ @[simp] lemma zero_div (a : with_zero α) : 0 / a = 0 := rfl @[simp] lemma div_zero (a : with_zero α) : a / 0 = 0 := by change a * _ = _; simp lemma div_coe (a b : α) : (a : with_zero α) / b = (a * b⁻¹ : α) := rfl lemma one_div (x : with_zero α) : 1 / x = x⁻¹ := one_mul _ @[simp] lemma div_one : ∀ (x : with_zero α), x / 1 = x | 0 := rfl | (a : α) := show _ * _ = _, by simp @[simp] lemma mul_right_inv : ∀ (x : with_zero α) (h : x ≠ 0), x * x⁻¹ = 1 | 0 h := false.elim $ h rfl | (a : α) h := by {norm_cast, simp [coe_one]} @[simp] lemma mul_left_inv : ∀ (x : with_zero α) (h : x ≠ 0), x⁻¹ * x = 1 | 0 h := false.elim $ h rfl | (a : α) h := by {norm_cast, simp [coe_one]} @[simp] lemma mul_inv_rev : ∀ (x y : with_zero α), (x * y)⁻¹ = y⁻¹ * x⁻¹ | 0 0 := rfl | 0 (b : α) := rfl | (a : α) 0 := rfl | (a : α) (b : α) := by {norm_cast, exact _root_.mul_inv_rev _ _} @[simp] lemma mul_div_cancel {a b : with_zero α} (hb : b ≠ 0) : a * b / b = a := show _ * _ * _ = _, by simp [mul_assoc, hb] @[simp] lemma div_mul_cancel {a b : with_zero α} (hb : b ≠ 0) : a / b * b = a := show _ * _ * _ = _, by simp [mul_assoc, hb] lemma div_eq_iff_mul_eq {a b c : with_zero α} (hb : b ≠ 0) : a / b = c ↔ c * b = a := by split; intro h; simp [h.symm, hb] lemma mul_inv_cancel : ∀ (a : with_zero α), a ≠ 0 → a * a⁻¹ = 1 := begin rintro (_ | a) h, {exact absurd rfl h }, { refine option.some_inj.2 (_root_.mul_right_inv _) } end /-- if `G` is a group then `with_zero G` is a group with zero. -/ instance : group_with_zero (with_zero α) := { inv_zero := with_zero.inv_zero, mul_inv_cancel := with_zero.mul_inv_cancel, ..with_zero.monoid_with_zero, ..with_zero.has_inv, ..with_zero.nontrivial } end group section comm_group variables [comm_group α] {a b c d : with_zero α} lemma div_eq_div (hb : b ≠ 0) (hd : d ≠ 0) : a / b = c / d ↔ a * d = b * c := begin rw ne_zero_iff_exists at hb hd, rcases hb with ⟨b, rfl⟩, rcases hd with ⟨d, rfl⟩, induction a using with_zero.cases_on; induction c using with_zero.cases_on, { refl }, { simp [div_coe] }, { simp [div_coe] }, erw [with_zero.coe_inj, with_zero.coe_inj], show a * b⁻¹ = c * d⁻¹ ↔ a * d = b * c, split; intro H, { rw mul_inv_eq_iff_eq_mul at H, rw [H, mul_right_comm, inv_mul_cancel_right, mul_comm] }, { rw [mul_inv_eq_iff_eq_mul, mul_right_comm, mul_comm c, ← H, mul_inv_cancel_right] } end theorem mul_comm {α : Type u} [comm_group α] : ∀ (a b : with_zero α), a * b = b * a := begin rintro (_ | a) (_ | b), { refl }, { refl }, { refl }, { apply option.some_inj.2, apply mul_comm } end /-- if `G` is a `comm_group` then `with_zero G` is a `comm_group_with_zero`. -/ instance : comm_group_with_zero (with_zero α) := { mul_comm := mul_comm, ..with_zero.group_with_zero } end comm_group section semiring instance [semiring α] : semiring (with_zero α) := { left_distrib := λ a b c, begin cases a with a, {refl}, cases b with b; cases c with c; try {refl}, exact congr_arg some (left_distrib _ _ _) end, right_distrib := λ a b c, begin cases c with c, { change (a + b) * 0 = a * 0 + b * 0, simp }, cases a with a; cases b with b; try {refl}, exact congr_arg some (right_distrib _ _ _) end, ..with_zero.add_comm_monoid, ..with_zero.mul_zero_class, ..with_zero.monoid_with_zero } end semiring attribute [irreducible] with_zero end with_zero
e1504f7b9a29e94e02846d8a75d98a4e61381f35
cc060cf567f81c404a13ee79bf21f2e720fa6db0
/lean/20170705-unfold_projs.lean
dbada5fde3eca603b308f085be1b74b1a8cca2c6
[ "Apache-2.0" ]
permissive
semorrison/proof
cf0a8c6957153bdb206fd5d5a762a75958a82bca
5ee398aa239a379a431190edbb6022b1a0aa2c70
refs/heads/master
1,610,414,502,842
1,518,696,851,000
1,518,696,851,000
78,375,937
2
1
null
null
null
null
UTF-8
Lean
false
false
2,179
lean
structure {u v} Category := ( Obj : Type u ) ( Hom : Obj → Obj → Type v ) ( identity : Π X : Obj, Hom X X ) ( compose : Π { X Y Z : Obj }, Hom X Y → Hom Y Z → Hom X Z ) ( left_identity : ∀ { X Y : Obj } (f : Hom X Y), compose (identity X) f = f ) ( right_identity : ∀ { X Y : Obj } (f : Hom X Y), compose f (identity Y) = f ) ( associativity : ∀ { W X Y Z : Obj } (f : Hom W X) (g : Hom X Y) (h : Hom Y Z), compose (compose f g) h = compose f (compose g h) ) structure {u1 v1 u2 v2} Functor (C : Category.{ u1 v1 }) (D : Category.{ u2 v2 }) := (onObjects : C.Obj → D.Obj) (onMorphisms : Π { X Y : C.Obj }, C.Hom X Y → D.Hom (onObjects X) (onObjects Y)) (identities : ∀ (X : C.Obj), onMorphisms (C.identity X) = D.identity (onObjects X)) (functoriality : ∀ { X Y Z : C.Obj } (f : C.Hom X Y) (g : C.Hom Y Z), onMorphisms (C.compose f g) = D.compose (onMorphisms f) (onMorphisms g)) definition {u1 v1 u2 v2 u3 v3} FunctorComposition { C : Category.{u1 v1} } { D : Category.{u2 v2} } { E : Category.{u3 v3} } ( F : Functor C D ) ( G : Functor D E ) : Functor C E := { onObjects := λ X, G.onObjects (F.onObjects X), onMorphisms := λ _ _ f, G.onMorphisms (F.onMorphisms f), identities := sorry, functoriality := sorry } structure {u1 v1 u2 v2} NaturalTransformation { C : Category.{u1 v1} } { D : Category.{u2 v2} } ( F G : Functor C D ) := (components: Π X : C.Obj, D.Hom (F.onObjects X) (G.onObjects X)) (naturality: ∀ { X Y : C.Obj } (f : C.Hom X Y), D.compose (F.onMorphisms f) (components Y) = D.compose (components X) (G.onMorphisms f)) definition {u1 v1 u2 v2 u3 v3} horizontal_composition_of_NaturalTransformations { C : Category.{u1 v1} } { D : Category.{u2 v2} } { E : Category.{u3 v3} } { F G : Functor C D } { H I : Functor D E } ( α : NaturalTransformation F G ) ( β : NaturalTransformation H I ) : NaturalTransformation (FunctorComposition F H) (FunctorComposition G I) := { components := λ X : C.Obj, E.compose (β.components (F.onObjects X)) (I.onMorphisms (α.components X)), naturality := begin intros, unfold_projs, end }
340aea075b0e870f514f536ca8aa08a3770935c9
88fb7558b0636ec6b181f2a548ac11ad3919f8a5
/library/init/native/ir.lean
350dfbf3cdc660a875131932705973afd11a92a8
[ "Apache-2.0" ]
permissive
moritayasuaki/lean
9f666c323cb6fa1f31ac597d777914aed41e3b7a
ae96ebf6ee953088c235ff7ae0e8c95066ba8001
refs/heads/master
1,611,135,440,814
1,493,852,869,000
1,493,852,869,000
90,269,903
0
0
null
1,493,906,291,000
1,493,906,291,000
null
UTF-8
Lean
false
false
2,738
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 init.meta.inductive_compiler 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 -- |
7d566a1186adb103ebc66a974685c6b50f383e09
e151e9053bfd6d71740066474fc500a087837323
/src/hott/algebra/binary.lean
abd22cc37f4a69f142e0467307f5bf1290aa7f4d
[ "Apache-2.0" ]
permissive
daniel-carranza/hott3
15bac2d90589dbb952ef15e74b2837722491963d
913811e8a1371d3a5751d7d32ff9dec8aa6815d9
refs/heads/master
1,610,091,349,670
1,596,222,336,000
1,596,222,336,000
241,957,822
0
0
Apache-2.0
1,582,222,839,000
1,582,222,838,000
null
UTF-8
Lean
false
false
4,692
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad General properties of binary operations. -/ import ..init universes u v w hott_theory namespace hott open function namespace binary section variable {A : Type _} variables (op₁ : A → A → A) (inv : A → A) (one : A) local notation a * b := op₁ a b local notation a ⁻¹ := inv a @[hott] def commutative := Πa b, a * b = b * a @[hott] def associative := Πa b c, (a * b) * c = a * (b * c) @[hott] def left_identity := Πa, one * a = a @[hott] def right_identity := Πa, a * one = a @[hott] def left_inverse := Πa, a⁻¹ * a = one @[hott] def right_inverse := Πa, a * a⁻¹ = one @[hott] def left_cancelative := Πa b c, a * b = a * c → b = c @[hott] def right_cancelative := Πa b c, a * b = c * b → a = c @[hott] def inv_op_cancel_left := Πa b, a⁻¹ * (a * b) = b @[hott] def op_inv_cancel_left := Πa b, a * (a⁻¹ * b) = b @[hott] def inv_op_cancel_right := Πa b, a * b⁻¹ * b = a @[hott] def op_inv_cancel_right := Πa b, a * b * b⁻¹ = a variable (op₂ : A → A → A) local notation a + b := op₂ a b @[hott] def left_distributive := Πa b c, a * (b + c) = a * b + a * c @[hott] def right_distributive := Πa b c, (a + b) * c = a * c + b * c @[hott] def right_commutative {B : Type _} (f : B → A → B) := Π b a₁ a₂, f (f b a₁) a₂ = f (f b a₂) a₁ @[hott] def left_commutative {B : Type _} (f : A → B → B) := Π a₁ a₂ b, f a₁ (f a₂ b) = f a₂ (f a₁ b) end section variable {A : Type _} variable {f : A → A → A} variable H_comm : commutative f variable H_assoc : associative f local infixl `*` := f @[hott] theorem left_comm : left_commutative f := λ a b c, calc a*(b*c) = (a*b)*c : (H_assoc _ _ _)⁻¹ ... = (b*a)*c : ap (λ x, x*c) (H_comm _ _) ... = b*(a*c) : H_assoc _ _ _ @[hott] theorem right_comm : right_commutative f := λ a b c, calc (a*b)*c = a*(b*c) : H_assoc _ _ _ ... = a*(c*b) : ap (λ x, a*x) (H_comm _ _) ... = (a*c)*b : (H_assoc _ _ _)⁻¹ @[hott] theorem comm4 (a b c d : A) : a*b*(c*d) = a*c*(b*d) := calc a*b*(c*d) = a*b*c*d : (H_assoc _ _ _)⁻¹ ... = a*c*b*d : ap (λx, x*d) (right_comm H_comm H_assoc _ _ _) ... = a*c*(b*d) : H_assoc _ _ _ end section variable {A : Type _} variable {f : A → A → A} variable H_assoc : associative f local infixl `*` := f @[hott] theorem assoc4helper (a b c d) : (a*b)*(c*d) = a*((b*c)*d) := calc (a*b)*(c*d) = a*(b*(c*d)) : H_assoc _ _ _ ... = a*((b*c)*d) : ap (λ x, a*x) (H_assoc _ _ _)⁻¹ᵖ end @[hott] def right_commutative_compose_right {A B : Type _} (f : A → A → A) (g : B → A) (rcomm : right_commutative f) : right_commutative (compose_right f g) := λ a b₁ b₂, (rcomm _ _ _) @[hott] def left_commutative_compose_left {A B : Type _} (f : A → A → A) (g : B → A) (lcomm : left_commutative f) : left_commutative (compose_left f g) := λ a b₁ b₂, (lcomm _ _ _) end binary open eq namespace is_equiv @[hott] def inv_preserve_binary {A B : Type _} (f : A → B) [H : is_equiv f] (mA : A → A → A) (mB : B → B → B) (H : Π(a a' : A), f (mA a a') = mB (f a) (f a')) (b b' : B) : f⁻¹ᶠ (mB b b') = mA (f⁻¹ᶠ b) (f⁻¹ᶠ b') := begin have H2 : f⁻¹ᶠ (mB (f (f⁻¹ᶠ b)) (f (f⁻¹ᶠ b'))) = f⁻¹ᶠ (f (mA (f⁻¹ᶠ b) (f⁻¹ᶠ b'))), from ap f⁻¹ᶠ (H _ _)⁻¹ᵖ, rwr [right_inv f, right_inv f, left_inv f] at H2, rwr H2 end @[hott] def preserve_binary_of_inv_preserve {A B : Type _} (f : A → B) [H : is_equiv f] (mA : A → A → A) (mB : B → B → B) (H : Π(b b' : B), f⁻¹ᶠ (mB b b') = mA (f⁻¹ᶠ b) (f⁻¹ᶠ b')) (a a' : A) : f (mA a a') = mB (f a) (f a') := begin have H2 : f (mA (f⁻¹ᶠ (f a)) (f⁻¹ᶠ (f a'))) = f (f⁻¹ᶠ (mB (f a) (f a'))), from ap f (H _ _)⁻¹ᵖ, rwr [right_inv f, left_inv f, left_inv f] at H2, rwr H2 end end is_equiv namespace equiv open hott.is_equiv @[hott] def inv_preserve_binary {A B : Type _} (f : A ≃ B) (mA : A → A → A) (mB : B → B → B) (H : Π(a a' : A), f (mA a a') = mB (f a) (f a')) (b b' : B) : f⁻¹ᶠ (mB b b') = mA (f⁻¹ᶠ b) (f⁻¹ᶠ b') := inv_preserve_binary f mA mB H b b' @[hott] def preserve_binary_of_inv_preserve {A B : Type _} (f : A ≃ B) (mA : A → A → A) (mB : B → B → B) (H : Π(b b' : B), f⁻¹ᶠ (mB b b') = mA (f⁻¹ᶠ b) (f⁻¹ᶠ b')) (a a' : A) : f (mA a a') = mB (f a) (f a') := preserve_binary_of_inv_preserve f mA mB H a a' end equiv end hott
34e5a3ab221fd0f64229ad111959007fc576be2c
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/group_theory/perm/via_embedding.lean
d1b4dbc15c0e628cb778dce11ce38cb50a5c63a3
[ "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,456
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, Mario Carneiro -/ import group_theory.perm.basic import logic.equiv.set /-! # `equiv.perm.via_embedding`, a noncomputable analogue of `equiv.perm.via_fintype_embedding`. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ variables {α β : Type*} namespace equiv namespace perm variables (e : perm α) (ι : α ↪ β) open_locale classical /-- Noncomputable version of `equiv.perm.via_fintype_embedding` that does not assume `fintype` -/ noncomputable def via_embedding : perm β := extend_domain e (of_injective ι.1 ι.2) lemma via_embedding_apply (x : α) : e.via_embedding ι (ι x) = ι (e x) := extend_domain_apply_image e (of_injective ι.1 ι.2) x lemma via_embedding_apply_of_not_mem (x : β) (hx : x ∉ _root_.set.range ι) : e.via_embedding ι x = x := extend_domain_apply_not_subtype e (of_injective ι.1 ι.2) hx /-- `via_embedding` as a group homomorphism -/ noncomputable def via_embedding_hom : perm α →* perm β:= extend_domain_hom (of_injective ι.1 ι.2) lemma via_embedding_hom_apply : via_embedding_hom ι e = via_embedding e ι := rfl lemma via_embedding_hom_injective : function.injective (via_embedding_hom ι) := extend_domain_hom_injective (of_injective ι.1 ι.2) end perm end equiv
9ccc062a674c84ce1af4dcd0410e9d5ee576571a
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/set/prod.lean
9bdeb92e401a696d5552634820617ffd22790464
[ "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
21,591
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johannes Hölzl, Patrick Massot -/ import data.set.basic /-! # Sets in product and pi types This file defines the product of sets in `α × β` and in `Π i, α i` along with the diagonal of a type. ## Main declarations * `set.prod`: Binary product of sets. For `s : set α`, `t : set β`, we have `s.prod t : set (α × β)`. * `set.diagonal`: Diagonal of a type. `set.diagonal α = {(x, x) | x : α}`. * `set.pi`: Arbitrary product of sets. -/ open function namespace set /-! ### Cartesian binary product of sets -/ section prod variables {α β γ δ : Type*} {s s₁ s₂ : set α} {t t₁ t₂ : set β} {a : α} {b : β} /-- The cartesian product `prod s t` is the set of `(a, b)` such that `a ∈ s` and `b ∈ t`. -/ def prod (s : set α) (t : set β) : set (α × β) := {p | p.1 ∈ s ∧ p.2 ∈ t} /- This notation binds more strongly than (pre)images, unions and intersections. -/ infixr (name := set.prod) ` ×ˢ `:82 := set.prod lemma prod_eq (s : set α) (t : set β) : s ×ˢ t = prod.fst ⁻¹' s ∩ prod.snd ⁻¹' t := rfl lemma mem_prod_eq {p : α × β} : p ∈ s ×ˢ t = (p.1 ∈ s ∧ p.2 ∈ t) := rfl @[simp] lemma mem_prod {p : α × β} : p ∈ s ×ˢ t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl @[simp] lemma prod_mk_mem_set_prod_eq : (a, b) ∈ s ×ˢ t = (a ∈ s ∧ b ∈ t) := rfl lemma mk_mem_prod (ha : a ∈ s) (hb : b ∈ t) : (a, b) ∈ s ×ˢ t := ⟨ha, hb⟩ instance decidable_mem_prod [hs : decidable_pred (∈ s)] [ht : decidable_pred (∈ t)] : decidable_pred (∈ (s ×ˢ t)) := λ _, and.decidable lemma prod_mono (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) : s₁ ×ˢ t₁ ⊆ s₂ ×ˢ t₂ := λ x ⟨h₁, h₂⟩, ⟨hs h₁, ht h₂⟩ @[simp] lemma prod_self_subset_prod_self : s₁ ×ˢ s₁ ⊆ s₂ ×ˢ s₂ ↔ s₁ ⊆ s₂ := ⟨λ h x hx, (h (mk_mem_prod hx hx)).1, λ h x hx, ⟨h hx.1, h hx.2⟩⟩ @[simp] lemma prod_self_ssubset_prod_self : s₁ ×ˢ s₁ ⊂ s₂ ×ˢ s₂ ↔ s₁ ⊂ s₂ := and_congr prod_self_subset_prod_self $ not_congr prod_self_subset_prod_self lemma prod_subset_iff {P : set (α × β)} : s ×ˢ t ⊆ P ↔ ∀ (x ∈ s) (y ∈ t), (x, y) ∈ P := ⟨λ h _ hx _ hy, h (mk_mem_prod hx hy), λ h ⟨_, _⟩ hp, h _ hp.1 _ hp.2⟩ lemma forall_prod_set {p : α × β → Prop} : (∀ x ∈ s ×ˢ t, p x) ↔ ∀ (x ∈ s) (y ∈ t), p (x, y) := prod_subset_iff lemma exists_prod_set {p : α × β → Prop} : (∃ x ∈ s ×ˢ t, p x) ↔ ∃ (x ∈ s) (y ∈ t), p (x, y) := by simp [and_assoc] @[simp] lemma prod_empty : s ×ˢ (∅ : set β) = ∅ := by { ext, exact and_false _ } @[simp] lemma empty_prod : (∅ : set α) ×ˢ t = ∅ := by { ext, exact false_and _ } @[simp] lemma univ_prod_univ : @univ α ×ˢ @univ β = univ := by { ext, exact true_and _ } lemma univ_prod {t : set β} : (univ : set α) ×ˢ t = prod.snd ⁻¹' t := by simp [prod_eq] lemma prod_univ {s : set α} : s ×ˢ (univ : set β) = prod.fst ⁻¹' s := by simp [prod_eq] @[simp] lemma singleton_prod : ({a} : set α) ×ˢ t = prod.mk a '' t := by { ext ⟨x, y⟩, simp [and.left_comm, eq_comm] } @[simp] lemma prod_singleton : s ×ˢ ({b} : set β) = (λ a, (a, b)) '' s := by { ext ⟨x, y⟩, simp [and.left_comm, eq_comm] } lemma singleton_prod_singleton : ({a} : set α) ×ˢ ({b} : set β) = {(a, b)} :=by simp @[simp] lemma union_prod : (s₁ ∪ s₂) ×ˢ t = s₁ ×ˢ t ∪ s₂ ×ˢ t := by { ext ⟨x, y⟩, simp [or_and_distrib_right] } @[simp] lemma prod_union : s ×ˢ (t₁ ∪ t₂) = s ×ˢ t₁ ∪ s ×ˢ t₂ := by { ext ⟨x, y⟩, simp [and_or_distrib_left] } lemma prod_inter_prod : s₁ ×ˢ t₁ ∩ s₂ ×ˢ t₂ = (s₁ ∩ s₂) ×ˢ (t₁ ∩ t₂) := by { ext ⟨x, y⟩, simp [and_assoc, and.left_comm] } lemma insert_prod : insert a s ×ˢ t = (prod.mk a '' t) ∪ s ×ˢ t := by { ext ⟨x, y⟩, simp [image, iff_def, or_imp_distrib, imp.swap] {contextual := tt} } lemma prod_insert : s ×ˢ (insert b t) = ((λa, (a, b)) '' s) ∪ s ×ˢ t := by { ext ⟨x, y⟩, simp [image, iff_def, or_imp_distrib, imp.swap] {contextual := tt} } lemma prod_preimage_eq {f : γ → α} {g : δ → β} : (f ⁻¹' s) ×ˢ (g ⁻¹' t) = (λ p : γ × δ, (f p.1, g p.2)) ⁻¹' s ×ˢ t := rfl lemma prod_preimage_left {f : γ → α} : (f ⁻¹' s) ×ˢ t = (λ p : γ × β, (f p.1, p.2)) ⁻¹' s ×ˢ t := rfl lemma prod_preimage_right {g : δ → β} : s ×ˢ (g ⁻¹' t) = (λ p : α × δ, (p.1, g p.2)) ⁻¹' s ×ˢ t := rfl lemma preimage_prod_map_prod (f : α → β) (g : γ → δ) (s : set β) (t : set δ) : prod.map f g ⁻¹' s ×ˢ t = (f ⁻¹' s) ×ˢ (g ⁻¹' t) := rfl lemma mk_preimage_prod (f : γ → α) (g : γ → β) : (λ x, (f x, g x)) ⁻¹' s ×ˢ t = f ⁻¹' s ∩ g ⁻¹' t := rfl @[simp] lemma mk_preimage_prod_left (hb : b ∈ t) : (λ a, (a, b)) ⁻¹' s ×ˢ t = s := by { ext a, simp [hb] } @[simp] lemma mk_preimage_prod_right (ha : a ∈ s) : prod.mk a ⁻¹' s ×ˢ t = t := by { ext b, simp [ha] } @[simp] lemma mk_preimage_prod_left_eq_empty (hb : b ∉ t) : (λ a, (a, b)) ⁻¹' s ×ˢ t = ∅ := by { ext a, simp [hb] } @[simp] lemma mk_preimage_prod_right_eq_empty (ha : a ∉ s) : prod.mk a ⁻¹' s ×ˢ t = ∅ := by { ext b, simp [ha] } lemma mk_preimage_prod_left_eq_if [decidable_pred (∈ t)] : (λ a, (a, b)) ⁻¹' s ×ˢ t = if b ∈ t then s else ∅ := by split_ifs; simp [h] lemma mk_preimage_prod_right_eq_if [decidable_pred (∈ s)] : prod.mk a ⁻¹' s ×ˢ t = if a ∈ s then t else ∅ := by split_ifs; simp [h] lemma mk_preimage_prod_left_fn_eq_if [decidable_pred (∈ t)] (f : γ → α) : (λ a, (f a, b)) ⁻¹' s ×ˢ t = if b ∈ t then f ⁻¹' s else ∅ := by rw [← mk_preimage_prod_left_eq_if, prod_preimage_left, preimage_preimage] lemma mk_preimage_prod_right_fn_eq_if [decidable_pred (∈ s)] (g : δ → β) : (λ b, (a, g b)) ⁻¹' s ×ˢ t = if a ∈ s then g ⁻¹' t else ∅ := by rw [← mk_preimage_prod_right_eq_if, prod_preimage_right, preimage_preimage] lemma preimage_swap_prod {s : set α} {t : set β} : prod.swap ⁻¹' t ×ˢ s = s ×ˢ t := by { ext ⟨x, y⟩, simp [and_comm] } lemma image_swap_prod : prod.swap '' t ×ˢ s = s ×ˢ t := by rw [image_swap_eq_preimage_swap, preimage_swap_prod] lemma prod_image_image_eq {m₁ : α → γ} {m₂ : β → δ} : (m₁ '' s) ×ˢ (m₂ '' t) = (λ p : α × β, (m₁ p.1, m₂ p.2)) '' s ×ˢ t := ext $ by simp [-exists_and_distrib_right, exists_and_distrib_right.symm, and.left_comm, and.assoc, and.comm] lemma prod_range_range_eq {m₁ : α → γ} {m₂ : β → δ} : (range m₁) ×ˢ (range m₂) = range (λ p : α × β, (m₁ p.1, m₂ p.2)) := ext $ by simp [range] @[simp] lemma range_prod_map {m₁ : α → γ} {m₂ : β → δ} : range (prod.map m₁ m₂) = (range m₁) ×ˢ (range m₂) := prod_range_range_eq.symm lemma prod_range_univ_eq {m₁ : α → γ} : (range m₁) ×ˢ (univ : set β) = range (λ p : α × β, (m₁ p.1, p.2)) := ext $ by simp [range] lemma prod_univ_range_eq {m₂ : β → δ} : (univ : set α) ×ˢ (range m₂) = range (λ p : α × β, (p.1, m₂ p.2)) := ext $ by simp [range] lemma range_pair_subset (f : α → β) (g : α → γ) : range (λ x, (f x, g x)) ⊆ (range f) ×ˢ (range g) := have (λ x, (f x, g x)) = prod.map f g ∘ (λ x, (x, x)), from funext (λ x, rfl), by { rw [this, ← range_prod_map], apply range_comp_subset_range } lemma nonempty.prod : s.nonempty → t.nonempty → (s ×ˢ t).nonempty := λ ⟨x, hx⟩ ⟨y, hy⟩, ⟨(x, y), ⟨hx, hy⟩⟩ lemma nonempty.fst : (s ×ˢ t).nonempty → s.nonempty := λ ⟨x, hx⟩, ⟨x.1, hx.1⟩ lemma nonempty.snd : (s ×ˢ t).nonempty → t.nonempty := λ ⟨x, hx⟩, ⟨x.2, hx.2⟩ lemma prod_nonempty_iff : (s ×ˢ t).nonempty ↔ s.nonempty ∧ t.nonempty := ⟨λ h, ⟨h.fst, h.snd⟩, λ h, h.1.prod h.2⟩ lemma prod_eq_empty_iff : s ×ˢ t = ∅ ↔ s = ∅ ∨ t = ∅ := by simp only [not_nonempty_iff_eq_empty.symm, prod_nonempty_iff, not_and_distrib] lemma prod_sub_preimage_iff {W : set γ} {f : α × β → γ} : s ×ˢ t ⊆ f ⁻¹' W ↔ ∀ a b, a ∈ s → b ∈ t → f (a, b) ∈ W := by simp [subset_def] lemma image_prod_mk_subset_prod_left (hb : b ∈ t) : (λ a, (a, b)) '' s ⊆ s ×ˢ t := by { rintro _ ⟨a, ha, rfl⟩, exact ⟨ha, hb⟩ } lemma image_prod_mk_subset_prod_right (ha : a ∈ s) : prod.mk a '' t ⊆ s ×ˢ t := by { rintro _ ⟨b, hb, rfl⟩, exact ⟨ha, hb⟩ } lemma prod_subset_preimage_fst (s : set α) (t : set β) : s ×ˢ t ⊆ prod.fst ⁻¹' s := inter_subset_left _ _ lemma fst_image_prod_subset (s : set α) (t : set β) : prod.fst '' s ×ˢ t ⊆ s := image_subset_iff.2 $ prod_subset_preimage_fst s t lemma fst_image_prod (s : set β) {t : set α} (ht : t.nonempty) : prod.fst '' s ×ˢ t = s := (fst_image_prod_subset _ _).antisymm $ λ y hy, let ⟨x, hx⟩ := ht in ⟨(y, x), ⟨hy, hx⟩, rfl⟩ lemma prod_subset_preimage_snd (s : set α) (t : set β) : s ×ˢ t ⊆ prod.snd ⁻¹' t := inter_subset_right _ _ lemma snd_image_prod_subset (s : set α) (t : set β) : prod.snd '' s ×ˢ t ⊆ t := image_subset_iff.2 $ prod_subset_preimage_snd s t lemma snd_image_prod {s : set α} (hs : s.nonempty) (t : set β) : prod.snd '' s ×ˢ t = t := (snd_image_prod_subset _ _).antisymm $ λ y y_in, let ⟨x, x_in⟩ := hs in ⟨(x, y), ⟨x_in, y_in⟩, rfl⟩ lemma prod_diff_prod : s ×ˢ t \ s₁ ×ˢ t₁ = s ×ˢ (t \ t₁) ∪ (s \ s₁) ×ˢ t := by { ext x, by_cases h₁ : x.1 ∈ s₁; by_cases h₂ : x.2 ∈ t₁; simp * } /-- A product set is included in a product set if and only factors are included, or a factor of the first set is empty. -/ lemma prod_subset_prod_iff : s ×ˢ t ⊆ s₁ ×ˢ t₁ ↔ s ⊆ s₁ ∧ t ⊆ t₁ ∨ s = ∅ ∨ t = ∅ := begin cases (s ×ˢ t).eq_empty_or_nonempty with h h, { simp [h, prod_eq_empty_iff.1 h] }, have st : s.nonempty ∧ t.nonempty, by rwa [prod_nonempty_iff] at h, refine ⟨λ H, or.inl ⟨_, _⟩, _⟩, { have := image_subset (prod.fst : α × β → α) H, rwa [fst_image_prod _ st.2, fst_image_prod _ (h.mono H).snd] at this }, { have := image_subset (prod.snd : α × β → β) H, rwa [snd_image_prod st.1, snd_image_prod (h.mono H).fst] at this }, { intro H, simp only [st.1.ne_empty, st.2.ne_empty, or_false] at H, exact prod_mono H.1 H.2 } end lemma prod_eq_prod_iff_of_nonempty (h : (s ×ˢ t).nonempty) : s ×ˢ t = s₁ ×ˢ t₁ ↔ s = s₁ ∧ t = t₁ := begin split, { intro heq, have h₁ : (s₁ ×ˢ t₁ : set _).nonempty, { rwa [← heq] }, rw [prod_nonempty_iff] at h h₁, rw [← fst_image_prod s h.2, ← fst_image_prod s₁ h₁.2, heq, eq_self_iff_true, true_and, ← snd_image_prod h.1 t, ← snd_image_prod h₁.1 t₁, heq] }, { rintro ⟨rfl, rfl⟩, refl } end lemma prod_eq_prod_iff : s ×ˢ t = s₁ ×ˢ t₁ ↔ s = s₁ ∧ t = t₁ ∨ (s = ∅ ∨ t = ∅) ∧ (s₁ = ∅ ∨ t₁ = ∅) := begin symmetry, cases eq_empty_or_nonempty (s ×ˢ t) with h h, { simp_rw [h, @eq_comm _ ∅, prod_eq_empty_iff, prod_eq_empty_iff.mp h, true_and, or_iff_right_iff_imp], rintro ⟨rfl, rfl⟩, exact prod_eq_empty_iff.mp h }, rw [prod_eq_prod_iff_of_nonempty h], rw [← ne_empty_iff_nonempty, ne.def, prod_eq_empty_iff] at h, simp_rw [h, false_and, or_false], end @[simp] lemma prod_eq_iff_eq (ht : t.nonempty) : s ×ˢ t = s₁ ×ˢ t ↔ s = s₁ := begin simp_rw [prod_eq_prod_iff, ht.ne_empty, eq_self_iff_true, and_true, or_iff_left_iff_imp, or_false], rintro ⟨rfl, rfl⟩, refl, end @[simp] lemma image_prod (f : α → β → γ) : (λ x : α × β, f x.1 x.2) '' s ×ˢ t = image2 f s t := set.ext $ λ a, ⟨ by { rintro ⟨_, _, rfl⟩, exact ⟨_, _, (mem_prod.mp ‹_›).1, (mem_prod.mp ‹_›).2, rfl⟩ }, by { rintro ⟨_, _, _, _, rfl⟩, exact ⟨(_, _), mem_prod.mpr ⟨‹_›, ‹_›⟩, rfl⟩ }⟩ @[simp] lemma image2_mk_eq_prod : image2 prod.mk s t = s ×ˢ t := ext $ by simp section mono variables [preorder α] {f : α → set β} {g : α → set γ} theorem _root_.monotone.set_prod (hf : monotone f) (hg : monotone g) : monotone (λ x, f x ×ˢ g x) := λ a b h, prod_mono (hf h) (hg h) theorem _root_.antitone.set_prod (hf : antitone f) (hg : antitone g) : antitone (λ x, f x ×ˢ g x) := λ a b h, prod_mono (hf h) (hg h) theorem _root_.monotone_on.set_prod (hf : monotone_on f s) (hg : monotone_on g s) : monotone_on (λ x, f x ×ˢ g x) s := λ a ha b hb h, prod_mono (hf ha hb h) (hg ha hb h) theorem _root_.antitone_on.set_prod (hf : antitone_on f s) (hg : antitone_on g s) : antitone_on (λ x, f x ×ˢ g x) s := λ a ha b hb h, prod_mono (hf ha hb h) (hg ha hb h) end mono end prod /-! ### Diagonal In this section we prove some lemmas about the diagonal set `{p | p.1 = p.2}` and the diagonal map `λ x, (x, x)`. -/ section diagonal variables {α : Type*} {s t : set α} /-- `diagonal α` is the set of `α × α` consisting of all pairs of the form `(a, a)`. -/ def diagonal (α : Type*) : set (α × α) := {p | p.1 = p.2} lemma mem_diagonal (x : α) : (x, x) ∈ diagonal α := by simp [diagonal] @[simp] lemma mem_diagonal_iff {x : α × α} : x ∈ diagonal α ↔ x.1 = x.2 := iff.rfl instance decidable_mem_diagonal [h : decidable_eq α] (x : α × α) : decidable (x ∈ diagonal α) := h x.1 x.2 lemma preimage_coe_coe_diagonal (s : set α) : (prod.map coe coe) ⁻¹' (diagonal α) = diagonal s := by { ext ⟨⟨x, hx⟩, ⟨y, hy⟩⟩, simp [set.diagonal] } @[simp] lemma range_diag : range (λ x, (x, x)) = diagonal α := by { ext ⟨x, y⟩, simp [diagonal, eq_comm] } @[simp] lemma prod_subset_compl_diagonal_iff_disjoint : s ×ˢ t ⊆ (diagonal α)ᶜ ↔ disjoint s t := subset_compl_comm.trans $ by simp_rw [← range_diag, range_subset_iff, disjoint_left, mem_compl_iff, prod_mk_mem_set_prod_eq, not_and] @[simp] lemma diag_preimage_prod (s t : set α) : (λ x, (x, x)) ⁻¹' (s ×ˢ t) = s ∩ t := rfl lemma diag_preimage_prod_self (s : set α) : (λ x, (x, x)) ⁻¹' (s ×ˢ s) = s := inter_self s end diagonal /-! ### Cartesian set-indexed product of sets -/ section pi variables {ι : Type*} {α β : ι → Type*} {s s₁ s₂ : set ι} {t t₁ t₂ : Π i, set (α i)} {i : ι} /-- Given an index set `ι` and a family of sets `t : Π i, set (α i)`, `pi s t` is the set of dependent functions `f : Πa, π a` such that `f a` belongs to `t a` whenever `a ∈ s`. -/ def pi (s : set ι) (t : Π i, set (α i)) : set (Π i, α i) := {f | ∀ i ∈ s, f i ∈ t i} @[simp] lemma mem_pi {f : Π i, α i} : f ∈ s.pi t ↔ ∀ i ∈ s, f i ∈ t i := iff.rfl @[simp] lemma mem_univ_pi {f : Π i, α i} : f ∈ pi univ t ↔ ∀ i, f i ∈ t i := by simp @[simp] lemma empty_pi (s : Π i, set (α i)) : pi ∅ s = univ := by { ext, simp [pi] } @[simp] lemma pi_univ (s : set ι) : pi s (λ i, (univ : set (α i))) = univ := eq_univ_of_forall $ λ f i hi, mem_univ _ lemma pi_mono (h : ∀ i ∈ s, t₁ i ⊆ t₂ i) : pi s t₁ ⊆ pi s t₂ := λ x hx i hi, (h i hi $ hx i hi) lemma pi_inter_distrib : s.pi (λ i, t i ∩ t₁ i) = s.pi t ∩ s.pi t₁ := ext $ λ x, by simp only [forall_and_distrib, mem_pi, mem_inter_eq] lemma pi_congr (h : s₁ = s₂) (h' : ∀ i ∈ s₁, t₁ i = t₂ i) : s₁.pi t₁ = s₂.pi t₂ := h ▸ (ext $ λ x, forall₂_congr $ λ i hi, h' i hi ▸ iff.rfl) lemma pi_eq_empty (hs : i ∈ s) (ht : t i = ∅) : s.pi t = ∅ := by { ext f, simp only [mem_empty_eq, not_forall, iff_false, mem_pi, not_imp], exact ⟨i, hs, by simp [ht]⟩ } lemma univ_pi_eq_empty (ht : t i = ∅) : pi univ t = ∅ := pi_eq_empty (mem_univ i) ht lemma pi_nonempty_iff : (s.pi t).nonempty ↔ ∀ i, ∃ x, i ∈ s → x ∈ t i := by simp [classical.skolem, set.nonempty] lemma univ_pi_nonempty_iff : (pi univ t).nonempty ↔ ∀ i, (t i).nonempty := by simp [classical.skolem, set.nonempty] lemma pi_eq_empty_iff : s.pi t = ∅ ↔ ∃ i, is_empty (α i) ∨ i ∈ s ∧ t i = ∅ := begin rw [← not_nonempty_iff_eq_empty, pi_nonempty_iff], push_neg, refine exists_congr (λ i, ⟨λ h, (is_empty_or_nonempty (α i)).imp_right _, _⟩), { rintro ⟨x⟩, exact ⟨(h x).1, by simp [eq_empty_iff_forall_not_mem, h]⟩ }, { rintro (h | h) x, { exact h.elim' x }, { simp [h] } } end lemma univ_pi_eq_empty_iff : pi univ t = ∅ ↔ ∃ i, t i = ∅ := by simp [← not_nonempty_iff_eq_empty, univ_pi_nonempty_iff] @[simp] lemma univ_pi_empty [h : nonempty ι] : pi univ (λ i, ∅ : Π i, set (α i)) = ∅ := univ_pi_eq_empty_iff.2 $ h.elim $ λ x, ⟨x, rfl⟩ @[simp] lemma range_dcomp (f : Π i, α i → β i) : range (λ (g : Π i, α i), (λ i, f i (g i))) = pi univ (λ i, range (f i)) := begin apply subset.antisymm _ (λ x hx, _), { rintro _ ⟨x, rfl⟩ i -, exact ⟨x i, rfl⟩ }, { choose y hy using hx, exact ⟨λ i, y i trivial, funext $ λ i, hy i trivial⟩ } end @[simp] lemma insert_pi (i : ι) (s : set ι) (t : Π i, set (α i)) : pi (insert i s) t = (eval i ⁻¹' t i) ∩ pi s t := by { ext, simp [pi, or_imp_distrib, forall_and_distrib] } @[simp] lemma singleton_pi (i : ι) (t : Π i, set (α i)) : pi {i} t = (eval i ⁻¹' t i) := by { ext, simp [pi] } lemma singleton_pi' (i : ι) (t : Π i, set (α i)) : pi {i} t = {x | x i ∈ t i} := singleton_pi i t lemma univ_pi_singleton (f : Π i, α i) : pi univ (λ i, {f i}) = ({f} : set (Π i, α i)) := ext $ λ g, by simp [funext_iff] lemma pi_if {p : ι → Prop} [h : decidable_pred p] (s : set ι) (t₁ t₂ : Π i, set (α i)) : pi s (λ i, if p i then t₁ i else t₂ i) = pi {i ∈ s | p i} t₁ ∩ pi {i ∈ s | ¬ p i} t₂ := begin ext f, refine ⟨λ h, _, _⟩, { split; { rintro i ⟨his, hpi⟩, simpa [*] using h i } }, { rintro ⟨ht₁, ht₂⟩ i his, by_cases p i; simp * at * } end lemma union_pi : (s₁ ∪ s₂).pi t = s₁.pi t ∩ s₂.pi t := by simp [pi, or_imp_distrib, forall_and_distrib, set_of_and] @[simp] lemma pi_inter_compl (s : set ι) : pi s t ∩ pi sᶜ t = pi univ t := by rw [← union_pi, union_compl_self] lemma pi_update_of_not_mem [decidable_eq ι] (hi : i ∉ s) (f : Π j, α j) (a : α i) (t : Π j, α j → set (β j)) : s.pi (λ j, t j (update f i a j)) = s.pi (λ j, t j (f j)) := pi_congr rfl $ λ j hj, by { rw update_noteq, exact λ h, hi (h ▸ hj) } lemma pi_update_of_mem [decidable_eq ι] (hi : i ∈ s) (f : Π j, α j) (a : α i) (t : Π j, α j → set (β j)) : s.pi (λ j, t j (update f i a j)) = {x | x i ∈ t i a} ∩ (s \ {i}).pi (λ j, t j (f j)) := calc s.pi (λ j, t j (update f i a j)) = ({i} ∪ s \ {i}).pi (λ j, t j (update f i a j)) : by rw [union_diff_self, union_eq_self_of_subset_left (singleton_subset_iff.2 hi)] ... = {x | x i ∈ t i a} ∩ (s \ {i}).pi (λ j, t j (f j)) : by { rw [union_pi, singleton_pi', update_same, pi_update_of_not_mem], simp } lemma univ_pi_update [decidable_eq ι] {β : Π i, Type*} (i : ι) (f : Π j, α j) (a : α i) (t : Π j, α j → set (β j)) : pi univ (λ j, t j (update f i a j)) = {x | x i ∈ t i a} ∩ pi {i}ᶜ (λ j, t j (f j)) := by rw [compl_eq_univ_diff, ← pi_update_of_mem (mem_univ _)] lemma univ_pi_update_univ [decidable_eq ι] (i : ι) (s : set (α i)) : pi univ (update (λ j : ι, (univ : set (α j))) i s) = eval i ⁻¹' s := by rw [univ_pi_update i (λ j, (univ : set (α j))) s (λ j t, t), pi_univ, inter_univ, preimage] lemma eval_image_pi_subset (hs : i ∈ s) : eval i '' s.pi t ⊆ t i := image_subset_iff.2 $ λ f hf, hf i hs lemma eval_image_univ_pi_subset : eval i '' pi univ t ⊆ t i := eval_image_pi_subset (mem_univ i) lemma eval_image_pi (hs : i ∈ s) (ht : (s.pi t).nonempty) : eval i '' s.pi t = t i := begin refine (eval_image_pi_subset hs).antisymm _, classical, obtain ⟨f, hf⟩ := ht, refine λ y hy, ⟨update f i y, λ j hj, _, update_same _ _ _⟩, obtain rfl | hji := eq_or_ne j i; simp [*, hf _ hj] end @[simp] lemma eval_image_univ_pi (ht : (pi univ t).nonempty) : (λ f : Π i, α i, f i) '' pi univ t = t i := eval_image_pi (mem_univ i) ht lemma eval_preimage [decidable_eq ι] {s : set (α i)} : eval i ⁻¹' s = pi univ (update (λ i, univ) i s) := by { ext x, simp [@forall_update_iff _ (λ i, set (α i)) _ _ _ _ (λ i' y, x i' ∈ y)] } lemma eval_preimage' [decidable_eq ι] {s : set (α i)} : eval i ⁻¹' s = pi {i} (update (λ i, univ) i s) := by { ext, simp } lemma update_preimage_pi [decidable_eq ι] {f : Π i, α i} (hi : i ∈ s) (hf : ∀ j ∈ s, j ≠ i → f j ∈ t j) : (update f i) ⁻¹' s.pi t = t i := begin ext x, refine ⟨λ h, _, λ hx j hj, _⟩, { convert h i hi, simp }, { obtain rfl | h := eq_or_ne j i, { simpa }, { rw update_noteq h, exact hf j hj h } } end lemma update_preimage_univ_pi [decidable_eq ι] {f : Π i, α i} (hf : ∀ j ≠ i, f j ∈ t j) : (update f i) ⁻¹' pi univ t = t i := update_preimage_pi (mem_univ i) (λ j _, hf j) lemma subset_pi_eval_image (s : set ι) (u : set (Π i, α i)) : u ⊆ pi s (λ i, eval i '' u) := λ f hf i hi, ⟨f, hf, rfl⟩ lemma univ_pi_ite (s : set ι) [decidable_pred (∈ s)] (t : Π i, set (α i)) : pi univ (λ i, if i ∈ s then t i else univ) = s.pi t := by { ext, simp_rw [mem_univ_pi], refine forall_congr (λ i, _), split_ifs; simp [h] } end pi end set
352203ea9c457e21d87d7b075c36354f548100a8
3adda22358e3c0fbae44c6c35fdddbebf9358ef4
/exam18.lean
5d79198c4b56dba8c17c50ccc556a21bb9dfb6e7
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/M1F-exam-may-2018
1539951b055cea5bac915bdb6fa1969e2f323402
8b5eca2037d4a14d6cfac3da1858b6c4119216d3
refs/heads/master
1,586,895,978,182
1,557,175,794,000
1,557,175,794,000
164,093,611
2
0
null
null
null
null
UTF-8
Lean
false
false
27,761
lean
import tactic.norm_num import tactic.linarith import tactic.ring import data.nat.basic import data.real.basic import data.set.basic import data.set.lattice import data.complex.basic import data.complex.exponential import data.polynomial --import analysis.polynomial --import analysis.exponential import data.nat.choose universe u local attribute [instance, priority 0] classical.prop_decidable --QUESTION 1 section question_1 open nat ----part a ------i theorem count (n : ℕ) (hn : n ≥ 1) : finset.sum (finset.range (nat.succ n)) (λ m, choose n m) = 2 ^ n := ---ans begin have H := (add_pow (1 : ℕ) 1 n).symm, simpa [nat.one_pow, one_mul, one_add_one_eq_two, (finset.sum_nat_cast _ _).symm, nat.cast_id] using H, end ------ii theorem countdown (n : ℕ) (hn : n ≥ 1) : finset.sum (finset.range (nat.succ n)) (λ m, (-1 : ℤ) ^ m * choose n m) = 0 := ---ans begin have H := (add_pow (-1 : ℤ) 1 n).symm, have H2 := @_root_.zero_pow ℤ _ _ hn, simpa [nat.one_pow, one_mul, one_add_one_eq_two, nat.zero_pow hn, (finset.sum_nat_cast _ _).symm, nat.cast_id, H2] using H, end ----part b ------i open real #exit noncomputable def chebyshev : ℕ → polynomial ℝ | 0 := polynomial.C 1 | 1 := polynomial.X | (n + 2) := 2 * polynomial.X * chebyshev (n + 1) - chebyshev n def chebyshev' : ℕ → polynomial ℤ | 0 := polynomial.C 1 | 1 := polynomial.X | (n + 2) := 2 * polynomial.X * chebyshev' (n + 1) - chebyshev' n lemma polycos (n : ℕ) (hn : n ≥ 1) : ∀ θ : ℝ, cos (n * θ) = polynomial.eval (cos θ) (chebyshev n) := begin intro θ, apply nat.strong_induction_on n, intros k ih, have ih1 : cos (↑(k - 1) * θ) = polynomial.eval (cos θ) (chebyshev (k - 1)), by_cases h : k = 0, simp [h, chebyshev], --by_cases h : k ≠ 0, exact ih (k - 1) (nat.sub_lt (nat.pos_of_ne_zero h) (by norm_num : 0 < 1)), have ih2 : cos (↑(k - 2) * θ) = polynomial.eval (cos θ) (chebyshev (k - 2)), by_cases h : k = 0, simp [h, chebyshev], --by_cases h : k ≠ 0, exact ih (k - 2) (nat.sub_lt (nat.pos_of_ne_zero h) (by norm_num : 0 < 2)), by_cases h1 : k = 0, simp [h1, chebyshev], by_cases h2 : k = 1, simp [h2, chebyshev], have hk : k = (k - 2) + 2, rw nat.sub_add_cancel, swap, rw [hk, chebyshev, ←hk, nat.succ_eq_add_one, (_ : k - 2 + 1 = k - 1), two_mul, polynomial.eval_sub, polynomial.eval_mul, polynomial.eval_add, polynomial.eval_X, ←two_mul, ←ih1, ←ih2], rw [←complex.of_real_inj, complex.of_real_sub, complex.of_real_mul, complex.of_real_mul, complex.of_real_cos, complex.of_real_cos, complex.of_real_cos, complex.of_real_cos, complex.cos, complex.cos, complex.cos, complex.cos], simp, rw [mul_div_cancel', ←mul_div_assoc, ←neg_div, ←add_div, add_mul, mul_add, mul_add, ←complex.exp_add, ←complex.exp_add, ←complex.exp_add, ←complex.exp_add, mul_assoc, mul_assoc, mul_assoc], rw [←one_mul (↑θ * complex.I)] {occs := occurrences.pos [5, 7]}, rw [←add_mul, ←sub_eq_add_neg, ←sub_mul, ←neg_one_mul (↑θ * complex.I), ←add_mul, ←sub_eq_add_neg, ←sub_mul, @nat.cast_sub _ _ _ 1 k, add_sub, nat.cast_one, add_sub_cancel', ←sub_add, sub_add_eq_add_sub, one_add_one_eq_two, add_sub, ←sub_add_eq_add_sub, ←neg_add', one_add_one_eq_two, ←sub_add, sub_add_eq_add_sub, neg_add_self, zero_sub, nat.cast_sub, neg_mul_eq_neg_mul, neg_mul_eq_neg_mul, neg_sub, nat.cast_two, neg_add, sub_eq_neg_add, ←add_assoc, ←neg_add, ←sub_eq_neg_add, add_sub_add_right_eq_sub, ←add_assoc, sub_add_cancel], all_goals { try { have H : k ≥ 2, apply le_of_not_gt, intro, have h12 : k = 0 ∨ k = 1, clear ih ih1 ih2 h1 h2, try { clear hk }, revert k a, exact dec_trivial, apply or.elim h12 (λ h12, h1 h12) (λ h12, h2 h12) }, try { exact H }, try { exact le_trans (by norm_num : 1 ≤ 2) H } }, apply two_ne_zero', apply @eq_of_add_eq_add_right _ _ _ 1 _, rw [add_assoc, one_add_one_eq_two, nat.sub_add_cancel H, nat.sub_add_cancel (le_trans (by norm_num : 1 ≤ 2) H)] end theorem exist_polycos (n : ℕ) (hn : n ≥ 1) : ∃ Pn : polynomial ℝ, ∀ θ : ℝ, cos (n * θ) = polynomial.eval (cos θ) Pn := ---ans Exists.intro (chebyshev n) (polycos n hn) ------ii open polynomial example : chebyshev' 4 = 8 * X ^ 4 - 8 * X ^ 2 + 1 := begin unfold chebyshev', ring end ------iii lemma useful (k : ℕ) : polynomial.degree (chebyshev' k) = k := begin apply nat.strong_induction_on k, intros n ih, have ih1 : polynomial.degree (chebyshev' (n - 1)) = ↑(n - 1), by_cases h : n = 0, simp [h, chebyshev'], refl, exact ih _ (nat.sub_lt (nat.pos_of_ne_zero h) (zero_lt_one)), have ih2 : polynomial.degree (chebyshev' (n - 2)) = ↑(n - 2), by_cases h : n ≤ 1, apply or.elim ((dec_trivial : ∀ j : ℕ, j ≤ 1 → j = 0 ∨ j = 1) n h), intro h0, simp [h0, chebyshev'], refl, intro h1, simp [h1, chebyshev'], refl, apply ih _, apply nat.sub_lt (lt_of_not_ge (λ w, h (le_trans w zero_le_one))), norm_num, by_cases h : n ≥ 2, have H : n - 2 + 2 = n := nat.sub_add_cancel h, have H' : nat.succ (n - 2) = n - 1, have W : n ≥ 2, apply le_of_not_gt, intro, have h12 : n = 0 ∨ n = 1, clear ih ih1 ih2 H h, revert n a, exact dec_trivial, apply or.elim h12, intro h1, rw h1 at h, revert h, norm_num, intro h2, rw h2 at h, revert h, norm_num, apply @eq_of_add_eq_add_right _ _ _ 1 _, show n - 2 + 1 + 1 = n - 1 + 1, rw [add_assoc, one_add_one_eq_two, nat.sub_add_cancel W, nat.sub_add_cancel (le_of_lt h)], rw [←H, chebyshev', H, sub_eq_neg_add, polynomial.degree_add_eq_of_degree_lt, polynomial.degree_mul_eq, polynomial.degree_mul_eq, polynomial.degree_X, H', ih1], show (polynomial.degree (polynomial.C 2) + 1 + ↑(n - 1) = ↑n), rw [polynomial.degree_C, zero_add, ←with_bot.coe_one, ←with_bot.coe_add, add_comm, nat.sub_add_cancel (le_of_lt h)], exact two_ne_zero', rw [polynomial.degree_neg, polynomial.degree_mul_eq, polynomial.degree_mul_eq, ih2, H', ih1], show (↑(n - 2) < polynomial.degree (polynomial.C 2) + polynomial.degree polynomial.X + ↑(n - 1)), rw [polynomial.degree_C, polynomial.degree_X, zero_add, ←with_bot.coe_one, ←with_bot.coe_add, add_comm, nat.sub_add_cancel (le_of_lt h), with_bot.coe_lt_coe], apply nat.sub_lt (lt_trans zero_lt_one h), norm_num, exact two_ne_zero', apply or.elim ((dec_trivial : ∀ j : ℕ, j ≤ 1 → j = 0 ∨ j = 1) n (le_of_not_gt h)), intro h0, simp [h0, chebyshev'], refl, intro h1, simp [h1, chebyshev'] end lemma useful' (k : ℕ) : polynomial.degree (chebyshev' (k - 2)) < 1 + polynomial.degree (chebyshev' (k - 1)) := begin rw [useful, useful, ←with_bot.coe_one, ←with_bot.coe_add, with_bot.coe_lt_coe, add_comm], by_cases h : k ≤ 1, apply or.elim ((dec_trivial : ∀ (j : ℕ), j ≤ 1 → j = 0 ∨ j = 1) k h), intro h0, simp [h0], exact zero_lt_one, intro h1, simp [h1], exact zero_lt_one, rw [nat.sub_add_cancel (le_of_not_le h)], apply nat.sub_lt (lt_of_lt_of_le zero_lt_one (le_of_not_le h)), norm_num end theorem not_useful (n : ℕ) : polynomial.leading_coeff (chebyshev' n) = 2 ^ (n - 1) := ---ans begin apply nat.strong_induction_on n, intros k hk, have h1 : polynomial.leading_coeff (chebyshev' (k - 1)) = 2 ^ (k - 1 - 1), by_cases h : k = 0, simp [h, chebyshev'], exact hk (k - 1) (nat.pred_lt h : k - 1 < k), have h2 : polynomial.leading_coeff (chebyshev' (k - 2)) = 2 ^ (k - 2 - 1), by_cases h : k ≤ 1, apply or.elim ((dec_trivial : ∀ j : ℕ, j ≤ 1 → j = 0 ∨ j = 1) k h), intro h0, simp [h0, chebyshev'], intro h1, simp [h1, chebyshev'], exact hk (k - 2) (nat.sub_lt (lt_of_not_ge (λ w, h (le_trans w zero_le_one))) (by norm_num)), by_cases h : k ≥ 2, have H : k - 2 + 2 = k := nat.sub_add_cancel h, rw [←H, chebyshev', H, (_ : nat.succ (k - 2) = k - 1), sub_eq_add_neg, add_comm, polynomial.leading_coeff_add_of_degree_lt, polynomial.leading_coeff_mul, polynomial.leading_coeff_mul, ←one_add_one_eq_two, polynomial.leading_coeff_add_of_degree_eq rfl, ←polynomial.C_1, polynomial.leading_coeff_C, polynomial.leading_coeff_X, h1, one_add_one_eq_two, mul_one, ←pow_succ, nat.sub_add_cancel], change 1 ≤ k - 1, rwa [nat.le_sub_left_iff_add_le (le_of_lt h), one_add_one_eq_two], rw [←polynomial.C_1, polynomial.leading_coeff_C, one_add_one_eq_two], exact two_ne_zero', rw [polynomial.degree_neg, polynomial.degree_mul_eq, polynomial.degree_mul_eq, ((one_add_one_eq_two).symm : ((2 : polynomial ℤ) = 1 + 1)), ←polynomial.C_1, ←polynomial.C_add, one_add_one_eq_two, polynomial.degree_C, zero_add, polynomial.degree_X], exact useful' k, exact two_ne_zero', rw [nat.succ_eq_add_one, eq_comm, ←nat.sub_eq_iff_eq_add, nat.sub_sub, one_add_one_eq_two], rwa [nat.le_sub_left_iff_add_le (le_of_lt h), one_add_one_eq_two], rw not_lt at h, have h' : k = 0 ∨ k = 1, clear hk h1 h2, revert k h, exact dec_trivial, cases h', all_goals { simp [h', chebyshev'] } end ------iv theorem cheby1 (n : ℕ) (hn : n ≥ 1) : polynomial.eval 1 (chebyshev n) = 1 := ---ans begin have h := (polycos n hn 0).symm, rwa [mul_zero, cos_zero] at h, end --QUESTION 2 ----part a ------i def ub (S : set ℝ) (x : ℝ) := ∀ s ∈ S, s ≤ x ---ans ------ii def iba (S : set ℝ) := ∃ x, ub S x ---ans ------iii def lub (S : set ℝ) (x : ℝ) := ub S x ∧ ∀ y : ℝ, (ub S y → x ≤ y) ---ans ----part b theorem lub_duh (S : set ℝ) : (∃ x, lub S x) → S ≠ ∅ ∧ iba S := ---ans begin intro Hexlub, cases Hexlub with x Hlub, split, intro Hemp, rw set.empty_def at Hemp, cases Hlub with Hub Hl, have Hallub : ∀ y : ℝ, ub S y, unfold ub, rw Hemp, change (∀ (y s : ℝ), false → s ≤ y), intros y s Hf, exfalso, exact Hf, have Hneginf : ∀ y : ℝ, x ≤ y, intro y, apply Hl, apply Hallub, have Hcontr := Hneginf (x - 1), revert Hcontr, norm_num, --split, existsi x, exact Hlub.left, end ----part c ------i def S1 := {x : ℝ | x < 59} lemma between_bounds (x y : ℝ) (H : x < y) : x < (x + y) / 2 ∧ (x + y) / 2 < y := ⟨by linarith, by linarith⟩ theorem S1_lub : ∃ x, lub S1 x := ---ans begin existsi (59 : ℝ), split, intro, change (s < 59 → s ≤ 59), exact le_of_lt, --split, intro y, change ((∀ (s : ℝ), s < 59 → s ≤ y) → 59 ≤ y), intro Hbub, apply le_of_not_gt, intro Hbadub, have Houtofbounds := between_bounds y 59 Hbadub, apply not_le_of_gt Houtofbounds.1 (Hbub ((y + 59) / 2) Houtofbounds.2), end ------ii /------------------SORRY--------------------/ ----part d ------i theorem ublub_the_first (S : set ℝ) (b : ℝ) (hub : ub S b) (hin : b ∈ S) : lub S b := ---ans begin split, exact hub, --split, intros y huby, exact huby b hin, end ------ii theorem adlub_the_second (S T : set ℝ) (b c : ℝ) (hlubb : lub S b) (hlubc : lub T c) ---ans : lub ({x : ℝ | ∃ s t : ℝ, s ∈ S ∧ t ∈ T ∧ x = s + t}) (b + c) := begin split, unfold ub, simp, intros x s hss t htt hxst, rw hxst, apply add_le_add (hlubb.1 s hss) (hlubc.1 t htt), --split, unfold ub, simp, intros x Hx, apply le_of_not_gt, intro Hcontr, let ε := b + c - x, have Hcontr' : ε > 0 := (by linarith : b + c - x > 0), have rwx : x = (b - ε / 2) + (c - ε / 2) := (by linarith : x = (b - (b + c - x) / 2) + (c - (b + c - x) / 2)), have hnbub : ∃ s' ∈ S, b - ε / 2 < s', by_contradiction, have a' : (¬∃ (s' : ℝ), s' ∈ S ∧ b - ε / 2 < s'), intro b, apply a, cases b with σ Hσ, existsi σ, existsi Hσ.1, exact Hσ.2, have a'' : ∀ (x : ℝ), x ∈ S → ¬(b - ε / 2 < x), intros x Hx Hb, rw not_exists at a', apply a' x, exact ⟨Hx, Hb⟩, simp only [not_lt] at a'', rw ←ub at a'', have a''' := hlubb.2 _ a'', linarith, have hnbuc : ∃ t' ∈ T, c - ε / 2 < t', by_contradiction, have a' : (¬∃ (t' : ℝ), t' ∈ T ∧ c - ε / 2 < t'), intro b, apply a, cases b with σ Hσ, existsi σ, existsi Hσ.1, exact Hσ.2, have a'' : ∀ (x : ℝ), x ∈ T → ¬(c - ε / 2 < x), intros x Hx Hc, rw not_exists at a', apply a' x, exact ⟨Hx, Hc⟩, simp only [not_lt] at a'', rw ←ub at a'', have a''' := hlubc.2 _ a'', linarith, cases hnbub with s' hnbub', cases hnbub' with Hs' hnbub'', cases hnbuc with t' hnbuc', cases hnbuc' with Ht' hnbuc'', have Hx' := Hx (s' + t') s' Hs' t' Ht' rfl, have Haha : x < x := lt_of_lt_of_le (by { rw rwx, apply add_lt_add hnbub'' hnbuc'' } : x < s' + t') Hx', linarith, end --QUESTION 3 variable {S : Type u} ----part a ------i variable (binary_relation : S → S → Prop) ---ans local infix ` ~ `:1000 := binary_relation ------ii def reflexivity := ∀ x, x ~ x def symmetry := ∀ (x y), x ~ y → y ~ x def transitivity := ∀ (x y z), x ~ y → y ~ z → x ~ z def is_equivalence := reflexivity binary_relation ∧ symmetry binary_relation ∧ transitivity binary_relation ---ans ------iii variable {binary_relation} def cl (h : is_equivalence binary_relation) (a : S) : set S := { x | x ~ a } ---ans ----part b theorem classes_injective2 (h : is_equivalence binary_relation) (a b : S) : (cl h a = cl h b) ∨ (cl h a ∩ cl h b) = ∅ := ---ans begin /-duplicate h so we can continue using it as a parameter to cl, then unpack hDupe-/ have hDupe : is_equivalence binary_relation := h, cases hDupe with hR hST, cases hST with hS hT, rw reflexivity at hR, rw symmetry at hS, rw transitivity at hT, /-if one of them is true (if they exclude) we don't need to bother-/ cases classical.em (cl h a ∩ cl h b = ∅) with excl intsct, --case excl right, exact excl, --case intsct left, /-prove that if something isn't empty it must have stuff in it-/ rw set.eq_empty_iff_forall_not_mem at intsct, rw not_forall_not at intsct, /-clean stuff up-/ cases intsct with x intsctX, cases intsctX with intsctXa intsctXb, rw cl at intsctXa, rw cl at intsctXb, change binary_relation x a at intsctXa, change binary_relation x b at intsctXb, rename intsctXa Hrxa, rename intsctXb Hrxb, rw cl, rw cl, /-now do the actual math-/ have Hrax : binary_relation a x, apply hS x a, exact Hrxa, have Hrab : binary_relation a b, apply hT a x b, exact Hrax, exact Hrxb, have Hrba : binary_relation b a, apply hS a b, exact Hrab, /-definition of set equivalence-/ apply set.eq_of_subset_of_subset, --split 1 /-clean things up again-/ intro y, intro Hrya, change binary_relation y a at Hrya, change binary_relation y b, /-do math again-/ apply hT y a b, exact Hrya, exact Hrab, --split 2 /-clean things up again-/ intro y, intro Hryb, change binary_relation y b at Hryb, change binary_relation y a, /-do math again-/ have Hrby : binary_relation b y, apply hS y b, exact Hryb, apply hT y b a, exact Hryb, exact Hrba, end ----part c inductive double_cosets : ℤ → ℤ → Prop | cond1 : ∀ x, double_cosets x (x + 3) | cond2 : ∀ x, double_cosets x (x - 5) | condT : ∀ x y z, double_cosets x y → double_cosets y z → double_cosets x z local infix ` ⋆ `:1001 := double_cosets theorem double_cosets_reflexive : reflexivity double_cosets := ---ans begin rw reflexivity, intro x, /-get some trivial things out of the way-/ have H0 : x - 5 - 5 - 5 + 3 + 3 + 3 + 3 + 3 = x, norm_num, /-start moving-/ have Hx5x : x ⋆ (x - 5), exact double_cosets.cond2 x, have H5x10x : (x - 5) ⋆ (x - 5 - 5), exact double_cosets.cond2 (x - 5), have H10x15x : (x - 5 - 5) ⋆ (x - 5 - 5 - 5), exact double_cosets.cond2 (x - 5 - 5), /-transitivity is hopper fare-/ have Hx10x : x ⋆ (x - 5 - 5), apply double_cosets.condT x (x - 5) (x - 5 - 5), exact Hx5x, exact H5x10x, have Hx15x : x ⋆ (x - 5 - 5 - 5), apply double_cosets.condT x (x - 5 - 5) (x - 5 - 5 - 5), exact Hx10x, exact H10x15x, /-now come back-/ have H15x12x : (x - 5 - 5 - 5) ⋆ (x - 5 - 5 - 5 + 3), exact double_cosets.cond1 (x - 5 - 5 - 5), have H12x9x : (x - 5 - 5 - 5 + 3) ⋆ (x - 5 - 5 - 5 + 3 + 3), exact double_cosets.cond1 (x - 5 - 5 - 5 + 3), have H9x6x : (x - 5 - 5 - 5 + 3 + 3) ⋆ (x - 5 - 5 - 5 + 3 + 3 + 3), exact double_cosets.cond1 (x - 5 - 5 - 5 + 3 + 3), have H6x3x : (x - 5 - 5 - 5 + 3 + 3 + 3) ⋆ (x - 5 - 5 - 5 + 3 + 3 + 3 + 3), exact double_cosets.cond1 (x - 5 - 5 - 5 + 3 + 3 + 3), have H3xx : (x - 5 - 5 - 5 + 3 + 3 + 3 + 3) ⋆ (x - 5 - 5 - 5 + 3 + 3 + 3 + 3 + 3), exact double_cosets.cond1 (x - 5 - 5 - 5 + 3 + 3 + 3 + 3), /-are we still within 1 hour?-/ have H15x9x : (x - 5 - 5 - 5) ⋆ (x - 5 - 5 - 5 + 3 + 3), apply double_cosets.condT (x - 5 - 5 - 5) (x - 5 - 5 - 5 + 3) (x - 5 - 5 - 5 + 3 + 3), exact H15x12x, exact H12x9x, have H15x6x : (x - 5 - 5 - 5) ⋆ (x - 5 - 5 - 5 + 3 + 3 + 3), apply double_cosets.condT (x - 5 - 5 - 5) (x - 5 - 5 - 5 + 3 + 3) (x - 5 - 5 - 5 + 3 + 3 + 3), exact H15x9x, exact H9x6x, have H15x3x : (x - 5 - 5 - 5) ⋆ (x - 5 - 5 - 5 + 3 + 3 + 3 + 3), apply double_cosets.condT (x - 5 - 5 - 5) (x - 5 - 5 - 5 + 3 + 3 + 3) (x - 5 - 5 - 5 + 3 + 3 + 3 + 3), exact H15x6x, exact H6x3x, have H15xx : (x - 5 - 5 - 5) ⋆ (x - 5 - 5 - 5 + 3 + 3 + 3 + 3 + 3), apply double_cosets.condT (x - 5 - 5 - 5) (x - 5 - 5 - 5 + 3 + 3 + 3 + 3) (x - 5 - 5 - 5 + 3 + 3 + 3 + 3 + 3), exact H15x3x, exact H3xx, have Hxx : x ⋆ (x - 5 - 5 - 5 + 3 + 3 + 3 + 3 + 3), apply double_cosets.condT x (x - 5 - 5 - 5) (x - 5 - 5 - 5 + 3 + 3 + 3 + 3 + 3), exact Hx15x, exact H15xx, /-show that we're back-/ rw H0 at Hxx, exact Hxx, end ----part d def S' : Type := fin 2 inductive self : fin 2 → fin 2 → Prop | condR : ∀ x, self x x local infix ` ⋆ `:1 := self theorem self_transitive : transitivity self := ---ans begin rw transitivity, intros x y z, --rw S' at z y x, have Hxyyzzx : x = y ∨ y = z ∨ z = x, cases classical.em (x = y ∨ y = z ∨ z = x) with corr contr, --case corr exact corr, --case contr exfalso, have contr_rw : ¬ (x = y) ∧ ¬ (y = z) ∧ ¬ (z = x), rw ←not_or_distrib, rw ←not_or_distrib, exact contr, cases contr_rw with contr_xy contr_yzzx, cases contr_yzzx with contr_yz contr_zx, have H01 : ∀ s : fin 2, s = 0 ∨ s = 1, exact dec_trivial, have x01 : x = 0 ∨ x = 1, exact H01 x, have y01 : y = 0 ∨ y = 1, exact H01 y, have z01 : z = 0 ∨ z = 1, exact H01 z, cases x01, cases y01, cases z01, rw ←y01 at x01, apply contr_xy, exact x01, rw ←y01 at x01, apply contr_xy, exact x01, cases z01, rw ←x01 at z01, apply contr_zx, exact z01, rw ←z01 at y01, apply contr_yz, exact y01, cases y01, cases z01, rw ←z01 at y01, apply contr_yz, exact y01, rw ←x01 at z01, apply contr_zx, exact z01, cases z01, rw ←y01 at x01, apply contr_xy, exact x01, rw ←y01 at x01, apply contr_xy, exact x01, cases Hxyyzzx with Hxy Hyzzx, --case Hxy rw Hxy, intro Hyy, intro Hyz, exact Hyz, cases Hyzzx with Hyz Hxy, --case Hyz rw Hyz, intro Hxz, intro Hzz, exact Hxz, --case Hxy rw Hxy, intro Hxy, intro Hyx, exact self.condR x, end --QUESTION 4 variable {X : Type u} variable {Y : Type u} variable {f : X → Y} ----part a ------i def injectivity (g : X → Y) := ∀ x1 x2 : X, g x1 = g x2 → x1 = x2 ---ans ------ii def surjectivity (g : X → Y) := ∀ y : Y, ∃ x : X, g x = y ---ans ------iii def bijectivity (g : X → Y) := injectivity g ∧ surjectivity g ---ans ----part b ------i def f1 : ℕ → ℕ | n := n + 2 theorem injection : ∃ f : ℕ → ℕ, injectivity f ∧ ¬ surjectivity f := ---ans begin have injectionf1 : injectivity f1 ∧ ¬ surjectivity f1, split, --split 1 rw injectivity, change ∀ (x1 x2 : ℕ), x1 + 2 = x2 + 2 → x1 = x2, intros x1 x2, intro Hinjsame, calc x1 = x1 + 2 - 2 : by rw nat.add_sub_cancel ... = x2 + 2 - 2 : by rw Hinjsame ... = x2 : by rw nat.add_sub_cancel, --split 2 rw surjectivity, intro Hsurj, change ∀ (y : ℕ), ∃ (x : ℕ), x + 2 = y at Hsurj, have Hsurj1 := Hsurj 1, cases Hsurj1 with x Hx10', have Hx10 : x + 1 = 0 := calc x + 1 = x + (2 - 1) : by norm_num ... = (x + 2) - 1 : begin rw ←nat.add_sub_assoc, norm_num end ... = 1 - 1 : by rw Hx10' ... = 0 : by rw nat.sub_self, have Hnx10 : x + 1 ≠ 0, exact nat.add_one_ne_zero x, apply Hnx10, exact Hx10, fapply exists.intro, exact f1, exact injectionf1, end ------ii def f2 : ℕ → ℕ | n := n / 2 theorem surjection : ∃ f : ℕ → ℕ, surjectivity f ∧ ¬ injectivity f := ---ans begin have surjectionf2 : surjectivity f2 ∧ ¬ injectivity f2, split, --split 1 rw surjectivity, change ∀ (y : ℕ), ∃ (x : ℕ), x / 2 = y, intro y, fapply exists.intro, exact 2 * y, calc 2 * y / 2 = (2 * y + 0) / 2 : by rw nat.add_zero ... = (0 + 2 * y) / 2 : by rw nat.add_comm ... = 0 / 2 + y : begin rw nat.add_mul_div_left 0 y, norm_num, end ... = 0 + y : by norm_num ... = y + 0 : by rw nat.add_comm ... = y : by rw nat.add_zero, --split 2 rw injectivity, intro Hinj, change ∀ (x1 x2 : ℕ), x1 / 2 = x2 / 2 → x1 = x2 at Hinj, have Hinjsame23 := Hinj 2 3, have Hn23 : 2 = 3 → false, norm_num, apply Hn23, apply Hinjsame23, norm_num, fapply exists.intro, exact f2, exact surjectionf2, end ------iii theorem bijections_are_injections : (∃ f : ℕ → ℕ, bijectivity f ∧ ¬ injectivity f) → false := ---ans begin intro Hf, cases Hf with f Hff, rw bijectivity at Hff, cases Hff with Hffis Hfffi, cases Hffis with Hffi Hffs, apply Hfffi, exact Hffi, end ------iv def setN : set ℕ := set.univ def powN := set.powerset setN theorem cantor : ¬ (∃ F : ℕ → set ℕ, bijectivity F) := ---ans begin intro HE_cantor, cases HE_cantor with F HE_cantor_F, let Snm : set ℕ := {n : ℕ | ¬ (n ∈ F n)}, rw bijectivity at HE_cantor_F, cases HE_cantor_F with HE_can_F HE_tor_F, rw surjectivity at HE_tor_F, rw injectivity at HE_can_F, have HE_tor_F_S := HE_tor_F Snm, cases HE_tor_F_S with x Hx_tor_F_S, cases classical.em (x ∈ Snm) with HxS HxnS, --case HxS have HnxS := HxS, change ¬ (x ∈ F x) at HnxS, rw Hx_tor_F_S at HnxS, apply HnxS, exact HxS, --case HxnS have HyxS := HxnS, change ¬ ¬ (x ∈ F x) at HyxS, rw Hx_tor_F_S at HyxS, apply HyxS, exact HxnS, end ----part c def G (f : X → Y) : set (X × Y) := { g | g.2 = f (g.1) } def p1 (g : G f) : X := g.1.1 def injectivity' {X' Y' : Type u} (g : X' → Y') := ∀ x1 x2 : X', g x1 = g x2 → x1 = x2 def surjectivity' {X' Y' : Type u} (g : X' → Y') := ∀ y : Y', ∃ x : X', g x = y def bijectivity' {X' Y' : Type u} (g : X' → Y') := injectivity' g ∧ surjectivity' g theorem bij_p1 : @bijectivity' (↥(G f)) X (p1) := ---ans begin split, intros x1 x2 Hpx, rw [p1, p1] at Hpx, cases x1, cases x2, cases x1_val, cases x2_val, change x1_val_snd = f(x1_val_fst) at x1_property, change x2_val_snd = f(x2_val_fst) at x2_property, simp, simp at Hpx, have Hpfx : x1_val_snd = x2_val_snd, rw [x1_property, x2_property, Hpx], split, rw Hpx, rw Hpfx, --split, intro x, let xy : (↥(G f)) := ⟨⟨x,f x⟩, rfl⟩, existsi xy, refl, end ----part d def p2 (g : G f) : Y := g.1.2 theorem bij_p2_f : @bijectivity' (↥(G f)) Y (p2) → bijectivity' f := ---ans begin intro Hp, cases Hp with Hpi Hps, rw injectivity' at Hpi, rw surjectivity' at Hps, split, intros a b Hfx, let afa : (↥(G f)) := ⟨⟨a,f a⟩, rfl⟩, let bfb : (↥(G f)) := ⟨⟨b,f b⟩, rfl⟩, have Hpab : p2 afa = p2 bfb, rw [p2, p2], simp, exact Hfx, have Hpiab := Hpi afa bfb Hpab, simp at Hpiab, cases Hpiab with Hab Hfab, exact Hab, --split, intro y, have Hpsy := Hps y, cases Hpsy with xy Hpxy, rw p2 at Hpxy, cases xy, cases xy_val, change xy_val_snd = y at Hpxy, change xy_val_snd = f xy_val_fst at xy_property, existsi xy_val_fst, rw [←xy_property, Hpxy], end
680da8e36d712d1e0edfa19a58ba8ab40bb6fb93
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/linear_algebra/matrix/nonsingular_inverse.lean
0d9c48d78bd74e256e34ee321b006509cc658a3b
[ "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
24,619
lean
/- Copyright (c) 2019 Tim Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tim Baanen, Lu-Ming Zhang -/ import algebra.regular.smul import linear_algebra.matrix.adjugate import linear_algebra.matrix.polynomial /-! # Nonsingular inverses In this file, we define an inverse for square matrices of invertible determinant. For matrices that are not square or not of full rank, there is a more general notion of pseudoinverses which we do not consider here. The definition of inverse used in this file is the adjugate divided by the determinant. We show that dividing the adjugate by `det A` (if possible), giving a matrix `A⁻¹` (`nonsing_inv`), will result in a multiplicative inverse to `A`. Note that there are at least three different inverses in mathlib: * `A⁻¹` (`has_inv.inv`): alone, this satisfies no properties, although it is usually used in conjunction with `group` or `group_with_zero`. On matrices, this is defined to be zero when no inverse exists. * `⅟A` (`inv_of`): this is only available in the presence of `[invertible A]`, which guarantees an inverse exists. * `ring.inverse A`: this is defined on any `monoid_with_zero`, and just like `⁻¹` on matrices, is defined to be zero when no inverse exists. We start by working with `invertible`, and show the main results: * `matrix.invertible_of_det_invertible` * `matrix.det_invertible_of_invertible` * `matrix.is_unit_iff_is_unit_det` * `matrix.mul_eq_one_comm` After this we define `matrix.has_inv` and show it matches `⅟A` and `ring.inverse A`. The rest of the results in the file are then about `A⁻¹` ## References * https://en.wikipedia.org/wiki/Cramer's_rule#Finding_inverse_matrix ## Tags matrix inverse, cramer, cramer's rule, adjugate -/ namespace matrix universes u u' v variables {m : Type u} {n : Type u'} {α : Type v} open_locale matrix big_operators open equiv equiv.perm finset /-! ### Matrices are `invertible` iff their determinants are -/ section invertible variables [fintype n] [decidable_eq n] [comm_ring α] /-- A copy of `inv_of_mul_self` using `⬝` not `*`. -/ protected lemma inv_of_mul_self (A : matrix n n α) [invertible A] : ⅟A ⬝ A = 1 := inv_of_mul_self A /-- A copy of `mul_inv_of_self` using `⬝` not `*`. -/ protected lemma mul_inv_of_self (A : matrix n n α) [invertible A] : A ⬝ ⅟A = 1 := mul_inv_of_self A /-- A copy of `inv_of_mul_self_assoc` using `⬝` not `*`. -/ protected lemma inv_of_mul_self_assoc (A : matrix n n α) (B : matrix n m α) [invertible A] : ⅟A ⬝ (A ⬝ B) = B := by rw [←matrix.mul_assoc, matrix.inv_of_mul_self, matrix.one_mul] /-- A copy of `mul_inv_of_self_assoc` using `⬝` not `*`. -/ protected lemma mul_inv_of_self_assoc (A : matrix n n α) (B : matrix n m α) [invertible A] : A ⬝ (⅟A ⬝ B) = B := by rw [←matrix.mul_assoc, matrix.mul_inv_of_self, matrix.one_mul] /-- A copy of `mul_inv_of_mul_self_cancel` using `⬝` not `*`. -/ protected lemma mul_inv_of_mul_self_cancel (A : matrix m n α) (B : matrix n n α) [invertible B] : A ⬝ ⅟B ⬝ B = A := by rw [matrix.mul_assoc, matrix.inv_of_mul_self, matrix.mul_one] /-- A copy of `mul_mul_inv_of_self_cancel` using `⬝` not `*`. -/ protected lemma mul_mul_inv_of_self_cancel (A : matrix m n α) (B : matrix n n α) [invertible B] : A ⬝ B ⬝ ⅟B = A := by rw [matrix.mul_assoc, matrix.mul_inv_of_self, matrix.mul_one] variables (A : matrix n n α) (B : matrix n n α) /-- If `A.det` has a constructive inverse, produce one for `A`. -/ def invertible_of_det_invertible [invertible A.det] : invertible A := { inv_of := ⅟A.det • A.adjugate, mul_inv_of_self := by rw [mul_smul_comm, matrix.mul_eq_mul, mul_adjugate, smul_smul, inv_of_mul_self, one_smul], inv_of_mul_self := by rw [smul_mul_assoc, matrix.mul_eq_mul, adjugate_mul, smul_smul, inv_of_mul_self, one_smul] } lemma inv_of_eq [invertible A.det] [invertible A] : ⅟A = ⅟A.det • A.adjugate := by { letI := invertible_of_det_invertible A, convert (rfl : ⅟A = _) } /-- `A.det` is invertible if `A` has a left inverse. -/ def det_invertible_of_left_inverse (h : B ⬝ A = 1) : invertible A.det := { inv_of := B.det, mul_inv_of_self := by rw [mul_comm, ← det_mul, h, det_one], inv_of_mul_self := by rw [← det_mul, h, det_one] } /-- `A.det` is invertible if `A` has a right inverse. -/ def det_invertible_of_right_inverse (h : A ⬝ B = 1) : invertible A.det := { inv_of := B.det, mul_inv_of_self := by rw [← det_mul, h, det_one], inv_of_mul_self := by rw [mul_comm, ← det_mul, h, det_one] } /-- If `A` has a constructive inverse, produce one for `A.det`. -/ def det_invertible_of_invertible [invertible A] : invertible A.det := det_invertible_of_left_inverse A (⅟A) (inv_of_mul_self _) lemma det_inv_of [invertible A] [invertible A.det] : (⅟A).det = ⅟A.det := by { letI := det_invertible_of_invertible A, convert (rfl : _ = ⅟A.det) } /-- Together `matrix.det_invertible_of_invertible` and `matrix.invertible_of_det_invertible` form an equivalence, although both sides of the equiv are subsingleton anyway. -/ @[simps] def invertible_equiv_det_invertible : invertible A ≃ invertible A.det := { to_fun := @det_invertible_of_invertible _ _ _ _ _ A, inv_fun := @invertible_of_det_invertible _ _ _ _ _ A, left_inv := λ _, subsingleton.elim _ _, right_inv := λ _, subsingleton.elim _ _ } variables {A B} lemma mul_eq_one_comm : A ⬝ B = 1 ↔ B ⬝ A = 1 := suffices ∀ A B, A ⬝ B = 1 → B ⬝ A = 1, from ⟨this A B, this B A⟩, assume A B h, begin letI : invertible B.det := det_invertible_of_left_inverse _ _ h, letI : invertible B := invertible_of_det_invertible B, calc B ⬝ A = (B ⬝ A) ⬝ (B ⬝ ⅟B) : by rw [matrix.mul_inv_of_self, matrix.mul_one] ... = B ⬝ ((A ⬝ B) ⬝ ⅟B) : by simp only [matrix.mul_assoc] ... = B ⬝ ⅟B : by rw [h, matrix.one_mul] ... = 1 : matrix.mul_inv_of_self B, end variables (A B) /-- We can construct an instance of invertible A if A has a left inverse. -/ def invertible_of_left_inverse (h : B ⬝ A = 1) : invertible A := ⟨B, h, mul_eq_one_comm.mp h⟩ /-- We can construct an instance of invertible A if A has a right inverse. -/ def invertible_of_right_inverse (h : A ⬝ B = 1) : invertible A := ⟨B, mul_eq_one_comm.mp h, h⟩ /-- Given a proof that `A.det` has a constructive inverse, lift `A` to `(matrix n n α)ˣ`-/ def unit_of_det_invertible [invertible A.det] : (matrix n n α)ˣ := @unit_of_invertible _ _ A (invertible_of_det_invertible A) /-- When lowered to a prop, `matrix.invertible_equiv_det_invertible` forms an `iff`. -/ lemma is_unit_iff_is_unit_det : is_unit A ↔ is_unit A.det := by simp only [← nonempty_invertible_iff_is_unit, (invertible_equiv_det_invertible A).nonempty_congr] /-! #### Variants of the statements above with `is_unit`-/ lemma is_unit_det_of_invertible [invertible A] : is_unit A.det := @is_unit_of_invertible _ _ _ (det_invertible_of_invertible A) variables {A B} lemma is_unit_det_of_left_inverse (h : B ⬝ A = 1) : is_unit A.det := @is_unit_of_invertible _ _ _ (det_invertible_of_left_inverse _ _ h) lemma is_unit_det_of_right_inverse (h : A ⬝ B = 1) : is_unit A.det := @is_unit_of_invertible _ _ _ (det_invertible_of_right_inverse _ _ h) lemma det_ne_zero_of_left_inverse [nontrivial α] (h : B ⬝ A = 1) : A.det ≠ 0 := (is_unit_det_of_left_inverse h).ne_zero lemma det_ne_zero_of_right_inverse [nontrivial α] (h : A ⬝ B = 1) : A.det ≠ 0 := (is_unit_det_of_right_inverse h).ne_zero end invertible variables [fintype n] [decidable_eq n] [comm_ring α] variables (A : matrix n n α) (B : matrix n n α) lemma is_unit_det_transpose (h : is_unit A.det) : is_unit Aᵀ.det := by { rw det_transpose, exact h, } /-! ### A noncomputable `has_inv` instance -/ /-- The inverse of a square matrix, when it is invertible (and zero otherwise).-/ noncomputable instance : has_inv (matrix n n α) := ⟨λ A, ring.inverse A.det • A.adjugate⟩ lemma inv_def (A : matrix n n α) : A⁻¹ = ring.inverse A.det • A.adjugate := rfl lemma nonsing_inv_apply_not_is_unit (h : ¬ is_unit A.det) : A⁻¹ = 0 := by rw [inv_def, ring.inverse_non_unit _ h, zero_smul] lemma nonsing_inv_apply (h : is_unit A.det) : A⁻¹ = (↑h.unit⁻¹ : α) • A.adjugate := by rw [inv_def, ←ring.inverse_unit h.unit, is_unit.unit_spec] /-- The nonsingular inverse is the same as `inv_of` when `A` is invertible. -/ @[simp] lemma inv_of_eq_nonsing_inv [invertible A] : ⅟A = A⁻¹ := begin letI := det_invertible_of_invertible A, rw [inv_def, ring.inverse_invertible, inv_of_eq], end /-- Coercing the result of `units.has_inv` is the same as coercing first and applying the nonsingular inverse. -/ @[simp, norm_cast] lemma coe_units_inv (A : (matrix n n α)ˣ) : ↑(A⁻¹) = (A⁻¹ : matrix n n α) := begin letI := A.invertible, rw [←inv_of_eq_nonsing_inv, inv_of_units], end /-- The nonsingular inverse is the same as the general `ring.inverse`. -/ lemma nonsing_inv_eq_ring_inverse : A⁻¹ = ring.inverse A := begin by_cases h_det : is_unit A.det, { casesI (A.is_unit_iff_is_unit_det.mpr h_det).nonempty_invertible, rw [←inv_of_eq_nonsing_inv, ring.inverse_invertible], }, { have h := mt A.is_unit_iff_is_unit_det.mp h_det, rw [ring.inverse_non_unit _ h, nonsing_inv_apply_not_is_unit A h_det], }, end lemma transpose_nonsing_inv : (A⁻¹)ᵀ = (Aᵀ)⁻¹ := by rw [inv_def, inv_def, transpose_smul, det_transpose, adjugate_transpose] lemma conj_transpose_nonsing_inv [star_ring α] : (A⁻¹)ᴴ = (Aᴴ)⁻¹ := by rw [inv_def, inv_def, conj_transpose_smul, det_conj_transpose, adjugate_conj_transpose, ring.inverse_star] /-- The `nonsing_inv` of `A` is a right inverse. -/ @[simp] lemma mul_nonsing_inv (h : is_unit A.det) : A ⬝ A⁻¹ = 1 := begin casesI (A.is_unit_iff_is_unit_det.mpr h).nonempty_invertible, rw [←inv_of_eq_nonsing_inv, matrix.mul_inv_of_self], end /-- The `nonsing_inv` of `A` is a left inverse. -/ @[simp] lemma nonsing_inv_mul (h : is_unit A.det) : A⁻¹ ⬝ A = 1 := begin casesI (A.is_unit_iff_is_unit_det.mpr h).nonempty_invertible, rw [←inv_of_eq_nonsing_inv, matrix.inv_of_mul_self], end @[simp] lemma mul_nonsing_inv_cancel_right (B : matrix m n α) (h : is_unit A.det) : B ⬝ A ⬝ A⁻¹ = B := by simp [matrix.mul_assoc, mul_nonsing_inv A h] @[simp] lemma mul_nonsing_inv_cancel_left (B : matrix n m α) (h : is_unit A.det) : A ⬝ (A⁻¹ ⬝ B) = B := by simp [←matrix.mul_assoc, mul_nonsing_inv A h] @[simp] lemma nonsing_inv_mul_cancel_right (B : matrix m n α) (h : is_unit A.det) : B ⬝ A⁻¹ ⬝ A = B := by simp [matrix.mul_assoc, nonsing_inv_mul A h] @[simp] lemma nonsing_inv_mul_cancel_left (B : matrix n m α) (h : is_unit A.det) : A⁻¹ ⬝ (A ⬝ B) = B := by simp [←matrix.mul_assoc, nonsing_inv_mul A h] @[simp] lemma mul_inv_of_invertible [invertible A] : A ⬝ A⁻¹ = 1 := mul_nonsing_inv A (is_unit_det_of_invertible A) @[simp] lemma inv_mul_of_invertible [invertible A] : A⁻¹ ⬝ A = 1 := nonsing_inv_mul A (is_unit_det_of_invertible A) @[simp] lemma mul_inv_cancel_right_of_invertible (B : matrix m n α) [invertible A] : B ⬝ A ⬝ A⁻¹ = B := mul_nonsing_inv_cancel_right A B (is_unit_det_of_invertible A) @[simp] lemma mul_inv_cancel_left_of_invertible (B : matrix n m α) [invertible A] : A ⬝ (A⁻¹ ⬝ B) = B := mul_nonsing_inv_cancel_left A B (is_unit_det_of_invertible A) @[simp] lemma inv_mul_cancel_right_of_invertible (B : matrix m n α) [invertible A] : B ⬝ A⁻¹ ⬝ A = B := nonsing_inv_mul_cancel_right A B (is_unit_det_of_invertible A) @[simp] lemma inv_mul_cancel_left_of_invertible (B : matrix n m α) [invertible A] : A⁻¹ ⬝ (A ⬝ B) = B := nonsing_inv_mul_cancel_left A B (is_unit_det_of_invertible A) lemma nonsing_inv_cancel_or_zero : (A⁻¹ ⬝ A = 1 ∧ A ⬝ A⁻¹ = 1) ∨ A⁻¹ = 0 := begin by_cases h : is_unit A.det, { exact or.inl ⟨nonsing_inv_mul _ h, mul_nonsing_inv _ h⟩ }, { exact or.inr (nonsing_inv_apply_not_is_unit _ h) } end lemma det_nonsing_inv_mul_det (h : is_unit A.det) : A⁻¹.det * A.det = 1 := by rw [←det_mul, A.nonsing_inv_mul h, det_one] @[simp] lemma det_nonsing_inv : A⁻¹.det = ring.inverse A.det := begin by_cases h : is_unit A.det, { casesI h.nonempty_invertible, letI := invertible_of_det_invertible A, rw [ring.inverse_invertible, ←inv_of_eq_nonsing_inv, det_inv_of] }, casesI is_empty_or_nonempty n, { rw [det_is_empty, det_is_empty, ring.inverse_one] }, { rw [ring.inverse_non_unit _ h, nonsing_inv_apply_not_is_unit _ h, det_zero ‹_›] }, end lemma is_unit_nonsing_inv_det (h : is_unit A.det) : is_unit A⁻¹.det := is_unit_of_mul_eq_one _ _ (A.det_nonsing_inv_mul_det h) @[simp] lemma nonsing_inv_nonsing_inv (h : is_unit A.det) : (A⁻¹)⁻¹ = A := calc (A⁻¹)⁻¹ = 1 ⬝ (A⁻¹)⁻¹ : by rw matrix.one_mul ... = A ⬝ A⁻¹ ⬝ (A⁻¹)⁻¹ : by rw A.mul_nonsing_inv h ... = A : by { rw [matrix.mul_assoc, (A⁻¹).mul_nonsing_inv (A.is_unit_nonsing_inv_det h), matrix.mul_one], } lemma is_unit_nonsing_inv_det_iff {A : matrix n n α} : is_unit A⁻¹.det ↔ is_unit A.det := by rw [matrix.det_nonsing_inv, is_unit_ring_inverse] /- `is_unit.invertible` lifts the proposition `is_unit A` to a constructive inverse of `A`. -/ /-- A version of `matrix.invertible_of_det_invertible` with the inverse defeq to `A⁻¹` that is therefore noncomputable. -/ noncomputable def invertible_of_is_unit_det (h : is_unit A.det) : invertible A := ⟨A⁻¹, nonsing_inv_mul A h, mul_nonsing_inv A h⟩ /-- A version of `matrix.units_of_det_invertible` with the inverse defeq to `A⁻¹` that is therefore noncomputable. -/ noncomputable def nonsing_inv_unit (h : is_unit A.det) : (matrix n n α)ˣ := @unit_of_invertible _ _ _ (invertible_of_is_unit_det A h) lemma unit_of_det_invertible_eq_nonsing_inv_unit [invertible A.det] : unit_of_det_invertible A = nonsing_inv_unit A (is_unit_of_invertible _) := by { ext, refl } variables {A} {B} /-- If matrix A is left invertible, then its inverse equals its left inverse. -/ lemma inv_eq_left_inv (h : B ⬝ A = 1) : A⁻¹ = B := begin letI := invertible_of_left_inverse _ _ h, exact inv_of_eq_nonsing_inv A ▸ inv_of_eq_left_inv h, end /-- If matrix A is right invertible, then its inverse equals its right inverse. -/ lemma inv_eq_right_inv (h : A ⬝ B = 1) : A⁻¹ = B := inv_eq_left_inv (mul_eq_one_comm.2 h) section inv_eq_inv variables {C : matrix n n α} /-- The left inverse of matrix A is unique when existing. -/ lemma left_inv_eq_left_inv (h : B ⬝ A = 1) (g : C ⬝ A = 1) : B = C := by rw [←inv_eq_left_inv h, ←inv_eq_left_inv g] /-- The right inverse of matrix A is unique when existing. -/ lemma right_inv_eq_right_inv (h : A ⬝ B = 1) (g : A ⬝ C = 1) : B = C := by rw [←inv_eq_right_inv h, ←inv_eq_right_inv g] /-- The right inverse of matrix A equals the left inverse of A when they exist. -/ lemma right_inv_eq_left_inv (h : A ⬝ B = 1) (g : C ⬝ A = 1) : B = C := by rw [←inv_eq_right_inv h, ←inv_eq_left_inv g] lemma inv_inj (h : A⁻¹ = B⁻¹) (h' : is_unit A.det) : A = B := begin refine left_inv_eq_left_inv (mul_nonsing_inv _ h') _, rw h, refine mul_nonsing_inv _ _, rwa [←is_unit_nonsing_inv_det_iff, ←h, is_unit_nonsing_inv_det_iff] end end inv_eq_inv variable (A) @[simp] lemma inv_zero : (0 : matrix n n α)⁻¹ = 0 := begin casesI (subsingleton_or_nontrivial α) with ht ht, { simp }, cases (fintype.card n).zero_le.eq_or_lt with hc hc, { rw [eq_comm, fintype.card_eq_zero_iff] at hc, haveI := hc, ext i, exact (is_empty.false i).elim }, { have hn : nonempty n := fintype.card_pos_iff.mp hc, refine nonsing_inv_apply_not_is_unit _ _, simp [hn] }, end @[simp] lemma inv_one : (1 : matrix n n α)⁻¹ = 1 := inv_eq_left_inv (by simp) lemma inv_smul (k : α) [invertible k] (h : is_unit A.det) : (k • A)⁻¹ = ⅟k • A⁻¹ := inv_eq_left_inv (by simp [h, smul_smul]) lemma inv_smul' (k : αˣ) (h : is_unit A.det) : (k • A)⁻¹ = k⁻¹ • A⁻¹ := inv_eq_left_inv (by simp [h, smul_smul]) lemma inv_adjugate (A : matrix n n α) (h : is_unit A.det) : (adjugate A)⁻¹ = h.unit⁻¹ • A := begin refine inv_eq_left_inv _, rw [smul_mul, mul_adjugate, units.smul_def, smul_smul, h.coe_inv_mul, one_smul] end /-- `diagonal v` is invertible if `v` is -/ def diagonal_invertible {α} [non_assoc_semiring α] (v : n → α) [invertible v] : invertible (diagonal v) := invertible.map (diagonal_ring_hom n α) v lemma inv_of_diagonal_eq {α} [semiring α] (v : n → α) [invertible v] [invertible (diagonal v)] : ⅟(diagonal v) = diagonal (⅟v) := by { letI := diagonal_invertible v, convert (rfl : ⅟(diagonal v) = _), convert subsingleton.elim _ _, apply invertible.subsingleton } /-- `v` is invertible if `diagonal v` is -/ def invertible_of_diagonal_invertible (v : n → α) [invertible (diagonal v)] : invertible v := { inv_of := diag (⅟(diagonal v)), inv_of_mul_self := funext $ λ i, begin letI : invertible (diagonal v).det := det_invertible_of_invertible _, rw [inv_of_eq, diag_smul, adjugate_diagonal, diag_diagonal], dsimp, rw [mul_assoc, prod_erase_mul _ _ (finset.mem_univ _), ←det_diagonal], exact mul_inv_of_self _, end, mul_inv_of_self := funext $ λ i, begin letI : invertible (diagonal v).det := det_invertible_of_invertible _, rw [inv_of_eq, diag_smul, adjugate_diagonal, diag_diagonal], dsimp, rw [mul_left_comm, mul_prod_erase _ _ (finset.mem_univ _), ←det_diagonal], exact mul_inv_of_self _, end } /-- Together `matrix.diagonal_invertible` and `matrix.invertible_of_diagonal_invertible` form an equivalence, although both sides of the equiv are subsingleton anyway. -/ @[simps] def diagonal_invertible_equiv_invertible (v : n → α) : invertible (diagonal v) ≃ invertible v := { to_fun := @invertible_of_diagonal_invertible _ _ _ _ _ _, inv_fun := @diagonal_invertible _ _ _ _ _ _, left_inv := λ _, subsingleton.elim _ _, right_inv := λ _, subsingleton.elim _ _ } /-- When lowered to a prop, `matrix.diagonal_invertible_equiv_invertible` forms an `iff`. -/ @[simp] lemma is_unit_diagonal {v : n → α} : is_unit (diagonal v) ↔ is_unit v := by simp only [← nonempty_invertible_iff_is_unit, (diagonal_invertible_equiv_invertible v).nonempty_congr] lemma inv_diagonal (v : n → α) : (diagonal v)⁻¹ = diagonal (ring.inverse v) := begin rw nonsing_inv_eq_ring_inverse, by_cases h : is_unit v, { have := is_unit_diagonal.mpr h, casesI this.nonempty_invertible, casesI h.nonempty_invertible, rw [ring.inverse_invertible, ring.inverse_invertible, inv_of_diagonal_eq], }, { have := is_unit_diagonal.not.mpr h, rw [ring.inverse_non_unit _ h, pi.zero_def, diagonal_zero, ring.inverse_non_unit _ this] } end @[simp] lemma inv_inv_inv (A : matrix n n α) : A⁻¹⁻¹⁻¹ = A⁻¹ := begin by_cases h : is_unit A.det, { rw [nonsing_inv_nonsing_inv _ h] }, { simp [nonsing_inv_apply_not_is_unit _ h] } end lemma mul_inv_rev (A B : matrix n n α) : (A ⬝ B)⁻¹ = B⁻¹ ⬝ A⁻¹ := begin simp only [inv_def], rw [matrix.smul_mul, matrix.mul_smul, smul_smul, det_mul, adjugate_mul_distrib, ring.mul_inverse_rev], end /-- A version of `list.prod_inv_reverse` for `matrix.has_inv`. -/ lemma list_prod_inv_reverse : ∀ l : list (matrix n n α), l.prod⁻¹ = (l.reverse.map has_inv.inv).prod | [] := by rw [list.reverse_nil, list.map_nil, list.prod_nil, inv_one] | (A :: Xs) := by rw [list.reverse_cons', list.map_concat, list.prod_concat, list.prod_cons, matrix.mul_eq_mul, matrix.mul_eq_mul, mul_inv_rev, list_prod_inv_reverse] /-- One form of **Cramer's rule**. See `matrix.mul_vec_cramer` for a stronger form. -/ @[simp] lemma det_smul_inv_mul_vec_eq_cramer (A : matrix n n α) (b : n → α) (h : is_unit A.det) : A.det • A⁻¹.mul_vec b = cramer A b := begin rw [cramer_eq_adjugate_mul_vec, A.nonsing_inv_apply h, ← smul_mul_vec_assoc, smul_smul, h.mul_coe_inv, one_smul] end /-- One form of **Cramer's rule**. See `matrix.mul_vec_cramer` for a stronger form. -/ @[simp] lemma det_smul_inv_vec_mul_eq_cramer_transpose (A : matrix n n α) (b : n → α) (h : is_unit A.det) : A.det • A⁻¹.vec_mul b = cramer Aᵀ b := by rw [← (A⁻¹).transpose_transpose, vec_mul_transpose, transpose_nonsing_inv, ← det_transpose, Aᵀ.det_smul_inv_mul_vec_eq_cramer _ (is_unit_det_transpose A h)] /-! ### More results about determinants -/ section det variables [fintype m] [decidable_eq m] /-- A variant of `matrix.det_units_conj`. -/ lemma det_conj {M : matrix m m α} (h : is_unit M) (N : matrix m m α) : det (M ⬝ N ⬝ M⁻¹) = det N := by rw [←h.unit_spec, ←coe_units_inv, det_units_conj] /-- A variant of `matrix.det_units_conj'`. -/ lemma det_conj' {M : matrix m m α} (h : is_unit M) (N : matrix m m α) : det (M⁻¹ ⬝ N ⬝ M) = det N := by rw [←h.unit_spec, ←coe_units_inv, det_units_conj'] /-- Determinant of a 2×2 block matrix, expanded around an invertible top left element in terms of the Schur complement. -/ lemma det_from_blocks₁₁ (A : matrix m m α) (B : matrix m n α) (C : matrix n m α) (D : matrix n n α) [invertible A] : (matrix.from_blocks A B C D).det = det A * det (D - C ⬝ (⅟A) ⬝ B) := begin have : from_blocks A B C D = from_blocks 1 0 (C ⬝ ⅟A) 1 ⬝ from_blocks A 0 0 (D - C ⬝ (⅟A) ⬝ B) ⬝ from_blocks 1 (⅟A ⬝ B) 0 1, { simp only [from_blocks_multiply, matrix.mul_zero, matrix.zero_mul, add_zero, zero_add, matrix.one_mul, matrix.mul_one, matrix.inv_of_mul_self, matrix.mul_inv_of_self_assoc, matrix.mul_inv_of_mul_self_cancel, matrix.mul_assoc, add_sub_cancel'_right] }, rw [this, det_mul, det_mul, det_from_blocks_zero₂₁, det_from_blocks_zero₂₁, det_from_blocks_zero₁₂, det_one, det_one, one_mul, one_mul, mul_one], end @[simp] lemma det_from_blocks_one₁₁ (B : matrix m n α) (C : matrix n m α) (D : matrix n n α) : (matrix.from_blocks 1 B C D).det = det (D - C ⬝ B) := begin haveI : invertible (1 : matrix m m α) := invertible_one, rw [det_from_blocks₁₁, inv_of_one, matrix.mul_one, det_one, one_mul], end /-- Determinant of a 2×2 block matrix, expanded around an invertible bottom right element in terms of the Schur complement. -/ lemma det_from_blocks₂₂ (A : matrix m m α) (B : matrix m n α) (C : matrix n m α) (D : matrix n n α) [invertible D] : (matrix.from_blocks A B C D).det = det D * det (A - B ⬝ (⅟D) ⬝ C) := begin have : from_blocks A B C D = (from_blocks D C B A).submatrix (sum_comm _ _) (sum_comm _ _), { ext i j, cases i; cases j; refl }, rw [this, det_submatrix_equiv_self, det_from_blocks₁₁], end @[simp] lemma det_from_blocks_one₂₂ (A : matrix m m α) (B : matrix m n α) (C : matrix n m α) : (matrix.from_blocks A B C 1).det = det (A - B ⬝ C) := begin haveI : invertible (1 : matrix n n α) := invertible_one, rw [det_from_blocks₂₂, inv_of_one, matrix.mul_one, det_one, one_mul], end /-- The **Weinstein–Aronszajn identity**. Note the `1` on the LHS is of shape m×m, while the `1` on the RHS is of shape n×n. -/ lemma det_one_add_mul_comm (A : matrix m n α) (B : matrix n m α) : det (1 + A ⬝ B) = det (1 + B ⬝ A) := calc det (1 + A ⬝ B) = det (from_blocks 1 (-A) B 1) : by rw [det_from_blocks_one₂₂, matrix.neg_mul, sub_neg_eq_add] ... = det (1 + B ⬝ A) : by rw [det_from_blocks_one₁₁, matrix.mul_neg, sub_neg_eq_add] /-- Alternate statement of the **Weinstein–Aronszajn identity** -/ lemma det_mul_add_one_comm (A : matrix m n α) (B : matrix n m α) : det (A ⬝ B + 1) = det (B ⬝ A + 1) := by rw [add_comm, det_one_add_mul_comm, add_comm] lemma det_one_sub_mul_comm (A : matrix m n α) (B : matrix n m α) : det (1 - A ⬝ B) = det (1 - B ⬝ A) := by rw [sub_eq_add_neg, ←matrix.neg_mul, det_one_add_mul_comm, matrix.mul_neg, ←sub_eq_add_neg] /-- A special case of the **Matrix determinant lemma** for when `A = I`. TODO: show this more generally. -/ lemma det_one_add_col_mul_row (u v : m → α) : det (1 + col u ⬝ row v) = 1 + v ⬝ᵥ u := by rw [det_one_add_mul_comm, det_unique, pi.add_apply, pi.add_apply, matrix.one_apply_eq, matrix.row_mul_col_apply] end det end matrix