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
36b49f068d44c2596d0a7a767d8647083bdd5596
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/simp_out_param.lean
db206782a6bdb18afc3b50d0404304ec6cc36b40
[ "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
694
lean
prelude import init.meta.interactive namespace unbundled class broken₁ (A : Type*) := (f : A → A) open broken₁ class broken₂ (A : Type*) (a : out_param $ A) [broken₁ A] := (f_eq : ∀ x, f x = a) open broken₂ -- Even if the goal doesn't contain an instance of `broken₂`, the parameter `a` -- to `f_eq` should still be inferrable since it's an `out_param`. example (A : Type*) (a : A) [broken₁ A] [broken₂ A a] (x : A) : f x = a := by rewrite [f_eq] example (A : Type*) (a : A) [broken₁ A] [broken₂ A a] (x : A) : f x = a := by simp only [f_eq] -- Previous error: "simplify tactic failed to simplify", `f_eq` failed because "fail to instantiate emetas" end unbundled
76eeed1f991ba42c5ea03c741d683123fd26fa93
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/281.lean
a32d9e29c7fce6b18e7f170e61eed034cd637052
[ "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
280
lean
inductive V (α : Bool → Type) : Bool → Type | mk₁ {b} : α true → V α b | mk₂ : V α false → V α false def V.map {α β} (f : (b : Bool) → α b → β b) : {b : Bool} → V α b → V β b | _, mk₁ x => mk₁ (f true x) | _, mk₂ e => mk₂ (e.map f)
5adf61b42f185f3cc6b5da769b220df073f37084
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/ring_theory/euclidean_domain.lean
9e2ce9664e80dd31db0829cff7daf960ff160198
[ "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
2,531
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Chris Hughes -/ import ring_theory.coprime import ring_theory.ideal.basic /-! # Lemmas about Euclidean domains Various about Euclidean domains are proved; all of them seem to be true more generally for principal ideal domains, so these lemmas should probably be reproved in more generality and this file perhaps removed? ## Tags euclidean domain -/ noncomputable theory open_locale classical open euclidean_domain set ideal -- TODO -- this should surely be proved for PIDs instead? theorem span_gcd {α} [euclidean_domain α] (x y : α) : span ({gcd x y} : set α) = span ({x, y} : set α) := begin apply le_antisymm, { refine span_le.2 (λ x, _), simp only [set.mem_singleton_iff, set_like.mem_coe, mem_span_pair], rintro rfl, exact ⟨gcd_a x y, gcd_b x y, by simp [gcd_eq_gcd_ab, mul_comm]⟩ }, { assume z , simp [mem_span_singleton, euclidean_domain.gcd_dvd_left, mem_span_pair, @eq_comm _ _ z] {contextual := tt}, exact λ a b _, dvd_add ((gcd_dvd_left x y).mul_left _) ((gcd_dvd_right x y).mul_left _) } end -- this should be proved for PIDs? theorem gcd_is_unit_iff {α} [euclidean_domain α] {x y : α} : is_unit (gcd x y) ↔ is_coprime x y := ⟨λ h, let ⟨b, hb⟩ := is_unit_iff_exists_inv'.1 h in ⟨b * gcd_a x y, b * gcd_b x y, by rw [← hb, gcd_eq_gcd_ab, mul_comm x, mul_comm y, mul_add, mul_assoc, mul_assoc]⟩, λ ⟨a, b, h⟩, is_unit_iff_dvd_one.2 $ h ▸ dvd_add ((gcd_dvd_left x y).mul_left _) ((gcd_dvd_right x y).mul_left _)⟩ -- this should be proved for UFDs surely? theorem is_coprime_of_dvd {α} [euclidean_domain α] {x y : α} (z : ¬ (x = 0 ∧ y = 0)) (H : ∀ z ∈ nonunits α, z ≠ 0 → z ∣ x → ¬ z ∣ y) : is_coprime x y := begin rw [← gcd_is_unit_iff], by_contra h, refine H _ h _ (gcd_dvd_left _ _) (gcd_dvd_right _ _), rwa [ne, euclidean_domain.gcd_eq_zero_iff] end -- this should be proved for UFDs surely? theorem dvd_or_coprime {α} [euclidean_domain α] (x y : α) (h : irreducible x) : x ∣ y ∨ is_coprime x y := begin refine or_iff_not_imp_left.2 (λ h', _), apply is_coprime_of_dvd, { unfreezingI { rintro ⟨rfl, rfl⟩ }, simpa using h }, { unfreezingI { rintro z nu nz ⟨w, rfl⟩ dy }, refine h' (dvd_trans _ dy), simpa using mul_dvd_mul_left z (is_unit_iff_dvd_one.1 $ (of_irreducible_mul h).resolve_left nu) } end
144bfdbe6d040ee590ba192c574b6eec4f0a6e00
fecda8e6b848337561d6467a1e30cf23176d6ad0
/src/order/bounded_lattice.lean
77e17849ca321015ebf7fed516e1acaaccee2d42
[ "Apache-2.0" ]
permissive
spolu/mathlib
bacf18c3d2a561d00ecdc9413187729dd1f705ed
480c92cdfe1cf3c2d083abded87e82162e8814f4
refs/heads/master
1,671,684,094,325
1,600,736,045,000
1,600,736,045,000
297,564,749
1
0
null
1,600,758,368,000
1,600,758,367,000
null
UTF-8
Lean
false
false
39,806
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 Defines bounded lattice type class hierarchy. Includes the Prop and fun instances. -/ import order.lattice import data.option.basic import tactic.pi_instances set_option old_structure_cmd true universes u v variables {α : Type u} {β : Type v} /-- Typeclass for the `⊤` (`\top`) notation -/ class has_top (α : Type u) := (top : α) /-- Typeclass for the `⊥` (`\bot`) notation -/ class has_bot (α : Type u) := (bot : α) notation `⊤` := has_top.top notation `⊥` := has_bot.bot attribute [pattern] has_bot.bot has_top.top /-- An `order_top` is a partial order with a maximal element. (We could state this on preorders, but then it wouldn't be unique so distinguishing one would seem odd.) -/ class order_top (α : Type u) extends has_top α, partial_order α := (le_top : ∀ a : α, a ≤ ⊤) section order_top variables [order_top α] {a b : α} @[simp] theorem le_top : a ≤ ⊤ := order_top.le_top a theorem top_unique (h : ⊤ ≤ a) : a = ⊤ := le_antisymm le_top h -- TODO: delete in favor of the next? theorem eq_top_iff : a = ⊤ ↔ ⊤ ≤ a := ⟨assume eq, eq.symm ▸ le_refl ⊤, top_unique⟩ @[simp] theorem top_le_iff : ⊤ ≤ a ↔ a = ⊤ := ⟨top_unique, λ h, h.symm ▸ le_refl ⊤⟩ @[simp] theorem not_top_lt : ¬ ⊤ < a := assume h, lt_irrefl a (lt_of_le_of_lt le_top h) theorem eq_top_mono (h : a ≤ b) (h₂ : a = ⊤) : b = ⊤ := top_le_iff.1 $ h₂ ▸ h lemma lt_top_iff_ne_top : a < ⊤ ↔ a ≠ ⊤ := begin haveI := classical.dec_eq α, haveI : decidable (⊤ ≤ a) := decidable_of_iff' _ top_le_iff, by simp [-top_le_iff, lt_iff_le_not_le, not_iff_not.2 (@top_le_iff _ _ a)] end lemma ne_top_of_lt (h : a < b) : a ≠ ⊤ := lt_top_iff_ne_top.1 $ lt_of_lt_of_le h le_top theorem ne_top_of_le_ne_top {a b : α} (hb : b ≠ ⊤) (hab : a ≤ b) : a ≠ ⊤ := assume ha, hb $ top_unique $ ha ▸ hab end order_top lemma strict_mono.top_preimage_top' [linear_order α] [order_top β] {f : α → β} (H : strict_mono f) {a} (h_top : f a = ⊤) (x : α) : x ≤ a := H.top_preimage_top (λ p, by { rw h_top, exact le_top }) x theorem order_top.ext_top {α} {A B : order_top α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : (by haveI := A; exact ⊤ : α) = ⊤ := top_unique $ by rw ← H; apply le_top theorem order_top.ext {α} {A B : order_top α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have := partial_order.ext H, have tt := order_top.ext_top H, casesI A, casesI B, injection this; congr' end /-- An `order_bot` is a partial order with a minimal element. (We could state this on preorders, but then it wouldn't be unique so distinguishing one would seem odd.) -/ class order_bot (α : Type u) extends has_bot α, partial_order α := (bot_le : ∀ a : α, ⊥ ≤ a) section order_bot variables [order_bot α] {a b : α} @[simp] theorem bot_le : ⊥ ≤ a := order_bot.bot_le a theorem bot_unique (h : a ≤ ⊥) : a = ⊥ := le_antisymm h bot_le -- TODO: delete? theorem eq_bot_iff : a = ⊥ ↔ a ≤ ⊥ := ⟨assume eq, eq.symm ▸ le_refl ⊥, bot_unique⟩ @[simp] theorem le_bot_iff : a ≤ ⊥ ↔ a = ⊥ := ⟨bot_unique, assume h, h.symm ▸ le_refl ⊥⟩ @[simp] theorem not_lt_bot : ¬ a < ⊥ := assume h, lt_irrefl a (lt_of_lt_of_le h bot_le) theorem ne_bot_of_le_ne_bot {a b : α} (hb : b ≠ ⊥) (hab : b ≤ a) : a ≠ ⊥ := assume ha, hb $ bot_unique $ ha ▸ hab theorem eq_bot_mono (h : a ≤ b) (h₂ : b = ⊥) : a = ⊥ := le_bot_iff.1 $ h₂ ▸ h lemma bot_lt_iff_ne_bot : ⊥ < a ↔ a ≠ ⊥ := begin haveI := classical.dec_eq α, haveI : decidable (a ≤ ⊥) := decidable_of_iff' _ le_bot_iff, simp [-le_bot_iff, lt_iff_le_not_le, not_iff_not.2 (@le_bot_iff _ _ a)] end lemma ne_bot_of_gt (h : a < b) : b ≠ ⊥ := bot_lt_iff_ne_bot.1 $ lt_of_le_of_lt bot_le h end order_bot lemma strict_mono.bot_preimage_bot' [linear_order α] [order_bot β] {f : α → β} (H : strict_mono f) {a} (h_bot : f a = ⊥) (x : α) : a ≤ x := H.bot_preimage_bot (λ p, by { rw h_bot, exact bot_le }) x theorem order_bot.ext_bot {α} {A B : order_bot α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : (by haveI := A; exact ⊥ : α) = ⊥ := bot_unique $ by rw ← H; apply bot_le theorem order_bot.ext {α} {A B : order_bot α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have := partial_order.ext H, have tt := order_bot.ext_bot H, casesI A, casesI B, injection this; congr' end /-- A `semilattice_sup_top` is a semilattice with top and join. -/ class semilattice_sup_top (α : Type u) extends order_top α, semilattice_sup α section semilattice_sup_top variables [semilattice_sup_top α] {a : α} @[simp] theorem top_sup_eq : ⊤ ⊔ a = ⊤ := sup_of_le_left le_top @[simp] theorem sup_top_eq : a ⊔ ⊤ = ⊤ := sup_of_le_right le_top end semilattice_sup_top /-- A `semilattice_sup_bot` is a semilattice with bottom and join. -/ class semilattice_sup_bot (α : Type u) extends order_bot α, semilattice_sup α section semilattice_sup_bot variables [semilattice_sup_bot α] {a b : α} @[simp] theorem bot_sup_eq : ⊥ ⊔ a = a := sup_of_le_right bot_le @[simp] theorem sup_bot_eq : a ⊔ ⊥ = a := sup_of_le_left bot_le @[simp] theorem sup_eq_bot_iff : a ⊔ b = ⊥ ↔ (a = ⊥ ∧ b = ⊥) := by rw [eq_bot_iff, sup_le_iff]; simp end semilattice_sup_bot instance nat.semilattice_sup_bot : semilattice_sup_bot ℕ := { bot := 0, bot_le := nat.zero_le, .. nat.distrib_lattice } /-- A `semilattice_inf_top` is a semilattice with top and meet. -/ class semilattice_inf_top (α : Type u) extends order_top α, semilattice_inf α section semilattice_inf_top variables [semilattice_inf_top α] {a b : α} @[simp] theorem top_inf_eq : ⊤ ⊓ a = a := inf_of_le_right le_top @[simp] theorem inf_top_eq : a ⊓ ⊤ = a := inf_of_le_left le_top @[simp] theorem inf_eq_top_iff : a ⊓ b = ⊤ ↔ (a = ⊤ ∧ b = ⊤) := by rw [eq_top_iff, le_inf_iff]; simp end semilattice_inf_top /-- A `semilattice_inf_bot` is a semilattice with bottom and meet. -/ class semilattice_inf_bot (α : Type u) extends order_bot α, semilattice_inf α section semilattice_inf_bot variables [semilattice_inf_bot α] {a : α} @[simp] theorem bot_inf_eq : ⊥ ⊓ a = ⊥ := inf_of_le_left bot_le @[simp] theorem inf_bot_eq : a ⊓ ⊥ = ⊥ := inf_of_le_right bot_le end semilattice_inf_bot /- Bounded lattices -/ /-- A bounded lattice is a lattice with a top and bottom element, denoted `⊤` and `⊥` respectively. This allows for the interpretation of all finite suprema and infima, taking `inf ∅ = ⊤` and `sup ∅ = ⊥`. -/ class bounded_lattice (α : Type u) extends lattice α, order_top α, order_bot α @[priority 100] -- see Note [lower instance priority] instance semilattice_inf_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_inf_top α := { le_top := assume x, @le_top α _ x, ..bl } @[priority 100] -- see Note [lower instance priority] instance semilattice_inf_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_inf_bot α := { bot_le := assume x, @bot_le α _ x, ..bl } @[priority 100] -- see Note [lower instance priority] instance semilattice_sup_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_sup_top α := { le_top := assume x, @le_top α _ x, ..bl } @[priority 100] -- see Note [lower instance priority] instance semilattice_sup_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_sup_bot α := { bot_le := assume x, @bot_le α _ x, ..bl } theorem bounded_lattice.ext {α} {A B : bounded_lattice α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have H1 : @bounded_lattice.to_lattice α A = @bounded_lattice.to_lattice α B := lattice.ext H, have H2 := order_bot.ext H, have H3 : @bounded_lattice.to_order_top α A = @bounded_lattice.to_order_top α B := order_top.ext H, have tt := order_bot.ext_bot H, casesI A, casesI B, injection H1; injection H2; injection H3; congr' end /-- A bounded distributive lattice is exactly what it sounds like. -/ class bounded_distrib_lattice α extends distrib_lattice α, bounded_lattice α lemma inf_eq_bot_iff_le_compl {α : Type u} [bounded_distrib_lattice α] {a b c : α} (h₁ : b ⊔ c = ⊤) (h₂ : b ⊓ c = ⊥) : a ⊓ b = ⊥ ↔ a ≤ c := ⟨assume : a ⊓ b = ⊥, calc a ≤ a ⊓ (b ⊔ c) : by simp [h₁] ... = (a ⊓ b) ⊔ (a ⊓ c) : by simp [inf_sup_left] ... ≤ c : by simp [this, inf_le_right], assume : a ≤ c, bot_unique $ calc a ⊓ b ≤ b ⊓ c : by { rw [inf_comm], exact inf_le_inf_left _ this } ... = ⊥ : h₂⟩ /- Prop instance -/ instance bounded_distrib_lattice_Prop : bounded_distrib_lattice Prop := { le := λa b, a → b, le_refl := assume _, id, le_trans := assume a b c f g, g ∘ f, le_antisymm := assume a b Hab Hba, propext ⟨Hab, Hba⟩, sup := or, le_sup_left := @or.inl, le_sup_right := @or.inr, sup_le := assume a b c, or.rec, inf := and, inf_le_left := @and.left, inf_le_right := @and.right, le_inf := assume a b c Hab Hac Ha, and.intro (Hab Ha) (Hac Ha), le_sup_inf := assume a b c H, or_iff_not_imp_left.2 $ λ Ha, ⟨H.1.resolve_left Ha, H.2.resolve_left Ha⟩, top := true, le_top := assume a Ha, true.intro, bot := false, bot_le := @false.elim } instance Prop.linear_order : linear_order Prop := { le_total := by intros p q; change (p → q) ∨ (q → p); tauto!, .. (_ : partial_order Prop) } @[simp] lemma le_iff_imp {p q : Prop} : p ≤ q ↔ (p → q) := iff.rfl section logic variable [preorder α] theorem monotone_and {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) : monotone (λx, p x ∧ q x) := assume a b h, and.imp (m_p h) (m_q h) -- Note: by finish [monotone] doesn't work theorem monotone_or {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) : monotone (λx, p x ∨ q x) := assume a b h, or.imp (m_p h) (m_q h) end logic instance pi.order_bot {α : Type*} {β : α → Type*} [∀ a, order_bot $ β a] : order_bot (Π a, β a) := { bot := λ _, ⊥, bot_le := λ x a, bot_le, .. pi.partial_order } /- Function lattices -/ instance pi.has_sup {ι : Type*} {α : ι → Type*} [Π i, has_sup (α i)] : has_sup (Π i, α i) := ⟨λ f g i, f i ⊔ g i⟩ @[simp] lemma sup_apply {ι : Type*} {α : ι → Type*} [Π i, has_sup (α i)] (f g : Π i, α i) (i : ι) : (f ⊔ g) i = f i ⊔ g i := rfl instance pi.has_inf {ι : Type*} {α : ι → Type*} [Π i, has_inf (α i)] : has_inf (Π i, α i) := ⟨λ f g i, f i ⊓ g i⟩ @[simp] lemma inf_apply {ι : Type*} {α : ι → Type*} [Π i, has_inf (α i)] (f g : Π i, α i) (i : ι) : (f ⊓ g) i = f i ⊓ g i := rfl instance pi.has_bot {ι : Type*} {α : ι → Type*} [Π i, has_bot (α i)] : has_bot (Π i, α i) := ⟨λ i, ⊥⟩ @[simp] lemma bot_apply {ι : Type*} {α : ι → Type*} [Π i, has_bot (α i)] (i : ι) : (⊥ : Π i, α i) i = ⊥ := rfl instance pi.has_top {ι : Type*} {α : ι → Type*} [Π i, has_top (α i)] : has_top (Π i, α i) := ⟨λ i, ⊤⟩ @[simp] lemma top_apply {ι : Type*} {α : ι → Type*} [Π i, has_top (α i)] (i : ι) : (⊤ : Π i, α i) i = ⊤ := rfl @[simps] instance pi.semilattice_sup {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup (α i)] : semilattice_sup (Π i, α i) := by refine_struct { sup := (⊔), .. pi.partial_order }; tactic.pi_instance_derive_field @[simps] instance pi.semilattice_inf {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf (α i)] : semilattice_inf (Π i, α i) := by refine_struct { inf := (⊓), .. pi.partial_order }; tactic.pi_instance_derive_field @[simps] instance pi.semilattice_inf_bot {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf_bot (α i)] : semilattice_inf_bot (Π i, α i) := by refine_struct { inf := (⊓), bot := ⊥, .. pi.partial_order }; tactic.pi_instance_derive_field @[simps] instance pi.semilattice_inf_top {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf_top (α i)] : semilattice_inf_top (Π i, α i) := by refine_struct { inf := (⊓), top := ⊤, .. pi.partial_order }; tactic.pi_instance_derive_field @[simps] instance pi.semilattice_sup_bot {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup_bot (α i)] : semilattice_sup_bot (Π i, α i) := by refine_struct { sup := (⊔), bot := ⊥, .. pi.partial_order }; tactic.pi_instance_derive_field @[simps] instance pi.semilattice_sup_top {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup_top (α i)] : semilattice_sup_top (Π i, α i) := by refine_struct { sup := (⊔), top := ⊤, .. pi.partial_order }; tactic.pi_instance_derive_field @[simps] instance pi.lattice {ι : Type*} {α : ι → Type*} [Π i, lattice (α i)] : lattice (Π i, α i) := { .. pi.semilattice_sup, .. pi.semilattice_inf } @[simps] instance pi.bounded_lattice {ι : Type*} {α : ι → Type*} [Π i, bounded_lattice (α i)] : bounded_lattice (Π i, α i) := { .. pi.semilattice_sup_top, .. pi.semilattice_inf_bot } /-- Attach `⊥` to a type. -/ def with_bot (α : Type*) := option α namespace with_bot meta instance {α} [has_to_format α] : has_to_format (with_bot α) := { to_format := λ x, match x with | none := "⊥" | (some x) := to_fmt x end } instance : has_coe_t α (with_bot α) := ⟨some⟩ instance has_bot : has_bot (with_bot α) := ⟨none⟩ instance : inhabited (with_bot α) := ⟨⊥⟩ lemma none_eq_bot : (none : with_bot α) = (⊥ : with_bot α) := rfl lemma some_eq_coe (a : α) : (some a : with_bot α) = (↑a : with_bot α) := rfl @[norm_cast] theorem coe_eq_coe {a b : α} : (a : with_bot α) = b ↔ a = b := by rw [← option.some.inj_eq a b]; refl @[priority 10] instance has_lt [has_lt α] : has_lt (with_bot α) := { lt := λ o₁ o₂ : option α, ∃ b ∈ o₂, ∀ a ∈ o₁, a < b } @[simp] theorem some_lt_some [has_lt α] {a b : α} : @has_lt.lt (with_bot α) _ (some a) (some b) ↔ a < b := by simp [(<)] lemma bot_lt_some [has_lt α] (a : α) : (⊥ : with_bot α) < some a := ⟨a, rfl, λ b hb, (option.not_mem_none _ hb).elim⟩ lemma bot_lt_coe [has_lt α] (a : α) : (⊥ : with_bot α) < a := bot_lt_some a instance [preorder α] : preorder (with_bot α) := { le := λ o₁ o₂ : option α, ∀ a ∈ o₁, ∃ b ∈ o₂, a ≤ b, lt := (<), lt_iff_le_not_le := by intros; cases a; cases b; simp [lt_iff_le_not_le]; simp [(<)]; split; refl, le_refl := λ o a ha, ⟨a, ha, le_refl _⟩, le_trans := λ o₁ o₂ o₃ h₁ h₂ a ha, let ⟨b, hb, ab⟩ := h₁ a ha, ⟨c, hc, bc⟩ := h₂ b hb in ⟨c, hc, le_trans ab bc⟩ } instance partial_order [partial_order α] : partial_order (with_bot α) := { le_antisymm := λ o₁ o₂ h₁ h₂, begin cases o₁ with a, { cases o₂ with b, {refl}, rcases h₂ b rfl with ⟨_, ⟨⟩, _⟩ }, { rcases h₁ a rfl with ⟨b, ⟨⟩, h₁'⟩, rcases h₂ b rfl with ⟨_, ⟨⟩, h₂'⟩, rw le_antisymm h₁' h₂' } end, .. with_bot.preorder } instance order_bot [partial_order α] : order_bot (with_bot α) := { bot_le := λ a a' h, option.no_confusion h, ..with_bot.partial_order, ..with_bot.has_bot } @[simp, norm_cast] theorem coe_le_coe [partial_order α] {a b : α} : (a : with_bot α) ≤ b ↔ a ≤ b := ⟨λ h, by rcases h a rfl with ⟨_, ⟨⟩, h⟩; exact h, λ h a' e, option.some_inj.1 e ▸ ⟨b, rfl, h⟩⟩ @[simp] theorem some_le_some [partial_order α] {a b : α} : @has_le.le (with_bot α) _ (some a) (some b) ↔ a ≤ b := coe_le_coe theorem coe_le [partial_order α] {a b : α} : ∀ {o : option α}, b ∈ o → ((a : with_bot α) ≤ o ↔ a ≤ b) | _ rfl := coe_le_coe @[norm_cast] lemma coe_lt_coe [partial_order α] {a b : α} : (a : with_bot α) < b ↔ a < b := some_lt_some lemma le_coe_get_or_else [preorder α] : ∀ (a : with_bot α) (b : α), a ≤ a.get_or_else b | (some a) b := le_refl a | none b := λ _ h, option.no_confusion h instance linear_order [linear_order α] : linear_order (with_bot α) := { le_total := λ o₁ o₂, begin cases o₁ with a, {exact or.inl bot_le}, cases o₂ with b, {exact or.inr bot_le}, simp [le_total] end, ..with_bot.partial_order } instance decidable_lt [has_lt α] [@decidable_rel α (<)] : @decidable_rel (with_bot α) (<) | none (some x) := is_true $ by existsi [x,rfl]; rintros _ ⟨⟩ | (some x) (some y) := if h : x < y then is_true $ by simp * else is_false $ by simp * | x none := is_false $ by rintro ⟨a,⟨⟨⟩⟩⟩ instance decidable_linear_order [decidable_linear_order α] : decidable_linear_order (with_bot α) := { decidable_le := λ a b, begin cases a with a, { exact is_true bot_le }, cases b with b, { exact is_false (mt (le_antisymm bot_le) (by simp)) }, { exact decidable_of_iff _ some_le_some } end, ..with_bot.linear_order } instance semilattice_sup [semilattice_sup α] : semilattice_sup_bot (with_bot α) := { sup := option.lift_or_get (⊔), le_sup_left := λ o₁ o₂ a ha, by cases ha; cases o₂; simp [option.lift_or_get], le_sup_right := λ o₁ o₂ a ha, by cases ha; cases o₁; simp [option.lift_or_get], sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases o₁ with b; cases o₂ with c; cases ha, { exact h₂ a rfl }, { exact h₁ a rfl }, { rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩, simp at h₂, exact ⟨d, rfl, sup_le h₁' h₂⟩ } end, ..with_bot.order_bot } instance semilattice_inf [semilattice_inf α] : semilattice_inf_bot (with_bot α) := { inf := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊓ b)), inf_le_left := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, inf_le_left⟩ end, inf_le_right := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, inf_le_right⟩ end, le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases ha, rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩, rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩, exact ⟨_, rfl, le_inf ab ac⟩ end, ..with_bot.order_bot } instance lattice [lattice α] : lattice (with_bot α) := { ..with_bot.semilattice_sup, ..with_bot.semilattice_inf } theorem lattice_eq_DLO [decidable_linear_order α] : lattice_of_decidable_linear_order = @with_bot.lattice α _ := lattice.ext $ λ x y, iff.rfl theorem sup_eq_max [decidable_linear_order α] (x y : with_bot α) : x ⊔ y = max x y := by rw [← sup_eq_max, lattice_eq_DLO] theorem inf_eq_min [decidable_linear_order α] (x y : with_bot α) : x ⊓ y = min x y := by rw [← inf_eq_min, lattice_eq_DLO] instance order_top [order_top α] : order_top (with_bot α) := { top := some ⊤, le_top := λ o a ha, by cases ha; exact ⟨_, rfl, le_top⟩, ..with_bot.partial_order } instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_bot α) := { ..with_bot.lattice, ..with_bot.order_top, ..with_bot.order_bot } lemma well_founded_lt [partial_order α] (h : well_founded ((<) : α → α → Prop)) : well_founded ((<) : with_bot α → with_bot α → Prop) := have acc_bot : acc ((<) : with_bot α → with_bot α → Prop) ⊥ := acc.intro _ (λ a ha, (not_le_of_gt ha bot_le).elim), ⟨λ a, option.rec_on a acc_bot (λ a, acc.intro _ (λ b, option.rec_on b (λ _, acc_bot) (λ b, well_founded.induction h b (show ∀ b : α, (∀ c, c < b → (c : with_bot α) < a → acc ((<) : with_bot α → with_bot α → Prop) c) → (b : with_bot α) < a → acc ((<) : with_bot α → with_bot α → Prop) b, from λ b ih hba, acc.intro _ (λ c, option.rec_on c (λ _, acc_bot) (λ c hc, ih _ (some_lt_some.1 hc) (lt_trans hc hba)))))))⟩ instance densely_ordered [partial_order α] [densely_ordered α] [no_bot_order α] : densely_ordered (with_bot α) := ⟨ assume a b, match a, b with | a, none := assume h : a < ⊥, (not_lt_bot h).elim | none, some b := assume h, let ⟨a, ha⟩ := no_bot b in ⟨a, bot_lt_coe a, coe_lt_coe.2 ha⟩ | some a, some b := assume h, let ⟨a, ha₁, ha₂⟩ := dense (coe_lt_coe.1 h) in ⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩ end⟩ end with_bot --TODO(Mario): Construct using order dual on with_bot def with_top (α : Type*) := option α namespace with_top meta instance {α} [has_to_format α] : has_to_format (with_top α) := { to_format := λ x, match x with | none := "⊤" | (some x) := to_fmt x end } instance : has_coe_t α (with_top α) := ⟨some⟩ instance has_top : has_top (with_top α) := ⟨none⟩ instance : inhabited (with_top α) := ⟨⊤⟩ lemma none_eq_top : (none : with_top α) = (⊤ : with_top α) := rfl lemma some_eq_coe (a : α) : (some a : with_top α) = (↑a : with_top α) := rfl @[norm_cast] theorem coe_eq_coe {a b : α} : (a : with_top α) = b ↔ a = b := by rw [← option.some.inj_eq a b]; refl @[simp] theorem top_ne_coe {a : α} : ⊤ ≠ (a : with_top α) . @[simp] theorem coe_ne_top {a : α} : (a : with_top α) ≠ ⊤ . @[priority 10] instance has_lt [has_lt α] : has_lt (with_top α) := { lt := λ o₁ o₂ : option α, ∃ b ∈ o₁, ∀ a ∈ o₂, b < a } @[priority 10] instance has_le [has_le α] : has_le (with_top α) := { le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a } @[simp] theorem some_lt_some [has_lt α] {a b : α} : @has_lt.lt (with_top α) _ (some a) (some b) ↔ a < b := by simp [(<)] @[simp] theorem some_le_some [has_le α] {a b : α} : @has_le.le (with_top α) _ (some a) (some b) ↔ a ≤ b := by simp [(≤)] @[simp] theorem none_le [has_le α] {a : with_top α} : @has_le.le (with_top α) _ a none := by simp [(≤)] @[simp] theorem none_lt_some [has_lt α] {a : α} : @has_lt.lt (with_top α) _ (some a) none := by simp [(<)]; existsi a; refl instance [preorder α] : preorder (with_top α) := { le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a, lt := (<), lt_iff_le_not_le := by { intros; cases a; cases b; simp [lt_iff_le_not_le]; simp [(<),(≤)] }, le_refl := λ o a ha, ⟨a, ha, le_refl _⟩, le_trans := λ o₁ o₂ o₃ h₁ h₂ c hc, let ⟨b, hb, bc⟩ := h₂ c hc, ⟨a, ha, ab⟩ := h₁ b hb in ⟨a, ha, le_trans ab bc⟩, } instance partial_order [partial_order α] : partial_order (with_top α) := { le_antisymm := λ o₁ o₂ h₁ h₂, begin cases o₂ with b, { cases o₁ with a, {refl}, rcases h₂ a rfl with ⟨_, ⟨⟩, _⟩ }, { rcases h₁ b rfl with ⟨a, ⟨⟩, h₁'⟩, rcases h₂ a rfl with ⟨_, ⟨⟩, h₂'⟩, rw le_antisymm h₁' h₂' } end, .. with_top.preorder } instance order_top [partial_order α] : order_top (with_top α) := { le_top := λ a a' h, option.no_confusion h, ..with_top.partial_order, .. with_top.has_top } @[simp, norm_cast] theorem coe_le_coe [partial_order α] {a b : α} : (a : with_top α) ≤ b ↔ a ≤ b := ⟨λ h, by rcases h b rfl with ⟨_, ⟨⟩, h⟩; exact h, λ h a' e, option.some_inj.1 e ▸ ⟨a, rfl, h⟩⟩ theorem le_coe [partial_order α] {a b : α} : ∀ {o : option α}, a ∈ o → (@has_le.le (with_top α) _ o b ↔ a ≤ b) | _ rfl := coe_le_coe theorem le_coe_iff [partial_order α] (b : α) : ∀(x : with_top α), x ≤ b ↔ (∃a:α, x = a ∧ a ≤ b) | (some a) := by simp [some_eq_coe, coe_eq_coe] | none := by simp [none_eq_top] theorem coe_le_iff [partial_order α] (a : α) : ∀(x : with_top α), ↑a ≤ x ↔ (∀b:α, x = ↑b → a ≤ b) | (some b) := by simp [some_eq_coe, coe_eq_coe] | none := by simp [none_eq_top] theorem lt_iff_exists_coe [partial_order α] : ∀(a b : with_top α), a < b ↔ (∃p:α, a = p ∧ ↑p < b) | (some a) b := by simp [some_eq_coe, coe_eq_coe] | none b := by simp [none_eq_top] @[norm_cast] lemma coe_lt_coe [partial_order α] {a b : α} : (a : with_top α) < b ↔ a < b := some_lt_some lemma coe_lt_top [partial_order α] (a : α) : (a : with_top α) < ⊤ := lt_of_le_of_ne le_top (λ h, option.no_confusion h) lemma not_top_le_coe [partial_order α] (a : α) : ¬ (⊤:with_top α) ≤ ↑a := assume h, (lt_irrefl ⊤ (lt_of_le_of_lt h (coe_lt_top a))).elim instance linear_order [linear_order α] : linear_order (with_top α) := { le_total := λ o₁ o₂, begin cases o₁ with a, {exact or.inr le_top}, cases o₂ with b, {exact or.inl le_top}, simp [le_total] end, ..with_top.partial_order } instance decidable_linear_order [decidable_linear_order α] : decidable_linear_order (with_top α) := { decidable_le := λ a b, begin cases b with b, { exact is_true le_top }, cases a with a, { exact is_false (mt (le_antisymm le_top) (by simp)) }, { exact decidable_of_iff _ some_le_some } end, ..with_top.linear_order } instance semilattice_inf [semilattice_inf α] : semilattice_inf_top (with_top α) := { inf := option.lift_or_get (⊓), inf_le_left := λ o₁ o₂ a ha, by cases ha; cases o₂; simp [option.lift_or_get], inf_le_right := λ o₁ o₂ a ha, by cases ha; cases o₁; simp [option.lift_or_get], le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases o₂ with b; cases o₃ with c; cases ha, { exact h₂ a rfl }, { exact h₁ a rfl }, { rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩, simp at h₂, exact ⟨d, rfl, le_inf h₁' h₂⟩ } end, ..with_top.order_top } lemma coe_inf [semilattice_inf α] (a b : α) : ((a ⊓ b : α) : with_top α) = a ⊓ b := rfl instance semilattice_sup [semilattice_sup α] : semilattice_sup_top (with_top α) := { sup := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊔ b)), le_sup_left := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, le_sup_left⟩ end, le_sup_right := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, le_sup_right⟩ end, sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases ha, rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩, rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩, exact ⟨_, rfl, sup_le ab ac⟩ end, ..with_top.order_top } lemma coe_sup [semilattice_sup α] (a b : α) : ((a ⊔ b : α) : with_top α) = a ⊔ b := rfl instance lattice [lattice α] : lattice (with_top α) := { ..with_top.semilattice_sup, ..with_top.semilattice_inf } theorem lattice_eq_DLO [decidable_linear_order α] : lattice_of_decidable_linear_order = @with_top.lattice α _ := lattice.ext $ λ x y, iff.rfl theorem sup_eq_max [decidable_linear_order α] (x y : with_top α) : x ⊔ y = max x y := by rw [← sup_eq_max, lattice_eq_DLO] theorem inf_eq_min [decidable_linear_order α] (x y : with_top α) : x ⊓ y = min x y := by rw [← inf_eq_min, lattice_eq_DLO] instance order_bot [order_bot α] : order_bot (with_top α) := { bot := some ⊥, bot_le := λ o a ha, by cases ha; exact ⟨_, rfl, bot_le⟩, ..with_top.partial_order } instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_top α) := { ..with_top.lattice, ..with_top.order_top, ..with_top.order_bot } lemma well_founded_lt {α : Type*} [partial_order α] (h : well_founded ((<) : α → α → Prop)) : well_founded ((<) : with_top α → with_top α → Prop) := have acc_some : ∀ a : α, acc ((<) : with_top α → with_top α → Prop) (some a) := λ a, acc.intro _ (well_founded.induction h a (show ∀ b, (∀ c, c < b → ∀ d : with_top α, d < some c → acc (<) d) → ∀ y : with_top α, y < some b → acc (<) y, from λ b ih c, option.rec_on c (λ hc, (not_lt_of_ge le_top hc).elim) (λ c hc, acc.intro _ (ih _ (some_lt_some.1 hc))))), ⟨λ a, option.rec_on a (acc.intro _ (λ y, option.rec_on y (λ h, (lt_irrefl _ h).elim) (λ _ _, acc_some _))) acc_some⟩ instance densely_ordered [partial_order α] [densely_ordered α] [no_top_order α] : densely_ordered (with_top α) := ⟨ assume a b, match a, b with | none, a := assume h : ⊤ < a, (not_top_lt h).elim | some a, none := assume h, let ⟨b, hb⟩ := no_top a in ⟨b, coe_lt_coe.2 hb, coe_lt_top b⟩ | some a, some b := assume h, let ⟨a, ha₁, ha₂⟩ := dense (coe_lt_coe.1 h) in ⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩ end⟩ lemma lt_iff_exists_coe_btwn [partial_order α] [densely_ordered α] [no_top_order α] {a b : with_top α} : (a < b) ↔ (∃ x : α, a < ↑x ∧ ↑x < b) := ⟨λ h, let ⟨y, hy⟩ := dense h, ⟨x, hx⟩ := (lt_iff_exists_coe _ _).1 hy.2 in ⟨x, hx.1 ▸ hy⟩, λ ⟨x, hx⟩, lt_trans hx.1 hx.2⟩ end with_top namespace subtype /-- A subtype forms a `⊔`-semilattice if `⊔` preserves the property. -/ protected def semilattice_sup [semilattice_sup α] {P : α → Prop} (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) : semilattice_sup {x : α // P x} := { sup := λ x y, ⟨x.1 ⊔ y.1, Psup x.2 y.2⟩, le_sup_left := λ x y, @le_sup_left _ _ (x : α) y, le_sup_right := λ x y, @le_sup_right _ _ (x : α) y, sup_le := λ x y z h1 h2, @sup_le α _ _ _ _ h1 h2, ..subtype.partial_order P } /-- A subtype forms a `⊓`-semilattice if `⊓` preserves the property. -/ protected def semilattice_inf [semilattice_inf α] {P : α → Prop} (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : semilattice_inf {x : α // P x} := { inf := λ x y, ⟨x.1 ⊓ y.1, Pinf x.2 y.2⟩, inf_le_left := λ x y, @inf_le_left _ _ (x : α) y, inf_le_right := λ x y, @inf_le_right _ _ (x : α) y, le_inf := λ x y z h1 h2, @le_inf α _ _ _ _ h1 h2, ..subtype.partial_order P } /-- A subtype forms a `⊔`-`⊥`-semilattice if `⊥` and `⊔` preserve the property. -/ protected def semilattice_sup_bot [semilattice_sup_bot α] {P : α → Prop} (Pbot : P ⊥) (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) : semilattice_sup_bot {x : α // P x} := { bot := ⟨⊥, Pbot⟩, bot_le := λ x, @bot_le α _ x, ..subtype.semilattice_sup Psup } /-- A subtype forms a `⊓`-`⊥`-semilattice if `⊥` and `⊓` preserve the property. -/ protected def semilattice_inf_bot [semilattice_inf_bot α] {P : α → Prop} (Pbot : P ⊥) (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : semilattice_inf_bot {x : α // P x} := { bot := ⟨⊥, Pbot⟩, bot_le := λ x, @bot_le α _ x, ..subtype.semilattice_inf Pinf } /-- A subtype forms a `⊓`-`⊤`-semilattice if `⊤` and `⊓` preserve the property. -/ protected def semilattice_inf_top [semilattice_inf_top α] {P : α → Prop} (Ptop : P ⊤) (Pinf : ∀{{x y}}, P x → P y → P (x ⊓ y)) : semilattice_inf_top {x : α // P x} := { top := ⟨⊤, Ptop⟩, le_top := λ x, @le_top α _ x, ..subtype.semilattice_inf Pinf } /-- A subtype forms a lattice if `⊔` and `⊓` preserve the property. -/ protected def lattice [lattice α] {P : α → Prop} (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : lattice {x : α // P x} := { ..subtype.semilattice_inf Pinf, ..subtype.semilattice_sup Psup } end subtype namespace order_dual variable (α) instance [has_bot α] : has_top (order_dual α) := ⟨(⊥ : α)⟩ instance [has_top α] : has_bot (order_dual α) := ⟨(⊤ : α)⟩ instance [order_bot α] : order_top (order_dual α) := { le_top := @bot_le α _, .. order_dual.partial_order α, .. order_dual.has_top α } instance [order_top α] : order_bot (order_dual α) := { bot_le := @le_top α _, .. order_dual.partial_order α, .. order_dual.has_bot α } instance [semilattice_inf_bot α] : semilattice_sup_top (order_dual α) := { .. order_dual.semilattice_sup α, .. order_dual.order_top α } instance [semilattice_inf_top α] : semilattice_sup_bot (order_dual α) := { .. order_dual.semilattice_sup α, .. order_dual.order_bot α } instance [semilattice_sup_bot α] : semilattice_inf_top (order_dual α) := { .. order_dual.semilattice_inf α, .. order_dual.order_top α } instance [semilattice_sup_top α] : semilattice_inf_bot (order_dual α) := { .. order_dual.semilattice_inf α, .. order_dual.order_bot α } instance [bounded_lattice α] : bounded_lattice (order_dual α) := { .. order_dual.lattice α, .. order_dual.order_top α, .. order_dual.order_bot α } instance [bounded_distrib_lattice α] : bounded_distrib_lattice (order_dual α) := { .. order_dual.bounded_lattice α, .. order_dual.distrib_lattice α } end order_dual namespace prod variables (α β) instance [has_top α] [has_top β] : has_top (α × β) := ⟨⟨⊤, ⊤⟩⟩ instance [has_bot α] [has_bot β] : has_bot (α × β) := ⟨⟨⊥, ⊥⟩⟩ instance [order_top α] [order_top β] : order_top (α × β) := { le_top := assume a, ⟨le_top, le_top⟩, .. prod.partial_order α β, .. prod.has_top α β } instance [order_bot α] [order_bot β] : order_bot (α × β) := { bot_le := assume a, ⟨bot_le, bot_le⟩, .. prod.partial_order α β, .. prod.has_bot α β } instance [semilattice_sup_top α] [semilattice_sup_top β] : semilattice_sup_top (α × β) := { .. prod.semilattice_sup α β, .. prod.order_top α β } instance [semilattice_inf_top α] [semilattice_inf_top β] : semilattice_inf_top (α × β) := { .. prod.semilattice_inf α β, .. prod.order_top α β } instance [semilattice_sup_bot α] [semilattice_sup_bot β] : semilattice_sup_bot (α × β) := { .. prod.semilattice_sup α β, .. prod.order_bot α β } instance [semilattice_inf_bot α] [semilattice_inf_bot β] : semilattice_inf_bot (α × β) := { .. prod.semilattice_inf α β, .. prod.order_bot α β } instance [bounded_lattice α] [bounded_lattice β] : bounded_lattice (α × β) := { .. prod.lattice α β, .. prod.order_top α β, .. prod.order_bot α β } instance [bounded_distrib_lattice α] [bounded_distrib_lattice β] : bounded_distrib_lattice (α × β) := { .. prod.bounded_lattice α β, .. prod.distrib_lattice α β } end prod section disjoint section semilattice_inf_bot variable [semilattice_inf_bot α] /-- Two elements of a lattice are disjoint if their inf is the bottom element. (This generalizes disjoint sets, viewed as members of the subset lattice.) -/ def disjoint (a b : α) : Prop := a ⊓ b ≤ ⊥ theorem disjoint.eq_bot {a b : α} (h : disjoint a b) : a ⊓ b = ⊥ := eq_bot_iff.2 h theorem disjoint_iff {a b : α} : disjoint a b ↔ a ⊓ b = ⊥ := eq_bot_iff.symm theorem disjoint.comm {a b : α} : disjoint a b ↔ disjoint b a := by rw [disjoint, disjoint, inf_comm] @[symm] theorem disjoint.symm ⦃a b : α⦄ : disjoint a b → disjoint b a := disjoint.comm.1 @[simp] theorem disjoint_bot_left {a : α} : disjoint ⊥ a := disjoint_iff.2 bot_inf_eq @[simp] theorem disjoint_bot_right {a : α} : disjoint a ⊥ := disjoint_iff.2 inf_bot_eq theorem disjoint.mono {a b c d : α} (h₁ : a ≤ b) (h₂ : c ≤ d) : disjoint b d → disjoint a c := le_trans (inf_le_inf h₁ h₂) theorem disjoint.mono_left {a b c : α} (h : a ≤ b) : disjoint b c → disjoint a c := disjoint.mono h (le_refl _) theorem disjoint.mono_right {a b c : α} (h : b ≤ c) : disjoint a c → disjoint a b := disjoint.mono (le_refl _) h @[simp] lemma disjoint_self {a : α} : disjoint a a ↔ a = ⊥ := by simp [disjoint] lemma disjoint.ne {a b : α} (ha : a ≠ ⊥) (hab : disjoint a b) : a ≠ b := by { intro h, rw [←h, disjoint_self] at hab, exact ha hab } end semilattice_inf_bot section bounded_distrib_lattice variables [bounded_distrib_lattice α] {a b c : α} @[simp] lemma disjoint_sup_left : disjoint (a ⊔ b) c ↔ disjoint a c ∧ disjoint b c := by simp only [disjoint_iff, inf_sup_right, sup_eq_bot_iff] @[simp] lemma disjoint_sup_right : disjoint a (b ⊔ c) ↔ disjoint a b ∧ disjoint a c := by simp only [disjoint_iff, inf_sup_left, sup_eq_bot_iff] lemma disjoint.sup_left (ha : disjoint a c) (hb : disjoint b c) : disjoint (a ⊔ b) c := disjoint_sup_left.2 ⟨ha, hb⟩ lemma disjoint.sup_right (hb : disjoint a b) (hc : disjoint a c) : disjoint a (b ⊔ c) := disjoint_sup_right.2 ⟨hb, hc⟩ end bounded_distrib_lattice end disjoint /-! ### `is_compl` predicate -/ /-- Two elements `x` and `y` are complements of each other if `x ⊔ y = ⊤` and `x ⊓ y = ⊥`. -/ structure is_compl [bounded_lattice α] (x y : α) : Prop := (inf_le_bot : x ⊓ y ≤ ⊥) (top_le_sup : ⊤ ≤ x ⊔ y) namespace is_compl section bounded_lattice variables [bounded_lattice α] {x y z : α} protected lemma disjoint (h : is_compl x y) : disjoint x y := h.1 @[symm] protected lemma symm (h : is_compl x y) : is_compl y x := ⟨by { rw inf_comm, exact h.1 }, by { rw sup_comm, exact h.2 }⟩ lemma of_eq (h₁ : x ⊓ y = ⊥) (h₂ : x ⊔ y = ⊤) : is_compl x y := ⟨le_of_eq h₁, le_of_eq h₂.symm⟩ lemma inf_eq_bot (h : is_compl x y) : x ⊓ y = ⊥ := h.disjoint.eq_bot lemma sup_eq_top (h : is_compl x y) : x ⊔ y = ⊤ := top_unique h.top_le_sup lemma to_order_dual (h : is_compl x y) : @is_compl (order_dual α) _ x y := ⟨h.2, h.1⟩ end bounded_lattice variables [bounded_distrib_lattice α] {x y z : α} lemma le_left_iff (h : is_compl x y) : z ≤ x ↔ disjoint z y := ⟨λ hz, h.disjoint.mono_left hz, λ hz, le_of_inf_le_sup_le (le_trans hz bot_le) (le_trans le_top h.top_le_sup)⟩ lemma le_right_iff (h : is_compl x y) : z ≤ y ↔ disjoint z x := h.symm.le_left_iff lemma left_le_iff (h : is_compl x y) : x ≤ z ↔ ⊤ ≤ z ⊔ y := h.to_order_dual.le_left_iff lemma right_le_iff (h : is_compl x y) : y ≤ z ↔ ⊤ ≤ z ⊔ x := h.symm.left_le_iff lemma antimono {x' y'} (h : is_compl x y) (h' : is_compl x' y') (hx : x ≤ x') : y' ≤ y := h'.right_le_iff.2 $ le_trans h.symm.top_le_sup (sup_le_sup_left hx _) lemma right_unique (hxy : is_compl x y) (hxz : is_compl x z) : y = z := le_antisymm (hxz.antimono hxy $ le_refl x) (hxy.antimono hxz $ le_refl x) lemma left_unique (hxz : is_compl x z) (hyz : is_compl y z) : x = y := hxz.symm.right_unique hyz.symm lemma sup_inf {x' y'} (h : is_compl x y) (h' : is_compl x' y') : is_compl (x ⊔ x') (y ⊓ y') := of_eq (by rw [inf_sup_right, ← inf_assoc, h.inf_eq_bot, bot_inf_eq, bot_sup_eq, inf_left_comm, h'.inf_eq_bot, inf_bot_eq]) (by rw [sup_inf_left, @sup_comm _ _ x, sup_assoc, h.sup_eq_top, sup_top_eq, top_inf_eq, sup_assoc, sup_left_comm, h'.sup_eq_top, sup_top_eq]) lemma inf_sup {x' y'} (h : is_compl x y) (h' : is_compl x' y') : is_compl (x ⊓ x') (y ⊔ y') := (h.symm.sup_inf h'.symm).symm lemma inf_left_eq_bot_iff (h : is_compl y z) : x ⊓ y = ⊥ ↔ x ≤ z := inf_eq_bot_iff_le_compl h.sup_eq_top h.inf_eq_bot lemma inf_right_eq_bot_iff (h : is_compl y z) : x ⊓ z = ⊥ ↔ x ≤ y := h.symm.inf_left_eq_bot_iff lemma disjoint_left_iff (h : is_compl y z) : disjoint x y ↔ x ≤ z := disjoint_iff.trans h.inf_left_eq_bot_iff lemma disjoint_right_iff (h : is_compl y z) : disjoint x z ↔ x ≤ y := h.symm.disjoint_left_iff end is_compl lemma is_compl_bot_top [bounded_lattice α] : is_compl (⊥ : α) ⊤ := is_compl.of_eq bot_inf_eq sup_top_eq lemma is_compl_top_bot [bounded_lattice α] : is_compl (⊤ : α) ⊥ := is_compl.of_eq inf_bot_eq top_sup_eq
7d4239560de1b6b6e5ed4da1f0b238dfd7dffa5b
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/set_theory/ordinal/fixed_point.lean
5d54671f8501611e1692f35f2cc6da3043cfc801
[ "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
23,248
lean
/- Copyright (c) 2018 Violeta Hernández Palacios, Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Violeta Hernández Palacios, Mario Carneiro -/ import set_theory.ordinal.arithmetic /-! # Fixed points of normal functions We prove various statements about the fixed points of normal ordinal functions. We state them in three forms: as statements about type-indexed families of normal functions, as statements about ordinal-indexed families of normal functions, and as statements about a single normal function. For the most part, the first case encompasses the others. Moreover, we prove some lemmas about the fixed points of specific normal functions. ## Main definitions and results * `nfp_family`, `nfp_bfamily`, `nfp`: the next fixed point of a (family of) normal function(s). * `fp_family_unbounded`, `fp_bfamily_unbounded`, `fp_unbounded`: the (common) fixed points of a (family of) normal function(s) are unbounded in the ordinals. * `deriv_add_eq_mul_omega_add`: a characterization of the derivative of addition. * `deriv_mul_eq_opow_omega_mul`: a characterization of the derivative of multiplication. -/ noncomputable theory universes u v open function order namespace ordinal /-! ### Fixed points of type-indexed families of ordinals -/ section variables {ι : Type u} {f : ι → ordinal.{max u v} → ordinal.{max u v}} /-- The next common fixed point, at least `a`, for a family of normal functions. `ordinal.nfp_family_fp` shows this is a fixed point, `ordinal.le_nfp_family` shows it's at least `a`, and `ordinal.nfp_family_le_fp` shows this is the least ordinal with these properties. -/ def nfp_family (f : ι → ordinal → ordinal) (a) : ordinal := sup (list.foldr f a) theorem nfp_family_eq_sup (f : ι → ordinal → ordinal) (a) : nfp_family f a = sup (list.foldr f a) := rfl theorem foldr_le_nfp_family (f : ι → ordinal → ordinal) (a l) : list.foldr f a l ≤ nfp_family f a := le_sup _ _ theorem le_nfp_family (f : ι → ordinal → ordinal) (a) : a ≤ nfp_family f a := le_sup _ [] theorem lt_nfp_family {a b} : a < nfp_family f b ↔ ∃ l, a < list.foldr f b l := lt_sup theorem nfp_family_le_iff {a b} : nfp_family f a ≤ b ↔ ∀ l, list.foldr f a l ≤ b := sup_le_iff theorem nfp_family_le {a b} : (∀ l, list.foldr f a l ≤ b) → nfp_family f a ≤ b := sup_le theorem nfp_family_monotone (hf : ∀ i, monotone (f i)) : monotone (nfp_family f) := λ a b h, sup_le $ λ l, (list.foldr_monotone hf l h).trans (le_sup _ l) theorem apply_lt_nfp_family (H : ∀ i, is_normal (f i)) {a b} (hb : b < nfp_family f a) (i) : f i b < nfp_family f a := let ⟨l, hl⟩ := lt_nfp_family.1 hb in lt_sup.2 ⟨i :: l, (H i).strict_mono hl⟩ theorem apply_lt_nfp_family_iff [nonempty ι] (H : ∀ i, is_normal (f i)) {a b} : (∀ i, f i b < nfp_family f a) ↔ b < nfp_family f a := ⟨λ h, lt_nfp_family.2 $ let ⟨l, hl⟩ := lt_sup.1 (h (classical.arbitrary ι)) in ⟨l, ((H _).self_le b).trans_lt hl⟩, apply_lt_nfp_family H⟩ theorem nfp_family_le_apply [nonempty ι] (H : ∀ i, is_normal (f i)) {a b} : (∃ i, nfp_family f a ≤ f i b) ↔ nfp_family f a ≤ b := by { rw ←not_iff_not, push_neg, exact apply_lt_nfp_family_iff H } theorem nfp_family_le_fp (H : ∀ i, monotone (f i)) {a b} (ab : a ≤ b) (h : ∀ i, f i b ≤ b) : nfp_family f a ≤ b := sup_le $ λ l, begin by_cases hι : is_empty ι, { resetI, rwa unique.eq_default l }, { haveI := not_is_empty_iff.1 hι, induction l with i l IH generalizing a, {exact ab}, exact (H i (IH ab)).trans (h i) } end theorem nfp_family_fp {i} (H : is_normal (f i)) (a) : f i (nfp_family f a) = nfp_family f a := begin unfold nfp_family, rw @is_normal.sup _ H _ _ ⟨[]⟩, apply le_antisymm; refine ordinal.sup_le (λ l, _), { exact le_sup _ (i :: l) }, { exact (H.self_le _).trans (le_sup _ _) } end theorem apply_le_nfp_family [hι : nonempty ι] {f : ι → ordinal → ordinal} (H : ∀ i, is_normal (f i)) {a b} : (∀ i, f i b ≤ nfp_family f a) ↔ b ≤ nfp_family f a := begin refine ⟨λ h, _, λ h i, _⟩, { unfreezingI { cases hι with i }, exact ((H i).self_le b).trans (h i) }, rw ←nfp_family_fp (H i), exact (H i).monotone h end theorem nfp_family_eq_self {f : ι → ordinal → ordinal} {a} (h : ∀ i, f i a = a) : nfp_family f a = a := le_antisymm (sup_le (λ l, (by rw list.foldr_fixed' h l))) (le_nfp_family f a) /-- A generalization of the fixed point lemma for normal functions: any family of normal functions has an unbounded set of common fixed points. -/ theorem fp_family_unbounded (H : ∀ i, is_normal (f i)) : (⋂ i, function.fixed_points (f i)).unbounded (<) := λ a, ⟨_, λ s ⟨i, hi⟩, begin rw ←hi, exact nfp_family_fp (H i) a end, (le_nfp_family f a).not_lt⟩ /-- The derivative of a family of normal functions is the sequence of their common fixed points. -/ def deriv_family (f : ι → ordinal → ordinal) (o : ordinal) : ordinal := limit_rec_on o (nfp_family f 0) (λ a IH, nfp_family f (succ IH)) (λ a l, bsup.{(max u v) u} a) @[simp] theorem deriv_family_zero (f : ι → ordinal → ordinal) : deriv_family f 0 = nfp_family f 0 := limit_rec_on_zero _ _ _ @[simp] theorem deriv_family_succ (f : ι → ordinal → ordinal) (o) : deriv_family f (succ o) = nfp_family f (succ (deriv_family f o)) := limit_rec_on_succ _ _ _ _ theorem deriv_family_limit (f : ι → ordinal → ordinal) {o} : is_limit o → deriv_family f o = bsup.{(max u v) u} o (λ a _, deriv_family f a) := limit_rec_on_limit _ _ _ _ theorem deriv_family_is_normal (f : ι → ordinal → ordinal) : is_normal (deriv_family f) := ⟨λ o, by rw [deriv_family_succ, ← succ_le_iff]; apply le_nfp_family, λ o l a, by rw [deriv_family_limit _ l, bsup_le_iff]⟩ theorem deriv_family_fp {i} (H : is_normal (f i)) (o : ordinal.{max u v}) : f i (deriv_family f o) = deriv_family f o := begin refine limit_rec_on o _ (λ o IH, _) _, { rw [deriv_family_zero], exact nfp_family_fp H 0 }, { rw [deriv_family_succ], exact nfp_family_fp H _ }, { intros o l IH, rw [deriv_family_limit _ l, is_normal.bsup.{(max u v) u (max u v)} H (λ a _, deriv_family f a) l.1], refine eq_of_forall_ge_iff (λ c, _), simp only [bsup_le_iff, IH] {contextual:=tt} } end theorem le_iff_deriv_family (H : ∀ i, is_normal (f i)) {a} : (∀ i, f i a ≤ a) ↔ ∃ o, deriv_family f o = a := ⟨λ ha, begin suffices : ∀ o (_ : a ≤ deriv_family f o), ∃ o, deriv_family f o = a, from this a ((deriv_family_is_normal _).self_le _), refine λ o, limit_rec_on o (λ h₁, ⟨0, le_antisymm _ h₁⟩) (λ o IH h₁, _) (λ o l IH h₁, _), { rw deriv_family_zero, exact nfp_family_le_fp (λ i, (H i).monotone) (ordinal.zero_le _) ha }, { cases le_or_lt a (deriv_family f o), {exact IH h}, refine ⟨succ o, le_antisymm _ h₁⟩, rw deriv_family_succ, exact nfp_family_le_fp (λ i, (H i).monotone) (succ_le_of_lt h) ha }, { cases eq_or_lt_of_le h₁, {exact ⟨_, h.symm⟩}, rw [deriv_family_limit _ l, ← not_le, bsup_le_iff, not_ball] at h, exact let ⟨o', h, hl⟩ := h in IH o' h (le_of_not_le hl) } end, λ ⟨o, e⟩ i, e ▸ le_of_eq (deriv_family_fp (H i) _)⟩ theorem fp_iff_deriv_family (H : ∀ i, is_normal (f i)) {a} : (∀ i, f i a = a) ↔ ∃ o, deriv_family f o = a := iff.trans ⟨λ h i, le_of_eq (h i), λ h i, (H i).le_iff_eq.1 (h i)⟩ (le_iff_deriv_family H) theorem deriv_family_eq_enum_ord (H : ∀ i, is_normal (f i)) : deriv_family f = enum_ord (⋂ i, function.fixed_points (f i)) := begin rw ←eq_enum_ord _ (fp_family_unbounded H), use (deriv_family_is_normal f).strict_mono, rw set.range_eq_iff, refine ⟨_, λ a ha, _⟩, { rintros a S ⟨i, hi⟩, rw ←hi, exact deriv_family_fp (H i) a }, rw set.mem_Inter at ha, rwa ←fp_iff_deriv_family H end end /-! ### Fixed points of ordinal-indexed families of ordinals -/ section variables {o : ordinal.{u}} {f : Π b < o, ordinal.{max u v} → ordinal.{max u v}} /-- The next common fixed point, at least `a`, for a family of normal functions indexed by ordinals. -/ def nfp_bfamily (o : ordinal) (f : Π b < o, ordinal → ordinal) : ordinal → ordinal := nfp_family (family_of_bfamily o f) theorem nfp_bfamily_eq_nfp_family {o : ordinal} (f : Π b < o, ordinal → ordinal) : nfp_bfamily o f = nfp_family (family_of_bfamily o f) := rfl theorem foldr_le_nfp_bfamily {o : ordinal} (f : Π b < o, ordinal → ordinal) (a l) : list.foldr (family_of_bfamily o f) a l ≤ nfp_bfamily o f a := le_sup _ _ theorem le_nfp_bfamily {o : ordinal} (f : Π b < o, ordinal → ordinal) (a) : a ≤ nfp_bfamily o f a := le_sup _ [] theorem lt_nfp_bfamily {a b} : a < nfp_bfamily o f b ↔ ∃ l, a < list.foldr (family_of_bfamily o f) b l := lt_sup theorem nfp_bfamily_le_iff {o : ordinal} {f : Π b < o, ordinal → ordinal} {a b} : nfp_bfamily o f a ≤ b ↔ ∀ l, list.foldr (family_of_bfamily o f) a l ≤ b := sup_le_iff theorem nfp_bfamily_le {o : ordinal} {f : Π b < o, ordinal → ordinal} {a b} : (∀ l, list.foldr (family_of_bfamily o f) a l ≤ b) → nfp_bfamily o f a ≤ b := sup_le theorem nfp_bfamily_monotone (hf : ∀ i hi, monotone (f i hi)) : monotone (nfp_bfamily o f) := nfp_family_monotone (λ i, hf _ _) theorem apply_lt_nfp_bfamily (ho : o ≠ 0) (H : ∀ i hi, is_normal (f i hi)) {a b} : (∀ i hi, f i hi b < nfp_bfamily o f a) ↔ b < nfp_bfamily o f a := begin unfold nfp_bfamily, rw ←@apply_lt_nfp_family_iff _ (family_of_bfamily o f) (out_nonempty_iff_ne_zero.2 ho) (λ i, H _ _), refine ⟨λ h i, h _ (typein_lt_self i), λ h i hio, _⟩, rw ←family_of_bfamily_enum o f, apply h end theorem nfp_bfamily_le_apply (ho : o ≠ 0) (H : ∀ i hi, is_normal (f i hi)) {a b} : (∃ i hi, nfp_bfamily o f a ≤ f i hi b) ↔ nfp_bfamily o f a ≤ b := by { rw ←not_iff_not, push_neg, convert apply_lt_nfp_bfamily ho H, simp only [not_le] } theorem nfp_bfamily_le_fp (H : ∀ i hi, monotone (f i hi)) {a b} (ab : a ≤ b) (h : ∀ i hi, f i hi b ≤ b) : nfp_bfamily o f a ≤ b := nfp_family_le_fp (λ _, H _ _) ab (λ i, h _ _) theorem nfp_bfamily_fp {i hi} (H : is_normal (f i hi)) (a) : f i hi (nfp_bfamily o f a) = nfp_bfamily o f a := by { rw ←family_of_bfamily_enum o f, apply nfp_family_fp, rw family_of_bfamily_enum, exact H } theorem apply_le_nfp_bfamily (ho : o ≠ 0) (H : ∀ i hi, is_normal (f i hi)) {a b} : (∀ i hi, f i hi b ≤ nfp_bfamily o f a) ↔ b ≤ nfp_bfamily o f a := begin refine ⟨λ h, _, λ h i hi, _⟩, { have ho' : 0 < o := ordinal.pos_iff_ne_zero.2 ho, exact ((H 0 ho').self_le b).trans (h 0 ho') }, rw ←nfp_bfamily_fp (H i hi), exact (H i hi).monotone h end theorem nfp_bfamily_eq_self {a} (h : ∀ i hi, f i hi a = a) : nfp_bfamily o f a = a := nfp_family_eq_self (λ _, h _ _) /-- A generalization of the fixed point lemma for normal functions: any family of normal functions has an unbounded set of common fixed points. -/ theorem fp_bfamily_unbounded (H : ∀ i hi, is_normal (f i hi)) : (⋂ i hi, function.fixed_points (f i hi)).unbounded (<) := λ a, ⟨_, by { rw set.mem_Inter₂, exact λ i hi, nfp_bfamily_fp (H i hi) _ }, (le_nfp_bfamily f a).not_lt⟩ /-- The derivative of a family of normal functions is the sequence of their common fixed points. -/ def deriv_bfamily (o : ordinal) (f : Π b < o, ordinal → ordinal) : ordinal → ordinal := deriv_family (family_of_bfamily o f) theorem deriv_bfamily_eq_deriv_family {o : ordinal} (f : Π b < o, ordinal → ordinal) : deriv_bfamily o f = deriv_family (family_of_bfamily o f) := rfl theorem deriv_bfamily_is_normal {o : ordinal} (f : Π b < o, ordinal → ordinal) : is_normal (deriv_bfamily o f) := deriv_family_is_normal _ theorem deriv_bfamily_fp {i hi} (H : is_normal (f i hi)) (a : ordinal) : f i hi (deriv_bfamily o f a) = deriv_bfamily o f a := by { rw ←family_of_bfamily_enum o f, apply deriv_family_fp, rw family_of_bfamily_enum, exact H } theorem le_iff_deriv_bfamily (H : ∀ i hi, is_normal (f i hi)) {a} : (∀ i hi, f i hi a ≤ a) ↔ ∃ b, deriv_bfamily o f b = a := begin unfold deriv_bfamily, rw ←le_iff_deriv_family, { refine ⟨λ h i, h _ _, λ h i hi, _⟩, rw ←family_of_bfamily_enum o f, apply h }, exact λ _, H _ _ end theorem fp_iff_deriv_bfamily (H : ∀ i hi, is_normal (f i hi)) {a} : (∀ i hi, f i hi a = a) ↔ ∃ b, deriv_bfamily o f b = a := begin rw ←le_iff_deriv_bfamily H, refine ⟨λ h i hi, le_of_eq (h i hi), λ h i hi, _⟩, rw ←(H i hi).le_iff_eq, exact h i hi end theorem deriv_bfamily_eq_enum_ord (H : ∀ i hi, is_normal (f i hi)) : deriv_bfamily o f = enum_ord (⋂ i hi, function.fixed_points (f i hi)) := begin rw ←eq_enum_ord _ (fp_bfamily_unbounded H), use (deriv_bfamily_is_normal f).strict_mono, rw set.range_eq_iff, refine ⟨λ a, set.mem_Inter₂.2 (λ i hi, deriv_bfamily_fp (H i hi) a), λ a ha, _⟩, rw set.mem_Inter₂ at ha, rwa ←fp_iff_deriv_bfamily H end end /-! ### Fixed points of a single function -/ section variable {f : ordinal.{u} → ordinal.{u}} /-- The next fixed point function, the least fixed point of the normal function `f`, at least `a`. -/ def nfp (f : ordinal → ordinal) : ordinal → ordinal := nfp_family (λ _ : unit, f) theorem nfp_eq_nfp_family (f : ordinal → ordinal) : nfp f = nfp_family (λ _ : unit, f) := rfl @[simp] theorem sup_iterate_eq_nfp (f : ordinal.{u} → ordinal.{u}) : (λ a, sup (λ n : ℕ, f^[n] a)) = nfp f := begin refine funext (λ a, le_antisymm _ (sup_le (λ l, _))), { rw sup_le_iff, intro n, rw [←list.length_repeat unit.star n, ←list.foldr_const f a], apply le_sup }, { rw list.foldr_const f a l, exact le_sup _ _ }, end theorem iterate_le_nfp (f a n) : f^[n] a ≤ nfp f a := by { rw ←sup_iterate_eq_nfp, exact le_sup _ n } theorem le_nfp (f a) : a ≤ nfp f a := iterate_le_nfp f a 0 theorem lt_nfp {a b} : a < nfp f b ↔ ∃ n, a < (f^[n]) b := by { rw ←sup_iterate_eq_nfp, exact lt_sup } theorem nfp_le_iff {a b} : nfp f a ≤ b ↔ ∀ n, (f^[n]) a ≤ b := by { rw ←sup_iterate_eq_nfp, exact sup_le_iff } theorem nfp_le {a b} : (∀ n, (f^[n]) a ≤ b) → nfp f a ≤ b := nfp_le_iff.2 @[simp] theorem nfp_id : nfp id = id := funext (λ a, begin simp_rw [←sup_iterate_eq_nfp, iterate_id], exact sup_const a end) theorem nfp_monotone (hf : monotone f) : monotone (nfp f) := nfp_family_monotone (λ i, hf) theorem is_normal.apply_lt_nfp {f} (H : is_normal f) {a b} : f b < nfp f a ↔ b < nfp f a := begin unfold nfp, rw ←@apply_lt_nfp_family_iff unit (λ _, f) _ (λ _, H) a b, exact ⟨λ h _, h, λ h, h unit.star⟩ end theorem is_normal.nfp_le_apply {f} (H : is_normal f) {a b} : nfp f a ≤ f b ↔ nfp f a ≤ b := le_iff_le_iff_lt_iff_lt.2 H.apply_lt_nfp theorem nfp_le_fp {f} (H : monotone f) {a b} (ab : a ≤ b) (h : f b ≤ b) : nfp f a ≤ b := nfp_family_le_fp (λ _, H) ab (λ _, h) theorem is_normal.nfp_fp {f} (H : is_normal f) : ∀ a, f (nfp f a) = nfp f a := @nfp_family_fp unit (λ _, f) unit.star H theorem is_normal.apply_le_nfp {f} (H : is_normal f) {a b} : f b ≤ nfp f a ↔ b ≤ nfp f a := ⟨le_trans (H.self_le _), λ h, by simpa only [H.nfp_fp] using H.le_iff.2 h⟩ theorem nfp_eq_self {f : ordinal → ordinal} {a} (h : f a = a) : nfp f a = a := nfp_family_eq_self (λ _, h) /-- The fixed point lemma for normal functions: any normal function has an unbounded set of fixed points. -/ theorem fp_unbounded (H : is_normal f) : (function.fixed_points f).unbounded (<) := by { convert fp_family_unbounded (λ _ : unit, H), exact (set.Inter_const _).symm } /-- The derivative of a normal function `f` is the sequence of fixed points of `f`. -/ def deriv (f : ordinal → ordinal) : ordinal → ordinal := deriv_family (λ _ : unit, f) theorem deriv_eq_deriv_family (f : ordinal → ordinal) : deriv f = deriv_family (λ _ : unit, f) := rfl @[simp] theorem deriv_zero (f) : deriv f 0 = nfp f 0 := deriv_family_zero _ @[simp] theorem deriv_succ (f o) : deriv f (succ o) = nfp f (succ (deriv f o)) := deriv_family_succ _ _ theorem deriv_limit (f) {o} : is_limit o → deriv f o = bsup.{u 0} o (λ a _, deriv f a) := deriv_family_limit _ theorem deriv_is_normal (f) : is_normal (deriv f) := deriv_family_is_normal _ theorem deriv_id_of_nfp_id {f : ordinal → ordinal} (h : nfp f = id) : deriv f = id := ((deriv_is_normal _).eq_iff_zero_and_succ is_normal.refl).2 (by simp [h]) theorem is_normal.deriv_fp {f} (H : is_normal f) : ∀ o, f (deriv f o) = deriv f o := @deriv_family_fp unit (λ _, f) unit.star H theorem is_normal.le_iff_deriv {f} (H : is_normal f) {a} : f a ≤ a ↔ ∃ o, deriv f o = a := begin unfold deriv, rw ←le_iff_deriv_family (λ _ : unit, H), exact ⟨λ h _, h, λ h, h unit.star⟩ end theorem is_normal.fp_iff_deriv {f} (H : is_normal f) {a} : f a = a ↔ ∃ o, deriv f o = a := by rw [←H.le_iff_eq, H.le_iff_deriv] theorem deriv_eq_enum_ord (H : is_normal f) : deriv f = enum_ord (function.fixed_points f) := by { convert deriv_family_eq_enum_ord (λ _ : unit, H), exact (set.Inter_const _).symm } theorem deriv_eq_id_of_nfp_eq_id {f : ordinal → ordinal} (h : nfp f = id) : deriv f = id := (is_normal.eq_iff_zero_and_succ (deriv_is_normal _) is_normal.refl).2 (by simp [h]) end /-! ### Fixed points of addition -/ @[simp] theorem nfp_add_zero (a) : nfp ((+) a) 0 = a * omega := begin simp_rw [←sup_iterate_eq_nfp, ←sup_mul_nat], congr, funext, induction n with n hn, { rw [nat.cast_zero, mul_zero, iterate_zero_apply] }, { nth_rewrite 1 nat.succ_eq_one_add, rw [nat.cast_add, nat.cast_one, mul_one_add, iterate_succ_apply', hn] } end theorem nfp_add_eq_mul_omega {a b} (hba : b ≤ a * omega) : nfp ((+) a) b = a * omega := begin apply le_antisymm (nfp_le_fp (add_is_normal a).monotone hba _), { rw ←nfp_add_zero, exact nfp_monotone (add_is_normal a).monotone (ordinal.zero_le b) }, { rw [←mul_one_add, one_add_omega] } end theorem add_eq_right_iff_mul_omega_le {a b : ordinal} : a + b = b ↔ a * omega ≤ b := begin refine ⟨λ h, _, λ h, _⟩, { rw [←nfp_add_zero a, ←deriv_zero], cases (add_is_normal a).fp_iff_deriv.1 h with c hc, rw ←hc, exact (deriv_is_normal _).monotone (ordinal.zero_le _) }, { have := ordinal.add_sub_cancel_of_le h, nth_rewrite 0 ←this, rwa [←add_assoc, ←mul_one_add, one_add_omega] } end theorem add_le_right_iff_mul_omega_le {a b : ordinal} : a + b ≤ b ↔ a * omega ≤ b := by { rw ←add_eq_right_iff_mul_omega_le, exact (add_is_normal a).le_iff_eq } theorem deriv_add_eq_mul_omega_add (a b : ordinal.{u}) : deriv ((+) a) b = a * omega + b := begin revert b, rw [←funext_iff, is_normal.eq_iff_zero_and_succ (deriv_is_normal _) (add_is_normal _)], refine ⟨_, λ a h, _⟩, { rw [deriv_zero, add_zero], exact nfp_add_zero a }, { rw [deriv_succ, h, add_succ], exact nfp_eq_self (add_eq_right_iff_mul_omega_le.2 ((le_add_right _ _).trans (le_succ _))) } end /-! ### Fixed points of multiplication -/ local infixr ^ := @pow ordinal ordinal ordinal.has_pow @[simp] theorem nfp_mul_one {a : ordinal} (ha : 0 < a) : nfp ((*) a) 1 = a ^ omega := begin rw [←sup_iterate_eq_nfp, ←sup_opow_nat], { dsimp, congr, funext, induction n with n hn, { rw [nat.cast_zero, opow_zero, iterate_zero_apply] }, nth_rewrite 1 nat.succ_eq_one_add, rw [nat.cast_add, nat.cast_one, opow_add, opow_one, iterate_succ_apply', hn] }, { exact ha } end @[simp] theorem nfp_mul_zero (a : ordinal) : nfp ((*) a) 0 = 0 := begin rw [←ordinal.le_zero, nfp_le_iff], intro n, induction n with n hn, { refl }, rwa [iterate_succ_apply, mul_zero] end @[simp] theorem nfp_zero_mul : nfp ((*) 0) = id := begin rw ←sup_iterate_eq_nfp, refine funext (λ a, (sup_le (λ n, _)).antisymm (le_sup (λ n, ((*) 0)^[n] a) 0)), induction n with n hn, { refl }, rw function.iterate_succ', change 0 * _ ≤ a, rw zero_mul, exact ordinal.zero_le a end @[simp] theorem deriv_mul_zero : deriv ((*) 0) = id := deriv_eq_id_of_nfp_eq_id nfp_zero_mul theorem nfp_mul_eq_opow_omega {a b : ordinal} (hb : 0 < b) (hba : b ≤ a ^ omega) : nfp ((*) a) b = a ^ omega.{u} := begin cases eq_zero_or_pos a with ha ha, { rw [ha, zero_opow omega_ne_zero] at *, rw [ordinal.le_zero.1 hba, nfp_zero_mul], refl }, apply le_antisymm, { apply nfp_le_fp (mul_is_normal ha).monotone hba, rw [←opow_one_add, one_add_omega] }, rw ←nfp_mul_one ha, exact nfp_monotone (mul_is_normal ha).monotone (one_le_iff_pos.2 hb) end theorem eq_zero_or_opow_omega_le_of_mul_eq_right {a b : ordinal} (hab : a * b = b) : b = 0 ∨ a ^ omega.{u} ≤ b := begin cases eq_zero_or_pos a with ha ha, { rw [ha, zero_opow omega_ne_zero], exact or.inr (ordinal.zero_le b) }, rw or_iff_not_imp_left, intro hb, change b ≠ 0 at hb, rw ←nfp_mul_one ha, rw ←one_le_iff_ne_zero at hb, exact nfp_le_fp (mul_is_normal ha).monotone hb (le_of_eq hab) end theorem mul_eq_right_iff_opow_omega_dvd {a b : ordinal} : a * b = b ↔ a ^ omega ∣ b := begin cases eq_zero_or_pos a with ha ha, { rw [ha, zero_mul, zero_opow omega_ne_zero, zero_dvd_iff], exact eq_comm }, refine ⟨λ hab, _, λ h, _⟩, { rw dvd_iff_mod_eq_zero, rw [←div_add_mod b (a ^ omega), mul_add, ←mul_assoc, ←opow_one_add, one_add_omega, add_left_cancel] at hab, cases eq_zero_or_opow_omega_le_of_mul_eq_right hab with hab hab, { exact hab }, refine (not_lt_of_le hab (mod_lt b (opow_ne_zero omega _))).elim, rwa ←ordinal.pos_iff_ne_zero }, cases h with c hc, rw [hc, ←mul_assoc, ←opow_one_add, one_add_omega] end theorem mul_le_right_iff_opow_omega_dvd {a b : ordinal} (ha : 0 < a) : a * b ≤ b ↔ a ^ omega ∣ b := by { rw ←mul_eq_right_iff_opow_omega_dvd, exact (mul_is_normal ha).le_iff_eq } theorem nfp_mul_opow_omega_add {a c : ordinal} (b) (ha : 0 < a) (hc : 0 < c) (hca : c ≤ a ^ omega) : nfp ((*) a) (a ^ omega * b + c) = a ^ omega.{u} * (succ b) := begin apply le_antisymm, { apply nfp_le_fp (mul_is_normal ha).monotone, { rw mul_succ, apply add_le_add_left hca }, { rw [←mul_assoc, ←opow_one_add, one_add_omega] } }, { cases mul_eq_right_iff_opow_omega_dvd.1 ((mul_is_normal ha).nfp_fp (a ^ omega * b + c)) with d hd, rw hd, apply mul_le_mul_left', have := le_nfp (has_mul.mul a) (a ^ omega * b + c), rw hd at this, have := (add_lt_add_left hc (a ^ omega * b)).trans_le this, rw [add_zero, mul_lt_mul_iff_left (opow_pos omega ha)] at this, rwa succ_le_iff } end theorem deriv_mul_eq_opow_omega_mul {a : ordinal.{u}} (ha : 0 < a) (b) : deriv ((*) a) b = a ^ omega * b := begin revert b, rw [←funext_iff, is_normal.eq_iff_zero_and_succ (deriv_is_normal _) (mul_is_normal (opow_pos omega ha))], refine ⟨_, λ c h, _⟩, { rw [deriv_zero, nfp_mul_zero, mul_zero] }, { rw [deriv_succ, h], exact nfp_mul_opow_omega_add c ha zero_lt_one (one_le_iff_pos.2 (opow_pos _ ha)) }, end end ordinal
47ab0178ee18397ce6b4034e59e82aa93f9e6329
3f7026ea8bef0825ca0339a275c03b911baef64d
/src/linear_algebra/sesquilinear_form.lean
837c811e3deb5e3493192b686e78a0b1a93e7954
[ "Apache-2.0" ]
permissive
rspencer01/mathlib
b1e3afa5c121362ef0881012cc116513ab09f18c
c7d36292c6b9234dc40143c16288932ae38fdc12
refs/heads/master
1,595,010,346,708
1,567,511,503,000
1,567,511,503,000
206,071,681
0
0
Apache-2.0
1,567,513,643,000
1,567,513,643,000
null
UTF-8
Lean
false
false
8,637
lean
/- Copyright (c) 2018 Andreas Swerdlow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Andreas Swerdlow -/ import algebra.module ring_theory.maps /-! # Sesquilinear form This file defines a bilinear form over a module. The definition requires a ring antiautomorphism on the scalar ring, which comes from the file ring_theory.involution. Basic ideas such as orthogonality are also introduced. A sesquilinear form on an R-module V, is a function from V x V to R, that is linear in the first argument and antilinear in the second, with respect to an antiautomorphism on R (an antiisomorphism from R to R). ## Notations Given any term S of type sesq_form, due to a coercion, can use the notation B x y to refer to the function field, ie. S x y = S.bilin x y. ## References * https://en.wikipedia.org/wiki/Sesquilinear_form#Over_arbitrary_rings ## Tags Sesquilinear form, -/ open ring_anti_equiv universes u v /-- A sesquilinear form over a module -/ structure sesq_form (α : Type u) (β : Type v) [ring α] (I : ring_anti_equiv α α) [add_comm_group β] [module α β] := (sesq : β → β → α) (sesq_add_left : ∀ (x y z : β), sesq (x + y) z = sesq x z + sesq y z) (sesq_smul_left : ∀ (a : α) (x y : β), sesq (a • x) y = a * (sesq x y)) (sesq_add_right : ∀ (x y z : β), sesq x (y + z) = sesq x y + sesq x z) (sesq_smul_right : ∀ (a : α) (x y : β), sesq x (a • y) = (I a) * (sesq x y)) namespace sesq_form variables {α : Type u} {β : Type v} [ring α] [add_comm_group β] [module α β] {I : ring_anti_equiv α α} {S : sesq_form α β I} instance : has_coe_to_fun (sesq_form α β I) := ⟨_, λ S, S.sesq⟩ lemma add_left (x y z : β) : S (x + y) z = S x z + S y z := sesq_add_left S x y z lemma smul_left (a : α) (x y : β) : S (a • x) y = a * (S x y) := sesq_smul_left S a x y lemma add_right (x y z : β) : S x (y + z) = S x y + S x z := sesq_add_right S x y z lemma smul_right (a : α) (x y : β) : S x (a • y) = (I a) * (S x y) := sesq_smul_right S a x y lemma zero_left (x : β) : S 0 x = 0 := by {rw [←@zero_smul α _ _ _ _ (0 : β), smul_left, zero_mul]} lemma zero_right (x : β) : S x 0 = 0 := by rw [←@zero_smul _ _ _ _ _ (0 : β), smul_right, map_zero, ring.zero_mul] lemma neg_left (x y : β) : S (-x) y = -(S x y) := by rw [←@neg_one_smul α _ _, smul_left, neg_one_mul] lemma neg_right (x y : β) : S x (-y) = -(S x y) := by rw [←@neg_one_smul α _ _, smul_right, map_neg_one, neg_one_mul] lemma sub_left (x y z : β) : S (x - y) z = S x z - S y z := by rw [sub_eq_add_neg, add_left, neg_left]; refl lemma sub_right (x y z : β) : S x (y - z) = S x y - S x z := by rw [sub_eq_add_neg, add_right, neg_right]; refl variable {D : sesq_form α β I} @[extensionality] lemma ext (H : ∀ (x y : β), S x y = D x y) : S = D := by {cases S, cases D, congr, funext, exact H _ _} instance : add_comm_group (sesq_form α β I) := { add := λ S D, { sesq := λ x y, S x y + D x y, sesq_add_left := λ x y z, by {rw add_left, rw add_left, simp}, sesq_smul_left := λ a x y, by {rw [smul_left, smul_left, mul_add]}, sesq_add_right := λ x y z, by {rw add_right, rw add_right, simp}, sesq_smul_right := λ a x y, by {rw [smul_right, smul_right, mul_add]} }, add_assoc := by {intros, ext, unfold coe_fn has_coe_to_fun.coe sesq coe_fn has_coe_to_fun.coe sesq, rw add_assoc}, zero := { sesq := λ x y, 0, sesq_add_left := λ x y z, (add_zero 0).symm, sesq_smul_left := λ a x y, (mul_zero a).symm, sesq_add_right := λ x y z, (zero_add 0).symm, sesq_smul_right := λ a x y, (mul_zero (I a)).symm }, zero_add := by {intros, ext, unfold coe_fn has_coe_to_fun.coe sesq, rw zero_add}, add_zero := by {intros, ext, unfold coe_fn has_coe_to_fun.coe sesq, rw add_zero}, neg := λ S, { sesq := λ x y, - (S.1 x y), sesq_add_left := λ x y z, by rw [sesq_add_left, neg_add], sesq_smul_left := λ a x y, by rw [sesq_smul_left, mul_neg_eq_neg_mul_symm], sesq_add_right := λ x y z, by rw [sesq_add_right, neg_add], sesq_smul_right := λ a x y, by rw [sesq_smul_right, mul_neg_eq_neg_mul_symm] }, add_left_neg := by {intros, ext, unfold coe_fn has_coe_to_fun.coe sesq, rw neg_add_self}, add_comm := by {intros, ext, unfold coe_fn has_coe_to_fun.coe sesq, rw add_comm} } section variables {χ : Type*} [comm_ring χ] [module χ β] {J : ring_anti_equiv χ χ} (F : sesq_form χ β J) (f : β → β) instance to_module : module χ (sesq_form χ β J) := { smul := λ c S, { sesq := λ x y, c * S x y, sesq_add_left := λ x y z, by {unfold coe_fn has_coe_to_fun.coe sesq, rw [sesq_add_left, left_distrib]}, sesq_smul_left := λ a x y, by {unfold coe_fn has_coe_to_fun.coe sesq, rw [sesq_smul_left, ←mul_assoc, mul_comm c, mul_assoc]}, sesq_add_right := λ x y z, by {unfold coe_fn has_coe_to_fun.coe sesq, rw [sesq_add_right, left_distrib]}, sesq_smul_right := λ a x y, by {unfold coe_fn has_coe_to_fun.coe sesq, rw [sesq_smul_right, ←mul_assoc, mul_comm c, mul_assoc], refl} }, smul_add := λ c S D, by {ext, unfold coe_fn has_coe_to_fun.coe sesq, rw left_distrib}, add_smul := λ c S D, by {ext, unfold coe_fn has_coe_to_fun.coe sesq, rw right_distrib}, mul_smul := λ a c D, by {ext, unfold coe_fn has_coe_to_fun.coe sesq, rw mul_assoc}, one_smul := λ S, by {ext, unfold coe_fn has_coe_to_fun.coe sesq, rw one_mul}, zero_smul := λ S, by {ext, unfold coe_fn has_coe_to_fun.coe sesq, rw zero_mul}, smul_zero := λ S, by {ext, unfold coe_fn has_coe_to_fun.coe sesq, rw mul_zero} } end /-- The proposition that two elements of a sesquilinear form space are orthogonal -/ def is_ortho (S : sesq_form α β I) (x y : β) : Prop := S x y = 0 lemma ortho_zero (x : β) : is_ortho S (0 : β) x := zero_left x section variables {γ : Type*} [domain γ] [module γ β] {K : ring_anti_equiv γ γ} {G : sesq_form γ β K} theorem ortho_smul_left {x y : β} {a : γ} (ha : a ≠ 0) : (is_ortho G x y) ↔ (is_ortho G (a • x) y) := begin dunfold is_ortho, split; intro H, { rw [smul_left, H, ring.mul_zero] }, { rw [smul_left, mul_eq_zero] at H, cases H, { trivial }, { exact H }} end theorem ortho_smul_right {x y : β} {a : γ} (ha : a ≠ 0) : (is_ortho G x y) ↔ (is_ortho G x (a • y)) := begin dunfold is_ortho, split; intro H, { rw [smul_right, H, ring.mul_zero] }, { rw [smul_right, mul_eq_zero] at H, cases H, { rw map_zero_iff at H, trivial }, { exact H }} end end end sesq_form namespace refl_sesq_form open refl_sesq_form sesq_form variables {α : Type*} {β : Type*} [ring α] [add_comm_group β] [module α β] {I : ring_anti_equiv α α} {S : sesq_form α β I} /-- The proposition that a sesquilinear form is reflexive -/ def is_refl (S : sesq_form α β I) : Prop := ∀ (x y : β), S x y = 0 → S y x = 0 variable (H : is_refl S) lemma eq_zero : ∀ {x y : β}, S x y = 0 → S y x = 0 := λ x y, H x y lemma ortho_sym {x y : β} : is_ortho S x y ↔ is_ortho S y x := ⟨eq_zero H, eq_zero H⟩ end refl_sesq_form namespace sym_sesq_form open sym_sesq_form sesq_form variables {α : Type*} {β : Type*} [ring α] [add_comm_group β] [module α β] {I : ring_anti_equiv α α} {S : sesq_form α β I} /-- The proposition that a sesquilinear form is symmetric -/ def is_sym (S : sesq_form α β I) : Prop := ∀ (x y : β), I (S x y) = S y x variable (H : is_sym S) include H lemma sym (x y : β) : I (S x y) = S y x := H x y lemma is_refl : refl_sesq_form.is_refl S := λ x y H1, by rw [←H, map_zero_iff, H1] lemma ortho_sym {x y : β} : is_ortho S x y ↔ is_ortho S y x := refl_sesq_form.ortho_sym (is_refl H) end sym_sesq_form namespace alt_sesq_form open alt_sesq_form sesq_form variables {α : Type*} {β : Type*} [ring α] [add_comm_group β] [module α β] {I : ring_anti_equiv α α} {S : sesq_form α β I} /-- The proposition that a sesquilinear form is alternating -/ def is_alt (S : sesq_form α β I) : Prop := ∀ (x : β), S x x = 0 variable (H : is_alt S) include H lemma self_eq_zero (x : β) : S x x = 0 := H x lemma neg (x y : β) : - S x y = S y x := begin have H1 : S (x + y) (x + y) = 0, { exact self_eq_zero H (x + y) }, rw [add_left, add_right, add_right, self_eq_zero H, self_eq_zero H, ring.zero_add, ring.add_zero, add_eq_zero_iff_neg_eq] at H1, exact H1, end end alt_sesq_form
35f38fbf919fefe2c1631db153456fa67bdd6f15
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/algebra/geom_sum.lean
33fe7c6d9a06c65acead687ff7d84b33e6672ed8
[ "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
15,384
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland -/ import algebra.group_with_zero.power import algebra.big_operators.order import algebra.big_operators.ring import algebra.big_operators.intervals /-! # Partial sums of geometric series This file determines the values of the geometric series $\sum_{i=0}^{n-1} x^i$ and $\sum_{i=0}^{n-1} x^i y^{n-1-i}$ and variants thereof. We also provide some bounds on the "geometric" sum of `a/b^i` where `a b : ℕ`. ## Main definitions * `geom_sum` defines for each $x$ in a semiring and each natural number $n$ the partial sum $\sum_{i=0}^{n-1} x^i$ of the geometric series. * `geom_sum₂` defines for each $x,y$ in a semiring and each natural number $n$ the partial sum $\sum_{i=0}^{n-1} x^i y^{n-1-i}$ of the geometric series. ## Main statements * `geom_sum_Ico` proves that $\sum_{i=m}^{n-1} x^i=\frac{x^n-x^m}{x-1}$ in a division ring. * `geom_sum₂_Ico` proves that $\sum_{i=m}^{n-1} x^i=\frac{x^n-y^{n-m}x^m}{x-y}$ in a field. Several variants are recorded, generalising in particular to the case of a noncommutative ring in which `x` and `y` commute. Even versions not using division or subtraction, valid in each semiring, are recorded. -/ universe u variable {α : Type u} open finset opposite open_locale big_operators /-- Sum of the finite geometric series $\sum_{i=0}^{n-1} x^i$. -/ def geom_sum [semiring α] (x : α) (n : ℕ) := ∑ i in range n, x ^ i theorem geom_sum_def [semiring α] (x : α) (n : ℕ) : geom_sum x n = ∑ i in range n, x ^ i := rfl @[simp] theorem geom_sum_zero [semiring α] (x : α) : geom_sum x 0 = 0 := rfl @[simp] theorem geom_sum_one [semiring α] (x : α) : geom_sum x 1 = 1 := by { rw [geom_sum_def, sum_range_one, pow_zero] } @[simp] lemma op_geom_sum [ring α] (x : α) (n : ℕ) : op (geom_sum x n) = geom_sum (op x) n := by simp [geom_sum_def] /-- Sum of the finite geometric series $\sum_{i=0}^{n-1} x^i y^{n-1-i}$. -/ def geom_sum₂ [semiring α] (x y : α) (n : ℕ) := ∑ i in range n, x ^ i * (y ^ (n - 1 - i)) theorem geom_sum₂_def [semiring α] (x y : α) (n : ℕ) : geom_sum₂ x y n = ∑ i in range n, x ^ i * y ^ (n - 1 - i) := rfl @[simp] theorem geom_sum₂_zero [semiring α] (x y : α) : geom_sum₂ x y 0 = 0 := rfl @[simp] theorem geom_sum₂_one [semiring α] (x y : α) : geom_sum₂ x y 1 = 1 := by { have : 1 - 1 - 0 = 0 := rfl, rw [geom_sum₂_def, sum_range_one, this, pow_zero, pow_zero, mul_one] } @[simp] lemma op_geom_sum₂ [ring α] (x y : α) (n : ℕ) : op (geom_sum₂ x y n) = geom_sum₂ (op y) (op x) n := begin simp only [geom_sum₂_def, op_sum, op_mul, op_pow], rw ← sum_range_reflect, refine sum_congr rfl (λ j j_in, _), rw [mem_range, nat.lt_iff_add_one_le] at j_in, congr, apply nat.sub_sub_self, exact nat.le_sub_right_of_add_le j_in end @[simp] theorem geom_sum₂_with_one [semiring α] (x : α) (n : ℕ) : geom_sum₂ x 1 n = geom_sum x n := sum_congr rfl (λ i _, by { rw [one_pow, mul_one] }) /-- $x^n-y^n = (x-y) \sum x^ky^{n-1-k}$ reformulated without `-` signs. -/ protected theorem commute.geom_sum₂_mul_add [semiring α] {x y : α} (h : commute x y) (n : ℕ) : (geom_sum₂ (x + y) y n) * x + y ^ n = (x + y) ^ n := begin let f := λ (m i : ℕ), (x + y) ^ i * y ^ (m - 1 - i), change (∑ i in range n, (f n) i) * x + y ^ n = (x + y) ^ n, induction n with n ih, { rw [range_zero, sum_empty, zero_mul, zero_add, pow_zero, pow_zero] }, { have f_last : f (n + 1) n = (x + y) ^ n := by { dsimp [f], rw [nat.sub_sub, nat.add_comm, nat.sub_self, pow_zero, mul_one] }, have f_succ : ∀ i, i ∈ range n → f (n + 1) i = y * f n i := λ i hi, by { dsimp [f], have : commute y ((x + y) ^ i) := (h.symm.add_right (commute.refl y)).pow_right i, rw [← mul_assoc, this.eq, mul_assoc, ← pow_succ y (n - 1 - i)], congr' 2, rw [nat.add_sub_cancel, nat.sub_sub, add_comm 1 i], have : i + 1 + (n - (i + 1)) = n := nat.add_sub_of_le (mem_range.mp hi), rw [add_comm (i + 1)] at this, rw [← this, nat.add_sub_cancel, add_comm i 1, ← add_assoc, nat.add_sub_cancel] }, rw [pow_succ (x + y), add_mul, sum_range_succ_comm, add_mul, f_last, add_assoc], rw (((commute.refl x).add_right h).pow_right n).eq, congr' 1, rw [sum_congr rfl f_succ, ← mul_sum, pow_succ y, mul_assoc, ← mul_add y, ih] } end theorem geom_sum₂_self {α : Type*} [comm_ring α] (x : α) (n : ℕ) : geom_sum₂ x x n = n * x ^ (n-1) := calc ∑ i in finset.range n, x ^ i * x ^ (n - 1 - i) = ∑ i in finset.range n, x ^ (i + (n - 1 - i)) : by simp_rw [← pow_add] ... = ∑ i in finset.range n, x ^ (n - 1) : finset.sum_congr rfl (λ i hi, congr_arg _ $ nat.add_sub_cancel' $ nat.le_pred_of_lt $ finset.mem_range.1 hi) ... = (finset.range n).card • (x ^ (n - 1)) : finset.sum_const _ ... = n * x ^ (n - 1) : by rw [finset.card_range, nsmul_eq_mul] /-- $x^n-y^n = (x-y) \sum x^ky^{n-1-k}$ reformulated without `-` signs. -/ theorem geom_sum₂_mul_add [comm_semiring α] (x y : α) (n : ℕ) : (geom_sum₂ (x + y) y n) * x + y ^ n = (x + y) ^ n := (commute.all x y).geom_sum₂_mul_add n theorem geom_sum_mul_add [semiring α] (x : α) (n : ℕ) : (geom_sum (x + 1) n) * x + 1 = (x + 1) ^ n := begin have := (commute.one_right x).geom_sum₂_mul_add n, rw [one_pow, geom_sum₂_with_one] at this, exact this end protected theorem commute.geom_sum₂_mul [ring α] {x y : α} (h : commute x y) (n : ℕ) : (geom_sum₂ x y n) * (x - y) = x ^ n - y ^ n := begin have := (h.sub_left (commute.refl y)).geom_sum₂_mul_add n, rw [sub_add_cancel] at this, rw [← this, add_sub_cancel] end lemma commute.mul_neg_geom_sum₂ [ring α] {x y : α} (h : commute x y) (n : ℕ) : (y - x) * (geom_sum₂ x y n) = y ^ n - x ^ n := begin rw ← op_inj_iff, simp only [op_mul, op_sub, op_geom_sum₂, op_pow], exact (commute.op h.symm).geom_sum₂_mul n end lemma commute.mul_geom_sum₂ [ring α] {x y : α} (h : commute x y) (n : ℕ) : (x - y) * (geom_sum₂ x y n) = x ^ n - y ^ n := by rw [← neg_sub (y ^ n), ← h.mul_neg_geom_sum₂, ← neg_mul_eq_neg_mul_symm, neg_sub] theorem geom_sum₂_mul [comm_ring α] (x y : α) (n : ℕ) : (geom_sum₂ x y n) * (x - y) = x ^ n - y ^ n := (commute.all x y).geom_sum₂_mul n theorem geom_sum_mul [ring α] (x : α) (n : ℕ) : (geom_sum x n) * (x - 1) = x ^ n - 1 := begin have := (commute.one_right x).geom_sum₂_mul n, rw [one_pow, geom_sum₂_with_one] at this, exact this end lemma mul_geom_sum [ring α] (x : α) (n : ℕ) : (x - 1) * (geom_sum x n) = x ^ n - 1 := begin rw ← op_inj_iff, simpa using geom_sum_mul (op x) n, end theorem geom_sum_mul_neg [ring α] (x : α) (n : ℕ) : (geom_sum x n) * (1 - x) = 1 - x ^ n := begin have := congr_arg has_neg.neg (geom_sum_mul x n), rw [neg_sub, ← mul_neg_eq_neg_mul_symm, neg_sub] at this, exact this end lemma mul_neg_geom_sum [ring α] (x : α) (n : ℕ) : (1 - x) * (geom_sum x n) = 1 - x ^ n := begin rw ← op_inj_iff, simpa using geom_sum_mul_neg (op x) n, end protected theorem commute.geom_sum₂ [division_ring α] {x y : α} (h' : commute x y) (h : x ≠ y) (n : ℕ) : (geom_sum₂ x y n) = (x ^ n - y ^ n) / (x - y) := have x - y ≠ 0, by simp [*, -sub_eq_add_neg, sub_eq_iff_eq_add] at *, by rw [← h'.geom_sum₂_mul, mul_div_cancel _ this] theorem geom₂_sum [field α] {x y : α} (h : x ≠ y) (n : ℕ) : (geom_sum₂ x y n) = (x ^ n - y ^ n) / (x - y) := (commute.all x y).geom_sum₂ h n theorem geom_sum_eq [division_ring α] {x : α} (h : x ≠ 1) (n : ℕ) : (geom_sum x n) = (x ^ n - 1) / (x - 1) := have x - 1 ≠ 0, by simp [*, -sub_eq_add_neg, sub_eq_iff_eq_add] at *, by rw [← geom_sum_mul, mul_div_cancel _ this] protected theorem commute.mul_geom_sum₂_Ico [ring α] {x y : α} (h : commute x y) {m n : ℕ} (hmn : m ≤ n) : (x - y) * (∑ i in finset.Ico m n, x ^ i * y ^ (n - 1 - i)) = x ^ n - x ^ m * y ^ (n - m) := begin rw [sum_Ico_eq_sub _ hmn, ← geom_sum₂_def], have : ∑ k in range m, x ^ k * y ^ (n - 1 - k) = ∑ k in range m, x ^ k * (y ^ (n - m) * y ^ (m - 1 - k)), { refine sum_congr rfl (λ j j_in, _), rw ← pow_add, congr, rw [mem_range, nat.lt_iff_add_one_le, add_comm] at j_in, have h' : n - m + (m - (1 + j)) = n - (1 + j) := nat.sub_add_sub_cancel hmn j_in, rw [nat.sub_sub m, h', nat.sub_sub] }, rw this, simp_rw pow_mul_comm y (n-m) _, simp_rw ← mul_assoc, rw [← sum_mul, ← geom_sum₂_def, mul_sub, h.mul_geom_sum₂, ← mul_assoc, h.mul_geom_sum₂, sub_mul, ← pow_add, nat.add_sub_of_le hmn, sub_sub_sub_cancel_right (x ^ n) (x ^ m * y ^ (n - m)) (y ^ n)], end protected theorem commute.geom_sum₂_succ_eq {α : Type u} [ring α] {x y : α} (h : commute x y) {n : ℕ} : geom_sum₂ x y (n + 1) = x ^ n + y * (geom_sum₂ x y n) := begin simp_rw [geom_sum₂, mul_sum, sum_range_succ_comm, nat.add_succ_sub_one, add_zero, nat.sub_self, pow_zero, mul_one, add_right_inj, ←mul_assoc, (h.symm.pow_right _).eq, mul_assoc, ←pow_succ], refine sum_congr rfl (λ i hi, _), suffices : n - 1 - i + 1 = n - i, { rw this }, cases n, { exact absurd (list.mem_range.mp hi) i.not_lt_zero }, { rw [nat.sub_add_eq_add_sub (nat.le_pred_of_lt (list.mem_range.mp hi)), nat.sub_add_cancel (nat.succ_le_iff.mpr n.succ_pos)] }, end theorem geom_sum₂_succ_eq {α : Type u} [comm_ring α] (x y : α) {n : ℕ} : geom_sum₂ x y (n + 1) = x ^ n + y * (geom_sum₂ x y n) := (commute.all x y).geom_sum₂_succ_eq theorem mul_geom_sum₂_Ico [comm_ring α] (x y : α) {m n : ℕ} (hmn : m ≤ n) : (x - y) * (∑ i in finset.Ico m n, x ^ i * y ^ (n - 1 - i)) = x ^ n - x ^ m * y ^ (n - m) := (commute.all x y).mul_geom_sum₂_Ico hmn protected theorem commute.geom_sum₂_Ico_mul [ring α] {x y : α} (h : commute x y) {m n : ℕ} (hmn : m ≤ n) : (∑ i in finset.Ico m n, x ^ i * y ^ (n - 1 - i)) * (x - y) = x ^ n - y ^ (n - m) * x ^ m := begin rw ← op_inj_iff, simp only [op_sub, op_mul, op_pow, op_sum], have : ∑ k in Ico m n, op y ^ (n - 1 - k) * op x ^ k = ∑ k in Ico m n, op x ^ k * op y ^ (n - 1 - k), { refine sum_congr rfl (λ k k_in, _), apply commute.pow_pow (commute.op h.symm) }, rw this, exact (commute.op h).mul_geom_sum₂_Ico hmn end theorem geom_sum_Ico_mul [ring α] (x : α) {m n : ℕ} (hmn : m ≤ n) : (∑ i in finset.Ico m n, x ^ i) * (x - 1) = x^n - x^m := by rw [sum_Ico_eq_sub _ hmn, ← geom_sum_def, ← geom_sum_def, sub_mul, geom_sum_mul, geom_sum_mul, sub_sub_sub_cancel_right] theorem geom_sum_Ico_mul_neg [ring α] (x : α) {m n : ℕ} (hmn : m ≤ n) : (∑ i in finset.Ico m n, x ^ i) * (1 - x) = x^m - x^n := by rw [sum_Ico_eq_sub _ hmn, ← geom_sum_def, ← geom_sum_def, sub_mul, geom_sum_mul_neg, geom_sum_mul_neg, sub_sub_sub_cancel_left] protected theorem commute.geom_sum₂_Ico [division_ring α] {x y : α} (h : commute x y) (hxy : x ≠ y) {m n : ℕ} (hmn : m ≤ n) : ∑ i in finset.Ico m n, x ^ i * y ^ (n - 1 - i) = (x ^ n - y ^ (n - m) * x ^ m ) / (x - y) := have x - y ≠ 0, by simp [*, -sub_eq_add_neg, sub_eq_iff_eq_add] at *, by rw [← h.geom_sum₂_Ico_mul hmn, mul_div_cancel _ this] theorem geom_sum₂_Ico [field α] {x y : α} (hxy : x ≠ y) {m n : ℕ} (hmn : m ≤ n) : ∑ i in finset.Ico m n, x ^ i * y ^ (n - 1 - i) = (x ^ n - y ^ (n - m) * x ^ m ) / (x - y) := (commute.all x y).geom_sum₂_Ico hxy hmn theorem geom_sum_Ico [division_ring α] {x : α} (hx : x ≠ 1) {m n : ℕ} (hmn : m ≤ n) : ∑ i in finset.Ico m n, x ^ i = (x ^ n - x ^ m) / (x - 1) := by simp only [sum_Ico_eq_sub _ hmn, (geom_sum_def _ _).symm, geom_sum_eq hx, div_sub_div_same, sub_sub_sub_cancel_right] theorem geom_sum_Ico' [division_ring α] {x : α} (hx : x ≠ 1) {m n : ℕ} (hmn : m ≤ n) : ∑ i in finset.Ico m n, x ^ i = (x ^ m - x ^ n) / (1 - x) := by { simp only [geom_sum_Ico hx hmn], convert neg_div_neg_eq (x^m - x^n) (1-x); abel } lemma geom_sum_inv [division_ring α] {x : α} (hx1 : x ≠ 1) (hx0 : x ≠ 0) (n : ℕ) : (geom_sum x⁻¹ n) = (x - 1)⁻¹ * (x - x⁻¹ ^ n * x) := have h₁ : x⁻¹ ≠ 1, by rwa [inv_eq_one_div, ne.def, div_eq_iff_mul_eq hx0, one_mul], have h₂ : x⁻¹ - 1 ≠ 0, from mt sub_eq_zero.1 h₁, have h₃ : x - 1 ≠ 0, from mt sub_eq_zero.1 hx1, have h₄ : x * (x ^ n)⁻¹ = (x ^ n)⁻¹ * x := nat.rec_on n (by simp) (λ n h, by rw [pow_succ, mul_inv_rev₀, ←mul_assoc, h, mul_assoc, mul_inv_cancel hx0, mul_assoc, inv_mul_cancel hx0]), begin rw [geom_sum_eq h₁, div_eq_iff_mul_eq h₂, ← mul_right_inj' h₃, ← mul_assoc, ← mul_assoc, mul_inv_cancel h₃], simp [mul_add, add_mul, mul_inv_cancel hx0, mul_assoc, h₄, sub_eq_add_neg, add_comm, add_left_comm], end variables {β : Type*} theorem ring_hom.map_geom_sum [semiring α] [semiring β] (x : α) (n : ℕ) (f : α →+* β) : f (geom_sum x n) = geom_sum (f x) n := by simp [geom_sum_def, f.map_sum] theorem ring_hom.map_geom_sum₂ [semiring α] [semiring β] (x y : α) (n : ℕ) (f : α →+* β) : f (geom_sum₂ x y n) = geom_sum₂ (f x) (f y) n := by simp [geom_sum₂_def, f.map_sum] /-! ### Geometric sum with `ℕ`-division -/ lemma nat.pred_mul_geom_sum_le (a b n : ℕ) : (b - 1) * ∑ i in range n.succ, a/b^i ≤ a * b - a/b^n := calc (b - 1) * (∑ i in range n.succ, a/b^i) = ∑ i in range n, a/b^(i + 1) * b + a * b - (∑ i in range n, a/b^i + a/b^n) : by rw [nat.mul_sub_right_distrib, mul_comm, sum_mul, one_mul, sum_range_succ', sum_range_succ, pow_zero, nat.div_one] ... ≤ ∑ i in range n, a/b^i + a * b - (∑ i in range n, a/b^i + a/b^n) : begin refine nat.sub_le_sub_right (add_le_add_right (sum_le_sum $ λ i _, _) _) _, rw [pow_succ', ←nat.div_div_eq_div_mul], exact nat.div_mul_le_self _ _, end ... = a * b - a/b^n : nat.add_sub_add_left _ _ _ lemma nat.geom_sum_le {b : ℕ} (hb : 2 ≤ b) (a n : ℕ) : ∑ i in range n, a/b^i ≤ a * b/(b - 1) := begin refine (nat.le_div_iff_mul_le _ _ $ nat.sub_pos_of_lt hb).2 _, cases n, { rw [sum_range_zero, zero_mul], exact nat.zero_le _ }, rw mul_comm, exact (nat.pred_mul_geom_sum_le a b n).trans (nat.sub_le_self _ _), end lemma nat.geom_sum_Ico_le {b : ℕ} (hb : 2 ≤ b) (a n : ℕ) : ∑ i in Ico 1 n, a/b^i ≤ a/(b - 1) := begin cases n, { rw [Ico.eq_empty_of_le zero_le_one, sum_empty], exact nat.zero_le _ }, rw ←add_le_add_iff_left a, calc a + ∑ (i : ℕ) in Ico 1 n.succ, a/b^i = a/b^0 + ∑ (i : ℕ) in Ico 1 n.succ, a/b^i : by rw [pow_zero, nat.div_one] ... = ∑ i in range n.succ, a/b^i : begin rw [range_eq_Ico, ←finset.Ico.insert_succ_bot (nat.succ_pos _), sum_insert], exact λ h, zero_lt_one.not_le (Ico.mem.1 h).1, end ... ≤ a * b/(b - 1) : nat.geom_sum_le hb a _ ... = (a * 1 + a * (b - 1))/(b - 1) : by rw [←mul_add, nat.add_sub_cancel' (one_le_two.trans hb)] ... = a + a/(b - 1) : by rw [mul_one, nat.add_mul_div_right _ _ (nat.sub_pos_of_lt hb), add_comm] end
c507e9c59f51cf74019a94cb16176ddcd7a840ad
367134ba5a65885e863bdc4507601606690974c1
/src/control/traversable/lemmas.lean
01842944f38b2f2b69b073560381ee9dfdbe9c06
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
3,804
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon Lemmas about traversing collections. Inspired by: The Essence of the Iterator Pattern Jeremy Gibbons and Bruno César dos Santos Oliveira In Journal of Functional Programming. Vol. 19. No. 3&4. Pages 377−402. 2009. <http://www.cs.ox.ac.uk/jeremy.gibbons/publications/iterator.pdf> -/ import control.traversable.basic import control.applicative universe variables u open is_lawful_traversable open function (hiding comp) open functor attribute [functor_norm] is_lawful_traversable.naturality attribute [simp] is_lawful_traversable.id_traverse namespace traversable variable {t : Type u → Type u} variables [traversable t] [is_lawful_traversable t] variables F G : Type u → Type u variables [applicative F] [is_lawful_applicative F] variables [applicative G] [is_lawful_applicative G] variables {α β γ : Type u} variables g : α → F β variables h : β → G γ variables f : β → γ /-- The natural applicative transformation from the identity functor to `F`, defined by `pure : Π {α}, α → F α`. -/ def pure_transformation : applicative_transformation id F := { app := @pure F _, preserves_pure' := λ α x, rfl, preserves_seq' := λ α β f x, by simp; refl } @[simp] theorem pure_transformation_apply {α} (x : id α) : (pure_transformation F) x = pure x := rfl variables {F G} (x : t β) lemma map_eq_traverse_id : map f = @traverse t _ _ _ _ _ (id.mk ∘ f) := funext $ λ y, (traverse_eq_map_id f y).symm theorem map_traverse (x : t α) : map f <$> traverse g x = traverse (map f ∘ g) x := begin rw @map_eq_traverse_id t _ _ _ _ f, refine (comp_traverse (id.mk ∘ f) g x).symm.trans _, congr, apply comp.applicative_comp_id end theorem traverse_map (f : β → F γ) (g : α → β) (x : t α) : traverse f (g <$> x) = traverse (f ∘ g) x := begin rw @map_eq_traverse_id t _ _ _ _ g, refine (comp_traverse f (id.mk ∘ g) x).symm.trans _, congr, apply comp.applicative_id_comp end lemma pure_traverse (x : t α) : traverse pure x = (pure x : F (t α)) := by have : traverse pure x = pure (traverse id.mk x) := (naturality (pure_transformation F) id.mk x).symm; rwa id_traverse at this lemma id_sequence (x : t α) : sequence (id.mk <$> x) = id.mk x := by simp [sequence, traverse_map, id_traverse]; refl lemma comp_sequence (x : t (F (G α))) : sequence (comp.mk <$> x) = comp.mk (sequence <$> sequence x) := by simp [sequence, traverse_map]; rw ← comp_traverse; simp [map_id] lemma naturality' (η : applicative_transformation F G) (x : t (F α)) : η (sequence x) = sequence (@η _ <$> x) := by simp [sequence, naturality, traverse_map] @[functor_norm] lemma traverse_id : traverse id.mk = (id.mk : t α → id (t α)) := by ext; simp [id_traverse]; refl @[functor_norm] lemma traverse_comp (g : α → F β) (h : β → G γ) : traverse (comp.mk ∘ map h ∘ g) = (comp.mk ∘ map (traverse h) ∘ traverse g : t α → comp F G (t γ)) := by ext; simp [comp_traverse] lemma traverse_eq_map_id' (f : β → γ) : traverse (id.mk ∘ f) = id.mk ∘ (map f : t β → t γ) := by ext;rw traverse_eq_map_id -- @[functor_norm] lemma traverse_map' (g : α → β) (h : β → G γ) : traverse (h ∘ g) = (traverse h ∘ map g : t α → G (t γ)) := by ext; simp [traverse_map] lemma map_traverse' (g : α → G β) (h : β → γ) : traverse (map h ∘ g) = (map (map h) ∘ traverse g : t α → G (t γ)) := by ext; simp [map_traverse] lemma naturality_pf (η : applicative_transformation F G) (f : α → F β) : traverse (@η _ ∘ f) = @η _ ∘ (traverse f : t α → F (t β)) := by ext; simp [naturality] end traversable
7627ad079cea83b9956757980b65c42a19f6ac99
f5f7e6fae601a5fe3cac7cc3ed353ed781d62419
/src/data/hash_map.lean
cb28f4e732e74f52ea51426285838c9827f7aa8d
[ "Apache-2.0" ]
permissive
EdAyers/mathlib
9ecfb2f14bd6caad748b64c9c131befbff0fb4e0
ca5d4c1f16f9c451cf7170b10105d0051db79e1b
refs/heads/master
1,626,189,395,845
1,555,284,396,000
1,555,284,396,000
144,004,030
0
0
Apache-2.0
1,533,727,664,000
1,533,727,663,000
null
UTF-8
Lean
false
false
27,762
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, Mario Carneiro -/ import data.list.basic data.pnat data.array.lemmas universes u v w /-- `bucket_array α β` is the underlying data type for `hash_map α β`, an array of linked lists of key-value pairs. -/ def bucket_array (α : Type u) (β : α → Type v) (n : ℕ+) := array n.1 (list Σ a, β a) /-- Make a hash_map index from a `nat` hash value and a (positive) buffer size -/ def hash_map.mk_idx (n : ℕ+) (i : nat) : fin n.1 := ⟨i % n.1, nat.mod_lt _ n.2⟩ namespace bucket_array section parameters {α : Type u} {β : α → Type v} (hash_fn : α → nat) variables {n : ℕ+} (data : bucket_array α β n) /-- Read the bucket corresponding to an element -/ def read (a : α) : list Σ a, β a := let bidx := hash_map.mk_idx n (hash_fn a) in data.read bidx /-- Write the bucket corresponding to an element -/ def write (a : α) (l : list Σ a, β a) : bucket_array α β n := let bidx := hash_map.mk_idx n (hash_fn a) in data.write bidx l /-- Modify (read, apply `f`, and write) the bucket corresponding to an element -/ def modify (a : α) (f : list (Σ a, β a) → list (Σ a, β a)) : bucket_array α β n := let bidx := hash_map.mk_idx n (hash_fn a) in array.write data bidx (f (array.read data bidx)) /-- The list of all key-value pairs in the bucket list -/ def as_list : list Σ a, β a := data.to_list.join theorem mem_as_list {a : Σ a, β a} : a ∈ data.as_list ↔ ∃i, a ∈ array.read data i := have (∃ (l : list (Σ (a : α), β a)) (i : fin (n.val)), a ∈ l ∧ array.read data i = l) ↔ ∃ (i : fin (n.val)), a ∈ array.read data i, by rw exists_swap; exact exists_congr (λ i, by simp), by simp [as_list]; simpa [array.mem.def, and_comm] /-- Fold a function `f` over the key-value pairs in the bucket list -/ def foldl {δ : Type w} (d : δ) (f : δ → Π a, β a → δ) : δ := data.foldl d (λ b d, b.foldl (λ r a, f r a.1 a.2) d) theorem foldl_eq {δ : Type w} (d : δ) (f : δ → Π a, β a → δ) : data.foldl d f = data.as_list.foldl (λ r a, f r a.1 a.2) d := by rw [foldl, as_list, list.foldl_join, ← array.to_list_foldl] end end bucket_array namespace hash_map section parameters {α : Type u} {β : α → Type v} (hash_fn : α → nat) /-- Insert the pair `⟨a, b⟩` into the correct location in the bucket array (without checking for duplication) -/ def reinsert_aux {n} (data : bucket_array α β n) (a : α) (b : β a) : bucket_array α β n := data.modify hash_fn a (λl, ⟨a, b⟩ :: l) parameter [decidable_eq α] /-- Search a bucket for a key `a` and return the value -/ def find_aux (a : α) : list (Σ a, β a) → option (β a) | [] := none | (⟨a',b⟩::t) := if h : a' = a then some (eq.rec_on h b) else find_aux t theorem find_aux_iff {a : α} {b : β a} : Π {l : list Σ a, β a}, (l.map sigma.fst).nodup → (find_aux a l = some b ↔ sigma.mk a b ∈ l) | [] nd := ⟨λn, by injection n, false.elim⟩ | (⟨a',b'⟩::t) nd := begin by_cases a' = a, { clear find_aux_iff, subst h, suffices : b' = b ↔ b' = b ∨ sigma.mk a' b ∈ t, {simpa [find_aux, eq_comm]}, refine (or_iff_left_of_imp (λ m, _)).symm, have : a' ∉ t.map sigma.fst, from list.not_mem_of_nodup_cons nd, exact this.elim (list.mem_map_of_mem sigma.fst m) }, { have : sigma.mk a b ≠ ⟨a', b'⟩, { intro e, injection e with e, exact h e.symm }, simp at nd, simp [find_aux, h, ne.symm h, find_aux_iff, nd] } end /-- Returns `tt` if the bucket `l` contains the key `a` -/ def contains_aux (a : α) (l : list Σ a, β a) : bool := (find_aux a l).is_some theorem contains_aux_iff {a : α} {l : list Σ a, β a} (nd : (l.map sigma.fst).nodup) : contains_aux a l ↔ a ∈ l.map sigma.fst := begin unfold contains_aux, cases h : find_aux a l with b; simp, { assume (b : β a) (m : sigma.mk a b ∈ l), rw (find_aux_iff nd).2 m at h, contradiction }, { show ∃ (b : β a), sigma.mk a b ∈ l, exact ⟨_, (find_aux_iff nd).1 h⟩ }, end /-- Modify a bucket to replace a value in the list. Leaves the list unchanged if the key is not found. -/ def replace_aux (a : α) (b : β a) : list (Σ a, β a) → list (Σ a, β a) | [] := [] | (⟨a', b'⟩::t) := if a' = a then ⟨a, b⟩::t else ⟨a', b'⟩ :: replace_aux t /-- Modify a bucket to remove a key, if it exists. -/ def erase_aux (a : α) : list (Σ a, β a) → list (Σ a, β a) | [] := [] | (⟨a', b'⟩::t) := if a' = a then t else ⟨a', b'⟩ :: erase_aux t /-- The predicate `valid bkts sz` means that `bkts` satisfies the `hash_map` invariants: There are exactly `sz` elements in it, every pair is in the bucket determined by its key and the hash function, and no key appears multiple times in the list. -/ structure valid {n} (bkts : bucket_array α β n) (sz : nat) : Prop := (len : bkts.as_list.length = sz) (idx : ∀ {i} {a : Σ a, β a}, a ∈ array.read bkts i → mk_idx n (hash_fn a.1) = i) (nodup : ∀i, ((array.read bkts i).map sigma.fst).nodup) theorem valid.idx_enum {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) {i l} (he : (i, l) ∈ bkts.to_list.enum) {a} {b : β a} (hl : sigma.mk a b ∈ l) : ∃ h, mk_idx n (hash_fn a) = ⟨i, h⟩ := (array.mem_to_list_enum.mp he).imp (λ h e, by subst e; exact v.idx hl) theorem valid.idx_enum_1 {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) {i l} (he : (i, l) ∈ bkts.to_list.enum) {a} {b : β a} (hl : sigma.mk a b ∈ l) : (mk_idx n (hash_fn a)).1 = i := let ⟨h, e⟩ := v.idx_enum _ he hl in by rw e; refl theorem valid.as_list_nodup {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) : (bkts.as_list.map sigma.fst).nodup := begin suffices : (bkts.to_list.map (list.map sigma.fst)).pairwise list.disjoint, { simp [bucket_array.as_list, list.nodup_join, this], change ∀ l s, array.mem s bkts → list.map sigma.fst s = l → l.nodup, introv m e, subst e, cases m with i e, subst e, apply v.nodup }, rw [← list.enum_map_snd bkts.to_list, list.pairwise_map, list.pairwise_map], have : (bkts.to_list.enum.map prod.fst).nodup := by simp [list.nodup_range], refine list.pairwise.imp_of_mem _ ((list.pairwise_map _).1 this), rw prod.forall, intros i l₁, rw prod.forall, intros j l₂ me₁ me₂ ij, simp [list.disjoint], intros a b ml₁ b' ml₂, apply ij, rwa [← v.idx_enum_1 _ me₁ ml₁, ← v.idx_enum_1 _ me₂ ml₂] end theorem mk_as_list (n : ℕ+) : bucket_array.as_list (mk_array n.1 [] : bucket_array α β n) = [] := list.eq_nil_iff_forall_not_mem.mpr $ λ x m, let ⟨i, h⟩ := (bucket_array.mem_as_list _).1 m in h theorem mk_valid (n : ℕ+) : @valid n (mk_array n.1 []) 0 := ⟨by simp [mk_as_list], λ i a h, by cases h, λ i, list.nodup_nil⟩ theorem valid.find_aux_iff {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) {a : α} {b : β a} : find_aux a (bkts.read hash_fn a) = some b ↔ sigma.mk a b ∈ bkts.as_list := (find_aux_iff (v.nodup _)).trans $ by rw bkts.mem_as_list; exact ⟨λ h, ⟨_, h⟩, λ ⟨i, h⟩, (v.idx h).symm ▸ h⟩ theorem valid.contains_aux_iff {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) (a : α) : contains_aux a (bkts.read hash_fn a) ↔ a ∈ bkts.as_list.map sigma.fst := by simp [contains_aux, option.is_some_iff_exists, v.find_aux_iff hash_fn] section parameters {n : ℕ+} {bkts : bucket_array α β n} {bidx : fin n.1} {f : list (Σ a, β a) → list (Σ a, β a)} (u v1 v2 w : list Σ a, β a) local notation `L` := array.read bkts bidx private def bkts' : bucket_array α β n := array.write bkts bidx (f L) variables (hl : L = u ++ v1 ++ w) (hfl : f L = u ++ v2 ++ w) include hl hfl theorem append_of_modify : ∃ u' w', bkts.as_list = u' ++ v1 ++ w' ∧ bkts'.as_list = u' ++ v2 ++ w' := begin unfold bucket_array.as_list, have h : bidx.1 < bkts.to_list.length, {simp [bidx.2]}, refine ⟨(bkts.to_list.take bidx.1).join ++ u, w ++ (bkts.to_list.drop (bidx.1+1)).join, _, _⟩, { conv { to_lhs, rw [← list.take_append_drop bidx.1 bkts.to_list, list.drop_eq_nth_le_cons h], simp [hl] }, simp }, { conv { to_lhs, rw [bkts', array.write_to_list, list.update_nth_eq_take_cons_drop _ h], simp [hfl] }, simp } end variables (hvnd : (v2.map sigma.fst).nodup) (hal : ∀ (a : Σ a, β a), a ∈ v2 → mk_idx n (hash_fn a.1) = bidx) (djuv : (u.map sigma.fst).disjoint (v2.map sigma.fst)) (djwv : (w.map sigma.fst).disjoint (v2.map sigma.fst)) include hvnd hal djuv djwv theorem valid.modify {sz : ℕ} (v : valid bkts sz) : sz + v2.length ≥ v1.length ∧ valid bkts' (sz + v2.length - v1.length) := begin rcases append_of_modify u v1 v2 w hl hfl with ⟨u', w', e₁, e₂⟩, rw [← v.len, e₁], suffices : valid bkts' (u' ++ v2 ++ w').length, { simpa [ge, nat.le_add_right, nat.add_sub_cancel_left] }, refine ⟨congr_arg _ e₂, λ i a, _, λ i, _⟩, { by_cases bidx = i, { subst i, rw [bkts', array.read_write, hfl], have := @valid.idx _ _ _ v bidx a, simp only [hl, list.mem_append, or_imp_distrib, forall_and_distrib] at this ⊢, exact ⟨⟨this.1.1, hal _⟩, this.2⟩ }, { rw [bkts', array.read_write_of_ne _ _ h], apply v.idx } }, { by_cases bidx = i, { subst i, rw [bkts', array.read_write, hfl], have := @valid.nodup _ _ _ v bidx, simp [hl, list.nodup_append] at this, simp [list.nodup_append, this, hvnd, djuv, djwv.symm] }, { rw [bkts', array.read_write_of_ne _ _ h], apply v.nodup } } end end theorem valid.replace_aux (a : α) (b : β a) : Π (l : list (Σ a, β a)), a ∈ l.map sigma.fst → ∃ (u w : list Σ a, β a) b', l = u ++ [⟨a, b'⟩] ++ w ∧ replace_aux a b l = u ++ [⟨a, b⟩] ++ w | [] := false.elim | (⟨a', b'⟩::t) := begin by_cases e : a' = a, { subst a', suffices : ∃ u w (b'' : β a), sigma.mk a b' :: t = u ++ ⟨a, b''⟩ :: w ∧ replace_aux a b (⟨a, b'⟩ :: t) = u ++ ⟨a, b⟩ :: w, {simpa}, refine ⟨[], t, b', _⟩, simp [replace_aux] }, { suffices : ∀ (x : β a) (_ : sigma.mk a x ∈ t), ∃ u w (b'' : β a), sigma.mk a' b' :: t = u ++ ⟨a, b''⟩ :: w ∧ sigma.mk a' b' :: replace_aux a b t = u ++ ⟨a, b⟩ :: w, { simpa [replace_aux, ne.symm e, e] }, intros x m, have IH : ∀ (x : β a) (_ : sigma.mk a x ∈ t), ∃ u w (b'' : β a), t = u ++ ⟨a, b''⟩ :: w ∧ replace_aux a b t = u ++ ⟨a, b⟩ :: w, { simpa using valid.replace_aux t }, rcases IH x m with ⟨u, w, b'', hl, hfl⟩, exact ⟨⟨a', b'⟩ :: u, w, b'', by simp [hl, hfl.symm, ne.symm e]⟩ } end theorem valid.replace {n : ℕ+} {bkts : bucket_array α β n} {sz : ℕ} (a : α) (b : β a) (Hc : contains_aux a (bkts.read hash_fn a)) (v : valid bkts sz) : valid (bkts.modify hash_fn a (replace_aux a b)) sz := begin have nd := v.nodup (mk_idx n (hash_fn a)), rcases hash_map.valid.replace_aux a b (array.read bkts (mk_idx n (hash_fn a))) ((contains_aux_iff nd).1 Hc) with ⟨u, w, b', hl, hfl⟩, simp [hl, list.nodup_append] at nd, refine (v.modify hash_fn u [⟨a, b'⟩] [⟨a, b⟩] w hl hfl (list.nodup_singleton _) (λa' e, by simp at e; rw e) (λa' e1 e2, _) (λa' e1 e2, _)).2; { revert e1, simp [-sigma.exists] at e2, subst a', simp [nd] } end theorem valid.insert {n : ℕ+} {bkts : bucket_array α β n} {sz : ℕ} (a : α) (b : β a) (Hnc : ¬ contains_aux a (bkts.read hash_fn a)) (v : valid bkts sz) : valid (reinsert_aux bkts a b) (sz+1) := begin have nd := v.nodup (mk_idx n (hash_fn a)), refine (v.modify hash_fn [] [] [⟨a, b⟩] (bkts.read hash_fn a) rfl rfl (list.nodup_singleton _) (λa' e, by simp at e; rw e) (λa', false.elim) (λa' e1 e2, _)).2, simp [-sigma.exists] at e2, subst a', exact Hnc ((contains_aux_iff nd).2 e1) end theorem valid.erase_aux (a : α) : Π (l : list (Σ a, β a)), a ∈ l.map sigma.fst → ∃ (u w : list Σ a, β a) b, l = u ++ [⟨a, b⟩] ++ w ∧ erase_aux a l = u ++ [] ++ w | [] := false.elim | (⟨a', b'⟩::t) := begin by_cases e : a' = a, { subst a', simpa [erase_aux, and_comm] using show ∃ u w (x : β a), t = u ++ w ∧ sigma.mk a b' :: t = u ++ ⟨a, x⟩ :: w, from ⟨[], t, b', by simp⟩ }, { simp [erase_aux, e, ne.symm e], suffices : ∀ (b : β a) (_ : sigma.mk a b ∈ t), ∃ u w (x : β a), sigma.mk a' b' :: t = u ++ ⟨a, x⟩ :: w ∧ sigma.mk a' b' :: erase_aux a t = u ++ w, { simpa [replace_aux, ne.symm e, e] }, intros b m, have IH : ∀ (x : β a) (_ : sigma.mk a x ∈ t), ∃ u w (x : β a), t = u ++ ⟨a, x⟩ :: w ∧ erase_aux a t = u ++ w, { simpa using valid.erase_aux t }, rcases IH b m with ⟨u, w, b'', hl, hfl⟩, exact ⟨⟨a', b'⟩ :: u, w, b'', by simp [hl, hfl.symm]⟩ } end theorem valid.erase {n} {bkts : bucket_array α β n} {sz} (a : α) (Hc : contains_aux a (bkts.read hash_fn a)) (v : valid bkts sz) : valid (bkts.modify hash_fn a (erase_aux a)) (sz-1) := begin have nd := v.nodup (mk_idx n (hash_fn a)), rcases hash_map.valid.erase_aux a (array.read bkts (mk_idx n (hash_fn a))) ((contains_aux_iff nd).1 Hc) with ⟨u, w, b, hl, hfl⟩, refine (v.modify hash_fn u [⟨a, b⟩] [] w hl hfl list.nodup_nil _ _ _).2; { intros, simp at *; contradiction } end end end hash_map /-- A hash map data structure, representing a finite key-value map with key type `α` and value type `β` (which may depend on `α`). -/ structure hash_map (α : Type u) [decidable_eq α] (β : α → Type v) := (hash_fn : α → nat) (size : ℕ) (nbuckets : ℕ+) (buckets : bucket_array α β nbuckets) (is_valid : hash_map.valid hash_fn buckets size) /-- Construct an empty hash map with buffer size `nbuckets` (default 8). -/ def mk_hash_map {α : Type u} [decidable_eq α] {β : α → Type v} (hash_fn : α → nat) (nbuckets := 8) : hash_map α β := let n := if nbuckets = 0 then 8 else nbuckets in let nz : n > 0 := by abstract { cases nbuckets, {simp, tactic.comp_val}, simp [if_pos, nat.succ_ne_zero], apply nat.zero_lt_succ} in { hash_fn := hash_fn, size := 0, nbuckets := ⟨n, nz⟩, buckets := mk_array n [], is_valid := hash_map.mk_valid _ _ } namespace hash_map variables {α : Type u} {β : α → Type v} [decidable_eq α] /-- Return the value corresponding to a key, or `none` if not found -/ def find (m : hash_map α β) (a : α) : option (β a) := find_aux a (m.buckets.read m.hash_fn a) /-- Return `tt` if the key exists in the map -/ def contains (m : hash_map α β) (a : α) : bool := (m.find a).is_some instance : has_mem α (hash_map α β) := ⟨λa m, m.contains a⟩ /-- Fold a function over the key-value pairs in the map -/ def fold {δ : Type w} (m : hash_map α β) (d : δ) (f : δ → Π a, β a → δ) : δ := m.buckets.foldl d f /-- The list of key-value pairs in the map -/ def entries (m : hash_map α β) : list Σ a, β a := m.buckets.as_list /-- The list of keys in the map -/ def keys (m : hash_map α β) : list α := m.entries.map sigma.fst theorem find_iff (m : hash_map α β) (a : α) (b : β a) : m.find a = some b ↔ sigma.mk a b ∈ m.entries := m.is_valid.find_aux_iff _ theorem contains_iff (m : hash_map α β) (a : α) : m.contains a ↔ a ∈ m.keys := m.is_valid.contains_aux_iff _ _ theorem entries_empty (hash_fn : α → nat) (n) : (@mk_hash_map α _ β hash_fn n).entries = [] := by dsimp [entries, mk_hash_map]; rw mk_as_list theorem keys_empty (hash_fn : α → nat) (n) : (@mk_hash_map α _ β hash_fn n).keys = [] := by dsimp [keys]; rw entries_empty; refl theorem find_empty (hash_fn : α → nat) (n a) : (@mk_hash_map α _ β hash_fn n).find a = none := by induction h : (@mk_hash_map α _ β hash_fn n).find a; [refl, { have := (find_iff _ _ _).1 h, rw entries_empty at this, contradiction }] theorem not_contains_empty (hash_fn : α → nat) (n a) : ¬ (@mk_hash_map α _ β hash_fn n).contains a := by apply bool_iff_false.2; dsimp [contains]; rw [find_empty]; refl theorem insert_lemma (hash_fn : α → nat) {n n'} {bkts : bucket_array α β n} {sz} (v : valid hash_fn bkts sz) : valid hash_fn (bkts.foldl (mk_array _ [] : bucket_array α β n') (reinsert_aux hash_fn)) sz := begin suffices : ∀ (l : list Σ a, β a) (t : bucket_array α β n') sz, valid hash_fn t sz → ((l ++ t.as_list).map sigma.fst).nodup → valid hash_fn (l.foldl (λr (a : Σ a, β a), reinsert_aux hash_fn r a.1 a.2) t) (sz + l.length), { have p := this bkts.as_list _ _ (mk_valid _ _), rw [mk_as_list, list.append_nil, zero_add, v.len] at p, rw bucket_array.foldl_eq, exact p (v.as_list_nodup _) }, intro l, induction l with c l IH; intros t sz v nd, {exact v}, rw show sz + (c :: l).length = sz + 1 + l.length, by simp, rcases (show (l.map sigma.fst).nodup ∧ ((bucket_array.as_list t).map sigma.fst).nodup ∧ c.fst ∉ l.map sigma.fst ∧ c.fst ∉ (bucket_array.as_list t).map sigma.fst ∧ (l.map sigma.fst).disjoint ((bucket_array.as_list t).map sigma.fst), by simpa [list.nodup_append, not_or_distrib, and_comm, and.left_comm] using nd) with ⟨nd1, nd2, nm1, nm2, dj⟩, have v' := v.insert _ _ c.2 (λHc, nm2 $ (v.contains_aux_iff _ c.1).1 Hc), apply IH _ _ v', suffices : ∀ ⦃a : α⦄ (b : β a), sigma.mk a b ∈ l → ∀ (b' : β a), sigma.mk a b' ∈ (reinsert_aux hash_fn t c.1 c.2).as_list → false, { simpa [list.nodup_append, nd1, v'.as_list_nodup _, list.disjoint] }, intros a b m1 b' m2, rcases (reinsert_aux hash_fn t c.1 c.2).mem_as_list.1 m2 with ⟨i, im⟩, have : sigma.mk a b' ∉ array.read t i, { intro m3, have : a ∈ list.map sigma.fst t.as_list := list.mem_map_of_mem sigma.fst (t.mem_as_list.2 ⟨_, m3⟩), exact dj (list.mem_map_of_mem sigma.fst m1) this }, by_cases h : mk_idx n' (hash_fn c.1) = i, { subst h, have e : sigma.mk a b' = ⟨c.1, c.2⟩, { simpa [reinsert_aux, bucket_array.modify, array.read_write, this] using im }, injection e with e, subst a, exact nm1.elim (@list.mem_map_of_mem _ _ sigma.fst _ _ m1) }, { apply this, simpa [reinsert_aux, bucket_array.modify, array.read_write_of_ne _ _ h] using im } end /-- Insert a key-value pair into the map. (Modifies `m` in-place when applicable) -/ def insert : Π (m : hash_map α β) (a : α) (b : β a), hash_map α β | ⟨hash_fn, size, n, buckets, v⟩ a b := let bkt := buckets.read hash_fn a in if hc : contains_aux a bkt then { hash_fn := hash_fn, size := size, nbuckets := n, buckets := buckets.modify hash_fn a (replace_aux a b), is_valid := v.replace _ a b hc } else let size' := size + 1, buckets' := buckets.modify hash_fn a (λl, ⟨a, b⟩::l), valid' := v.insert _ a b hc in if size' ≤ n.1 then { hash_fn := hash_fn, size := size', nbuckets := n, buckets := buckets', is_valid := valid' } else let n' : ℕ+ := ⟨n.1 * 2, mul_pos n.2 dec_trivial⟩, buckets'' : bucket_array α β n' := buckets'.foldl (mk_array _ []) (reinsert_aux hash_fn) in { hash_fn := hash_fn, size := size', nbuckets := n', buckets := buckets'', is_valid := insert_lemma _ valid' } theorem mem_insert : Π (m : hash_map α β) (a b a' b'), (sigma.mk a' b' : sigma β) ∈ (m.insert a b).entries ↔ if a = a' then b == b' else sigma.mk a' b' ∈ m.entries | ⟨hash_fn, size, n, bkts, v⟩ a b a' b' := begin let bkt := bkts.read hash_fn a, have nd : (bkt.map sigma.fst).nodup := v.nodup (mk_idx n (hash_fn a)), have lem : Π (bkts' : bucket_array α β n) (v1 u w) (hl : bucket_array.as_list bkts = u ++ v1 ++ w) (hfl : bucket_array.as_list bkts' = u ++ [⟨a, b⟩] ++ w) (veq : (v1 = [] ∧ ¬ contains_aux a bkt) ∨ ∃b'', v1 = [⟨a, b''⟩]), sigma.mk a' b' ∈ bkts'.as_list ↔ if a = a' then b == b' else sigma.mk a' b' ∈ bkts.as_list, { intros bkts' v1 u w hl hfl veq, rw [hl, hfl], by_cases h : a = a', { subst a', suffices : b = b' ∨ sigma.mk a b' ∈ u ∨ sigma.mk a b' ∈ w ↔ b = b', { simpa [eq_comm, or.left_comm] }, refine or_iff_left_of_imp (not.elim $ not_or_distrib.2 _), rcases veq with ⟨rfl, Hnc⟩ | ⟨b'', rfl⟩, { have na := (not_iff_not_of_iff $ v.contains_aux_iff _ _).1 Hnc, simp [hl, not_or_distrib] at na, simp [na] }, { have nd' := v.as_list_nodup _, simp [hl, list.nodup_append] at nd', simp [nd'] } }, { suffices : sigma.mk a' b' ∉ v1, {simp [h, ne.symm h, this]}, rcases veq with ⟨rfl, Hnc⟩ | ⟨b'', rfl⟩; simp [ne.symm h] } }, by_cases Hc : (contains_aux a bkt : Prop), { rcases hash_map.valid.replace_aux a b (array.read bkts (mk_idx n (hash_fn a))) ((contains_aux_iff nd).1 Hc) with ⟨u', w', b'', hl', hfl'⟩, rcases (append_of_modify u' [⟨a, b''⟩] [⟨a, b⟩] w' hl' hfl') with ⟨u, w, hl, hfl⟩, simpa [insert, @dif_pos (contains_aux a bkt) _ Hc] using lem _ _ u w hl hfl (or.inr ⟨b'', rfl⟩) }, { let size' := size + 1, let bkts' := bkts.modify hash_fn a (λl, ⟨a, b⟩::l), have mi : sigma.mk a' b' ∈ bkts'.as_list ↔ if a = a' then b == b' else sigma.mk a' b' ∈ bkts.as_list := let ⟨u, w, hl, hfl⟩ := append_of_modify [] [] [⟨a, b⟩] _ rfl rfl in lem bkts' _ u w hl hfl $ or.inl ⟨rfl, Hc⟩, simp [insert, @dif_neg (contains_aux a bkt) _ Hc], by_cases h : size' ≤ n.1, -- TODO(Mario): Why does the by_cases assumption look different than the stated one? { simpa [show size' ≤ n.1, from h] using mi }, { let n' : ℕ+ := ⟨n.1 * 2, mul_pos n.2 dec_trivial⟩, let bkts'' : bucket_array α β n' := bkts'.foldl (mk_array _ []) (reinsert_aux hash_fn), suffices : sigma.mk a' b' ∈ bkts''.as_list ↔ sigma.mk a' b' ∈ bkts'.as_list.reverse, { simpa [show ¬ size' ≤ n.1, from h, mi] }, rw [show bkts'' = bkts'.as_list.foldl _ _, from bkts'.foldl_eq _ _, ← list.foldr_reverse], induction bkts'.as_list.reverse with a l IH, { simp [mk_as_list] }, { cases a with a'' b'', let B := l.foldr (λ (y : sigma β) (x : bucket_array α β n'), reinsert_aux hash_fn x y.1 y.2) (mk_array n'.1 []), rcases append_of_modify [] [] [⟨a'', b''⟩] _ rfl rfl with ⟨u, w, hl, hfl⟩, simp [IH.symm, or.left_comm, show B.as_list = _, from hl, show (reinsert_aux hash_fn B a'' b'').as_list = _, from hfl] } } } end theorem find_insert_eq (m : hash_map α β) (a : α) (b : β a) : (m.insert a b).find a = some b := (find_iff (m.insert a b) a b).2 $ (mem_insert m a b a b).2 $ by rw if_pos rfl theorem find_insert_ne (m : hash_map α β) (a a' : α) (b : β a) (h : a ≠ a') : (m.insert a b).find a' = m.find a' := option.eq_of_eq_some $ λb', let t := mem_insert m a b a' b' in (find_iff _ _ _).trans $ iff.trans (by rwa if_neg h at t) (find_iff _ _ _).symm theorem find_insert (m : hash_map α β) (a' a : α) (b : β a) : (m.insert a b).find a' = if h : a = a' then some (eq.rec_on h b) else m.find a' := if h : a = a' then by rw dif_pos h; exact match a', h with ._, rfl := find_insert_eq m a b end else by rw dif_neg h; exact find_insert_ne m a a' b h /-- Insert a list of key-value pairs into the map. (Modifies `m` in-place when applicable) -/ def insert_all (l : list (Σ a, β a)) (m : hash_map α β) : hash_map α β := l.foldl (λ m ⟨a, b⟩, insert m a b) m /-- Construct a hash map from a list of key-value pairs. -/ def of_list (l : list (Σ a, β a)) (hash_fn) : hash_map α β := insert_all l (mk_hash_map hash_fn (2 * l.length)) /-- Remove a key from the map. (Modifies `m` in-place when applicable) -/ def erase (m : hash_map α β) (a : α) : hash_map α β := match m with ⟨hash_fn, size, n, buckets, v⟩ := if hc : contains_aux a (buckets.read hash_fn a) then { hash_fn := hash_fn, size := size - 1, nbuckets := n, buckets := buckets.modify hash_fn a (erase_aux a), is_valid := v.erase _ a hc } else m end theorem mem_erase : Π (m : hash_map α β) (a a' b'), (sigma.mk a' b' : sigma β) ∈ (m.erase a).entries ↔ a ≠ a' ∧ sigma.mk a' b' ∈ m.entries | ⟨hash_fn, size, n, bkts, v⟩ a a' b' := begin let bkt := bkts.read hash_fn a, by_cases Hc : (contains_aux a bkt : Prop), { let bkts' := bkts.modify hash_fn a (erase_aux a), suffices : sigma.mk a' b' ∈ bkts'.as_list ↔ a ≠ a' ∧ sigma.mk a' b' ∈ bkts.as_list, { simpa [erase, @dif_pos (contains_aux a bkt) _ Hc] }, have nd := v.nodup (mk_idx n (hash_fn a)), rcases valid.erase_aux a bkt ((contains_aux_iff nd).1 Hc) with ⟨u', w', b, hl', hfl'⟩, rcases append_of_modify u' [⟨a, b⟩] [] _ hl' hfl' with ⟨u, w, hl, hfl⟩, suffices : ∀_:sigma.mk a' b' ∈ u ∨ sigma.mk a' b' ∈ w, a ≠ a', { have : sigma.mk a' b' ∈ u ∨ sigma.mk a' b' ∈ w ↔ (¬a = a' ∧ a' = a) ∧ b' == b ∨ ¬a = a' ∧ (sigma.mk a' b' ∈ u ∨ sigma.mk a' b' ∈ w), { simp [eq_comm, not_and_self_iff, and_iff_right_of_imp this] }, simpa [hl, show bkts'.as_list = _, from hfl, and_or_distrib_left, and_comm, and.left_comm, or.left_comm] }, intros m e, subst a', revert m, apply not_or_distrib.2, have nd' := v.as_list_nodup _, simp [hl, list.nodup_append] at nd', simp [nd'] }, { suffices : ∀_:sigma.mk a' b' ∈ bucket_array.as_list bkts, a ≠ a', { simp [erase, @dif_neg (contains_aux a bkt) _ Hc, entries, and_iff_right_of_imp this] }, intros m e, subst a', exact Hc ((v.contains_aux_iff _ _).2 (list.mem_map_of_mem sigma.fst m)) } end theorem find_erase_eq (m : hash_map α β) (a : α) : (m.erase a).find a = none := begin cases h : (m.erase a).find a with b, {refl}, exact absurd rfl ((mem_erase m a a b).1 ((find_iff (m.erase a) a b).1 h)).left end theorem find_erase_ne (m : hash_map α β) (a a' : α) (h : a ≠ a') : (m.erase a).find a' = m.find a' := option.eq_of_eq_some $ λb', (find_iff _ _ _).trans $ (mem_erase m a a' b').trans $ (and_iff_right h).trans (find_iff _ _ _).symm theorem find_erase (m : hash_map α β) (a' a : α) : (m.erase a).find a' = if a = a' then none else m.find a' := if h : a = a' then by subst a'; simp [find_erase_eq m a] else by rw if_neg h; exact find_erase_ne m a a' h section string variables [has_to_string α] [∀ a, has_to_string (β a)] open prod private def key_data_to_string (a : α) (b : β a) (first : bool) : string := (if first then "" else ", ") ++ sformat!"{a} ← {b}" private def to_string (m : hash_map α β) : string := "⟨" ++ (fst (fold m ("", tt) (λ p a b, (fst p ++ key_data_to_string a b (snd p), ff)))) ++ "⟩" instance : has_to_string (hash_map α β) := ⟨to_string⟩ end string section format open format prod variables [has_to_format α] [∀ a, has_to_format (β a)] private meta def format_key_data (a : α) (b : β a) (first : bool) : format := (if first then to_fmt "" else to_fmt "," ++ line) ++ to_fmt a ++ space ++ to_fmt "←" ++ space ++ to_fmt b private meta def to_format (m : hash_map α β) : format := group $ to_fmt "⟨" ++ nest 1 (fst (fold m (to_fmt "", tt) (λ p a b, (fst p ++ format_key_data a b (snd p), ff)))) ++ to_fmt "⟩" meta instance : has_to_format (hash_map α β) := ⟨to_format⟩ end format end hash_map
50d9638d422fb9032226430099587344a38cbefe
6fb1523f14e3297f9ad9b10eb132e6170b011888
/src/2021/logic/sheet5.lean
9a44ddfabeb6e46ab13ddc16e72c1877fbe9be54
[]
no_license
jfmc/M40001_lean
392ef2ca3984f0d56b2f9bb22eafc45416e694ba
4502e3eb1af550c345cfda3aef7ffa89474fac24
refs/heads/master
1,693,810,669,330
1,634,755,889,000
1,634,755,889,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,414
lean
/- Copyright (c) 2021 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author : Kevin Buzzard -/ import tactic -- imports all the Lean tactics /-! # Logic in Lean, example sheet 5 : "iff" (`↔`) We learn about how to manipulate `P ↔ Q` in Lean. ## Tactics You'll need to know about the tactics from the previous sheets, and also the following two new tactics: * `refl` * `rw` ### The `refl` tactic If your goal is `P ↔ P` then `refl,` will solve it. ### The `rw` tactic If `h : P ↔ Q` is a hypothesis, you can decompose it using `cases h with hPQ hQP,`. However, if you keep it around then you can do `rw h,` which changes all `P`s in the goal to `Q`s. Variant: `rw h at h2,` will change all `P`s to `Q`s in hypothesis `h2`. -/ variables (P Q R S : Prop) example : P ↔ P := begin sorry end example : (P ↔ Q) → (Q ↔ P) := begin sorry end example : (P ↔ Q) ↔ (Q ↔ P) := begin sorry end example : (P ↔ Q) → (Q ↔ R) → (P ↔ R) := begin sorry end example : P ∧ Q ↔ Q ∧ P := begin sorry end example : ((P ∧ Q) ∧ R) ↔ (P ∧ (Q ∧ R)) := begin sorry end example : P ↔ (P ∧ true) := begin sorry end example : false ↔ (P ∧ false) := begin sorry end example : (P ↔ Q) → (R ↔ S) → (P ∧ Q ↔ R ∧ S) := begin sorry end example : ¬ (P ↔ ¬ P) := begin sorry, end
89627482e14fe7a44f422faf7eefe9da4b97aa87
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/init/option.lean
a926493c3e80114c97b19764a3151336ba6301b1
[ "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
3,318
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.logic init.monad init.alternative open decidable universe variables u v attribute [instance] definition option_is_inhabited (A : Type u) : inhabited (option A) := ⟨none⟩ attribute [instance] definition option_has_decidable_eq {A : Type u} [H : decidable_eq A] : ∀ o₁ o₂ : option A, decidable (o₁ = o₂) | none none := is_true rfl | none (some v₂) := is_false (λ H, option.no_confusion H) | (some v₁) none := is_false (λ H, option.no_confusion H) | (some v₁) (some v₂) := match (H v₁ v₂) with | (is_true e) := is_true (congr_arg (@some A) e) | (is_false n) := is_false (λ H, option.no_confusion H (λ e, absurd e n)) end attribute [inline] definition option_fmap {A : Type u} {B : Type v} (f : A → B) : option A → option B | none := none | (some a) := some (f a) attribute [inline] definition option_bind {A : Type u} {B : Type v} : option A → (A → option B) → option B | none b := none | (some a) b := b a attribute [instance] definition option_is_monad : monad option := monad.mk @option_fmap @some @option_bind definition option_orelse {A : Type u} : option A → option A → option A | (some a) o := some a | none (some a) := some a | none none := none attribute [instance] definition option_is_alternative {A : Type u} : alternative option := alternative.mk @option_fmap @some (@fapp _ _) @none @option_orelse definition optionT (M : Type (max 1 u) → Type v) [monad M] (A : Type u) : Type v := M (option A) attribute [inline] definition optionT_fmap {M : Type (max 1 u) → Type v} [monad M] {A B : Type u} (f : A → B) (e : optionT M A) : optionT M B := show M (option B), from do o ← e, match o with | none := return none | (some a) := return (some (f a)) end attribute [inline] definition optionT_bind {M : Type (max 1 u) → Type v} [monad M] {A B : Type u} (a : optionT M A) (b : A → optionT M B) : optionT M B := show M (option B), from do o ← a, match o with | none := return none | (some a) := b a end attribute [inline] definition optionT_return {M : Type (max 1 u) → Type v} [monad M] {A : Type u} (a : A) : optionT M A := show M (option A), from return (some a) attribute [instance] definition optionT_is_monad {M : Type (max 1 u) → Type v} [monad M] {A : Type u} : monad (optionT M) := monad.mk (@optionT_fmap M _) (@optionT_return M _) (@optionT_bind M _) definition optionT_orelse {M : Type (max 1 u) → Type v} [monad M] {A : Type u} (a : optionT M A) (b : optionT M A) : optionT M A := show M (option A), from do o ← a, match o with | none := b | (some v) := return (some v) end definition optionT_fail {M : Type (max 1 u) → Type v} [monad M] {A : Type u} : optionT M A := show M (option A), from return none attribute [instance] definition optionT_is_alternative {M : Type (max 1 u) → Type v} [monad M] {A : Type u} : alternative (optionT M) := alternative.mk (@optionT_fmap M _) (@optionT_return M _) (@fapp (optionT M) (@optionT_is_monad M _ A)) (@optionT_fail M _) (@optionT_orelse M _)
a839a3950015ee786442d5d86dfa92fa69f6a865
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/run/ind5.lean
7aabee10e55f9e633b36387751bda135a3751cc6
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
174
lean
definition Prop : Type.{1} := Type.{0} inductive or (A B : Prop) : Prop := intro_left : A → or A B, intro_right : B → or A B check or check or.intro_left check or.rec
ec8d53c2089bb1e51021aced70627170030fd267
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/playground/arith_eval_uint32.lean
b644100c92c9d1d438bdaaceffb90a9ee00d90a4
[ "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
455
lean
inductive Expr | Var : UInt32 → Expr | Val : UInt32 → Expr | Add : Expr → Expr → Expr open Expr def dec (n : UInt32) : UInt32 := if n = 0 then 0 else n-1 def mkExpr : UInt32 → UInt32 → Expr | n, v => if n = 0 then Val v else Add (mkExpr (n-1) (v+1)) (mkExpr (n-1) (dec v)) def eval : Expr → UInt32 | Var x => 0 | Val v => v | Add l r => eval l + eval r def main : IO UInt32 := IO.println (toString $ eval (mkExpr 26 1)) *> pure 0
9bf78ab23c029dd6401939c0e30019993d5ead2a
2662838d4e13f0ccc8c72b15fad39eed96e9e148
/examples/sets.lean
6e0c6f8a6156c3a96984e29e5a7280a354a6343f
[]
no_license
avigad/nlp
3c57390046518f11ec6e6e7732f0fe5ae3794674
a937dbb2f5dfc91d35b5b55795eab6cb0ced712f
refs/heads/master
1,609,032,855,319
1,446,922,577,000
1,446,922,577,000
45,743,759
0
0
null
1,446,912,972,000
1,446,912,971,000
null
UTF-8
Lean
false
false
6,604
lean
import data.set open set classical variable {X : Type} variables A B C D : set X -- Here is a short, though laconic, Lean proof of Proposition 0.1. example : A ∪ (B ∩ C) = (A ∪ B) ∩ (A ∪ C) := eq_of_subset_of_subset (take x, suppose x ∈ A ∪ (B ∩ C), or.elim this (suppose x ∈ A, and.intro (or.inl this) (or.inl this)) (suppose x ∈ B ∩ C, and.intro (or.inr (and.left this)) (or.inr (and.right this)))) (take x, assume H : x ∈ (A ∪ B) ∩ (A ∪ C), by_cases (suppose x ∈ A, or.inl this) (suppose x ∉ A, or.inr (and.intro (or_resolve_right (and.left H) this) (or_resolve_right (and.right H) this)))) -- Here is what could hopefully be inferred from the text. -- Notice that the text proof does not say what is proved in "case1" and "case2", -- it just does it. -- From the structure of the proof, Lean can infer the placeholders, that is, -- the values that should be assigned to the underscores. example : A ∪ (B ∩ C) = (A ∪ B) ∩ (A ∪ C) := have H1 : _, from take x, -- not explicitly introduced in the text suppose x ∈ A ∪ (B ∩ C), have x ∈ A ∨ x ∈ B ∩ C, from sorry, have case1 : _, from suppose x ∈ A, -- here we have to guess that we are splitting the "or" have x ∈ A ∪ B, from sorry, have x ∈ A ∪ C, from sorry, show x ∈ (A ∪ B) ∩ (A ∪ C), from sorry, have case2 : _, from suppose x ∈ B ∩ C, -- the second component of the "or" have x ∈ B, from sorry, have x ∈ C, from sorry, have x ∈ A ∪ B, from sorry, have x ∈ A ∪ C, from sorry, show x ∈ (A ∪ B) ∩ (A ∪ C), from sorry, show x ∈ (A ∪ B) ∩ (A ∪ C), from sorry, -- this is hard. because this is the -- conclusion of each case, it must be the -- conclusion of the first paragraph have H2 : _, from take x, -- again, not explicitly introduced in the text suppose x ∈ (A ∪ B) ∩ (A ∪ C), have x ∈ A ∪ B, from sorry, have x ∈ A ∪ C, from sorry, have case1 : _, from -- the "If x is in A" suggests a case split suppose x ∈ A, show x ∈ A ∪ (B ∩ C), from sorry, have case2 : _, from -- the "If x is not in A" case suppose x ∉ A, have x ∈ B, using `x ∈ A ∪ B`, from sorry, have x ∈ C, using `x ∈ A ∪ C`, from sorry, have x ∈ B ∩ C, from sorry, show x ∈ A ∪ (B ∩ C), from sorry, show x ∈ A ∩ (B ∪ C), from sorry, show A ∪ (B ∩ C) = (A ∪ B) ∩ (A ∪ C), from sorry -- The details can be filled in, as follows. example : A ∪ (B ∩ C) = (A ∪ B) ∩ (A ∪ C) := have H1 : _, from take x, suppose x ∈ A ∪ (B ∩ C), have H1e : x ∈ A ∨ x ∈ B ∩ C, from this, have case1 : _, from suppose x ∈ A, -- here we have to guess that we are splitting the "or" have H1a : x ∈ A ∪ B, from or.inl `x ∈ A`, have H1b : x ∈ A ∪ C, from or.inl `x ∈ A`, show x ∈ (A ∪ B) ∩ (A ∪ C), from and.intro H1a H1b, have case2 : _, from suppose x ∈ B ∩ C, -- the second component of the "or" have x ∈ B, from and.left `x ∈ B ∩ C`, have x ∈ C, from and.right `x ∈ B ∩ C`, have H1c : x ∈ A ∪ B, from or.inr `x ∈ B`, have H1d : x ∈ A ∪ C, from or.inr `x ∈ C`, show x ∈ (A ∪ B) ∩ (A ∪ C), from and.intro H1c H1d, show x ∈ (A ∪ B) ∩ (A ∪ C), from or.elim H1e case1 case2, have H2 : _, from take x, -- again, not explicitly introduced in the text assume H2a : x ∈ (A ∪ B) ∩ (A ∪ C), have x ∈ A ∪ B, from and.left H2a, have x ∈ A ∪ C, from and.right H2a, have case1 : _, from -- the "If x is in A" suggests a case split suppose x ∈ A, show x ∈ A ∪ (B ∩ C), from or.inl this, have case2 : _, from -- the "If x is not in A" case suppose x ∉ A, have x ∈ B, from or_resolve_right `x ∈ A ∪ B` `x ∉ A`, have x ∈ C, from or_resolve_right `x ∈ A ∪ C` `x ∉ A`, have x ∈ B ∩ C, from and.intro `x ∈ B` `x ∈ C`, show x ∈ A ∪ (B ∩ C), from or.inr this, show x ∈ A ∪ (B ∩ C), from by_cases case1 case2, show A ∪ (B ∩ C) = (A ∪ B) ∩ (A ∪ C), from eq_of_subset_of_subset H1 H2 -- Here is a complete Lean proof of Proposition 0.2. example : A ∩ (B ∪ C) = (A ∩ B) ∪ (A ∩ C) := eq_of_subset_of_subset (take x, assume H : x ∈ A ∩ (B ∪ C), have x ∈ A, from and.left H, have x ∈ B ∪ C, from and.right H, or.elim (`x ∈ B ∪ C`) (suppose x ∈ B, have x ∈ A ∩ B, from and.intro `x ∈ A` `x ∈ B`, show x ∈ (A ∩ B) ∪ (A ∩ C), from or.inl this) (suppose x ∈ C, have x ∈ A ∩ C, from and.intro `x ∈ A` `x ∈ C`, show x ∈ (A ∩ B) ∪ (A ∩ C), from or.inr this)) (take x, suppose x ∈ (A ∩ B) ∪ (A ∩ C), or.elim this (assume H : x ∈ A ∩ B, have x ∈ A, from and.left H, have x ∈ B, from and.right H, have x ∈ B ∪ C, from or.inl this, show x ∈ A ∩ (B ∪ C), from and.intro `x ∈ A` this) (assume H : x ∈ A ∩ C, have x ∈ A, from and.left H, have x ∈ C, from and.right H, have x ∈ B ∪ C, from or.inr this, show x ∈ A ∩ (B ∪ C), from and.intro `x ∈ A` this)) -- Here is a complete Lean proof of Proposition 0.3 example : -(A \ B) = -A ∪ B := eq_of_subset_of_subset (take x, assume H : x ∉ A \ B, by_cases (suppose x ∈ A, have x ∈ B, from by_contradiction (suppose x ∉ B, have x ∈ A \ B, from and.intro `x ∈ A` this, show false, from H this), show x ∈ -A ∪ B, from or.inr this) (suppose x ∉ A, or.inl this)) (take x, suppose x ∈ -A ∪ B, or.elim this (suppose x ∉ A, show x ∉ A \ B, from assume H, this (and.left H)) (suppose x ∈ B, show x ∉ A \ B, from assume H, and.right H this)) -- IOU proposition 0.4 -- Here is a proof of Proposition 0.5 definition disjoint (A B : set X) : Prop := A ∩ B = ∅ example (H : disjoint A B) (H1 : C ⊆ A) (H2 : D ⊆ B) : disjoint C D := eq_empty_of_forall_not_mem (take x, suppose x ∈ C ∩ D, obtain (H3 : x ∈ C) (H4 : x ∈ D), from this, have x ∈ A ∩ B, from and.intro (H1 H3) (H2 H4), have x ∈ ∅, from eq.subst H this, show false, from this)
230e5d13a41f9400c2d65731456efe292620d616
c777c32c8e484e195053731103c5e52af26a25d1
/src/geometry/manifold/partition_of_unity.lean
7598e00e1f47955a24aa4d84b01b7ffeddf68aba
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
27,470
lean
/- Copyright (c) 2021 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import geometry.manifold.algebra.structures import geometry.manifold.bump_function import topology.metric_space.partition_of_unity import topology.shrinking_lemma /-! # Smooth partition of unity In this file we define two structures, `smooth_bump_covering` and `smooth_partition_of_unity`. Both structures describe coverings of a set by a locally finite family of supports of smooth functions with some additional properties. The former structure is mostly useful as an intermediate step in the construction of a smooth partition of unity but some proofs that traditionally deal with a partition of unity can use a `smooth_bump_covering` as well. Given a real manifold `M` and its subset `s`, a `smooth_bump_covering ι I M s` is a collection of `smooth_bump_function`s `f i` indexed by `i : ι` such that * the center of each `f i` belongs to `s`; * the family of sets `support (f i)` is locally finite; * for each `x ∈ s`, there exists `i : ι` such that `f i =ᶠ[𝓝 x] 1`. In the same settings, a `smooth_partition_of_unity ι I M s` is a collection of smooth nonnegative functions `f i : C^∞⟮I, M; 𝓘(ℝ), ℝ⟯`, `i : ι`, such that * the family of sets `support (f i)` is locally finite; * for each `x ∈ s`, the sum `∑ᶠ i, f i x` equals one; * for each `x`, the sum `∑ᶠ i, f i x` is less than or equal to one. We say that `f : smooth_bump_covering ι I M s` is *subordinate* to a map `U : M → set M` if for each index `i`, we have `tsupport (f i) ⊆ U (f i).c`. This notion is a bit more general than being subordinate to an open covering of `M`, because we make no assumption about the way `U x` depends on `x`. We prove that on a smooth finitely dimensional real manifold with `σ`-compact Hausdorff topology, for any `U : M → set M` such that `∀ x ∈ s, U x ∈ 𝓝 x` there exists a `smooth_bump_covering ι I M s` subordinate to `U`. Then we use this fact to prove a similar statement about smooth partitions of unity, see `smooth_partition_of_unity.exists_is_subordinate`. Finally, we use existence of a partition of unity to prove lemma `exists_smooth_forall_mem_convex_of_local` that allows us to construct a globally defined smooth function from local functions. ## TODO * Build a framework for to transfer local definitions to global using partition of unity and use it to define, e.g., the integral of a differential form over a manifold. Lemma `exists_smooth_forall_mem_convex_of_local` is a first step in this direction. ## Tags smooth bump function, partition of unity -/ universes uι uE uH uM uF open function filter finite_dimensional set open_locale topology manifold classical filter big_operators noncomputable theory variables {ι : Type uι} {E : Type uE} [normed_add_comm_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {F : Type uF} [normed_add_comm_group F] [normed_space ℝ F] {H : Type uH} [topological_space H] (I : model_with_corners ℝ E H) {M : Type uM} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] /-! ### Covering by supports of smooth bump functions In this section we define `smooth_bump_covering ι I M s` to be a collection of `smooth_bump_function`s such that their supports is a locally finite family of sets and for each `x ∈ s` some function `f i` from the collection is equal to `1` in a neighborhood of `x`. A covering of this type is useful to construct a smooth partition of unity and can be used instead of a partition of unity in some proofs. We prove that on a smooth finite dimensional real manifold with `σ`-compact Hausdorff topology, for any `U : M → set M` such that `∀ x ∈ s, U x ∈ 𝓝 x` there exists a `smooth_bump_covering ι I M s` subordinate to `U`. Then we use this fact to prove a version of the Whitney embedding theorem: any compact real manifold can be embedded into `ℝ^n` for large enough `n`. -/ variables (ι M) /-- We say that a collection of `smooth_bump_function`s is a `smooth_bump_covering` of a set `s` if * `(f i).c ∈ s` for all `i`; * the family `λ i, support (f i)` is locally finite; * for each point `x ∈ s` there exists `i` such that `f i =ᶠ[𝓝 x] 1`; in other words, `x` belongs to the interior of `{y | f i y = 1}`; If `M` is a finite dimensional real manifold which is a `σ`-compact Hausdorff topological space, then for every covering `U : M → set M`, `∀ x, U x ∈ 𝓝 x`, there exists a `smooth_bump_covering` subordinate to `U`, see `smooth_bump_covering.exists_is_subordinate`. This covering can be used, e.g., to construct a partition of unity and to prove the weak Whitney embedding theorem. -/ @[nolint has_nonempty_instance] structure smooth_bump_covering (s : set M := univ) := (c : ι → M) (to_fun : Π i, smooth_bump_function I (c i)) (c_mem' : ∀ i, c i ∈ s) (locally_finite' : locally_finite (λ i, support (to_fun i))) (eventually_eq_one' : ∀ x ∈ s, ∃ i, to_fun i =ᶠ[𝓝 x] 1) /-- We say that that a collection of functions form a smooth partition of unity on a set `s` if * all functions are infinitely smooth and nonnegative; * the family `λ i, support (f i)` is locally finite; * for all `x ∈ s` the sum `∑ᶠ i, f i x` equals one; * for all `x`, the sum `∑ᶠ i, f i x` is less than or equal to one. -/ structure smooth_partition_of_unity (s : set M := univ) := (to_fun : ι → C^∞⟮I, M; 𝓘(ℝ), ℝ⟯) (locally_finite' : locally_finite (λ i, support (to_fun i))) (nonneg' : ∀ i x, 0 ≤ to_fun i x) (sum_eq_one' : ∀ x ∈ s, ∑ᶠ i, to_fun i x = 1) (sum_le_one' : ∀ x, ∑ᶠ i, to_fun i x ≤ 1) variables {ι I M} namespace smooth_partition_of_unity variables {s : set M} (f : smooth_partition_of_unity ι I M s) {n : ℕ∞} instance {s : set M} : has_coe_to_fun (smooth_partition_of_unity ι I M s) (λ _, ι → C^∞⟮I, M; 𝓘(ℝ), ℝ⟯) := ⟨smooth_partition_of_unity.to_fun⟩ protected lemma locally_finite : locally_finite (λ i, support (f i)) := f.locally_finite' lemma nonneg (i : ι) (x : M) : 0 ≤ f i x := f.nonneg' i x lemma sum_eq_one {x} (hx : x ∈ s) : ∑ᶠ i, f i x = 1 := f.sum_eq_one' x hx lemma sum_le_one (x : M) : ∑ᶠ i, f i x ≤ 1 := f.sum_le_one' x /-- Reinterpret a smooth partition of unity as a continuous partition of unity. -/ def to_partition_of_unity : partition_of_unity ι M s := { to_fun := λ i, f i, .. f } lemma smooth_sum : smooth I 𝓘(ℝ) (λ x, ∑ᶠ i, f i x) := smooth_finsum (λ i, (f i).smooth) f.locally_finite lemma le_one (i : ι) (x : M) : f i x ≤ 1 := f.to_partition_of_unity.le_one i x lemma sum_nonneg (x : M) : 0 ≤ ∑ᶠ i, f i x := f.to_partition_of_unity.sum_nonneg x lemma cont_mdiff_smul {g : M → F} {i} (hg : ∀ x ∈ tsupport (f i), cont_mdiff_at I 𝓘(ℝ, F) n g x) : cont_mdiff I 𝓘(ℝ, F) n (λ x, f i x • g x) := cont_mdiff_of_support $ λ x hx, ((f i).cont_mdiff.cont_mdiff_at.of_le le_top).smul $ hg x $ tsupport_smul_subset_left _ _ hx lemma smooth_smul {g : M → F} {i} (hg : ∀ x ∈ tsupport (f i), smooth_at I 𝓘(ℝ, F) g x) : smooth I 𝓘(ℝ, F) (λ x, f i x • g x) := f.cont_mdiff_smul hg /-- If `f` is a smooth partition of unity on a set `s : set M` and `g : ι → M → F` is a family of functions such that `g i` is $C^n$ smooth at every point of the topological support of `f i`, then the sum `λ x, ∑ᶠ i, f i x • g i x` is smooth on the whole manifold. -/ lemma cont_mdiff_finsum_smul {g : ι → M → F} (hg : ∀ i (x ∈ tsupport (f i)), cont_mdiff_at I 𝓘(ℝ, F) n (g i) x) : cont_mdiff I 𝓘(ℝ, F) n (λ x, ∑ᶠ i, f i x • g i x) := cont_mdiff_finsum (λ i, f.cont_mdiff_smul (hg i)) $ f.locally_finite.subset $ λ i, support_smul_subset_left _ _ /-- If `f` is a smooth partition of unity on a set `s : set M` and `g : ι → M → F` is a family of functions such that `g i` is smooth at every point of the topological support of `f i`, then the sum `λ x, ∑ᶠ i, f i x • g i x` is smooth on the whole manifold. -/ lemma smooth_finsum_smul {g : ι → M → F} (hg : ∀ i (x ∈ tsupport (f i)), smooth_at I 𝓘(ℝ, F) (g i) x) : smooth I 𝓘(ℝ, F) (λ x, ∑ᶠ i, f i x • g i x) := f.cont_mdiff_finsum_smul hg lemma finsum_smul_mem_convex {g : ι → M → F} {t : set F} {x : M} (hx : x ∈ s) (hg : ∀ i, f i x ≠ 0 → g i x ∈ t) (ht : convex ℝ t) : ∑ᶠ i, f i x • g i x ∈ t := ht.finsum_mem (λ i, f.nonneg _ _) (f.sum_eq_one hx) hg /-- A smooth partition of unity `f i` is subordinate to a family of sets `U i` indexed by the same type if for each `i` the closure of the support of `f i` is a subset of `U i`. -/ def is_subordinate (f : smooth_partition_of_unity ι I M s) (U : ι → set M) := ∀ i, tsupport (f i) ⊆ U i variables {f} {U : ι → set M} @[simp] lemma is_subordinate_to_partition_of_unity : f.to_partition_of_unity.is_subordinate U ↔ f.is_subordinate U := iff.rfl alias is_subordinate_to_partition_of_unity ↔ _ is_subordinate.to_partition_of_unity /-- If `f` is a smooth partition of unity on a set `s : set M` subordinate to a family of open sets `U : ι → set M` and `g : ι → M → F` is a family of functions such that `g i` is $C^n$ smooth on `U i`, then the sum `λ x, ∑ᶠ i, f i x • g i x` is $C^n$ smooth on the whole manifold. -/ lemma is_subordinate.cont_mdiff_finsum_smul {g : ι → M → F} (hf : f.is_subordinate U) (ho : ∀ i, is_open (U i)) (hg : ∀ i, cont_mdiff_on I 𝓘(ℝ, F) n (g i) (U i)) : cont_mdiff I 𝓘(ℝ, F) n (λ x, ∑ᶠ i, f i x • g i x) := f.cont_mdiff_finsum_smul $ λ i x hx, (hg i).cont_mdiff_at $ (ho i).mem_nhds (hf i hx) /-- If `f` is a smooth partition of unity on a set `s : set M` subordinate to a family of open sets `U : ι → set M` and `g : ι → M → F` is a family of functions such that `g i` is smooth on `U i`, then the sum `λ x, ∑ᶠ i, f i x • g i x` is smooth on the whole manifold. -/ lemma is_subordinate.smooth_finsum_smul {g : ι → M → F} (hf : f.is_subordinate U) (ho : ∀ i, is_open (U i)) (hg : ∀ i, smooth_on I 𝓘(ℝ, F) (g i) (U i)) : smooth I 𝓘(ℝ, F) (λ x, ∑ᶠ i, f i x • g i x) := hf.cont_mdiff_finsum_smul ho hg end smooth_partition_of_unity namespace bump_covering -- Repeat variables to drop [finite_dimensional ℝ E] and [smooth_manifold_with_corners I M] lemma smooth_to_partition_of_unity {E : Type uE} [normed_add_comm_group E] [normed_space ℝ E] {H : Type uH} [topological_space H] {I : model_with_corners ℝ E H} {M : Type uM} [topological_space M] [charted_space H M] {s : set M} (f : bump_covering ι M s) (hf : ∀ i, smooth I 𝓘(ℝ) (f i)) (i : ι) : smooth I 𝓘(ℝ) (f.to_partition_of_unity i) := (hf i).mul $ smooth_finprod_cond (λ j _, smooth_const.sub (hf j)) $ by { simp only [mul_support_one_sub], exact f.locally_finite } variables {s : set M} /-- A `bump_covering` such that all functions in this covering are smooth generates a smooth partition of unity. In our formalization, not every `f : bump_covering ι M s` with smooth functions `f i` is a `smooth_bump_covering`; instead, a `smooth_bump_covering` is a covering by supports of `smooth_bump_function`s. So, we define `bump_covering.to_smooth_partition_of_unity`, then reuse it in `smooth_bump_covering.to_smooth_partition_of_unity`. -/ def to_smooth_partition_of_unity (f : bump_covering ι M s) (hf : ∀ i, smooth I 𝓘(ℝ) (f i)) : smooth_partition_of_unity ι I M s := { to_fun := λ i, ⟨f.to_partition_of_unity i, f.smooth_to_partition_of_unity hf i⟩, .. f.to_partition_of_unity } @[simp] lemma to_smooth_partition_of_unity_to_partition_of_unity (f : bump_covering ι M s) (hf : ∀ i, smooth I 𝓘(ℝ) (f i)) : (f.to_smooth_partition_of_unity hf).to_partition_of_unity = f.to_partition_of_unity := rfl @[simp] lemma coe_to_smooth_partition_of_unity (f : bump_covering ι M s) (hf : ∀ i, smooth I 𝓘(ℝ) (f i)) (i : ι) : ⇑(f.to_smooth_partition_of_unity hf i) = f.to_partition_of_unity i := rfl lemma is_subordinate.to_smooth_partition_of_unity {f : bump_covering ι M s} {U : ι → set M} (h : f.is_subordinate U) (hf : ∀ i, smooth I 𝓘(ℝ) (f i)) : (f.to_smooth_partition_of_unity hf).is_subordinate U := h.to_partition_of_unity end bump_covering namespace smooth_bump_covering variables {s : set M} {U : M → set M} (fs : smooth_bump_covering ι I M s) {I} instance : has_coe_to_fun (smooth_bump_covering ι I M s) (λ x, Π (i : ι), smooth_bump_function I (x.c i)) := ⟨to_fun⟩ @[simp] lemma coe_mk (c : ι → M) (to_fun : Π i, smooth_bump_function I (c i)) (h₁ h₂ h₃) : ⇑(mk c to_fun h₁ h₂ h₃ : smooth_bump_covering ι I M s) = to_fun := rfl /-- We say that `f : smooth_bump_covering ι I M s` is *subordinate* to a map `U : M → set M` if for each index `i`, we have `tsupport (f i) ⊆ U (f i).c`. This notion is a bit more general than being subordinate to an open covering of `M`, because we make no assumption about the way `U x` depends on `x`. -/ def is_subordinate {s : set M} (f : smooth_bump_covering ι I M s) (U : M → set M) := ∀ i, tsupport (f i) ⊆ U (f.c i) lemma is_subordinate.support_subset {fs : smooth_bump_covering ι I M s} {U : M → set M} (h : fs.is_subordinate U) (i : ι) : support (fs i) ⊆ U (fs.c i) := subset.trans subset_closure (h i) variable (I) /-- Let `M` be a smooth manifold with corners modelled on a finite dimensional real vector space. Suppose also that `M` is a Hausdorff `σ`-compact topological space. Let `s` be a closed set in `M` and `U : M → set M` be a collection of sets such that `U x ∈ 𝓝 x` for every `x ∈ s`. Then there exists a smooth bump covering of `s` that is subordinate to `U`. -/ lemma exists_is_subordinate [t2_space M] [sigma_compact_space M] (hs : is_closed s) (hU : ∀ x ∈ s, U x ∈ 𝓝 x) : ∃ (ι : Type uM) (f : smooth_bump_covering ι I M s), f.is_subordinate U := begin -- First we deduce some missing instances haveI : locally_compact_space H := I.locally_compact, haveI : locally_compact_space M := charted_space.locally_compact H M, haveI : normal_space M := normal_of_paracompact_t2, -- Next we choose a covering by supports of smooth bump functions have hB := λ x hx, smooth_bump_function.nhds_basis_support I (hU x hx), rcases refinement_of_locally_compact_sigma_compact_of_nhds_basis_set hs hB with ⟨ι, c, f, hf, hsub', hfin⟩, choose hcs hfU using hf, /- Then we use the shrinking lemma to get a covering by smaller open -/ rcases exists_subset_Union_closed_subset hs (λ i, (f i).is_open_support) (λ x hx, hfin.point_finite x) hsub' with ⟨V, hsV, hVc, hVf⟩, choose r hrR hr using λ i, (f i).exists_r_pos_lt_subset_ball (hVc i) (hVf i), refine ⟨ι, ⟨c, λ i, (f i).update_r (r i) (hrR i), hcs, _, λ x hx, _⟩, λ i, _⟩, { simpa only [smooth_bump_function.support_update_r] }, { refine (mem_Union.1 $ hsV hx).imp (λ i hi, _), exact ((f i).update_r _ _).eventually_eq_one_of_dist_lt ((f i).support_subset_source $ hVf _ hi) (hr i hi).2 }, { simpa only [coe_mk, smooth_bump_function.support_update_r, tsupport] using hfU i } end variables {I M} protected lemma locally_finite : locally_finite (λ i, support (fs i)) := fs.locally_finite' protected lemma point_finite (x : M) : {i | fs i x ≠ 0}.finite := fs.locally_finite.point_finite x lemma mem_chart_at_source_of_eq_one {i : ι} {x : M} (h : fs i x = 1) : x ∈ (chart_at H (fs.c i)).source := (fs i).support_subset_source $ by simp [h] lemma mem_ext_chart_at_source_of_eq_one {i : ι} {x : M} (h : fs i x = 1) : x ∈ (ext_chart_at I (fs.c i)).source := by { rw ext_chart_at_source, exact fs.mem_chart_at_source_of_eq_one h } /-- Index of a bump function such that `fs i =ᶠ[𝓝 x] 1`. -/ def ind (x : M) (hx : x ∈ s) : ι := (fs.eventually_eq_one' x hx).some lemma eventually_eq_one (x : M) (hx : x ∈ s) : fs (fs.ind x hx) =ᶠ[𝓝 x] 1 := (fs.eventually_eq_one' x hx).some_spec lemma apply_ind (x : M) (hx : x ∈ s) : fs (fs.ind x hx) x = 1 := (fs.eventually_eq_one x hx).eq_of_nhds lemma mem_support_ind (x : M) (hx : x ∈ s) : x ∈ support (fs $ fs.ind x hx) := by simp [fs.apply_ind x hx] lemma mem_chart_at_ind_source (x : M) (hx : x ∈ s) : x ∈ (chart_at H (fs.c (fs.ind x hx))).source := fs.mem_chart_at_source_of_eq_one (fs.apply_ind x hx) lemma mem_ext_chart_at_ind_source (x : M) (hx : x ∈ s) : x ∈ (ext_chart_at I (fs.c (fs.ind x hx))).source := fs.mem_ext_chart_at_source_of_eq_one (fs.apply_ind x hx) /-- The index type of a `smooth_bump_covering` of a compact manifold is finite. -/ protected def fintype [compact_space M] : fintype ι := fs.locally_finite.fintype_of_compact $ λ i, (fs i).nonempty_support variable [t2_space M] /-- Reinterpret a `smooth_bump_covering` as a continuous `bump_covering`. Note that not every `f : bump_covering ι M s` with smooth functions `f i` is a `smooth_bump_covering`. -/ def to_bump_covering : bump_covering ι M s := { to_fun := λ i, ⟨fs i, (fs i).continuous⟩, locally_finite' := fs.locally_finite, nonneg' := λ i x, (fs i).nonneg, le_one' := λ i x, (fs i).le_one, eventually_eq_one' := fs.eventually_eq_one' } @[simp] lemma is_subordinate_to_bump_covering {f : smooth_bump_covering ι I M s} {U : M → set M} : f.to_bump_covering.is_subordinate (λ i, U (f.c i)) ↔ f.is_subordinate U := iff.rfl alias is_subordinate_to_bump_covering ↔ _ is_subordinate.to_bump_covering /-- Every `smooth_bump_covering` defines a smooth partition of unity. -/ def to_smooth_partition_of_unity : smooth_partition_of_unity ι I M s := fs.to_bump_covering.to_smooth_partition_of_unity (λ i, (fs i).smooth) lemma to_smooth_partition_of_unity_apply (i : ι) (x : M) : fs.to_smooth_partition_of_unity i x = fs i x * ∏ᶠ j (hj : well_ordering_rel j i), (1 - fs j x) := rfl lemma to_smooth_partition_of_unity_eq_mul_prod (i : ι) (x : M) (t : finset ι) (ht : ∀ j, well_ordering_rel j i → fs j x ≠ 0 → j ∈ t) : fs.to_smooth_partition_of_unity i x = fs i x * ∏ j in t.filter (λ j, well_ordering_rel j i), (1 - fs j x) := fs.to_bump_covering.to_partition_of_unity_eq_mul_prod i x t ht lemma exists_finset_to_smooth_partition_of_unity_eventually_eq (i : ι) (x : M) : ∃ t : finset ι, fs.to_smooth_partition_of_unity i =ᶠ[𝓝 x] fs i * ∏ j in t.filter (λ j, well_ordering_rel j i), (1 - fs j) := fs.to_bump_covering.exists_finset_to_partition_of_unity_eventually_eq i x lemma to_smooth_partition_of_unity_zero_of_zero {i : ι} {x : M} (h : fs i x = 0) : fs.to_smooth_partition_of_unity i x = 0 := fs.to_bump_covering.to_partition_of_unity_zero_of_zero h lemma support_to_smooth_partition_of_unity_subset (i : ι) : support (fs.to_smooth_partition_of_unity i) ⊆ support (fs i) := fs.to_bump_covering.support_to_partition_of_unity_subset i lemma is_subordinate.to_smooth_partition_of_unity {f : smooth_bump_covering ι I M s} {U : M → set M} (h : f.is_subordinate U) : f.to_smooth_partition_of_unity.is_subordinate (λ i, U (f.c i)) := h.to_bump_covering.to_partition_of_unity lemma sum_to_smooth_partition_of_unity_eq (x : M) : ∑ᶠ i, fs.to_smooth_partition_of_unity i x = 1 - ∏ᶠ i, (1 - fs i x) := fs.to_bump_covering.sum_to_partition_of_unity_eq x end smooth_bump_covering variable (I) /-- Given two disjoint closed sets in a Hausdorff σ-compact finite dimensional manifold, there exists an infinitely smooth function that is equal to `0` on one of them and is equal to one on the other. -/ lemma exists_smooth_zero_one_of_closed [t2_space M] [sigma_compact_space M] {s t : set M} (hs : is_closed s) (ht : is_closed t) (hd : disjoint s t) : ∃ f : C^∞⟮I, M; 𝓘(ℝ), ℝ⟯, eq_on f 0 s ∧ eq_on f 1 t ∧ ∀ x, f x ∈ Icc (0 : ℝ) 1 := begin have : ∀ x ∈ t, sᶜ ∈ 𝓝 x, from λ x hx, hs.is_open_compl.mem_nhds (disjoint_right.1 hd hx), rcases smooth_bump_covering.exists_is_subordinate I ht this with ⟨ι, f, hf⟩, set g := f.to_smooth_partition_of_unity, refine ⟨⟨_, g.smooth_sum⟩, λ x hx, _, λ x, g.sum_eq_one, λ x, ⟨g.sum_nonneg x, g.sum_le_one x⟩⟩, suffices : ∀ i, g i x = 0, by simp only [this, cont_mdiff_map.coe_fn_mk, finsum_zero, pi.zero_apply], refine λ i, f.to_smooth_partition_of_unity_zero_of_zero _, exact nmem_support.1 (subset_compl_comm.1 (hf.support_subset i) hx) end namespace smooth_partition_of_unity /-- A `smooth_partition_of_unity` that consists of a single function, uniformly equal to one, defined as an example for `inhabited` instance. -/ def single (i : ι) (s : set M) : smooth_partition_of_unity ι I M s := (bump_covering.single i s).to_smooth_partition_of_unity $ λ j, begin rcases eq_or_ne j i with rfl|h, { simp only [smooth_one, continuous_map.coe_one, bump_covering.coe_single, pi.single_eq_same] }, { simp only [smooth_zero, bump_covering.coe_single, pi.single_eq_of_ne h, continuous_map.coe_zero] } end instance [inhabited ι] (s : set M) : inhabited (smooth_partition_of_unity ι I M s) := ⟨single I default s⟩ variables [t2_space M] [sigma_compact_space M] /-- If `X` is a paracompact normal topological space and `U` is an open covering of a closed set `s`, then there exists a `bump_covering ι X s` that is subordinate to `U`. -/ lemma exists_is_subordinate {s : set M} (hs : is_closed s) (U : ι → set M) (ho : ∀ i, is_open (U i)) (hU : s ⊆ ⋃ i, U i) : ∃ f : smooth_partition_of_unity ι I M s, f.is_subordinate U := begin haveI : locally_compact_space H := I.locally_compact, haveI : locally_compact_space M := charted_space.locally_compact H M, haveI : normal_space M := normal_of_paracompact_t2, rcases bump_covering.exists_is_subordinate_of_prop (smooth I 𝓘(ℝ)) _ hs U ho hU with ⟨f, hf, hfU⟩, { exact ⟨f.to_smooth_partition_of_unity hf, hfU.to_smooth_partition_of_unity hf⟩ }, { intros s t hs ht hd, rcases exists_smooth_zero_one_of_closed I hs ht hd with ⟨f, hf⟩, exact ⟨f, f.smooth, hf⟩ } end end smooth_partition_of_unity variables [sigma_compact_space M] [t2_space M] {t : M → set F} {n : ℕ∞} /-- Let `M` be a σ-compact Hausdorff finite dimensional topological manifold. Let `t : M → set F` be a family of convex sets. Suppose that for each point `x : M` there exists a neighborhood `U ∈ 𝓝 x` and a function `g : M → F` such that `g` is $C^n$ smooth on `U` and `g y ∈ t y` for all `y ∈ U`. Then there exists a $C^n$ smooth function `g : C^∞⟮I, M; 𝓘(ℝ, F), F⟯` such that `g x ∈ t x` for all `x`. See also `exists_smooth_forall_mem_convex_of_local` and `exists_smooth_forall_mem_convex_of_local_const`. -/ lemma exists_cont_mdiff_forall_mem_convex_of_local (ht : ∀ x, convex ℝ (t x)) (Hloc : ∀ x : M, ∃ (U ∈ 𝓝 x) (g : M → F), cont_mdiff_on I 𝓘(ℝ, F) n g U ∧ ∀ y ∈ U, g y ∈ t y) : ∃ g : C^n⟮I, M; 𝓘(ℝ, F), F⟯, ∀ x, g x ∈ t x := begin choose U hU g hgs hgt using Hloc, obtain ⟨f, hf⟩ := smooth_partition_of_unity.exists_is_subordinate I is_closed_univ (λ x, interior (U x)) (λ x, is_open_interior) (λ x hx, mem_Union.2 ⟨x, mem_interior_iff_mem_nhds.2 (hU x)⟩), refine ⟨⟨λ x, ∑ᶠ i, f i x • g i x, hf.cont_mdiff_finsum_smul (λ i, is_open_interior) $ λ i, (hgs i).mono interior_subset⟩, λ x, f.finsum_smul_mem_convex (mem_univ x) (λ i hi, hgt _ _ _) (ht _)⟩, exact interior_subset (hf _ $ subset_closure hi) end /-- Let `M` be a σ-compact Hausdorff finite dimensional topological manifold. Let `t : M → set F` be a family of convex sets. Suppose that for each point `x : M` there exists a neighborhood `U ∈ 𝓝 x` and a function `g : M → F` such that `g` is smooth on `U` and `g y ∈ t y` for all `y ∈ U`. Then there exists a smooth function `g : C^∞⟮I, M; 𝓘(ℝ, F), F⟯` such that `g x ∈ t x` for all `x`. See also `exists_cont_mdiff_forall_mem_convex_of_local` and `exists_smooth_forall_mem_convex_of_local_const`. -/ lemma exists_smooth_forall_mem_convex_of_local (ht : ∀ x, convex ℝ (t x)) (Hloc : ∀ x : M, ∃ (U ∈ 𝓝 x) (g : M → F), smooth_on I 𝓘(ℝ, F) g U ∧ ∀ y ∈ U, g y ∈ t y) : ∃ g : C^∞⟮I, M; 𝓘(ℝ, F), F⟯, ∀ x, g x ∈ t x := exists_cont_mdiff_forall_mem_convex_of_local I ht Hloc /-- Let `M` be a σ-compact Hausdorff finite dimensional topological manifold. Let `t : M → set F` be a family of convex sets. Suppose that for each point `x : M` there exists a vector `c : F` such that for all `y` in a neighborhood of `x` we have `c ∈ t y`. Then there exists a smooth function `g : C^∞⟮I, M; 𝓘(ℝ, F), F⟯` such that `g x ∈ t x` for all `x`. See also `exists_cont_mdiff_forall_mem_convex_of_local` and `exists_smooth_forall_mem_convex_of_local`. -/ lemma exists_smooth_forall_mem_convex_of_local_const (ht : ∀ x, convex ℝ (t x)) (Hloc : ∀ x : M, ∃ c : F, ∀ᶠ y in 𝓝 x, c ∈ t y) : ∃ g : C^∞⟮I, M; 𝓘(ℝ, F), F⟯, ∀ x, g x ∈ t x := exists_smooth_forall_mem_convex_of_local I ht $ λ x, let ⟨c, hc⟩ := Hloc x in ⟨_, hc, λ _, c, smooth_on_const, λ y, id⟩ /-- Let `M` be a smooth σ-compact manifold with extended distance. Let `K : ι → set M` be a locally finite family of closed sets, let `U : ι → set M` be a family of open sets such that `K i ⊆ U i` for all `i`. Then there exists a positive smooth function `δ : M → ℝ≥0` such that for any `i` and `x ∈ K i`, we have `emetric.closed_ball x (δ x) ⊆ U i`. -/ lemma emetric.exists_smooth_forall_closed_ball_subset {M} [emetric_space M] [charted_space H M] [smooth_manifold_with_corners I M] [sigma_compact_space M] {K : ι → set M} {U : ι → set M} (hK : ∀ i, is_closed (K i)) (hU : ∀ i, is_open (U i)) (hKU : ∀ i, K i ⊆ U i) (hfin : locally_finite K) : ∃ δ : C^∞⟮I, M; 𝓘(ℝ, ℝ), ℝ⟯, (∀ x, 0 < δ x) ∧ ∀ i (x ∈ K i), emetric.closed_ball x (ennreal.of_real (δ x)) ⊆ U i := by simpa only [mem_inter_iff, forall_and_distrib, mem_preimage, mem_Inter, @forall_swap ι M] using exists_smooth_forall_mem_convex_of_local_const I emetric.exists_forall_closed_ball_subset_aux₂ (emetric.exists_forall_closed_ball_subset_aux₁ hK hU hKU hfin) /-- Let `M` be a smooth σ-compact manifold with a metric. Let `K : ι → set M` be a locally finite family of closed sets, let `U : ι → set M` be a family of open sets such that `K i ⊆ U i` for all `i`. Then there exists a positive smooth function `δ : M → ℝ≥0` such that for any `i` and `x ∈ K i`, we have `metric.closed_ball x (δ x) ⊆ U i`. -/ lemma metric.exists_smooth_forall_closed_ball_subset {M} [metric_space M] [charted_space H M] [smooth_manifold_with_corners I M] [sigma_compact_space M] {K : ι → set M} {U : ι → set M} (hK : ∀ i, is_closed (K i)) (hU : ∀ i, is_open (U i)) (hKU : ∀ i, K i ⊆ U i) (hfin : locally_finite K) : ∃ δ : C^∞⟮I, M; 𝓘(ℝ, ℝ), ℝ⟯, (∀ x, 0 < δ x) ∧ ∀ i (x ∈ K i), metric.closed_ball x (δ x) ⊆ U i := begin rcases emetric.exists_smooth_forall_closed_ball_subset I hK hU hKU hfin with ⟨δ, hδ0, hδ⟩, refine ⟨δ, hδ0, λ i x hx, _⟩, rw [← metric.emetric_closed_ball (hδ0 _).le], exact hδ i x hx end
4596274e419e183931abee2feae646676b1b8245
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/ring_theory/witt_vector/witt_polynomial.lean
4d3d03cc81fb734332ff203d0c40eb921d806189
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
10,588
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Robert Y. Lewis -/ import algebra.invertible import data.mv_polynomial.variables import data.mv_polynomial.comm_ring import data.mv_polynomial.expand import data.zmod.basic open mv_polynomial open finset (hiding map) open finsupp (single) open_locale big_operators local attribute [-simp] coe_eval₂_hom variables (p : ℕ) variables (R : Type*) [comm_ring R] /-! # Witt polynomials To endow `witt_vector p R` with a ring structure, we need to study the so-called Witt polynomials. Fix a base value `p : ℕ`. The `p`-adic Witt polynomials are an infinite family of polynomials indexed by a natural number `n`, taking values in an arbitrary ring `R`. The variables of these polynomials are represented by natural numbers. The variable set of the `n`th Witt polynomial contains at most `n+1` elements `{0, ..., n}`, with exactly these variables when `R` has characteristic `0`. These polynomials are used to define the addition and multiplication operators on the type of Witt vectors. (While this type itself is not complicated, the ring operations are what make it interesting.) When the base `p` is invertible in `R`, the `p`-adic Witt polynomials form a basis for `mv_polynomial ℕ R`, equivalent to the standard basis. ## Main declarations * `witt_polynomial p R n`: the `n`-th Witt polynomial, viewed as polynomial over the ring `R` * `X_in_terms_of_W p R n`: if `p` is invertible, the polynomial `X n` is contained in the subalgebra generated by the Witt polynomials. `X_in_terms_of_W p R n` is the explicit polynomial, which upon being bound to the Witt polynomials yields `X n`. * `bind₁_witt_polynomial_X_in_terms_of_W`: the proof of the claim that `bind₁ (X_in_terms_of_W p R) (W_ R n) = X n` * `bind₁_X_in_terms_of_W_witt_polynomial`: the converse of the above statement ## Notation In this file we use the following notation * `p` is a natural number, typically assumed to be prime. * `R` and `S` are commutative rings * `W n` (and `W_ R n` when the ring needs to be explicit) denotes the `n`th Witt polynomial -/ /-- `witt_polynomial p R n` is the `n`-th Witt polynomial with respect to a prime `p` with coefficients in a commutative ring `R`. It is defined as: `∑_{i ≤ n} p^i X_i^{p^{n-i}} ∈ R[X_0, X_1, X_2, …]`. -/ noncomputable def witt_polynomial (n : ℕ) : mv_polynomial ℕ R := ∑ i in range (n+1), monomial (single i (p ^ (n - i))) (p ^ i) lemma witt_polynomial_eq_sum_C_mul_X_pow (n : ℕ) : witt_polynomial p R n = ∑ i in range (n+1), C (p ^ i : R) * X i ^ (p ^ (n - i)) := begin apply sum_congr rfl, rintro i -, rw [monomial_eq, finsupp.prod_single_index], rw pow_zero, end /-! We set up notation locally to this file, to keep statements short and comprehensible. This allows us to simply write `W n` or `W_ ℤ n`. -/ -- Notation with ring of coefficients explicit localized "notation `W_` := witt_polynomial p" in witt -- Notation with ring of coefficients implicit localized "notation `W` := witt_polynomial p _" in witt open_locale witt open mv_polynomial /- The first observation is that the Witt polynomial doesn't really depend on the coefficient ring. If we map the coefficients through a ring homomorphism, we obtain the corresponding Witt polynomial over the target ring. -/ section variables {R} {S : Type*} [comm_ring S] @[simp] lemma map_witt_polynomial (f : R →+* S) (n : ℕ) : map f (W n) = W n := begin rw [witt_polynomial, ring_hom.map_sum, witt_polynomial, sum_congr rfl], intros i hi, rw [map_monomial, ring_hom.map_pow, ring_hom.map_nat_cast], end variables (R) @[simp] lemma constant_coeff_witt_polynomial [hp : fact p.prime] (n : ℕ) : constant_coeff (witt_polynomial p R n) = 0 := begin simp only [witt_polynomial, ring_hom.map_sum, constant_coeff_monomial], rw [sum_eq_zero], rintro i hi, rw [if_neg], rw [finsupp.single_eq_zero], exact ne_of_gt (pow_pos hp.pos _) end @[simp] lemma witt_polynomial_zero : witt_polynomial p R 0 = X 0 := by simp only [witt_polynomial, X, sum_singleton, range_one, pow_zero] @[simp] lemma witt_polynomial_one : witt_polynomial p R 1 = C ↑p * X 1 + (X 0) ^ p := by simp only [witt_polynomial_eq_sum_C_mul_X_pow, sum_range_succ, range_one, sum_singleton, one_mul, pow_one, C_1, pow_zero] lemma aeval_witt_polynomial {A : Type*} [comm_ring A] [algebra R A] (f : ℕ → A) (n : ℕ) : aeval f (W_ R n) = ∑ i in range (n+1), p^i * (f i) ^ (p ^ (n-i)) := by simp [witt_polynomial, alg_hom.map_sum, aeval_monomial, finsupp.prod_single_index] /-- Over the ring `zmod (p^(n+1))`, we produce the `n+1`st Witt polynomial by expanding the `n`th witt polynomial by `p`. -/ @[simp] lemma witt_polynomial_zmod_self (n : ℕ) : W_ (zmod (p ^ (n + 1))) (n + 1) = expand p (W_ (zmod (p^(n + 1))) n) := begin simp only [witt_polynomial_eq_sum_C_mul_X_pow], rw [sum_range_succ, ← nat.cast_pow, char_p.cast_eq_zero (zmod (p^(n+1))) (p^(n+1)), C_0, zero_mul, zero_add, alg_hom.map_sum, sum_congr rfl], intros k hk, rw [alg_hom.map_mul, alg_hom.map_pow, expand_X, alg_hom_C, ← pow_mul, ← pow_succ], congr, rw mem_range at hk, omega end section p_prime -- in fact, `0 < p` would be sufficient variables [hp : fact p.prime] include hp lemma witt_polynomial_vars [char_zero R] (n : ℕ) : (witt_polynomial p R n).vars = range (n + 1) := begin have : ∀ i, (monomial (finsupp.single i (p ^ (n - i))) (p ^ i : R)).vars = {i}, { intro i, rw vars_monomial_single, { rw ← pos_iff_ne_zero, apply pow_pos hp.pos }, { rw [← nat.cast_pow, nat.cast_ne_zero], apply ne_of_gt, apply pow_pos hp.pos i } }, rw [witt_polynomial, vars_sum_of_disjoint], { simp only [this, int.nat_cast_eq_coe_nat, bind_singleton_eq_self], }, { simp only [this, int.nat_cast_eq_coe_nat], intros a b h, apply singleton_disjoint.mpr, rwa mem_singleton, }, end lemma witt_polynomial_vars_subset (n : ℕ) : (witt_polynomial p R n).vars ⊆ range (n + 1) := begin rw [← map_witt_polynomial p (int.cast_ring_hom R), ← witt_polynomial_vars p ℤ], apply vars_map, end end p_prime end /-! ## Witt polynomials as a basis of the polynomial algebra If `p` is invertible in `R`, then the Witt polynomials form a basis of the polynomial algebra `mv_polynomial ℕ R`. The polynomials `X_in_terms_of_W` give the coordinate transformation in the backwards direction. -/ /-- The `X_in_terms_of_W p R n` is the polynomial on the basis of Witt polynomials that corresponds to the ordinary `X n`. -/ noncomputable def X_in_terms_of_W [invertible (p : R)] : ℕ → mv_polynomial ℕ R | n := (X n - (∑ i : fin n, have _ := i.2, (C (p^(i : ℕ) : R) * (X_in_terms_of_W i)^(p^(n-i))))) * C (⅟p ^ n : R) lemma X_in_terms_of_W_eq [invertible (p : R)] {n : ℕ} : X_in_terms_of_W p R n = (X n - (∑ i in range n, C (p^i : R) * X_in_terms_of_W p R i ^ p ^ (n - i))) * C (⅟p ^ n : R) := by { rw [X_in_terms_of_W, ← fin.sum_univ_eq_sum_range] } @[simp] lemma constant_coeff_X_in_terms_of_W [hp : fact p.prime] [invertible (p : R)] (n : ℕ) : constant_coeff (X_in_terms_of_W p R n) = 0 := begin apply nat.strong_induction_on n; clear n, intros n IH, rw [X_in_terms_of_W_eq, mul_comm, ring_hom.map_mul, ring_hom.map_sub, ring_hom.map_sum, constant_coeff_C, sum_eq_zero], { simp only [constant_coeff_X, sub_zero, mul_zero] }, { intros m H, rw mem_range at H, simp only [ring_hom.map_mul, ring_hom.map_pow, constant_coeff_C, IH m H], rw [zero_pow, mul_zero], apply pow_pos hp.pos, } end @[simp] lemma X_in_terms_of_W_zero [invertible (p : R)] : X_in_terms_of_W p R 0 = X 0 := by rw [X_in_terms_of_W_eq, range_zero, sum_empty, pow_zero, C_1, mul_one, sub_zero] section p_prime variables [hp : fact p.prime] include hp lemma X_in_terms_of_W_vars_aux (n : ℕ) : n ∈ (X_in_terms_of_W p ℚ n).vars ∧ (X_in_terms_of_W p ℚ n).vars ⊆ range (n + 1) := begin apply nat.strong_induction_on n, clear n, intros n ih, rw [X_in_terms_of_W_eq, mul_comm, vars_C_mul, vars_sub_of_disjoint, vars_X, range_succ, insert_eq], swap 3, { apply nonzero_of_invertible }, work_on_goal 0 { simp only [true_and, true_or, eq_self_iff_true, mem_union, mem_singleton], intro i, rw [mem_union, mem_union], apply or.imp id }, work_on_goal 1 { rw [vars_X, singleton_disjoint] }, all_goals { intro H, replace H := vars_sum_subset _ _ H, rw mem_bind at H, rcases H with ⟨j, hj, H⟩, rw vars_C_mul at H, swap, { apply pow_ne_zero, exact_mod_cast hp.ne_zero }, rw mem_range at hj, replace H := (ih j hj).2 (vars_pow _ _ H), rw mem_range at H }, { rw mem_range, exact lt_of_lt_of_le H hj }, { exact lt_irrefl n (lt_of_lt_of_le H hj) }, end lemma X_in_terms_of_W_vars_subset (n : ℕ) : (X_in_terms_of_W p ℚ n).vars ⊆ range (n + 1) := (X_in_terms_of_W_vars_aux p n).2 end p_prime lemma X_in_terms_of_W_aux [invertible (p : R)] (n : ℕ) : X_in_terms_of_W p R n * C (p^n : R) = X n - ∑ i in range n, C (p^i : R) * (X_in_terms_of_W p R i)^p^(n-i) := by rw [X_in_terms_of_W_eq, mul_assoc, ← C_mul, ← mul_pow, inv_of_mul_self, one_pow, C_1, mul_one] @[simp] lemma bind₁_X_in_terms_of_W_witt_polynomial [invertible (p : R)] (k : ℕ) : bind₁ (X_in_terms_of_W p R) (W_ R k) = X k := begin rw [witt_polynomial_eq_sum_C_mul_X_pow, alg_hom.map_sum], simp only [alg_hom.map_pow, C_pow, alg_hom.map_mul, alg_hom_C], rw [sum_range_succ, nat.sub_self, pow_zero, pow_one, bind₁_X_right, mul_comm, ← C_pow, X_in_terms_of_W_aux], simp only [C_pow, bind₁_X_right, sub_add_cancel], end @[simp] lemma bind₁_witt_polynomial_X_in_terms_of_W [invertible (p : R)] (n : ℕ) : bind₁ (W_ R) (X_in_terms_of_W p R n) = X n := begin apply nat.strong_induction_on n, clear n, intros n H, rw [X_in_terms_of_W_eq, alg_hom.map_mul, alg_hom.map_sub, bind₁_X_right, alg_hom_C, alg_hom.map_sum], have : W_ R n - ∑ i in range n, C (p ^ i : R) * (X i) ^ p ^ (n - i) = C (p ^ n : R) * X n, by simp only [witt_polynomial_eq_sum_C_mul_X_pow, nat.sub_self, sum_range_succ, pow_one, add_sub_cancel, pow_zero], rw [sum_congr rfl, this], { -- this is really slow for some reason rw [mul_right_comm, ← C_mul, ← mul_pow, mul_inv_of_self, one_pow, C_1, one_mul] }, { intros i h, rw mem_range at h, simp only [alg_hom.map_mul, alg_hom.map_pow, alg_hom_C, H i h] }, end
3608451c3a5efa073f1e7f61e14fb563ceee08f8
90fa9fe9dea3618a11a131395140bd5365706e2b
/update.lean
613e1e7b3df8831580f1dc7f5119432b3aea545f
[]
no_license
Grayson9352/fortnite
5a303b0bb77724f70f3e3c45606ca0b2dec07fa1
b9abbb9f1394ad1048c38e59dbcc3167b8c4f2dd
refs/heads/main
1,682,798,000,276
1,621,638,863,000
1,621,638,863,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10
lean
x\0040XaR
605be1ddd76f769fda5a061b0989c8564f6ac7a1
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/computability/partrec.lean
c5a3c13381e7391bfc1e22e347f8da9cf8fd813a
[ "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
28,206
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro The partial recursive functions are defined similarly to the primitive recursive functions, but now all functions are partial, implemented using the `roption` monad, and there is an additional operation, called μ-recursion, which performs unbounded minimization. -/ import computability.primrec data.pfun open encodable denumerable roption namespace nat section rfind parameter (p : ℕ →. bool) private def lbp (m n : ℕ) : Prop := m = n + 1 ∧ ∀ k ≤ n, ff ∈ p k parameter (H : ∃ n, tt ∈ p n ∧ ∀ k < n, (p k).dom) private def wf_lbp : well_founded lbp := ⟨let ⟨n, pn⟩ := H in begin suffices : ∀m k, n ≤ k + m → acc (lbp p) k, { from λa, this _ _ (nat.le_add_left _ _) }, intros m k kn, induction m with m IH generalizing k; refine ⟨_, λ y r, _⟩; rcases r with ⟨rfl, a⟩, { injection mem_unique pn.1 (a _ kn) }, { exact IH _ (by rw nat.add_right_comm; exact kn) } end⟩ def rfind_x : {n // tt ∈ p n ∧ ∀m < n, ff ∈ p m} := suffices ∀ k, (∀n < k, ff ∈ p n) → {n // tt ∈ p n ∧ ∀m < n, ff ∈ p m}, from this 0 (λ n, (nat.not_lt_zero _).elim), @well_founded.fix _ _ lbp wf_lbp begin intros m IH al, have pm : (p m).dom, { rcases H with ⟨n, h₁, h₂⟩, rcases decidable.lt_trichotomy m n with h₃|h₃|h₃, { exact h₂ _ h₃ }, { rw h₃, exact h₁.fst }, { injection mem_unique h₁ (al _ h₃) } }, cases e : (p m).get pm, { suffices, exact IH _ ⟨rfl, this⟩ (λ n h, this _ (le_of_lt_succ h)), intros n h, cases decidable.lt_or_eq_of_le h with h h, { exact al _ h }, { rw h, exact ⟨_, e⟩ } }, { exact ⟨m, ⟨_, e⟩, al⟩ } end end rfind def rfind (p : ℕ →. bool) : roption ℕ := ⟨_, λ h, (rfind_x p h).1⟩ theorem rfind_spec {p : ℕ →. bool} {n : ℕ} (h : n ∈ rfind p) : tt ∈ p n := h.snd ▸ (rfind_x p h.fst).2.1 theorem rfind_min {p : ℕ →. bool} {n : ℕ} (h : n ∈ rfind p) : ∀ {m : ℕ}, m < n → ff ∈ p m := h.snd ▸ (rfind_x p h.fst).2.2 @[simp] theorem rfind_dom {p : ℕ →. bool} : (rfind p).dom ↔ ∃ n, tt ∈ p n ∧ ∀ {m : ℕ}, m < n → (p m).dom := iff.rfl @[simp] theorem rfind_dom' {p : ℕ →. bool} : (rfind p).dom ↔ ∃ n, tt ∈ p n ∧ ∀ {m : ℕ}, m ≤ n → (p m).dom := exists_congr $ λ n, and_congr_right $ λ pn, ⟨λ H m h, (eq_or_lt_of_le h).elim (λ e, e.symm ▸ pn.fst) (H _), λ H m h, H (le_of_lt h)⟩ @[simp] theorem mem_rfind {p : ℕ →. bool} {n : ℕ} : n ∈ rfind p ↔ tt ∈ p n ∧ ∀ {m : ℕ}, m < n → ff ∈ p m := ⟨λ h, ⟨rfind_spec h, @rfind_min _ _ h⟩, λ ⟨h₁, h₂⟩, let ⟨m, hm⟩ := dom_iff_mem.1 $ (@rfind_dom p).2 ⟨_, h₁, λ m mn, (h₂ mn).fst⟩ in begin rcases lt_trichotomy m n with h|h|h, { injection mem_unique (h₂ h) (rfind_spec hm) }, { rwa ← h }, { injection mem_unique h₁ (rfind_min hm h) }, end⟩ theorem rfind_min' {p : ℕ → bool} {m : ℕ} (pm : p m) : ∃ n ∈ rfind p, n ≤ m := have tt ∈ (p : ℕ →. bool) m, from ⟨trivial, pm⟩, let ⟨n, hn⟩ := dom_iff_mem.1 $ (@rfind_dom p).2 ⟨m, this, λ k h, ⟨⟩⟩ in ⟨n, hn, not_lt.1 $ λ h, by injection mem_unique this (rfind_min hn h)⟩ theorem rfind_zero_none (p : ℕ →. bool) (p0 : p 0 = none) : rfind p = none := eq_none_iff.2 $ λ a h, let ⟨n, h₁, h₂⟩ := rfind_dom'.1 h.fst in (p0 ▸ h₂ (zero_le _) : (@roption.none bool).dom) def rfind_opt {α} (f : ℕ → option α) : roption α := (rfind (λ n, (f n).is_some)).bind (λ n, f n) theorem rfind_opt_spec {α} {f : ℕ → option α} {a} (h : a ∈ rfind_opt f) : ∃ n, a ∈ f n := let ⟨n, h₁, h₂⟩ := mem_bind_iff.1 h in ⟨n, mem_coe.1 h₂⟩ theorem rfind_opt_dom {α} {f : ℕ → option α} : (rfind_opt f).dom ↔ ∃ n a, a ∈ f n := ⟨λ h, (rfind_opt_spec ⟨h, rfl⟩).imp (λ n h, ⟨_, h⟩), λ h, begin have h' : ∃ n, (f n).is_some := h.imp (λ n, option.is_some_iff_exists.2), have s := nat.find_spec h', have fd : (rfind (λ n, (f n).is_some)).dom := ⟨nat.find h', by simpa using s.symm, λ _ _, trivial⟩, refine ⟨fd, _⟩, have := rfind_spec (get_mem fd), simp at this ⊢, cases option.is_some_iff_exists.1 this.symm with a e, rw e, trivial end⟩ theorem rfind_opt_mono {α} {f : ℕ → option α} (H : ∀ {a m n}, m ≤ n → a ∈ f m → a ∈ f n) {a} : a ∈ rfind_opt f ↔ ∃ n, a ∈ f n := ⟨rfind_opt_spec, λ ⟨n, h⟩, begin have h' := rfind_opt_dom.2 ⟨_, _, h⟩, cases rfind_opt_spec ⟨h', rfl⟩ with k hk, have := (H (le_max_left _ _) h).symm.trans (H (le_max_right _ _) hk), simp at this, simp [this, get_mem] end⟩ inductive partrec : (ℕ →. ℕ) → Prop | zero : partrec (pure 0) | succ : partrec succ | left : partrec (λ n, n.unpair.1) | right : partrec (λ n, n.unpair.2) | pair {f g} : partrec f → partrec g → partrec (λ n, mkpair <$> f n <*> g n) | comp {f g} : partrec f → partrec g → partrec (λ n, g n >>= f) | prec {f g} : partrec f → partrec g → partrec (unpaired (λ a n, n.elim (f a) (λ y IH, do i ← IH, g (mkpair a (mkpair y i))))) | rfind {f} : partrec f → partrec (λ a, rfind (λ n, (λ m, m = 0) <$> f (mkpair a n))) namespace partrec theorem of_eq {f g : ℕ →. ℕ} (hf : partrec f) (H : ∀ n, f n = g n) : partrec g := (funext H : f = g) ▸ hf theorem of_eq_tot {f : ℕ →. ℕ} {g : ℕ → ℕ} (hf : partrec f) (H : ∀ n, g n ∈ f n) : partrec g := hf.of_eq (λ n, eq_some_iff.2 (H n)) theorem of_primrec {f : ℕ → ℕ} (hf : primrec f) : partrec f := begin induction hf, case nat.primrec.zero { exact zero }, case nat.primrec.succ { exact succ }, case nat.primrec.left { exact left }, case nat.primrec.right { exact right }, case nat.primrec.pair : f g hf hg pf pg { refine (pf.pair pg).of_eq_tot (λ n, _), simp [has_seq.seq] }, case nat.primrec.comp : f g hf hg pf pg { refine (pf.comp pg).of_eq_tot (λ n, _), simp }, case nat.primrec.prec : f g hf hg pf pg { refine (pf.prec pg).of_eq_tot (λ n, _), simp, induction n.unpair.2 with m IH, {simp}, simp, exact ⟨_, IH, rfl⟩ }, end protected theorem some : partrec some := of_primrec primrec.id theorem none : partrec (λ n, none) := (of_primrec (nat.primrec.const 1)).rfind.of_eq $ λ n, eq_none_iff.2 $ λ a ⟨h, e⟩, by simpa using h theorem prec' {f g h} (hf : partrec f) (hg : partrec g) (hh : partrec h) : partrec (λ a, (f a).bind (λ n, n.elim (g a) (λ y IH, do i ← IH, h (mkpair a (mkpair y i))))) := ((prec hg hh).comp (pair partrec.some hf)).of_eq $ λ a, ext $ λ s, by simp [(<*>)]; exact ⟨λ ⟨n, h₁, h₂⟩, ⟨_, ⟨_, h₁, rfl⟩, by simpa using h₂⟩, λ ⟨_, ⟨n, h₁, rfl⟩, h₂⟩, ⟨_, h₁, by simpa using h₂⟩⟩ theorem ppred : partrec (λ n, ppred n) := have primrec₂ (λ n m, if n = nat.succ m then 0 else 1), from (primrec.ite (@@primrec_rel.comp _ _ _ _ _ _ _ primrec.eq primrec.fst (_root_.primrec.succ.comp primrec.snd)) (_root_.primrec.const 0) (_root_.primrec.const 1)).to₂, (of_primrec (primrec₂.unpaired'.2 this)).rfind.of_eq $ λ n, begin cases n; simp, { exact eq_none_iff.2 (λ a ⟨⟨m, h, _⟩, _⟩, by simpa [show 0 ≠ m.succ, by intro h; injection h] using h) }, { refine eq_some_iff.2 _, simp, intros m h, simp [ne_of_gt h] } end end partrec end nat def partrec {α σ} [primcodable α] [primcodable σ] (f : α →. σ) := nat.partrec (λ n, roption.bind (decode α n) (λ a, (f a).map encode)) def partrec₂ {α β σ} [primcodable α] [primcodable β] [primcodable σ] (f : α → β →. σ) := partrec (λ p : α × β, f p.1 p.2) def computable {α σ} [primcodable α] [primcodable σ] (f : α → σ) := partrec (f : α →. σ) def computable₂ {α β σ} [primcodable α] [primcodable β] [primcodable σ] (f : α → β → σ) := computable (λ p : α × β, f p.1 p.2) theorem primrec.to_comp {α σ} [primcodable α] [primcodable σ] {f : α → σ} (hf : primrec f) : computable f := (nat.partrec.ppred.comp (nat.partrec.of_primrec hf)).of_eq $ λ n, by simp; cases decode α n; simp theorem primrec₂.to_comp {α β σ} [primcodable α] [primcodable β] [primcodable σ] {f : α → β → σ} (hf : primrec₂ f) : computable₂ f := hf.to_comp theorem computable.part {α σ} [primcodable α] [primcodable σ] {f : α → σ} (hf : computable f) : partrec (f : α →. σ) := hf theorem computable₂.part {α β σ} [primcodable α] [primcodable β] [primcodable σ] {f : α → β → σ} (hf : computable₂ f) : partrec₂ (λ a, (f a : β →. σ)) := hf namespace computable variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem of_eq {f g : α → σ} (hf : computable f) (H : ∀ n, f n = g n) : computable g := (funext H : f = g) ▸ hf theorem const (s : σ) : computable (λ a : α, s) := (primrec.const _).to_comp theorem of_option {f : α → option β} (hf : computable f) : partrec (λ a, (f a : roption β)) := (nat.partrec.ppred.comp hf).of_eq $ λ n, begin cases decode α n with a; simp, cases f a with b; simp end theorem to₂ {f : α × β → σ} (hf : computable f) : computable₂ (λ a b, f (a, b)) := hf.of_eq $ λ ⟨a, b⟩, rfl protected theorem id : computable (@id α) := primrec.id.to_comp theorem fst : computable (@prod.fst α β) := primrec.fst.to_comp theorem snd : computable (@prod.snd α β) := primrec.snd.to_comp theorem pair {f : α → β} {g : α → γ} (hf : computable f) (hg : computable g) : computable (λ a, (f a, g a)) := (hf.pair hg).of_eq $ λ n, by cases decode α n; simp [(<*>)] theorem unpair : computable nat.unpair := primrec.unpair.to_comp theorem succ : computable nat.succ := primrec.succ.to_comp theorem pred : computable nat.pred := primrec.pred.to_comp theorem nat_bodd : computable nat.bodd := primrec.nat_bodd.to_comp theorem nat_div2 : computable nat.div2 := primrec.nat_div2.to_comp theorem sum_inl : computable (@sum.inl α β) := primrec.sum_inl.to_comp theorem sum_inr : computable (@sum.inr α β) := primrec.sum_inr.to_comp theorem list_cons : computable₂ (@list.cons α) := primrec.list_cons.to_comp theorem list_reverse : computable (@list.reverse α) := primrec.list_reverse.to_comp theorem list_nth : computable₂ (@list.nth α) := primrec.list_nth.to_comp theorem list_append : computable₂ ((++) : list α → list α → list α) := primrec.list_append.to_comp theorem list_concat : computable₂ (λ l (a:α), l ++ [a]) := primrec.list_concat.to_comp theorem list_length : computable (@list.length α) := primrec.list_length.to_comp theorem vector_cons {n} : computable₂ (@vector.cons α n) := primrec.vector_cons.to_comp theorem vector_to_list {n} : computable (@vector.to_list α n) := primrec.vector_to_list.to_comp theorem vector_length {n} : computable (@vector.length α n) := primrec.vector_length.to_comp theorem vector_head {n} : computable (@vector.head α n) := primrec.vector_head.to_comp theorem vector_tail {n} : computable (@vector.tail α n) := primrec.vector_tail.to_comp theorem vector_nth {n} : computable₂ (@vector.nth α n) := primrec.vector_nth.to_comp theorem vector_nth' {n} : computable (@vector.nth α n) := primrec.vector_nth'.to_comp theorem vector_of_fn' {n} : computable (@vector.of_fn α n) := primrec.vector_of_fn'.to_comp theorem fin_app {n} : computable₂ (@id (fin n → σ)) := primrec.fin_app.to_comp protected theorem encode : computable (@encode α _) := primrec.encode.to_comp protected theorem decode : computable (decode α) := primrec.decode.to_comp protected theorem of_nat (α) [denumerable α] : computable (of_nat α) := (primrec.of_nat _).to_comp theorem encode_iff {f : α → σ} : computable (λ a, encode (f a)) ↔ computable f := iff.rfl theorem option_some : computable (@option.some α) := primrec.option_some.to_comp end computable namespace partrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] open computable theorem of_eq {f g : α →. σ} (hf : partrec f) (H : ∀ n, f n = g n) : partrec g := (funext H : f = g) ▸ hf theorem of_eq_tot {f : α →. σ} {g : α → σ} (hf : partrec f) (H : ∀ n, g n ∈ f n) : computable g := hf.of_eq (λ a, eq_some_iff.2 (H a)) theorem none : partrec (λ a : α, @roption.none σ) := nat.partrec.none.of_eq $ λ n, by cases decode α n; simp protected theorem some : partrec (@roption.some α) := computable.id theorem const' (s : roption σ) : partrec (λ a : α, s) := by haveI := classical.dec s.dom; exact (of_option (const (to_option s))).of_eq (λ a, of_to_option s) protected theorem bind {f : α →. β} {g : α → β →. σ} (hf : partrec f) (hg : partrec₂ g) : partrec (λ a, (f a).bind (g a)) := (hg.comp (nat.partrec.some.pair hf)).of_eq $ λ n, by simp [(<*>)]; cases e : decode α n with a; simp [e, encodek] theorem map {f : α →. β} {g : α → β → σ} (hf : partrec f) (hg : computable₂ g) : partrec (λ a, (f a).map (g a)) := by simpa [bind_some_eq_map] using @@partrec.bind _ _ _ (λ a b, roption.some (g a b)) hf hg theorem to₂ {f : α × β →. σ} (hf : partrec f) : partrec₂ (λ a b, f (a, b)) := hf.of_eq $ λ ⟨a, b⟩, rfl theorem nat_elim {f : α → ℕ} {g : α →. σ} {h : α → ℕ × σ →. σ} (hf : computable f) (hg : partrec g) (hh : partrec₂ h) : partrec (λ a, (f a).elim (g a) (λ y IH, IH.bind (λ i, h a (y, i)))) := (nat.partrec.prec' hf hg hh).of_eq $ λ n, begin cases e : decode α n with a; simp [e], induction f a with m IH; simp, rw [IH, bind_map], congr, funext s, simp [encodek] end theorem comp {f : β →. σ} {g : α → β} (hf : partrec f) (hg : computable g) : partrec (λ a, f (g a)) := (hf.comp hg).of_eq $ λ n, by simp; cases e : decode α n with a; simp [e, encodek] theorem nat_iff {f : ℕ →. ℕ} : partrec f ↔ nat.partrec f := by simp [partrec, map_id'] theorem map_encode_iff {f : α →. σ} : partrec (λ a, (f a).map encode) ↔ partrec f := iff.rfl end partrec namespace partrec₂ variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] theorem unpaired {f : ℕ → ℕ →. α} : partrec (nat.unpaired f) ↔ partrec₂ f := ⟨λ h, by simpa using h.comp primrec₂.mkpair.to_comp, λ h, h.comp primrec.unpair.to_comp⟩ theorem unpaired' {f : ℕ → ℕ →. ℕ} : nat.partrec (nat.unpaired f) ↔ partrec₂ f := partrec.nat_iff.symm.trans unpaired theorem comp {f : β → γ →. σ} {g : α → β} {h : α → γ} (hf : partrec₂ f) (hg : computable g) (hh : computable h) : partrec (λ a, f (g a) (h a)) := hf.comp (hg.pair hh) theorem comp₂ {f : γ → δ →. σ} {g : α → β → γ} {h : α → β → δ} (hf : partrec₂ f) (hg : computable₂ g) (hh : computable₂ h) : partrec₂ (λ a b, f (g a b) (h a b)) := hf.comp hg hh end partrec₂ namespace computable variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem comp {f : β → σ} {g : α → β} (hf : computable f) (hg : computable g) : computable (λ a, f (g a)) := hf.comp hg theorem comp₂ {f : γ → σ} {g : α → β → γ} (hf : computable f) (hg : computable₂ g) : computable₂ (λ a b, f (g a b)) := hf.comp hg end computable namespace computable₂ variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] theorem comp {f : β → γ → σ} {g : α → β} {h : α → γ} (hf : computable₂ f) (hg : computable g) (hh : computable h) : computable (λ a, f (g a) (h a)) := hf.comp (hg.pair hh) theorem comp₂ {f : γ → δ → σ} {g : α → β → γ} {h : α → β → δ} (hf : computable₂ f) (hg : computable₂ g) (hh : computable₂ h) : computable₂ (λ a b, f (g a b) (h a b)) := hf.comp hg hh end computable₂ namespace partrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] open computable theorem rfind {p : α → ℕ →. bool} (hp : partrec₂ p) : partrec (λ a, nat.rfind (p a)) := (nat.partrec.rfind $ hp.map ((primrec.dom_bool (λ b, cond b 0 1)) .comp primrec.snd).to₂.to_comp).of_eq $ λ n, begin cases e : decode α n with a; simp [e, nat.rfind_zero_none, map_id'], congr, funext n, simp [roption.map_map, (∘)], apply map_id' (λ b, _), cases b; refl end theorem rfind_opt {f : α → ℕ → option σ} (hf : computable₂ f) : partrec (λ a, nat.rfind_opt (f a)) := (rfind (primrec.option_is_some.to_comp.comp hf).part.to₂).bind (of_option hf) theorem nat_cases_right {f : α → ℕ} {g : α → σ} {h : α → ℕ →. σ} (hf : computable f) (hg : computable g) (hh : partrec₂ h) : partrec (λ a, (f a).cases (some (g a)) (h a)) := (nat_elim hf hg (hh.comp fst (pred.comp $ hf.comp fst)).to₂).of_eq $ λ a, begin simp, cases f a; simp, refine ext (λ b, ⟨λ H, _, λ H, _⟩), { rcases mem_bind_iff.1 H with ⟨c, h₁, h₂⟩, exact h₂ }, { have : ∀ m, (nat.elim (roption.some (g a)) (λ y IH, IH.bind (λ _, h a n)) m).dom, { intro, induction m; simp [*, H.fst] }, exact ⟨⟨this n, H.fst⟩, H.snd⟩ } end theorem bind_decode2_iff {f : α →. σ} : partrec f ↔ nat.partrec (λ n, roption.bind (decode2 α n) (λ a, (f a).map encode)) := ⟨λ hf, nat_iff.1 $ (of_option primrec.decode2.to_comp).bind $ (map hf (computable.encode.comp snd).to₂).comp snd, λ h, map_encode_iff.1 $ by simpa [encodek2] using (nat_iff.2 h).comp (@computable.encode α _)⟩ theorem vector_m_of_fn : ∀ {n} {f : fin n → α →. σ}, (∀ i, partrec (f i)) → partrec (λ (a : α), vector.m_of_fn (λ i, f i a)) | 0 f hf := const _ | (n+1) f hf := by simp [vector.m_of_fn]; exact (hf 0).bind (partrec.bind ((vector_m_of_fn (λ i, hf i.succ)).comp fst) (primrec.vector_cons.to_comp.comp (snd.comp fst) snd)) end partrec @[simp] theorem vector.m_of_fn_roption_some {α n} : ∀ (f : fin n → α), vector.m_of_fn (λ i, roption.some (f i)) = roption.some (vector.of_fn f) := vector.m_of_fn_pure namespace computable variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem option_some_iff {f : α → σ} : computable (λ a, some (f a)) ↔ computable f := ⟨λ h, encode_iff.1 $ primrec.pred.to_comp.comp $ encode_iff.2 h, option_some.comp⟩ theorem bind_decode_iff {f : α → β → option σ} : computable₂ (λ a n, (decode β n).bind (f a)) ↔ computable₂ f := ⟨λ hf, nat.partrec.of_eq (((partrec.nat_iff.2 (nat.partrec.ppred.comp $ nat.partrec.of_primrec $ primcodable.prim β)).comp snd).bind (computable.comp hf fst).to₂.part) $ λ n, by simp; cases decode α n.unpair.1; simp; cases decode β n.unpair.2; simp, λ hf, begin have : partrec (λ a : α × ℕ, (encode (decode β a.2)).cases (some option.none) (λ n, roption.map (f a.1) (decode β n))) := partrec.nat_cases_right (primrec.encdec.to_comp.comp snd) (const none) ((of_option (computable.decode.comp snd)).map (hf.comp (fst.comp $ fst.comp fst) snd).to₂), refine this.of_eq (λ a, _), simp, cases decode β a.2; simp [encodek] end⟩ theorem map_decode_iff {f : α → β → σ} : computable₂ (λ a n, (decode β n).map (f a)) ↔ computable₂ f := bind_decode_iff.trans option_some_iff theorem nat_elim {f : α → ℕ} {g : α → σ} {h : α → ℕ × σ → σ} (hf : computable f) (hg : computable g) (hh : computable₂ h) : computable (λ a, (f a).elim (g a) (λ y IH, h a (y, IH))) := (partrec.nat_elim hf hg hh.part).of_eq $ λ a, by simp; induction f a; simp * theorem nat_cases {f : α → ℕ} {g : α → σ} {h : α → ℕ → σ} (hf : computable f) (hg : computable g) (hh : computable₂ h) : computable (λ a, (f a).cases (g a) (h a)) := nat_elim hf hg (hh.comp fst $ fst.comp snd).to₂ theorem cond {c : α → bool} {f : α → σ} {g : α → σ} (hc : computable c) (hf : computable f) (hg : computable g) : computable (λ a, cond (c a) (f a) (g a)) := (nat_cases (encode_iff.2 hc) hg (hf.comp fst).to₂).of_eq $ λ a, by cases c a; refl theorem option_cases {o : α → option β} {f : α → σ} {g : α → β → σ} (ho : computable o) (hf : computable f) (hg : computable₂ g) : @computable _ σ _ _ (λ a, option.cases_on (o a) (f a) (g a)) := option_some_iff.1 $ (nat_cases (encode_iff.2 ho) (option_some_iff.2 hf) (map_decode_iff.2 hg)).of_eq $ λ a, by cases o a; simp [encodek]; refl theorem option_bind {f : α → option β} {g : α → β → option σ} (hf : computable f) (hg : computable₂ g) : computable (λ a, (f a).bind (g a)) := (option_cases hf (const option.none) hg).of_eq $ λ a, by cases f a; refl theorem option_map {f : α → option β} {g : α → β → σ} (hf : computable f) (hg : computable₂ g) : computable (λ a, (f a).map (g a)) := option_bind hf (option_some.comp₂ hg) theorem sum_cases {f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ → σ} (hf : computable f) (hg : computable₂ g) (hh : computable₂ h) : @computable _ σ _ _ (λ a, sum.cases_on (f a) (g a) (h a)) := option_some_iff.1 $ (cond (nat_bodd.comp $ encode_iff.2 hf) (option_map (computable.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hh) (option_map (computable.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hg)).of_eq $ λ a, by cases f a with b c; simp [nat.div2_bit, nat.bodd_bit, encodek]; refl theorem nat_strong_rec (f : α → ℕ → σ) {g : α → list σ → option σ} (hg : computable₂ g) (H : ∀ a n, g a ((list.range n).map (f a)) = some (f a n)) : computable₂ f := suffices computable₂ (λ a n, (list.range n).map (f a)), from option_some_iff.1 $ (list_nth.comp (this.comp fst (succ.comp snd)) snd).to₂.of_eq $ λ a, by simp [list.nth_range (nat.lt_succ_self a.2)]; refl, option_some_iff.1 $ (nat_elim snd (const (option.some [])) (to₂ $ option_bind (snd.comp snd) $ to₂ $ option_map (hg.comp (fst.comp $ fst.comp fst) snd) (to₂ $ list_concat.comp (snd.comp fst) snd))).of_eq $ λ a, begin simp, induction a.2 with n IH, {refl}, simp [IH, H, list.range_concat] end theorem list_of_fn : ∀ {n} {f : fin n → α → σ}, (∀ i, computable (f i)) → computable (λ a, list.of_fn (λ i, f i a)) | 0 f hf := const [] | (n+1) f hf := by simp [list.of_fn_succ]; exact list_cons.comp (hf 0) (list_of_fn (λ i, hf i.succ)) theorem vector_of_fn {n} {f : fin n → α → σ} (hf : ∀ i, computable (f i)) : computable (λ a, vector.of_fn (λ i, f i a)) := (partrec.vector_m_of_fn hf).of_eq $ λ a, by simp end computable namespace partrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] open computable theorem option_some_iff {f : α →. σ} : partrec (λ a, (f a).map option.some) ↔ partrec f := ⟨λ h, (nat.partrec.ppred.comp h).of_eq $ λ n, by simp [roption.bind_assoc, bind_some_eq_map], λ hf, hf.map (option_some.comp snd).to₂⟩ theorem option_cases_right {o : α → option β} {f : α → σ} {g : α → β →. σ} (ho : computable o) (hf : computable f) (hg : partrec₂ g) : @partrec _ σ _ _ (λ a, option.cases_on (o a) (some (f a)) (g a)) := have partrec (λ (a : α), nat.cases (roption.some (f a)) (λ n, roption.bind (decode β n) (g a)) (encode (o a))) := nat_cases_right (encode_iff.2 ho) hf.part $ ((@computable.decode β _).comp snd).of_option.bind (hg.comp (fst.comp fst) snd).to₂, this.of_eq $ λ a, by cases o a with b; simp [encodek] theorem sum_cases_right {f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ →. σ} (hf : computable f) (hg : computable₂ g) (hh : partrec₂ h) : @partrec _ σ _ _ (λ a, sum.cases_on (f a) (λ b, some (g a b)) (h a)) := have partrec (λ a, (option.cases_on (sum.cases_on (f a) (λ b, option.none) option.some : option γ) (some (sum.cases_on (f a) (λ b, some (g a b)) (λ c, option.none))) (λ c, (h a c).map option.some) : roption (option σ))) := option_cases_right (sum_cases hf (const option.none).to₂ (option_some.comp snd).to₂) (sum_cases hf (option_some.comp hg) (const option.none).to₂) (option_some_iff.2 hh), option_some_iff.1 $ this.of_eq $ λ a, by cases f a; simp theorem sum_cases_left {f : α → β ⊕ γ} {g : α → β →. σ} {h : α → γ → σ} (hf : computable f) (hg : partrec₂ g) (hh : computable₂ h) : @partrec _ σ _ _ (λ a, sum.cases_on (f a) (g a) (λ c, some (h a c))) := (sum_cases_right (sum_cases hf (sum_inr.comp snd).to₂ (sum_inl.comp snd).to₂) hh hg).of_eq $ λ a, by cases f a; simp private lemma fix_aux {f : α →. σ ⊕ α} (hf : partrec f) (a : α) (b : σ) : let F : α → ℕ →. σ ⊕ α := λ a n, n.elim (some (sum.inr a)) $ λ y IH, IH.bind $ λ s, sum.cases_on s (λ _, roption.some s) f in (∃ (n : ℕ), ((∃ (b' : σ), sum.inl b' ∈ F a n) ∧ ∀ {m : ℕ}, m < n → (∃ (b : α), sum.inr b ∈ F a m)) ∧ sum.inl b ∈ F a n) ↔ b ∈ pfun.fix f a := begin intro, refine ⟨λ h, _, λ h, _⟩, { rcases h with ⟨n, ⟨_x, h₁⟩, h₂⟩, have : ∀ m a' (_: sum.inr a' ∈ F a m) (_: b ∈ pfun.fix f a'), b ∈ pfun.fix f a, { intros m a' am ba, induction m with m IH generalizing a'; simp [F] at am, { rwa ← am }, rcases am with ⟨a₂, am₂, fa₂⟩, exact IH _ am₂ (pfun.mem_fix_iff.2 (or.inr ⟨_, fa₂, ba⟩)) }, cases n; simp [F] at h₂, {cases h₂}, rcases h₂ with h₂ | ⟨a', am', fa'⟩, { cases h₁ (nat.lt_succ_self _) with a' h, injection mem_unique h h₂ }, { exact this _ _ am' (pfun.mem_fix_iff.2 (or.inl fa')) } }, { suffices : ∀ a' (_: b ∈ pfun.fix f a') k (_: sum.inr a' ∈ F a k), ∃ n, sum.inl b ∈ F a n ∧ ∀ (m < n) (_ : k ≤ m), ∃ a₂, sum.inr a₂ ∈ F a m, { rcases this _ h 0 (by simp [F]) with ⟨n, hn₁, hn₂⟩, exact ⟨_, ⟨⟨_, hn₁⟩, λ m mn, hn₂ m mn (nat.zero_le _)⟩, hn₁⟩ }, intros a₁ h₁, apply pfun.fix_induction h₁, intros a₂ h₂ IH k hk, rcases pfun.mem_fix_iff.1 h₂ with h₂ | ⟨a₃, am₃, fa₃⟩, { refine ⟨k.succ, _, λ m mk km, ⟨a₂, _⟩⟩, { simp [F], exact or.inr ⟨_, hk, h₂⟩ }, { rwa le_antisymm (nat.le_of_lt_succ mk) km } }, { rcases IH _ fa₃ am₃ k.succ _ with ⟨n, hn₁, hn₂⟩, { refine ⟨n, hn₁, λ m mn km, _⟩, cases lt_or_eq_of_le km with km km, { exact hn₂ _ mn km }, { exact km ▸ ⟨_, hk⟩ } }, { simp [F], exact ⟨_, hk, am₃⟩ } } } end theorem fix {f : α →. σ ⊕ α} (hf : partrec f) : partrec (pfun.fix f) := let F : α → ℕ →. σ ⊕ α := λ a n, n.elim (some (sum.inr a)) $ λ y IH, IH.bind $ λ s, sum.cases_on s (λ _, roption.some s) f in have hF : partrec₂ F := partrec.nat_elim snd (sum_inr.comp fst).part (sum_cases_right (snd.comp snd) (snd.comp $ snd.comp fst).to₂ (hf.comp snd).to₂).to₂, let p := λ a n, @roption.map _ bool (λ s, sum.cases_on s (λ_, tt) (λ _, ff)) (F a n) in have hp : partrec₂ p := hF.map ((sum_cases computable.id (const tt).to₂ (const ff).to₂).comp snd).to₂, (hp.rfind.bind (hF.bind (sum_cases_right snd snd.to₂ none.to₂).to₂).to₂).of_eq $ λ a, ext $ λ b, by simp; apply fix_aux hf end partrec
4ae0a77f9b5da624a5333e5f603f8f2f6808b39d
4727251e0cd73359b15b664c3170e5d754078599
/src/tactic/omega/nat/dnf.lean
95e2507509282dbccaec996822d9105a67b5766e
[ "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
5,000
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Seul Baek -/ import data.list.prod_sigma import tactic.omega.clause import tactic.omega.nat.form /-! # DNF transformation -/ namespace omega namespace nat open_locale omega.nat @[simp] def dnf_core : preform → list clause | (p ∨* q) := (dnf_core p) ++ (dnf_core q) | (p ∧* q) := (list.product (dnf_core p) (dnf_core q)).map (λ pq, clause.append pq.fst pq.snd) | (t =* s) := [([term.sub (canonize s) (canonize t)],[])] | (t ≤* s) := [([],[term.sub (canonize s) (canonize t)])] | (¬* _) := [] lemma exists_clause_holds_core {v : nat → nat} : ∀ {p : preform}, p.neg_free → p.sub_free → p.holds v → ∃ c ∈ (dnf_core p), clause.holds (λ x, ↑(v x)) c := begin preform.induce `[intros h1 h0 h2], { apply list.exists_mem_cons_of, constructor, rw list.forall_mem_singleton, cases h0 with ht hs, simp only [val_canonize ht, val_canonize hs, term.val_sub, preform.holds, sub_eq_add_neg] at *, rw [h2, add_neg_self], apply list.forall_mem_nil }, { apply list.exists_mem_cons_of, constructor, apply list.forall_mem_nil, rw list.forall_mem_singleton, simp only [val_canonize (h0.left), val_canonize (h0.right), term.val_sub, preform.holds, sub_eq_add_neg] at *, rw [←sub_eq_add_neg, le_sub, sub_zero, int.coe_nat_le], assumption }, { cases h1 }, { cases h2 with h2 h2; [ {cases (ihp h1.left h0.left h2) with c h3}, {cases (ihq h1.right h0.right h2) with c h3}]; cases h3 with h3 h4; refine ⟨c, list.mem_append.elim_right _, h4⟩; [left,right]; assumption }, { rcases (ihp h1.left h0.left h2.left) with ⟨cp, hp1, hp2⟩, rcases (ihq h1.right h0.right h2.right) with ⟨cq, hq1, hq2⟩, refine ⟨clause.append cp cq, ⟨_, clause.holds_append hp2 hq2⟩⟩, simp only [dnf_core, list.mem_map], refine ⟨(cp,cq),⟨_,rfl⟩⟩, rw list.mem_product, constructor; assumption } end def term.vars_core (is : list int) : list bool := is.map (λ i, if i = 0 then ff else tt) /-- Return a list of bools that encodes which variables have nonzero coefficients -/ def term.vars (t : term) : list bool := term.vars_core t.snd def bools.or : list bool → list bool → list bool | [] bs2 := bs2 | bs1 [] := bs1 | (b1::bs1) (b2::bs2) := (b1 || b2)::(bools.or bs1 bs2) /-- Return a list of bools that encodes which variables have nonzero coefficients in any one of the input terms. -/ def terms.vars : list term → list bool | [] := [] | (t::ts) := bools.or (term.vars t) (terms.vars ts) open_locale list.func -- get notation for list.func.set def nonneg_consts_core : nat → list bool → list term | _ [] := [] | k (ff::bs) := nonneg_consts_core (k+1) bs | k (tt::bs) := ⟨0, [] {k ↦ 1}⟩::nonneg_consts_core (k+1) bs def nonneg_consts (bs : list bool) : list term := nonneg_consts_core 0 bs def nonnegate : clause → clause | (eqs,les) := let xs := terms.vars eqs in let ys := terms.vars les in let bs := bools.or xs ys in (eqs, nonneg_consts bs ++ les) /-- DNF transformation -/ def dnf (p : preform) : list clause := (dnf_core p).map nonnegate lemma holds_nonneg_consts_core {v : nat → int} (h1 : ∀ x, 0 ≤ v x) : ∀ m bs, (∀ t ∈ (nonneg_consts_core m bs), 0 ≤ term.val v t) | _ [] := λ _ h2, by cases h2 | k (ff::bs) := holds_nonneg_consts_core (k+1) bs | k (tt::bs) := begin simp only [nonneg_consts_core], rw list.forall_mem_cons, constructor, { simp only [term.val, one_mul, zero_add, coeffs.val_set], apply h1 }, { apply holds_nonneg_consts_core (k+1) bs } end lemma holds_nonneg_consts {v : nat → int} {bs : list bool} : (∀ x, 0 ≤ v x) → (∀ t ∈ (nonneg_consts bs), 0 ≤ term.val v t) | h1 := by apply holds_nonneg_consts_core h1 lemma exists_clause_holds {v : nat → nat} {p : preform} : p.neg_free → p.sub_free → p.holds v → ∃ c ∈ (dnf p), clause.holds (λ x, ↑(v x)) c := begin intros h1 h2 h3, rcases (exists_clause_holds_core h1 h2 h3) with ⟨c,h4,h5⟩, existsi (nonnegate c), have h6 : nonnegate c ∈ dnf p, { simp only [dnf], rw list.mem_map, refine ⟨c,h4,rfl⟩ }, refine ⟨h6,_⟩, cases c with eqs les, simp only [nonnegate, clause.holds], constructor, apply h5.left, rw list.forall_mem_append, apply and.intro (holds_nonneg_consts _) h5.right, assume x, apply int.coe_nat_nonneg end lemma exists_clause_sat {p : preform} : p.neg_free → p.sub_free → p.sat → ∃ c ∈ (dnf p), clause.sat c := begin intros h1 h2 h3, cases h3 with v h3, rcases (exists_clause_holds h1 h2 h3) with ⟨c,h4,h5⟩, refine ⟨c,h4,_,h5⟩ end lemma unsat_of_unsat_dnf (p : preform) : p.neg_free → p.sub_free → clauses.unsat (dnf p) → p.unsat := begin intros hnf hsf h1 h2, apply h1, apply exists_clause_sat hnf hsf h2 end end nat end omega
78868fa6e430bf04e26d4eb515c2d8c0d6e9fda1
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/group_theory/nilpotent.lean
3acfd6222da00c6f4997bfc5a7e4439356bfbf85
[ "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
38,017
lean
/- Copyright (c) 2021 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Ines Wright, Joachim Breitner -/ import group_theory.quotient_group import group_theory.solvable import group_theory.p_group import group_theory.sylow import data.nat.factorization.basic import tactic.tfae /-! # Nilpotent groups An API for nilpotent groups, that is, groups for which the upper central series reaches `⊤`. ## Main definitions Recall that if `H K : subgroup G` then `⁅H, K⁆ : subgroup G` is the subgroup of `G` generated by the commutators `hkh⁻¹k⁻¹`. Recall also Lean's conventions that `⊤` denotes the subgroup `G` of `G`, and `⊥` denotes the trivial subgroup `{1}`. * `upper_central_series G : ℕ → subgroup G` : the upper central series of a group `G`. This is an increasing sequence of normal subgroups `H n` of `G` with `H 0 = ⊥` and `H (n + 1) / H n` is the centre of `G / H n`. * `lower_central_series G : ℕ → subgroup G` : the lower central series of a group `G`. This is a decreasing sequence of normal subgroups `H n` of `G` with `H 0 = ⊤` and `H (n + 1) = ⁅H n, G⁆`. * `is_nilpotent` : A group G is nilpotent if its upper central series reaches `⊤`, or equivalently if its lower central series reaches `⊥`. * `nilpotency_class` : the length of the upper central series of a nilpotent group. * `is_ascending_central_series (H : ℕ → subgroup G) : Prop` and * `is_descending_central_series (H : ℕ → subgroup G) : Prop` : Note that in the literature a "central series" for a group is usually defined to be a *finite* sequence of normal subgroups `H 0`, `H 1`, ..., starting at `⊤`, finishing at `⊥`, and with each `H n / H (n + 1)` central in `G / H (n + 1)`. In this formalisation it is convenient to have two weaker predicates on an infinite sequence of subgroups `H n` of `G`: we say a sequence is a *descending central series* if it starts at `G` and `⁅H n, ⊤⁆ ⊆ H (n + 1)` for all `n`. Note that this series may not terminate at `⊥`, and the `H i` need not be normal. Similarly a sequence is an *ascending central series* if `H 0 = ⊥` and `⁅H (n + 1), ⊤⁆ ⊆ H n` for all `n`, again with no requirement that the series reaches `⊤` or that the `H i` are normal. ## Main theorems `G` is *defined* to be nilpotent if the upper central series reaches `⊤`. * `nilpotent_iff_finite_ascending_central_series` : `G` is nilpotent iff some ascending central series reaches `⊤`. * `nilpotent_iff_finite_descending_central_series` : `G` is nilpotent iff some descending central series reaches `⊥`. * `nilpotent_iff_lower` : `G` is nilpotent iff the lower central series reaches `⊥`. * The `nilpotency_class` can likeways be obtained from these equivalent definitions, see `least_ascending_central_series_length_eq_nilpotency_class`, `least_descending_central_series_length_eq_nilpotency_class` and `lower_central_series_length_eq_nilpotency_class`. * If `G` is nilpotent, then so are its subgroups, images, quotients and preimages. Binary and finite products of nilpotent groups are nilpotent. Infinite products are nilpotent if their nilpotent class is bounded. Corresponding lemmas about the `nilpotency_class` are provided. * The `nilpotency_class` of `G ⧸ center G` is given explicitly, and an induction principle is derived from that. * `is_nilpotent.to_is_solvable`: If `G` is nilpotent, it is solvable. ## Warning A "central series" is usually defined to be a finite sequence of normal subgroups going from `⊥` to `⊤` with the property that each subquotient is contained within the centre of the associated quotient of `G`. This means that if `G` is not nilpotent, then none of what we have called `upper_central_series G`, `lower_central_series G` or the sequences satisfying `is_ascending_central_series` or `is_descending_central_series` are actually central series. Note that the fact that the upper and lower central series are not central series if `G` is not nilpotent is a standard abuse of notation. -/ open subgroup section with_group variables {G : Type*} [group G] (H : subgroup G) [normal H] /-- If `H` is a normal subgroup of `G`, then the set `{x : G | ∀ y : G, x*y*x⁻¹*y⁻¹ ∈ H}` is a subgroup of `G` (because it is the preimage in `G` of the centre of the quotient group `G/H`.) -/ def upper_central_series_step : subgroup G := { carrier := {x : G | ∀ y : G, x * y * x⁻¹ * y⁻¹ ∈ H}, one_mem' := λ y, by simp [subgroup.one_mem], mul_mem' := λ a b ha hb y, begin convert subgroup.mul_mem _ (ha (b * y * b⁻¹)) (hb y) using 1, group, end, inv_mem' := λ x hx y, begin specialize hx y⁻¹, rw [mul_assoc, inv_inv] at ⊢ hx, exact subgroup.normal.mem_comm infer_instance hx, end } lemma mem_upper_central_series_step (x : G) : x ∈ upper_central_series_step H ↔ ∀ y, x * y * x⁻¹ * y⁻¹ ∈ H := iff.rfl open quotient_group /-- The proof that `upper_central_series_step H` is the preimage of the centre of `G/H` under the canonical surjection. -/ lemma upper_central_series_step_eq_comap_center : upper_central_series_step H = subgroup.comap (mk' H) (center (G ⧸ H)) := begin ext, rw [mem_comap, mem_center_iff, forall_coe], apply forall_congr, intro y, rw [coe_mk', ←quotient_group.coe_mul, ←quotient_group.coe_mul, eq_comm, eq_iff_div_mem, div_eq_mul_inv, mul_inv_rev, mul_assoc], end instance : normal (upper_central_series_step H) := begin rw upper_central_series_step_eq_comap_center, apply_instance, end variable (G) /-- An auxiliary type-theoretic definition defining both the upper central series of a group, and a proof that it is normal, all in one go. -/ def upper_central_series_aux : ℕ → Σ' (H : subgroup G), normal H | 0 := ⟨⊥, infer_instance⟩ | (n + 1) := let un := upper_central_series_aux n, un_normal := un.2 in by exactI ⟨upper_central_series_step un.1, infer_instance⟩ /-- `upper_central_series G n` is the `n`th term in the upper central series of `G`. -/ def upper_central_series (n : ℕ) : subgroup G := (upper_central_series_aux G n).1 instance (n : ℕ) : normal (upper_central_series G n) := (upper_central_series_aux G n).2 @[simp] lemma upper_central_series_zero : upper_central_series G 0 = ⊥ := rfl @[simp] lemma upper_central_series_one : upper_central_series G 1 = center G := begin ext, simp only [upper_central_series, upper_central_series_aux, upper_central_series_step, center, set.center, mem_mk, mem_bot, set.mem_set_of_eq], exact forall_congr (λ y, by rw [mul_inv_eq_one, mul_inv_eq_iff_eq_mul, eq_comm]), end /-- The `n+1`st term of the upper central series `H i` has underlying set equal to the `x` such that `⁅x,G⁆ ⊆ H n`-/ lemma mem_upper_central_series_succ_iff (n : ℕ) (x : G) : x ∈ upper_central_series G (n + 1) ↔ ∀ y : G, x * y * x⁻¹ * y⁻¹ ∈ upper_central_series G n := iff.rfl -- is_nilpotent is already defined in the root namespace (for elements of rings). /-- A group `G` is nilpotent if its upper central series is eventually `G`. -/ class group.is_nilpotent (G : Type*) [group G] : Prop := (nilpotent [] : ∃ n : ℕ, upper_central_series G n = ⊤) open group variable {G} /-- A sequence of subgroups of `G` is an ascending central series if `H 0` is trivial and `⁅H (n + 1), G⁆ ⊆ H n` for all `n`. Note that we do not require that `H n = G` for some `n`. -/ def is_ascending_central_series (H : ℕ → subgroup G) : Prop := H 0 = ⊥ ∧ ∀ (x : G) (n : ℕ), x ∈ H (n + 1) → ∀ g, x * g * x⁻¹ * g⁻¹ ∈ H n /-- A sequence of subgroups of `G` is a descending central series if `H 0` is `G` and `⁅H n, G⁆ ⊆ H (n + 1)` for all `n`. Note that we do not requre that `H n = {1}` for some `n`. -/ def is_descending_central_series (H : ℕ → subgroup G) := H 0 = ⊤ ∧ ∀ (x : G) (n : ℕ), x ∈ H n → ∀ g, x * g * x⁻¹ * g⁻¹ ∈ H (n + 1) /-- Any ascending central series for a group is bounded above by the upper central series. -/ lemma ascending_central_series_le_upper (H : ℕ → subgroup G) (hH : is_ascending_central_series H) : ∀ n : ℕ, H n ≤ upper_central_series G n | 0 := hH.1.symm ▸ le_refl ⊥ | (n + 1) := begin intros x hx, rw mem_upper_central_series_succ_iff, exact λ y, ascending_central_series_le_upper n (hH.2 x n hx y), end variable (G) /-- The upper central series of a group is an ascending central series. -/ lemma upper_central_series_is_ascending_central_series : is_ascending_central_series (upper_central_series G) := ⟨rfl, λ x n h, h⟩ lemma upper_central_series_mono : monotone (upper_central_series G) := begin refine monotone_nat_of_le_succ _, intros n x hx y, rw [mul_assoc, mul_assoc, ← mul_assoc y x⁻¹ y⁻¹], exact mul_mem hx (normal.conj_mem (upper_central_series.subgroup.normal G n) x⁻¹ (inv_mem hx) y) end /-- A group `G` is nilpotent iff there exists an ascending central series which reaches `G` in finitely many steps. -/ theorem nilpotent_iff_finite_ascending_central_series : is_nilpotent G ↔ ∃ n : ℕ, ∃ H : ℕ → subgroup G, is_ascending_central_series H ∧ H n = ⊤ := begin split, { rintro ⟨n, nH⟩, refine ⟨_, _, upper_central_series_is_ascending_central_series G, nH⟩ }, { rintro ⟨n, H, hH, hn⟩, use n, rw [eq_top_iff, ←hn], exact ascending_central_series_le_upper H hH n } end lemma is_decending_rev_series_of_is_ascending {H: ℕ → subgroup G} {n : ℕ} (hn : H n = ⊤) (hasc : is_ascending_central_series H) : is_descending_central_series (λ (m : ℕ), H (n - m)) := begin cases hasc with h0 hH, refine ⟨hn, λ x m hx g, _⟩, dsimp at hx, by_cases hm : n ≤ m, { rw [tsub_eq_zero_of_le hm, h0, subgroup.mem_bot] at hx, subst hx, convert subgroup.one_mem _, group }, { push_neg at hm, apply hH, convert hx, rw [tsub_add_eq_add_tsub (nat.succ_le_of_lt hm), nat.succ_sub_succ] }, end lemma is_ascending_rev_series_of_is_descending {H: ℕ → subgroup G} {n : ℕ} (hn : H n = ⊥) (hdesc : is_descending_central_series H) : is_ascending_central_series (λ (m : ℕ), H (n - m)) := begin cases hdesc with h0 hH, refine ⟨hn, λ x m hx g, _⟩, dsimp only at hx ⊢, by_cases hm : n ≤ m, { have hnm : n - m = 0 := tsub_eq_zero_iff_le.mpr hm, rw [hnm, h0], exact mem_top _ }, { push_neg at hm, convert hH x _ hx g, rw [tsub_add_eq_add_tsub (nat.succ_le_of_lt hm), nat.succ_sub_succ] }, end /-- A group `G` is nilpotent iff there exists a descending central series which reaches the trivial group in a finite time. -/ theorem nilpotent_iff_finite_descending_central_series : is_nilpotent G ↔ ∃ n : ℕ, ∃ H : ℕ → subgroup G, is_descending_central_series H ∧ H n = ⊥ := begin rw nilpotent_iff_finite_ascending_central_series, split, { rintro ⟨n, H, hH, hn⟩, refine ⟨n, λ m, H (n - m), is_decending_rev_series_of_is_ascending G hn hH, _⟩, rw tsub_self, exact hH.1 }, { rintro ⟨n, H, hH, hn⟩, refine ⟨n, λ m, H (n - m), is_ascending_rev_series_of_is_descending G hn hH, _⟩, rw tsub_self, exact hH.1 }, end /-- The lower central series of a group `G` is a sequence `H n` of subgroups of `G`, defined by `H 0` is all of `G` and for `n≥1`, `H (n + 1) = ⁅H n, G⁆` -/ def lower_central_series (G : Type*) [group G] : ℕ → subgroup G | 0 := ⊤ | (n+1) := ⁅lower_central_series n, ⊤⁆ variable {G} @[simp] lemma lower_central_series_zero : lower_central_series G 0 = ⊤ := rfl @[simp] lemma lower_central_series_one : lower_central_series G 1 = commutator G := rfl lemma mem_lower_central_series_succ_iff (n : ℕ) (q : G) : q ∈ lower_central_series G (n + 1) ↔ q ∈ closure {x | ∃ (p ∈ lower_central_series G n) (q ∈ (⊤ : subgroup G)), p * q * p⁻¹ * q⁻¹ = x} := iff.rfl lemma lower_central_series_succ (n : ℕ) : lower_central_series G (n + 1) = closure {x | ∃ (p ∈ lower_central_series G n) (q ∈ (⊤ : subgroup G)), p * q * p⁻¹ * q⁻¹ = x} := rfl instance (n : ℕ) : normal (lower_central_series G n) := begin induction n with d hd, { exact (⊤ : subgroup G).normal_of_characteristic }, { exactI subgroup.commutator_normal (lower_central_series G d) ⊤ }, end lemma lower_central_series_antitone : antitone (lower_central_series G) := begin refine antitone_nat_of_succ_le (λ n x hx, _), simp only [mem_lower_central_series_succ_iff, exists_prop, mem_top, exists_true_left, true_and] at hx, refine closure_induction hx _ (subgroup.one_mem _) (@subgroup.mul_mem _ _ _) (@subgroup.inv_mem _ _ _), rintros y ⟨z, hz, a, ha⟩, rw [← ha, mul_assoc, mul_assoc, ← mul_assoc a z⁻¹ a⁻¹], exact mul_mem hz (normal.conj_mem (lower_central_series.subgroup.normal n) z⁻¹ (inv_mem hz) a) end /-- The lower central series of a group is a descending central series. -/ theorem lower_central_series_is_descending_central_series : is_descending_central_series (lower_central_series G) := begin split, refl, intros x n hxn g, exact commutator_mem_commutator hxn (mem_top g), end /-- Any descending central series for a group is bounded below by the lower central series. -/ lemma descending_central_series_ge_lower (H : ℕ → subgroup G) (hH : is_descending_central_series H) : ∀ n : ℕ, lower_central_series G n ≤ H n | 0 := hH.1.symm ▸ le_refl ⊤ | (n + 1) := commutator_le.mpr (λ x hx q _, hH.2 x n (descending_central_series_ge_lower n hx) q) /-- A group is nilpotent if and only if its lower central series eventually reaches the trivial subgroup. -/ theorem nilpotent_iff_lower_central_series : is_nilpotent G ↔ ∃ n, lower_central_series G n = ⊥ := begin rw nilpotent_iff_finite_descending_central_series, split, { rintro ⟨n, H, ⟨h0, hs⟩, hn⟩, use n, rw [eq_bot_iff, ←hn], exact descending_central_series_ge_lower H ⟨h0, hs⟩ n }, { rintro ⟨n, hn⟩, exact ⟨n, lower_central_series G, lower_central_series_is_descending_central_series, hn⟩ }, end section classical open_locale classical variables [hG : is_nilpotent G] include hG variable (G) /-- The nilpotency class of a nilpotent group is the smallest natural `n` such that the `n`'th term of the upper central series is `G`. -/ noncomputable def group.nilpotency_class : ℕ := nat.find (is_nilpotent.nilpotent G) variable {G} @[simp] lemma upper_central_series_nilpotency_class : upper_central_series G (group.nilpotency_class G) = ⊤ := nat.find_spec (is_nilpotent.nilpotent G) lemma upper_central_series_eq_top_iff_nilpotency_class_le {n : ℕ} : (upper_central_series G n = ⊤) ↔ (group.nilpotency_class G ≤ n) := begin split, { intro h, exact (nat.find_le h), }, { intro h, apply eq_top_iff.mpr, rw ← upper_central_series_nilpotency_class, exact (upper_central_series_mono _ h), } end /-- The nilpotency class of a nilpotent `G` is equal to the smallest `n` for which an ascending central series reaches `G` in its `n`'th term. -/ lemma least_ascending_central_series_length_eq_nilpotency_class : nat.find ((nilpotent_iff_finite_ascending_central_series G).mp hG) = group.nilpotency_class G := begin refine le_antisymm (nat.find_mono _) (nat.find_mono _), { intros n hn, exact ⟨upper_central_series G, upper_central_series_is_ascending_central_series G, hn ⟩, }, { rintros n ⟨H, ⟨hH, hn⟩⟩, rw [←top_le_iff, ←hn], exact ascending_central_series_le_upper H hH n, } end /-- The nilpotency class of a nilpotent `G` is equal to the smallest `n` for which the descending central series reaches `⊥` in its `n`'th term. -/ lemma least_descending_central_series_length_eq_nilpotency_class : nat.find ((nilpotent_iff_finite_descending_central_series G).mp hG) = group.nilpotency_class G := begin rw ← least_ascending_central_series_length_eq_nilpotency_class, refine le_antisymm (nat.find_mono _) (nat.find_mono _), { rintros n ⟨H, ⟨hH, hn⟩⟩, refine ⟨(λ m, H (n - m)), is_decending_rev_series_of_is_ascending G hn hH, _⟩, rw tsub_self, exact hH.1 }, { rintros n ⟨H, ⟨hH, hn⟩⟩, refine ⟨(λ m, H (n - m)), is_ascending_rev_series_of_is_descending G hn hH, _⟩, rw tsub_self, exact hH.1 }, end /-- The nilpotency class of a nilpotent `G` is equal to the length of the lower central series. -/ lemma lower_central_series_length_eq_nilpotency_class : nat.find (nilpotent_iff_lower_central_series.mp hG) = @group.nilpotency_class G _ _ := begin rw ← least_descending_central_series_length_eq_nilpotency_class, refine le_antisymm (nat.find_mono _) (nat.find_mono _), { rintros n ⟨H, ⟨hH, hn⟩⟩, rw [←le_bot_iff, ←hn], exact (descending_central_series_ge_lower H hH n), }, { rintros n h, exact ⟨lower_central_series G, ⟨lower_central_series_is_descending_central_series, h⟩⟩ }, end @[simp] lemma lower_central_series_nilpotency_class : lower_central_series G (group.nilpotency_class G) = ⊥ := begin rw ← lower_central_series_length_eq_nilpotency_class, exact (nat.find_spec (nilpotent_iff_lower_central_series.mp _)) end lemma lower_central_series_eq_bot_iff_nilpotency_class_le {n : ℕ} : (lower_central_series G n = ⊥) ↔ (group.nilpotency_class G ≤ n) := begin split, { intro h, rw ← lower_central_series_length_eq_nilpotency_class, exact (nat.find_le h), }, { intro h, apply eq_bot_iff.mpr, rw ← lower_central_series_nilpotency_class, exact (lower_central_series_antitone h), } end end classical lemma lower_central_series_map_subtype_le (H : subgroup G) (n : ℕ) : (lower_central_series H n).map H.subtype ≤ lower_central_series G n := begin induction n with d hd, { simp }, { rw [lower_central_series_succ, lower_central_series_succ, monoid_hom.map_closure], apply subgroup.closure_mono, rintros x1 ⟨x2, ⟨x3, hx3, x4, hx4, rfl⟩, rfl⟩, exact ⟨x3, (hd (mem_map.mpr ⟨x3, hx3, rfl⟩)), x4, by simp⟩ } end /-- A subgroup of a nilpotent group is nilpotent -/ instance subgroup.is_nilpotent (H : subgroup G) [hG : is_nilpotent G] : is_nilpotent H := begin rw nilpotent_iff_lower_central_series at *, rcases hG with ⟨n, hG⟩, use n, have := lower_central_series_map_subtype_le H n, simp only [hG, set_like.le_def, mem_map, forall_apply_eq_imp_iff₂, exists_imp_distrib] at this, exact eq_bot_iff.mpr (λ x hx, subtype.ext (this x hx)), end /-- A the nilpotency class of a subgroup is less or equal the the nilpotency class of the group -/ lemma subgroup.nilpotency_class_le (H : subgroup G) [hG : is_nilpotent G] : group.nilpotency_class H ≤ group.nilpotency_class G := begin repeat { rw ← lower_central_series_length_eq_nilpotency_class }, apply nat.find_mono, intros n hG, have := lower_central_series_map_subtype_le H n, simp only [hG, set_like.le_def, mem_map, forall_apply_eq_imp_iff₂, exists_imp_distrib] at this, exact eq_bot_iff.mpr (λ x hx, subtype.ext (this x hx)), end @[priority 100] instance is_nilpotent_of_subsingleton [subsingleton G] : is_nilpotent G := nilpotent_iff_lower_central_series.2 ⟨0, subsingleton.elim ⊤ ⊥⟩ lemma upper_central_series.map {H : Type*} [group H] {f : G →* H} (h : function.surjective f) (n : ℕ) : subgroup.map f (upper_central_series G n) ≤ upper_central_series H n := begin induction n with d hd, { simp }, { rintros _ ⟨x, hx : x ∈ upper_central_series G d.succ, rfl⟩ y', rcases h y' with ⟨y, rfl⟩, simpa using hd (mem_map_of_mem f (hx y)) } end lemma lower_central_series.map {H : Type*} [group H] (f : G →* H) (n : ℕ) : subgroup.map f (lower_central_series G n) ≤ lower_central_series H n := begin induction n with d hd, { simp [nat.nat_zero_eq_zero] }, { rintros a ⟨x, hx : x ∈ lower_central_series G d.succ, rfl⟩, refine closure_induction hx _ (by simp [f.map_one, subgroup.one_mem _]) (λ y z hy hz, by simp [monoid_hom.map_mul, subgroup.mul_mem _ hy hz]) (λ y hy, by simp [f.map_inv, subgroup.inv_mem _ hy]), rintros a ⟨y, hy, z, ⟨-, rfl⟩⟩, apply mem_closure.mpr, exact λ K hK, hK ⟨f y, hd (mem_map_of_mem f hy), by simp [commutator_element_def]⟩ } end lemma lower_central_series_succ_eq_bot {n : ℕ} (h : lower_central_series G n ≤ center G) : lower_central_series G (n + 1) = ⊥ := begin rw [lower_central_series_succ, closure_eq_bot_iff, set.subset_singleton_iff], rintro x ⟨y, hy1, z, ⟨⟩, rfl⟩, rw [mul_assoc, ←mul_inv_rev, mul_inv_eq_one, eq_comm], exact mem_center_iff.mp (h hy1) z, end /-- The preimage of a nilpotent group is nilpotent if the kernel of the homomorphism is contained in the center -/ lemma is_nilpotent_of_ker_le_center {H : Type*} [group H] (f : G →* H) (hf1 : f.ker ≤ center G) (hH : is_nilpotent H) : is_nilpotent G := begin rw nilpotent_iff_lower_central_series at *, rcases hH with ⟨n, hn⟩, use (n + 1), refine lower_central_series_succ_eq_bot (le_trans ((map_eq_bot_iff _).mp _) hf1), exact eq_bot_iff.mpr (hn ▸ (lower_central_series.map f n)), end lemma nilpotency_class_le_of_ker_le_center {H : Type*} [group H] (f : G →* H) (hf1 : f.ker ≤ center G) (hH : is_nilpotent H) : @group.nilpotency_class G _ (is_nilpotent_of_ker_le_center f hf1 hH) ≤ group.nilpotency_class H + 1 := begin rw ← lower_central_series_length_eq_nilpotency_class, apply nat.find_min', refine lower_central_series_succ_eq_bot (le_trans ((map_eq_bot_iff _).mp _) hf1), apply eq_bot_iff.mpr, apply (le_trans (lower_central_series.map f _)), simp only [lower_central_series_nilpotency_class, le_bot_iff], end /-- The range of a surjective homomorphism from a nilpotent group is nilpotent -/ lemma nilpotent_of_surjective {G' : Type*} [group G'] [h : is_nilpotent G] (f : G →* G') (hf : function.surjective f) : is_nilpotent G' := begin unfreezingI { rcases h with ⟨n, hn⟩ }, use n, apply eq_top_iff.mpr, calc ⊤ = f.range : symm (f.range_top_of_surjective hf) ... = subgroup.map f ⊤ : monoid_hom.range_eq_map _ ... = subgroup.map f (upper_central_series G n) : by rw hn ... ≤ upper_central_series G' n : upper_central_series.map hf n, end /-- The nilpotency class of the range of a surejctive homomorphism from a nilpotent group is less or equal the nilpotency class of the domain -/ lemma nilpotency_class_le_of_surjective {G' : Type*} [group G'] (f : G →* G') (hf : function.surjective f) [h : is_nilpotent G] : @group.nilpotency_class G' _ (nilpotent_of_surjective _ hf) ≤ group.nilpotency_class G := begin apply nat.find_mono, intros n hn, apply eq_top_iff.mpr, calc ⊤ = f.range : symm (f.range_top_of_surjective hf) ... = subgroup.map f ⊤ : monoid_hom.range_eq_map _ ... = subgroup.map f (upper_central_series G n) : by rw hn ... ≤ upper_central_series G' n : upper_central_series.map hf n, end /-- Nilpotency respects isomorphisms -/ lemma nilpotent_of_mul_equiv {G' : Type*} [group G'] [h : is_nilpotent G] (f : G ≃* G') : is_nilpotent G' := nilpotent_of_surjective f.to_monoid_hom (mul_equiv.surjective f) /-- A quotient of a nilpotent group is nilpotent -/ instance nilpotent_quotient_of_nilpotent (H : subgroup G) [H.normal] [h : is_nilpotent G] : is_nilpotent (G ⧸ H) := nilpotent_of_surjective _ (show function.surjective (quotient_group.mk' H), by tidy) /-- The nilpotency class of a quotient of `G` is less or equal the nilpotency class of `G` -/ lemma nilpotency_class_quotient_le (H : subgroup G) [H.normal] [h : is_nilpotent G] : group.nilpotency_class (G ⧸ H) ≤ group.nilpotency_class G := nilpotency_class_le_of_surjective _ _ -- This technical lemma helps with rewriting the subgroup, which occurs in indices private lemma comap_center_subst {H₁ H₂ : subgroup G} [normal H₁] [normal H₂] (h : H₁ = H₂) : comap (mk' H₁) (center (G ⧸ H₁)) = comap (mk' H₂) (center (G ⧸ H₂)) := by unfreezingI { subst h } lemma comap_upper_central_series_quotient_center (n : ℕ) : comap (mk' (center G)) (upper_central_series (G ⧸ center G) n) = upper_central_series G n.succ := begin induction n with n ih, { simp, }, { let Hn := upper_central_series (G ⧸ center G) n, calc comap (mk' (center G)) (upper_central_series_step Hn) = comap (mk' (center G)) (comap (mk' Hn) (center ((G ⧸ center G) ⧸ Hn))) : by rw upper_central_series_step_eq_comap_center ... = comap (mk' (comap (mk' (center G)) Hn)) (center (G ⧸ (comap (mk' (center G)) Hn))) : quotient_group.comap_comap_center ... = comap (mk' (upper_central_series G n.succ)) (center (G ⧸ upper_central_series G n.succ)) : comap_center_subst ih ... = upper_central_series_step (upper_central_series G n.succ) : symm (upper_central_series_step_eq_comap_center _), } end lemma nilpotency_class_zero_iff_subsingleton [is_nilpotent G] : group.nilpotency_class G = 0 ↔ subsingleton G := by simp [group.nilpotency_class, nat.find_eq_zero, subsingleton_iff_bot_eq_top] /-- Quotienting the `center G` reduces the nilpotency class by 1 -/ lemma nilpotency_class_quotient_center [hH : is_nilpotent G] : group.nilpotency_class (G ⧸ center G) = group.nilpotency_class G - 1 := begin generalize hn : group.nilpotency_class G = n, rcases n with rfl | n, { simp [nilpotency_class_zero_iff_subsingleton] at *, haveI := hn, apply_instance, }, { suffices : group.nilpotency_class (G ⧸ center G) = n, by simpa, apply le_antisymm, { apply upper_central_series_eq_top_iff_nilpotency_class_le.mp, apply (@comap_injective G _ _ _ (mk' (center G)) (surjective_quot_mk _)), rw [ comap_upper_central_series_quotient_center, comap_top, ← hn], exact upper_central_series_nilpotency_class, }, { apply le_of_add_le_add_right, calc n + 1 = n.succ : rfl ... = group.nilpotency_class G : symm hn ... ≤ group.nilpotency_class (G ⧸ center G) + 1 : nilpotency_class_le_of_ker_le_center _ (le_of_eq (ker_mk _)) _, } } end /-- The nilpotency class of a non-trivial group is one more than its quotient by the center -/ lemma nilpotency_class_eq_quotient_center_plus_one [hH : is_nilpotent G] [nontrivial G] : group.nilpotency_class G = group.nilpotency_class (G ⧸ center G) + 1 := begin rw nilpotency_class_quotient_center, rcases h : group.nilpotency_class G, { exfalso, rw nilpotency_class_zero_iff_subsingleton at h, resetI, apply (false_of_nontrivial_of_subsingleton G), }, { simp } end /-- If the quotient by `center G` is nilpotent, then so is G. -/ lemma of_quotient_center_nilpotent (h : is_nilpotent (G ⧸ center G)) : is_nilpotent G := begin obtain ⟨n, hn⟩ := h.nilpotent, use n.succ, simp [← comap_upper_central_series_quotient_center, hn], end /-- A custom induction principle for nilpotent groups. The base case is a trivial group (`subsingleton G`), and in the induction step, one can assume the hypothesis for the group quotiented by its center. -/ @[elab_as_eliminator] lemma nilpotent_center_quotient_ind {P : Π G [group G], by exactI ∀ [is_nilpotent G], Prop} (G : Type*) [group G] [is_nilpotent G] (hbase : ∀ G [group G] [subsingleton G], by exactI P G) (hstep : ∀ G [group G], by exactI ∀ [is_nilpotent G], by exactI ∀ (ih : P (G ⧸ center G)), P G) : P G := begin obtain ⟨n, h⟩ : ∃ n, group.nilpotency_class G = n := ⟨ _, rfl⟩, unfreezingI { induction n with n ih generalizing G }, { haveI := nilpotency_class_zero_iff_subsingleton.mp h, exact hbase _, }, { have hn : group.nilpotency_class (G ⧸ center G) = n := by simp [nilpotency_class_quotient_center, h], exact hstep _ (ih _ hn), }, end lemma derived_le_lower_central (n : ℕ) : derived_series G n ≤ lower_central_series G n := by { induction n with i ih, { simp }, { apply commutator_mono ih, simp } } /-- Abelian groups are nilpotent -/ @[priority 100] instance comm_group.is_nilpotent {G : Type*} [comm_group G] : is_nilpotent G := begin use 1, rw upper_central_series_one, apply comm_group.center_eq_top, end /-- Abelian groups have nilpotency class at most one -/ lemma comm_group.nilpotency_class_le_one {G : Type*} [comm_group G] : group.nilpotency_class G ≤ 1 := begin apply upper_central_series_eq_top_iff_nilpotency_class_le.mp, rw upper_central_series_one, apply comm_group.center_eq_top, end /-- Groups with nilpotency class at most one are abelian -/ def comm_group_of_nilpotency_class [is_nilpotent G] (h : group.nilpotency_class G ≤ 1) : comm_group G := group.comm_group_of_center_eq_top $ begin rw ← upper_central_series_one, exact upper_central_series_eq_top_iff_nilpotency_class_le.mpr h, end section prod variables {G₁ G₂ : Type*} [group G₁] [group G₂] lemma lower_central_series_prod (n : ℕ): lower_central_series (G₁ × G₂) n = (lower_central_series G₁ n).prod (lower_central_series G₂ n) := begin induction n with n ih, { simp, }, { calc lower_central_series (G₁ × G₂) n.succ = ⁅lower_central_series (G₁ × G₂) n, ⊤⁆ : rfl ... = ⁅(lower_central_series G₁ n).prod (lower_central_series G₂ n), ⊤⁆ : by rw ih ... = ⁅(lower_central_series G₁ n).prod (lower_central_series G₂ n), (⊤ : subgroup G₁).prod ⊤⁆ : by simp ... = ⁅lower_central_series G₁ n, (⊤ : subgroup G₁)⁆.prod ⁅lower_central_series G₂ n, ⊤⁆ : commutator_prod_prod _ _ _ _ ... = (lower_central_series G₁ n.succ).prod (lower_central_series G₂ n.succ) : rfl } end /-- Products of nilpotent groups are nilpotent -/ instance is_nilpotent_prod [is_nilpotent G₁] [is_nilpotent G₂] : is_nilpotent (G₁ × G₂) := begin rw nilpotent_iff_lower_central_series, refine ⟨max (group.nilpotency_class G₁) (group.nilpotency_class G₂), _ ⟩, rw [lower_central_series_prod, lower_central_series_eq_bot_iff_nilpotency_class_le.mpr (le_max_left _ _), lower_central_series_eq_bot_iff_nilpotency_class_le.mpr (le_max_right _ _), bot_prod_bot], end /-- The nilpotency class of a product is the max of the nilpotency classes of the factors -/ lemma nilpotency_class_prod [is_nilpotent G₁] [is_nilpotent G₂] : group.nilpotency_class (G₁ × G₂) = max (group.nilpotency_class G₁) (group.nilpotency_class G₂) := begin refine eq_of_forall_ge_iff (λ k, _), simp only [max_le_iff, ← lower_central_series_eq_bot_iff_nilpotency_class_le, lower_central_series_prod, prod_eq_bot_iff ], end end prod section bounded_pi -- First the case of infinite products with bounded nilpotency class variables {η : Type*} {Gs : η → Type*} [∀ i, group (Gs i)] lemma lower_central_series_pi_le (n : ℕ): lower_central_series (Π i, Gs i) n ≤ subgroup.pi set.univ (λ i, lower_central_series (Gs i) n) := begin let pi := λ (f : Π i, subgroup (Gs i)), subgroup.pi set.univ f, induction n with n ih, { simp [pi_top] }, { calc lower_central_series (Π i, Gs i) n.succ = ⁅lower_central_series (Π i, Gs i) n, ⊤⁆ : rfl ... ≤ ⁅pi (λ i, (lower_central_series (Gs i) n)), ⊤⁆ : commutator_mono ih (le_refl _) ... = ⁅pi (λ i, (lower_central_series (Gs i) n)), pi (λ i, ⊤)⁆ : by simp [pi, pi_top] ... ≤ pi (λ i, ⁅(lower_central_series (Gs i) n), ⊤⁆) : commutator_pi_pi_le _ _ ... = pi (λ i, lower_central_series (Gs i) n.succ) : rfl } end /-- products of nilpotent groups are nilpotent if their nipotency class is bounded -/ lemma is_nilpotent_pi_of_bounded_class [∀ i, is_nilpotent (Gs i)] (n : ℕ) (h : ∀ i, group.nilpotency_class (Gs i) ≤ n) : is_nilpotent (Π i, Gs i) := begin rw nilpotent_iff_lower_central_series, refine ⟨n, _⟩, rw eq_bot_iff, apply le_trans (lower_central_series_pi_le _), rw [← eq_bot_iff, pi_eq_bot_iff], intros i, apply lower_central_series_eq_bot_iff_nilpotency_class_le.mpr (h i), end end bounded_pi section finite_pi -- Now for finite products variables {η : Type*} {Gs : η → Type*} [∀ i, group (Gs i)] lemma lower_central_series_pi_of_finite [finite η] (n : ℕ) : lower_central_series (Π i, Gs i) n = subgroup.pi set.univ (λ i, lower_central_series (Gs i) n) := begin let pi := λ (f : Π i, subgroup (Gs i)), subgroup.pi set.univ f, induction n with n ih, { simp [pi_top] }, { calc lower_central_series (Π i, Gs i) n.succ = ⁅lower_central_series (Π i, Gs i) n, ⊤⁆ : rfl ... = ⁅pi (λ i, (lower_central_series (Gs i) n)), ⊤⁆ : by rw ih ... = ⁅pi (λ i, (lower_central_series (Gs i) n)), pi (λ i, ⊤)⁆ : by simp [pi, pi_top] ... = pi (λ i, ⁅(lower_central_series (Gs i) n), ⊤⁆) : commutator_pi_pi_of_finite _ _ ... = pi (λ i, lower_central_series (Gs i) n.succ) : rfl } end /-- n-ary products of nilpotent groups are nilpotent -/ instance is_nilpotent_pi [finite η] [∀ i, is_nilpotent (Gs i)] : is_nilpotent (Π i, Gs i) := begin casesI nonempty_fintype η, rw nilpotent_iff_lower_central_series, refine ⟨finset.univ.sup (λ i, group.nilpotency_class (Gs i)), _⟩, rw [lower_central_series_pi_of_finite, pi_eq_bot_iff], intros i, apply lower_central_series_eq_bot_iff_nilpotency_class_le.mpr, exact @finset.le_sup _ _ _ _ finset.univ (λ i, group.nilpotency_class (Gs i)) _ (finset.mem_univ i), end /-- The nilpotency class of an n-ary product is the sup of the nilpotency classes of the factors -/ lemma nilpotency_class_pi [fintype η] [∀ i, is_nilpotent (Gs i)] : group.nilpotency_class (Π i, Gs i) = finset.univ.sup (λ i, group.nilpotency_class (Gs i)) := begin apply eq_of_forall_ge_iff, intros k, simp only [finset.sup_le_iff, ← lower_central_series_eq_bot_iff_nilpotency_class_le, lower_central_series_pi_of_finite, pi_eq_bot_iff, finset.mem_univ, true_implies_iff ], end end finite_pi /-- A nilpotent subgroup is solvable -/ @[priority 100] instance is_nilpotent.to_is_solvable [h : is_nilpotent G]: is_solvable G := begin obtain ⟨n, hn⟩ := nilpotent_iff_lower_central_series.1 h, use n, rw [eq_bot_iff, ←hn], exact derived_le_lower_central n, end lemma normalizer_condition_of_is_nilpotent [h : is_nilpotent G] : normalizer_condition G := begin -- roughly based on https://groupprops.subwiki.org/wiki/Nilpotent_implies_normalizer_condition rw normalizer_condition_iff_only_full_group_self_normalizing, apply nilpotent_center_quotient_ind G; unfreezingI { clear_dependent G }, { introsI G _ _ H _, apply subsingleton.elim, }, { introsI G _ _ ih H hH, have hch : center G ≤ H := subgroup.center_le_normalizer.trans (le_of_eq hH), have hkh : (mk' (center G)).ker ≤ H, by simpa using hch, have hsur : function.surjective (mk' (center G)), by exact surjective_quot_mk _, let H' := H.map (mk' (center G)), have hH' : H'.normalizer = H', { apply comap_injective hsur, rw [comap_normalizer_eq_of_surjective _ hsur, comap_map_eq_self hkh], exact hH, }, apply map_injective_of_ker_le (mk' (center G)) hkh le_top, exact (ih H' hH').trans (symm (map_top_of_surjective _ hsur)), }, end end with_group section with_finite_group open group fintype variables {G : Type*} [hG : group G] include hG /-- A p-group is nilpotent -/ lemma is_p_group.is_nilpotent [finite G] {p : ℕ} [hp : fact (nat.prime p)] (h : is_p_group p G) : is_nilpotent G := begin casesI nonempty_fintype G, classical, unfreezingI { revert hG, induction val using fintype.induction_subsingleton_or_nontrivial with G hG hS G hG hN ih }, { apply_instance, }, { introI _, intro h, have hcq : fintype.card (G ⧸ center G) < fintype.card G, { rw card_eq_card_quotient_mul_card_subgroup (center G), apply lt_mul_of_one_lt_right, exact (fintype.card_pos_iff.mpr has_one.nonempty), exact ((subgroup.one_lt_card_iff_ne_bot _).mpr (ne_of_gt h.bot_lt_center)), }, have hnq : is_nilpotent (G ⧸ center G) := ih _ hcq (h.to_quotient (center G)), exact (of_quotient_center_nilpotent hnq), } end variables [fintype G] /-- If a finite group is the direct product of its Sylow groups, it is nilpotent -/ theorem is_nilpotent_of_product_of_sylow_group (e : (Π p : (fintype.card G).factorization.support, Π P : sylow p G, (↑P : subgroup G)) ≃* G) : is_nilpotent G := begin classical, let ps := (fintype.card G).factorization.support, haveI : ∀ (p : ps) (P : sylow p G), is_nilpotent (↑P : subgroup G), { intros p P, haveI : fact (nat.prime ↑p) := fact.mk (nat.prime_of_mem_factorization (finset.coe_mem p)), exact P.is_p_group'.is_nilpotent, }, exact nilpotent_of_mul_equiv e, end /-- A finite group is nilpotent iff the normalizer condition holds, and iff all maximal groups are normal and iff all sylow groups are normal and iff the group is the direct product of its sylow groups. -/ theorem is_nilpotent_of_finite_tfae : tfae [ is_nilpotent G, normalizer_condition G, ∀ (H : subgroup G), is_coatom H → H.normal, ∀ (p : ℕ) (hp : fact p.prime) (P : sylow p G), (↑P : subgroup G).normal, nonempty ((Π p : (card G).factorization.support, Π P : sylow p G, (↑P : subgroup G)) ≃* G) ] := begin tfae_have : 1 → 2, { exact @normalizer_condition_of_is_nilpotent _ _ }, tfae_have : 2 → 3, { exact λ h H, normalizer_condition.normal_of_coatom H h }, tfae_have : 3 → 4, { introsI h p _ P, exact sylow.normal_of_all_max_subgroups_normal h _ }, tfae_have : 4 → 5, { exact λ h, nonempty.intro (sylow.direct_product_of_normal h) }, tfae_have : 5 → 1, { rintros ⟨e⟩, exact is_nilpotent_of_product_of_sylow_group e }, tfae_finish, end end with_finite_group
7eec421f1b0e258dedf1d23a0853b50b78c562eb
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/order/module.lean
8c3ef26904dd8517b96a7f5b5ef0eb03cf329919
[ "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
8,240
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, Yaël Dillies -/ import algebra.order.smul /-! # Ordered module In this file we provide lemmas about `ordered_smul` that hold once a module structure is present. ## References * https://en.wikipedia.org/wiki/Ordered_module ## Tags ordered module, ordered scalar, ordered smul, ordered action, ordered vector space -/ open_locale pointwise variables {k M N : Type*} instance [semiring k] [ordered_add_comm_monoid M] [module k M] : module k Mᵒᵈ := { add_smul := λ r s x, order_dual.rec (add_smul _ _) x, zero_smul := λ m, order_dual.rec (zero_smul _) m } section semiring variables [ordered_semiring k] [ordered_add_comm_group M] [module k M] [ordered_smul k M] {a b : M} {c : k} /- can be generalized from `module k M` to `distrib_mul_action_with_zero k M` once it exists. where `distrib_mul_action_with_zero k M`is the conjunction of `distrib_mul_action k M` and `smul_with_zero k M`.-/ lemma smul_neg_iff_of_pos (hc : 0 < c) : c • a < 0 ↔ a < 0 := begin rw [←neg_neg a, smul_neg, neg_neg_iff_pos, neg_neg_iff_pos], exact smul_pos_iff_of_pos hc, end end semiring section ring variables [ordered_ring k] [ordered_add_comm_group M] [module k M] [ordered_smul k M] {a b : M} {c : k} lemma smul_lt_smul_of_neg (h : a < b) (hc : c < 0) : c • b < c • a := begin rw [←neg_neg c, neg_smul, neg_smul (-c), neg_lt_neg_iff], exact smul_lt_smul_of_pos h (neg_pos_of_neg hc), end lemma smul_le_smul_of_nonpos (h : a ≤ b) (hc : c ≤ 0) : c • b ≤ c • a := begin rw [←neg_neg c, neg_smul, neg_smul (-c), neg_le_neg_iff], exact smul_le_smul_of_nonneg h (neg_nonneg_of_nonpos hc), end lemma eq_of_smul_eq_smul_of_neg_of_le (hab : c • a = c • b) (hc : c < 0) (h : a ≤ b) : a = b := begin rw [←neg_neg c, neg_smul, neg_smul (-c), neg_inj] at hab, exact eq_of_smul_eq_smul_of_pos_of_le hab (neg_pos_of_neg hc) h, end lemma lt_of_smul_lt_smul_of_nonpos (h : c • a < c • b) (hc : c ≤ 0) : b < a := begin rw [←neg_neg c, neg_smul, neg_smul (-c), neg_lt_neg_iff] at h, exact lt_of_smul_lt_smul_of_nonneg h (neg_nonneg_of_nonpos hc), end lemma smul_lt_smul_iff_of_neg (hc : c < 0) : c • a < c • b ↔ b < a := begin rw [←neg_neg c, neg_smul, neg_smul (-c), neg_lt_neg_iff], exact smul_lt_smul_iff_of_pos (neg_pos_of_neg hc), end lemma smul_neg_iff_of_neg (hc : c < 0) : c • a < 0 ↔ 0 < a := begin rw [←neg_neg c, neg_smul, neg_neg_iff_pos], exact smul_pos_iff_of_pos (neg_pos_of_neg hc), end lemma smul_pos_iff_of_neg (hc : c < 0) : 0 < c • a ↔ a < 0 := begin rw [←neg_neg c, neg_smul, neg_pos], exact smul_neg_iff_of_pos (neg_pos_of_neg hc), end lemma smul_nonpos_of_nonpos_of_nonneg (hc : c ≤ 0) (ha : 0 ≤ a) : c • a ≤ 0 := calc c • a ≤ c • 0 : smul_le_smul_of_nonpos ha hc ... = 0 : smul_zero c lemma smul_nonneg_of_nonpos_of_nonpos (hc : c ≤ 0) (ha : a ≤ 0) : 0 ≤ c • a := @smul_nonpos_of_nonpos_of_nonneg k Mᵒᵈ _ _ _ _ _ _ hc ha alias smul_pos_iff_of_neg ↔ _ smul_pos_of_neg_of_neg alias smul_neg_iff_of_pos ↔ _ smul_neg_of_pos_of_neg alias smul_neg_iff_of_neg ↔ _ smul_neg_of_neg_of_pos lemma antitone_smul_left (hc : c ≤ 0) : antitone (has_smul.smul c : M → M) := λ a b h, smul_le_smul_of_nonpos h hc lemma strict_anti_smul_left (hc : c < 0) : strict_anti (has_smul.smul c : M → M) := λ a b h, smul_lt_smul_of_neg h hc /-- Binary **rearrangement inequality**. -/ lemma smul_add_smul_le_smul_add_smul [contravariant_class M M (+) (≤)] {a b : k} {c d : M} (hab : a ≤ b) (hcd : c ≤ d) : a • d + b • c ≤ a • c + b • d := begin obtain ⟨b, rfl⟩ := exists_add_of_le hab, obtain ⟨d, rfl⟩ := exists_add_of_le hcd, rw [smul_add, add_right_comm, smul_add, ←add_assoc, add_smul _ _ d], rw le_add_iff_nonneg_right at hab hcd, exact add_le_add_left (le_add_of_nonneg_right $ smul_nonneg hab hcd) _, end /-- Binary **rearrangement inequality**. -/ lemma smul_add_smul_le_smul_add_smul' [contravariant_class M M (+) (≤)] {a b : k} {c d : M} (hba : b ≤ a) (hdc : d ≤ c) : a • d + b • c ≤ a • c + b • d := by { rw [add_comm (a • d), add_comm (a • c)], exact smul_add_smul_le_smul_add_smul hba hdc } /-- Binary strict **rearrangement inequality**. -/ lemma smul_add_smul_lt_smul_add_smul [covariant_class M M (+) (<)] [contravariant_class M M (+) (<)] {a b : k} {c d : M} (hab : a < b) (hcd : c < d) : a • d + b • c < a • c + b • d := begin obtain ⟨b, rfl⟩ := exists_add_of_le hab.le, obtain ⟨d, rfl⟩ := exists_add_of_le hcd.le, rw [smul_add, add_right_comm, smul_add, ←add_assoc, add_smul _ _ d], rw lt_add_iff_pos_right at hab hcd, exact add_lt_add_left (lt_add_of_pos_right _ $ smul_pos hab hcd) _, end /-- Binary strict **rearrangement inequality**. -/ lemma smul_add_smul_lt_smul_add_smul' [covariant_class M M (+) (<)] [contravariant_class M M (+) (<)] {a b : k} {c d : M} (hba : b < a) (hdc : d < c) : a • d + b • c < a • c + b • d := by { rw [add_comm (a • d), add_comm (a • c)], exact smul_add_smul_lt_smul_add_smul hba hdc } end ring section field variables [linear_ordered_field k] [ordered_add_comm_group M] [module k M] [ordered_smul k M] {a b : M} {c : k} lemma smul_le_smul_iff_of_neg (hc : c < 0) : c • a ≤ c • b ↔ b ≤ a := begin rw [←neg_neg c, neg_smul, neg_smul (-c), neg_le_neg_iff], exact smul_le_smul_iff_of_pos (neg_pos_of_neg hc), end lemma inv_smul_le_iff_of_neg (h : c < 0) : c⁻¹ • a ≤ b ↔ c • b ≤ a := by { rw [←smul_le_smul_iff_of_neg h, smul_inv_smul₀ h.ne], apply_instance } lemma inv_smul_lt_iff_of_neg (h : c < 0) : c⁻¹ • a < b ↔ c • b < a := by { rw [←smul_lt_smul_iff_of_neg h, smul_inv_smul₀ h.ne], apply_instance } lemma smul_inv_le_iff_of_neg (h : c < 0) : a ≤ c⁻¹ • b ↔ b ≤ c • a := by { rw [←smul_le_smul_iff_of_neg h, smul_inv_smul₀ h.ne], apply_instance } lemma smul_inv_lt_iff_of_neg (h : c < 0) : a < c⁻¹ • b ↔ b < c • a := by { rw [←smul_lt_smul_iff_of_neg h, smul_inv_smul₀ h.ne], apply_instance } variables (M) /-- Left scalar multiplication as an order isomorphism. -/ @[simps] def order_iso.smul_left_dual {c : k} (hc : c < 0) : M ≃o Mᵒᵈ := { to_fun := λ b, order_dual.to_dual (c • b), inv_fun := λ b, c⁻¹ • (order_dual.of_dual b), left_inv := inv_smul_smul₀ hc.ne, right_inv := smul_inv_smul₀ hc.ne, map_rel_iff' := λ b₁ b₂, smul_le_smul_iff_of_neg hc } end field /-! ### Upper/lower bounds -/ section ordered_ring variables [ordered_ring k] [ordered_add_comm_group M] [module k M] [ordered_smul k M] {s : set M} {c : k} lemma smul_lower_bounds_subset_upper_bounds_smul (hc : c ≤ 0) : c • lower_bounds s ⊆ upper_bounds (c • s) := (antitone_smul_left hc).image_lower_bounds_subset_upper_bounds_image lemma smul_upper_bounds_subset_lower_bounds_smul (hc : c ≤ 0) : c • upper_bounds s ⊆ lower_bounds (c • s) := (antitone_smul_left hc).image_upper_bounds_subset_lower_bounds_image lemma bdd_below.smul_of_nonpos (hc : c ≤ 0) (hs : bdd_below s) : bdd_above (c • s) := (antitone_smul_left hc).map_bdd_below hs lemma bdd_above.smul_of_nonpos (hc : c ≤ 0) (hs : bdd_above s) : bdd_below (c • s) := (antitone_smul_left hc).map_bdd_above hs end ordered_ring section linear_ordered_field variables [linear_ordered_field k] [ordered_add_comm_group M] [module k M] [ordered_smul k M] {s : set M} {c : k} @[simp] lemma lower_bounds_smul_of_neg (hc : c < 0) : lower_bounds (c • s) = c • upper_bounds s := (order_iso.smul_left_dual M hc).upper_bounds_image @[simp] lemma upper_bounds_smul_of_neg (hc : c < 0) : upper_bounds (c • s) = c • lower_bounds s := (order_iso.smul_left_dual M hc).lower_bounds_image @[simp] lemma bdd_below_smul_iff_of_neg (hc : c < 0) : bdd_below (c • s) ↔ bdd_above s := (order_iso.smul_left_dual M hc).bdd_above_image @[simp] lemma bdd_above_smul_iff_of_neg (hc : c < 0) : bdd_above (c • s) ↔ bdd_below s := (order_iso.smul_left_dual M hc).bdd_below_image end linear_ordered_field
c77fec9c6d7a5310754ab3affbc06a21cdc95e44
94e33a31faa76775069b071adea97e86e218a8ee
/src/analysis/complex/cauchy_integral.lean
33d2020f4862446d7ee8210b0a8452413c5012ae
[ "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
36,596
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import measure_theory.measure.complex_lebesgue import measure_theory.integral.divergence_theorem import measure_theory.integral.circle_integral import analysis.calculus.dslope import analysis.analytic.basic import analysis.complex.re_im_topology import analysis.calculus.diff_on_int_cont import data.real.cardinality /-! # Cauchy integral formula In this file we prove the Cauchy-Goursat theorem and the Cauchy integral formula for integrals over circles. Most results are formulated for a function `f : ℂ → E` that takes values in a complex Banach space with second countable topology. ## Main statements In the following theorems, if the name ends with `off_countable`, then the actual theorem assumes differentiability at all but countably many points of the set mentioned below. * `complex.integral_boundary_rect_of_has_fderiv_within_at_real_off_countable`: If a function `f : ℂ → E` is continuous on a closed rectangle and *real* differentiable on its interior, then its integral over the boundary of this rectangle is equal to the integral of `I • f' (x + y * I) 1 - f' (x + y * I) I` over the rectangle, where `f' z w : E` is the derivative of `f` at `z` in the direction `w` and `I = complex.I` is the imaginary unit. * `complex.integral_boundary_rect_eq_zero_of_differentiable_on_off_countable`: If a function `f : ℂ → E` is continuous on a closed rectangle and is *complex* differentiable on its interior, then its integral over the boundary of this rectangle is equal to zero. * `complex.circle_integral_sub_center_inv_smul_eq_of_differentiable_on_annulus_off_countable`: If a function `f : ℂ → E` is continuous on a closed annulus `{z | r ≤ |z - c| ≤ R}` and is complex differentiable on its interior `{z | r < |z - c| < R}`, then the integrals of `(z - c)⁻¹ • f z` over the outer boundary and over the inner boundary are equal. * `complex.circle_integral_sub_center_inv_smul_of_differentiable_on_off_countable_of_tendsto`, `complex.circle_integral_sub_center_inv_smul_of_differentiable_on_off_countable`: If a function `f : ℂ → E` is continuous on a punctured closed disc `{z | |z - c| ≤ R ∧ z ≠ c}`, is complex differentiable on the corresponding punctured open disc, and tends to `y` as `z → c`, `z ≠ c`, then the integral of `(z - c)⁻¹ • f z` over the circle `|z - c| = R` is equal to `2πiy`. In particular, if `f` is continuous on the whole closed disc and is complex differentiable on the corresponding open disc, then this integral is equal to `2πif(c)`. * `complex.circle_integral_sub_inv_smul_of_differentiable_on_off_countable`, `complex.two_pi_I_inv_smul_circle_integral_sub_inv_smul_of_differentiable_on_off_countable` **Cauchy integral formula**: if `f : ℂ → E` is continuous on a closed disc of radius `R` and is complex differentiable on the corresponding open disc, then for any `w` in the corresponding open disc the integral of `(z - w)⁻¹ • f z` over the boundary of the disc is equal to `2πif(w)`. Two versions of the lemma put the multiplier `2πi` at the different sides of the equality. * `complex.has_fpower_series_on_ball_of_differentiable_off_countable`: If `f : ℂ → E` is continuous on a closed disc of positive radius and is complex differentiable on the corresponding open disc, then it is analytic on the corresponding open disc, and the coefficients of the power series are given by Cauchy integral formulas. * `differentiable_on.has_fpower_series_on_ball`: If `f : ℂ → E` is complex differentiable on a closed disc of positive radius, then it is analytic on the corresponding open disc, and the coefficients of the power series are given by Cauchy integral formulas. * `differentiable_on.analytic_at`, `differentiable.analytic_at`: If `f : ℂ → E` is differentiable on a neighborhood of a point, then it is analytic at this point. In particular, if `f : ℂ → E` is differentiable on the whole `ℂ`, then it is analytic at every point `z : ℂ`. * `differentiable.has_power_series_on_ball`: If `f : ℂ → E` is differentiable everywhere then the `cauchy_power_series f z R` is a formal power series representing `f` at `z` with infinite radius of convergence (this holds for any choice of `0 < R`). ## Implementation details The proof of the Cauchy integral formula in this file is based on a very general version of the divergence theorem, see `measure_theory.integral_divergence_of_has_fderiv_within_at_off_countable` (a version for functions defined on `fin (n + 1) → ℝ`), `measure_theory.integral_divergence_prod_Icc_of_has_fderiv_within_at_off_countable_of_le`, and `measure_theory.integral2_divergence_prod_of_has_fderiv_within_at_off_countable` (versions for functions defined on `ℝ × ℝ`). Usually, the divergence theorem is formulated for a $C^1$ smooth function. The theorems formulated above deal with a function that is * continuous on a closed box/rectangle; * differentiable at all but countably many points of its interior; * have divergence integrable over the closed box/rectangle. First, we reformulate the theorem for a *real*-differentiable map `ℂ → E`, and relate the integral of `f` over the boundary of a rectangle in `ℂ` to the integral of the derivative $\frac{\partial f}{\partial \bar z}$ over the interior of this box. In particular, for a *complex* differentiable function, the latter derivative is zero, hence the integral over the boundary of a rectangle is zero. Thus we get the Cauchy-Goursat theorem for a rectangle in `ℂ`. Next, we apply the this theorem to the function $F(z)=f(c+e^{z})$ on the rectangle $[\ln r, \ln R]\times [0, 2\pi]$ to prove that $$ \oint_{|z-c|=r}\frac{f(z)\,dz}{z-c}=\oint_{|z-c|=R}\frac{f(z)\,dz}{z-c} $$ provided that `f` is continuous on the closed annulus `r ≤ |z - c| ≤ R` and is complex differentiable on its interior `r < |z - c| < R` (possibly, at all but countably many points). Here and below, we write $\frac{f(z)}{z-c}$ in the documentation while the actual lemmas use `(z - c)⁻¹ • f z` because `f z` belongs to some Banach space over `ℂ` and `f z / (z - c)` is undefined. Taking the limit of this equality as `r` tends to `𝓝[>] 0`, we prove $$ \oint_{|z-c|=R}\frac{f(z)\,dz}{z-c}=2\pi if(c) $$ provided that `f` is continuous on the closed disc `|z - c| ≤ R` and is differentiable at all but countably many points of its interior. This is the Cauchy integral formula for the center of a circle. In particular, if we apply this function to `F z = (z - c) • f z`, then we get $$ \oint_{|z-c|=R} f(z)\,dz=0. $$ In order to deduce the Cauchy integral formula for any point `w`, `|w - c| < R`, we consider the slope function `g : ℂ → E` given by `g z = (z - w)⁻¹ • (f z - f w)` if `z ≠ w` and `g w = f' w`. This function satisfies assumptions of the previous theorem, so we have $$ \oint_{|z-c|=R} \frac{f(z)\,dz}{z-w}=\oint_{|z-c|=R} \frac{f(w)\,dz}{z-w}= \left(\oint_{|z-c|=R} \frac{dz}{z-w}\right)f(w). $$ The latter integral was computed in `circle_integral.integral_sub_inv_of_mem_ball` and is equal to `2 * π * complex.I`. There is one more step in the actual proof. Since we allow `f` to be non-differentiable on a countable set `s`, we cannot immediately claim that `g` is continuous at `w` if `w ∈ s`. So, we use the proof outlined in the previous paragraph for `w ∉ s` (see `complex.circle_integral_sub_inv_smul_of_differentiable_on_off_countable_aux`), then use continuity of both sides of the formula and density of `sᶜ` to prove the formula for all points of the open ball, see `complex.circle_integral_sub_inv_smul_of_differentiable_on_off_countable`. Finally, we use the properties of the Cauchy integrals established elsewhere (see `has_fpower_series_on_cauchy_integral`) and Cauchy integral formula to prove that the original function is analytic on the open ball. ## Tags Cauchy-Goursat theorem, Cauchy integral formula -/ open topological_space set measure_theory interval_integral metric filter function open_locale interval real nnreal ennreal topological_space big_operators noncomputable theory universes u variables {E : Type u} [normed_group E] [normed_space ℂ E] [complete_space E] namespace complex /-- Suppose that a function `f : ℂ → E` is continuous on a closed rectangle with opposite corners at `z w : ℂ`, is *real* differentiable at all but countably many points of the corresponding open rectangle, and $\frac{\partial f}{\partial \bar z}$ is integrable on this rectangle. Then the integral of `f` over the boundary of the rectangle is equal to the integral of $2i\frac{\partial f}{\partial \bar z}=i\frac{\partial f}{\partial x}-\frac{\partial f}{\partial y}$ over the rectangle. -/ lemma integral_boundary_rect_of_has_fderiv_at_real_off_countable (f : ℂ → E) (f' : ℂ → ℂ →L[ℝ] E) (z w : ℂ) (s : set ℂ) (hs : s.countable) (Hc : continuous_on f ([z.re, w.re] ×ℂ [z.im, w.im])) (Hd : ∀ x ∈ (Ioo (min z.re w.re) (max z.re w.re) ×ℂ Ioo (min z.im w.im) (max z.im w.im)) \ s, has_fderiv_at f (f' x) x) (Hi : integrable_on (λ z, I • f' z 1 - f' z I) ([z.re, w.re] ×ℂ [z.im, w.im])) : (∫ x : ℝ in z.re..w.re, f (x + z.im * I)) - (∫ x : ℝ in z.re..w.re, f (x + w.im * I)) + (I • ∫ y : ℝ in z.im..w.im, f (re w + y * I)) - I • ∫ y : ℝ in z.im..w.im, f (re z + y * I) = ∫ x : ℝ in z.re..w.re, ∫ y : ℝ in z.im..w.im, I • f' (x + y * I) 1 - f' (x + y * I) I := begin set e : (ℝ × ℝ) ≃L[ℝ] ℂ := equiv_real_prodₗ.symm, have he : ∀ x y : ℝ, ↑x + ↑y * I = e (x, y), from λ x y, (mk_eq_add_mul_I x y).symm, have he₁ : e (1, 0) = 1 := rfl, have he₂ : e (0, 1) = I := rfl, simp only [he] at *, set F : (ℝ × ℝ) → E := f ∘ e, set F' : (ℝ × ℝ) → (ℝ × ℝ) →L[ℝ] E := λ p, (f' (e p)).comp (e : (ℝ × ℝ) →L[ℝ] ℂ), have hF' : ∀ p : ℝ × ℝ, (-(I • F' p)) (1, 0) + F' p (0, 1) = -(I • f' (e p) 1 - f' (e p) I), { rintro ⟨x, y⟩, simp [F', he₁, he₂, ← sub_eq_neg_add], }, set R : set (ℝ × ℝ) := [z.re, w.re] ×ˢ [w.im, z.im], set t : set (ℝ × ℝ) := e ⁻¹' s, rw [interval_swap z.im] at Hc Hi, rw [min_comm z.im, max_comm z.im] at Hd, have hR : e ⁻¹' ([z.re, w.re] ×ℂ [w.im, z.im]) = R := rfl, have htc : continuous_on F R, from Hc.comp e.continuous_on hR.ge, have htd : ∀ p ∈ Ioo (min z.re w.re) (max z.re w.re) ×ˢ Ioo (min w.im z.im) (max w.im z.im) \ t, has_fderiv_at F (F' p) p := λ p hp, (Hd (e p) hp).comp p e.has_fderiv_at, simp_rw [← interval_integral.integral_smul, interval_integral.integral_symm w.im z.im, ← interval_integral.integral_neg, ← hF'], refine (integral2_divergence_prod_of_has_fderiv_within_at_off_countable (λ p, -(I • F p)) F (λ p, - (I • F' p)) F' z.re w.im w.re z.im t (hs.preimage e.injective) (htc.const_smul _).neg htc (λ p hp, ((htd p hp).const_smul I).neg) htd _).symm, rw [← (volume_preserving_equiv_real_prod.symm _).integrable_on_comp_preimage (measurable_equiv.measurable_embedding _)] at Hi, simpa only [hF'] using Hi.neg end /-- Suppose that a function `f : ℂ → E` is continuous on a closed rectangle with opposite corners at `z w : ℂ`, is *real* differentiable on the corresponding open rectangle, and $\frac{\partial f}{\partial \bar z}$ is integrable on this rectangle. Then the integral of `f` over the boundary of the rectangle is equal to the integral of $2i\frac{\partial f}{\partial \bar z}=i\frac{\partial f}{\partial x}-\frac{\partial f}{\partial y}$ over the rectangle. -/ lemma integral_boundary_rect_of_continuous_on_of_has_fderiv_at_real (f : ℂ → E) (f' : ℂ → ℂ →L[ℝ] E) (z w : ℂ) (Hc : continuous_on f ([z.re, w.re] ×ℂ [z.im, w.im])) (Hd : ∀ x ∈ (Ioo (min z.re w.re) (max z.re w.re) ×ℂ Ioo (min z.im w.im) (max z.im w.im)), has_fderiv_at f (f' x) x) (Hi : integrable_on (λ z, I • f' z 1 - f' z I) ([z.re, w.re] ×ℂ [z.im, w.im])) : (∫ x : ℝ in z.re..w.re, f (x + z.im * I)) - (∫ x : ℝ in z.re..w.re, f (x + w.im * I)) + (I • ∫ y : ℝ in z.im..w.im, f (re w + y * I)) - I • ∫ y : ℝ in z.im..w.im, f (re z + y * I) = ∫ x : ℝ in z.re..w.re, ∫ y : ℝ in z.im..w.im, I • f' (x + y * I) 1 - f' (x + y * I) I := integral_boundary_rect_of_has_fderiv_at_real_off_countable f f' z w ∅ countable_empty Hc (λ x hx, Hd x hx.1) Hi /-- Suppose that a function `f : ℂ → E` is *real* differentiable on a closed rectangle with opposite corners at `z w : ℂ` and $\frac{\partial f}{\partial \bar z}$ is integrable on this rectangle. Then the integral of `f` over the boundary of the rectangle is equal to the integral of $2i\frac{\partial f}{\partial \bar z}=i\frac{\partial f}{\partial x}-\frac{\partial f}{\partial y}$ over the rectangle. -/ lemma integral_boundary_rect_of_differentiable_on_real (f : ℂ → E) (z w : ℂ) (Hd : differentiable_on ℝ f ([z.re, w.re] ×ℂ [z.im, w.im])) (Hi : integrable_on (λ z, I • fderiv ℝ f z 1 - fderiv ℝ f z I) ([z.re, w.re] ×ℂ [z.im, w.im])) : (∫ x : ℝ in z.re..w.re, f (x + z.im * I)) - (∫ x : ℝ in z.re..w.re, f (x + w.im * I)) + (I • ∫ y : ℝ in z.im..w.im, f (re w + y * I)) - I • ∫ y : ℝ in z.im..w.im, f (re z + y * I) = ∫ x : ℝ in z.re..w.re, ∫ y : ℝ in z.im..w.im, I • fderiv ℝ f (x + y * I) 1 - fderiv ℝ f (x + y * I) I := integral_boundary_rect_of_has_fderiv_at_real_off_countable f (fderiv ℝ f) z w ∅ countable_empty Hd.continuous_on (λ x hx, Hd.has_fderiv_at $ by simpa only [← mem_interior_iff_mem_nhds, interior_re_prod_im, interval, interior_Icc] using hx.1) Hi /-- **Cauchy-Goursat theorem** for a rectangle: the integral of a complex differentiable function over the boundary of a rectangle equals zero. More precisely, if `f` is continuous on a closed rectangle and is complex differentiable at all but countably many points of the corresponding open rectangle, then its integral over the boundary of the rectangle equals zero. -/ lemma integral_boundary_rect_eq_zero_of_differentiable_on_off_countable (f : ℂ → E) (z w : ℂ) (s : set ℂ) (hs : s.countable) (Hc : continuous_on f ([z.re, w.re] ×ℂ [z.im, w.im])) (Hd : ∀ x ∈ (Ioo (min z.re w.re) (max z.re w.re) ×ℂ Ioo (min z.im w.im) (max z.im w.im)) \ s, differentiable_at ℂ f x) : (∫ x : ℝ in z.re..w.re, f (x + z.im * I)) - (∫ x : ℝ in z.re..w.re, f (x + w.im * I)) + (I • ∫ y : ℝ in z.im..w.im, f (re w + y * I)) - I • ∫ y : ℝ in z.im..w.im, f (re z + y * I) = 0 := by refine (integral_boundary_rect_of_has_fderiv_at_real_off_countable f (λ z, (fderiv ℂ f z).restrict_scalars ℝ) z w s hs Hc (λ x hx, (Hd x hx).has_fderiv_at.restrict_scalars ℝ) _).trans _; simp [← continuous_linear_map.map_smul] /-- **Cauchy-Goursat theorem for a rectangle**: the integral of a complex differentiable function over the boundary of a rectangle equals zero. More precisely, if `f` is continuous on a closed rectangle and is complex differentiable on the corresponding open rectangle, then its integral over the boundary of the rectangle equals zero. -/ lemma integral_boundary_rect_eq_zero_of_continuous_on_of_differentiable_on (f : ℂ → E) (z w : ℂ) (Hc : continuous_on f ([z.re, w.re] ×ℂ [z.im, w.im])) (Hd : differentiable_on ℂ f (Ioo (min z.re w.re) (max z.re w.re) ×ℂ Ioo (min z.im w.im) (max z.im w.im))) : (∫ x : ℝ in z.re..w.re, f (x + z.im * I)) - (∫ x : ℝ in z.re..w.re, f (x + w.im * I)) + (I • ∫ y : ℝ in z.im..w.im, f (re w + y * I)) - I • ∫ y : ℝ in z.im..w.im, f (re z + y * I) = 0 := integral_boundary_rect_eq_zero_of_differentiable_on_off_countable f z w ∅ countable_empty Hc $ λ x hx, Hd.differentiable_at $ (is_open_Ioo.re_prod_im is_open_Ioo).mem_nhds hx.1 /-- **Cauchy-Goursat theorem** for a rectangle: the integral of a complex differentiable function over the boundary of a rectangle equals zero. More precisely, if `f` is complex differentiable on a closed rectangle, then its integral over the boundary of the rectangle equals zero. -/ lemma integral_boundary_rect_eq_zero_of_differentiable_on (f : ℂ → E) (z w : ℂ) (H : differentiable_on ℂ f ([z.re, w.re] ×ℂ [z.im, w.im])) : (∫ x : ℝ in z.re..w.re, f (x + z.im * I)) - (∫ x : ℝ in z.re..w.re, f (x + w.im * I)) + (I • ∫ y : ℝ in z.im..w.im, f (re w + y * I)) - I • ∫ y : ℝ in z.im..w.im, f (re z + y * I) = 0 := integral_boundary_rect_eq_zero_of_continuous_on_of_differentiable_on f z w H.continuous_on $ H.mono $ inter_subset_inter (preimage_mono Ioo_subset_Icc_self) (preimage_mono Ioo_subset_Icc_self) /-- If `f : ℂ → E` is continuous the closed annulus `r ≤ ∥z - c∥ ≤ R`, `0 < r ≤ R`, and is complex differentiable at all but countably many points of its interior, then the integrals of `f z / (z - c)` (formally, `(z - c)⁻¹ • f z`) over the circles `∥z - c∥ = r` and `∥z - c∥ = R` are equal to each other. -/ lemma circle_integral_sub_center_inv_smul_eq_of_differentiable_on_annulus_off_countable {c : ℂ} {r R : ℝ} (h0 : 0 < r) (hle : r ≤ R) {f : ℂ → E} {s : set ℂ} (hs : s.countable) (hc : continuous_on f (closed_ball c R \ ball c r)) (hd : ∀ z ∈ ball c R \ closed_ball c r \ s, differentiable_at ℂ f z) : ∮ z in C(c, R), (z - c)⁻¹ • f z = ∮ z in C(c, r), (z - c)⁻¹ • f z := begin /- We apply the previous lemma to `λ z, f (c + exp z)` on the rectangle `[log r, log R] × [0, 2 * π]`. -/ set A := closed_ball c R \ ball c r, obtain ⟨a, rfl⟩ : ∃ a, real.exp a = r, from ⟨real.log r, real.exp_log h0⟩, obtain ⟨b, rfl⟩ : ∃ b, real.exp b = R, from ⟨real.log R, real.exp_log (h0.trans_le hle)⟩, rw [real.exp_le_exp] at hle, -- Unfold definition of `circle_integral` and cancel some terms. suffices : ∫ θ in 0..2 * π, I • f (circle_map c (real.exp b) θ) = ∫ θ in 0..2 * π, I • f (circle_map c (real.exp a) θ), by simpa only [circle_integral, add_sub_cancel', of_real_exp, ← exp_add, smul_smul, ← div_eq_mul_inv, mul_div_cancel_left _ (circle_map_ne_center (real.exp_pos _).ne'), circle_map_sub_center, deriv_circle_map], set R := [a, b] ×ℂ [0, 2 * π], set g : ℂ → ℂ := (+) c ∘ exp, have hdg : differentiable ℂ g := differentiable_exp.const_add _, replace hs : (g ⁻¹' s).countable := (hs.preimage (add_right_injective c)).preimage_cexp, have h_maps : maps_to g R A, { rintro z ⟨h, -⟩, simpa [dist_eq, g, abs_exp, hle] using h.symm }, replace hc : continuous_on (f ∘ g) R, from hc.comp hdg.continuous.continuous_on h_maps, replace hd : ∀ z ∈ (Ioo (min a b) (max a b) ×ℂ Ioo (min 0 (2 * π)) (max 0 (2 * π))) \ g ⁻¹' s, differentiable_at ℂ (f ∘ g) z, { refine λ z hz, (hd (g z) ⟨_, hz.2⟩).comp z (hdg _), simpa [g, dist_eq, abs_exp, hle, and.comm] using hz.1.1 }, simpa [g, circle_map, exp_periodic _, sub_eq_zero, ← exp_add] using integral_boundary_rect_eq_zero_of_differentiable_on_off_countable _ ⟨a, 0⟩ ⟨b, 2 * π⟩ _ hs hc hd end /-- **Cauchy-Goursat theorem** for an annulus. If `f : ℂ → E` is continuous on the closed annulus `r ≤ ∥z - c∥ ≤ R`, `0 < r ≤ R`, and is complex differentiable at all but countably many points of its interior, then the integrals of `f` over the circles `∥z - c∥ = r` and `∥z - c∥ = R` are equal to each other. -/ lemma circle_integral_eq_of_differentiable_on_annulus_off_countable {c : ℂ} {r R : ℝ} (h0 : 0 < r) (hle : r ≤ R) {f : ℂ → E} {s : set ℂ} (hs : s.countable) (hc : continuous_on f (closed_ball c R \ ball c r)) (hd : ∀ z ∈ ball c R \ closed_ball c r \ s, differentiable_at ℂ f z) : ∮ z in C(c, R), f z = ∮ z in C(c, r), f z := calc ∮ z in C(c, R), f z = ∮ z in C(c, R), (z - c)⁻¹ • (z - c) • f z : (circle_integral.integral_sub_inv_smul_sub_smul _ _ _ _).symm ... = ∮ z in C(c, r), (z - c)⁻¹ • (z - c) • f z : circle_integral_sub_center_inv_smul_eq_of_differentiable_on_annulus_off_countable h0 hle hs ((continuous_on_id.sub continuous_on_const).smul hc) (λ z hz, (differentiable_at_id.sub_const _).smul (hd z hz)) ... = ∮ z in C(c, r), f z : circle_integral.integral_sub_inv_smul_sub_smul _ _ _ _ /-- **Cauchy integral formula** for the value at the center of a disc. If `f` is continuous on a punctured closed disc of radius `R`, is differentiable at all but countably many points of the interior of this disc, and has a limit `y` at the center of the disc, then the integral $\oint_{∥z-c∥=R} \frac{f(z)}{z-c}\,dz$ is equal to $2πiy`. -/ lemma circle_integral_sub_center_inv_smul_of_differentiable_on_off_countable_of_tendsto {c : ℂ} {R : ℝ} (h0 : 0 < R) {f : ℂ → E} {y : E} {s : set ℂ} (hs : s.countable) (hc : continuous_on f (closed_ball c R \ {c})) (hd : ∀ z ∈ ball c R \ {c} \ s, differentiable_at ℂ f z) (hy : tendsto f (𝓝[{c}ᶜ] c) (𝓝 y)) : ∮ z in C(c, R), (z - c)⁻¹ • f z = (2 * π * I : ℂ) • y := begin rw [← sub_eq_zero, ← norm_le_zero_iff], refine le_of_forall_le_of_dense (λ ε ε0, _), obtain ⟨δ, δ0, hδ⟩ : ∃ δ > (0 : ℝ), ∀ z ∈ closed_ball c δ \ {c}, dist (f z) y < ε / (2 * π), from ((nhds_within_has_basis nhds_basis_closed_ball _).tendsto_iff nhds_basis_ball).1 hy _ (div_pos ε0 real.two_pi_pos), obtain ⟨r, hr0, hrδ, hrR⟩ : ∃ r, 0 < r ∧ r ≤ δ ∧ r ≤ R := ⟨min δ R, lt_min δ0 h0, min_le_left _ _, min_le_right _ _⟩, have hsub : closed_ball c R \ ball c r ⊆ closed_ball c R \ {c}, from diff_subset_diff_right (singleton_subset_iff.2 $ mem_ball_self hr0), have hsub' : ball c R \ closed_ball c r ⊆ ball c R \ {c}, from diff_subset_diff_right (singleton_subset_iff.2 $ mem_closed_ball_self hr0.le), have hzne : ∀ z ∈ sphere c r, z ≠ c, from λ z hz, ne_of_mem_of_not_mem hz (λ h, hr0.ne' $ dist_self c ▸ eq.symm h), /- The integral `∮ z in C(c, r), f z / (z - c)` does not depend on `0 < r ≤ R` and tends to `2πIy` as `r → 0`. -/ calc ∥(∮ z in C(c, R), (z - c)⁻¹ • f z) - (2 * ↑π * I) • y∥ = ∥(∮ z in C(c, r), (z - c)⁻¹ • f z) - ∮ z in C(c, r), (z - c)⁻¹ • y∥ : begin congr' 2, { exact circle_integral_sub_center_inv_smul_eq_of_differentiable_on_annulus_off_countable hr0 hrR hs (hc.mono hsub) (λ z hz, hd z ⟨hsub' hz.1, hz.2⟩) }, { simp [hr0.ne'] } end ... = ∥∮ z in C(c, r), (z - c)⁻¹ • (f z - y)∥ : begin simp only [smul_sub], have hc' : continuous_on (λ z, (z - c)⁻¹) (sphere c r), from (continuous_on_id.sub continuous_on_const).inv₀ (λ z hz, sub_ne_zero.2 $ hzne _ hz), rw circle_integral.integral_sub; refine (hc'.smul _).circle_integrable hr0.le, { exact hc.mono (subset_inter (sphere_subset_closed_ball.trans $ closed_ball_subset_closed_ball hrR) hzne) }, { exact continuous_on_const } end ... ≤ 2 * π * r * (r⁻¹ * (ε / (2 * π))) : begin refine circle_integral.norm_integral_le_of_norm_le_const hr0.le (λ z hz, _), specialize hzne z hz, rw [mem_sphere, dist_eq_norm] at hz, rw [norm_smul, norm_inv, hz, ← dist_eq_norm], refine mul_le_mul_of_nonneg_left (hδ _ ⟨_, hzne⟩).le (inv_nonneg.2 hr0.le), rwa [mem_closed_ball_iff_norm, hz] end ... = ε : by { field_simp [hr0.ne', real.two_pi_pos.ne'], ac_refl } end /-- **Cauchy integral formula** for the value at the center of a disc. If `f : ℂ → E` is continuous on a closed disc of radius `R` and is complex differentiable at all but countably many points of its interior, then the integral $\oint_{|z-c|=R} \frac{f(z)}{z-c}\,dz$ is equal to $2πiy`. -/ lemma circle_integral_sub_center_inv_smul_of_differentiable_on_off_countable {R : ℝ} (h0 : 0 < R) {f : ℂ → E} {c : ℂ} {s : set ℂ} (hs : s.countable) (hc : continuous_on f (closed_ball c R)) (hd : ∀ z ∈ ball c R \ s, differentiable_at ℂ f z) : ∮ z in C(c, R), (z - c)⁻¹ • f z = (2 * π * I : ℂ) • f c := circle_integral_sub_center_inv_smul_of_differentiable_on_off_countable_of_tendsto h0 hs (hc.mono $ diff_subset _ _) (λ z hz, hd z ⟨hz.1.1, hz.2⟩) (hc.continuous_at $ closed_ball_mem_nhds _ h0).continuous_within_at /-- **Cauchy-Goursat theorem** for a disk: if `f : ℂ → E` is continuous on a closed disk `{z | ∥z - c∥ ≤ R}` and is complex differentiable at all but countably many points of its interior, then the integral $\oint_{|z-c|=R}f(z)\,dz$ equals zero. -/ lemma circle_integral_eq_zero_of_differentiable_on_off_countable {R : ℝ} (h0 : 0 ≤ R) {f : ℂ → E} {c : ℂ} {s : set ℂ} (hs : s.countable) (hc : continuous_on f (closed_ball c R)) (hd : ∀ z ∈ ball c R \ s, differentiable_at ℂ f z) : ∮ z in C(c, R), f z = 0 := begin rcases h0.eq_or_lt with rfl|h0, { apply circle_integral.integral_radius_zero }, calc ∮ z in C(c, R), f z = ∮ z in C(c, R), (z - c)⁻¹ • (z - c) • f z : (circle_integral.integral_sub_inv_smul_sub_smul _ _ _ _).symm ... = (2 * ↑π * I : ℂ) • (c - c) • f c : circle_integral_sub_center_inv_smul_of_differentiable_on_off_countable h0 hs ((continuous_on_id.sub continuous_on_const).smul hc) (λ z hz, (differentiable_at_id.sub_const _).smul (hd z hz)) ... = 0 : by rw [sub_self, zero_smul, smul_zero] end /-- An auxiliary lemma for `complex.circle_integral_sub_inv_smul_of_differentiable_on_off_countable`. This lemma assumes `w ∉ s` while the main lemma drops this assumption. -/ lemma circle_integral_sub_inv_smul_of_differentiable_on_off_countable_aux {R : ℝ} {c w : ℂ} {f : ℂ → E} {s : set ℂ} (hs : s.countable) (hw : w ∈ ball c R \ s) (hc : continuous_on f (closed_ball c R)) (hd : ∀ x ∈ ball c R \ s, differentiable_at ℂ f x) : ∮ z in C(c, R), (z - w)⁻¹ • f z = (2 * π * I : ℂ) • f w := begin have hR : 0 < R := dist_nonneg.trans_lt hw.1, set F : ℂ → E := dslope f w, have hws : (insert w s).countable := hs.insert w, have hnhds : closed_ball c R ∈ 𝓝 w, from closed_ball_mem_nhds_of_mem hw.1, have hcF : continuous_on F (closed_ball c R), from (continuous_on_dslope $ closed_ball_mem_nhds_of_mem hw.1).2 ⟨hc, hd _ hw⟩, have hdF : ∀ z ∈ ball (c : ℂ) R \ (insert w s), differentiable_at ℂ F z, from λ z hz, (differentiable_at_dslope_of_ne (ne_of_mem_of_not_mem (mem_insert _ _) hz.2).symm).2 (hd _ (diff_subset_diff_right (subset_insert _ _) hz)), have HI := circle_integral_eq_zero_of_differentiable_on_off_countable hR.le hws hcF hdF, have hne : ∀ z ∈ sphere c R, z ≠ w, from λ z hz, ne_of_mem_of_not_mem hz (ne_of_lt hw.1), have hFeq : eq_on F (λ z, (z - w)⁻¹ • f z - (z - w)⁻¹ • f w) (sphere c R), { intros z hz, calc F z = (z - w)⁻¹ • (f z - f w) : update_noteq (hne z hz) _ _ ... = (z - w)⁻¹ • f z - (z - w)⁻¹ • f w : smul_sub _ _ _ }, have hc' : continuous_on (λ z, (z - w)⁻¹) (sphere c R), from (continuous_on_id.sub continuous_on_const).inv₀ (λ z hz, sub_ne_zero.2 $ hne z hz), rw [← circle_integral.integral_sub_inv_of_mem_ball hw.1, ← circle_integral.integral_smul_const, ← sub_eq_zero, ← circle_integral.integral_sub, ← circle_integral.integral_congr hR.le hFeq, HI], exacts [(hc'.smul (hc.mono sphere_subset_closed_ball)).circle_integrable hR.le, (hc'.smul continuous_on_const).circle_integrable hR.le] end /-- **Cauchy integral formula**: if `f : ℂ → E` is continuous on a closed disc of radius `R` and is complex differentiable at all but countably many points of its interior, then for any `w` in this interior we have $\frac{1}{2πi}\oint_{|z-c|=R}(z-w)^{-1}f(z)\,dz=f(w)$. -/ lemma two_pi_I_inv_smul_circle_integral_sub_inv_smul_of_differentiable_on_off_countable {R : ℝ} {c w : ℂ} {f : ℂ → E} {s : set ℂ} (hs : s.countable) (hw : w ∈ ball c R) (hc : continuous_on f (closed_ball c R)) (hd : ∀ x ∈ ball c R \ s, differentiable_at ℂ f x) : (2 * π * I : ℂ)⁻¹ • ∮ z in C(c, R), (z - w)⁻¹ • f z = f w := begin have hR : 0 < R := dist_nonneg.trans_lt hw, suffices : w ∈ closure (ball c R \ s), { lift R to ℝ≥0 using hR.le, have A : continuous_at (λ w, (2 * π * I : ℂ)⁻¹ • ∮ z in C(c, R), (z - w)⁻¹ • f z) w, { have := has_fpower_series_on_cauchy_integral ((hc.mono sphere_subset_closed_ball).circle_integrable R.coe_nonneg) hR, refine this.continuous_on.continuous_at (emetric.is_open_ball.mem_nhds _), rwa metric.emetric_ball_nnreal }, have B : continuous_at f w, from hc.continuous_at (closed_ball_mem_nhds_of_mem hw), refine tendsto_nhds_unique_of_frequently_eq A B ((mem_closure_iff_frequently.1 this).mono _), intros z hz, rw [circle_integral_sub_inv_smul_of_differentiable_on_off_countable_aux hs hz hc hd, inv_smul_smul₀], simp [real.pi_ne_zero, I_ne_zero] }, refine mem_closure_iff_nhds.2 (λ t ht, _), -- TODO: generalize to any vector space over `ℝ` set g : ℝ → ℂ := λ x, w + x, have : tendsto g (𝓝 0) (𝓝 w), from (continuous_const.add continuous_of_real).tendsto' 0 w (add_zero _), rcases mem_nhds_iff_exists_Ioo_subset.1 (this $ inter_mem ht $ is_open_ball.mem_nhds hw) with ⟨l, u, hlu₀, hlu_sub⟩, obtain ⟨x, hx⟩ : (Ioo l u \ g ⁻¹' s).nonempty, { refine nonempty_diff.2 (λ hsub, _), have : (Ioo l u).countable, from (hs.preimage ((add_right_injective w).comp of_real_injective)).mono hsub, rw [← cardinal.mk_set_le_aleph_0, cardinal.mk_Ioo_real (hlu₀.1.trans hlu₀.2)] at this, exact this.not_lt cardinal.aleph_0_lt_continuum }, exact ⟨g x, (hlu_sub hx.1).1, (hlu_sub hx.1).2, hx.2⟩ end /-- **Cauchy integral formula**: if `f : ℂ → E` is continuous on a closed disc of radius `R` and is complex differentiable at all but countably many points of its interior, then for any `w` in this interior we have $\oint_{|z-c|=R}(z-w)^{-1}f(z)\,dz=2πif(w)$. -/ lemma circle_integral_sub_inv_smul_of_differentiable_on_off_countable {R : ℝ} {c w : ℂ} {f : ℂ → E} {s : set ℂ} (hs : s.countable) (hw : w ∈ ball c R) (hc : continuous_on f (closed_ball c R)) (hd : ∀ x ∈ ball c R \ s, differentiable_at ℂ f x) : ∮ z in C(c, R), (z - w)⁻¹ • f z = (2 * π * I : ℂ) • f w := by { rw [← two_pi_I_inv_smul_circle_integral_sub_inv_smul_of_differentiable_on_off_countable hs hw hc hd, smul_inv_smul₀], simp [real.pi_ne_zero, I_ne_zero] } /-- **Cauchy integral formula**: if `f : ℂ → E` is complex differentiable on an open disc and is continuous on its closure, then for any `w` in this open ball we have $\oint_{|z-c|=R}(z-w)^{-1}f(z)\,dz=2πif(w)$. -/ lemma _root_.diff_cont_on_cl.circle_integral_sub_inv_smul {R : ℝ} {c w : ℂ} {f : ℂ → E} (h : diff_cont_on_cl ℂ f (ball c R)) (hw : w ∈ ball c R) : ∮ z in C(c, R), (z - w)⁻¹ • f z = (2 * π * I : ℂ) • f w := circle_integral_sub_inv_smul_of_differentiable_on_off_countable countable_empty hw h.continuous_on_ball $ λ x hx, h.differentiable_at is_open_ball hx.1 /-- **Cauchy integral formula**: if `f : ℂ → E` is complex differentiable on a closed disc of radius `R`, then for any `w` in its interior we have $\oint_{|z-c|=R}(z-w)^{-1}f(z)\,dz=2πif(w)$. -/ lemma _root_.differentiable_on.circle_integral_sub_inv_smul {R : ℝ} {c w : ℂ} {f : ℂ → E} (hd : differentiable_on ℂ f (closed_ball c R)) (hw : w ∈ ball c R) : ∮ z in C(c, R), (z - w)⁻¹ • f z = (2 * π * I : ℂ) • f w := (hd.mono closure_ball_subset_closed_ball).diff_cont_on_cl.circle_integral_sub_inv_smul hw /-- **Cauchy integral formula**: if `f : ℂ → ℂ` is continuous on a closed disc of radius `R` and is complex differentiable at all but countably many points of its interior, then for any `w` in this interior we have $\oint_{|z-c|=R}\frac{f(z)}{z-w}dz=2\pi i\,f(w)$. -/ lemma circle_integral_div_sub_of_differentiable_on_off_countable {R : ℝ} {c w : ℂ} {s : set ℂ} (hs : s.countable) (hw : w ∈ ball c R) {f : ℂ → ℂ} (hc : continuous_on f (closed_ball c R)) (hd : ∀ z ∈ ball c R \ s, differentiable_at ℂ f z) : ∮ z in C(c, R), f z / (z - w) = 2 * π * I * f w := by simpa only [smul_eq_mul, div_eq_inv_mul] using circle_integral_sub_inv_smul_of_differentiable_on_off_countable hs hw hc hd /-- If `f : ℂ → E` is continuous on a closed ball of positive radius and is differentiable at all but countably many points of the corresponding open ball, then it is analytic on the open ball with coefficients of the power series given by Cauchy integral formulas. -/ lemma has_fpower_series_on_ball_of_differentiable_off_countable {R : ℝ≥0} {c : ℂ} {f : ℂ → E} {s : set ℂ} (hs : s.countable) (hc : continuous_on f (closed_ball c R)) (hd : ∀ z ∈ ball c R \ s, differentiable_at ℂ f z) (hR : 0 < R) : has_fpower_series_on_ball f (cauchy_power_series f c R) c R := { r_le := le_radius_cauchy_power_series _ _ _, r_pos := ennreal.coe_pos.2 hR, has_sum := λ w hw, begin have hw' : c + w ∈ ball c R, by simpa only [add_mem_ball_iff_norm, ← coe_nnnorm, mem_emetric_ball_zero_iff, nnreal.coe_lt_coe, ennreal.coe_lt_coe] using hw, rw ← two_pi_I_inv_smul_circle_integral_sub_inv_smul_of_differentiable_on_off_countable hs hw' hc hd, exact (has_fpower_series_on_cauchy_integral ((hc.mono sphere_subset_closed_ball).circle_integrable R.2) hR).has_sum hw end } /-- If `f : ℂ → E` is complex differentiable on an open disc of positive radius and is continuous on its closure, then it is analytic on the open disc with coefficients of the power series given by Cauchy integral formulas. -/ lemma _root_.diff_cont_on_cl.has_fpower_series_on_ball {R : ℝ≥0} {c : ℂ} {f : ℂ → E} (hf : diff_cont_on_cl ℂ f (ball c R)) (hR : 0 < R) : has_fpower_series_on_ball f (cauchy_power_series f c R) c R := has_fpower_series_on_ball_of_differentiable_off_countable countable_empty hf.continuous_on_ball (λ z hz, hf.differentiable_at is_open_ball hz.1) hR /-- If `f : ℂ → E` is complex differentiable on a closed disc of positive radius, then it is analytic on the corresponding open disc, and the coefficients of the power series are given by Cauchy integral formulas. See also `complex.has_fpower_series_on_ball_of_differentiable_off_countable` for a version of this lemma with weaker assumptions. -/ protected lemma _root_.differentiable_on.has_fpower_series_on_ball {R : ℝ≥0} {c : ℂ} {f : ℂ → E} (hd : differentiable_on ℂ f (closed_ball c R)) (hR : 0 < R) : has_fpower_series_on_ball f (cauchy_power_series f c R) c R := (hd.mono closure_ball_subset_closed_ball).diff_cont_on_cl.has_fpower_series_on_ball hR /-- If `f : ℂ → E` is complex differentiable on some set `s`, then it is analytic at any point `z` such that `s ∈ 𝓝 z` (equivalently, `z ∈ interior s`). -/ protected lemma _root_.differentiable_on.analytic_at {s : set ℂ} {f : ℂ → E} {z : ℂ} (hd : differentiable_on ℂ f s) (hz : s ∈ 𝓝 z) : analytic_at ℂ f z := begin rcases nhds_basis_closed_ball.mem_iff.1 hz with ⟨R, hR0, hRs⟩, lift R to ℝ≥0 using hR0.le, exact ((hd.mono hRs).has_fpower_series_on_ball hR0).analytic_at end /-- A complex differentiable function `f : ℂ → E` is analytic at every point. -/ protected lemma _root_.differentiable.analytic_at {f : ℂ → E} (hf : differentiable ℂ f) (z : ℂ) : analytic_at ℂ f z := hf.differentiable_on.analytic_at univ_mem /-- When `f : ℂ → E` is differentiable, the `cauchy_power_series f z R` represents `f` as a power series centered at `z` in the entirety of `ℂ`, regardless of `R : ℝ≥0`, with `0 < R`. -/ protected lemma _root_.differentiable.has_fpower_series_on_ball {f : ℂ → E} (h : differentiable ℂ f) (z : ℂ) {R : ℝ≥0} (hR : 0 < R) : has_fpower_series_on_ball f (cauchy_power_series f z R) z ∞ := (h.differentiable_on.has_fpower_series_on_ball hR).r_eq_top_of_exists $ λ r hr, ⟨_, h.differentiable_on.has_fpower_series_on_ball hr⟩ end complex
26d99fb41ef0b2945af14770a139d028a171091d
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch5/ex0302.lean
035d5e2842c32a56f14167b409b297462a96e719
[]
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
123
lean
example (p q : Prop) : p ∧ q → q ∧ p := begin intro h, cases h with hp hq, constructor, exact hq, exact hp end
0c399334daae9a555a482fdfddc51947f882473a
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/ring_theory/polynomial/scale_roots.lean
54db400530fb2bbac1eba2246d3451b04aecf761
[ "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
5,040
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen, Devon Tuma -/ import ring_theory.polynomial.basic import ring_theory.non_zero_divisors section scale_roots variables {A K R S : Type*} [integral_domain A] [field K] [comm_ring R] [comm_ring S] variables {M : submonoid A} open finsupp polynomial /-- `scale_roots p s` is a polynomial with root `r * s` for each root `r` of `p`. -/ noncomputable def scale_roots (p : polynomial R) (s : R) : polynomial R := on_finset p.support (λ i, coeff p i * s ^ (p.nat_degree - i)) (λ i h, mem_support_iff.mpr (left_ne_zero_of_mul h)) @[simp] lemma coeff_scale_roots (p : polynomial R) (s : R) (i : ℕ) : (scale_roots p s).coeff i = coeff p i * s ^ (p.nat_degree - i) := rfl lemma coeff_scale_roots_nat_degree (p : polynomial R) (s : R) : (scale_roots p s).coeff p.nat_degree = p.leading_coeff := by rw [leading_coeff, coeff_scale_roots, nat.sub_self, pow_zero, mul_one] @[simp] lemma zero_scale_roots (s : R) : scale_roots 0 s = 0 := by { ext, simp } lemma scale_roots_ne_zero {p : polynomial R} (hp : p ≠ 0) (s : R) : scale_roots p s ≠ 0 := begin intro h, have : p.coeff p.nat_degree ≠ 0 := mt leading_coeff_eq_zero.mp hp, have : (scale_roots p s).coeff p.nat_degree = 0 := congr_fun (congr_arg (coeff : polynomial R → ℕ → R) h) p.nat_degree, rw [coeff_scale_roots_nat_degree] at this, contradiction end lemma support_scale_roots_le (p : polynomial R) (s : R) : (scale_roots p s).support ≤ p.support := begin intros i, simp only [mem_support_iff, scale_roots, on_finset_apply], exact left_ne_zero_of_mul end lemma support_scale_roots_eq (p : polynomial R) {s : R} (hs : s ∈ non_zero_divisors R) : (scale_roots p s).support = p.support := le_antisymm (support_scale_roots_le p s) begin intro i, simp only [mem_support_iff, scale_roots, on_finset_apply], intros p_ne_zero ps_zero, have := ((non_zero_divisors R).pow_mem hs (p.nat_degree - i)) _ ps_zero, contradiction end @[simp] lemma degree_scale_roots (p : polynomial R) {s : R} : degree (scale_roots p s) = degree p := begin haveI := classical.prop_decidable, by_cases hp : p = 0, { rw [hp, zero_scale_roots] }, have := scale_roots_ne_zero hp s, refine le_antisymm (finset.sup_mono (support_scale_roots_le p s)) (degree_le_degree _), rw coeff_scale_roots_nat_degree, intro h, have := leading_coeff_eq_zero.mp h, contradiction, end @[simp] lemma nat_degree_scale_roots (p : polynomial R) (s : R) : nat_degree (scale_roots p s) = nat_degree p := by simp only [nat_degree, degree_scale_roots] lemma monic_scale_roots_iff {p : polynomial R} (s : R) : monic (scale_roots p s) ↔ monic p := by simp [monic, leading_coeff] lemma scale_roots_eval₂_eq_zero {p : polynomial S} (f : S →+* R) {r : R} {s : S} (hr : eval₂ f r p = 0) : eval₂ f (f s * r) (scale_roots p s) = 0 := calc eval₂ f (f s * r) (scale_roots p s) = (scale_roots p s).support.sum (λ i, f (coeff p i * s ^ (p.nat_degree - i)) * (f s * r) ^ i) : eval₂_eq_sum ... = p.support.sum (λ i, f (coeff p i * s ^ (p.nat_degree - i)) * (f s * r) ^ i) : finset.sum_subset (support_scale_roots_le p s) (λ i hi hi', let this : coeff p i * s ^ (p.nat_degree - i) = 0 := by simpa using hi' in by simp [this]) ... = p.support.sum (λ (i : ℕ), f (p.coeff i) * f s ^ (p.nat_degree - i + i) * r ^ i) : finset.sum_congr rfl (λ i hi, by simp_rw [f.map_mul, f.map_pow, pow_add, mul_pow, mul_assoc]) ... = p.support.sum (λ (i : ℕ), f s ^ p.nat_degree * (f (p.coeff i) * r ^ i)) : finset.sum_congr rfl (λ i hi, by { rw [mul_assoc, mul_left_comm, nat.sub_add_cancel], exact le_nat_degree_of_ne_zero (mem_support_iff.mp hi) }) ... = f s ^ p.nat_degree * p.support.sum (λ (i : ℕ), (f (p.coeff i) * r ^ i)) : finset.mul_sum.symm ... = f s ^ p.nat_degree * eval₂ f r p : by { rw [eval₂_eq_sum], refl } ... = 0 : by rw [hr, _root_.mul_zero] lemma scale_roots_aeval_eq_zero [algebra S R] {p : polynomial S} {r : R} {s : S} (hr : aeval r p = 0) : aeval (algebra_map S R s * r) (scale_roots p s) = 0 := scale_roots_eval₂_eq_zero (algebra_map S R) hr lemma scale_roots_eval₂_eq_zero_of_eval₂_div_eq_zero {p : polynomial A} {f : A →+* K} (hf : function.injective f) {r s : A} (hr : eval₂ f (f r / f s) p = 0) (hs : s ∈ non_zero_divisors A) : eval₂ f (f r) (scale_roots p s) = 0 := begin convert scale_roots_eval₂_eq_zero f hr, rw [←mul_div_assoc, mul_comm, mul_div_cancel], exact @map_ne_zero_of_mem_non_zero_divisors _ _ _ _ _ _ hf ⟨s, hs⟩ end lemma scale_roots_aeval_eq_zero_of_aeval_div_eq_zero [algebra A K] (inj : function.injective (algebra_map A K)) {p : polynomial A} {r s : A} (hr : aeval (algebra_map A K r / algebra_map A K s) p = 0) (hs : s ∈ non_zero_divisors A) : aeval (algebra_map A K r) (scale_roots p s) = 0 := scale_roots_eval₂_eq_zero_of_eval₂_div_eq_zero inj hr hs end scale_roots
8aa976d24107834a4ab03155a2560bb1af5cbd68
98beff2e97d91a54bdcee52f922c4e1866a6c9b9
/src/sieve.lean
df1741c9dbb977e80b331f0e9b01cb3cf95e5ffe
[]
no_license
b-mehta/topos
c3fc43fb04ba16bae1965ce5c26c6461172e5bc6
c9032b11789e36038bc841a1e2b486972421b983
refs/heads/master
1,629,609,492,867
1,609,907,263,000
1,609,907,263,000
240,943,034
43
3
null
1,598,210,062,000
1,581,877,668,000
Lean
UTF-8
Lean
false
false
9,542
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, E. W. Ayers -/ import category_theory.over import category_theory.limits.shapes.finite_limits import category_theory.yoneda import order.complete_lattice import data.set.lattice universes v u namespace category_theory /-- A sieve on X is a set of morphisms to X that is closed under left composition. -/ structure sieve {C : Type u} [category.{v} C] (X : C) := (arrows : set (over X)) (subs : ∀ {Y Z : C} {f : Y ⟶ X} (g : Z ⟶ Y), over.mk f ∈ arrows → over.mk (g ≫ f) ∈ arrows) namespace sieve variables {C : Type u} [category.{v} C] variables {X Y Z : C} {S R : sieve X} @[simp, priority 100] lemma downward_closed (S : sieve X) {f : Y ⟶ X} (Hf : over.mk f ∈ S.arrows) (g : Z ⟶ Y) : over.mk (g ≫ f) ∈ S.arrows := S.subs g Hf lemma arrow_ext : Π {R S : sieve X}, R.arrows = S.arrows → R = S | ⟨Ra, _⟩ ⟨Sa, _⟩ rfl := rfl @[ext] lemma ext_iff {R S : sieve X} : (∀ {Y} (f : Y ⟶ X), over.mk f ∈ R.arrows ↔ over.mk f ∈ S.arrows) → R = S := begin intros a, apply arrow_ext, ext ⟨_, _, _⟩, convert a x_hom; apply subsingleton.elim, end open lattice /-- The supremum of a collection of sieves: just the union of them all. -/ protected def Sup (𝒮 : set (sieve X)) : (sieve X) := { arrows := ⋃ (S : {i // i ∈ 𝒮}), S.1.arrows, subs := begin rintros Y Z f g ⟨R, ⟨⟨S, hS⟩, rfl⟩, w⟩, refine ⟨_, ⟨⟨S, hS⟩, rfl⟩, _⟩, simp [w], end } /-- The infimum of a collection of sieves: the intersection of them all. -/ protected def Inf (𝒮 : set (sieve X)) : (sieve X) := { arrows := ⋂ (S : {S // S ∈ 𝒮}), S.1.arrows, subs := begin rintros Y Z f g R _ ⟨⟨S, hS⟩, rfl⟩, simp [R _ ⟨⟨S, hS⟩, rfl⟩], end } /-- The union of two sieves is a sieve. -/ protected def union (S R : sieve X) : sieve X := { arrows := S.arrows ∪ R.arrows, subs := begin rintros Y Z f g (a | a); { simp [a] }, end } /-- The intersection of two sieves is a sieve. -/ protected def inter (S R : sieve X) : sieve X := { arrows := S.arrows ∩ R.arrows, subs := begin rintros Y Z f g ⟨h₁, h₂⟩, simp [h₁, h₂], end } /-- Sieves on an object `X` form a complete lattice. We generate this directly rather than using the galois insertion for nicer definitional properties. -/ instance : complete_lattice (sieve X) := { le := λ S R, ∀ Y (f : Y ⟶ X), over.mk f ∈ S.arrows → over.mk f ∈ R.arrows, le_refl := λ S f q, id, le_trans := λ S₁ S₂ S₃ S₁₂ S₂₃ Y f h, S₂₃ _ _ (S₁₂ _ _ h), le_antisymm := begin intros S R p q, ext, refine ⟨p _ _, q _ _⟩ end, top := { arrows := set.univ, subs := λ Y Z f g h, ⟨⟩ }, bot := { arrows := ∅, subs := λ a aa Z g, false.elim }, sup := sieve.union, inf := sieve.inter, Sup := sieve.Sup, Inf := sieve.Inf, le_Sup := λ _ S hS _ _ h, ⟨_, ⟨⟨S, hS⟩, rfl⟩, h⟩, Sup_le := begin rintros 𝒮 S hS Y f ⟨_, ⟨⟨T, hT⟩, rfl⟩, q⟩, apply hS _ hT _ _ q end, Inf_le := λ _ S hS _ _ h, h _ ⟨⟨_, hS⟩, rfl⟩, le_Inf := begin rintros 𝒮 S hS Y f h q ⟨⟨T, hT⟩, rfl⟩, apply hS _ hT _ _ h end, le_sup_left := λ _ _ _ _, or.inl, le_sup_right := λ _ _ _ _, or.inr, sup_le := begin rintros _ _ _ a b _ _ (q | q), apply a _ _ q, apply b _ _ q end, inf_le_left := λ _ _ _ _, and.left, inf_le_right := λ _ _ _ _, and.right, le_inf := begin intros _ _ _ p q _ _ z, exact ⟨p _ _ z, q _ _ z⟩, end, le_top := λ _ _ _ _, trivial, bot_le := by { rintros _ _ _ ⟨⟩ } } @[simp] lemma mem_inter {R S : sieve X} {Y} (f : Y ⟶ X) : over.mk f ∈ (R ⊓ S).arrows ↔ over.mk f ∈ R.arrows ∧ over.mk f ∈ S.arrows := iff.rfl @[simp] lemma mem_union {R S : sieve X} {Y} (f : Y ⟶ X) : over.mk f ∈ (R ⊔ S).arrows ↔ over.mk f ∈ R.arrows ∨ over.mk f ∈ S.arrows := iff.rfl @[simp] lemma mem_top (f : Y ⟶ X) : over.mk f ∈ (⊤ : sieve X).arrows := trivial instance : preorder (sieve X) := by apply_instance instance : partial_order (sieve X) := by apply_instance inductive generate_sets (𝒢 : set (over X)) : over X → Prop | basic : Π {f : over X}, f ∈ 𝒢 → generate_sets f | subs : Π {Y Z} {f : Y ⟶ X} (g : Z ⟶ Y), generate_sets (over.mk f) → generate_sets (over.mk (g ≫ f)) /-- Generate the smallest sieve containing the given set of arrows. -/ def generate (𝒢 : set (over X)) : sieve X := { arrows := generate_sets 𝒢, subs := λ Y Z f g t, generate_sets.subs _ t } open order lattice lemma sets_iff_generate {𝒢 : set (over X)} : generate 𝒢 ≤ S ↔ 𝒢 ⊆ S.arrows := iff.intro (λ H g hg, begin have : over.mk g.hom = g, cases g, dsimp [over.mk], congr' 1, apply subsingleton.elim, rw ← this at *, apply H, apply generate_sets.basic hg, end ) (λ ss Y f hf, begin induction hf with hf_f hf_a hf_Y hf_Z hf_f hf_g hf_a hf_ih, apply ss hf_a, apply downward_closed, apply hf_ih end) /-- Show that there is a galois insertion (generate, .arrows). -/ def gi_generate : @galois_insertion (set (over X)) (sieve X) (by apply_instance) _ generate sieve.arrows := { gc := λ s f, sets_iff_generate, choice := λ 𝒢 f, generate 𝒢, choice_eq := λ 𝒢 h, rfl, le_l_u := λ _ _ _, generate_sets.basic } /-- Given a morphism `h : Y ⟶ X`, send a sieve S on X to a sieve on Y as the inverse image of S with `_ ≫ h`. That is, `sieve.pullback S h := (≫ h) '⁻¹ S`. -/ def pullback (S : sieve X) (h : Y ⟶ X) : sieve Y := { arrows := {sl | over.mk (sl.hom ≫ h) ∈ S.arrows }, subs := λ f hf Z g k, by { dsimp at k, simp [k] } } @[simp] lemma mem_pullback (h : Y ⟶ X) {f : Z ⟶ Y} : over.mk f ∈ (pullback S h).arrows ↔ over.mk (f ≫ h) ∈ S.arrows := iff.rfl /-- Push a sieve `R` on `Y` forward along an arrow `f : Y ⟶ X`: `gf : Z ⟶ X` is in the sieve if `gf` factors through some `g : Z ⟶ Y` which is in `R`. -/ def comp (R : sieve Y) (f : Y ⟶ X) : sieve X := { arrows := λ gf, ∃ (g : gf.left ⟶ Y), over.mk g ∈ R.arrows ∧ g ≫ f = gf.hom, subs := begin rintros Z₁ Z₂ g h ⟨j, k, z⟩, refine ⟨h ≫ j, _, _⟩, simp [k], simp [z], end } -- def comps (R : Π (f : over X), sieve f.left) (S : sieve X) : sieve X := -- ⨆ (f ∈ S.arrows), comp (R f) f.hom /-- Pullback is monotonic -/ lemma pullback_le_map {S R : sieve X} (Hss : S ≤ R) (f : Y ⟶ X) : pullback S f ≤ pullback R f := begin rintros Z H, apply Hss end lemma pullback_top {f : Y ⟶ X} : pullback ⊤ f = ⊤ := top_unique (λ _ g, id) lemma pullback_comp {f : Y ⟶ X} {g : Z ⟶ Y} (S : sieve X) : S.pullback (g ≫ f) = (S.pullback f).pullback g := begin ext W h, simp, end lemma pullback_inter {f : Y ⟶ X} (S R : sieve X) : (S ⊓ R).pullback f = S.pullback f ⊓ R.pullback f := begin ext Z g, simp, end lemma le_pullback_comp {R : sieve Y} {f : Y ⟶ X} : R ≤ pullback (comp R f) f := begin rintros Z g b, refine ⟨_, _, rfl⟩, simpa end /-- If the identity arrow is in a sieve, the sieve is maximal. -/ lemma id_mem_iff_eq_top : over.mk (𝟙 X) ∈ S.arrows ↔ S = ⊤ := ⟨begin intro h, rw eq_top_iff, rintros Y f ⟨⟩, suffices : over.mk (f ≫ (𝟙 _)) ∈ S.arrows, simpa using this, apply downward_closed _ h, end, by { rintro rfl, trivial } ⟩ lemma pullback_eq_top_iff_mem (f : Y ⟶ X) : over.mk f ∈ S.arrows ↔ S.pullback f = ⊤ := by rw [← id_mem_iff_eq_top, mem_pullback, category.id_comp] -- lemma comp_le_comps -- (R : Π (f : over X), sieve f.1) -- (S : sieve X) -- (f : over X) -- (H : f ∈ S.arrows) : -- comp (R f) f.hom ≤ comps R S := -- calc comp (R f) f.hom ≤ ⨆ (_ : f ∈ S.arrows), comp (R f) f.hom : le_supr _ H -- ... ≤ comps R S : le_supr _ f -- lemma comps_le -- (R : Π (f : over X), sieve f.left) -- (S : sieve X) : -- comps R S ≤ S := -- begin -- apply supr_le _, -- rintros f, -- apply supr_le _, -- rintros H Y g, -- rintros ⟨a,b,e⟩, -- -- suffices : over.mk (g.hom) ∈ S.arrows, simp at this, apply this, -- -- rw ← e, -- -- apply downward_closed, -- -- apply H, -- end /-- A sieve induces a presheaf. -/ @[simps] def as_functor (S : sieve X) : Cᵒᵖ ⥤ Type v := { obj := λ Y, {g : Y.unop ⟶ X // over.mk g ∈ S.arrows}, map := λ Y Z f g, ⟨f.unop ≫ g.1, downward_closed _ g.2 _⟩ } @[simps] def le_as_functor {S T : sieve X} (h : S ≤ T) : S.as_functor ⟶ T.as_functor := { app := λ Y f, ⟨f.1, h _ _ f.2⟩ }. /-- The natural inclusion from the functor induced by a sieve to the yoneda embedding. -/ @[simps] def functor_inclusion (S : sieve X) : S.as_functor ⟶ yoneda.obj X := { app := λ Y f, f.1 }. lemma le_as_functor_comm {S T : sieve X} (h : S ≤ T) : le_as_functor h ≫ functor_inclusion _ = functor_inclusion _ := begin ext c t, refl, end /-- The presheaf induced by a sieve is a subobject of the yoneda embedding. -/ instance functor_inclusion_is_mono : mono (functor_inclusion S) := ⟨λ Z f g h, begin ext Y y, have : (f ≫ functor_inclusion S).app Y y = (g ≫ functor_inclusion S).app Y y, rw h, exact this end⟩ end sieve end category_theory
4f04b3ebd3d80911340c2b2f99a59a66ab7ce52f
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/group_theory/specific_groups/alternating.lean
c5922d72f872c53afe89f5bd65fa76993f2d3e96
[ "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
15,200
lean
/- Copyright (c) 2021 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import group_theory.perm.fin import tactic.interval_cases /-! # Alternating Groups The alternating group on a finite type `α` is the subgroup of the permutation group `perm α` consisting of the even permutations. ## Main definitions * `alternating_group α` is the alternating group on `α`, defined as a `subgroup (perm α)`. ## Main results * `two_mul_card_alternating_group` shows that the alternating group is half as large as the permutation group it is a subgroup of. * `closure_three_cycles_eq_alternating` shows that the alternating group is generated by 3-cycles. * `alternating_group.is_simple_group_five` shows that the alternating group on `fin 5` is simple. The proof shows that the normal closure of any non-identity element of this group contains a 3-cycle. ## Tags alternating group permutation ## TODO * Show that `alternating_group α` is simple if and only if `fintype.card α ≠ 4`. -/ open equiv equiv.perm subgroup fintype variables (α : Type*) [fintype α] [decidable_eq α] /-- The alternating group on a finite type, realized as a subgroup of `equiv.perm`. For $A_n$, use `alternating_group (fin n)`. -/ @[derive fintype] def alternating_group : subgroup (perm α) := sign.ker instance [subsingleton α] : unique (alternating_group α) := ⟨⟨1⟩, λ ⟨p, hp⟩, subtype.eq (subsingleton.elim p _)⟩ variables {α} lemma alternating_group_eq_sign_ker : alternating_group α = sign.ker := rfl namespace equiv.perm @[simp] lemma mem_alternating_group {f : perm α} : f ∈ alternating_group α ↔ sign f = 1 := sign.mem_ker lemma prod_list_swap_mem_alternating_group_iff_even_length {l : list (perm α)} (hl : ∀ g ∈ l, is_swap g) : l.prod ∈ alternating_group α ↔ even l.length := begin rw [mem_alternating_group, sign_prod_list_swap hl, ← units.coe_eq_one, units.coe_pow, units.coe_neg_one, nat.neg_one_pow_eq_one_iff_even], dec_trivial end lemma is_three_cycle.mem_alternating_group {f : perm α} (h : is_three_cycle f) : f ∈ alternating_group α := mem_alternating_group.2 h.sign lemma fin_rotate_bit1_mem_alternating_group {n : ℕ} : fin_rotate (bit1 n) ∈ alternating_group (fin (bit1 n)) := by rw [mem_alternating_group, bit1, sign_fin_rotate, pow_bit0', int.units_mul_self, one_pow] end equiv.perm lemma two_mul_card_alternating_group [nontrivial α] : 2 * card (alternating_group α) = card (perm α) := begin let := (quotient_group.quotient_ker_equiv_of_surjective _ (sign_surjective α)).to_equiv, rw [←fintype.card_units_int, ←fintype.card_congr this], exact (subgroup.card_eq_card_quotient_mul_card_subgroup _).symm, end namespace alternating_group open equiv.perm instance normal : (alternating_group α).normal := sign.normal_ker lemma is_conj_of {σ τ : alternating_group α} (hc : is_conj (σ : perm α) (τ : perm α)) (hσ : (σ : perm α).support.card + 2 ≤ fintype.card α) : is_conj σ τ := begin obtain ⟨σ, hσ⟩ := σ, obtain ⟨τ, hτ⟩ := τ, obtain ⟨π, hπ⟩ := is_conj_iff.1 hc, rw [subtype.coe_mk, subtype.coe_mk] at hπ, cases int.units_eq_one_or (sign π) with h h, { rw is_conj_iff, refine ⟨⟨π, mem_alternating_group.mp h⟩, subtype.val_injective _⟩, simpa only [subtype.val_eq_coe, subgroup.coe_mul, coe_inv, coe_mk] using hπ }, { have h2 : 2 ≤ σ.supportᶜ.card, { rw [finset.card_compl, nat.le_sub_left_iff_add_le σ.support.card_le_univ], exact hσ }, obtain ⟨a, ha, b, hb, ab⟩ := finset.one_lt_card.1 h2, refine is_conj_iff.2 ⟨⟨π * swap a b, _⟩, subtype.val_injective _⟩, { rw [mem_alternating_group, monoid_hom.map_mul, h, sign_swap ab, int.units_mul_self] }, { simp only [←hπ, coe_mk, subgroup.coe_mul, subtype.val_eq_coe], have hd : disjoint (swap a b) σ, { rw [disjoint_iff_disjoint_support, support_swap ab, finset.disjoint_insert_left, finset.singleton_disjoint], exact ⟨finset.mem_compl.1 ha, finset.mem_compl.1 hb⟩ }, rw [mul_assoc π _ σ, hd.commute.eq, coe_inv, coe_mk], simp [mul_assoc] } } end lemma is_three_cycle_is_conj (h5 : 5 ≤ fintype.card α) {σ τ : alternating_group α} (hσ : is_three_cycle (σ : perm α)) (hτ : is_three_cycle (τ : perm α)) : is_conj σ τ := alternating_group.is_conj_of (is_conj_iff_cycle_type_eq.2 (hσ.trans hτ.symm)) (by rwa hσ.card_support) end alternating_group namespace equiv.perm open alternating_group @[simp] theorem closure_three_cycles_eq_alternating : closure {σ : perm α | is_three_cycle σ} = alternating_group α := closure_eq_of_le _ (λ σ hσ, mem_alternating_group.2 hσ.sign) $ λ σ hσ, begin suffices hind : ∀ (n : ℕ) (l : list (perm α)) (hl : ∀ g, g ∈ l → is_swap g) (hn : l.length = 2 * n), l.prod ∈ closure {σ : perm α | is_three_cycle σ}, { obtain ⟨l, rfl, hl⟩ := trunc_swap_factors σ, obtain ⟨n, hn⟩ := (prod_list_swap_mem_alternating_group_iff_even_length hl).1 hσ, exact hind n l hl hn }, intro n, induction n with n ih; intros l hl hn, { simp [list.length_eq_zero.1 hn, one_mem] }, rw [nat.mul_succ] at hn, obtain ⟨a, l, rfl⟩ := l.exists_of_length_succ hn, rw [list.length_cons, nat.succ_inj'] at hn, obtain ⟨b, l, rfl⟩ := l.exists_of_length_succ hn, rw [list.prod_cons, list.prod_cons, ← mul_assoc], rw [list.length_cons, nat.succ_inj'] at hn, exact mul_mem _ (is_swap.mul_mem_closure_three_cycles (hl a (list.mem_cons_self a _)) (hl b (list.mem_cons_of_mem a (l.mem_cons_self b)))) (ih _ (λ g hg, hl g (list.mem_cons_of_mem _ (list.mem_cons_of_mem _ hg))) hn), end /-- A key lemma to prove $A_5$ is simple. Shows that any normal subgroup of an alternating group on at least 5 elements is the entire alternating group if it contains a 3-cycle. -/ lemma is_three_cycle.alternating_normal_closure (h5 : 5 ≤ fintype.card α) {f : perm α} (hf : is_three_cycle f) : normal_closure ({⟨f, hf.mem_alternating_group⟩} : set (alternating_group α)) = ⊤ := eq_top_iff.2 begin have hi : function.injective (alternating_group α).subtype := subtype.coe_injective, refine eq_top_iff.1 (map_injective hi (le_antisymm (map_mono le_top) _)), rw [← monoid_hom.range_eq_map, subtype_range, normal_closure, monoid_hom.map_closure], refine (le_of_eq closure_three_cycles_eq_alternating.symm).trans (closure_mono _), intros g h, obtain ⟨c, rfl⟩ := is_conj_iff.1 (is_conj_iff_cycle_type_eq.2 (hf.trans h.symm)), refine ⟨⟨c * f * c⁻¹, h.mem_alternating_group⟩, _, rfl⟩, rw group.mem_conjugates_of_set_iff, exact ⟨⟨f, hf.mem_alternating_group⟩, set.mem_singleton _, is_three_cycle_is_conj h5 hf h⟩ end /-- Part of proving $A_5$ is simple. Shows that the square of any element of $A_5$ with a 3-cycle in its cycle decomposition is a 3-cycle, so the normal closure of the original element must be $A_5$. -/ lemma is_three_cycle_sq_of_three_mem_cycle_type_five {g : perm (fin 5)} (h : 3 ∈ cycle_type g) : is_three_cycle (g * g) := begin obtain ⟨c, g', rfl, hd, hc, h3⟩ := mem_cycle_type_iff.1 h, simp only [mul_assoc], rw [hd.commute.eq, ← mul_assoc g'], suffices hg' : order_of g' ∣ 2, { rw [← pow_two, order_of_dvd_iff_pow_eq_one.1 hg', one_mul], exact (card_support_eq_three_iff.1 h3).is_three_cycle_sq }, rw [← lcm_cycle_type, multiset.lcm_dvd], intros n hn, rw le_antisymm (two_le_of_mem_cycle_type hn) (le_trans (le_card_support_of_mem_cycle_type hn) _), apply le_of_add_le_add_left, rw [← hd.card_support_mul, h3], exact (c * g').support.card_le_univ, end end equiv.perm namespace alternating_group open equiv.perm lemma nontrivial_of_three_le_card (h3 : 3 ≤ card α) : nontrivial (alternating_group α) := begin haveI := fintype.one_lt_card_iff_nontrivial.1 (lt_trans dec_trivial h3), rw ← fintype.one_lt_card_iff_nontrivial, refine lt_of_mul_lt_mul_left _ (le_of_lt nat.prime_two.pos), rw [two_mul_card_alternating_group, card_perm, ← nat.succ_le_iff], exact le_trans h3 (card α).self_le_factorial, end instance {n : ℕ} : nontrivial (alternating_group (fin (n + 3))) := nontrivial_of_three_le_card (by { rw card_fin, exact le_add_left (le_refl 3) }) /-- The normal closure of the 5-cycle `fin_rotate 5` within $A_5$ is the whole group. This will be used to show that the normal closure of any 5-cycle within $A_5$ is the whole group. -/ lemma normal_closure_fin_rotate_five : (normal_closure ({⟨fin_rotate 5, fin_rotate_bit1_mem_alternating_group⟩} : set (alternating_group (fin 5)))) = ⊤ := eq_top_iff.2 begin have h3 : is_three_cycle ((fin.cycle_range 2) * (fin_rotate 5) * (fin.cycle_range 2)⁻¹ * (fin_rotate 5)⁻¹) := card_support_eq_three_iff.1 dec_trivial, rw ← h3.alternating_normal_closure (by rw [card_fin]), refine normal_closure_le_normal _, rw [set.singleton_subset_iff, set_like.mem_coe], have h : (⟨fin_rotate 5, fin_rotate_bit1_mem_alternating_group⟩ : alternating_group (fin 5)) ∈ normal_closure _ := set_like.mem_coe.1 (subset_normal_closure (set.mem_singleton _)), exact mul_mem _ (subgroup.normal_closure_normal.conj_mem _ h ⟨fin.cycle_range 2, fin.is_three_cycle_cycle_range_two.mem_alternating_group⟩) (inv_mem _ h), end /-- The normal closure of $(04)(13)$ within $A_5$ is the whole group. This will be used to show that the normal closure of any permutation of cycle type $(2,2)$ is the whole group. -/ lemma normal_closure_swap_mul_swap_five : (normal_closure ({⟨swap 0 4 * swap 1 3, mem_alternating_group.2 dec_trivial⟩} : set (alternating_group (fin 5)))) = ⊤ := begin let g1 := (⟨swap 0 2 * swap 0 1, mem_alternating_group.2 dec_trivial⟩ : alternating_group (fin 5)), let g2 := (⟨swap 0 4 * swap 1 3, mem_alternating_group.2 dec_trivial⟩ : alternating_group (fin 5)), have h5 : g1 * g2 * g1⁻¹ * g2⁻¹ = ⟨fin_rotate 5, fin_rotate_bit1_mem_alternating_group⟩, { rw subtype.ext_iff, simp only [fin.coe_mk, subgroup.coe_mul, subgroup.coe_inv, fin.coe_mk], dec_trivial }, rw [eq_top_iff, ← normal_closure_fin_rotate_five], refine normal_closure_le_normal _, rw [set.singleton_subset_iff, set_like.mem_coe, ← h5], have h : g2 ∈ normal_closure {g2} := set_like.mem_coe.1 (subset_normal_closure (set.mem_singleton _)), exact mul_mem _ (subgroup.normal_closure_normal.conj_mem _ h g1) (inv_mem _ h), end /-- Shows that any non-identity element of $A_5$ whose cycle decomposition consists only of swaps is conjugate to $(04)(13)$. This is used to show that the normal closure of such a permutation in $A_5$ is $A_5$. -/ lemma is_conj_swap_mul_swap_of_cycle_type_two {g : perm (fin 5)} (ha : g ∈ alternating_group (fin 5)) (h1 : g ≠ 1) (h2 : ∀ n, n ∈ cycle_type (g : perm (fin 5)) → n = 2) : is_conj (swap 0 4 * swap 1 3) g := begin have h := g.support.card_le_univ, rw [← sum_cycle_type, multiset.eq_repeat_of_mem h2, multiset.sum_repeat, smul_eq_mul] at h, rw [← multiset.eq_repeat'] at h2, have h56 : 5 ≤ 3 * 2 := nat.le_succ 5, have h := le_of_mul_le_mul_right (le_trans h h56) dec_trivial, rw [mem_alternating_group, sign_of_cycle_type, h2, multiset.map_repeat, multiset.prod_repeat, int.units_pow_two, units.ext_iff, units.coe_one, units.coe_pow, units.coe_neg_one, nat.neg_one_pow_eq_one_iff_even _] at ha, swap, { dec_trivial }, rw [is_conj_iff_cycle_type_eq, h2], interval_cases multiset.card g.cycle_type, { exact (h1 (card_cycle_type_eq_zero.1 h_1)).elim }, { contrapose! ha, simp [h_1] }, { have h04 : (0 : fin 5) ≠ 4 := dec_trivial, have h13 : (1 : fin 5) ≠ 3 := dec_trivial, rw [h_1, disjoint.cycle_type, (is_cycle_swap h04).cycle_type, (is_cycle_swap h13).cycle_type, card_support_swap h04, card_support_swap h13], { refl }, { rw [disjoint_iff_disjoint_support, support_swap h04, support_swap h13], dec_trivial } }, { contrapose! ha, simp [h_1] } end /-- Shows that $A_5$ is simple by taking an arbitrary non-identity element and showing by casework on its cycle type that its normal closure is all of $A_5$. -/ instance is_simple_group_five : is_simple_group (alternating_group (fin 5)) := ⟨exists_pair_ne _, λ H, begin introI Hn, refine or_not.imp (id) (λ Hb, _), rw [eq_bot_iff_forall] at Hb, push_neg at Hb, obtain ⟨⟨g, gA⟩, gH, g1⟩ : ∃ (x : ↥(alternating_group (fin 5))), x ∈ H ∧ x ≠ 1 := Hb, -- `g` is a non-identity alternating permutation in a normal subgroup `H` of $A_5$. rw [← set_like.mem_coe, ← set.singleton_subset_iff] at gH, refine eq_top_iff.2 (le_trans (ge_of_eq _) (normal_closure_le_normal gH)), -- It suffices to show that the normal closure of `g` in $A_5$ is $A_5$. by_cases h2 : ∀ n ∈ g.cycle_type, n = 2, { -- If the cycle decomposition of `g` consists entirely of swaps, then the cycle type is $(2,2)$. -- This means that it is conjugate to $(04)(13)$, whose normal closure is $A_5$. rw [ne.def, subtype.ext_iff] at g1, exact (is_conj_swap_mul_swap_of_cycle_type_two gA g1 h2).normal_closure_eq_top_of normal_closure_swap_mul_swap_five }, push_neg at h2, obtain ⟨n, ng, n2⟩ : ∃ (n : ℕ), n ∈ g.cycle_type ∧ n ≠ 2 := h2, -- `n` is the size of a non-swap cycle in the decomposition of `g`. have n2' : 2 < n := lt_of_le_of_ne (two_le_of_mem_cycle_type ng) n2.symm, have n5 : n ≤ 5 := le_trans _ g.support.card_le_univ, -- We check that `2 < n ≤ 5`, so that `interval_cases` has a precise range to check. swap, { obtain ⟨m, hm⟩ := multiset.exists_cons_of_mem ng, rw [← sum_cycle_type, hm, multiset.sum_cons], exact le_add_right (le_refl _) }, interval_cases n, -- This breaks into cases `n = 3`, `n = 4`, `n = 5`. { -- If `n = 3`, then `g` has a 3-cycle in its decomposition, so `g^2` is a 3-cycle. -- `g^2` is in the normal closure of `g`, so that normal closure must be $A_5$. rw [eq_top_iff, ← (is_three_cycle_sq_of_three_mem_cycle_type_five ng).alternating_normal_closure (by rw card_fin )], refine normal_closure_le_normal _, rw [set.singleton_subset_iff, set_like.mem_coe], have h := set_like.mem_coe.1 (subset_normal_closure (set.mem_singleton _)), exact mul_mem _ h h }, { -- The case `n = 4` leads to contradiction, as no element of $A_5$ includes a 4-cycle. have con := mem_alternating_group.1 gA, contrapose! con, rw [sign_of_cycle_type, cycle_type_of_card_le_mem_cycle_type_add_two dec_trivial ng], simp only [multiset.singleton_eq_singleton, multiset.map_cons, mul_one, multiset.prod_cons, units.neg_mul, multiset.prod_zero, multiset.map_zero], dec_trivial }, { -- If `n = 5`, then `g` is itself a 5-cycle, conjugate to `fin_rotate 5`. refine (is_conj_iff_cycle_type_eq.2 _).normal_closure_eq_top_of normal_closure_fin_rotate_five, rw [cycle_type_of_card_le_mem_cycle_type_add_two dec_trivial ng, cycle_type_fin_rotate] } end⟩ end alternating_group
2a1b340130ed159970fa67cc72921883c7e0ff51
f3a5af2927397cf346ec0e24312bfff077f00425
/src/tactic/modded.lean
8ebede8e898b8802129eba0d7433386abb355dc5
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/natural_number_game
05c39e1586408cfb563d1a12e1085a90726ab655
f29b6c2884299fc63fdfc81ae5d7daaa3219f9fd
refs/heads/master
1,688,570,964,990
1,636,908,242,000
1,636,908,242,000
195,403,790
277
84
Apache-2.0
1,694,547,955,000
1,562,328,792,000
Lean
UTF-8
Lean
false
false
3,612
lean
-- modded induction', cases', rw' -- *TODO* -- waiting for simon PR for symmetry' import tactic.interactive run_cmd mk_simp_attr `leakage open lean open lean.parser local postfix `?`:9001 := optional local postfix *:9001 := many namespace tactic namespace interactive open interactive interactive.types expr private meta def resolve_name' (n : name) : tactic expr := do { p ← resolve_name n, match p with | expr.const n _ := mk_const n -- create metavars for universe levels | _ := i_to_expr p end } private meta def rw_goal (cfg : rewrite_cfg) (rs : list rw_rule) : tactic unit := rs.mmap' $ λ r, do save_info r.pos, eq_lemmas ← get_rule_eqn_lemmas r, orelse' (do e ← to_expr' r.rule, rewrite_target e {symm := r.symm, ..cfg}) (eq_lemmas.mfirst $ λ n, do e ← mk_const n, rewrite_target e {symm := r.symm, ..cfg}) (eq_lemmas.empty) private meta def uses_hyp (e : expr) (h : expr) : bool := e.fold ff $ λ t _ r, r || to_bool (t = h) private meta def rw_hyp (cfg : rewrite_cfg) : list rw_rule → expr → tactic unit | [] hyp := skip | (r::rs) hyp := do save_info r.pos, eq_lemmas ← get_rule_eqn_lemmas r, orelse' (do e ← to_expr' r.rule, when (not (uses_hyp e hyp)) $ rewrite_hyp e hyp {symm := r.symm, ..cfg} >>= rw_hyp rs) (eq_lemmas.mfirst $ λ n, do e ← mk_const n, rewrite_hyp e hyp {symm := r.symm, ..cfg} >>= rw_hyp rs) (eq_lemmas.empty) private meta def rw_core (rs : parse rw_rules) (loca : parse location) (cfg : rewrite_cfg) : tactic unit := match loca with | loc.wildcard := loca.try_apply (rw_hyp cfg rs.rules) (rw_goal cfg rs.rules) | _ := loca.apply (rw_hyp cfg rs.rules) (rw_goal cfg rs.rules) end >> (returnopt rs.end_pos >>= save_info <|> skip) meta def rw' (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit := propagate_tags (rw_core q l cfg) meta def use' (l : parse pexpr_list_or_texpr) : tactic unit := tactic.use l end interactive end tactic namespace tactic.interactive open tactic.interactive interactive.types expr lean lean.parser tactic interactive meta def induction' (hp : parse cases_arg_p) (rec_name : parse using_ident) (ids : parse with_ident_list) (revert : parse $ (tk "generalizing" *> ident*)?) : tactic unit := do tactic.interactive.induction hp rec_name ids revert, all_goals `[try { dsimp only with leakage at * }] --meta def induction' (hp : parse cases_arg_p) (ids : parse with_ident_list) : tactic unit := --do tactic.interactive.induction hp none ids none, --all_goals `[ -- try {rw' (show mynat.zero = (0 : mynat), from rfl) at *}, -- try {change mynat.le with (≤) at *}] -- try {change @mynat.succ with (λ n, n + 1) at *, dsimp only at *}] meta def cases' (hp : parse cases_arg_p) (ids : parse with_ident_list) : tactic unit := do tactic.interactive.cases hp ids, all_goals `[try { dsimp only with leakage at * }] --meta def cases' : parse cases_arg_p → parse with_ident_list → tactic unit --| (none, p) ids := do -- e ← i_to_expr p, -- cases_core e ids, -- all_goals `[ -- try {rw' (show mynat.zero = (0 : mynat), from rfl) at *}, -- try {rw' (show mynat.le = (≤), from rfl) at *} -- ] --| (some h, p) ids := do -- x ← get_unused_name, -- generalize h () (p, x), -- hx ← get_local x, -- cases_core hx ids, -- all_goals `[ -- try {rw' (show mynat.zero = (0 : mynat), from rfl) at *}, -- try {rw' (show mynat.le = (≤), from rfl) at *}] -- next def is waiting on https://github.com/leanprover-community/mathlib/pull/1269 --meta def := symmetry' -- already there end tactic.interactive
4bc55b583c1b45b965e4606256642fd996bae92f
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/analysis/calculus/fderiv_analytic.lean
ce82fb6b3c0ca4a5bd40c80ee92b27b9873695a6
[ "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
7,200
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.calculus.deriv import analysis.analytic.basic import analysis.calculus.cont_diff /-! # Frechet derivatives of analytic functions. A function expressible as a power series at a point has a Frechet derivative there. Also the special case in terms of `deriv` when the domain is 1-dimensional. -/ open filter asymptotics open_locale ennreal variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] variables {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] variables {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F] section fderiv variables {p : formal_multilinear_series 𝕜 E F} {r : ℝ≥0∞} variables {f : E → F} {x : E} {s : set E} lemma has_fpower_series_at.has_strict_fderiv_at (h : has_fpower_series_at f p x) : has_strict_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p 1)) x := begin refine h.is_O_image_sub_norm_mul_norm_sub.trans_is_o (is_o.of_norm_right _), refine is_o_iff_exists_eq_mul.2 ⟨λ y, ∥y - (x, x)∥, _, eventually_eq.rfl⟩, refine (continuous_id.sub continuous_const).norm.tendsto' _ _ _, rw [_root_.id, sub_self, norm_zero] end lemma has_fpower_series_at.has_fderiv_at (h : has_fpower_series_at f p x) : has_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p 1)) x := h.has_strict_fderiv_at.has_fderiv_at lemma has_fpower_series_at.differentiable_at (h : has_fpower_series_at f p x) : differentiable_at 𝕜 f x := h.has_fderiv_at.differentiable_at lemma analytic_at.differentiable_at : analytic_at 𝕜 f x → differentiable_at 𝕜 f x | ⟨p, hp⟩ := hp.differentiable_at lemma analytic_at.differentiable_within_at (h : analytic_at 𝕜 f x) : differentiable_within_at 𝕜 f s x := h.differentiable_at.differentiable_within_at lemma has_fpower_series_at.fderiv_eq (h : has_fpower_series_at f p x) : fderiv 𝕜 f x = continuous_multilinear_curry_fin1 𝕜 E F (p 1) := h.has_fderiv_at.fderiv lemma has_fpower_series_on_ball.differentiable_on [complete_space F] (h : has_fpower_series_on_ball f p x r) : differentiable_on 𝕜 f (emetric.ball x r) := λ y hy, (h.analytic_at_of_mem hy).differentiable_within_at lemma analytic_on.differentiable_on (h : analytic_on 𝕜 f s) : differentiable_on 𝕜 f s := λ y hy, (h y hy).differentiable_within_at lemma has_fpower_series_on_ball.has_fderiv_at [complete_space F] (h : has_fpower_series_on_ball f p x r) {y : E} (hy : (∥y∥₊ : ℝ≥0∞) < r) : has_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p.change_origin y 1)) (x + y) := (h.change_origin hy).has_fpower_series_at.has_fderiv_at lemma has_fpower_series_on_ball.fderiv_eq [complete_space F] (h : has_fpower_series_on_ball f p x r) {y : E} (hy : (∥y∥₊ : ℝ≥0∞) < r) : fderiv 𝕜 f (x + y) = continuous_multilinear_curry_fin1 𝕜 E F (p.change_origin y 1) := (h.has_fderiv_at hy).fderiv /-- If a function has a power series on a ball, then so does its derivative. -/ lemma has_fpower_series_on_ball.fderiv [complete_space F] (h : has_fpower_series_on_ball f p x r) : has_fpower_series_on_ball (fderiv 𝕜 f) ((continuous_multilinear_curry_fin1 𝕜 E F : (E [×1]→L[𝕜] F) →L[𝕜] (E →L[𝕜] F)) .comp_formal_multilinear_series (p.change_origin_series 1)) x r := begin suffices A : has_fpower_series_on_ball (λ z, continuous_multilinear_curry_fin1 𝕜 E F (p.change_origin (z - x) 1)) ((continuous_multilinear_curry_fin1 𝕜 E F : (E [×1]→L[𝕜] F) →L[𝕜] (E →L[𝕜] F)) .comp_formal_multilinear_series (p.change_origin_series 1)) x r, { apply A.congr, assume z hz, dsimp, rw [← h.fderiv_eq, add_sub_cancel'_right], simpa only [edist_eq_coe_nnnorm_sub, emetric.mem_ball] using hz}, suffices B : has_fpower_series_on_ball (λ z, p.change_origin (z - x) 1) (p.change_origin_series 1) x r, from (continuous_multilinear_curry_fin1 𝕜 E F).to_continuous_linear_equiv .to_continuous_linear_map.comp_has_fpower_series_on_ball B, simpa using ((p.has_fpower_series_on_ball_change_origin 1 (h.r_pos.trans_le h.r_le)).mono h.r_pos h.r_le).comp_sub x, end /-- If a function is analytic on a set `s`, so is its Fréchet derivative. -/ lemma analytic_on.fderiv [complete_space F] (h : analytic_on 𝕜 f s) : analytic_on 𝕜 (fderiv 𝕜 f) s := begin assume y hy, rcases h y hy with ⟨p, r, hp⟩, exact hp.fderiv.analytic_at, end /-- If a function is analytic on a set `s`, so are its successive Fréchet derivative. -/ lemma analytic_on.iterated_fderiv [complete_space F] (h : analytic_on 𝕜 f s) (n : ℕ) : analytic_on 𝕜 (iterated_fderiv 𝕜 n f) s := begin induction n with n IH, { rw iterated_fderiv_zero_eq_comp, exact ((continuous_multilinear_curry_fin0 𝕜 E F).symm : F →L[𝕜] (E [×0]→L[𝕜] F)) .comp_analytic_on h }, { rw iterated_fderiv_succ_eq_comp_left, apply (continuous_multilinear_curry_left_equiv 𝕜 (λ (i : fin (n + 1)), E) F) .to_continuous_linear_equiv.to_continuous_linear_map.comp_analytic_on, exact IH.fderiv } end /-- An analytic function is infinitely differentiable. -/ lemma analytic_on.cont_diff_on [complete_space F] (h : analytic_on 𝕜 f s) {n : with_top ℕ} : cont_diff_on 𝕜 n f s := begin let t := {x | analytic_at 𝕜 f x}, suffices : cont_diff_on 𝕜 n f t, from this.mono h, have H : analytic_on 𝕜 f t := λ x hx, hx, have t_open : is_open t := is_open_analytic_at 𝕜 f, apply cont_diff_on_of_continuous_on_differentiable_on, { assume m hm, apply (H.iterated_fderiv m).continuous_on.congr, assume x hx, exact iterated_fderiv_within_of_is_open _ t_open hx }, { assume m hm, apply (H.iterated_fderiv m).differentiable_on.congr, assume x hx, exact iterated_fderiv_within_of_is_open _ t_open hx } end end fderiv section deriv variables {p : formal_multilinear_series 𝕜 𝕜 F} {r : ℝ≥0∞} variables {f : 𝕜 → F} {x : 𝕜} {s : set 𝕜} protected lemma has_fpower_series_at.has_strict_deriv_at (h : has_fpower_series_at f p x) : has_strict_deriv_at f (p 1 (λ _, 1)) x := h.has_strict_fderiv_at.has_strict_deriv_at protected lemma has_fpower_series_at.has_deriv_at (h : has_fpower_series_at f p x) : has_deriv_at f (p 1 (λ _, 1)) x := h.has_strict_deriv_at.has_deriv_at protected lemma has_fpower_series_at.deriv (h : has_fpower_series_at f p x) : deriv f x = p 1 (λ _, 1) := h.has_deriv_at.deriv /-- If a function is analytic on a set `s`, so is its derivative. -/ lemma analytic_on.deriv [complete_space F] (h : analytic_on 𝕜 f s) : analytic_on 𝕜 (deriv f) s := (continuous_linear_map.apply 𝕜 F (1 : 𝕜)).comp_analytic_on h.fderiv /-- If a function is analytic on a set `s`, so are its successive derivatives. -/ lemma analytic_on.iterated_deriv [complete_space F] (h : analytic_on 𝕜 f s) (n : ℕ) : analytic_on 𝕜 (deriv^[n] f) s := begin induction n with n IH, { exact h }, { simpa only [function.iterate_succ', function.comp_app] using IH.deriv } end end deriv
5e349faeb6f877b06601aa0b50fd639743ef2800
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/nat/cast_field.lean
756844efebfc6ab7371ec90e600788c6f74c4c3f
[ "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
1,904
lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Yaël Dillies, Patrick Stevens -/ import algebra.order.field import data.nat.cast /-! # Cast of naturals into fields This file concerns the canonical homomorphism `ℕ → F`, where `F` is a field. ## Main results * `nat.cast_div`: if `n` divides `m`, then `↑(m / n) = ↑m / ↑n` * `nat.cast_div_le`: in all cases, `↑(m / n) ≤ ↑m / ↑ n` -/ namespace nat variables {α : Type*} @[simp] theorem cast_div [field α] {m n : ℕ} (n_dvd : n ∣ m) (n_nonzero : (n : α) ≠ 0) : ((m / n : ℕ) : α) = m / n := begin rcases n_dvd with ⟨k, rfl⟩, have : n ≠ 0, {rintro rfl, simpa using n_nonzero}, rw [nat.mul_div_cancel_left _ this.bot_lt, cast_mul, mul_div_cancel_left _ n_nonzero], end section linear_ordered_semifield variables [linear_ordered_semifield α] /-- Natural division is always less than division in the field. -/ lemma cast_div_le {m n : ℕ} : ((m / n : ℕ) : α) ≤ m / n := begin cases n, { rw [cast_zero, div_zero, nat.div_zero, cast_zero] }, rwa [le_div_iff, ←nat.cast_mul], exact nat.cast_le.2 (nat.div_mul_le_self m n.succ), { exact nat.cast_pos.2 n.succ_pos } end lemma inv_pos_of_nat {n : ℕ} : 0 < ((n : α) + 1)⁻¹ := inv_pos.2 $ add_pos_of_nonneg_of_pos n.cast_nonneg zero_lt_one lemma one_div_pos_of_nat {n : ℕ} : 0 < 1 / ((n : α) + 1) := by { rw one_div, exact inv_pos_of_nat } lemma one_div_le_one_div {n m : ℕ} (h : n ≤ m) : 1 / ((m : α) + 1) ≤ 1 / ((n : α) + 1) := by { refine one_div_le_one_div_of_le _ _, exact nat.cast_add_one_pos _, simpa } lemma one_div_lt_one_div {n m : ℕ} (h : n < m) : 1 / ((m : α) + 1) < 1 / ((n : α) + 1) := by { refine one_div_lt_one_div_of_lt _ _, exact nat.cast_add_one_pos _, simpa } end linear_ordered_semifield end nat
ab7706ce8cefc737e5ef966aacc94bd2cf9439cd
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/protected_test.lean
cf50ccde1804369a725b97bee6f45e23ecd5626c
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
298
lean
namespace nat check induction_on -- ERROR check rec_on -- ERROR check nat.induction_on check less_than_or_equal.rec_on -- OK check nat.less_than_or_equal.rec_on namespace le check rec_on -- ERROR check less_than_or_equal.rec_on end le end nat
a5aed87fc9c1cf07bb1267144a9c7762c4adb8b9
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/normed_space/add_torsor_bases.lean
e41165992a954136aafaebaac3e833e7402f9754
[ "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,118
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import analysis.normed_space.finite_dimension import analysis.calculus.affine_map import analysis.convex.combination import linear_algebra.affine_space.basis /-! # Bases in normed affine spaces. This file contains results about bases in normed affine spaces. ## Main definitions: * `continuous_barycentric_coord` * `is_open_map_barycentric_coord` * `affine_basis.interior_convex_hull` * `exists_subset_affine_independent_span_eq_top_of_open` * `interior_convex_hull_nonempty_iff_affine_span_eq_top` -/ section barycentric variables {ι 𝕜 E P : Type*} [nontrivially_normed_field 𝕜] [complete_space 𝕜] variables [normed_add_comm_group E] [normed_space 𝕜 E] variables [metric_space P] [normed_add_torsor E P] include E lemma is_open_map_barycentric_coord [nontrivial ι] (b : affine_basis ι 𝕜 P) (i : ι) : is_open_map (b.coord i) := affine_map.is_open_map_linear_iff.mp $ (b.coord i).linear.is_open_map_of_finite_dimensional $ (b.coord i).surjective_iff_linear_surjective.mpr (b.surjective_coord i) variables [finite_dimensional 𝕜 E] (b : affine_basis ι 𝕜 P) @[continuity] lemma continuous_barycentric_coord (i : ι) : continuous (b.coord i) := (b.coord i).continuous_of_finite_dimensional lemma smooth_barycentric_coord (b : affine_basis ι 𝕜 E) (i : ι) : cont_diff 𝕜 ⊤ (b.coord i) := (⟨b.coord i, continuous_barycentric_coord b i⟩ : E →A[𝕜] 𝕜).cont_diff end barycentric open set /-- Given a finite-dimensional normed real vector space, the interior of the convex hull of an affine basis is the set of points whose barycentric coordinates are strictly positive with respect to this basis. TODO Restate this result for affine spaces (instead of vector spaces) once the definition of convexity is generalised to this setting. -/ lemma affine_basis.interior_convex_hull {ι E : Type*} [finite ι] [normed_add_comm_group E] [normed_space ℝ E] (b : affine_basis ι ℝ E) : interior (convex_hull ℝ (range b.points)) = {x | ∀ i, 0 < b.coord i x} := begin casesI subsingleton_or_nontrivial ι, { -- The zero-dimensional case. have : range (b.points) = univ, from affine_subspace.eq_univ_of_subsingleton_span_eq_top (subsingleton_range _) b.tot, simp [this] }, { -- The positive-dimensional case. haveI : finite_dimensional ℝ E := b.finite_dimensional, have : convex_hull ℝ (range b.points) = ⋂ i, (b.coord i)⁻¹' Ici 0, { rw [convex_hull_affine_basis_eq_nonneg_barycentric b, set_of_forall], refl }, ext, simp only [this, interior_Inter, ← is_open_map.preimage_interior_eq_interior_preimage (is_open_map_barycentric_coord b _) (continuous_barycentric_coord b _), interior_Ici, mem_Inter, mem_set_of_eq, mem_Ioi, mem_preimage], }, end variables {V P : Type*} [normed_add_comm_group V] [normed_space ℝ V] [metric_space P] [normed_add_torsor V P] include V open affine_map /-- Given a set `s` of affine-independent points belonging to an open set `u`, we may extend `s` to an affine basis, all of whose elements belong to `u`. -/ lemma is_open.exists_between_affine_independent_span_eq_top {s u : set P} (hu : is_open u) (hsu : s ⊆ u) (hne : s.nonempty) (h : affine_independent ℝ (coe : s → P)) : ∃ t : set P, s ⊆ t ∧ t ⊆ u ∧ affine_independent ℝ (coe : t → P) ∧ affine_span ℝ t = ⊤ := begin obtain ⟨q, hq⟩ := hne, obtain ⟨ε, ε0, hεu⟩ := metric.nhds_basis_closed_ball.mem_iff.1 (hu.mem_nhds $ hsu hq), obtain ⟨t, ht₁, ht₂, ht₃⟩ := exists_subset_affine_independent_affine_span_eq_top h, let f : P → P := λ y, line_map q y (ε / dist y q), have hf : ∀ y, f y ∈ u, { refine λ y, hεu _, simp only [f], rw [metric.mem_closed_ball, line_map_apply, dist_vadd_left, norm_smul, real.norm_eq_abs, dist_eq_norm_vsub V y q, abs_div, abs_of_pos ε0, abs_of_nonneg (norm_nonneg _), div_mul_comm], exact mul_le_of_le_one_left ε0.le (div_self_le_one _) }, have hεyq : ∀ y ∉ s, ε / dist y q ≠ 0, from λ y hy, div_ne_zero ε0.ne' (dist_ne_zero.2 (ne_of_mem_of_not_mem hq hy).symm), classical, let w : t → ℝˣ := λ p, if hp : (p : P) ∈ s then 1 else units.mk0 _ (hεyq ↑p hp), refine ⟨set.range (λ (p : t), line_map q p (w p : ℝ)), _, _, _, _⟩, { intros p hp, use ⟨p, ht₁ hp⟩, simp [w, hp], }, { rintros y ⟨⟨p, hp⟩, rfl⟩, by_cases hps : p ∈ s; simp only [w, hps, line_map_apply_one, units.coe_mk0, dif_neg, dif_pos, not_false_iff, units.coe_one, subtype.coe_mk]; [exact hsu hps, exact hf p], }, { exact (ht₂.units_line_map ⟨q, ht₁ hq⟩ w).range, }, { rw [affine_span_eq_affine_span_line_map_units (ht₁ hq) w, ht₃], }, end lemma is_open.exists_subset_affine_independent_span_eq_top {u : set P} (hu : is_open u) (hne : u.nonempty) : ∃ s ⊆ u, affine_independent ℝ (coe : s → P) ∧ affine_span ℝ s = ⊤ := begin rcases hne with ⟨x, hx⟩, rcases hu.exists_between_affine_independent_span_eq_top (singleton_subset_iff.mpr hx) (singleton_nonempty _) (affine_independent_of_subsingleton _ _) with ⟨s, -, hsu, hs⟩, exact ⟨s, hsu, hs⟩ end /-- The affine span of a nonempty open set is `⊤`. -/ lemma is_open.affine_span_eq_top {u : set P} (hu : is_open u) (hne : u.nonempty) : affine_span ℝ u = ⊤ := let ⟨s, hsu, hs, hs'⟩ := hu.exists_subset_affine_independent_span_eq_top hne in top_unique $ hs' ▸ affine_span_mono _ hsu lemma affine_span_eq_top_of_nonempty_interior {s : set V} (hs : (interior $ convex_hull ℝ s).nonempty) : affine_span ℝ s = ⊤ := top_unique $ is_open_interior.affine_span_eq_top hs ▸ (affine_span_mono _ interior_subset).trans_eq (affine_span_convex_hull _) lemma affine_basis.centroid_mem_interior_convex_hull {ι} [fintype ι] (b : affine_basis ι ℝ V) : finset.univ.centroid ℝ b.points ∈ interior (convex_hull ℝ (range b.points)) := begin haveI := b.nonempty, simp only [b.interior_convex_hull, mem_set_of_eq, b.coord_apply_centroid (finset.mem_univ _), inv_pos, nat.cast_pos, finset.card_pos, finset.univ_nonempty, forall_true_iff] end lemma interior_convex_hull_nonempty_iff_affine_span_eq_top [finite_dimensional ℝ V] {s : set V} : (interior (convex_hull ℝ s)).nonempty ↔ affine_span ℝ s = ⊤ := begin refine ⟨affine_span_eq_top_of_nonempty_interior, λ h, _⟩, obtain ⟨t, hts, b, hb⟩ := affine_basis.exists_affine_subbasis h, suffices : (interior (convex_hull ℝ (range b.points))).nonempty, { rw [hb, subtype.range_coe_subtype, set_of_mem_eq] at this, refine this.mono _, mono* }, lift t to finset V using b.finite_set, exact ⟨_, b.centroid_mem_interior_convex_hull⟩ end lemma convex.interior_nonempty_iff_affine_span_eq_top [finite_dimensional ℝ V] {s : set V} (hs : convex ℝ s) : (interior s).nonempty ↔ affine_span ℝ s = ⊤ := by rw [← interior_convex_hull_nonempty_iff_affine_span_eq_top, hs.convex_hull_eq]
514d03e960f6fb4134f3bdce3d656ad268a3adce
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/sizeof3.lean
082352af8ada6424c3f0a568d5f49fe3abff4667
[ "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
495
lean
mutual inductive AList (α β : Type u) | nil | cons (a : α) (t : BList α β) inductive BList (α β : Type u) | cons (b : β) (t : AList α β) end #print AList.nil.sizeOf_spec #print AList.cons.sizeOf_spec #print BList.cons.sizeOf_spec mutual inductive Foo (α : Type u) | mk (cs : AList (Foo α) (Boo α)) inductive Boo (α : Type u) | mk (a : α) (cs : BList (Foo α) (Boo α)) end #print Boo.mk.sizeOf_spec #print Foo._sizeOf_4_eq #print Foo._sizeOf_3_eq
1db7b2186b7e4759ae6c2736300832374262ac17
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/interactive.lean
e64e4e054e37dbb64f15e22972e756006fd88b00
[]
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
32,920
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jannis Limperg -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.meta.tactic import Mathlib.Lean3Lib.init.meta.type_context import Mathlib.Lean3Lib.init.meta.rewrite_tactic import Mathlib.Lean3Lib.init.meta.simp_tactic import Mathlib.Lean3Lib.init.meta.smt.congruence_closure import Mathlib.Lean3Lib.init.control.combinators import Mathlib.Lean3Lib.init.meta.interactive_base import Mathlib.Lean3Lib.init.meta.derive import Mathlib.Lean3Lib.init.meta.match_tactic import Mathlib.Lean3Lib.init.meta.congr_tactic import Mathlib.Lean3Lib.init.meta.case_tag universes l u v namespace Mathlib namespace tactic /- allows metavars -/ /- allow metavars and no subgoals -/ /- doesn't allows metavars -/ /- Auxiliary version of i_to_expr for apply-like tactics. This is a workaround for comment https://github.com/leanprover/lean/issues/1342#issuecomment-307912291 at issue #1342. In interactive mode, given a tactic apply f we want the apply tactic to create all metavariables. The following definition will return `@f` for `f`. That is, it will **not** create metavariables for implicit arguments. Before we added `i_to_expr_for_apply`, the tactic apply le_antisymm would first elaborate `le_antisymm`, and create @le_antisymm ?m_1 ?m_2 ?m_3 ?m_4 The type class resolution problem ?m_2 : weak_order ?m_1 by the elaborator since ?m_1 is not assigned yet, and the problem is discarded. Then, we would invoke `apply_core`, which would create two new metavariables for the explicit arguments, and try to unify the resulting type with the current target. After the unification, the metavariables ?m_1, ?m_3 and ?m_4 are assigned, but we lost the information about the pending type class resolution problem. With `i_to_expr_for_apply`, `le_antisymm` is elaborate into `@le_antisymm`, the apply_core tactic creates all metavariables, and solves the ones that can be solved by type class resolution. Another possible fix: we modify the elaborator to return pending type class resolution problems, and store them in the tactic_state. -/ namespace interactive /-- itactic: parse a nested "interactive" tactic. That is, parse `{` tactic `}` -/ /-- If the current goal is a Pi/forall `∀ x : t, u` (resp. `let x := t in u`) then `intro` puts `x : t` (resp. `x := t`) in the local context. The new subgoal target is `u`. If the goal is an arrow `t → u`, then it puts `h : t` in the local context and the new goal target is `u`. If the goal is neither a Pi/forall nor begins with a let binder, the tactic `intro` applies the tactic `whnf` until an introduction can be applied or the goal is not head reducible. In the latter case, the tactic fails. -/ /-- Similar to `intro` tactic. The tactic `intros` will keep introducing new hypotheses until the goal target is not a Pi/forall or let binder. The variant `intros h₁ ... hₙ` introduces `n` new hypotheses using the given identifiers to name them. -/ /-- The tactic `introv` allows the user to automatically introduce the variables of a theorem and explicitly name the hypotheses involved. The given names are used to name non-dependent hypotheses. Examples: ``` example : ∀ a b : nat, a = b → b = a := begin introv h, exact h.symm end ``` The state after `introv h` is ``` a b : ℕ, h : a = b ⊢ b = a ``` ``` example : ∀ a b : nat, a = b → ∀ c, b = c → a = c := begin introv h₁ h₂, exact h₁.trans h₂ end ``` The state after `introv h₁ h₂` is ``` a b : ℕ, h₁ : a = b, c : ℕ, h₂ : b = c ⊢ a = c ``` -/ /-- Parse a current name and new name for `rename`. -/ /-- Parse the arguments of `rename`. -/ /-- Rename one or more local hypotheses. The renamings are given as follows: ``` rename x y -- rename x to y rename x → y -- ditto rename [x y, a b] -- rename x to y and a to b rename [x → y, a → b] -- ditto ``` Note that if there are multiple hypotheses called `x` in the context, then `rename x y` will rename *all* of them. If you want to rename only one, use `dedup` first. -/ /-- The `apply` tactic tries to match the current goal against the conclusion of the type of term. The argument term should be a term well-formed in the local context of the main goal. If it succeeds, then the tactic returns as many subgoals as the number of premises that have not been fixed by type inference or type class resolution. Non-dependent premises are added before dependent ones. The `apply` tactic uses higher-order pattern matching, type class resolution, and first-order unification with dependent types. -/ /-- Similar to the `apply` tactic, but does not reorder goals. -/ /-- Similar to the `apply` tactic, but only creates subgoals for non-dependent premises that have not been fixed by type inference or type class resolution. -/ /-- Similar to the `apply` tactic, but allows the user to provide a `apply_cfg` configuration object. -/ /-- Similar to the `apply` tactic, but uses matching instead of unification. `apply_match t` is equivalent to `apply_with t {unify := ff}` -/ /-- This tactic tries to close the main goal `... ⊢ t` by generating a term of type `t` using type class resolution. -/ /-- This tactic behaves like `exact`, but with a big difference: the user can put underscores `_` in the expression as placeholders for holes that need to be filled, and `refine` will generate as many subgoals as there are holes. Note that some holes may be implicit. The type of each hole must either be synthesized by the system or declared by an explicit type ascription like `(_ : nat → Prop)`. -/ /-- This tactic looks in the local context for a hypothesis whose type is equal to the goal target. If it finds one, it uses it to prove the goal, and otherwise it fails. -/ /-- Try to apply `assumption` to all goals. -/ /-- `change u` replaces the target `t` of the main goal to `u` provided that `t` is well formed with respect to the local context of the main goal and `t` and `u` are definitionally equal. `change u at h` will change a local hypothesis to `u`. `change t with u at h1 h2 ...` will replace `t` with `u` in all the supplied hypotheses (or `*`), or in the goal if no `at` clause is specified, provided that `t` and `u` are definitionally equal. -/ /-- This tactic provides an exact proof term to solve the main goal. If `t` is the goal and `p` is a term of type `u` then `exact p` succeeds if and only if `t` and `u` can be unified. -/ /-- Like `exact`, but takes a list of terms and checks that all goals are discharged after the tactic. -/ /-- A synonym for `exact` that allows writing `have/suffices/show ..., from ...` in tactic mode. -/ /-- `revert h₁ ... hₙ` applies to any goal with hypotheses `h₁` ... `hₙ`. It moves the hypotheses and their dependencies to the target of the goal. This tactic is the inverse of `intro`. -/ /- Version of to_expr that tries to bypass the elaborator if `p` is just a constant or local constant. This is not an optimization, by skipping the elaborator we make sure that no unwanted resolution is used. Example: the elaborator will force any unassigned ?A that must have be an instance of (has_one ?A) to nat. Remark: another benefit is that auxiliary temporary metavariables do not appear in error messages. -/ -- accepts the same content as `pexpr_list_or_texpr`, but with correct goal info pos annotations /-- `rewrite e` applies identity `e` as a rewrite rule to the target of the main goal. If `e` is preceded by left arrow (`←` or `<-`), the rewrite is applied in the reverse direction. If `e` is a defined constant, then the equational lemmas associated with `e` are used. This provides a convenient way to unfold `e`. `rewrite [e₁, ..., eₙ]` applies the given rules sequentially. `rewrite e at l` rewrites `e` at location(s) `l`, where `l` is either `*` or a list of hypotheses in the local context. In the latter case, a turnstile `⊢` or `|-` can also be used, to signify the target of the goal. -/ /-- An abbreviation for `rewrite`. -/ /-- `rewrite` followed by `assumption`. -/ /-- A variant of `rewrite` that uses the unifier more aggressively, unfolding semireducible definitions. -/ /-- An abbreviation for `erewrite`. -/ /-- Returns the unique names of all hypotheses (local constants) in the context. -/ /-- Returns all hypotheses (local constants) from the context except those whose unique names are in `hyp_uids`. -/ /-- Apply `t` to the main goal and revert any new hypothesis in the generated goals. If `t` is a supported tactic or chain of supported tactics (e.g. `induction`, `cases`, `apply`, `constructor`), the generated goals are also tagged with case tags. You can then use `case` to focus such tagged goals. Two typical uses of `with_cases`: 1. Applying a custom eliminator: ``` lemma my_nat_rec : ∀ n {P : ℕ → Prop} (zero : P 0) (succ : ∀ n, P n → P (n + 1)), P n := ... example (n : ℕ) : n = n := begin with_cases { apply my_nat_rec n }, case zero { refl }, case succ : m ih { refl } end ``` 2. Enabling the use of `case` after a chain of case-splitting tactics: ``` example (n m : ℕ) : unit := begin with_cases { cases n; induction m }, case nat.zero nat.zero { exact () }, case nat.zero nat.succ : k { exact () }, case nat.succ nat.zero : i { exact () }, case nat.succ nat.succ : k i ih_i { exact () } end ``` -/ /-- `generalize : e = x` replaces all occurrences of `e` in the target with a new hypothesis `x` of the same type. `generalize h : e = x` in addition registers the hypothesis `h : e = x`. -/ /-- Updates the tags of new subgoals produced by `cases` or `induction`. `in_tag` is the initial tag, i.e. the tag of the goal on which `cases`/`induction` was applied. `rs` should contain, for each subgoal, the constructor name associated with that goal and the hypotheses that were introduced. -/ /-- Assuming `x` is a variable in the local context with an inductive type, `induction x` applies induction on `x` to the main goal, producing one goal for each constructor of the inductive type, in which the target is replaced by a general instance of that constructor and an inductive hypothesis is added for each recursive argument to the constructor. If the type of an element in the local context depends on `x`, that element is reverted and reintroduced afterward, so that the inductive hypothesis incorporates that hypothesis as well. For example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `induction n` produces one goal with hypothesis `h : P 0` and target `Q 0`, and one goal with hypotheses `h : P (nat.succ a)` and `ih₁ : P a → Q a` and target `Q (nat.succ a)`. Here the names `a` and `ih₁` ire chosen automatically. `induction e`, where `e` is an expression instead of a variable, generalizes `e` in the goal, and then performs induction on the resulting variable. `induction e with y₁ ... yₙ`, where `e` is a variable or an expression, specifies that the sequence of names `y₁ ... yₙ` should be used for the arguments to the constructors and inductive hypotheses, including implicit arguments. If the list does not include enough names for all of the arguments, additional names are generated automatically. If too many names are given, the extra ones are ignored. Underscores can be used in the list, in which case the corresponding names are generated automatically. Note that for long sequences of names, the `case` tactic provides a more convenient naming mechanism. `induction e using r` allows the user to specify the principle of induction that should be used. Here `r` should be a theorem whose result type must be of the form `C t`, where `C` is a bound variable and `t` is a (possibly empty) sequence of bound variables `induction e generalizing z₁ ... zₙ`, where `z₁ ... zₙ` are variables in the local context, generalizes over `z₁ ... zₙ` before applying the induction but then introduces them in each goal. In other words, the net effect is that each inductive hypothesis is generalized. `induction h : t` will introduce an equality of the form `h : t = C x y`, asserting that the input term is equal to the current constructor case, to the context. -/ /-- Focuses on a goal ('case') generated by `induction`, `cases` or `with_cases`. The goal is selected by giving one or more names which must match exactly one goal. A goal is matched if the given names are a suffix of its goal tag. Additionally, each name in the sequence can be abbreviated to a suffix of the corresponding name in the goal tag. Thus, a goal with tag ``` nat.zero, list.nil ``` can be selected with any of these invocations (among others): ``` case nat.zero list.nil {...} case nat.zero nil {...} case zero nil {...} case nil {...} ``` Additionally, the form ``` case C : N₀ ... Nₙ {...} ``` can be used to rename hypotheses introduced by the preceding `cases`/`induction`/`with_cases`, using the names `Nᵢ`. For example: ``` example (xs : list ℕ) : xs = xs := begin induction xs, case nil { reflexivity }, case cons : x xs ih { -- x : ℕ, xs : list ℕ, ih : xs = xs reflexivity } end ``` Note that this renaming functionality only work reliably *directly after* an `induction`/`cases`/`with_cases`. If you need to perform additional work after an `induction` or `cases` (e.g. introduce hypotheses in all goals), use `with_cases`. -/ /- TODO `case` could be generalised to work with zero names as well. The form case : x y z { ... } would select the first goal (or the first goal with a case tag), renaming hypotheses to `x, y, z`. The renaming functionality would be available only if the goal has a case tag. -/ /-- Assuming `x` is a variable in the local context with an inductive type, `destruct x` splits the main goal, producing one goal for each constructor of the inductive type, in which `x` is assumed to be a general instance of that constructor. In contrast to `cases`, the local context is unchanged, i.e. no elements are reverted or introduced. For example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `destruct n` produces one goal with target `n = 0 → Q n`, and one goal with target `∀ (a : ℕ), (λ (w : ℕ), n = w → Q n) (nat.succ a)`. Here the name `a` is chosen automatically. -/ /-- Assuming `x` is a variable in the local context with an inductive type, `cases x` splits the main goal, producing one goal for each constructor of the inductive type, in which the target is replaced by a general instance of that constructor. If the type of an element in the local context depends on `x`, that element is reverted and reintroduced afterward, so that the case split affects that hypothesis as well. For example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `cases n` produces one goal with hypothesis `h : P 0` and target `Q 0`, and one goal with hypothesis `h : P (nat.succ a)` and target `Q (nat.succ a)`. Here the name `a` is chosen automatically. `cases e`, where `e` is an expression instead of a variable, generalizes `e` in the goal, and then cases on the resulting variable. `cases e with y₁ ... yₙ`, where `e` is a variable or an expression, specifies that the sequence of names `y₁ ... yₙ` should be used for the arguments to the constructors, including implicit arguments. If the list does not include enough names for all of the arguments, additional names are generated automatically. If too many names are given, the extra ones are ignored. Underscores can be used in the list, in which case the corresponding names are generated automatically. `cases h : e`, where `e` is a variable or an expression, performs cases on `e` as above, but also adds a hypothesis `h : e = ...` to each hypothesis, where `...` is the constructor instance for that particular case. -/ /-- `cases_matching p` applies the `cases` tactic to a hypothesis `h : type` if `type` matches the pattern `p`. `cases_matching [p_1, ..., p_n]` applies the `cases` tactic to a hypothesis `h : type` if `type` matches one of the given patterns. `cases_matching* p` more efficient and compact version of `focus1 { repeat { cases_matching p } }`. It is more efficient because the pattern is compiled once. Example: The following tactic destructs all conjunctions and disjunctions in the current goal. ``` cases_matching* [_ ∨ _, _ ∧ _] ``` -/ /-- Shorthand for `cases_matching` -/ /-- `cases_type I` applies the `cases` tactic to a hypothesis `h : (I ...)` `cases_type I_1 ... I_n` applies the `cases` tactic to a hypothesis `h : (I_1 ...)` or ... or `h : (I_n ...)` `cases_type* I` is shorthand for `focus1 { repeat { cases_type I } }` `cases_type! I` only applies `cases` if the number of resulting subgoals is <= 1. Example: The following tactic destructs all conjunctions and disjunctions in the current goal. ``` cases_type* or and ``` -/ /-- Tries to solve the current goal using a canonical proof of `true`, or the `reflexivity` tactic, or the `contradiction` tactic. -/ /-- Closes the main goal using `sorry`. -/ /-- Closes the main goal using `sorry`. -/ /-- The contradiction tactic attempts to find in the current local context a hypothesis that is equivalent to an empty inductive type (e.g. `false`), a hypothesis of the form `c_1 ... = c_2 ...` where `c_1` and `c_2` are distinct constructors, or two contradictory hypotheses. -/ /-- `iterate { t }` repeatedly applies tactic `t` until `t` fails. `iterate { t }` always succeeds. `iterate n { t }` applies `t` `n` times. -/ /-- `repeat { t }` applies `t` to each goal. If the application succeeds, the tactic is applied recursively to all the generated subgoals until it eventually fails. The recursion stops in a subgoal when the tactic has failed to make progress. The tactic `repeat { t }` never fails. -/ /-- `try { t }` tries to apply tactic `t`, but succeeds whether or not `t` succeeds. -/ /-- A do-nothing tactic that always succeeds. -/ /-- `solve1 { t }` applies the tactic `t` to the main goal and fails if it is not solved. -/ /-- `abstract id { t }` tries to use tactic `t` to solve the main goal. If it succeeds, it abstracts the goal as an independent definition or theorem with name `id`. If `id` is omitted, a name is generated automatically. -/ /-- `all_goals { t }` applies the tactic `t` to every goal, and succeeds if each application succeeds. -/ /-- `any_goals { t }` applies the tactic `t` to every goal, and succeeds if at least one application succeeds. -/ /-- `focus { t }` temporarily hides all goals other than the first, applies `t`, and then restores the other goals. It fails if there are no goals. -/ /-- Assuming the target of the goal is a Pi or a let, `assume h : t` unifies the type of the binder with `t` and introduces it with name `h`, just like `intro h`. If `h` is absent, the tactic uses the name `this`. If `t` is omitted, it will be inferred. `assume (h₁ : t₁) ... (hₙ : tₙ)` introduces multiple hypotheses. Any of the types may be omitted, but the names must be present. -/ /-- `have h : t := p` adds the hypothesis `h : t` to the current goal if `p` a term of type `t`. If `t` is omitted, it will be inferred. `have h : t` adds the hypothesis `h : t` to the current goal and opens a new subgoal with target `t`. The new subgoal becomes the main goal. If `t` is omitted, it will be replaced by a fresh metavariable. If `h` is omitted, the name `this` is used. -/ /-- `let h : t := p` adds the hypothesis `h : t := p` to the current goal if `p` a term of type `t`. If `t` is omitted, it will be inferred. `let h : t` adds the hypothesis `h : t := ?M` to the current goal and opens a new subgoal `?M : t`. The new subgoal becomes the main goal. If `t` is omitted, it will be replaced by a fresh metavariable. If `h` is omitted, the name `this` is used. -/ /-- `suffices h : t` is the same as `have h : t, tactic.swap`. In other words, it adds the hypothesis `h : t` to the current goal and opens a new subgoal with target `t`. -/ /-- This tactic displays the current state in the tracing buffer. -/ /-- `trace a` displays `a` in the tracing buffer. -/ /-- `existsi e` will instantiate an existential quantifier in the target with `e` and leave the instantiated body as the new target. More generally, it applies to any inductive type with one constructor and at least two arguments, applying the constructor with `e` as the first argument and leaving the remaining arguments as goals. `existsi [e₁, ..., eₙ]` iteratively does the same for each expression in the list. -/ /-- This tactic applies to a goal such that its conclusion is an inductive type (say `I`). It tries to apply each constructor of `I` until it succeeds. -/ /-- Similar to `constructor`, but only non-dependent premises are added as new goals. -/ /-- Applies the first constructor when the type of the target is an inductive data type with two constructors. -/ /-- Applies the second constructor when the type of the target is an inductive data type with two constructors. -/ /-- Applies the constructor when the type of the target is an inductive data type with one constructor. -/ /-- Replaces the target of the main goal by `false`. -/ /-- The `injection` tactic is based on the fact that constructors of inductive data types are injections. That means that if `c` is a constructor of an inductive datatype, and if `(c t₁)` and `(c t₂)` are two terms that are equal then `t₁` and `t₂` are equal too. If `q` is a proof of a statement of conclusion `t₁ = t₂`, then injection applies injectivity to derive the equality of all arguments of `t₁` and `t₂` placed in the same positions. For example, from `(a::b) = (c::d)` we derive `a=c` and `b=d`. To use this tactic `t₁` and `t₂` should be constructor applications of the same constructor. Given `h : a::b = c::d`, the tactic `injection h` adds two new hypothesis with types `a = c` and `b = d` to the main goal. The tactic `injection h with h₁ h₂` uses the names `h₁` and `h₂` to name the new hypotheses. -/ /-- `injections with h₁ ... hₙ` iteratively applies `injection` to hypotheses using the names `h₁ ... hₙ`. -/ end interactive /-- Decode a list of `simp_arg_type` into lists for each type. This is a backwards-compatibility version of `decode_simp_arg_list_with_symm`. This version fails when an argument of the form `simp_arg_type.symm_expr` is included, so that `simp`-like tactics that do not (yet) support backwards rewriting should properly report an error but function normally on other inputs. -/ /-- Decode a list of `simp_arg_type` into lists for each type. This is the newer version of `decode_simp_arg_list`, and has a new name for backwards compatibility. This version indicates the direction of a `simp` lemma by including a `bool` with the `pexpr`. -/ namespace interactive /-- The `simp` tactic uses lemmas and hypotheses to simplify the main goal target or non-dependent hypotheses. It has many variants. `simp` simplifies the main goal target using lemmas tagged with the attribute `[simp]`. `simp [h₁ h₂ ... hₙ]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and the given `hᵢ`'s, where the `hᵢ`'s are expressions. If `hᵢ` is preceded by left arrow (`←` or `<-`), the simplification is performed in the reverse direction. If an `hᵢ` is a defined constant `f`, then the equational lemmas associated with `f` are used. This provides a convenient way to unfold `f`. `simp [*]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and all hypotheses. `simp *` is a shorthand for `simp [*]`. `simp only [h₁ h₂ ... hₙ]` is like `simp [h₁ h₂ ... hₙ]` but does not use `[simp]` lemmas `simp [-id_1, ... -id_n]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]`, but removes the ones named `idᵢ`. `simp at h₁ h₂ ... hₙ` simplifies the non-dependent hypotheses `h₁ : T₁` ... `hₙ : Tₙ`. The tactic fails if the target or another hypothesis depends on one of them. The token `⊢` or `|-` can be added to the list to include the target. `simp at *` simplifies all the hypotheses and the target. `simp * at *` simplifies target and all (non-dependent propositional) hypotheses using the other hypotheses. `simp with attr₁ ... attrₙ` simplifies the main goal target using the lemmas tagged with any of the attributes `[attr₁]`, ..., `[attrₙ]` or `[simp]`. -/ /-- Just construct the simp set and trace it. Used for debugging. -/ /-- `simp_intros h₁ h₂ ... hₙ` is similar to `intros h₁ h₂ ... hₙ` except that each hypothesis is simplified as it is introduced, and each introduced hypothesis is used to simplify later ones and the final target. As with `simp`, a list of simplification lemmas can be provided. The modifiers `only` and `with` behave as with `simp`. -/ /-- `dsimp` is similar to `simp`, except that it only uses definitional equalities. -/ /-- This tactic applies to a goal whose target has the form `t ~ u` where `~` is a reflexive relation, that is, a relation which has a reflexivity lemma tagged with the attribute `[refl]`. The tactic checks whether `t` and `u` are definitionally equal and then solves the goal. -/ /-- Shorter name for the tactic `reflexivity`. -/ /-- This tactic applies to a goal whose target has the form `t ~ u` where `~` is a symmetric relation, that is, a relation which has a symmetry lemma tagged with the attribute `[symm]`. It replaces the target with `u ~ t`. -/ /-- This tactic applies to a goal whose target has the form `t ~ u` where `~` is a transitive relation, that is, a relation which has a transitivity lemma tagged with the attribute `[trans]`. `transitivity s` replaces the goal with the two subgoals `t ~ s` and `s ~ u`. If `s` is omitted, then a metavariable is used instead. -/ /-- Proves a goal with target `s = t` when `s` and `t` are equal up to the associativity and commutativity of their binary operations. -/ /-- An abbreviation for `ac_reflexivity`. -/ /-- Tries to prove the main goal using congruence closure. -/ /-- Given hypothesis `h : x = t` or `h : t = x`, where `x` is a local constant, `subst h` substitutes `x` by `t` everywhere in the main goal and then clears `h`. -/ /-- Apply `subst` to all hypotheses of the form `h : x = t` or `h : t = x`. -/ /-- `clear h₁ ... hₙ` tries to clear each hypothesis `hᵢ` from the local context. -/ /-- Similar to `unfold`, but only uses definitional equalities. -/ /-- Similar to `dunfold`, but performs a raw delta reduction, rather than using an equation associated with the defined constants. -/ /-- This tactic unfolds all structure projections. -/ end interactive structure unfold_config extends simp_config where namespace interactive /-- Given defined constants `e₁ ... eₙ`, `unfold e₁ ... eₙ` iteratively unfolds all occurrences in the target of the main goal, using equational lemmas associated with the definitions. As with `simp`, the `at` modifier can be used to specify locations for the unfolding. -/ /-- Similar to `unfold`, but does not iterate the unfolding. -/ /-- If the target of the main goal is an `opt_param`, assigns the default value. -/ /-- If the target of the main goal is an `auto_param`, executes the associated tactic. -/ /-- Fails if the given tactic succeeds. -/ /-- Succeeds if the given tactic fails. -/ /-- `guard_target t` fails if the target of the main goal is not `t`. We use this tactic for writing tests. -/ /-- `guard_hyp h : t` fails if the hypothesis `h` does not have type `t`. We use this tactic for writing tests. -/ /-- `match_target t` fails if target does not match pattern `t`. -/ /-- `by_cases p` splits the main goal into two cases, assuming `h : p` in the first branch, and `h : ¬ p` in the second branch. You can specify the name of the new hypothesis using the syntax `by_cases h : p`. -/ /-- Apply function extensionality and introduce new hypotheses. The tactic `funext` will keep applying new the `funext` lemma until the goal target is not reducible to ``` |- ((fun x, ...) = (fun x, ...)) ``` The variant `funext h₁ ... hₙ` applies `funext` `n` times, and uses the given identifiers to name the new hypotheses. -/ /-- If the target of the main goal is a proposition `p`, `by_contradiction` reduces the goal to proving `false` using the additional hypothesis `h : ¬ p`. `by_contradiction h` can be used to name the hypothesis `h : ¬ p`. This tactic will attempt to use decidability of `p` if available, and will otherwise fall back on classical reasoning. -/ /-- If the target of the main goal is a proposition `p`, `by_contra` reduces the goal to proving `false` using the additional hypothesis `h : ¬ p`. `by_contra h` can be used to name the hypothesis `h : ¬ p`. This tactic will attempt to use decidability of `p` if available, and will otherwise fall back on classical reasoning. -/ /-- Type check the given expression, and trace its type. -/ /-- Fail if there are unsolved goals. -/ /-- `show t` finds the first goal whose target unifies with `t`. It makes that the main goal, performs the unification, and replaces the target with the unified version of `t`. -/ /-- The tactic `specialize h a₁ ... aₙ` works on local hypothesis `h`. The premises of this hypothesis, either universal quantifications or non-dependent implications, are instantiated by concrete terms coming either from arguments `a₁` ... `aₙ`. The tactic adds a new hypothesis with the same name `h := h a₁ ... aₙ` and tries to clear the previous one. -/ end interactive end tactic /- See add_interactive -/ /-- Copy a list of meta definitions in the current namespace to tactic.interactive. This command is useful when we want to update tactic.interactive without closing the current namespace. -/ /-- Renames hypotheses with the same name. -/ namespace tactic /- Helper tactic for `mk_inj_eq -/ /- Auxiliary tactic for proving `I.C.inj_eq` lemmas. These lemmas are automatically generated by the equation compiler. Example: ``` list.cons.inj_eq : forall h1 h2 t1 t2, (h1::t1 = h2::t2) = (h1 = h2 ∧ t1 = t2) := by mk_inj_eq ``` -/ end tactic /- Define inj_eq lemmas for inductive datatypes that were declared before `mk_inj_eq` -/ theorem sum.inl.inj_eq {α : Type u} (β : Type v) (a₁ : α) (a₂ : α) : sum.inl a₁ = sum.inl a₂ = (a₁ = a₂) := propext { mp := fun (h : sum.inl a₁ = sum.inl a₂) => sum.inl.inj h, mpr := fun (ᾰ : a₁ = a₂) => (fun (val val_1 : α) (e_2 : val = val_1) => congr_arg sum.inl e_2) a₁ a₂ ᾰ } theorem sum.inr.inj_eq (α : Type u) {β : Type v} (b₁ : β) (b₂ : β) : sum.inr b₁ = sum.inr b₂ = (b₁ = b₂) := sorry theorem psum.inl.inj_eq {α : Sort u} (β : Sort v) (a₁ : α) (a₂ : α) : psum.inl a₁ = psum.inl a₂ = (a₁ = a₂) := propext { mp := fun (h : psum.inl a₁ = psum.inl a₂) => psum.inl.inj h, mpr := fun (ᾰ : a₁ = a₂) => (fun (val val_1 : α) (e_2 : val = val_1) => congr_arg psum.inl e_2) a₁ a₂ ᾰ } theorem psum.inr.inj_eq (α : Sort u) {β : Sort v} (b₁ : β) (b₂ : β) : psum.inr b₁ = psum.inr b₂ = (b₁ = b₂) := sorry theorem sigma.mk.inj_eq {α : Type u} {β : α → Type v} (a₁ : α) (b₁ : β a₁) (a₂ : α) (b₂ : β a₂) : sigma.mk a₁ b₁ = sigma.mk a₂ b₂ = (a₁ = a₂ ∧ b₁ == b₂) := sorry theorem psigma.mk.inj_eq {α : Sort u} {β : α → Sort v} (a₁ : α) (b₁ : β a₁) (a₂ : α) (b₂ : β a₂) : psigma.mk a₁ b₁ = psigma.mk a₂ b₂ = (a₁ = a₂ ∧ b₁ == b₂) := sorry theorem subtype.mk.inj_eq {α : Sort u} {p : α → Prop} (a₁ : α) (h₁ : p a₁) (a₂ : α) (h₂ : p a₂) : { val := a₁, property := h₁ } = { val := a₂, property := h₂ } = (a₁ = a₂) := sorry theorem option.some.inj_eq {α : Type u} (a₁ : α) (a₂ : α) : some a₁ = some a₂ = (a₁ = a₂) := propext { mp := fun (h : some a₁ = some a₂) => option.some.inj h, mpr := fun (ᾰ : a₁ = a₂) => (fun (val val_1 : α) (e_1 : val = val_1) => congr_arg some e_1) a₁ a₂ ᾰ } theorem list.cons.inj_eq {α : Type u} (h₁ : α) (t₁ : List α) (h₂ : α) (t₂ : List α) : h₁ :: t₁ = h₂ :: t₂ = (h₁ = h₂ ∧ t₁ = t₂) := sorry theorem nat.succ.inj_eq (n₁ : ℕ) (n₂ : ℕ) : Nat.succ n₁ = Nat.succ n₂ = (n₁ = n₂) := propext { mp := fun (h : Nat.succ n₁ = Nat.succ n₂) => nat.succ.inj h, mpr := fun (ᾰ : n₁ = n₂) => (fun (n n_1 : ℕ) (e_1 : n = n_1) => congr_arg Nat.succ e_1) n₁ n₂ ᾰ }
f37878e32e0cd7037554435f79f92edec3644e4a
f608b09bd951f29eccb4c27187f55223000fa85f
/2020/lean/day1.lean
60fc543ee72d7360a8073b692ce2646617f86c0b
[]
no_license
bobismijnnaam/advent-of-code
9482d954b8f381b28a4823337e3688963fd05d6d
471b9cad04eba7010da79416aef7a3218b1f4541
refs/heads/master
1,639,530,767,572
1,639,425,773,000
1,639,425,773,000
225,140,719
0
0
null
null
null
null
UTF-8
Lean
false
false
3,118
lean
import .lovelib import init.data.char.basic namespace Day1 def search_helper : ℕ → ℕ → list ℕ → list (ℕ × ℕ) | needle a (b :: bs) := if a + b = needle then (a, b) :: search_helper needle a bs else search_helper needle a bs | _ _ [] := [] def search : ℕ → list ℕ → list (ℕ × ℕ) | needle (n :: ns) := search_helper needle n ns ++ search needle ns | _ [] := [] def search_spec : ℕ → set ℕ → set (ℕ × ℕ) | needle ns := {ab | prod.fst ab ∈ ns ∧ prod.snd ab ∈ ns ∧ prod.fst ab + prod.snd ab = needle } lemma search_search_spec (needle : ℕ) (ns : list ℕ) : set_of (λn, list.mem n (search needle ns)) = search_spec needle (set_of $ (λns n, list.mem n ns) ns) := begin induction' ns, case nil { ext1 ab, apply iff.intro, { intro hab, tauto }, { intro hab, cases' hab, tauto }, }, case cons { ext1 ab, apply iff.intro, { intro hab, apply and.intro, { }, apply and.intro, { sorry }, { sorry } }, { sorry } } end def search_helper_helper₂ : ℕ → ℕ → ℕ → list ℕ → list (ℕ × ℕ × ℕ) | needle a b (c :: cs) := if a + b + c = needle then (a, b, c) :: search_helper_helper₂ needle a b cs else search_helper_helper₂ needle a b cs | _ _ _ [] := [] def search_helper₂ : ℕ → ℕ → list ℕ → list (ℕ × ℕ × ℕ) | needle a (b :: bs) := search_helper_helper₂ needle a b bs ++ search_helper₂ needle a bs | _ _ [] := [] def search₂ : ℕ → list ℕ → list (ℕ × ℕ × ℕ) | needle (n :: ns) := search_helper₂ needle n ns ++ search₂ needle ns | _ [] := [] def split_helper : char → list string → char → list string | s (word :: words) c := if s = c then ("" :: word :: words) else ((string.append word c.to_string) :: words) | s [] c := if s = c then ["", ""] else [c.to_string] def split : string → char → list string | xs s := string.fold [] (split_helper s) xs def main : io unit := do input ← io.fs.read_file "input1.txt", -- io.put_str_ln input.to_string, let words := list.reverse $ list.tail $ split input.to_string '\n', -- io.put_str_ln (words.to_string), let nums := functor.map string.to_nat words, -- io.put_str_ln nums.to_string, let answers := search 2020 nums, io.put_str_ln "answers:", io.put_str_ln answers.to_string, match list.nth answers 0 with | option.some (ab) := io.put_str_ln (prod.fst ab * prod.snd ab).repr | _ := pure () end, let answers := search₂ 2020 nums, io.put_str_ln "answers₂:", io.put_str_ln answers.to_string, match list.nth answers 0 with | option.some (ab) := io.put_str_ln (prod.fst ab * (prod.fst $ prod.snd ab) * (prod.snd $ prod.snd ab)).repr | _ := pure () end end Day1 def main := Day1.main #eval main
e9d2463e0fecedb2bf47c65efc619006f7510f1c
94e33a31faa76775069b071adea97e86e218a8ee
/src/analysis/normed_space/basic.lean
b4e1bd06932af5c7aea037a02e83cecfb07240a0
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
23,015
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 analysis.normed.field.basic import analysis.normed.group.infinite_sum import data.matrix.basic import topology.sequences /-! # Normed spaces In this file we define (semi)normed spaces and algebras. We also prove some theorems about these definitions. -/ variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*} noncomputable theory open filter metric function set open_locale topological_space big_operators nnreal ennreal uniformity pointwise section semi_normed_group section prio set_option extends_priority 920 -- Here, we set a rather high priority for the instance `[normed_space α β] : module α β` -- to take precedence over `semiring.to_module` as this leads to instance paths with better -- unification properties. /-- 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`. Note that since this requires `semi_normed_group` and not `normed_group`, this typeclass can be used for "semi normed spaces" too, just as `module` can be used for "semi modules". -/ class normed_space (α : Type*) (β : Type*) [normed_field α] [semi_normed_group β] extends module α β := (norm_smul_le : ∀ (a:α) (b:β), ∥a • b∥ ≤ ∥a∥ * ∥b∥) end prio variables [normed_field α] [semi_normed_group β] @[priority 100] -- see Note [lower instance priority] instance normed_space.has_bounded_smul [normed_space α β] : has_bounded_smul α β := { dist_smul_pair' := λ x y₁ y₂, by simpa [dist_eq_norm, smul_sub] using normed_space.norm_smul_le x (y₁ - y₂), dist_pair_smul' := λ x₁ x₂ y, by simpa [dist_eq_norm, sub_smul] using normed_space.norm_smul_le (x₁ - x₂) y } instance normed_field.to_normed_space : normed_space α α := { norm_smul_le := λ a b, le_of_eq (norm_mul a b) } lemma norm_smul [normed_space α β] (s : α) (x : β) : ∥s • x∥ = ∥s∥ * ∥x∥ := begin 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∥) : mul_le_mul_of_nonneg_left (normed_space.norm_smul_le _ _) (norm_nonneg _) ... = ∥s • x∥ : by rw [norm_inv, ← mul_assoc, mul_inv_cancel (mt norm_eq_zero.1 h), one_mul] } end @[simp] lemma abs_norm_eq_norm (z : β) : |∥z∥| = ∥z∥ := (abs_eq (norm_nonneg z)).mpr (or.inl rfl) lemma inv_norm_smul_mem_closed_unit_ball [normed_space ℝ β] (x : β) : ∥x∥⁻¹ • x ∈ closed_ball (0 : β) 1 := by simp only [mem_closed_ball_zero_iff, norm_smul, norm_inv, norm_norm, ← div_eq_inv_mul, div_self_le_one] 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 : β) : ∥s • x∥₊ = ∥s∥₊ * ∥x∥₊ := nnreal.eq $ norm_smul s x lemma nndist_smul [normed_space α β] (s : α) (x y : β) : nndist (s • x) (s • y) = ∥s∥₊ * nndist x y := nnreal.eq $ dist_smul s x y lemma lipschitz_with_smul [normed_space α β] (s : α) : lipschitz_with ∥s∥₊ ((•) s : β → β) := lipschitz_with_iff_dist_le_mul.2 $ λ x y, by rw [dist_smul, coe_nnnorm] lemma norm_smul_of_nonneg [normed_space ℝ β] {t : ℝ} (ht : 0 ≤ t) (x : β) : ∥t • x∥ = t * ∥x∥ := by rw [norm_smul, real.norm_eq_abs, abs_of_nonneg ht] variables {E : Type*} [semi_normed_group E] [normed_space α E] variables {F : Type*} [semi_normed_group F] [normed_space α F] theorem eventually_nhds_norm_smul_sub_lt (c : α) (x : E) {ε : ℝ} (h : 0 < ε) : ∀ᶠ y in 𝓝 x, ∥c • (y - x)∥ < ε := have tendsto (λ y, ∥c • (y - x)∥) (𝓝 x) (𝓝 0), from ((continuous_id.sub continuous_const).const_smul _).norm.tendsto' _ _ (by simp), this.eventually (gt_mem_nhds h) lemma filter.tendsto.zero_smul_is_bounded_under_le {f : ι → α} {g : ι → E} {l : filter ι} (hf : tendsto f l (𝓝 0)) (hg : is_bounded_under (≤) l (norm ∘ g)) : tendsto (λ x, f x • g x) l (𝓝 0) := hf.op_zero_is_bounded_under_le hg (•) (λ x y, (norm_smul x y).le) lemma filter.is_bounded_under.smul_tendsto_zero {f : ι → α} {g : ι → E} {l : filter ι} (hf : is_bounded_under (≤) l (norm ∘ f)) (hg : tendsto g l (𝓝 0)) : tendsto (λ x, f x • g x) l (𝓝 0) := hg.op_zero_is_bounded_under_le hf (flip (•)) (λ x y, ((norm_smul y x).trans (mul_comm _ _)).le) theorem closure_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : r ≠ 0) : closure (ball x r) = closed_ball x r := begin refine subset.antisymm closure_ball_subset_closed_ball (λ y hy, _), have : continuous_within_at (λ c : ℝ, c • (y - x) + x) (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_ne_one ℝ _ _), zero_le_one] }, { rintros c ⟨hc0, hc1⟩, rw [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, replace hr : 0 < r, from ((norm_nonneg _).trans hy).lt_of_ne hr.symm, apply mul_lt_mul'; assumption } end theorem frontier_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : r ≠ 0) : frontier (ball x r) = sphere x r := begin rw [frontier, closure_ball x hr, is_open_ball.interior_eq], ext x, exact (@eq_iff_le_not_lt ℝ _ _ _).symm end theorem interior_closed_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : r ≠ 0) : interior (closed_ball x r) = ball x r := begin cases hr.lt_or_lt with hr hr, { rw [closed_ball_eq_empty.2 hr, ball_eq_empty.2 hr.le, interior_empty] }, refine subset.antisymm _ ball_subset_interior_closed_ball, intros y hy, rcases (mem_closed_ball.1 $ interior_subset hy).lt_or_eq with hr|rfl, { exact hr }, set f : ℝ → E := λ c : ℝ, c • (y - x) + x, suffices : f ⁻¹' closed_ball x (dist y x) ⊆ 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 (Icc (-1:ℝ) 1) := interior_mono this (preimage_interior_subset_interior_preimage hfc hf1), contrapose h1, simp }, intros c hc, rw [mem_Icc, ← abs_le, ← real.norm_eq_abs, ← mul_le_mul_right hr], simpa [f, dist_eq_norm, norm_smul] using hc end theorem frontier_closed_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : r ≠ 0) : frontier (closed_ball x r) = sphere x r := by rw [frontier, closure_closed_ball, interior_closed_ball x hr, closed_ball_diff_ball] /-- A (semi) normed real vector space is homeomorphic to the unit ball in the same space. This homeomorphism sends `x : E` to `(1 + ∥x∥)⁻¹ • x`. In many cases the actual implementation is not important, so we don't mark the projection lemmas `homeomorph_unit_ball_apply_coe` and `homeomorph_unit_ball_symm_apply` as `@[simp]`. -/ @[simps { attrs := [] }] def homeomorph_unit_ball {E : Type*} [semi_normed_group E] [normed_space ℝ E] : E ≃ₜ ball (0 : E) 1 := { to_fun := λ x, ⟨(1 + ∥x∥)⁻¹ • x, begin have : ∥x∥ < |1 + ∥x∥| := (lt_one_add _).trans_le (le_abs_self _), rwa [mem_ball_zero_iff, norm_smul, real.norm_eq_abs, abs_inv, ← div_eq_inv_mul, div_lt_one ((norm_nonneg x).trans_lt this)], end⟩, inv_fun := λ x, (1 - ∥(x : E)∥)⁻¹ • (x : E), left_inv := λ x, begin have : 0 < 1 + ∥x∥ := (norm_nonneg x).trans_lt (lt_one_add _), field_simp [this.ne', abs_of_pos this, norm_smul, smul_smul, abs_div] end, right_inv := λ x, subtype.ext begin have : 0 < 1 - ∥(x : E)∥ := sub_pos.2 (mem_ball_zero_iff.1 x.2), field_simp [norm_smul, smul_smul, abs_div, abs_of_pos this, this.ne'] end, continuous_to_fun := continuous_subtype_mk _ $ ((continuous_const.add continuous_norm).inv₀ (λ x, ((norm_nonneg x).trans_lt (lt_one_add _)).ne')).smul continuous_id, continuous_inv_fun := continuous.smul ((continuous_const.sub continuous_subtype_coe.norm).inv₀ $ λ x, (sub_pos.2 $ mem_ball_zero_iff.1 x.2).ne') continuous_subtype_coe } open normed_field instance : normed_space α (ulift E) := { norm_smul_le := λ s x, (normed_space.norm_smul_le s x.down : _), ..ulift.normed_group, ..ulift.module' } /-- The product of two normed spaces is a normed space, with the sup norm. -/ instance prod.normed_space : normed_space α (E × F) := { norm_smul_le := λ s x, le_of_eq $ by simp [prod.norm_def, norm_smul, mul_max_of_nonneg], ..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, semi_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 : ι), ∥a • f b∥₊)) : ℝ) = ∥a∥₊ * ↑(finset.sup finset.univ (λ (b : ι), ∥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 {𝕜 R : Type*} [has_smul 𝕜 R] [normed_field 𝕜] [ring R] {E : Type*} [semi_normed_group E] [normed_space 𝕜 E] [module R E] [is_scalar_tower 𝕜 R E] (s : submodule R E) : normed_space 𝕜 s := { norm_smul_le := λc x, le_of_eq $ norm_smul c (x : E) } /-- If there is a scalar `c` with `∥c∥>1`, then any element with nonzero norm 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_semi_normed {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 ((ne.symm hx).le_iff_lt.1 (norm_nonneg x)) εpos, rcases exists_mem_Ico_zpow 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_zpow, 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_lt_iff cnpos, mul_comm, norm_zpow], exact (div_lt_iff εpos).1 (hn.2) }, show ε / ∥c∥ ≤ ∥(c ^ (n + 1))⁻¹ • x∥, { rw [div_le_iff cpos, norm_smul, norm_inv, norm_zpow, zpow_add₀ (ne_of_gt cpos), zpow_one, mul_inv_rev, mul_comm, ← mul_assoc, ← mul_assoc, mul_inv_cancel (ne_of_gt cpos), one_mul, ← div_eq_inv_mul, le_div_iff (zpow_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_zpow, zpow_add₀ (ne_of_gt cpos), zpow_one, this, ← div_eq_inv_mul], exact mul_le_mul_of_nonneg_right hn.1 (norm_nonneg _) } end end semi_normed_group section normed_group variables [normed_field α] variables {E : Type*} [normed_group E] [normed_space α E] variables {F : Type*} [normed_group F] [normed_space α F] open normed_field /-- While this may appear identical to `normed_space.to_module`, it contains an implicit argument involving `normed_group.to_semi_normed_group` that typeclass inference has trouble inferring. Specifically, the following instance cannot be found without this `normed_space.to_module'`: ```lean example (𝕜 ι : Type*) (E : ι → Type*) [normed_field 𝕜] [Π i, normed_group (E i)] [Π i, normed_space 𝕜 (E i)] : Π i, module 𝕜 (E i) := by apply_instance ``` [This Zulip thread](https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/Typeclass.20resolution.20under.20binders/near/245151099) gives some more context. -/ @[priority 100] instance normed_space.to_module' : module α F := normed_space.to_module section surj variables (E) [normed_space ℝ E] [nontrivial E] lemma exists_norm_eq {c : ℝ} (hc : 0 ≤ c) : ∃ x : E, ∥x∥ = c := begin rcases exists_ne (0 : E) with ⟨x, hx⟩, rw ← norm_ne_zero_iff at hx, use c • ∥x∥⁻¹ • x, simp [norm_smul, real.norm_of_nonneg hc, hx] end @[simp] lemma range_norm : range (norm : E → ℝ) = Ici 0 := subset.antisymm (range_subset_iff.2 norm_nonneg) (λ _, exists_norm_eq E) lemma nnnorm_surjective : surjective (nnnorm : E → ℝ≥0) := λ c, (exists_norm_eq E c.coe_nonneg).imp $ λ x h, nnreal.eq h @[simp] lemma range_nnnorm : range (nnnorm : E → ℝ≥0) = univ := (nnnorm_surjective E).range_eq end surj theorem interior_closed_ball' [normed_space ℝ E] [nontrivial E] (x : E) (r : ℝ) : interior (closed_ball x r) = ball x r := begin rcases eq_or_ne r 0 with rfl|hr, { rw [closed_ball_zero, ball_zero, interior_singleton] }, { exact interior_closed_ball x hr } end theorem frontier_closed_ball' [normed_space ℝ E] [nontrivial E] (x : E) (r : ℝ) : frontier (closed_ball x r) = sphere x r := by rw [frontier, closure_closed_ball, interior_closed_ball' x r, closed_ball_diff_ball] variables {α} /-- 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∥) := rescale_to_shell_semi_normed hc εpos (ne_of_lt (norm_pos_iff.2 hx)).symm end normed_group section normed_space_nondiscrete variables (𝕜 E : Type*) [nondiscrete_normed_field 𝕜] [normed_group E] [normed_space 𝕜 E] [nontrivial E] include 𝕜 /-- If `E` is a nontrivial normed space over a nondiscrete normed field `𝕜`, then `E` is unbounded: for any `c : ℝ`, there exists a vector `x : E` with norm strictly greater than `c`. -/ lemma normed_space.exists_lt_norm (c : ℝ) : ∃ x : E, c < ∥x∥ := begin rcases exists_ne (0 : E) with ⟨x, hx⟩, rcases normed_field.exists_lt_norm 𝕜 (c / ∥x∥) with ⟨r, hr⟩, use r • x, rwa [norm_smul, ← div_lt_iff], rwa norm_pos_iff end protected lemma normed_space.unbounded_univ : ¬bounded (univ : set E) := λ h, let ⟨R, hR⟩ := bounded_iff_forall_norm_le.1 h, ⟨x, hx⟩ := normed_space.exists_lt_norm 𝕜 E R in hx.not_le (hR x trivial) /-- A normed vector space over a nondiscrete normed field is a noncompact space. This cannot be an instance because in order to apply it, Lean would have to search for `normed_space 𝕜 E` with unknown `𝕜`. We register this as an instance in two cases: `𝕜 = E` and `𝕜 = ℝ`. -/ protected lemma normed_space.noncompact_space : noncompact_space E := ⟨λ h, normed_space.unbounded_univ 𝕜 _ h.bounded⟩ @[priority 100] instance nondiscrete_normed_field.noncompact_space : noncompact_space 𝕜 := normed_space.noncompact_space 𝕜 𝕜 omit 𝕜 @[priority 100] instance real_normed_space.noncompact_space [normed_space ℝ E] : noncompact_space E := normed_space.noncompact_space ℝ E end normed_space_nondiscrete section normed_algebra /-- A normed algebra `𝕜'` over `𝕜` is normed module that is also an algebra. See the implementation notes for `algebra` for a discussion about non-unital algebras. Following the strategy there, a non-unital *normed* algebra can be written as: ```lean variables [normed_field 𝕜] [non_unital_semi_normed_ring 𝕜'] variables [normed_module 𝕜 𝕜'] [smul_comm_class 𝕜 𝕜' 𝕜'] [is_scalar_tower 𝕜 𝕜' 𝕜'] ``` -/ class normed_algebra (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [semi_normed_ring 𝕜'] extends algebra 𝕜 𝕜' := (norm_smul_le : ∀ (r : 𝕜) (x : 𝕜'), ∥r • x∥ ≤ ∥r∥ * ∥x∥) variables {𝕜 : Type*} (𝕜' : Type*) [normed_field 𝕜] [semi_normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] @[priority 100] instance normed_algebra.to_normed_space : normed_space 𝕜 𝕜' := { norm_smul_le := normed_algebra.norm_smul_le } /-- While this may appear identical to `normed_algebra.to_normed_space`, it contains an implicit argument involving `normed_ring.to_semi_normed_ring` that typeclass inference has trouble inferring. Specifically, the following instance cannot be found without this `normed_space.to_module'`: ```lean example (𝕜 ι : Type*) (E : ι → Type*) [normed_field 𝕜] [Π i, normed_ring (E i)] [Π i, normed_algebra 𝕜 (E i)] : Π i, module 𝕜 (E i) := by apply_instance ``` See `normed_space.to_module'` for a similar situation. -/ @[priority 100] instance normed_algebra.to_normed_space' {𝕜'} [normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] : normed_space 𝕜 𝕜' := by apply_instance lemma norm_algebra_map (x : 𝕜) : ∥algebra_map 𝕜 𝕜' x∥ = ∥x∥ * ∥(1 : 𝕜')∥ := begin rw algebra.algebra_map_eq_smul_one, exact norm_smul _ _, end lemma nnnorm_algebra_map (x : 𝕜) : ∥algebra_map 𝕜 𝕜' x∥₊ = ∥x∥₊ * ∥(1 : 𝕜')∥₊ := subtype.ext $ norm_algebra_map 𝕜' x @[simp] lemma norm_algebra_map' [norm_one_class 𝕜'] (x : 𝕜) : ∥algebra_map 𝕜 𝕜' x∥ = ∥x∥ := by rw [norm_algebra_map, norm_one, mul_one] @[simp] lemma nnnorm_algebra_map' [norm_one_class 𝕜'] (x : 𝕜) : ∥algebra_map 𝕜 𝕜' x∥₊ = ∥x∥₊ := subtype.ext $ norm_algebra_map' _ _ variables (𝕜 𝕜') /-- In a normed algebra, the inclusion of the base field in the extended field is an isometry. -/ lemma algebra_map_isometry [norm_one_class 𝕜'] : isometry (algebra_map 𝕜 𝕜') := begin refine isometry_emetric_iff_metric.2 (λx y, _), rw [dist_eq_norm, dist_eq_norm, ← ring_hom.map_sub, norm_algebra_map'], end /-- The inclusion of the base field in a normed algebra as a continuous linear map. -/ @[simps] def algebra_map_clm : 𝕜 →L[𝕜] 𝕜' := { to_fun := algebra_map 𝕜 𝕜', map_add' := (algebra_map 𝕜 𝕜').map_add, map_smul' := λ r x, by rw [algebra.id.smul_eq_mul, map_mul, ring_hom.id_apply, algebra.smul_def], cont := have lipschitz_with ∥(1 : 𝕜')∥₊ (algebra_map 𝕜 𝕜') := λ x y, begin rw [edist_eq_coe_nnnorm_sub, edist_eq_coe_nnnorm_sub, ←map_sub, ←ennreal.coe_mul, ennreal.coe_le_coe, mul_comm], exact (nnnorm_algebra_map _ _).le, end, this.continuous } lemma algebra_map_clm_coe : (algebra_map_clm 𝕜 𝕜' : 𝕜 → 𝕜') = (algebra_map 𝕜 𝕜' : 𝕜 → 𝕜') := rfl lemma algebra_map_clm_to_linear_map : (algebra_map_clm 𝕜 𝕜').to_linear_map = algebra.linear_map 𝕜 𝕜' := rfl instance normed_algebra.id : normed_algebra 𝕜 𝕜 := { .. normed_field.to_normed_space, .. algebra.id 𝕜} /-- Any normed characteristic-zero division ring that is a normed_algebra over the reals is also a normed algebra over the rationals. Phrased another way, if `𝕜` is a normed algebra over the reals, then `algebra_rat` respects that norm. -/ instance normed_algebra_rat {𝕜} [normed_division_ring 𝕜] [char_zero 𝕜] [normed_algebra ℝ 𝕜] : normed_algebra ℚ 𝕜 := { norm_smul_le := λ q x, by rw [←smul_one_smul ℝ q x, rat.smul_one_eq_coe, norm_smul, rat.norm_cast_real], } instance punit.normed_algebra : normed_algebra 𝕜 punit := { norm_smul_le := λ q x, by simp only [punit.norm_eq_zero, mul_zero] } instance : normed_algebra 𝕜 (ulift 𝕜') := { ..ulift.normed_space } /-- The product of two normed algebras is a normed algebra, with the sup norm. -/ instance prod.normed_algebra {E F : Type*} [semi_normed_ring E] [semi_normed_ring F] [normed_algebra 𝕜 E] [normed_algebra 𝕜 F] : normed_algebra 𝕜 (E × F) := { ..prod.normed_space } /-- The product of finitely many normed algebras is a normed algebra, with the sup norm. -/ instance pi.normed_algebra {E : ι → Type*} [fintype ι] [Π i, semi_normed_ring (E i)] [Π i, normed_algebra 𝕜 (E i)] : normed_algebra 𝕜 (Π i, E i) := { .. pi.normed_space, .. pi.algebra _ E } end normed_algebra section restrict_scalars variables (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] (E : Type*) [semi_normed_group E] [normed_space 𝕜' E] instance {𝕜 : Type*} {𝕜' : Type*} {E : Type*} [I : semi_normed_group E] : semi_normed_group (restrict_scalars 𝕜 𝕜' E) := I instance {𝕜 : Type*} {𝕜' : Type*} {E : Type*} [I : normed_group E] : normed_group (restrict_scalars 𝕜 𝕜' E) := I /-- If `E` is a normed space over `𝕜'` and `𝕜` is a normed algebra over `𝕜'`, then `restrict_scalars.module` is additionally a `normed_space`. -/ instance : normed_space 𝕜 (restrict_scalars 𝕜 𝕜' E) := { norm_smul_le := λ c x, (normed_space.norm_smul_le (algebra_map 𝕜 𝕜' c) (_ : E)).trans_eq $ by rw norm_algebra_map', ..restrict_scalars.module 𝕜 𝕜' E } /-- The action of the original normed_field on `restrict_scalars 𝕜 𝕜' E`. This is not an instance as it would be contrary to the purpose of `restrict_scalars`. -/ -- If you think you need this, consider instead reproducing `restrict_scalars.lsmul` -- appropriately modified here. def module.restrict_scalars.normed_space_orig {𝕜 : Type*} {𝕜' : Type*} {E : Type*} [normed_field 𝕜'] [semi_normed_group E] [I : normed_space 𝕜' E] : normed_space 𝕜' (restrict_scalars 𝕜 𝕜' E) := I /-- Warning: This declaration should be used judiciously. Please consider using `is_scalar_tower` and/or `restrict_scalars 𝕜 𝕜' E` instead. This definition allows the `restrict_scalars.normed_space` instance to be put directly on `E` rather on `restrict_scalars 𝕜 𝕜' E`. This would be a very bad instance; both because `𝕜'` cannot be inferred, and because it is likely to create instance diamonds. -/ def normed_space.restrict_scalars : normed_space 𝕜 E := restrict_scalars.normed_space _ 𝕜' _ end restrict_scalars
180baf629721f3fed3097052725e27e47b3d4811
c86b74188c4b7a462728b1abd659ab4e5828dd61
/stage0/src/Lean/Data/Json/FromToJson.lean
ea956e438e9d4869e75c296548182f5dcdeffc4d
[ "Apache-2.0" ]
permissive
cwb96/lean4
75e1f92f1ba98bbaa6b34da644b3dfab2ce7bf89
b48831cda76e64f13dd1c0edde7ba5fb172ed57a
refs/heads/master
1,686,347,881,407
1,624,483,842,000
1,624,483,842,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,127
lean
/- Copyright (c) 2019 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Marc Huisinga -/ import Lean.Data.Json.Basic namespace Lean universes u class FromJson (α : Type u) where fromJson? : Json → Except String α export FromJson (fromJson?) class ToJson (α : Type u) where toJson : α → Json export ToJson (toJson) instance : FromJson Json := ⟨Except.ok⟩ instance : ToJson Json := ⟨id⟩ instance : FromJson JsonNumber := ⟨Json.getNum?⟩ instance : ToJson JsonNumber := ⟨Json.num⟩ -- looks like id, but there are coercions happening instance : FromJson Bool := ⟨Json.getBool?⟩ instance : ToJson Bool := ⟨fun b => b⟩ instance : FromJson Nat := ⟨Json.getNat?⟩ instance : ToJson Nat := ⟨fun n => n⟩ instance : FromJson Int := ⟨Json.getInt?⟩ instance : ToJson Int := ⟨fun n => Json.num n⟩ instance : FromJson String := ⟨Json.getStr?⟩ instance : ToJson String := ⟨fun s => s⟩ instance [FromJson α] : FromJson (Array α) where fromJson? | Json.arr a => a.mapM fromJson? | _ => throw "JSON array expected" instance [ToJson α] : ToJson (Array α) := ⟨fun a => Json.arr (a.map toJson)⟩ instance [FromJson α] : FromJson (Option α) where fromJson? | Json.null => Except.ok none | j => some <$> fromJson? j instance [ToJson α] : ToJson (Option α) := ⟨fun | none => Json.null | some a => toJson a⟩ namespace Json instance : FromJson Structured := ⟨fun | arr a => Structured.arr a | obj o => Structured.obj o | _ => throw "structured object expected"⟩ instance : ToJson Structured := ⟨fun | Structured.arr a => arr a | Structured.obj o => obj o⟩ def toStructured? [ToJson α] (v : α) : Except String Structured := fromJson? (toJson v) def getObjValAs? (j : Json) (α : Type u) [FromJson α] (k : String) : Except String α := fromJson? <| j.getObjValD k def opt [ToJson α] (k : String) : Option α → List (String × Json) | none => [] | some o => [⟨k, toJson o⟩] end Json end Lean
304eec51715a99db694039f00d52060af23c0dc3
9dc8cecdf3c4634764a18254e94d43da07142918
/src/measure_theory/function/conditional_expectation/real.lean
e9f7021abe50c80683ca41820240116f30832e36
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
19,612
lean
/- Copyright (c) 2022 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne, Kexing Ying -/ import measure_theory.function.conditional_expectation.indicator /-! # Conditional expectation of real-valued functions This file proves some results regarding the conditional expectation of real-valued functions. ## Main results * `measure_theory.rn_deriv_ae_eq_condexp`: the conditional expectation `μ[f | m]` is equal to the Radon-Nikodym derivative of `fμ` restricted on `m` with respect to `μ` restricted on `m`. * `measure_theory.integrable.uniform_integrable_condexp`: the conditional expectation of a function form a uniformly integrable class. * `measure_theory.condexp_strongly_measurable_mul`: the pull-out property of the conditional expectation. -/ noncomputable theory open topological_space measure_theory.Lp filter continuous_linear_map open_locale nnreal ennreal topological_space big_operators measure_theory namespace measure_theory variables {α : Type*} {m m0 : measurable_space α} {μ : measure α} lemma rn_deriv_ae_eq_condexp {hm : m ≤ m0} [hμm : sigma_finite (μ.trim hm)] {f : α → ℝ} (hf : integrable f μ) : signed_measure.rn_deriv ((μ.with_densityᵥ f).trim hm) (μ.trim hm) =ᵐ[μ] μ[f | m] := begin refine ae_eq_condexp_of_forall_set_integral_eq hm hf _ _ _, { exact λ _ _ _, (integrable_of_integrable_trim hm (signed_measure.integrable_rn_deriv ((μ.with_densityᵥ f).trim hm) (μ.trim hm))).integrable_on }, { intros s hs hlt, conv_rhs { rw [← hf.with_densityᵥ_trim_eq_integral hm hs, ← signed_measure.with_densityᵥ_rn_deriv_eq ((μ.with_densityᵥ f).trim hm) (μ.trim hm) (hf.with_densityᵥ_trim_absolutely_continuous hm)], }, rw [with_densityᵥ_apply (signed_measure.integrable_rn_deriv ((μ.with_densityᵥ f).trim hm) (μ.trim hm)) hs, ← set_integral_trim hm _ hs], exact (signed_measure.measurable_rn_deriv _ _).strongly_measurable }, { exact strongly_measurable.ae_strongly_measurable' (signed_measure.measurable_rn_deriv _ _).strongly_measurable }, end -- TODO: the following couple of lemmas should be generalized and proved using Jensen's inequality -- for the conditional expectation (not in mathlib yet) . lemma snorm_one_condexp_le_snorm (f : α → ℝ) : snorm (μ[f | m]) 1 μ ≤ snorm f 1 μ := begin by_cases hf : integrable f μ, swap, { rw [condexp_undef hf, snorm_zero], exact zero_le _ }, by_cases hm : m ≤ m0, swap, { rw [condexp_of_not_le hm, snorm_zero], exact zero_le _ }, by_cases hsig : sigma_finite (μ.trim hm), swap, { rw [condexp_of_not_sigma_finite hm hsig, snorm_zero], exact zero_le _ }, calc snorm (μ[f | m]) 1 μ ≤ snorm (μ[|f| | m]) 1 μ : begin refine snorm_mono_ae _, filter_upwards [@condexp_mono _ m m0 _ _ _ _ _ _ _ _ hf hf.abs (@ae_of_all _ m0 _ μ (λ x, le_abs_self (f x) : ∀ x, f x ≤ |f x|)), eventually_le.trans (condexp_neg f).symm.le (@condexp_mono _ m m0 _ _ _ _ _ _ _ _ hf.neg hf.abs (@ae_of_all _ m0 _ μ (λ x, neg_le_abs_self (f x) : ∀ x, -f x ≤ |f x|)))] with x hx₁ hx₂, exact abs_le_abs hx₁ hx₂, end ... = snorm f 1 μ : begin rw [snorm_one_eq_lintegral_nnnorm, snorm_one_eq_lintegral_nnnorm, ← ennreal.to_real_eq_to_real (ne_of_lt integrable_condexp.2) (ne_of_lt hf.2), ← integral_norm_eq_lintegral_nnnorm (strongly_measurable_condexp.mono hm).ae_strongly_measurable, ← integral_norm_eq_lintegral_nnnorm hf.1], simp_rw [real.norm_eq_abs], rw ← @integral_condexp _ _ _ _ _ m m0 μ _ hm hsig hf.abs, refine integral_congr_ae _, have : 0 ≤ᵐ[μ] μ[|f| | m], { rw ← @condexp_zero α ℝ _ _ _ m m0 μ, exact condexp_mono (integrable_zero _ _ _) hf.abs (@ae_of_all _ m0 _ μ (λ x, abs_nonneg (f x) : ∀ x, 0 ≤ |f x|)) }, filter_upwards [this] with x hx, exact abs_eq_self.2 hx end end lemma integral_abs_condexp_le (f : α → ℝ) : ∫ x, |μ[f | m] x| ∂μ ≤ ∫ x, |f x| ∂μ := begin by_cases hm : m ≤ m0, swap, { simp_rw [condexp_of_not_le hm, pi.zero_apply, abs_zero, integral_zero], exact integral_nonneg (λ x, abs_nonneg _) }, by_cases hfint : integrable f μ, swap, { simp only [condexp_undef hfint, pi.zero_apply, abs_zero, integral_const, algebra.id.smul_eq_mul, mul_zero], exact integral_nonneg (λ x, abs_nonneg _) }, rw [integral_eq_lintegral_of_nonneg_ae, integral_eq_lintegral_of_nonneg_ae], { rw ennreal.to_real_le_to_real; simp_rw [← real.norm_eq_abs, of_real_norm_eq_coe_nnnorm], { rw [← snorm_one_eq_lintegral_nnnorm, ← snorm_one_eq_lintegral_nnnorm], exact snorm_one_condexp_le_snorm _ }, { exact ne_of_lt integrable_condexp.2 }, { exact ne_of_lt hfint.2 } }, { exact eventually_of_forall (λ x, abs_nonneg _) }, { simp_rw ← real.norm_eq_abs, exact hfint.1.norm }, { exact eventually_of_forall (λ x, abs_nonneg _) }, { simp_rw ← real.norm_eq_abs, exact (strongly_measurable_condexp.mono hm).ae_strongly_measurable.norm } end lemma set_integral_abs_condexp_le {s : set α} (hs : measurable_set[m] s) (f : α → ℝ) : ∫ x in s, |μ[f | m] x| ∂μ ≤ ∫ x in s, |f x| ∂μ := begin by_cases hnm : m ≤ m0, swap, { simp_rw [condexp_of_not_le hnm, pi.zero_apply, abs_zero, integral_zero], exact integral_nonneg (λ x, abs_nonneg _) }, by_cases hfint : integrable f μ, swap, { simp only [condexp_undef hfint, pi.zero_apply, abs_zero, integral_const, algebra.id.smul_eq_mul, mul_zero], exact integral_nonneg (λ x, abs_nonneg _) }, have : ∫ x in s, |μ[f | m] x| ∂μ = ∫ x, |μ[s.indicator f | m] x| ∂μ, { rw ← integral_indicator, swap, { exact hnm _ hs }, refine integral_congr_ae _, have : (λ x, |μ[s.indicator f | m] x|) =ᵐ[μ] λ x, |s.indicator (μ[f | m]) x| := eventually_eq.fun_comp (condexp_indicator hfint hs) _, refine eventually_eq.trans (eventually_of_forall $ λ x, _) this.symm, rw [← real.norm_eq_abs, norm_indicator_eq_indicator_norm], refl }, rw [this, ← integral_indicator], swap, { exact hnm _ hs }, refine (integral_abs_condexp_le _).trans (le_of_eq $ integral_congr_ae $ eventually_of_forall $ λ x, _), rw [← real.norm_eq_abs, norm_indicator_eq_indicator_norm], refl, end /-- If the real valued function `f` is bounded almost everywhere by `R`, then so is its conditional expectation. -/ lemma ae_bdd_condexp_of_ae_bdd {R : ℝ≥0} {f : α → ℝ} (hbdd : ∀ᵐ x ∂μ, |f x| ≤ R) : ∀ᵐ x ∂μ, |μ[f | m] x| ≤ R := begin by_cases hnm : m ≤ m0, swap, { simp_rw [condexp_of_not_le hnm, pi.zero_apply, abs_zero], refine eventually_of_forall (λ x, R.coe_nonneg) }, by_cases hfint : integrable f μ, swap, { simp_rw [condexp_undef hfint], filter_upwards [hbdd] with x hx, rw [pi.zero_apply, abs_zero], exact (abs_nonneg _).trans hx }, by_contra h, change μ _ ≠ 0 at h, simp only [← zero_lt_iff, set.compl_def, set.mem_set_of_eq, not_le] at h, suffices : (μ {x | ↑R < |μ[f | m] x|}).to_real * ↑R < (μ {x | ↑R < |μ[f | m] x|}).to_real * ↑R, { exact this.ne rfl }, refine lt_of_lt_of_le (set_integral_gt_gt R.coe_nonneg _ _ h.ne.symm) _, { simp_rw [← real.norm_eq_abs], exact (strongly_measurable_condexp.mono hnm).measurable.norm }, { exact integrable_condexp.abs.integrable_on }, refine (set_integral_abs_condexp_le _ _).trans _, { simp_rw [← real.norm_eq_abs], exact @measurable_set_lt _ _ _ _ _ m _ _ _ _ _ measurable_const strongly_measurable_condexp.norm.measurable }, simp only [← smul_eq_mul, ← set_integral_const, nnreal.val_eq_coe, is_R_or_C.coe_real_eq_id, id.def], refine set_integral_mono_ae hfint.abs.integrable_on _ _, { refine ⟨ae_strongly_measurable_const, lt_of_le_of_lt _ (integrable_condexp.integrable_on : integrable_on (μ[f | m]) {x | ↑R < |μ[f | m] x|} μ).2⟩, refine set_lintegral_mono (measurable.nnnorm _).coe_nnreal_ennreal (strongly_measurable_condexp.mono hnm).measurable.nnnorm.coe_nnreal_ennreal (λ x hx, _), { exact measurable_const }, { rw [ennreal.coe_le_coe, real.nnnorm_of_nonneg R.coe_nonneg], exact subtype.mk_le_mk.2 (le_of_lt hx) } }, { exact hbdd }, end /-- Given a integrable function `g`, the conditional expectations of `g` with respect to a sequence of sub-σ-algebras is uniformly integrable. -/ lemma integrable.uniform_integrable_condexp {ι : Type*} [is_finite_measure μ] {g : α → ℝ} (hint : integrable g μ) {ℱ : ι → measurable_space α} (hℱ : ∀ i, ℱ i ≤ m0) : uniform_integrable (λ i, μ[g | ℱ i]) 1 μ := begin have hmeas : ∀ n, ∀ C, measurable_set {x | C ≤ ∥μ[g | ℱ n] x∥₊} := λ n C, measurable_set_le measurable_const (strongly_measurable_condexp.mono (hℱ n)).measurable.nnnorm, have hg : mem_ℒp g 1 μ := mem_ℒp_one_iff_integrable.2 hint, refine uniform_integrable_of le_rfl ennreal.one_ne_top (λ n, (strongly_measurable_condexp.mono (hℱ n)).ae_strongly_measurable) (λ ε hε, _), by_cases hne : snorm g 1 μ = 0, { rw snorm_eq_zero_iff hg.1 one_ne_zero at hne, refine ⟨0, λ n, (le_of_eq $ (snorm_eq_zero_iff ((strongly_measurable_condexp.mono (hℱ n)).ae_strongly_measurable.indicator (hmeas n 0)) one_ne_zero).2 _).trans (zero_le _)⟩, filter_upwards [@condexp_congr_ae _ _ _ _ _ (ℱ n) m0 μ _ _ hne] with x hx, simp only [zero_le', set.set_of_true, set.indicator_univ, pi.zero_apply, hx, condexp_zero] }, obtain ⟨δ, hδ, h⟩ := hg.snorm_indicator_le μ le_rfl ennreal.one_ne_top hε, set C : ℝ≥0 := ⟨δ, hδ.le⟩⁻¹ * (snorm g 1 μ).to_nnreal with hC, have hCpos : 0 < C := mul_pos (nnreal.inv_pos.2 hδ) (ennreal.to_nnreal_pos hne hg.snorm_lt_top.ne), have : ∀ n, μ {x : α | C ≤ ∥μ[g | ℱ n] x∥₊} ≤ ennreal.of_real δ, { intro n, have := mul_meas_ge_le_pow_snorm' μ one_ne_zero ennreal.one_ne_top ((@strongly_measurable_condexp _ _ _ _ _ (ℱ n) _ μ g).mono (hℱ n)).ae_strongly_measurable C, rw [ennreal.one_to_real, ennreal.rpow_one, ennreal.rpow_one, mul_comm, ← ennreal.le_div_iff_mul_le (or.inl (ennreal.coe_ne_zero.2 hCpos.ne.symm)) (or.inl ennreal.coe_lt_top.ne)] at this, simp_rw [ennreal.coe_le_coe] at this, refine this.trans _, rw [ennreal.div_le_iff_le_mul (or.inl (ennreal.coe_ne_zero.2 hCpos.ne.symm)) (or.inl ennreal.coe_lt_top.ne), hC, nonneg.inv_mk, ennreal.coe_mul, ennreal.coe_to_nnreal hg.snorm_lt_top.ne, ← mul_assoc, ← ennreal.of_real_eq_coe_nnreal, ← ennreal.of_real_mul hδ.le, mul_inv_cancel hδ.ne.symm, ennreal.of_real_one, one_mul], exact snorm_one_condexp_le_snorm _ }, refine ⟨C, λ n, le_trans _ (h {x : α | C ≤ ∥μ[g | ℱ n] x∥₊} (hmeas n C) (this n))⟩, have hmeasℱ : measurable_set[ℱ n] {x : α | C ≤ ∥μ[g | ℱ n] x∥₊} := @measurable_set_le _ _ _ _ _ (ℱ n) _ _ _ _ _ measurable_const (@measurable.nnnorm _ _ _ _ _ (ℱ n) _ strongly_measurable_condexp.measurable), rw ← snorm_congr_ae (condexp_indicator hint hmeasℱ), exact snorm_one_condexp_le_snorm _, end section pull_out -- TODO: this section could be generalized beyond multiplication, to any bounded bilinear map. /-- Auxiliary lemma for `condexp_measurable_mul`. -/ lemma condexp_strongly_measurable_simple_func_mul (hm : m ≤ m0) (f : @simple_func α m ℝ) {g : α → ℝ} (hg : integrable g μ) : μ[f * g | m] =ᵐ[μ] f * μ[g | m] := begin have : ∀ s c (f : α → ℝ), set.indicator s (function.const α c) * f = s.indicator (c • f), { intros s c f, ext1 x, by_cases hx : x ∈ s, { simp only [hx, pi.mul_apply, set.indicator_of_mem, pi.smul_apply, algebra.id.smul_eq_mul] }, { simp only [hx, pi.mul_apply, set.indicator_of_not_mem, not_false_iff, zero_mul], }, }, refine @simple_func.induction _ _ m _ _ (λ c s hs, _) (λ g₁ g₂ h_disj h_eq₁ h_eq₂, _) f, { simp only [simple_func.const_zero, simple_func.coe_piecewise, simple_func.coe_const, simple_func.coe_zero, set.piecewise_eq_indicator], rw [this, this], refine (condexp_indicator (hg.smul c) hs).trans _, filter_upwards [@condexp_smul α ℝ ℝ _ _ _ _ _ m m0 μ c g] with x hx, classical, simp_rw [set.indicator_apply, hx], }, { have h_add := @simple_func.coe_add _ _ m _ g₁ g₂, calc μ[⇑(g₁ + g₂) * g|m] =ᵐ[μ] μ[(⇑g₁ + ⇑g₂) * g|m] : by { refine condexp_congr_ae (eventually_eq.mul _ eventually_eq.rfl), rw h_add, } ... =ᵐ[μ] μ[⇑g₁ * g|m] + μ[⇑g₂ * g|m] : by { rw add_mul, exact condexp_add (hg.simple_func_mul' hm _) (hg.simple_func_mul' hm _), } ... =ᵐ[μ] ⇑g₁ * μ[g|m] + ⇑g₂ * μ[g|m] : eventually_eq.add h_eq₁ h_eq₂ ... =ᵐ[μ] ⇑(g₁ + g₂) * μ[g|m] : by rw [h_add, add_mul], }, end lemma condexp_strongly_measurable_mul_of_bound (hm : m ≤ m0) [is_finite_measure μ] {f g : α → ℝ} (hf : strongly_measurable[m] f) (hg : integrable g μ) (c : ℝ) (hf_bound : ∀ᵐ x ∂μ, ∥f x∥ ≤ c) : μ[f * g | m] =ᵐ[μ] f * μ[g | m] := begin let fs := hf.approx_bounded c, have hfs_tendsto : ∀ᵐ x ∂μ, tendsto (λ n, fs n x) at_top (𝓝 (f x)), from hf.tendsto_approx_bounded_ae hf_bound, by_cases hμ : μ = 0, { simp only [hμ, ae_zero], }, haveI : μ.ae.ne_bot, by simp only [hμ, ae_ne_bot, ne.def, not_false_iff], have hc : 0 ≤ c, { have h_exists : ∃ x, ∥f x∥ ≤ c := eventually.exists hf_bound, exact (norm_nonneg _).trans h_exists.some_spec, }, have hfs_bound : ∀ n x, ∥fs n x∥ ≤ c := hf.norm_approx_bounded_le hc, have hn_eq : ∀ n, μ[fs n * g | m] =ᵐ[μ] fs n * μ[g | m], from λ n, condexp_strongly_measurable_simple_func_mul hm _ hg, have : μ[f * μ[g|m]|m] = f * μ[g|m], { refine condexp_of_strongly_measurable hm (hf.mul strongly_measurable_condexp) _, exact integrable_condexp.bdd_mul' ((hf.mono hm).ae_strongly_measurable) hf_bound, }, rw ← this, refine tendsto_condexp_unique (λ n x, fs n x * g x) (λ n x, fs n x * μ[g|m] x) (f * g) (f * μ[g|m]) _ _ _ _ (λ x, c * ∥g x∥) _ (λ x, c * ∥μ[g|m] x∥) _ _ _ _, { exact λ n, hg.bdd_mul' ((simple_func.strongly_measurable (fs n)).mono hm).ae_strongly_measurable (eventually_of_forall (hfs_bound n)), }, { exact λ n, integrable_condexp.bdd_mul' ((simple_func.strongly_measurable (fs n)).mono hm).ae_strongly_measurable (eventually_of_forall (hfs_bound n)), }, { filter_upwards [hfs_tendsto] with x hx, rw pi.mul_apply, exact tendsto.mul hx tendsto_const_nhds, }, { filter_upwards [hfs_tendsto] with x hx, rw pi.mul_apply, exact tendsto.mul hx tendsto_const_nhds, }, { exact hg.norm.const_mul c, }, { exact integrable_condexp.norm.const_mul c, }, { refine λ n, eventually_of_forall (λ x, _), exact (norm_mul_le _ _).trans (mul_le_mul_of_nonneg_right (hfs_bound n x) (norm_nonneg _)), }, { refine λ n, eventually_of_forall (λ x, _), exact (norm_mul_le _ _).trans (mul_le_mul_of_nonneg_right (hfs_bound n x) (norm_nonneg _)), }, { intros n, simp_rw ← pi.mul_apply, refine (condexp_strongly_measurable_simple_func_mul hm _ hg).trans _, rw condexp_of_strongly_measurable hm ((simple_func.strongly_measurable _).mul strongly_measurable_condexp) _, { apply_instance, }, { apply_instance, }, exact integrable_condexp.bdd_mul' ((simple_func.strongly_measurable (fs n)).mono hm).ae_strongly_measurable (eventually_of_forall (hfs_bound n)), }, end lemma condexp_strongly_measurable_mul_of_bound₀ (hm : m ≤ m0) [is_finite_measure μ] {f g : α → ℝ} (hf : ae_strongly_measurable' m f μ) (hg : integrable g μ) (c : ℝ) (hf_bound : ∀ᵐ x ∂μ, ∥f x∥ ≤ c) : μ[f * g | m] =ᵐ[μ] f * μ[g | m] := begin have : μ[f * g | m] =ᵐ[μ] μ[hf.mk f * g | m], from condexp_congr_ae (eventually_eq.mul hf.ae_eq_mk eventually_eq.rfl), refine this.trans _, have : f * μ[g | m] =ᵐ[μ] hf.mk f * μ[g | m] := eventually_eq.mul hf.ae_eq_mk eventually_eq.rfl, refine eventually_eq.trans _ this.symm, refine condexp_strongly_measurable_mul_of_bound hm hf.strongly_measurable_mk hg c _, filter_upwards [hf_bound, hf.ae_eq_mk] with x hxc hx_eq, rw ← hx_eq, exact hxc, end /-- Pull-out property of the conditional expectation. -/ lemma condexp_strongly_measurable_mul {f g : α → ℝ} (hf : strongly_measurable[m] f) (hfg : integrable (f * g) μ) (hg : integrable g μ) : μ[f * g | m] =ᵐ[μ] f * μ[g | m] := begin by_cases hm : m ≤ m0, swap, { simp_rw condexp_of_not_le hm, rw mul_zero, }, by_cases hμm : sigma_finite (μ.trim hm), swap, { simp_rw condexp_of_not_sigma_finite hm hμm, rw mul_zero, }, haveI : sigma_finite (μ.trim hm) := hμm, obtain ⟨sets, sets_prop, h_univ⟩ := hf.exists_spanning_measurable_set_norm_le hm μ, simp_rw forall_and_distrib at sets_prop, obtain ⟨h_meas, h_finite, h_norm⟩ := sets_prop, suffices : ∀ n, ∀ᵐ x ∂μ, x ∈ sets n → μ[f * g|m] x = f x * μ[g|m] x, { rw ← ae_all_iff at this, filter_upwards [this] with x hx, rw pi.mul_apply, obtain ⟨i, hi⟩ : ∃ i, x ∈ sets i, { have h_mem : x ∈ ⋃ i, sets i, { rw h_univ, exact set.mem_univ _, }, simpa using h_mem, }, exact hx i hi, }, refine λ n, ae_imp_of_ae_restrict _, suffices : (μ.restrict (sets n))[f * g | m] =ᵐ[μ.restrict (sets n)] f * (μ.restrict (sets n))[g | m], { simp_rw ← pi.mul_apply, refine (condexp_restrict_ae_eq_restrict hm (h_meas n) hfg).symm.trans _, exact this.trans (eventually_eq.rfl.mul (condexp_restrict_ae_eq_restrict hm (h_meas n) hg)), }, suffices : (μ.restrict (sets n))[((sets n).indicator f) * g | m] =ᵐ[μ.restrict (sets n)] ((sets n).indicator f) * (μ.restrict (sets n))[g | m], { refine eventually_eq.trans _ (this.trans _), { exact condexp_congr_ae ((indicator_ae_eq_restrict (hm _ (h_meas n))).symm.mul eventually_eq.rfl), }, { exact (indicator_ae_eq_restrict (hm _ (h_meas n))).mul eventually_eq.rfl, }, }, haveI : is_finite_measure (μ.restrict (sets n)), { constructor, rw measure.restrict_apply_univ, exact h_finite n, }, refine condexp_strongly_measurable_mul_of_bound hm (hf.indicator (h_meas n)) hg.integrable_on n _, refine eventually_of_forall (λ x, _), by_cases hxs : x ∈ sets n, { simp only [hxs, set.indicator_of_mem], exact h_norm n x hxs, }, { simp only [hxs, set.indicator_of_not_mem, not_false_iff, _root_.norm_zero, nat.cast_nonneg], }, end /-- Pull-out property of the conditional expectation. -/ lemma condexp_strongly_measurable_mul₀ {f g : α → ℝ} (hf : ae_strongly_measurable' m f μ) (hfg : integrable (f * g) μ) (hg : integrable g μ) : μ[f * g | m] =ᵐ[μ] f * μ[g | m] := begin have : μ[f * g | m] =ᵐ[μ] μ[hf.mk f * g | m], from condexp_congr_ae (eventually_eq.mul hf.ae_eq_mk eventually_eq.rfl), refine this.trans _, have : f * μ[g | m] =ᵐ[μ] hf.mk f * μ[g | m] := eventually_eq.mul hf.ae_eq_mk eventually_eq.rfl, refine eventually_eq.trans _ this.symm, refine condexp_strongly_measurable_mul hf.strongly_measurable_mk _ hg, refine (integrable_congr _).mp hfg, exact eventually_eq.mul hf.ae_eq_mk eventually_eq.rfl, end end pull_out end measure_theory
c100872341a86e1db315e241b0031cef939ce56e
94e33a31faa76775069b071adea97e86e218a8ee
/src/algebra/category/Ring/constructions.lean
d577bca1f06323b84c1eda30208a47d819fa2ea8
[ "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
7,791
lean
/- Copyright (c) 2021 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import category_theory.limits.shapes.pullbacks import ring_theory.tensor_product import algebra.category.Ring.limits import algebra.category.Ring.colimits import category_theory.limits.shapes.strict_initial import ring_theory.subring.basic import ring_theory.ideal.local_ring import category_theory.limits.preserves.limits /-! # Constructions of (co)limits in CommRing In this file we provide the explicit (co)cones for various (co)limits in `CommRing`, including * tensor product is the pushout * `Z` is the initial object * `0` is the strict terminal object * cartesian product is the product * `ring_hom.eq_locus` is the equalizer -/ universes u u' open category_theory category_theory.limits open_locale tensor_product namespace CommRing section pushout variables {R A B : CommRing.{u}} (f : R ⟶ A) (g : R ⟶ B) /-- The explicit cocone with tensor products as the fibered product in `CommRing`. -/ def pushout_cocone : limits.pushout_cocone f g := begin letI := ring_hom.to_algebra f, letI := ring_hom.to_algebra g, apply limits.pushout_cocone.mk, show CommRing, from CommRing.of (A ⊗[R] B), show A ⟶ _, from algebra.tensor_product.include_left.to_ring_hom, show B ⟶ _, from algebra.tensor_product.include_right.to_ring_hom, ext r, transitivity algebra_map R (A ⊗[R] B) r, { exact algebra.tensor_product.include_left.commutes r }, { exact (algebra.tensor_product.include_right.commutes r).symm } end @[simp] lemma pushout_cocone_inl : (pushout_cocone f g).inl = (by { letI := f.to_algebra, letI := g.to_algebra, exactI algebra.tensor_product.include_left.to_ring_hom }) := rfl @[simp] lemma pushout_cocone_inr : (pushout_cocone f g).inr = (by { letI := f.to_algebra, letI := g.to_algebra, exactI algebra.tensor_product.include_right.to_ring_hom }) := rfl @[simp] lemma pushout_cocone_X : (pushout_cocone f g).X = (by { letI := f.to_algebra, letI := g.to_algebra, exactI CommRing.of (A ⊗[R] B) }) := rfl /-- Verify that the `pushout_cocone` is indeed the colimit. -/ def pushout_cocone_is_colimit : limits.is_colimit (pushout_cocone f g) := limits.pushout_cocone.is_colimit_aux' _ (λ s, begin letI := ring_hom.to_algebra f, letI := ring_hom.to_algebra g, letI := ring_hom.to_algebra (f ≫ s.inl), let f' : A →ₐ[R] s.X := { commutes' := λ r, by { change s.inl.to_fun (f r) = (f ≫ s.inl) r, refl }, ..s.inl }, let g' : B →ₐ[R] s.X := { commutes' := λ r, by { change (g ≫ s.inr) r = (f ≫ s.inl) r, congr' 1, exact (s.ι.naturality limits.walking_span.hom.snd).trans (s.ι.naturality limits.walking_span.hom.fst).symm }, ..s.inr }, /- The factor map is a ⊗ b ↦ f(a) * g(b). -/ use alg_hom.to_ring_hom (algebra.tensor_product.product_map f' g'), simp only [pushout_cocone_inl, pushout_cocone_inr], split, { ext x, exact algebra.tensor_product.product_map_left_apply _ _ x, }, split, { ext x, exact algebra.tensor_product.product_map_right_apply _ _ x, }, intros h eq1 eq2, let h' : (A ⊗[R] B) →ₐ[R] s.X := { commutes' := λ r, by { change h ((f r) ⊗ₜ[R] 1) = s.inl (f r), rw ← eq1, simp }, ..h }, suffices : h' = algebra.tensor_product.product_map f' g', { ext x, change h' x = algebra.tensor_product.product_map f' g' x, rw this }, apply algebra.tensor_product.ext, intros a b, simp [← eq1, ← eq2, ← h.map_mul], end) end pushout section terminal /-- The trivial ring is the (strict) terminal object of `CommRing`. -/ def punit_is_terminal : is_terminal (CommRing.of.{u} punit) := begin apply_with is_terminal.of_unique { instances := ff }, tidy end instance CommRing_has_strict_terminal_objects : has_strict_terminal_objects CommRing.{u} := begin apply has_strict_terminal_objects_of_terminal_is_strict (CommRing.of punit), intros X f, refine ⟨⟨by tidy, by ext, _⟩⟩, ext, have e : (0 : X) = 1 := by { rw [← f.map_one, ← f.map_zero], congr }, replace e : 0 * x = 1 * x := congr_arg (λ a, a * x) e, rw [one_mul, zero_mul, ← f.map_zero] at e, exact e, end lemma subsingleton_of_is_terminal {X : CommRing} (hX : is_terminal X) : subsingleton X := (hX.unique_up_to_iso punit_is_terminal).CommRing_iso_to_ring_equiv.to_equiv .subsingleton_congr.mpr (show subsingleton punit, by apply_instance) /-- `ℤ` is the initial object of `CommRing`. -/ def Z_is_initial : is_initial (CommRing.of ℤ) := begin apply_with is_initial.of_unique { instances := ff }, exact λ R, ⟨⟨int.cast_ring_hom R⟩, λ a, a.ext_int _⟩, end end terminal section product variables (A B : CommRing.{u}) /-- The product in `CommRing` is the cartesian product. This is the binary fan. -/ @[simps X] def prod_fan : binary_fan A B := binary_fan.mk (CommRing.of_hom $ ring_hom.fst A B) (CommRing.of_hom $ ring_hom.snd A B) /-- The product in `CommRing` is the cartesian product. -/ def prod_fan_is_limit : is_limit (prod_fan A B) := { lift := λ c, ring_hom.prod (c.π.app ⟨walking_pair.left⟩) (c.π.app ⟨walking_pair.right⟩), fac' := λ c j, by { ext, rcases j with ⟨⟨⟩⟩; simpa only [binary_fan.π_app_left, binary_fan.π_app_right, comp_apply, ring_hom.prod_apply] }, uniq' := λ s m h, by { ext, { simpa using congr_hom (h ⟨walking_pair.left⟩) x }, { simpa using congr_hom (h ⟨walking_pair.right⟩) x } } } end product section equalizer variables {A B : CommRing.{u}} (f g : A ⟶ B) /-- The equalizer in `CommRing` is the equalizer as sets. This is the equalizer fork. -/ def equalizer_fork : fork f g := fork.of_ι (CommRing.of_hom (ring_hom.eq_locus f g).subtype) (by { ext ⟨x, e⟩, simpa using e }) /-- The equalizer in `CommRing` is the equalizer as sets. -/ def equalizer_fork_is_limit : is_limit (equalizer_fork f g) := begin fapply fork.is_limit.mk', intro s, use s.ι.cod_restrict _ (λ x, (concrete_category.congr_hom s.condition x : _)), split, { ext, refl }, { intros m hm, ext x, exact concrete_category.congr_hom hm x } end instance : is_local_ring_hom (equalizer_fork f g).ι := begin constructor, rintros ⟨a, (h₁ : _ = _)⟩ (⟨⟨x,y,h₃,h₄⟩,(rfl : x = _)⟩ : is_unit a), have : y ∈ ring_hom.eq_locus f g, { apply (f.is_unit_map ⟨⟨x,y,h₃,h₄⟩,rfl⟩ : is_unit (f x)).mul_left_inj.mp, conv_rhs { rw h₁ }, rw [← f.map_mul, ← g.map_mul, h₄, f.map_one, g.map_one] }, rw is_unit_iff_exists_inv, exact ⟨⟨y, this⟩, subtype.eq h₃⟩, end instance equalizer_ι_is_local_ring_hom (F : walking_parallel_pair ⥤ CommRing.{u}) : is_local_ring_hom (limit.π F walking_parallel_pair.zero) := begin have := lim_map_π (diagram_iso_parallel_pair F).hom walking_parallel_pair.zero, rw ← is_iso.comp_inv_eq at this, rw ← this, rw ← limit.iso_limit_cone_hom_π ⟨_, equalizer_fork_is_limit (F.map walking_parallel_pair_hom.left) (F.map walking_parallel_pair_hom.right)⟩ walking_parallel_pair.zero, change is_local_ring_hom ((lim.map _ ≫ _ ≫ (equalizer_fork _ _).ι) ≫ _), apply_instance end open category_theory.limits.walking_parallel_pair opposite open category_theory.limits.walking_parallel_pair_hom instance equalizer_ι_is_local_ring_hom' (F : walking_parallel_pairᵒᵖ ⥤ CommRing.{u}) : is_local_ring_hom (limit.π F (opposite.op walking_parallel_pair.one)) := begin have : _ = limit.π F (walking_parallel_pair_op_equiv.functor.obj _) := (limit.iso_limit_cone_inv_π ⟨_, is_limit.whisker_equivalence (limit.is_limit F) walking_parallel_pair_op_equiv⟩ walking_parallel_pair.zero : _), erw ← this, apply_instance end end equalizer end CommRing
199295d1ee4a5b2b52b53917e9e8ea12b021c91b
f47872278edfa65030d6cd0604480581b09ae4b5
/src/ordered/between.lean
4c37c96653a1162c256927538a8fc19fb553bd70
[ "MIT" ]
permissive
ocornoc/geodude
c822c494d9ed5d6dd2efa434cbaa5e0e42c22691
e63c87db67f1686c902e9bcd1863e74e1a29457f
refs/heads/master
1,681,951,483,388
1,620,592,363,000
1,620,595,412,000
287,442,904
0
0
null
null
null
null
UTF-8
Lean
false
false
15,404
lean
/- Copyright 2020 Grayson Burton License available in the LICENSE file. -/ import data.set.basic tactic private lemma {u} set_ins_comm {α : Type u} (x y : α) : ({x, y} : set α) = {y, x} := by simp [set.insert_def, or.comm] /-- A strict betweenness relation. -/ class {u} has_betweenness (α : Type u) : Type u := (between : α → α → α → Prop) (between_extend : ∀ {p q}, p ≠ q → ∃ r, between p q r) (between_irrefl : ∀ {p q r}, between p q r → p ≠ r) (between_symm : ∀ {p q r}, between p q r → between r q p) (between_not_rotate : ∀ {p q r}, between p q r → ¬ between r p q) /-- `between P Q R` means "`Q` lies in the line segment `PR` and isnt an endpoint." -/ def {u} between {α : Type u} [has_betweenness α] := @has_betweenness.between α _ namespace between section universe u parameters {α : Type u} [has_betweenness α] /-- For any two distinct points `P`,`Q` there is another point `R` such that `Q` is between `P` and `R`. -/ lemma extend {p q : α} : p ≠ q → ∃ r, between p q r := has_betweenness.between_extend lemma eq_of_no_extension {p q : α} : (¬ ∃ r, between p q r) → p = q := by contrapose!; exact extend lemma eq_of_no_extension' {p q : α} : (∀ r, ¬ between p q r) → p = q := by contrapose!; exact extend /-- If `Q` is between `P` and `R`, then `P ≠ R`. -/ protected lemma irrefl {p q r : α} : between p q r → p ≠ r := has_betweenness.between_irrefl lemma not_between_of_eq {p r : α} (q : α) : p = r → ¬ between p q r := by contrapose!; exact between.irrefl protected lemma symm {p q r : α} : between p q r → between r q p := has_betweenness.between_symm /-- `Q` is between `P` and `R` iff it is between `R` and `P`. -/ lemma symm_iff (p q r : α) : between p q r ↔ between r q p := iff.intro between.symm between.symm /-- If `Q` is between `P` and `R`, then `P` isn't between `R` and `Q`. -/ lemma not_rotate {p q r : α} : between p q r → ¬ between r p q := has_betweenness.between_not_rotate /-- There is no point between `P` and itself. -/ lemma irrefl' (p q : α) : ¬ between p q p := not_between_of_eq q rfl /-- No point is between itself and another point. -/ theorem not_self_between (p q : α) : ¬ between p p q := λ h, h.not_rotate h.symm /-- No point is between itself and another point. -/ theorem not_between_self (p q : α) : ¬ between p q q := λ h, not_self_between _ _ h.symm end end between section universe u parameters {α : Type u} [has_betweenness α] /-- A line segment excluding the endpoints -/ def segment (x y : α) : set α := {z | between x z y} /-- A line segment including the endpoints -/ def interval (x y : α) : set α := segment x y ∪ {x, y} /-- The ray (or half line) from `x` to `y`. Excludes `x`. -/ def ray (x y : α) : set α := {z | between z y x} ∪ segment x y ∪ {y} /-- A line through `x` and `y` -/ def line (x y : α) : set α := interval x y ∪ ray x y ∪ ray y x /-- `collinear P Q R` means "There is a line with `p`, `r`, and `q` on it." -/ def collinear (p q r : α) : Prop := ∃ v₀ v₁, p ∈ line v₀ v₁ ∧ q ∈ line v₀ v₁ ∧ r ∈ line v₀ v₁ end section universe u parameters {α : Type u} [has_betweenness α] namespace segment @[simp] lemma seg_def (x y : α) : segment x y = {z | between x z y} := rfl theorem empty_of_same_ends (x : α) : segment x x = ∅ := by rw set.eq_empty_iff_forall_not_mem; apply between.irrefl' theorem end_not_mem_seg_left (x y : α) : x ∉ segment x y := between.not_self_between _ _ theorem end_not_mem_seg_right (x y : α) : y ∉ segment x y := between.not_between_self _ _ theorem swap (x y : α) : segment x y = segment y x := by dsimp; congr; funext; rw between.symm_iff lemma symm {p q r : α} (h : r ∈ segment p q) : r ∈ segment q p := by rwa swap at h theorem subs_intrv (x y : α) : segment x y ⊆ interval x y := λ _, or.inl theorem ssubs_intrv (x y : α) : segment x y ⊂ interval x y := begin rw set.ssubset_iff_subset_ne, refine ⟨subs_intrv _ _, λ h₁, _⟩, replace h₁ := eq_iff_iff.mp (congr_fun h₁ x), apply end_not_mem_seg_left x y, exact h₁.mpr (or.inr $ or.inl rfl) end theorem seg_subs_ray (x y : α) : segment x y ⊆ ray x y := λ _, or.inl ∘ or.inr theorem seg_ssubs_ray (x y : α) : segment x y ⊂ ray x y := begin rw set.ssubset_iff_subset_ne, refine ⟨seg_subs_ray _ _, λ h₁, _⟩, replace h₁ := eq_iff_iff.mp (congr_fun h₁ y), apply end_not_mem_seg_right x y, exact h₁.mpr (or.inr rfl) end theorem seg_subs_line (x y : α) : segment x y ⊆ line x y := λ _, or.inl ∘ or.inl ∘ or.inl theorem seg_ssubs_line (x y : α) : segment x y ⊂ line x y := begin rw set.ssubset_iff_subset_ne, refine ⟨seg_subs_line _ _, λ h₁, _⟩, replace h₁ := eq_iff_iff.mp (congr_fun h₁ y), apply end_not_mem_seg_right x y, exact h₁.mpr (or.inl $ or.inr $ or.inr rfl) end theorem ne_ends_of_mem {x y : α} (h : ∃ z, z ∈ segment x y) : x ≠ y := begin intro he, induction he, cases h with _ h, rw empty_of_same_ends at h, exact h end theorem ne_left_of_mem {x y z : α} (h : x ∈ segment y z) : x ≠ y := λ he, by rw he at h; exact (end_not_mem_seg_left _ _).elim h theorem ne_right_of_mem {x y z : α} (h : x ∈ segment y z) : x ≠ z := λ he, by rw he at h; exact (end_not_mem_seg_right _ _).elim h theorem not_in_rotate {x y z : α} : z ∈ segment x y → x ∉ segment y z := between.not_rotate theorem not_in_rotate' {x y z : α} : z ∈ segment x y → x ∉ segment z y := by rw swap z y; exact not_in_rotate end segment namespace interval @[simp] lemma intrv_def (x y : α) : interval x y = {z | between x z y ∨ z = x ∨ z = y} := rfl @[simp] lemma intrv_def' (x y : α) : interval x y = segment x y ∪ {x, y} := rfl theorem seg_subs (x y : α) : segment x y ⊆ interval x y := segment.subs_intrv _ _ @[simp] theorem single_self (x : α) : interval x x = {x} := begin rw intrv_def, congr, funext, rw or_self, apply or_eq_of_eq_false_left, rw eq_false, apply between.irrefl' end theorem end_mem_intrv_left (x y : α) : x ∈ interval x y := or.inr $ or.inl rfl theorem end_mem_intrv_right (x y : α) : y ∈ interval x y := or.inr $ or.inr rfl theorem seg_ssubs (x y : α) : segment x y ⊂ interval x y := segment.ssubs_intrv _ _ theorem swap (x y : α) : interval x y = interval y x := by simp only [intrv_def', segment.swap, set_ins_comm] theorem eq_of_mem_same {p q : α} (h : p ∈ interval q q) : p = q := by rw single_self at h; exact h theorem eq_iff_mem_same (p q : α) : p ∈ interval q q ↔ p = q := ⟨eq_of_mem_same, λ _, by simpa⟩ end interval namespace ray @[simp] lemma ray_def (x y : α) : ray x y = {z | between z y x} ∪ segment x y ∪ {y} := rfl @[simp] theorem single_self (x : α) : ray x x = {x} := begin rw ray_def, funext, apply or_eq_of_eq_false_left, apply eq_false_intro, change ¬ (_ ∨ _), push_neg, exact ⟨between.not_between_self _ _, between.irrefl' _ _⟩ end lemma end_not_mem_ray_left_of_ne {x y : α} : x ≠ y → x ∉ ray x y := begin intro h, rw ray_def, change ¬ ((_ ∨ _) ∨ _), push_neg, exact ⟨⟨between.irrefl' _ _, segment.end_not_mem_seg_left _ _⟩, h⟩ end lemma ne_of_end_not_mem_ray_left {x y : α} : x ∉ ray x y → x ≠ y := begin intro h, rw ray_def at h, change ¬ ((_ ∨ _) ∨ _) at h, push_neg at h, exact h.right end theorem end_not_mem_ray_left_iff_ne (x y : α) : x ≠ y ↔ x ∉ ray x y := iff.intro end_not_mem_ray_left_of_ne ne_of_end_not_mem_ray_left theorem end_mem_ray_left_iff_eq (x y : α) : x = y ↔ x ∈ ray x y := begin classical, exact not_iff_not.mp (end_not_mem_ray_left_iff_ne _ _) end theorem end_mem_ray_right (x y : α) : y ∈ ray x y := or.inr rfl theorem seg_subs (x y : α) : segment x y ⊆ ray x y := segment.seg_subs_ray _ _ theorem seg_ssubs (x y : α) : segment x y ⊂ ray x y := segment.seg_ssubs_ray _ _ theorem eq_of_mem_same {x y : α} (h : x ∈ ray y y) : x = y := by rw single_self at h; exact h @[simp] theorem eq_iff_mem_same (x y : α) : x ∈ ray y y ↔ x = y := ⟨eq_of_mem_same, λ h, by simp [h]⟩ end ray namespace line @[simp] theorem line_def (x y : α) : line x y = interval x y ∪ ray x y ∪ ray y x := rfl @[simp] theorem single_self (x : α) : line x x = {x} := by simp theorem swap (x y : α) : line x y = line y x := by rw [line_def, interval.swap, set.union_assoc, set.union_comm (ray _ _), ←set.union_assoc, line_def] theorem ray_subs (x y : α) : ray x y ⊆ line x y := λ _, or.inl ∘ or.inr theorem ray_subs' (x y : α) : ray y x ⊆ line x y := λ _, or.inr theorem seg_subs (x y : α) : segment x y ⊆ line x y := segment.seg_subs_line x y theorem seg_ssubs (x y : α) : segment x y ⊂ line x y := segment.seg_ssubs_line x y theorem intrv_subs (x y : α) : interval x y ⊆ line x y := λ _, or.inl ∘ or.inl theorem end_mem_line_left (x y : α) : x ∈ line x y := or.inr $ ray.end_mem_ray_right _ _ theorem end_mem_line_right (x y : α) : y ∈ line x y := or.inl $ or.inr $ ray.end_mem_ray_right _ _ theorem ray_ssubs_of_ne {x y : α} (h : x ≠ y) : ray x y ⊂ line x y := begin apply set.ssubset_iff_subset_ne.mpr ⟨ray_subs _ _, λ h₁, _⟩, rw [ray.end_not_mem_ray_left_iff_ne, h₁] at h, exact h (end_mem_line_left _ _) end theorem ray_ssubs_of_ne' {x y : α} (h : x ≠ y) : ray y x ⊂ line x y := by rw swap; exact ray_ssubs_of_ne h.symm theorem rotate_of_ne {x y z : α} : x ≠ z → x ∈ line y z → y ∈ line x z := by finish using between.symm_iff @[simp] theorem rotate_iff_of_ne {x y z : α} : x ≠ z → y ≠ z → (x ∈ line y z ↔ y ∈ line x z) := λ h₁ h₂, ⟨rotate_of_ne h₁, rotate_of_ne h₂⟩ theorem eq_of_mem_same {x y : α} (h : x ∈ line y y) : x = y := begin rcases h with ⟨h | h⟩ | h, { exact interval.eq_of_mem_same h }, { exact ray.eq_of_mem_same h }, { exact ray.eq_of_mem_same h } end @[simp] theorem eq_iff_mem_same (x y : α) : x ∈ line y y ↔ x = y := ⟨eq_of_mem_same, λ h, by simp [h]⟩ end line namespace collinear @[simp] theorem collin_def (p q r : α) : collinear p q r = ∃ v₀ v₁ : α, p ∈ line v₀ v₁ ∧ q ∈ line v₀ v₁ ∧ r ∈ line v₀ v₁ := rfl theorem of_left (p q : α) : collinear p p q := ⟨p, q, by simp⟩ theorem of_right (p q : α) : collinear p q q := ⟨p, q, by simp⟩ theorem of_ends (p q : α) : collinear p q p := ⟨p, q, by simp⟩ theorem of_same (p : α) : collinear p p p := of_left p p theorem swap_iff (p q r : α) : collinear p q r ↔ collinear q p r := begin refine ⟨λ h, _, λ h, _⟩, all_goals { rcases h with ⟨_, _, h⟩, rw [←and.assoc, @and.comm (_ ∈ _), and.assoc] at h, exact ⟨_, _, h⟩ } end theorem swap {p q r : α} : collinear p q r → collinear q p r := (swap_iff p q r).mp theorem mem_of_mem_line {p q r : α} (h : p ∈ line q r) : collinear q r p := ⟨q, r, by simp, by simp, h⟩ theorem mem_of_mem_ray {p q r : α} (h : p ∈ ray q r) : collinear q r p := mem_of_mem_line $ line.ray_subs _ _ h theorem mem_of_mem_ray' {p q r : α} (h : p ∈ ray r q) : collinear q r p := mem_of_mem_line $ line.ray_subs' _ _ h theorem mem_of_mem_intrv {p q r : α} (h : p ∈ interval q r) : collinear q r p := mem_of_mem_line $ line.intrv_subs _ _ h theorem rotate' {p q r : α} (h : collinear p q r) : collinear r p q := begin rcases h with ⟨_, _, h⟩, rw [@and.comm (_ ∈ _), and.assoc, @and.comm (_ ∈ _), and.assoc] at h, exact ⟨_, _, h⟩ end theorem rotate {p q r : α} : collinear p q r → collinear q r p := rotate' ∘ rotate' theorem rotate_iff {p q r : α} : collinear p q r ↔ collinear q r p := ⟨rotate, rotate'⟩ theorem swap_iff' (p q r : α) : collinear p q r ↔ collinear p r q := by rw [rotate_iff, swap_iff _ r q, rotate_iff] theorem of_left' (p q : α) : collinear p p q := (of_ends _ _).rotate' theorem ex_collinear_of_mem {p : α} {s : set α} (h : p ∈ s) : ∃ q r ∈ s, collinear p q r := ⟨_, _, h, h, of_same _⟩ @[simp] theorem none_collinear_iff_empty (s : set α) : (∀ p q r ∈ s, ¬ collinear p q r) ↔ s = ∅ := begin refine ⟨λ h, set.eq_empty_iff_forall_not_mem.mpr $ λ _, _, λ h _ _ _ hp, _⟩, { intro hx, exact h _ _ _ hx hx hx (of_same _) }, { rw h at hp, exact (set.not_mem_empty _).elim hp } end @[simp] theorem none_collinear_iff_empty_2 (s : set α) : (∀ p q ∈ s, ¬ collinear p p q) ↔ s = ∅ := begin refine ⟨λ h, set.eq_empty_iff_forall_not_mem.mpr $ λ _, _, λ h _ _ _ hp, _⟩, { intro hx, exact h _ _ hx hx (of_same _) }, { rw h at hp, exact (set.not_mem_empty _).elim hp } end @[simp] theorem none_collinear_iff_empty_2' (s : set α) : (∀ p q ∈ s, ¬ collinear p q q) ↔ s = ∅ := begin refine ⟨λ h, set.eq_empty_iff_forall_not_mem.mpr $ λ _, _, λ h _ _ _ hp, _⟩, { intro hx, exact h _ _ hx hx (of_same _) }, { rw h at hp, exact (set.not_mem_empty _).elim hp } end @[simp] theorem none_collinear_iff_empty_2'' (s : set α) : (∀ p q ∈ s, ¬ collinear p q p) ↔ s = ∅ := begin refine ⟨λ h, set.eq_empty_iff_forall_not_mem.mpr $ λ _, _, λ h _ _ _ hp, _⟩, { intro hx, exact h _ _ hx hx (of_same _) }, { rw h at hp, exact (set.not_mem_empty _).elim hp } end @[simp] theorem none_collinear_iff_empty_fixed_1 (s : set α) (p : α) : (∀ q r ∈ s, ¬ collinear p q r) ↔ s = ∅ := begin refine ⟨λ h, set.eq_empty_iff_forall_not_mem.mpr $ λ _, _, λ h _ _ _ hp, _⟩, { intro hx, exact h _ _ hx hx (of_right _ _) }, { rw h at hp, exact (set.not_mem_empty _).elim hp } end @[simp] theorem none_collinear_iff_empty_fixed_1' (s : set α) (p : α) : (∀ q r ∈ s, ¬ collinear q p r) ↔ s = ∅ := begin refine ⟨λ h, set.eq_empty_iff_forall_not_mem.mpr $ λ _, _, λ h _ _ _ hp, _⟩, { intro hx, exact h _ _ hx hx (of_ends _ _) }, { rw h at hp, exact (set.not_mem_empty _).elim hp } end @[simp] theorem none_collinear_iff_empty_fixed_1'' (s : set α) (p : α) : (∀ q r ∈ s, ¬ collinear q r p) ↔ s = ∅ := begin refine ⟨λ h, set.eq_empty_iff_forall_not_mem.mpr $ λ _, _, λ h _ _ _ hp, _⟩, { intro hx, exact h _ _ hx hx (of_left _ _) }, { rw h at hp, exact (set.not_mem_empty _).elim hp } end @[simp] theorem none_collinear_iff_empty_fixed_2 (s : set α) (p q : α) (hq : q ∈ s) : (∀ r ∈ s, ¬ collinear p q r) ↔ s = ∅ := begin refine ⟨λ h, set.eq_empty_iff_forall_not_mem.mpr $ λ _, _, λ h _ hp, _⟩, { intro hx, exact h _ hq (of_right _ _) }, { rw h at hp, exact (set.not_mem_empty _).elim hp } end @[simp] theorem none_collinear_iff_empty_fixed_2' (s : set α) (p q : α) (hq : q ∈ s) : (∀ r ∈ s, ¬ collinear p r q) ↔ s = ∅ := begin refine ⟨λ h, set.eq_empty_iff_forall_not_mem.mpr $ λ _, _, λ h _ hp, _⟩, { intro hx, exact h _ hq (of_right _ _) }, { rw h at hp, exact (set.not_mem_empty _).elim hp } end @[simp] theorem none_collinear_iff_empty_fixed_2'' (s : set α) (p q : α) (hq : q ∈ s) : (∀ r ∈ s, ¬ collinear r p q) ↔ s = ∅ := begin refine ⟨λ h, set.eq_empty_iff_forall_not_mem.mpr $ λ _, _, λ h _ hp, _⟩, { intro hx, exact h _ hq (of_ends _ _) }, { rw h at hp, exact (set.not_mem_empty _).elim hp } end end collinear end
7ea970a55e964327d2b921586297958d508a204a
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/stage0/src/Lean/Elab/PreDefinition/WF/Eqns.lean
df87a094b3676c24459b108651691168c0e7e5cf
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
9,991
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Tactic.Rewrite import Lean.Meta.Tactic.Split import Lean.Elab.PreDefinition.Basic import Lean.Elab.PreDefinition.Eqns namespace Lean.Elab.WF open Meta open Eqns structure EqnInfo extends EqnInfoCore where declNames : Array Name declNameNonRec : Name fixedPrefixSize : Nat deriving Inhabited private partial def deltaLHSUntilFix (mvarId : MVarId) : MetaM MVarId := mvarId.withContext do let target ← mvarId.getType' let some (_, lhs, _) := target.eq? | throwTacticEx `deltaLHSUntilFix mvarId "equality expected" if lhs.isAppOf ``WellFounded.fix then return mvarId else deltaLHSUntilFix (← deltaLHS mvarId) private def rwFixEq (mvarId : MVarId) : MetaM MVarId := mvarId.withContext do let target ← mvarId.getType' let some (_, lhs, rhs) := target.eq? | unreachable! let h := mkAppN (mkConst ``WellFounded.fix_eq lhs.getAppFn.constLevels!) lhs.getAppArgs let some (_, _, lhsNew) := (← inferType h).eq? | unreachable! let targetNew ← mkEq lhsNew rhs let mvarNew ← mkFreshExprSyntheticOpaqueMVar targetNew mvarId.assign (← mkEqTrans h mvarNew) return mvarNew.mvarId! private def hasWellFoundedFix (e : Expr) : Bool := Option.isSome <| e.find? (·.isConstOf ``WellFounded.fix) /-- Helper function for decoding the packed argument for a `WellFounded.fix` application. Recall that we use `PSum` and `PSigma` for packing the arguments of mutually recursive nary functions. -/ private partial def decodePackedArg? (info : EqnInfo) (e : Expr) : Option (Name × Array Expr) := do if info.declNames.size == 1 then let args := decodePSigma e #[] return (info.declNames[0]!, args) else decodePSum? e 0 where decodePSum? (e : Expr) (i : Nat) : Option (Name × Array Expr) := do if e.isAppOfArity ``PSum.inl 3 then decodePSum? e.appArg! i else if e.isAppOfArity ``PSum.inr 3 then decodePSum? e.appArg! (i+1) else guard (i < info.declNames.size) return (info.declNames[i]!, decodePSigma e #[]) decodePSigma (e : Expr) (acc : Array Expr) : Array Expr := /- TODO: check arity of the given function. If it takes a PSigma as the last argument, this function will produce incorrect results. -/ if e.isAppOfArity ``PSigma.mk 4 then decodePSigma e.appArg! (acc.push e.appFn!.appArg!) else acc.push e /-- Try to fold `WellFounded.fix` applications that represent recursive applications of the functions in `info.declNames`. We need that to make sure `simpMatchWF?` succeeds at goals such as ```lean ... h : g x = 0 ... |- (match (WellFounded.fix ...) with | ...) = ... ``` where `WellFounded.fix ...` can be folded back to `g x`. -/ private def tryToFoldWellFoundedFix (info : EqnInfo) (us : List Level) (fixedPrefix : Array Expr) (e : Expr) : MetaM Expr := do if hasWellFoundedFix e then transform e (pre := pre) else return e where pre (e : Expr) : MetaM TransformStep := do let e' := e.headBeta if e'.isAppOf ``WellFounded.fix && e'.getAppNumArgs >= 6 then let args := e'.getAppArgs let packedArg := args[5]! let extraArgs := args[6:] if let some (declName, args) := decodePackedArg? info packedArg then let candidate := mkAppN (mkAppN (mkAppN (mkConst declName us) fixedPrefix) args) extraArgs trace[Elab.definition.wf] "found nested WF at discr {candidate}" if (← withDefault <| isDefEq candidate e) then return .visit candidate return .continue /-- Simplify `match`-expressions when trying to prove equation theorems for a recursive declaration defined using well-founded recursion. It is similar to `simpMatch?`, but is also tries to fold `WellFounded.fix` applications occurring in discriminants. See comment at `tryToFoldWellFoundedFix`. -/ def simpMatchWF? (info : EqnInfo) (us : List Level) (fixedPrefix : Array Expr) (mvarId : MVarId) : MetaM (Option MVarId) := mvarId.withContext do let target ← instantiateMVars (← mvarId.getType) let (targetNew, _) ← Simp.main target (← Split.getSimpMatchContext) (methods := { pre }) let mvarIdNew ← applySimpResultToTarget mvarId target targetNew if mvarId != mvarIdNew then return some mvarIdNew else return none where pre (e : Expr) : SimpM Simp.Step := do let some app ← matchMatcherApp? e | return Simp.Step.visit { expr := e } if app.discrs.any hasWellFoundedFix then let discrsNew ← app.discrs.mapM (tryToFoldWellFoundedFix info us fixedPrefix ·) if discrsNew != app.discrs then let app := { app with discrs := discrsNew } let eNew := app.toExpr trace[Elab.definition.wf] "folded discriminants {indentExpr eNew}" return Simp.Step.visit { expr := app.toExpr } -- First try to reduce matcher match (← reduceRecMatcher? e) with | some e' => return Simp.Step.done { expr := e' } | none => match (← Simp.simpMatchCore? app e SplitIf.discharge?) with | some r => return r | none => return Simp.Step.visit { expr := e } private def tryToFoldLHS? (info : EqnInfo) (us : List Level) (fixedPrefix : Array Expr) (mvarId : MVarId) : MetaM (Option MVarId) := mvarId.withContext do let target ← mvarId.getType' let some (_, lhs, rhs) := target.eq? | unreachable! let lhsNew ← tryToFoldWellFoundedFix info us fixedPrefix lhs if lhs == lhsNew then return none let targetNew ← mkEq lhsNew rhs let mvarNew ← mkFreshExprSyntheticOpaqueMVar targetNew mvarId.assign mvarNew return mvarNew.mvarId! /-- Given a goal of the form `|- f.{us} a_1 ... a_n b_1 ... b_m = ...`, return `(us, #[a_1, ..., a_n])` where `f` is a constant named `declName`, and `n = info.fixedPrefixSize`. -/ private def getFixedPrefix (declName : Name) (info : EqnInfo) (mvarId : MVarId) : MetaM (List Level × Array Expr) := mvarId.withContext do let target ← mvarId.getType' let some (_, lhs, _) := target.eq? | unreachable! let lhsArgs := lhs.getAppArgs if lhsArgs.size < info.fixedPrefixSize || !lhs.getAppFn matches .const .. then throwError "failed to generate equational theorem for '{declName}', unexpected number of arguments in the equation left-hand-side\n{mvarId}" let result := lhsArgs[:info.fixedPrefixSize] trace[Elab.definition.wf.eqns] "fixedPrefix: {result}" return (lhs.getAppFn.constLevels!, result) private partial def mkProof (declName : Name) (info : EqnInfo) (type : Expr) : MetaM Expr := do trace[Elab.definition.wf.eqns] "proving: {type}" withNewMCtxDepth do let main ← mkFreshExprSyntheticOpaqueMVar type let (_, mvarId) ← main.mvarId!.intros let (us, fixedPrefix) ← getFixedPrefix declName info mvarId let rec go (mvarId : MVarId) : MetaM Unit := do trace[Elab.definition.wf.eqns] "step\n{MessageData.ofGoal mvarId}" if (← tryURefl mvarId) then return () else if (← tryContradiction mvarId) then return () else if let some mvarId ← simpMatchWF? info us fixedPrefix mvarId then go mvarId else if let some mvarId ← simpIf? mvarId then go mvarId else if let some mvarId ← whnfReducibleLHS? mvarId then go mvarId else match (← simpTargetStar mvarId { config.dsimp := false }).1 with | TacticResultCNM.closed => return () | TacticResultCNM.modified mvarId => go mvarId | TacticResultCNM.noChange => if let some mvarIds ← casesOnStuckLHS? mvarId then mvarIds.forM go else if let some mvarIds ← splitTarget? mvarId then mvarIds.forM go else if let some mvarId ← tryToFoldLHS? info us fixedPrefix mvarId then go mvarId else throwError "failed to generate equational theorem for '{declName}'\n{MessageData.ofGoal mvarId}" go (← rwFixEq (← deltaLHSUntilFix mvarId)) instantiateMVars main def mkEqns (declName : Name) (info : EqnInfo) : MetaM (Array Name) := withOptions (tactic.hygienic.set · false) do let baseName := mkPrivateName (← getEnv) declName let eqnTypes ← withNewMCtxDepth <| lambdaTelescope info.value fun xs body => do let us := info.levelParams.map mkLevelParam let target ← mkEq (mkAppN (Lean.mkConst declName us) xs) body let goal ← mkFreshExprSyntheticOpaqueMVar target mkEqnTypes info.declNames goal.mvarId! let mut thmNames := #[] for i in [: eqnTypes.size] do let type := eqnTypes[i]! trace[Elab.definition.wf.eqns] "{eqnTypes[i]!}" let name := baseName ++ (`_eq).appendIndexAfter (i+1) thmNames := thmNames.push name let value ← mkProof declName info type let (type, value) ← removeUnusedEqnHypotheses type value addDecl <| Declaration.thmDecl { name, type, value levelParams := info.levelParams } return thmNames builtin_initialize eqnInfoExt : MapDeclarationExtension EqnInfo ← mkMapDeclarationExtension `wfEqInfo def registerEqnsInfo (preDefs : Array PreDefinition) (declNameNonRec : Name) (fixedPrefixSize : Nat) : CoreM Unit := do let declNames := preDefs.map (·.declName) modifyEnv fun env => preDefs.foldl (init := env) fun env preDef => eqnInfoExt.insert env preDef.declName { preDef with declNames, declNameNonRec, fixedPrefixSize } def getEqnsFor? (declName : Name) : MetaM (Option (Array Name)) := do if let some info := eqnInfoExt.find? (← getEnv) declName then mkEqns declName info else return none def getUnfoldFor? (declName : Name) : MetaM (Option Name) := do let env ← getEnv Eqns.getUnfoldFor? declName fun _ => eqnInfoExt.find? env declName |>.map (·.toEqnInfoCore) builtin_initialize registerGetEqnsFn getEqnsFor? registerGetUnfoldEqnFn getUnfoldFor? registerTraceClass `Elab.definition.wf.eqns end Lean.Elab.WF
bd357a3dfac6cf0770b3b45f7497713dd54985b0
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/topology/uniform_space/cauchy.lean
5f98409cb50a4e0b99d550d14dae854148dd64ce
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
16,084
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro Theory of Cauchy filters in uniform spaces. Complete uniform spaces. Totally bounded subsets. -/ import topology.uniform_space.basic open filter topological_space lattice set classical local attribute [instance, priority 0] prop_decidable variables {α : Type*} {β : Type*} [uniform_space α] universe u local notation `𝓤` := uniformity /-- A filter `f` is Cauchy if for every entourage `r`, there exists an `s ∈ f` such that `s × s ⊆ r`. This is a generalization of Cauchy sequences, because if `a : ℕ → α` then the filter of sets containing cofinitely many of the `a n` is Cauchy iff `a` is a Cauchy sequence. -/ def cauchy (f : filter α) := f ≠ ⊥ ∧ filter.prod f f ≤ (𝓤 α) def is_complete (s : set α) := ∀f, cauchy f → f ≤ principal s → ∃x∈s, f ≤ nhds x lemma cauchy_iff {f : filter α} : cauchy f ↔ (f ≠ ⊥ ∧ (∀ s ∈ 𝓤 α, ∃t∈f.sets, set.prod t t ⊆ s)) := and_congr (iff.refl _) $ forall_congr $ assume s, forall_congr $ assume hs, mem_prod_same_iff lemma cauchy_map_iff {l : filter β} {f : β → α} : cauchy (l.map f) ↔ (l ≠ ⊥ ∧ tendsto (λp:β×β, (f p.1, f p.2)) (l.prod l) (𝓤 α)) := by rw [cauchy, (≠), map_eq_bot_iff, prod_map_map_eq]; refl lemma cauchy_downwards {f g : filter α} (h_c : cauchy f) (hg : g ≠ ⊥) (h_le : g ≤ f) : cauchy g := ⟨hg, le_trans (filter.prod_mono h_le h_le) h_c.right⟩ lemma cauchy_nhds {a : α} : cauchy (nhds a) := ⟨nhds_neq_bot, calc filter.prod (nhds a) (nhds a) = (𝓤 α).lift (λs:set (α×α), (𝓤 α).lift' (λt:set(α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (a, y) ∈ t})) : nhds_nhds_eq_uniformity_uniformity_prod ... ≤ (𝓤 α).lift' (λs:set (α×α), comp_rel s s) : le_infi $ assume s, le_infi $ assume hs, infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le s $ infi_le_of_le hs $ principal_mono.mpr $ assume ⟨x, y⟩ ⟨(hx : (x, a) ∈ s), (hy : (a, y) ∈ s)⟩, ⟨a, hx, hy⟩ ... ≤ 𝓤 α : comp_le_uniformity⟩ lemma cauchy_pure {a : α} : cauchy (pure a) := cauchy_downwards cauchy_nhds (show principal {a} ≠ ⊥, by simp) (pure_le_nhds a) lemma le_nhds_of_cauchy_adhp {f : filter α} {x : α} (hf : cauchy f) (adhs : f ⊓ nhds x ≠ ⊥) : f ≤ nhds x := have ∀s∈f.sets, x ∈ closure s, begin intros s hs, simp [closure_eq_nhds, inf_comm], exact assume h', adhs $ bot_unique $ h' ▸ inf_le_inf (by simp; exact hs) (le_refl _) end, calc f ≤ f.lift' (λs:set α, {y | x ∈ closure s ∧ y ∈ closure s}) : le_infi $ assume s, le_infi $ assume hs, begin rw [←forall_sets_neq_empty_iff_neq_bot] at adhs, simp [this s hs], exact mem_sets_of_superset hs subset_closure end ... ≤ f.lift' (λs:set α, {y | (x, y) ∈ closure (set.prod s s)}) : by simp [closure_prod_eq]; exact le_refl _ ... = (filter.prod f f).lift' (λs:set (α×α), {y | (x, y) ∈ closure s}) : begin rw [prod_same_eq], rw [lift'_lift'_assoc], exact monotone_prod monotone_id monotone_id, exact monotone_comp (assume s t h x h', closure_mono h h') monotone_preimage end ... ≤ (𝓤 α).lift' (λs:set (α×α), {y | (x, y) ∈ closure s}) : lift'_mono hf.right (le_refl _) ... = ((𝓤 α).lift' closure).lift' (λs:set (α×α), {y | (x, y) ∈ s}) : begin rw [lift'_lift'_assoc], exact assume s t h, closure_mono h, exact monotone_preimage end ... = (𝓤 α).lift' (λs:set (α×α), {y | (x, y) ∈ s}) : by rw [←uniformity_eq_uniformity_closure] ... = nhds x : by rw [nhds_eq_uniformity] lemma le_nhds_iff_adhp_of_cauchy {f : filter α} {x : α} (hf : cauchy f) : f ≤ nhds x ↔ f ⊓ nhds x ≠ ⊥ := ⟨assume h, (inf_of_le_left h).symm ▸ hf.left, le_nhds_of_cauchy_adhp hf⟩ lemma cauchy_map [uniform_space β] {f : filter α} {m : α → β} (hm : uniform_continuous m) (hf : cauchy f) : cauchy (map m f) := ⟨have f ≠ ⊥, from hf.left, by simp; assumption, calc filter.prod (map m f) (map m f) = map (λp:α×α, (m p.1, m p.2)) (filter.prod f f) : filter.prod_map_map_eq ... ≤ map (λp:α×α, (m p.1, m p.2)) (𝓤 α) : map_mono hf.right ... ≤ 𝓤 β : hm⟩ lemma cauchy_comap [uniform_space β] {f : filter β} {m : α → β} (hm : comap (λp:α×α, (m p.1, m p.2)) (𝓤 β) ≤ 𝓤 α) (hf : cauchy f) (hb : comap m f ≠ ⊥) : cauchy (comap m f) := ⟨hb, calc filter.prod (comap m f) (comap m f) = comap (λp:α×α, (m p.1, m p.2)) (filter.prod f f) : filter.prod_comap_comap_eq ... ≤ comap (λp:α×α, (m p.1, m p.2)) (𝓤 β) : comap_mono hf.right ... ≤ 𝓤 α : hm⟩ /-- Cauchy sequences. Usually defined on ℕ, but often it is also useful to say that a function defined on ℝ is Cauchy at +∞ to deduce convergence. Therefore, we define it in a type class that is general enough to cover both ℕ and ℝ, which are the main motivating examples. -/ def cauchy_seq [inhabited β] [semilattice_sup β] (u : β → α) := cauchy (at_top.map u) lemma cauchy_seq_iff_prod_map [inhabited β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ map (prod.map u u) at_top ≤ 𝓤 α := iff.trans (and_iff_right (map_ne_bot at_top_ne_bot)) (prod_map_at_top_eq u u ▸ iff.rfl) /-- A complete space is defined here using uniformities. A uniform space is complete if every Cauchy filter converges. -/ class complete_space (α : Type u) [uniform_space α] : Prop := (complete : ∀{f:filter α}, cauchy f → ∃x, f ≤ nhds x) lemma complete_univ {α : Type u} [uniform_space α] [complete_space α] : is_complete (univ : set α) := begin assume f hf _, rcases complete_space.complete hf with ⟨x, hx⟩, exact ⟨x, by simp, hx⟩ end lemma cauchy_prod [uniform_space β] {f : filter α} {g : filter β} : cauchy f → cauchy g → cauchy (filter.prod f g) | ⟨f_proper, hf⟩ ⟨g_proper, hg⟩ := ⟨filter.prod_neq_bot.2 ⟨f_proper, g_proper⟩, let p_α := λp:(α×β)×(α×β), (p.1.1, p.2.1), p_β := λp:(α×β)×(α×β), (p.1.2, p.2.2) in suffices (f.prod f).comap p_α ⊓ (g.prod g).comap p_β ≤ (𝓤 α).comap p_α ⊓ (𝓤 β).comap p_β, by simpa [uniformity_prod, filter.prod, filter.comap_inf, filter.comap_comap_comp, (∘), lattice.inf_assoc, lattice.inf_comm, lattice.inf_left_comm], lattice.inf_le_inf (filter.comap_mono hf) (filter.comap_mono hg)⟩ instance complete_space.prod [uniform_space β] [complete_space α] [complete_space β] : complete_space (α × β) := { complete := λ f hf, let ⟨x1, hx1⟩ := complete_space.complete $ cauchy_map uniform_continuous_fst hf in let ⟨x2, hx2⟩ := complete_space.complete $ cauchy_map uniform_continuous_snd hf in ⟨(x1, x2), by rw [nhds_prod_eq, filter.prod_def]; from filter.le_lift (λ s hs, filter.le_lift' $ λ t ht, have H1 : prod.fst ⁻¹' s ∈ f.sets := hx1 hs, have H2 : prod.snd ⁻¹' t ∈ f.sets := hx2 ht, filter.inter_mem_sets H1 H2)⟩ } /--If `univ` is complete, the space is a complete space -/ lemma complete_space_of_is_complete_univ (h : is_complete (univ : set α)) : complete_space α := ⟨λ f hf, let ⟨x, _, hx⟩ := h f hf ((@principal_univ α).symm ▸ le_top) in ⟨x, hx⟩⟩ lemma cauchy_iff_exists_le_nhds [uniform_space α] [complete_space α] {l : filter α} (hl : l ≠ ⊥) : cauchy l ↔ (∃x, l ≤ nhds x) := ⟨complete_space.complete, assume ⟨x, hx⟩, cauchy_downwards cauchy_nhds hl hx⟩ lemma cauchy_map_iff_exists_tendsto [uniform_space α] [complete_space α] {l : filter β} {f : β → α} (hl : l ≠ ⊥) : cauchy (l.map f) ↔ (∃x, tendsto f l (nhds x)) := cauchy_iff_exists_le_nhds (map_ne_bot hl) /-- A Cauchy sequence in a complete space converges -/ theorem cauchy_seq_tendsto_of_complete [inhabited β] [semilattice_sup β] [complete_space α] {u : β → α} (H : cauchy_seq u) : ∃x, tendsto u at_top (nhds x) := complete_space.complete H theorem le_nhds_lim_of_cauchy {α} [uniform_space α] [complete_space α] [inhabited α] {f : filter α} (hf : cauchy f) : f ≤ nhds (lim f) := lim_spec (complete_space.complete hf) lemma is_complete_of_is_closed [complete_space α] {s : set α} (h : is_closed s) : is_complete s := λ f cf fs, let ⟨x, hx⟩ := complete_space.complete cf in ⟨x, is_closed_iff_nhds.mp h x (neq_bot_of_le_neq_bot cf.left (le_inf hx fs)), hx⟩ /-- A set `s` is totally bounded if for every entourage `d` there is a finite set of points `t` such that every element of `s` is `d`-near to some element of `t`. -/ def totally_bounded (s : set α) : Prop := ∀d ∈ 𝓤 α, ∃t : set α, finite t ∧ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}) theorem totally_bounded_iff_subset {s : set α} : totally_bounded s ↔ ∀d ∈ 𝓤 α, ∃t ⊆ s, finite t ∧ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}) := ⟨λ H d hd, begin rcases comp_symm_of_uniformity hd with ⟨r, hr, rs, rd⟩, rcases H r hr with ⟨k, fk, ks⟩, let u := {y ∈ k | ∃ x, x ∈ s ∧ (x, y) ∈ r}, let f : u → α := λ x, classical.some x.2.2, have : ∀ x : u, f x ∈ s ∧ (f x, x.1) ∈ r := λ x, classical.some_spec x.2.2, refine ⟨range f, _, _, _⟩, { exact range_subset_iff.2 (λ x, (this x).1) }, { have : finite u := finite_subset fk (λ x h, h.1), exact ⟨@set.fintype_range _ _ _ _ this.fintype⟩ }, { intros x xs, have := ks xs, simp at this, rcases this with ⟨y, hy, xy⟩, let z : coe_sort u := ⟨y, hy, x, xs, xy⟩, exact mem_bUnion_iff.2 ⟨_, ⟨z, rfl⟩, rd $ mem_comp_rel.2 ⟨_, xy, rs (this z).2⟩⟩ } end, λ H d hd, let ⟨t, _, ht⟩ := H d hd in ⟨t, ht⟩⟩ lemma totally_bounded_subset [uniform_space α] {s₁ s₂ : set α} (hs : s₁ ⊆ s₂) (h : totally_bounded s₂) : totally_bounded s₁ := assume d hd, let ⟨t, ht₁, ht₂⟩ := h d hd in ⟨t, ht₁, subset.trans hs ht₂⟩ lemma totally_bounded_empty [uniform_space α] : totally_bounded (∅ : set α) := λ d hd, ⟨∅, finite_empty, empty_subset _⟩ lemma totally_bounded_closure [uniform_space α] {s : set α} (h : totally_bounded s) : totally_bounded (closure s) := assume t ht, let ⟨t', ht', hct', htt'⟩ := mem_uniformity_is_closed ht, ⟨c, hcf, hc⟩ := h t' ht' in ⟨c, hcf, calc closure s ⊆ closure (⋃ (y : α) (H : y ∈ c), {x : α | (x, y) ∈ t'}) : closure_mono hc ... = _ : closure_eq_of_is_closed $ is_closed_bUnion hcf $ assume i hi, continuous_iff_is_closed.mp (continuous_id.prod_mk continuous_const) _ hct' ... ⊆ _ : bUnion_subset $ assume i hi, subset.trans (assume x, @htt' (x, i)) (subset_bUnion_of_mem hi)⟩ lemma totally_bounded_image [uniform_space α] [uniform_space β] {f : α → β} {s : set α} (hf : uniform_continuous f) (hs : totally_bounded s) : totally_bounded (f '' s) := assume t ht, have {p:α×α | (f p.1, f p.2) ∈ t} ∈ 𝓤 α, from hf ht, let ⟨c, hfc, hct⟩ := hs _ this in ⟨f '' c, finite_image f hfc, begin simp [image_subset_iff], simp [subset_def] at hct, intros x hx, simp [-mem_image], exact let ⟨i, hi, ht⟩ := hct x hx in ⟨f i, mem_image_of_mem f hi, ht⟩ end⟩ lemma cauchy_of_totally_bounded_of_ultrafilter {s : set α} {f : filter α} (hs : totally_bounded s) (hf : is_ultrafilter f) (h : f ≤ principal s) : cauchy f := ⟨hf.left, assume t ht, let ⟨t', ht'₁, ht'_symm, ht'_t⟩ := comp_symm_of_uniformity ht in let ⟨i, hi, hs_union⟩ := hs t' ht'₁ in have (⋃y∈i, {x | (x,y) ∈ t'}) ∈ f.sets, from mem_sets_of_superset (le_principal_iff.mp h) hs_union, have ∃y∈i, {x | (x,y) ∈ t'} ∈ f.sets, from mem_of_finite_Union_ultrafilter hf hi this, let ⟨y, hy, hif⟩ := this in have set.prod {x | (x,y) ∈ t'} {x | (x,y) ∈ t'} ⊆ comp_rel t' t', from assume ⟨x₁, x₂⟩ ⟨(h₁ : (x₁, y) ∈ t'), (h₂ : (x₂, y) ∈ t')⟩, ⟨y, h₁, ht'_symm h₂⟩, (filter.prod f f).sets_of_superset (prod_mem_prod hif hif) (subset.trans this ht'_t)⟩ lemma totally_bounded_iff_filter {s : set α} : totally_bounded s ↔ (∀f, f ≠ ⊥ → f ≤ principal s → ∃c ≤ f, cauchy c) := ⟨assume : totally_bounded s, assume f hf hs, ⟨ultrafilter_of f, ultrafilter_of_le, cauchy_of_totally_bounded_of_ultrafilter this (ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hs)⟩, assume h : ∀f, f ≠ ⊥ → f ≤ principal s → ∃c ≤ f, cauchy c, assume d hd, classical.by_contradiction $ assume hs, have hd_cover : ∀{t:set α}, finite t → ¬ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}), by simpa using hs, let f := ⨅t:{t : set α // finite t}, principal (s \ (⋃y∈t.val, {x | (x,y) ∈ d})), ⟨a, ha⟩ := @exists_mem_of_ne_empty α s (assume h, hd_cover finite_empty $ h.symm ▸ empty_subset _) in have f ≠ ⊥, from infi_neq_bot_of_directed ⟨a⟩ (assume ⟨t₁, ht₁⟩ ⟨t₂, ht₂⟩, ⟨⟨t₁ ∪ t₂, finite_union ht₁ ht₂⟩, principal_mono.mpr $ diff_subset_diff_right $ Union_subset_Union $ assume t, Union_subset_Union_const or.inl, principal_mono.mpr $ diff_subset_diff_right $ Union_subset_Union $ assume t, Union_subset_Union_const or.inr⟩) (assume ⟨t, ht⟩, by simp [diff_eq_empty]; exact hd_cover ht), have f ≤ principal s, from infi_le_of_le ⟨∅, finite_empty⟩ $ by simp; exact subset.refl s, let ⟨c, (hc₁ : c ≤ f), (hc₂ : cauchy c)⟩ := h f ‹f ≠ ⊥› this, ⟨m, hm, (hmd : set.prod m m ⊆ d)⟩ := (@mem_prod_same_iff α c d).mp $ hc₂.right hd in have c ≤ principal s, from le_trans ‹c ≤ f› this, have m ∩ s ∈ c.sets, from inter_mem_sets hm $ le_principal_iff.mp this, let ⟨y, hym, hys⟩ := inhabited_of_mem_sets hc₂.left this in let ys := (⋃y'∈({y}:set α), {x | (x, y') ∈ d}) in have m ⊆ ys, from assume y' hy', show y' ∈ (⋃y'∈({y}:set α), {x | (x, y') ∈ d}), by simp; exact @hmd (y', y) ⟨hy', hym⟩, have c ≤ principal (s - ys), from le_trans hc₁ $ infi_le_of_le ⟨{y}, finite_singleton _⟩ $ le_refl _, have (s - ys) ∩ (m ∩ s) ∈ c.sets, from inter_mem_sets (le_principal_iff.mp this) ‹m ∩ s ∈ c.sets›, have ∅ ∈ c.sets, from c.sets_of_superset this $ assume x ⟨⟨hxs, hxys⟩, hxm, _⟩, hxys $ ‹m ⊆ ys› hxm, hc₂.left $ empty_in_sets_eq_bot.mp this⟩ lemma totally_bounded_iff_ultrafilter {s : set α} : totally_bounded s ↔ (∀f, is_ultrafilter f → f ≤ principal s → cauchy f) := ⟨assume hs f, cauchy_of_totally_bounded_of_ultrafilter hs, assume h, totally_bounded_iff_filter.mpr $ assume f hf hfs, have cauchy (ultrafilter_of f), from h (ultrafilter_of f) (ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hfs), ⟨ultrafilter_of f, ultrafilter_of_le, this⟩⟩ lemma compact_iff_totally_bounded_complete {s : set α} : compact s ↔ totally_bounded s ∧ is_complete s := ⟨λ hs, ⟨totally_bounded_iff_ultrafilter.2 (λ f hf1 hf2, let ⟨x, xs, fx⟩ := compact_iff_ultrafilter_le_nhds.1 hs f hf1 hf2 in cauchy_downwards (cauchy_nhds) (hf1.1) fx), λ f fc fs, let ⟨a, as, fa⟩ := hs f fc.1 fs in ⟨a, as, le_nhds_of_cauchy_adhp fc fa⟩⟩, λ ⟨ht, hc⟩, compact_iff_ultrafilter_le_nhds.2 (λf hf hfs, hc _ (totally_bounded_iff_ultrafilter.1 ht _ hf hfs) hfs)⟩ instance complete_of_compact {α : Type u} [uniform_space α] [compact_space α] : complete_space α := ⟨λf hf, by simpa [principal_univ] using (compact_iff_totally_bounded_complete.1 compact_univ).2 f hf⟩ lemma compact_of_totally_bounded_is_closed [complete_space α] {s : set α} (ht : totally_bounded s) (hc : is_closed s) : compact s := (@compact_iff_totally_bounded_complete α _ s).2 ⟨ht, is_complete_of_is_closed hc⟩
93312575bf5f7e0d6fbd9bfe5ce7030d489dbe1d
8e2026ac8a0660b5a490dfb895599fb445bb77a0
/library/init/data/array.lean
35f5ee82ddf16e7d3a518fb063b446972607e436
[ "Apache-2.0" ]
permissive
pcmoritz/lean
6a8575115a724af933678d829b4f791a0cb55beb
35eba0107e4cc8a52778259bb5392300267bfc29
refs/heads/master
1,607,896,326,092
1,490,752,175,000
1,490,752,175,000
86,612,290
0
0
null
1,490,809,641,000
1,490,809,641,000
null
UTF-8
Lean
false
false
3,713
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.data.nat universes u w structure array (α : Type u) (n : nat) := (data : fin n → α) def mk_array {α} (n) (v : α) : array α n := {data := λ _, v} namespace array variables {α : Type u} {β : Type w} {n : nat} def read (a : array α n) (i : fin n) : α := a.data i def read' [inhabited α] (a : array α n) (i : nat) : α := if h : i < n then a.read ⟨i,h⟩ else default α def write (a : array α n) (i : fin n) (v : α) : array α n := {data := λ j, if i = j then v else a.read j} def write' (a : array α n) (i : nat) (v : α) : array α n := if h : i < n then a.write ⟨i, h⟩ v else a lemma push_back_idx {j n} : j < n + 1 → j ≠ n → j < n := λ h₁ h₂, nat.lt_of_le_and_ne (nat.le_of_lt_succ h₁) h₂ def push_back (a : array α n) (v : α) : array α (n+1) := {data := λ ⟨j, h₁⟩, if h₂ : j = n then v else a.read ⟨j, push_back_idx h₁ h₂⟩} lemma pop_back_idx {j n} : j < n → j < n + 1 := λ h, nat.lt.step h def pop_back (a : array α (n+1)) : array α n := {data := λ ⟨j, h⟩, a.read ⟨j, pop_back_idx h⟩} lemma lt_aux_1 {a b c : nat} : a + c < b → a < b := λ h, lt_of_le_of_lt (nat.le_add_right a c) h lemma lt_aux_2 {n} : n > 0 → n - 1 < n := assume h, have h₁ : 1 > 0, from dec_trivial, nat.sub_lt h h₁ lemma lt_aux_3 {n i} : i + 1 < n → n - 2 - i < n := assume h, have n > 0, from lt.trans (nat.zero_lt_succ i) h, have n - 2 < n, from nat.sub_lt this (dec_trivial), lt_of_le_of_lt (nat.sub_le _ _) this def foreach_aux (f : fin n → α → α) : Π (i : nat), i < n → array α n → array α n | 0 h a := let i : fin n := ⟨n - 1, lt_aux_2 h⟩ in a.write i (f i (a.read i)) | (j+1) h a := let i : fin n := ⟨n - 2 - j, lt_aux_3 h⟩ in foreach_aux j (lt_aux_1 h) (a.write i (f i (a.read i))) def foreach : Π {n}, array α n → (fin n → α → α) → array α n | 0 a f:= a | (n+1) a f := foreach_aux f n (nat.lt_succ_self _) a def map {α} {n} (f : α → α) (a : array α n) : array α n := foreach a (λ _, f) def map₂ {α} {n} (f : α → α → α) (a b : array α n) : array α n := foreach b (λ i, f (a.read i)) def iterate_aux (f : fin n → α → β → β) : Π (i : nat), i < n → array α n → β → β | 0 h a b := let i : fin n := ⟨n - 1, lt_aux_2 h⟩ in f i (a.read i) b | (j+1) h a b := let i : fin n := ⟨n - 2 - j, lt_aux_3 h⟩ in iterate_aux j (lt_aux_1 h) a (f i (a.read i) b) def iterate : Π {n}, array α n → β → (fin n → α → β → β) → β | 0 a b fn := b | (n+1) a b fn := iterate_aux fn n (nat.lt_succ_self _) a b def foldl {n} (a : array α n) (b : β) (f : α → β → β) : β := iterate a b (λ _, f) def rev_iterate_aux (f : fin n → α → β → β) : Π (i : nat), i < n → array α n → β → β | 0 h a b := let z : fin n := ⟨0, h⟩ in f z (a.read z) b | (j+1) h a b := let i : fin n := ⟨j+1, h⟩ in rev_iterate_aux j (lt_aux_1 h) a (f i (a.read i) b) def rev_iterate : Π {n : nat}, array α n → β → (fin n → α → β → β) → β | 0 a b fn := b | (n+1) a b fn := rev_iterate_aux fn n (nat.lt_succ_self _) a b def to_list (a : array α n) : list α := a.rev_iterate [] (λ _ v l, v :: l) instance [has_to_string α] : has_to_string (array α n) := ⟨to_string ∘ to_list⟩ meta instance [has_to_format α] : has_to_format (array α n) := ⟨to_fmt ∘ to_list⟩ meta instance [has_to_tactic_format α] : has_to_tactic_format (array α n) := ⟨tactic.pp ∘ to_list⟩ end array
591d8966e18812d434bf9dd1e389449ff0286378
3dd1b66af77106badae6edb1c4dea91a146ead30
/examples/standard/constable.lean
656b423e93594cacfc7683abea7cc0b6fe41c6e9
[ "Apache-2.0" ]
permissive
silky/lean
79c20c15c93feef47bb659a2cc139b26f3614642
df8b88dca2f8da1a422cb618cd476ef5be730546
refs/heads/master
1,610,737,587,697
1,406,574,534,000
1,406,574,534,000
22,362,176
1
0
null
null
null
null
UTF-8
Lean
false
false
7,056
lean
-- Theorems/Exercises from "Logical Investigations, with the Nuprl Proof Assistant" -- by Robert L. Constable and Anne Trostle -- http://www.nuprl.org/MathLibrary/LogicalInvestigations/ import logic -- 2. The Minimal Implicational Calculus theorem thm1 {A B : Prop} : A → B → A := assume Ha Hb, Ha theorem thm2 {A B C : Prop} : (A → B) → (A → B → C) → (A → C) := assume Hab Habc Ha, Habc Ha (Hab Ha) theorem thm3 {A B C : Prop} : (A → B) → (B → C) → (A → C) := assume Hab Hbc Ha, Hbc (Hab Ha) -- 3. False Propositions and Negation theorem thm4 {P Q : Prop} : ¬P → P → Q := assume Hnp Hp, absurd_elim Q Hp Hnp theorem thm5 {P : Prop} : P → ¬¬P := assume (Hp : P) (HnP : ¬P), absurd Hp HnP theorem thm6 {P Q : Prop} : (P → Q) → (¬Q → ¬P) := assume (Hpq : P → Q) (Hnq : ¬Q) (Hp : P), have Hq : Q, from Hpq Hp, show false, from absurd Hq Hnq theorem thm7 {P Q : Prop} : (P → ¬P) → (P → Q) := assume Hpnp Hp, absurd_elim Q Hp (Hpnp Hp) theorem thm8 {P Q : Prop} : ¬(P → Q) → (P → ¬Q) := assume (Hn : ¬(P → Q)) (Hp : P) (Hq : Q), -- Rermak we don't even need the hypothesis Hp have H : P → Q, from assume H', Hq, absurd H Hn -- 4. Conjunction and Disjunction theorem thm9 {P : Prop} : (P ∨ ¬P) → (¬¬P → P) := assume (em : P ∨ ¬P) (Hnn : ¬¬P), or_elim em (assume Hp, Hp) (assume Hn, absurd_elim P Hn Hnn) theorem thm10 {P : Prop} : ¬¬(P ∨ ¬P) := assume Hnem : ¬(P ∨ ¬P), have Hnp : ¬P, from assume Hp : P, have Hem : P ∨ ¬P, from or_inl Hp, absurd Hem Hnem, have Hem : P ∨ ¬P, from or_inr Hnp, absurd Hem Hnem theorem thm11 {P Q : Prop} : ¬P ∨ ¬Q → ¬(P ∧ Q) := assume (H : ¬P ∨ ¬Q) (Hn : P ∧ Q), or_elim H (assume Hnp : ¬P, absurd (and_elim_left Hn) Hnp) (assume Hnq : ¬Q, absurd (and_elim_right Hn) Hnq) theorem thm12 {P Q : Prop} : ¬(P ∨ Q) → ¬P ∧ ¬Q := assume H : ¬(P ∨ Q), have Hnp : ¬P, from assume Hp : P, absurd (or_inl Hp) H, have Hnq : ¬Q, from assume Hq : Q, absurd (or_inr Hq) H, and_intro Hnp Hnq theorem thm13 {P Q : Prop} : ¬P ∧ ¬Q → ¬(P ∨ Q) := assume (H : ¬P ∧ ¬Q) (Hn : P ∨ Q), or_elim Hn (assume Hp : P, absurd Hp (and_elim_left H)) (assume Hq : Q, absurd Hq (and_elim_right H)) theorem thm14 {P Q : Prop} : ¬P ∨ Q → P → Q := assume (Hor : ¬P ∨ Q) (Hp : P), or_elim Hor (assume Hnp : ¬P, absurd_elim Q Hp Hnp) (assume Hq : Q, Hq) theorem thm15 {P Q : Prop} : (P → Q) → ¬¬(¬P ∨ Q) := assume (Hpq : P → Q) (Hn : ¬(¬P ∨ Q)), have H1 : ¬¬P ∧ ¬Q, from thm12 Hn, have Hnp : ¬P, from mt Hpq (and_elim_right H1), absurd Hnp (and_elim_left H1) theorem thm16 {P Q : Prop} : (P → Q) ∧ ((P ∨ ¬P) ∨ (Q ∨ ¬Q)) → ¬P ∨ Q := assume H : (P → Q) ∧ ((P ∨ ¬P) ∨ (Q ∨ ¬Q)), have Hpq : P → Q, from and_elim_left H, or_elim (and_elim_right H) (assume Hem1 : P ∨ ¬P, or_elim Hem1 (assume Hp : P, or_inr (Hpq Hp)) (assume Hnp : ¬P, or_inl Hnp)) (assume Hem2 : Q ∨ ¬Q, or_elim Hem2 (assume Hq : Q, or_inr Hq) (assume Hnq : ¬Q, or_inl (mt Hpq Hnq))) -- 5. First-Order Logic: All and Exists section parameters {T : Type} {C : Prop} {P : T → Prop} theorem thm17a : (C → ∀x, P x) → (∀x, C → P x) := assume H : C → ∀x, P x, take x : T, assume Hc : C, H Hc x theorem thm17b : (∀x, C → P x) → (C → ∀x, P x) := assume (H : ∀x, C → P x) (Hc : C), take x : T, H x Hc theorem thm18a : ((∃x, P x) → C) → (∀x, P x → C) := assume H : (∃x, P x) → C, take x, assume Hp : P x, have Hex : ∃x, P x, from exists_intro x Hp, H Hex theorem thm18b : (∀x, P x → C) → (∃x, P x) → C := assume (H1 : ∀x, P x → C) (H2 : ∃x, P x), obtain (w : T) (Hw : P w), from H2, H1 w Hw theorem thm19a : (C ∨ ¬C) → (∃x : T, true) → (C → (∃x, P x)) → (∃x, C → P x) := assume (Hem : C ∨ ¬C) (Hin : ∃x : T, true) (H1 : C → ∃x, P x), or_elim Hem (assume Hc : C, obtain (w : T) (Hw : P w), from H1 Hc, have Hr : C → P w, from assume Hc, Hw, exists_intro w Hr) (assume Hnc : ¬C, obtain (w : T) (Hw : true), from Hin, have Hr : C → P w, from assume Hc, absurd_elim (P w) Hc Hnc, exists_intro w Hr) theorem thm19b : (∃x, C → P x) → C → (∃x, P x) := assume (H : ∃x, C → P x) (Hc : C), obtain (w : T) (Hw : C → P w), from H, exists_intro w (Hw Hc) theorem thm20a : (C ∨ ¬C) → (∃x : T, true) → ((¬∀x, P x) → ∃x, ¬P x) → ((∀x, P x) → C) → (∃x, P x → C) := assume Hem Hin Hnf H, or_elim Hem (assume Hc : C, obtain (w : T) (Hw : true), from Hin, exists_intro w (assume H : P w, Hc)) (assume Hnc : ¬C, have H1 : ¬(∀x, P x), from mt H Hnc, have H2 : ∃x, ¬P x, from Hnf H1, obtain (w : T) (Hw : ¬P w), from H2, exists_intro w (assume H : P w, absurd_elim C H Hw)) theorem thm20b : (∃x, P x → C) → (∀ x, P x) → C := assume Hex Hall, obtain (w : T) (Hw : P w → C), from Hex, Hw (Hall w) theorem thm21a : (∃x : T, true) → ((∃x, P x) ∨ C) → (∃x, P x ∨ C) := assume Hin H, or_elim H (assume Hex : ∃x, P x, obtain (w : T) (Hw : P w), from Hex, exists_intro w (or_inl Hw)) (assume Hc : C, obtain (w : T) (Hw : true), from Hin, exists_intro w (or_inr Hc)) theorem thm21b : (∃x, P x ∨ C) → ((∃x, P x) ∨ C) := assume H, obtain (w : T) (Hw : P w ∨ C), from H, or_elim Hw (assume H : P w, or_inl (exists_intro w H)) (assume Hc : C, or_inr Hc) theorem thm22a : (∀x, P x) ∨ C → ∀x, P x ∨ C := assume H, take x, or_elim H (assume Hl, or_inl (Hl x)) (assume Hr, or_inr Hr) theorem thm22b : (C ∨ ¬C) → (∀x, P x ∨ C) → ((∀x, P x) ∨ C) := assume Hem H1, or_elim Hem (assume Hc : C, or_inr Hc) (assume Hnc : ¬C, have Hx : ∀x, P x, from take x, have H1 : P x ∨ C, from H1 x, resolve_left H1 Hnc, or_inl Hx) theorem thm23a : (∃x, P x) ∧ C → (∃x, P x ∧ C) := assume H, have Hex : ∃x, P x, from and_elim_left H, have Hc : C, from and_elim_right H, obtain (w : T) (Hw : P w), from Hex, exists_intro w (and_intro Hw Hc) theorem thm23b : (∃x, P x ∧ C) → (∃x, P x) ∧ C := assume H, obtain (w : T) (Hw : P w ∧ C), from H, have Hex : ∃x, P x, from exists_intro w (and_elim_left Hw), and_intro Hex (and_elim_right Hw) theorem thm24a : (∀x, P x) ∧ C → (∀x, P x ∧ C) := assume H, take x, and_intro (and_elim_left H x) (and_elim_right H) theorem thm24b : (∃x : T, true) → (∀x, P x ∧ C) → (∀x, P x) ∧ C := assume Hin H, obtain (w : T) (Hw : true), from Hin, have Hc : C, from and_elim_right (H w), have Hx : ∀x, P x, from take x, and_elim_left (H x), and_intro Hx Hc end -- of section
9ad3e749ff560e55f0993ee4701df85e839654c3
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/mv_polynomial/pderiv_auto.lean
e17664736f10cbfd101ee82848491f8e67daaf27
[]
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
3,286
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Shing Tak Lam -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.mv_polynomial.variables import Mathlib.algebra.module.basic import Mathlib.tactic.ring import Mathlib.PostPort universes u u_1 namespace Mathlib /-! # Partial derivatives of polynomials This file defines the notion of the formal *partial derivative* of a polynomial, the derivative with respect to a single variable. This derivative is not connected to the notion of derivative from analysis. It is based purely on the polynomial exponents and coefficients. ## Main declarations * `mv_polynomial.pderiv i p` : the partial derivative of `p` with respect to `i`. ## Notation As in other polynomial files, we typically use the notation: + `σ : Type*` (indexing the variables) + `R : Type*` `[comm_ring R]` (the coefficients) + `s : σ →₀ ℕ`, a function from `σ` to `ℕ` which is zero away from a finite set. This will give rise to a monomial in `mv_polynomial σ R` which mathematicians might call `X^s` + `a : R` + `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians + `p : mv_polynomial σ R` -/ namespace mv_polynomial /-- `pderiv i p` is the partial derivative of `p` with respect to `i` -/ def pderiv {R : Type u} {σ : Type u_1} [comm_semiring R] (i : σ) : linear_map R (mv_polynomial σ R) (mv_polynomial σ R) := linear_map.mk (fun (p : mv_polynomial σ R) => finsupp.sum p fun (A : σ →₀ ℕ) (B : R) => monomial (A - finsupp.single i 1) (B * ↑(coe_fn A i))) sorry sorry @[simp] theorem pderiv_monomial {R : Type u} {σ : Type u_1} {a : R} {s : σ →₀ ℕ} [comm_semiring R] {i : σ} : coe_fn (pderiv i) (monomial s a) = monomial (s - finsupp.single i 1) (a * ↑(coe_fn s i)) := sorry @[simp] theorem pderiv_C {R : Type u} {σ : Type u_1} {a : R} [comm_semiring R] {i : σ} : coe_fn (pderiv i) (coe_fn C a) = 0 := sorry theorem pderiv_eq_zero_of_not_mem_vars {R : Type u} {σ : Type u_1} [comm_semiring R] {i : σ} {f : mv_polynomial σ R} (h : ¬i ∈ vars f) : coe_fn (pderiv i) f = 0 := sorry theorem pderiv_monomial_single {R : Type u} {σ : Type u_1} {a : R} [comm_semiring R] {i : σ} {n : ℕ} : coe_fn (pderiv i) (monomial (finsupp.single i n) a) = monomial (finsupp.single i (n - 1)) (a * ↑n) := sorry theorem pderiv_monomial_mul {R : Type u} {σ : Type u_1} {a : R} {a' : R} {s : σ →₀ ℕ} [comm_semiring R] {i : σ} {s' : σ →₀ ℕ} : coe_fn (pderiv i) (monomial s a * monomial s' a') = coe_fn (pderiv i) (monomial s a) * monomial s' a' + monomial s a * coe_fn (pderiv i) (monomial s' a') := sorry @[simp] theorem pderiv_mul {R : Type u} {σ : Type u_1} [comm_semiring R] {i : σ} {f : mv_polynomial σ R} {g : mv_polynomial σ R} : coe_fn (pderiv i) (f * g) = coe_fn (pderiv i) f * g + f * coe_fn (pderiv i) g := sorry @[simp] theorem pderiv_C_mul {R : Type u} {σ : Type u_1} {a : R} [comm_semiring R] {f : mv_polynomial σ R} {i : σ} : coe_fn (pderiv i) (coe_fn C a * f) = coe_fn C a * coe_fn (pderiv i) f := sorry end Mathlib
ac851e31a32205ce4c3d2bb3fd499d28d80f7a4e
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/list/range.lean
7732a69fe75750502c2b5b2311a535736b5a4838
[ "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
10,544
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kenny Lau, Scott Morrison -/ import data.list.chain import data.list.nodup import data.list.of_fn import data.list.zip /-! # Ranges of naturals as lists This file shows basic results about `list.iota`, `list.range`, `list.range'` (all defined in `data.list.defs`) and defines `list.fin_range`. `fin_range n` is the list of elements of `fin n`. `iota n = [1, ..., n]` and `range n = [0, ..., n - 1]` are basic list constructions used for tactics. `range' a b = [a, ..., a + b - 1]` is there to help prove properties about them. Actual maths should use `list.Ico` instead. -/ universe u open nat namespace list variables {α : Type u} @[simp] theorem length_range' : ∀ (s n : ℕ), length (range' s n) = n | s 0 := rfl | s (n+1) := congr_arg succ (length_range' _ _) @[simp] theorem range'_eq_nil {s n : ℕ} : range' s n = [] ↔ n = 0 := by rw [← length_eq_zero, length_range'] @[simp] theorem mem_range' {m : ℕ} : ∀ {s n : ℕ}, m ∈ range' s n ↔ s ≤ m ∧ m < s + n | s 0 := (false_iff _).2 $ λ ⟨H1, H2⟩, not_le_of_lt H2 H1 | s (succ n) := have m = s → m < s + n + 1, from λ e, e ▸ lt_succ_of_le (nat.le_add_right _ _), have l : m = s ∨ s + 1 ≤ m ↔ s ≤ m, by simpa only [eq_comm] using (@decidable.le_iff_eq_or_lt _ _ _ s m).symm, (mem_cons_iff _ _ _).trans $ by simp only [mem_range', or_and_distrib_left, or_iff_right_of_imp this, l, add_right_comm]; refl theorem map_add_range' (a) : ∀ s n : ℕ, map ((+) a) (range' s n) = range' (a + s) n | s 0 := rfl | s (n+1) := congr_arg (cons _) (map_add_range' (s+1) n) theorem map_sub_range' (a) : ∀ (s n : ℕ) (h : a ≤ s), map (λ x, x - a) (range' s n) = range' (s - a) n | s 0 _ := rfl | s (n+1) h := begin convert congr_arg (cons (s-a)) (map_sub_range' (s+1) n (nat.le_succ_of_le h)), rw nat.succ_sub h, refl, end theorem chain_succ_range' : ∀ s n : ℕ, chain (λ a b, b = succ a) s (range' (s+1) n) | s 0 := chain.nil | s (n+1) := (chain_succ_range' (s+1) n).cons rfl theorem chain_lt_range' (s n : ℕ) : chain (<) s (range' (s+1) n) := (chain_succ_range' s n).imp (λ a b e, e.symm ▸ lt_succ_self _) theorem pairwise_lt_range' : ∀ s n : ℕ, pairwise (<) (range' s n) | s 0 := pairwise.nil | s (n+1) := (chain_iff_pairwise (by exact λ a b c, lt_trans)).1 (chain_lt_range' s n) theorem nodup_range' (s n : ℕ) : nodup (range' s n) := (pairwise_lt_range' s n).imp (λ a b, ne_of_lt) @[simp] theorem range'_append : ∀ s m n : ℕ, range' s m ++ range' (s+m) n = range' s (n+m) | s 0 n := rfl | s (m+1) n := show s :: (range' (s+1) m ++ range' (s+m+1) n) = s :: range' (s+1) (n+m), by rw [add_right_comm, range'_append] theorem range'_sublist_right {s m n : ℕ} : range' s m <+ range' s n ↔ m ≤ n := ⟨λ h, by simpa only [length_range'] using length_le_of_sublist h, λ h, by rw [← tsub_add_cancel_of_le h, ← range'_append]; apply sublist_append_left⟩ theorem range'_subset_right {s m n : ℕ} : range' s m ⊆ range' s n ↔ m ≤ n := ⟨λ h, le_of_not_lt $ λ hn, lt_irrefl (s+n) $ (mem_range'.1 $ h $ mem_range'.2 ⟨nat.le_add_right _ _, nat.add_lt_add_left hn s⟩).2, λ h, (range'_sublist_right.2 h).subset⟩ theorem nth_range' : ∀ s {m n : ℕ}, m < n → nth (range' s n) m = some (s + m) | s 0 (n+1) _ := rfl | s (m+1) (n+1) h := (nth_range' (s+1) (lt_of_add_lt_add_right h)).trans $ by rw add_right_comm; refl @[simp] lemma nth_le_range' {n m} (i) (H : i < (range' n m).length) : nth_le (range' n m) i H = n + i := option.some.inj $ by rw [←nth_le_nth _, nth_range' _ (by simpa using H)] theorem range'_concat (s n : ℕ) : range' s (n + 1) = range' s n ++ [s+n] := by rw add_comm n 1; exact (range'_append s n 1).symm theorem range_core_range' : ∀ s n : ℕ, range_core s (range' s n) = range' 0 (n + s) | 0 n := rfl | (s+1) n := by rw [show n+(s+1) = n+1+s, from add_right_comm n s 1]; exact range_core_range' s (n+1) theorem range_eq_range' (n : ℕ) : range n = range' 0 n := (range_core_range' n 0).trans $ by rw zero_add theorem range_succ_eq_map (n : ℕ) : range (n + 1) = 0 :: map succ (range n) := by rw [range_eq_range', range_eq_range', range', add_comm, ← map_add_range']; congr; exact funext one_add theorem range'_eq_map_range (s n : ℕ) : range' s n = map ((+) s) (range n) := by rw [range_eq_range', map_add_range']; refl @[simp] theorem length_range (n : ℕ) : length (range n) = n := by simp only [range_eq_range', length_range'] @[simp] theorem range_eq_nil {n : ℕ} : range n = [] ↔ n = 0 := by rw [← length_eq_zero, length_range] theorem pairwise_lt_range (n : ℕ) : pairwise (<) (range n) := by simp only [range_eq_range', pairwise_lt_range'] theorem nodup_range (n : ℕ) : nodup (range n) := by simp only [range_eq_range', nodup_range'] theorem range_sublist {m n : ℕ} : range m <+ range n ↔ m ≤ n := by simp only [range_eq_range', range'_sublist_right] theorem range_subset {m n : ℕ} : range m ⊆ range n ↔ m ≤ n := by simp only [range_eq_range', range'_subset_right] @[simp] theorem mem_range {m n : ℕ} : m ∈ range n ↔ m < n := by simp only [range_eq_range', mem_range', nat.zero_le, true_and, zero_add] @[simp] theorem not_mem_range_self {n : ℕ} : n ∉ range n := mt mem_range.1 $ lt_irrefl _ @[simp] theorem self_mem_range_succ (n : ℕ) : n ∈ range (n + 1) := by simp only [succ_pos', lt_add_iff_pos_right, mem_range] theorem nth_range {m n : ℕ} (h : m < n) : nth (range n) m = some m := by simp only [range_eq_range', nth_range' _ h, zero_add] theorem range_succ (n : ℕ) : range (succ n) = range n ++ [n] := by simp only [range_eq_range', range'_concat, zero_add] @[simp] lemma range_zero : range 0 = [] := rfl theorem iota_eq_reverse_range' : ∀ n : ℕ, iota n = reverse (range' 1 n) | 0 := rfl | (n+1) := by simp only [iota, range'_concat, iota_eq_reverse_range' n, reverse_append, add_comm]; refl @[simp] theorem length_iota (n : ℕ) : length (iota n) = n := by simp only [iota_eq_reverse_range', length_reverse, length_range'] theorem pairwise_gt_iota (n : ℕ) : pairwise (>) (iota n) := by simp only [iota_eq_reverse_range', pairwise_reverse, pairwise_lt_range'] theorem nodup_iota (n : ℕ) : nodup (iota n) := by simp only [iota_eq_reverse_range', nodup_reverse, nodup_range'] theorem mem_iota {m n : ℕ} : m ∈ iota n ↔ 1 ≤ m ∧ m ≤ n := by simp only [iota_eq_reverse_range', mem_reverse, mem_range', add_comm, lt_succ_iff] theorem reverse_range' : ∀ s n : ℕ, reverse (range' s n) = map (λ i, s + n - 1 - i) (range n) | s 0 := rfl | s (n+1) := by rw [range'_concat, reverse_append, range_succ_eq_map]; simpa only [show s + (n + 1) - 1 = s + n, from rfl, (∘), λ a i, show a - 1 - i = a - succ i, from pred_sub _ _, reverse_singleton, map_cons, tsub_zero, cons_append, nil_append, eq_self_iff_true, true_and, map_map] using reverse_range' s n /-- All elements of `fin n`, from `0` to `n-1`. -/ def fin_range (n : ℕ) : list (fin n) := (range n).pmap fin.mk (λ _, list.mem_range.1) @[simp] lemma fin_range_zero : fin_range 0 = [] := rfl @[simp] lemma mem_fin_range {n : ℕ} (a : fin n) : a ∈ fin_range n := mem_pmap.2 ⟨a.1, mem_range.2 a.2, fin.eta _ _⟩ lemma nodup_fin_range (n : ℕ) : (fin_range n).nodup := nodup_pmap (λ _ _ _ _, fin.veq_of_eq) (nodup_range _) @[simp] lemma length_fin_range (n : ℕ) : (fin_range n).length = n := by rw [fin_range, length_pmap, length_range] @[simp] lemma fin_range_eq_nil {n : ℕ} : fin_range n = [] ↔ n = 0 := by rw [← length_eq_zero, length_fin_range] @[to_additive] theorem prod_range_succ {α : Type u} [monoid α] (f : ℕ → α) (n : ℕ) : ((range n.succ).map f).prod = ((range n).map f).prod * f n := by rw [range_succ, map_append, map_singleton, prod_append, prod_cons, prod_nil, mul_one] /-- A variant of `prod_range_succ` which pulls off the first term in the product rather than the last.-/ @[to_additive "A variant of `sum_range_succ` which pulls off the first term in the sum rather than the last."] theorem prod_range_succ' {α : Type u} [monoid α] (f : ℕ → α) (n : ℕ) : ((range n.succ).map f).prod = f 0 * ((range n).map (λ i, f (succ i))).prod := nat.rec_on n (show 1 * f 0 = f 0 * 1, by rw [one_mul, mul_one]) (λ _ hd, by rw [list.prod_range_succ, hd, mul_assoc, ←list.prod_range_succ]) @[simp] theorem enum_from_map_fst : ∀ n (l : list α), map prod.fst (enum_from n l) = range' n l.length | n [] := rfl | n (a :: l) := congr_arg (cons _) (enum_from_map_fst _ _) @[simp] theorem enum_map_fst (l : list α) : map prod.fst (enum l) = range l.length := by simp only [enum, enum_from_map_fst, range_eq_range'] lemma enum_eq_zip_range (l : list α) : l.enum = (range l.length).zip l := zip_of_prod (enum_map_fst _) (enum_map_snd _) @[simp] lemma unzip_enum_eq_prod (l : list α) : l.enum.unzip = (range l.length, l) := by simp only [enum_eq_zip_range, unzip_zip, length_range] lemma enum_from_eq_zip_range' (l : list α) {n : ℕ} : l.enum_from n = (range' n l.length).zip l := zip_of_prod (enum_from_map_fst _ _) (enum_from_map_snd _ _) @[simp] lemma unzip_enum_from_eq_prod (l : list α) {n : ℕ} : (l.enum_from n).unzip = (range' n l.length, l) := by simp only [enum_from_eq_zip_range', unzip_zip, length_range'] @[simp] lemma nth_le_range {n} (i) (H : i < (range n).length) : nth_le (range n) i H = i := option.some.inj $ by rw [← nth_le_nth _, nth_range (by simpa using H)] @[simp] lemma nth_le_fin_range {n : ℕ} {i : ℕ} (h) : (fin_range n).nth_le i h = ⟨i, length_fin_range n ▸ h⟩ := by simp only [fin_range, nth_le_range, nth_le_pmap, fin.mk_eq_subtype_mk] theorem of_fn_eq_pmap {α n} {f : fin n → α} : of_fn f = pmap (λ i hi, f ⟨i, hi⟩) (range n) (λ _, mem_range.1) := by rw [pmap_eq_map_attach]; from ext_le (by simp) (λ i hi1 hi2, by { simp at hi1, simp [nth_le_of_fn f ⟨i, hi1⟩, -subtype.val_eq_coe] }) theorem of_fn_id (n) : of_fn id = fin_range n := of_fn_eq_pmap theorem of_fn_eq_map {α n} {f : fin n → α} : of_fn f = (fin_range n).map f := by rw [← of_fn_id, map_of_fn, function.right_id] theorem nodup_of_fn {α n} {f : fin n → α} (hf : function.injective f) : nodup (of_fn f) := by rw of_fn_eq_pmap; from nodup_pmap (λ _ _ _ _ H, fin.veq_of_eq $ hf H) (nodup_range n) end list
87fb2a747a0df2d0b18d86fe5639ac73b75e64ce
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/seq/wseq.lean
b0c0fd63a5f83a3850b8395551262c766b3697c2
[ "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
54,991
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import data.seq.seq import data.dlist universes u v w /- coinductive wseq (α : Type u) : Type u | nil : wseq α | cons : α → wseq α → wseq α | think : wseq α → wseq α -/ /-- Weak sequences. While the `seq` structure allows for lists which may not be finite, a weak sequence also allows the computation of each element to involve an indeterminate amount of computation, including possibly an infinite loop. This is represented as a regular `seq` interspersed with `none` elements to indicate that computation is ongoing. This model is appropriate for Haskell style lazy lists, and is closed under most interesting computation patterns on infinite lists, but conversely it is difficult to extract elements from it. -/ def wseq (α) := seq (option α) namespace wseq variables {α : Type u} {β : Type v} {γ : Type w} /-- Turn a sequence into a weak sequence -/ def of_seq : seq α → wseq α := (<$>) some /-- Turn a list into a weak sequence -/ def of_list (l : list α) : wseq α := of_seq l /-- Turn a stream into a weak sequence -/ def of_stream (l : stream α) : wseq α := of_seq l instance coe_seq : has_coe (seq α) (wseq α) := ⟨of_seq⟩ instance coe_list : has_coe (list α) (wseq α) := ⟨of_list⟩ instance coe_stream : has_coe (stream α) (wseq α) := ⟨of_stream⟩ /-- The empty weak sequence -/ def nil : wseq α := seq.nil instance : inhabited (wseq α) := ⟨nil⟩ /-- Prepend an element to a weak sequence -/ def cons (a : α) : wseq α → wseq α := seq.cons (some a) /-- Compute for one tick, without producing any elements -/ def think : wseq α → wseq α := seq.cons none /-- Destruct a weak sequence, to (eventually possibly) produce either `none` for `nil` or `some (a, s)` if an element is produced. -/ def destruct : wseq α → computation (option (α × wseq α)) := computation.corec (λs, match seq.destruct s with | none := sum.inl none | some (none, s') := sum.inr s' | some (some a, s') := sum.inl (some (a, s')) end) def cases_on {C : wseq α → Sort v} (s : wseq α) (h1 : C nil) (h2 : ∀ x s, C (cons x s)) (h3 : ∀ s, C (think s)) : C s := seq.cases_on s h1 (λ o, option.cases_on o h3 h2) protected def mem (a : α) (s : wseq α) := seq.mem (some a) s instance : has_mem α (wseq α) := ⟨wseq.mem⟩ theorem not_mem_nil (a : α) : a ∉ @nil α := seq.not_mem_nil a /-- Get the head of a weak sequence. This involves a possibly infinite computation. -/ def head (s : wseq α) : computation (option α) := computation.map ((<$>) prod.fst) (destruct s) /-- Encode a computation yielding a weak sequence into additional `think` constructors in a weak sequence -/ def flatten : computation (wseq α) → wseq α := seq.corec (λc, match computation.destruct c with | sum.inl s := seq.omap return (seq.destruct s) | sum.inr c' := some (none, c') end) /-- Get the tail of a weak sequence. This doesn't need a `computation` wrapper, unlike `head`, because `flatten` allows us to hide this in the construction of the weak sequence itself. -/ def tail (s : wseq α) : wseq α := flatten $ (λo, option.rec_on o nil prod.snd) <$> destruct s /-- drop the first `n` elements from `s`. -/ def drop (s : wseq α) : ℕ → wseq α | 0 := s | (n+1) := tail (drop n) attribute [simp] drop /-- Get the nth element of `s`. -/ def nth (s : wseq α) (n : ℕ) : computation (option α) := head (drop s n) /-- Convert `s` to a list (if it is finite and completes in finite time). -/ def to_list (s : wseq α) : computation (list α) := @computation.corec (list α) (list α × wseq α) (λ⟨l, s⟩, match seq.destruct s with | none := sum.inl l.reverse | some (none, s') := sum.inr (l, s') | some (some a, s') := sum.inr (a::l, s') end) ([], s) /-- Get the length of `s` (if it is finite and completes in finite time). -/ def length (s : wseq α) : computation ℕ := @computation.corec ℕ (ℕ × wseq α) (λ⟨n, s⟩, match seq.destruct s with | none := sum.inl n | some (none, s') := sum.inr (n, s') | some (some a, s') := sum.inr (n+1, s') end) (0, s) /-- A weak sequence is finite if `to_list s` terminates. Equivalently, it is a finite number of `think` and `cons` applied to `nil`. -/ @[class] def is_finite (s : wseq α) : Prop := (to_list s).terminates instance to_list_terminates (s : wseq α) [h : is_finite s] : (to_list s).terminates := h /-- Get the list corresponding to a finite weak sequence. -/ def get (s : wseq α) [is_finite s] : list α := (to_list s).get /-- A weak sequence is *productive* if it never stalls forever - there are always a finite number of `think`s between `cons` constructors. The sequence itself is allowed to be infinite though. -/ @[class] def productive (s : wseq α) : Prop := ∀ n, (nth s n).terminates instance nth_terminates (s : wseq α) [h : productive s] : ∀ n, (nth s n).terminates := h instance head_terminates (s : wseq α) [h : productive s] : (head s).terminates := h 0 /-- Replace the `n`th element of `s` with `a`. -/ def update_nth (s : wseq α) (n : ℕ) (a : α) : wseq α := @seq.corec (option α) (ℕ × wseq α) (λ⟨n, s⟩, match seq.destruct s, n with | none, n := none | some (none, s'), n := some (none, n, s') | some (some a', s'), 0 := some (some a', 0, s') | some (some a', s'), 1 := some (some a, 0, s') | some (some a', s'), (n+2) := some (some a', n+1, s') end) (n+1, s) /-- Remove the `n`th element of `s`. -/ def remove_nth (s : wseq α) (n : ℕ) : wseq α := @seq.corec (option α) (ℕ × wseq α) (λ⟨n, s⟩, match seq.destruct s, n with | none, n := none | some (none, s'), n := some (none, n, s') | some (some a', s'), 0 := some (some a', 0, s') | some (some a', s'), 1 := some (none, 0, s') | some (some a', s'), (n+2) := some (some a', n+1, s') end) (n+1, s) /-- Map the elements of `s` over `f`, removing any values that yield `none`. -/ def filter_map (f : α → option β) : wseq α → wseq β := seq.corec (λs, match seq.destruct s with | none := none | some (none, s') := some (none, s') | some (some a, s') := some (f a, s') end) /-- Select the elements of `s` that satisfy `p`. -/ def filter (p : α → Prop) [decidable_pred p] : wseq α → wseq α := filter_map (λa, if p a then some a else none) -- example of infinite list manipulations /-- Get the first element of `s` satisfying `p`. -/ def find (p : α → Prop) [decidable_pred p] (s : wseq α) : computation (option α) := head $ filter p s /-- Zip a function over two weak sequences -/ def zip_with (f : α → β → γ) (s1 : wseq α) (s2 : wseq β) : wseq γ := @seq.corec (option γ) (wseq α × wseq β) (λ⟨s1, s2⟩, match seq.destruct s1, seq.destruct s2 with | some (none, s1'), some (none, s2') := some (none, s1', s2') | some (some a1, s1'), some (none, s2') := some (none, s1, s2') | some (none, s1'), some (some a2, s2') := some (none, s1', s2) | some (some a1, s1'), some (some a2, s2') := some (some (f a1 a2), s1', s2') | _, _ := none end) (s1, s2) /-- Zip two weak sequences into a single sequence of pairs -/ def zip : wseq α → wseq β → wseq (α × β) := zip_with prod.mk /-- Get the list of indexes of elements of `s` satisfying `p` -/ def find_indexes (p : α → Prop) [decidable_pred p] (s : wseq α) : wseq ℕ := (zip s (stream.nats : wseq ℕ)).filter_map (λ ⟨a, n⟩, if p a then some n else none) /-- Get the index of the first element of `s` satisfying `p` -/ def find_index (p : α → Prop) [decidable_pred p] (s : wseq α) : computation ℕ := (λ o, option.get_or_else o 0) <$> head (find_indexes p s) /-- Get the index of the first occurrence of `a` in `s` -/ def index_of [decidable_eq α] (a : α) : wseq α → computation ℕ := find_index (eq a) /-- Get the indexes of occurrences of `a` in `s` -/ def indexes_of [decidable_eq α] (a : α) : wseq α → wseq ℕ := find_indexes (eq a) /-- `union s1 s2` is a weak sequence which interleaves `s1` and `s2` in some order (nondeterministically). -/ def union (s1 s2 : wseq α) : wseq α := @seq.corec (option α) (wseq α × wseq α) (λ⟨s1, s2⟩, match seq.destruct s1, seq.destruct s2 with | none, none := none | some (a1, s1'), none := some (a1, s1', nil) | none, some (a2, s2') := some (a2, nil, s2') | some (none, s1'), some (none, s2') := some (none, s1', s2') | some (some a1, s1'), some (none, s2') := some (some a1, s1', s2') | some (none, s1'), some (some a2, s2') := some (some a2, s1', s2') | some (some a1, s1'), some (some a2, s2') := some (some a1, cons a2 s1', s2') end) (s1, s2) /-- Returns `tt` if `s` is `nil` and `ff` if `s` has an element -/ def is_empty (s : wseq α) : computation bool := computation.map option.is_none $ head s /-- Calculate one step of computation -/ def compute (s : wseq α) : wseq α := match seq.destruct s with | some (none, s') := s' | _ := s end /-- Get the first `n` elements of a weak sequence -/ def take (s : wseq α) (n : ℕ) : wseq α := @seq.corec (option α) (ℕ × wseq α) (λ⟨n, s⟩, match n, seq.destruct s with | 0, _ := none | m+1, none := none | m+1, some (none, s') := some (none, m+1, s') | m+1, some (some a, s') := some (some a, m, s') end) (n, s) /-- Split the sequence at position `n` into a finite initial segment and the weak sequence tail -/ def split_at (s : wseq α) (n : ℕ) : computation (list α × wseq α) := @computation.corec (list α × wseq α) (ℕ × list α × wseq α) (λ⟨n, l, s⟩, match n, seq.destruct s with | 0, _ := sum.inl (l.reverse, s) | m+1, none := sum.inl (l.reverse, s) | m+1, some (none, s') := sum.inr (n, l, s') | m+1, some (some a, s') := sum.inr (m, a::l, s') end) (n, [], s) /-- Returns `tt` if any element of `s` satisfies `p` -/ def any (s : wseq α) (p : α → bool) : computation bool := computation.corec (λs : wseq α, match seq.destruct s with | none := sum.inl ff | some (none, s') := sum.inr s' | some (some a, s') := if p a then sum.inl tt else sum.inr s' end) s /-- Returns `tt` if every element of `s` satisfies `p` -/ def all (s : wseq α) (p : α → bool) : computation bool := computation.corec (λs : wseq α, match seq.destruct s with | none := sum.inl tt | some (none, s') := sum.inr s' | some (some a, s') := if p a then sum.inr s' else sum.inl ff end) s /-- Apply a function to the elements of the sequence to produce a sequence of partial results. (There is no `scanr` because this would require working from the end of the sequence, which may not exist.) -/ def scanl (f : α → β → α) (a : α) (s : wseq β) : wseq α := cons a $ @seq.corec (option α) (α × wseq β) (λ⟨a, s⟩, match seq.destruct s with | none := none | some (none, s') := some (none, a, s') | some (some b, s') := let a' := f a b in some (some a', a', s') end) (a, s) /-- Get the weak sequence of initial segments of the input sequence -/ def inits (s : wseq α) : wseq (list α) := cons [] $ @seq.corec (option (list α)) (dlist α × wseq α) (λ ⟨l, s⟩, match seq.destruct s with | none := none | some (none, s') := some (none, l, s') | some (some a, s') := let l' := l.concat a in some (some l'.to_list, l', s') end) (dlist.empty, s) /-- Like take, but does not wait for a result. Calculates `n` steps of computation and returns the sequence computed so far -/ def collect (s : wseq α) (n : ℕ) : list α := (seq.take n s).filter_map id /-- Append two weak sequences. As with `seq.append`, this may not use the second sequence if the first one takes forever to compute -/ def append : wseq α → wseq α → wseq α := seq.append /-- Map a function over a weak sequence -/ def map (f : α → β) : wseq α → wseq β := seq.map (option.map f) /-- Flatten a sequence of weak sequences. (Note that this allows empty sequences, unlike `seq.join`.) -/ def join (S : wseq (wseq α)) : wseq α := seq.join ((λo : option (wseq α), match o with | none := seq1.ret none | some s := (none, s) end) <$> S) /-- Monadic bind operator for weak sequences -/ def bind (s : wseq α) (f : α → wseq β) : wseq β := join (map f s) @[simp] def lift_rel_o (R : α → β → Prop) (C : wseq α → wseq β → Prop) : option (α × wseq α) → option (β × wseq β) → Prop | none none := true | (some (a, s)) (some (b, t)) := R a b ∧ C s t | _ _ := false theorem lift_rel_o.imp {R S : α → β → Prop} {C D : wseq α → wseq β → Prop} (H1 : ∀ a b, R a b → S a b) (H2 : ∀ s t, C s t → D s t) : ∀ {o p}, lift_rel_o R C o p → lift_rel_o S D o p | none none h := trivial | (some (a, s)) (some (b, t)) h := and.imp (H1 _ _) (H2 _ _) h | none (some _) h := false.elim h | (some (_, _)) none h := false.elim h theorem lift_rel_o.imp_right (R : α → β → Prop) {C D : wseq α → wseq β → Prop} (H : ∀ s t, C s t → D s t) {o p} : lift_rel_o R C o p → lift_rel_o R D o p := lift_rel_o.imp (λ _ _, id) H @[simp] def bisim_o (R : wseq α → wseq α → Prop) : option (α × wseq α) → option (α × wseq α) → Prop := lift_rel_o (=) R theorem bisim_o.imp {R S : wseq α → wseq α → Prop} (H : ∀ s t, R s t → S s t) {o p} : bisim_o R o p → bisim_o S o p := lift_rel_o.imp_right _ H /-- Two weak sequences are `lift_rel R` related if they are either both empty, or they are both nonempty and the heads are `R` related and the tails are `lift_rel R` related. (This is a coinductive definition.) -/ def lift_rel (R : α → β → Prop) (s : wseq α) (t : wseq β) : Prop := ∃ C : wseq α → wseq β → Prop, C s t ∧ ∀ {s t}, C s t → computation.lift_rel (lift_rel_o R C) (destruct s) (destruct t) /-- If two sequences are equivalent, then they have the same values and the same computational behavior (i.e. if one loops forever then so does the other), although they may differ in the number of `think`s needed to arrive at the answer. -/ def equiv : wseq α → wseq α → Prop := lift_rel (=) theorem lift_rel_destruct {R : α → β → Prop} {s : wseq α} {t : wseq β} : lift_rel R s t → computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t) | ⟨R, h1, h2⟩ := by refine computation.lift_rel.imp _ _ _ (h2 h1); apply lift_rel_o.imp_right; exact λ s' t' h', ⟨R, h', @h2⟩ theorem lift_rel_destruct_iff {R : α → β → Prop} {s : wseq α} {t : wseq β} : lift_rel R s t ↔ computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t) := ⟨lift_rel_destruct, λ h, ⟨λ s t, lift_rel R s t ∨ computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t), or.inr h, λ s t h, begin have h : computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t), { cases h with h h, exact lift_rel_destruct h, assumption }, apply computation.lift_rel.imp _ _ _ h, intros a b, apply lift_rel_o.imp_right, intros s t, apply or.inl end⟩⟩ infix ~ := equiv theorem destruct_congr {s t : wseq α} : s ~ t → computation.lift_rel (bisim_o (~)) (destruct s) (destruct t) := lift_rel_destruct theorem destruct_congr_iff {s t : wseq α} : s ~ t ↔ computation.lift_rel (bisim_o (~)) (destruct s) (destruct t) := lift_rel_destruct_iff theorem lift_rel.refl (R : α → α → Prop) (H : reflexive R) : reflexive (lift_rel R) := λ s, begin refine ⟨(=), rfl, λ s t (h : s = t), _⟩, rw ←h, apply computation.lift_rel.refl, intro a, cases a with a, simp, cases a; simp, apply H end theorem lift_rel_o.swap (R : α → β → Prop) (C) : function.swap (lift_rel_o R C) = lift_rel_o (function.swap R) (function.swap C) := by funext x y; cases x with x; [skip, cases x]; { cases y with y; [skip, cases y]; refl } theorem lift_rel.swap_lem {R : α → β → Prop} {s1 s2} (h : lift_rel R s1 s2) : lift_rel (function.swap R) s2 s1 := begin refine ⟨function.swap (lift_rel R), h, λ s t (h : lift_rel R t s), _⟩, rw [←lift_rel_o.swap, computation.lift_rel.swap], apply lift_rel_destruct h end theorem lift_rel.swap (R : α → β → Prop) : function.swap (lift_rel R) = lift_rel (function.swap R) := funext $ λ x, funext $ λ y, propext ⟨lift_rel.swap_lem, lift_rel.swap_lem⟩ theorem lift_rel.symm (R : α → α → Prop) (H : symmetric R) : symmetric (lift_rel R) := λ s1 s2 (h : function.swap (lift_rel R) s2 s1), by rwa [lift_rel.swap, show function.swap R = R, from funext $ λ a, funext $ λ b, propext $ by constructor; apply H] at h theorem lift_rel.trans (R : α → α → Prop) (H : transitive R) : transitive (lift_rel R) := λ s t u h1 h2, begin refine ⟨λ s u, ∃ t, lift_rel R s t ∧ lift_rel R t u, ⟨t, h1, h2⟩, λ s u h, _⟩, rcases h with ⟨t, h1, h2⟩, have h1 := lift_rel_destruct h1, have h2 := lift_rel_destruct h2, refine computation.lift_rel_def.2 ⟨(computation.terminates_of_lift_rel h1).trans (computation.terminates_of_lift_rel h2), λ a c ha hc, _⟩, rcases h1.left ha with ⟨b, hb, t1⟩, have t2 := computation.rel_of_lift_rel h2 hb hc, cases a with a; cases c with c, { trivial }, { cases b, {cases t2}, {cases t1} }, { cases a, cases b with b, {cases t1}, {cases b, cases t2} }, { cases a with a s, cases b with b, {cases t1}, cases b with b t, cases c with c u, cases t1 with ab st, cases t2 with bc tu, exact ⟨H ab bc, t, st, tu⟩ } end theorem lift_rel.equiv (R : α → α → Prop) : equivalence R → equivalence (lift_rel R) | ⟨refl, symm, trans⟩ := ⟨lift_rel.refl R refl, lift_rel.symm R symm, lift_rel.trans R trans⟩ @[refl] theorem equiv.refl : ∀ (s : wseq α), s ~ s := lift_rel.refl (=) eq.refl @[symm] theorem equiv.symm : ∀ {s t : wseq α}, s ~ t → t ~ s := lift_rel.symm (=) (@eq.symm _) @[trans] theorem equiv.trans : ∀ {s t u : wseq α}, s ~ t → t ~ u → s ~ u := lift_rel.trans (=) (@eq.trans _) theorem equiv.equivalence : equivalence (@equiv α) := ⟨@equiv.refl _, @equiv.symm _, @equiv.trans _⟩ open computation local notation `return` := computation.return @[simp] theorem destruct_nil : destruct (nil : wseq α) = return none := computation.destruct_eq_ret rfl @[simp] theorem destruct_cons (a : α) (s) : destruct (cons a s) = return (some (a, s)) := computation.destruct_eq_ret $ by simp [destruct, cons, computation.rmap] @[simp] theorem destruct_think (s : wseq α) : destruct (think s) = (destruct s).think := computation.destruct_eq_think $ by simp [destruct, think, computation.rmap] @[simp] theorem seq_destruct_nil : seq.destruct (nil : wseq α) = none := seq.destruct_nil @[simp] theorem seq_destruct_cons (a : α) (s) : seq.destruct (cons a s) = some (some a, s) := seq.destruct_cons _ _ @[simp] theorem seq_destruct_think (s : wseq α) : seq.destruct (think s) = some (none, s) := seq.destruct_cons _ _ @[simp] theorem head_nil : head (nil : wseq α) = return none := by simp [head]; refl @[simp] theorem head_cons (a : α) (s) : head (cons a s) = return (some a) := by simp [head]; refl @[simp] theorem head_think (s : wseq α) : head (think s) = (head s).think := by simp [head]; refl @[simp] theorem flatten_ret (s : wseq α) : flatten (return s) = s := begin refine seq.eq_of_bisim (λs1 s2, flatten (return s2) = s1) _ rfl, intros s' s h, rw ←h, simp [flatten], cases seq.destruct s, { simp }, { cases val with o s', simp } end @[simp] theorem flatten_think (c : computation (wseq α)) : flatten c.think = think (flatten c) := seq.destruct_eq_cons $ by simp [flatten, think] @[simp] theorem destruct_flatten (c : computation (wseq α)) : destruct (flatten c) = c >>= destruct := begin refine computation.eq_of_bisim (λc1 c2, c1 = c2 ∨ ∃ c, c1 = destruct (flatten c) ∧ c2 = computation.bind c destruct) _ (or.inr ⟨c, rfl, rfl⟩), intros c1 c2 h, exact match c1, c2, h with | _, _, (or.inl $ eq.refl c) := by cases c.destruct; simp | _, _, (or.inr ⟨c, rfl, rfl⟩) := begin apply c.cases_on (λa, _) (λc', _); repeat {simp}, { cases (destruct a).destruct; simp }, { exact or.inr ⟨c', rfl, rfl⟩ } end end end theorem head_terminates_iff (s : wseq α) : terminates (head s) ↔ terminates (destruct s) := terminates_map_iff _ (destruct s) @[simp] theorem tail_nil : tail (nil : wseq α) = nil := by simp [tail] @[simp] theorem tail_cons (a : α) (s) : tail (cons a s) = s := by simp [tail] @[simp] theorem tail_think (s : wseq α) : tail (think s) = (tail s).think := by simp [tail] @[simp] theorem dropn_nil (n) : drop (nil : wseq α) n = nil := by induction n; simp [*, drop] @[simp] theorem dropn_cons (a : α) (s) (n) : drop (cons a s) (n+1) = drop s n := by induction n; simp [*, drop] @[simp] theorem dropn_think (s : wseq α) (n) : drop (think s) n = (drop s n).think := by induction n; simp [*, drop] theorem dropn_add (s : wseq α) (m) : ∀ n, drop s (m + n) = drop (drop s m) n | 0 := rfl | (n+1) := congr_arg tail (dropn_add n) theorem dropn_tail (s : wseq α) (n) : drop (tail s) n = drop s (n + 1) := by rw add_comm; symmetry; apply dropn_add theorem nth_add (s : wseq α) (m n) : nth s (m + n) = nth (drop s m) n := congr_arg head (dropn_add _ _ _) theorem nth_tail (s : wseq α) (n) : nth (tail s) n = nth s (n + 1) := congr_arg head (dropn_tail _ _) @[simp] theorem join_nil : join nil = (nil : wseq α) := seq.join_nil @[simp] theorem join_think (S : wseq (wseq α)) : join (think S) = think (join S) := by { simp [think, join], unfold functor.map, simp [join, seq1.ret] } @[simp] theorem join_cons (s : wseq α) (S) : join (cons s S) = think (append s (join S)) := by { simp [think, join], unfold functor.map, simp [join, cons, append] } @[simp] theorem nil_append (s : wseq α) : append nil s = s := seq.nil_append _ @[simp] theorem cons_append (a : α) (s t) : append (cons a s) t = cons a (append s t) := seq.cons_append _ _ _ @[simp] theorem think_append (s t : wseq α) : append (think s) t = think (append s t) := seq.cons_append _ _ _ @[simp] theorem append_nil (s : wseq α) : append s nil = s := seq.append_nil _ @[simp] theorem append_assoc (s t u : wseq α) : append (append s t) u = append s (append t u) := seq.append_assoc _ _ _ @[simp] def tail.aux : option (α × wseq α) → computation (option (α × wseq α)) | none := return none | (some (a, s)) := destruct s theorem destruct_tail (s : wseq α) : destruct (tail s) = destruct s >>= tail.aux := begin simp [tail], rw [← bind_pure_comp_eq_map, is_lawful_monad.bind_assoc], apply congr_arg, ext1 (_|⟨a, s⟩); apply (@pure_bind computation _ _ _ _ _ _).trans _; simp end @[simp] def drop.aux : ℕ → option (α × wseq α) → computation (option (α × wseq α)) | 0 := return | (n+1) := λ a, tail.aux a >>= drop.aux n theorem drop.aux_none : ∀ n, @drop.aux α n none = return none | 0 := rfl | (n+1) := show computation.bind (return none) (drop.aux n) = return none, by rw [ret_bind, drop.aux_none] theorem destruct_dropn : ∀ (s : wseq α) n, destruct (drop s n) = destruct s >>= drop.aux n | s 0 := (bind_ret' _).symm | s (n+1) := by rw [← dropn_tail, destruct_dropn _ n, destruct_tail, is_lawful_monad.bind_assoc]; refl theorem head_terminates_of_head_tail_terminates (s : wseq α) [T : terminates (head (tail s))] : terminates (head s) := (head_terminates_iff _).2 $ begin cases (head_terminates_iff _).1 T with a h, simp [tail] at h, rcases exists_of_mem_bind h with ⟨s', h1, h2⟩, unfold functor.map at h1, exact let ⟨t, h3, h4⟩ := exists_of_mem_map h1 in terminates_of_mem h3 end theorem destruct_some_of_destruct_tail_some {s : wseq α} {a} (h : some a ∈ destruct (tail s)) : ∃ a', some a' ∈ destruct s := begin unfold tail functor.map at h, simp at h, rcases exists_of_mem_bind h with ⟨t, tm, td⟩, clear h, rcases exists_of_mem_map tm with ⟨t', ht', ht2⟩, clear tm, cases t' with t'; rw ←ht2 at td; simp at td, { have := mem_unique td (ret_mem _), contradiction }, { exact ⟨_, ht'⟩ } end theorem head_some_of_head_tail_some {s : wseq α} {a} (h : some a ∈ head (tail s)) : ∃ a', some a' ∈ head s := begin unfold head at h, rcases exists_of_mem_map h with ⟨o, md, e⟩, clear h, cases o with o; injection e with h', clear e h', cases destruct_some_of_destruct_tail_some md with a am, exact ⟨_, mem_map ((<$>) (@prod.fst α (wseq α))) am⟩ end theorem head_some_of_nth_some {s : wseq α} {a n} (h : some a ∈ nth s n) : ∃ a', some a' ∈ head s := begin revert a, induction n with n IH; intros, exacts [⟨_, h⟩, let ⟨a', h'⟩ := head_some_of_head_tail_some h in IH h'] end instance productive_tail (s : wseq α) [productive s] : productive (tail s) := λ n, by rw [nth_tail]; apply_instance instance productive_dropn (s : wseq α) [productive s] (n) : productive (drop s n) := λ m, by rw [←nth_add]; apply_instance /-- Given a productive weak sequence, we can collapse all the `think`s to produce a sequence. -/ def to_seq (s : wseq α) [productive s] : seq α := ⟨λ n, (nth s n).get, λn h, begin cases e : computation.get (nth s (n + 1)), {assumption}, have := mem_of_get_eq _ e, simp [nth] at this h, cases head_some_of_head_tail_some this with a' h', have := mem_unique h' (@mem_of_get_eq _ _ _ _ h), contradiction end⟩ theorem nth_terminates_le {s : wseq α} {m n} (h : m ≤ n) : terminates (nth s n) → terminates (nth s m) := by induction h with m' h IH; [exact id, exact λ T, IH (@head_terminates_of_head_tail_terminates _ _ T)] theorem head_terminates_of_nth_terminates {s : wseq α} {n} : terminates (nth s n) → terminates (head s) := nth_terminates_le (nat.zero_le n) theorem destruct_terminates_of_nth_terminates {s : wseq α} {n} (T : terminates (nth s n)) : terminates (destruct s) := (head_terminates_iff _).1 $ head_terminates_of_nth_terminates T theorem mem_rec_on {C : wseq α → Prop} {a s} (M : a ∈ s) (h1 : ∀ b s', (a = b ∨ C s') → C (cons b s')) (h2 : ∀ s, C s → C (think s)) : C s := begin apply seq.mem_rec_on M, intros o s' h, cases o with b, { apply h2, cases h, {contradiction}, {assumption} }, { apply h1, apply or.imp_left _ h, intro h, injection h } end @[simp] theorem mem_think (s : wseq α) (a) : a ∈ think s ↔ a ∈ s := begin cases s with f al, change some (some a) ∈ some none :: f ↔ some (some a) ∈ f, constructor; intro h, { apply (stream.eq_or_mem_of_mem_cons h).resolve_left, intro, injections }, { apply stream.mem_cons_of_mem _ h } end theorem eq_or_mem_iff_mem {s : wseq α} {a a' s'} : some (a', s') ∈ destruct s → (a ∈ s ↔ a = a' ∨ a ∈ s') := begin generalize e : destruct s = c, intro h, revert s, apply computation.mem_rec_on h _ (λ c IH, _); intro s; apply s.cases_on _ (λ x s, _) (λ s, _); intros m; have := congr_arg computation.destruct m; simp at this; cases this with i1 i2, { rw [i1, i2], cases s' with f al, unfold cons has_mem.mem wseq.mem seq.mem seq.cons, simp, have h_a_eq_a' : a = a' ↔ some (some a) = some (some a'), {simp}, rw [h_a_eq_a'], refine ⟨stream.eq_or_mem_of_mem_cons, λo, _⟩, { cases o with e m, { rw e, apply stream.mem_cons }, { exact stream.mem_cons_of_mem _ m } } }, { simp, exact IH this } end @[simp] theorem mem_cons_iff (s : wseq α) (b) {a} : a ∈ cons b s ↔ a = b ∨ a ∈ s := eq_or_mem_iff_mem $ by simp [ret_mem] theorem mem_cons_of_mem {s : wseq α} (b) {a} (h : a ∈ s) : a ∈ cons b s := (mem_cons_iff _ _).2 (or.inr h) theorem mem_cons (s : wseq α) (a) : a ∈ cons a s := (mem_cons_iff _ _).2 (or.inl rfl) theorem mem_of_mem_tail {s : wseq α} {a} : a ∈ tail s → a ∈ s := begin intro h, have := h, cases h with n e, revert s, simp [stream.nth], induction n with n IH; intro s; apply s.cases_on _ (λx s, _) (λ s, _); repeat{simp}; intros m e; injections, { exact or.inr m }, { exact or.inr m }, { apply IH m, rw e, cases tail s, refl } end theorem mem_of_mem_dropn {s : wseq α} {a} : ∀ {n}, a ∈ drop s n → a ∈ s | 0 h := h | (n+1) h := @mem_of_mem_dropn n (mem_of_mem_tail h) theorem nth_mem {s : wseq α} {a n} : some a ∈ nth s n → a ∈ s := begin revert s, induction n with n IH; intros s h, { rcases exists_of_mem_map h with ⟨o, h1, h2⟩, cases o with o; injection h2 with h', cases o with a' s', exact (eq_or_mem_iff_mem h1).2 (or.inl h'.symm) }, { have := @IH (tail s), rw nth_tail at this, exact mem_of_mem_tail (this h) } end theorem exists_nth_of_mem {s : wseq α} {a} (h : a ∈ s) : ∃ n, some a ∈ nth s n := begin apply mem_rec_on h, { intros a' s' h, cases h with h h, { existsi 0, simp [nth], rw h, apply ret_mem }, { cases h with n h, existsi n+1, simp [nth], exact h } }, { intros s' h, cases h with n h, existsi n, simp [nth], apply think_mem h } end theorem exists_dropn_of_mem {s : wseq α} {a} (h : a ∈ s) : ∃ n s', some (a, s') ∈ destruct (drop s n) := let ⟨n, h⟩ := exists_nth_of_mem h in ⟨n, begin cases (head_terminates_iff _).1 ⟨_, h⟩ with o om, have := mem_unique (mem_map _ om) h, cases o with o; injection this with i, cases o with a' s', dsimp at i, rw i at om, exact ⟨_, om⟩ end⟩ theorem lift_rel_dropn_destruct {R : α → β → Prop} {s t} (H : lift_rel R s t) : ∀ n, computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct (drop s n)) (destruct (drop t n)) | 0 := lift_rel_destruct H | (n+1) := begin simp [destruct_tail], apply lift_rel_bind, apply lift_rel_dropn_destruct n, exact λ a b o, match a, b, o with | none, none, _ := by simp | some (a, s), some (b, t), ⟨h1, h2⟩ := by simp [tail.aux]; apply lift_rel_destruct h2 end end theorem exists_of_lift_rel_left {R : α → β → Prop} {s t} (H : lift_rel R s t) {a} (h : a ∈ s) : ∃ {b}, b ∈ t ∧ R a b := let ⟨n, h⟩ := exists_nth_of_mem h, ⟨some (._, s'), sd, rfl⟩ := exists_of_mem_map h, ⟨some (b, t'), td, ⟨ab, _⟩⟩ := (lift_rel_dropn_destruct H n).left sd in ⟨b, nth_mem (mem_map ((<$>) prod.fst.{v v}) td), ab⟩ theorem exists_of_lift_rel_right {R : α → β → Prop} {s t} (H : lift_rel R s t) {b} (h : b ∈ t) : ∃ {a}, a ∈ s ∧ R a b := by rw ←lift_rel.swap at H; exact exists_of_lift_rel_left H h theorem head_terminates_of_mem {s : wseq α} {a} (h : a ∈ s) : terminates (head s) := let ⟨n, h⟩ := exists_nth_of_mem h in head_terminates_of_nth_terminates ⟨_, h⟩ theorem of_mem_append {s₁ s₂ : wseq α} {a : α} : a ∈ append s₁ s₂ → a ∈ s₁ ∨ a ∈ s₂ := seq.of_mem_append theorem mem_append_left {s₁ s₂ : wseq α} {a : α} : a ∈ s₁ → a ∈ append s₁ s₂ := seq.mem_append_left theorem exists_of_mem_map {f} {b : β} : ∀ {s : wseq α}, b ∈ map f s → ∃ a, a ∈ s ∧ f a = b | ⟨g, al⟩ h := let ⟨o, om, oe⟩ := seq.exists_of_mem_map h in by cases o with a; injection oe with h'; exact ⟨a, om, h'⟩ @[simp] theorem lift_rel_nil (R : α → β → Prop) : lift_rel R nil nil := by rw [lift_rel_destruct_iff]; simp @[simp] theorem lift_rel_cons (R : α → β → Prop) (a b s t) : lift_rel R (cons a s) (cons b t) ↔ R a b ∧ lift_rel R s t := by rw [lift_rel_destruct_iff]; simp @[simp] theorem lift_rel_think_left (R : α → β → Prop) (s t) : lift_rel R (think s) t ↔ lift_rel R s t := by rw [lift_rel_destruct_iff, lift_rel_destruct_iff]; simp @[simp] theorem lift_rel_think_right (R : α → β → Prop) (s t) : lift_rel R s (think t) ↔ lift_rel R s t := by rw [lift_rel_destruct_iff, lift_rel_destruct_iff]; simp theorem cons_congr {s t : wseq α} (a : α) (h : s ~ t) : cons a s ~ cons a t := by unfold equiv; simp; exact h theorem think_equiv (s : wseq α) : think s ~ s := by unfold equiv; simp; apply equiv.refl theorem think_congr {s t : wseq α} (a : α) (h : s ~ t) : think s ~ think t := by unfold equiv; simp; exact h theorem head_congr : ∀ {s t : wseq α}, s ~ t → head s ~ head t := suffices ∀ {s t : wseq α}, s ~ t → ∀ {o}, o ∈ head s → o ∈ head t, from λ s t h o, ⟨this h, this h.symm⟩, begin intros s t h o ho, rcases @computation.exists_of_mem_map _ _ _ _ (destruct s) ho with ⟨ds, dsm, dse⟩, rw ←dse, cases destruct_congr h with l r, rcases l dsm with ⟨dt, dtm, dst⟩, cases ds with a; cases dt with b, { apply mem_map _ dtm }, { cases b, cases dst }, { cases a, cases dst }, { cases a with a s', cases b with b t', rw dst.left, exact @mem_map _ _ (@functor.map _ _ (α × wseq α) _ prod.fst) _ (destruct t) dtm } end theorem flatten_equiv {c : computation (wseq α)} {s} (h : s ∈ c) : flatten c ~ s := begin apply computation.mem_rec_on h, { simp }, { intro s', apply equiv.trans, simp [think_equiv] } end theorem lift_rel_flatten {R : α → β → Prop} {c1 : computation (wseq α)} {c2 : computation (wseq β)} (h : c1.lift_rel (lift_rel R) c2) : lift_rel R (flatten c1) (flatten c2) := let S := λ s t, ∃ c1 c2, s = flatten c1 ∧ t = flatten c2 ∧ computation.lift_rel (lift_rel R) c1 c2 in ⟨S, ⟨c1, c2, rfl, rfl, h⟩, λ s t h, match s, t, h with ._, ._, ⟨c1, c2, rfl, rfl, h⟩ := begin simp, apply lift_rel_bind _ _ h, intros a b ab, apply computation.lift_rel.imp _ _ _ (lift_rel_destruct ab), intros a b, apply lift_rel_o.imp_right, intros s t h, refine ⟨return s, return t, _, _, _⟩; simp [h] end end⟩ theorem flatten_congr {c1 c2 : computation (wseq α)} : computation.lift_rel equiv c1 c2 → flatten c1 ~ flatten c2 := lift_rel_flatten theorem tail_congr {s t : wseq α} (h : s ~ t) : tail s ~ tail t := begin apply flatten_congr, unfold functor.map, rw [←bind_ret, ←bind_ret], apply lift_rel_bind _ _ (destruct_congr h), intros a b h, simp, cases a with a; cases b with b, { trivial }, { cases h }, { cases a, cases h }, { cases a with a s', cases b with b t', exact h.right } end theorem dropn_congr {s t : wseq α} (h : s ~ t) (n) : drop s n ~ drop t n := by induction n; simp [*, tail_congr] theorem nth_congr {s t : wseq α} (h : s ~ t) (n) : nth s n ~ nth t n := head_congr (dropn_congr h _) theorem mem_congr {s t : wseq α} (h : s ~ t) (a) : a ∈ s ↔ a ∈ t := suffices ∀ {s t : wseq α}, s ~ t → a ∈ s → a ∈ t, from ⟨this h, this h.symm⟩, λ s t h as, let ⟨n, hn⟩ := exists_nth_of_mem as in nth_mem ((nth_congr h _ _).1 hn) theorem productive_congr {s t : wseq α} (h : s ~ t) : productive s ↔ productive t := forall_congr $ λn, terminates_congr $ nth_congr h _ theorem equiv.ext {s t : wseq α} (h : ∀ n, nth s n ~ nth t n) : s ~ t := ⟨λ s t, ∀ n, nth s n ~ nth t n, h, λs t h, begin refine lift_rel_def.2 ⟨_, _⟩, { rw [←head_terminates_iff, ←head_terminates_iff], exact terminates_congr (h 0) }, { intros a b ma mb, cases a with a; cases b with b, { trivial }, { injection mem_unique (mem_map _ ma) ((h 0 _).2 (mem_map _ mb)) }, { injection mem_unique (mem_map _ ma) ((h 0 _).2 (mem_map _ mb)) }, { cases a with a s', cases b with b t', injection mem_unique (mem_map _ ma) ((h 0 _).2 (mem_map _ mb)) with ab, refine ⟨ab, λ n, _⟩, refine (nth_congr (flatten_equiv (mem_map _ ma)) n).symm.trans ((_ : nth (tail s) n ~ nth (tail t) n).trans (nth_congr (flatten_equiv (mem_map _ mb)) n)), rw [nth_tail, nth_tail], apply h } } end⟩ theorem length_eq_map (s : wseq α) : length s = computation.map list.length (to_list s) := begin refine eq_of_bisim (λ c1 c2, ∃ (l : list α) (s : wseq α), c1 = corec length._match_2 (l.length, s) ∧ c2 = computation.map list.length (corec to_list._match_2 (l, s))) _ ⟨[], s, rfl, rfl⟩, intros s1 s2 h, rcases h with ⟨l, s, h⟩, rw [h.left, h.right], apply s.cases_on _ (λ a s, _) (λ s, _); repeat {simp [to_list, nil, cons, think, length]}, { refine ⟨a::l, s, _, _⟩; simp }, { refine ⟨l, s, _, _⟩; simp } end @[simp] theorem of_list_nil : of_list [] = (nil : wseq α) := rfl @[simp] theorem of_list_cons (a : α) (l) : of_list (a :: l) = cons a (of_list l) := show seq.map some (seq.of_list (a :: l)) = seq.cons (some a) (seq.map some (seq.of_list l)), by simp @[simp] theorem to_list'_nil (l : list α) : corec to_list._match_2 (l, nil) = return l.reverse := destruct_eq_ret rfl @[simp] theorem to_list'_cons (l : list α) (s : wseq α) (a : α) : corec to_list._match_2 (l, cons a s) = (corec to_list._match_2 (a::l, s)).think := destruct_eq_think $ by simp [to_list, cons] @[simp] theorem to_list'_think (l : list α) (s : wseq α) : corec to_list._match_2 (l, think s) = (corec to_list._match_2 (l, s)).think := destruct_eq_think $ by simp [to_list, think] theorem to_list'_map (l : list α) (s : wseq α) : corec to_list._match_2 (l, s) = ((++) l.reverse) <$> to_list s := begin refine eq_of_bisim (λ c1 c2, ∃ (l' : list α) (s : wseq α), c1 = corec to_list._match_2 (l' ++ l, s) ∧ c2 = computation.map ((++) l.reverse) (corec to_list._match_2 (l', s))) _ ⟨[], s, rfl, rfl⟩, intros s1 s2 h, rcases h with ⟨l', s, h⟩, rw [h.left, h.right], apply s.cases_on _ (λ a s, _) (λ s, _); repeat {simp [to_list, nil, cons, think, length]}, { refine ⟨a::l', s, _, _⟩; simp }, { refine ⟨l', s, _, _⟩; simp } end @[simp] theorem to_list_cons (a : α) (s) : to_list (cons a s) = (list.cons a <$> to_list s).think := destruct_eq_think $ by unfold to_list; simp; rw to_list'_map; simp; refl @[simp] theorem to_list_nil : to_list (nil : wseq α) = return [] := destruct_eq_ret rfl theorem to_list_of_list (l : list α) : l ∈ to_list (of_list l) := by induction l with a l IH; simp [ret_mem]; exact think_mem (mem_map _ IH) @[simp] theorem destruct_of_seq (s : seq α) : destruct (of_seq s) = return (s.head.map $ λ a, (a, of_seq s.tail)) := destruct_eq_ret $ begin simp [of_seq, head, destruct, seq.destruct, seq.head], rw [show seq.nth (some <$> s) 0 = some <$> seq.nth s 0, by apply seq.map_nth], cases seq.nth s 0 with a, { refl }, unfold functor.map, simp [destruct] end @[simp] theorem head_of_seq (s : seq α) : head (of_seq s) = return s.head := by simp [head]; cases seq.head s; refl @[simp] theorem tail_of_seq (s : seq α) : tail (of_seq s) = of_seq s.tail := begin simp [tail], apply s.cases_on _ (λ x s, _); simp [of_seq], {refl}, rw [seq.head_cons, seq.tail_cons], refl end @[simp] theorem dropn_of_seq (s : seq α) : ∀ n, drop (of_seq s) n = of_seq (s.drop n) | 0 := rfl | (n+1) := by dsimp [drop]; rw [dropn_of_seq, tail_of_seq] theorem nth_of_seq (s : seq α) (n) : nth (of_seq s) n = return (seq.nth s n) := by dsimp [nth]; rw [dropn_of_seq, head_of_seq, seq.head_dropn] instance productive_of_seq (s : seq α) : productive (of_seq s) := λ n, by rw nth_of_seq; apply_instance theorem to_seq_of_seq (s : seq α) : to_seq (of_seq s) = s := begin apply subtype.eq, funext n, dsimp [to_seq], apply get_eq_of_mem, rw nth_of_seq, apply ret_mem end /-- The monadic `return a` is a singleton list containing `a`. -/ def ret (a : α) : wseq α := of_list [a] @[simp] theorem map_nil (f : α → β) : map f nil = nil := rfl @[simp] theorem map_cons (f : α → β) (a s) : map f (cons a s) = cons (f a) (map f s) := seq.map_cons _ _ _ @[simp] theorem map_think (f : α → β) (s) : map f (think s) = think (map f s) := seq.map_cons _ _ _ @[simp] theorem map_id (s : wseq α) : map id s = s := by simp [map] @[simp] theorem map_ret (f : α → β) (a) : map f (ret a) = ret (f a) := by simp [ret] @[simp] theorem map_append (f : α → β) (s t) : map f (append s t) = append (map f s) (map f t) := seq.map_append _ _ _ theorem map_comp (f : α → β) (g : β → γ) (s : wseq α) : map (g ∘ f) s = map g (map f s) := begin dsimp [map], rw ←seq.map_comp, apply congr_fun, apply congr_arg, ext ⟨⟩; refl end theorem mem_map (f : α → β) {a : α} {s : wseq α} : a ∈ s → f a ∈ map f s := seq.mem_map (option.map f) -- The converse is not true without additional assumptions theorem exists_of_mem_join {a : α} : ∀ {S : wseq (wseq α)}, a ∈ join S → ∃ s, s ∈ S ∧ a ∈ s := suffices ∀ ss : wseq α, a ∈ ss → ∀ s S, append s (join S) = ss → a ∈ append s (join S) → a ∈ s ∨ ∃ s, s ∈ S ∧ a ∈ s, from λ S h, (this _ h nil S (by simp) (by simp [h])).resolve_left (not_mem_nil _), begin intros ss h, apply mem_rec_on h (λ b ss o, _) (λ ss IH, _); intros s S, { refine s.cases_on (S.cases_on _ (λ s S, _) (λ S, _)) (λ b' s, _) (λ s, _); intros ej m; simp at ej; have := congr_arg seq.destruct ej; simp at this; try {cases this}; try {contradiction}, substs b' ss, simp at m ⊢, cases o with e IH, { simp [e] }, cases m with e m, { simp [e] }, exact or.imp_left or.inr (IH _ _ rfl m) }, { refine s.cases_on (S.cases_on _ (λ s S, _) (λ S, _)) (λ b' s, _) (λ s, _); intros ej m; simp at ej; have := congr_arg seq.destruct ej; simp at this; try { try {have := this.1}, contradiction }; subst ss, { apply or.inr, simp at m ⊢, cases IH s S rfl m with as ex, { exact ⟨s, or.inl rfl, as⟩ }, { rcases ex with ⟨s', sS, as⟩, exact ⟨s', or.inr sS, as⟩ } }, { apply or.inr, simp at m, rcases (IH nil S (by simp) (by simp [m])).resolve_left (not_mem_nil _) with ⟨s, sS, as⟩, exact ⟨s, by simp [sS], as⟩ }, { simp at m IH ⊢, apply IH _ _ rfl m } } end theorem exists_of_mem_bind {s : wseq α} {f : α → wseq β} {b} (h : b ∈ bind s f) : ∃ a ∈ s, b ∈ f a := let ⟨t, tm, bt⟩ := exists_of_mem_join h, ⟨a, as, e⟩ := exists_of_mem_map tm in ⟨a, as, by rwa e⟩ theorem destruct_map (f : α → β) (s : wseq α) : destruct (map f s) = computation.map (option.map (prod.map f (map f))) (destruct s) := begin apply eq_of_bisim (λ c1 c2, ∃ s, c1 = destruct (map f s) ∧ c2 = computation.map (option.map (prod.map f (map f))) (destruct s)), { intros c1 c2 h, cases h with s h, rw [h.left, h.right], apply s.cases_on _ (λ a s, _) (λ s, _); simp, exact ⟨s, rfl, rfl⟩ }, { exact ⟨s, rfl, rfl⟩ } end theorem lift_rel_map {δ} (R : α → β → Prop) (S : γ → δ → Prop) {s1 : wseq α} {s2 : wseq β} {f1 : α → γ} {f2 : β → δ} (h1 : lift_rel R s1 s2) (h2 : ∀ {a b}, R a b → S (f1 a) (f2 b)) : lift_rel S (map f1 s1) (map f2 s2) := ⟨λ s1 s2, ∃ s t, s1 = map f1 s ∧ s2 = map f2 t ∧ lift_rel R s t, ⟨s1, s2, rfl, rfl, h1⟩, λ s1 s2 h, match s1, s2, h with ._, ._, ⟨s, t, rfl, rfl, h⟩ := begin simp [destruct_map], apply computation.lift_rel_map _ _ (lift_rel_destruct h), intros o p h, cases o with a; cases p with b; simp, { cases b; cases h }, { cases a; cases h }, { cases a with a s; cases b with b t, cases h with r h, exact ⟨h2 r, s, rfl, t, rfl, h⟩ } end end⟩ theorem map_congr (f : α → β) {s t : wseq α} (h : s ~ t) : map f s ~ map f t := lift_rel_map _ _ h (λ _ _, congr_arg _) @[simp] def destruct_append.aux (t : wseq α) : option (α × wseq α) → computation (option (α × wseq α)) | none := destruct t | (some (a, s)) := return (some (a, append s t)) theorem destruct_append (s t : wseq α) : destruct (append s t) = (destruct s).bind (destruct_append.aux t) := begin apply eq_of_bisim (λ c1 c2, ∃ s t, c1 = destruct (append s t) ∧ c2 = (destruct s).bind (destruct_append.aux t)) _ ⟨s, t, rfl, rfl⟩, intros c1 c2 h, rcases h with ⟨s, t, h⟩, rw [h.left, h.right], apply s.cases_on _ (λ a s, _) (λ s, _); simp, { apply t.cases_on _ (λ b t, _) (λ t, _); simp, { refine ⟨nil, t, _, _⟩; simp } }, { exact ⟨s, t, rfl, rfl⟩ } end @[simp] def destruct_join.aux : option (wseq α × wseq (wseq α)) → computation (option (α × wseq α)) | none := return none | (some (s, S)) := (destruct (append s (join S))).think theorem destruct_join (S : wseq (wseq α)) : destruct (join S) = (destruct S).bind destruct_join.aux := begin apply eq_of_bisim (λ c1 c2, c1 = c2 ∨ ∃ S, c1 = destruct (join S) ∧ c2 = (destruct S).bind destruct_join.aux) _ (or.inr ⟨S, rfl, rfl⟩), intros c1 c2 h, exact match c1, c2, h with | _, _, (or.inl $ eq.refl c) := by cases c.destruct; simp | _, _, or.inr ⟨S, rfl, rfl⟩ := begin apply S.cases_on _ (λ s S, _) (λ S, _); simp, { refine or.inr ⟨S, rfl, rfl⟩ } end end end theorem lift_rel_append (R : α → β → Prop) {s1 s2 : wseq α} {t1 t2 : wseq β} (h1 : lift_rel R s1 t1) (h2 : lift_rel R s2 t2) : lift_rel R (append s1 s2) (append t1 t2) := ⟨λ s t, lift_rel R s t ∨ ∃ s1 t1, s = append s1 s2 ∧ t = append t1 t2 ∧ lift_rel R s1 t1, or.inr ⟨s1, t1, rfl, rfl, h1⟩, λ s t h, match s, t, h with | s, t, or.inl h := begin apply computation.lift_rel.imp _ _ _ (lift_rel_destruct h), intros a b, apply lift_rel_o.imp_right, intros s t, apply or.inl end | ._, ._, or.inr ⟨s1, t1, rfl, rfl, h⟩ := begin simp [destruct_append], apply computation.lift_rel_bind _ _ (lift_rel_destruct h), intros o p h, cases o with a; cases p with b, { simp, apply computation.lift_rel.imp _ _ _ (lift_rel_destruct h2), intros a b, apply lift_rel_o.imp_right, intros s t, apply or.inl }, { cases b; cases h }, { cases a; cases h }, { cases a with a s; cases b with b t, cases h with r h, simp, exact ⟨r, or.inr ⟨s, rfl, t, rfl, h⟩⟩ } end end⟩ theorem lift_rel_join.lem (R : α → β → Prop) {S T} {U : wseq α → wseq β → Prop} (ST : lift_rel (lift_rel R) S T) (HU : ∀ s1 s2, (∃ s t S T, s1 = append s (join S) ∧ s2 = append t (join T) ∧ lift_rel R s t ∧ lift_rel (lift_rel R) S T) → U s1 s2) {a} (ma : a ∈ destruct (join S)) : ∃ {b}, b ∈ destruct (join T) ∧ lift_rel_o R U a b := begin cases exists_results_of_mem ma with n h, clear ma, revert a S T, apply nat.strong_induction_on n _, intros n IH a S T ST ra, simp [destruct_join] at ra, exact let ⟨o, m, k, rs1, rs2, en⟩ := of_results_bind ra, ⟨p, mT, rop⟩ := computation.exists_of_lift_rel_left (lift_rel_destruct ST) rs1.mem in by exact match o, p, rop, rs1, rs2, mT with | none, none, _, rs1, rs2, mT := by simp [destruct_join]; exact ⟨none, mem_bind mT (ret_mem _), by rw eq_of_ret_mem rs2.mem; trivial⟩ | some (s, S'), some (t, T'), ⟨st, ST'⟩, rs1, rs2, mT := by simp [destruct_append] at rs2; exact let ⟨k1, rs3, ek⟩ := of_results_think rs2, ⟨o', m1, n1, rs4, rs5, ek1⟩ := of_results_bind rs3, ⟨p', mt, rop'⟩ := computation.exists_of_lift_rel_left (lift_rel_destruct st) rs4.mem in by exact match o', p', rop', rs4, rs5, mt with | none, none, _, rs4, rs5', mt := have n1 < n, begin rw [en, ek, ek1], apply lt_of_lt_of_le _ (nat.le_add_right _ _), apply nat.lt_succ_of_le (nat.le_add_right _ _) end, let ⟨ob, mb, rob⟩ := IH _ this ST' rs5' in by refine ⟨ob, _, rob⟩; { simp [destruct_join], apply mem_bind mT, simp [destruct_append], apply think_mem, apply mem_bind mt, exact mb } | some (a, s'), some (b, t'), ⟨ab, st'⟩, rs4, rs5, mt := begin simp at rs5, refine ⟨some (b, append t' (join T')), _, _⟩, { simp [destruct_join], apply mem_bind mT, simp [destruct_append], apply think_mem, apply mem_bind mt, apply ret_mem }, rw eq_of_ret_mem rs5.mem, exact ⟨ab, HU _ _ ⟨s', t', S', T', rfl, rfl, st', ST'⟩⟩ end end end end theorem lift_rel_join (R : α → β → Prop) {S : wseq (wseq α)} {T : wseq (wseq β)} (h : lift_rel (lift_rel R) S T) : lift_rel R (join S) (join T) := ⟨λ s1 s2, ∃ s t S T, s1 = append s (join S) ∧ s2 = append t (join T) ∧ lift_rel R s t ∧ lift_rel (lift_rel R) S T, ⟨nil, nil, S, T, by simp, by simp, by simp, h⟩, λs1 s2 ⟨s, t, S, T, h1, h2, st, ST⟩, begin clear _fun_match _x, rw [h1, h2], rw [destruct_append, destruct_append], apply computation.lift_rel_bind _ _ (lift_rel_destruct st), exact λ o p h, match o, p, h with | some (a, s), some (b, t), ⟨h1, h2⟩ := by simp; exact ⟨h1, s, t, S, rfl, T, rfl, h2, ST⟩ | none, none, _ := begin dsimp [destruct_append.aux, computation.lift_rel], constructor, { intro, apply lift_rel_join.lem _ ST (λ _ _, id) }, { intros b mb, rw [←lift_rel_o.swap], apply lift_rel_join.lem (function.swap R), { rw [←lift_rel.swap R, ←lift_rel.swap], apply ST }, { rw [←lift_rel.swap R, ←lift_rel.swap (lift_rel R)], exact λ s1 s2 ⟨s, t, S, T, h1, h2, st, ST⟩, ⟨t, s, T, S, h2, h1, st, ST⟩ }, { exact mb } } end end end⟩ theorem join_congr {S T : wseq (wseq α)} (h : lift_rel equiv S T) : join S ~ join T := lift_rel_join _ h theorem lift_rel_bind {δ} (R : α → β → Prop) (S : γ → δ → Prop) {s1 : wseq α} {s2 : wseq β} {f1 : α → wseq γ} {f2 : β → wseq δ} (h1 : lift_rel R s1 s2) (h2 : ∀ {a b}, R a b → lift_rel S (f1 a) (f2 b)) : lift_rel S (bind s1 f1) (bind s2 f2) := lift_rel_join _ (lift_rel_map _ _ h1 @h2) theorem bind_congr {s1 s2 : wseq α} {f1 f2 : α → wseq β} (h1 : s1 ~ s2) (h2 : ∀ a, f1 a ~ f2 a) : bind s1 f1 ~ bind s2 f2 := lift_rel_bind _ _ h1 (λ a b h, by rw h; apply h2) @[simp] theorem join_ret (s : wseq α) : join (ret s) ~ s := by simp [ret]; apply think_equiv @[simp] theorem join_map_ret (s : wseq α) : join (map ret s) ~ s := begin refine ⟨λ s1 s2, join (map ret s2) = s1, rfl, _⟩, intros s' s h, rw ←h, apply lift_rel_rec (λ c1 c2, ∃ s, c1 = destruct (join (map ret s)) ∧ c2 = destruct s), { exact λ c1 c2 h, match c1, c2, h with | ._, ._, ⟨s, rfl, rfl⟩ := begin clear h _match, apply s.cases_on _ (λ a s, _) (λ s, _); simp [ret], { refine ⟨_, ret_mem _, _⟩, simp }, { exact ⟨s, rfl, rfl⟩ } end end }, { exact ⟨s, rfl, rfl⟩ } end @[simp] theorem join_append (S T : wseq (wseq α)) : join (append S T) ~ append (join S) (join T) := begin refine ⟨λ s1 s2, ∃ s S T, s1 = append s (join (append S T)) ∧ s2 = append s (append (join S) (join T)), ⟨nil, S, T, by simp, by simp⟩, _⟩, intros s1 s2 h, apply lift_rel_rec (λ c1 c2, ∃ (s : wseq α) S T, c1 = destruct (append s (join (append S T))) ∧ c2 = destruct (append s (append (join S) (join T)))) _ _ _ (let ⟨s, S, T, h1, h2⟩ := h in ⟨s, S, T, congr_arg destruct h1, congr_arg destruct h2⟩), intros c1 c2 h, exact match c1, c2, h with ._, ._, ⟨s, S, T, rfl, rfl⟩ := begin clear _match h h, apply wseq.cases_on s _ (λ a s, _) (λ s, _); simp, { apply wseq.cases_on S _ (λ s S, _) (λ S, _); simp, { apply wseq.cases_on T _ (λ s T, _) (λ T, _); simp, { refine ⟨s, nil, T, _, _⟩; simp }, { refine ⟨nil, nil, T, _, _⟩; simp } }, { exact ⟨s, S, T, rfl, rfl⟩ }, { refine ⟨nil, S, T, _, _⟩; simp } }, { exact ⟨s, S, T, rfl, rfl⟩ }, { exact ⟨s, S, T, rfl, rfl⟩ } end end end @[simp] theorem bind_ret (f : α → β) (s) : bind s (ret ∘ f) ~ map f s := begin dsimp [bind], change (λx, ret (f x)) with (ret ∘ f), rw [map_comp], apply join_map_ret end @[simp] theorem ret_bind (a : α) (f : α → wseq β) : bind (ret a) f ~ f a := by simp [bind] @[simp] theorem map_join (f : α → β) (S) : map f (join S) = join (map (map f) S) := begin apply seq.eq_of_bisim (λs1 s2, ∃ s S, s1 = append s (map f (join S)) ∧ s2 = append s (join (map (map f) S))), { intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, S, rfl, rfl⟩ := begin apply wseq.cases_on s _ (λ a s, _) (λ s, _); simp, { apply wseq.cases_on S _ (λ s S, _) (λ S, _); simp, { exact ⟨map f s, S, rfl, rfl⟩ }, { refine ⟨nil, S, _, _⟩; simp } }, { exact ⟨_, _, rfl, rfl⟩ }, { exact ⟨_, _, rfl, rfl⟩ } end end }, { refine ⟨nil, S, _, _⟩; simp } end @[simp] theorem join_join (SS : wseq (wseq (wseq α))) : join (join SS) ~ join (map join SS) := begin refine ⟨λ s1 s2, ∃ s S SS, s1 = append s (join (append S (join SS))) ∧ s2 = append s (append (join S) (join (map join SS))), ⟨nil, nil, SS, by simp, by simp⟩, _⟩, intros s1 s2 h, apply lift_rel_rec (λ c1 c2, ∃ s S SS, c1 = destruct (append s (join (append S (join SS)))) ∧ c2 = destruct (append s (append (join S) (join (map join SS))))) _ (destruct s1) (destruct s2) (let ⟨s, S, SS, h1, h2⟩ := h in ⟨s, S, SS, by simp [h1], by simp [h2]⟩), intros c1 c2 h, exact match c1, c2, h with ._, ._, ⟨s, S, SS, rfl, rfl⟩ := begin clear _match h h, apply wseq.cases_on s _ (λ a s, _) (λ s, _); simp, { apply wseq.cases_on S _ (λ s S, _) (λ S, _); simp, { apply wseq.cases_on SS _ (λ S SS, _) (λ SS, _); simp, { refine ⟨nil, S, SS, _, _⟩; simp }, { refine ⟨nil, nil, SS, _, _⟩; simp } }, { exact ⟨s, S, SS, rfl, rfl⟩ }, { refine ⟨nil, S, SS, _, _⟩; simp } }, { exact ⟨s, S, SS, rfl, rfl⟩ }, { exact ⟨s, S, SS, rfl, rfl⟩ } end end end @[simp] theorem bind_assoc (s : wseq α) (f : α → wseq β) (g : β → wseq γ) : bind (bind s f) g ~ bind s (λ (x : α), bind (f x) g) := begin simp [bind], rw [← map_comp f (map g), map_comp (map g ∘ f) join], apply join_join end instance : monad wseq := { map := @map, pure := @ret, bind := @bind } /- Unfortunately, wseq is not a lawful monad, because it does not satisfy the monad laws exactly, only up to sequence equivalence. Furthermore, even quotienting by the equivalence is not sufficient, because the join operation involves lists of quotient elements, with a lifted equivalence relation, and pure quotients cannot handle this type of construction. instance : is_lawful_monad wseq := { id_map := @map_id, bind_pure_comp_eq_map := @bind_ret, pure_bind := @ret_bind, bind_assoc := @bind_assoc } -/ end wseq
2735ca7373daa1f313c3e12f71b7b49c1736224c
9bf90df35bb15a2f76571e35c48192142a328c40
/src/ch1.lean
3da233a1020b17fe6e8113d0cf73c6997213b8ad
[]
no_license
ehaskell1/set_theory
ed0726520e84990d5f3180bafa0a3674ed31fb5e
e6c829c4dd953d98c9cba08f9f79784cd91794fb
refs/heads/master
1,693,282,405,362
1,636,928,916,000
1,636,928,916,000
428,055,746
0
0
null
null
null
null
UTF-8
Lean
false
false
3,144
lean
import logic import set_theory.zfc namespace Set -- We have ext axiom. (Set.ext) -- Set.eq_empty proves there is only one empty set (using extensionality). -- We have pairing axiom. (Set.mem_pair) theorem pair_commutative {x y : Set} : ({x, y} : Set) = {y, x} := begin apply Set.ext, intro z, simp [Set.mem_pair] at *, exact or.comm, end theorem singleton_of_pair_self {x : Set} : ({x, x} : Set) = {x} := begin apply Set.ext, intro z, simp [Set.mem_pair] at *, end def from_list : list Set → Set | [] := ∅ | (hd :: tl) := {hd} ∪ from_list tl theorem mem_from_list {l : list Set} (z : Set) : z ∈ from_list l ↔ z ∈ l := begin induction l with hd tl ih, simp only [list.mem_nil_iff, iff_false, from_list], exact Set.mem_empty _, simp only [from_list, list.mem_cons_iff, Set.mem_union, Set.mem_singleton], rw ih, end theorem empty_is_subset (x : Set) : ∅ ⊆ x := begin intros z h, exfalso, exact (Set.mem_empty _) h, end theorem p2a : (∅ : Set) ≠ {∅} := begin intro he, have h : ∅ ∈ {∅} := Set.mem_singleton.mpr rfl, rw ←he at h, exact Set.mem_empty _ h, end theorem p2b : ({∅} : Set) ≠ {{∅}} := begin intro he, have h : {∅} ∈ {{∅}} := Set.mem_singleton.mpr rfl, rw ←he at h, rw Set.mem_singleton at h, exact p2a h.symm, end theorem p2c : (∅ : Set) ≠ {{∅}} := begin intro he, have h : {∅} ∈ {{∅}} := Set.mem_singleton.mpr rfl, rw ←he at h, exact Set.mem_empty _ h, end -- powerset axiom enabled by Set.powerset and Set.mem_powerset theorem p4 {x y B : Set} (h : {x, y} ⊆ B) : x.pair y ∈ B.powerset.powerset := begin simp only [Set.mem_powerset, Set.pair], intros z hm, simp only [Set.mem_pair] at hm, simp only [Set.mem_powerset], cases hm, { rw hm, intros s he, rw Set.mem_singleton at he, rw he, apply h, simp only [Set.mem_pair], left, refl, }, { rw hm, exact h, }, end def finite_hierarchy : ℕ → Set | 0 := ∅ | (n + 1) := let V := finite_hierarchy n in V ∪ V.powerset theorem subset_union_of_subset {x y z : Set} (h : x ⊆ z) : x ⊆ z ∪ y := begin intros c hm, specialize h hm, simp only [Set.mem_union], left, exact h, end theorem subset_finite_hierarchy_of_mem {n : ℕ} {x : Set} : x ∈ finite_hierarchy n → x ⊆ finite_hierarchy n := begin induction n with m ih, { simp only [finite_hierarchy], intro h, exfalso, exact Set.mem_empty _ h, }, { simp only [finite_hierarchy, Set.mem_union], intros h, cases h, exact subset_union_of_subset (ih h), exact subset_union_of_subset (Set.mem_powerset.mp h), }, end theorem finite_hierarchy_succ (n : ℕ) : finite_hierarchy (n + 1) = (finite_hierarchy n).powerset := begin simp only [finite_hierarchy], apply Set.ext, simp only [Set.mem_union], intro z, split; intro h, { cases h, simp only [Set.mem_powerset], exact subset_finite_hierarchy_of_mem h, exact h, }, { right, exact h, }, end lemma singleton_eq {x y : Set} : ({x} : Set) = {y} ↔ x = y := begin rw ←Set.ext_iff, simp only [Set.mem_singleton], exact eq_iff_eq_cancel_left, end end Set
a4fed8dffcc84e92941de012513465d97471553c
26ac254ecb57ffcb886ff709cf018390161a9225
/src/data/polynomial/derivative.lean
a71ed17d3a2dba13fa59f2303104f782f58e3a55
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
10,939
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.field_division /-! # Theory of univariate polynomials -/ noncomputable theory local attribute [instance, priority 100] classical.prop_decidable open finsupp finset add_monoid_algebra open_locale big_operators namespace polynomial universes u v w y z variables {R : Type u} {S : Type v} {T : Type w} {ι : Type y} {A : Type z} {a b : R} {n : ℕ} section derivative section semiring variables [semiring R] /-- `derivative p` is the formal derivative of the polynomial `p` -/ def derivative (p : polynomial R) : polynomial R := p.sum (λn a, C (a * n) * X^(n - 1)) lemma coeff_derivative (p : polynomial R) (n : ℕ) : coeff (derivative p) n = coeff p (n + 1) * (n + 1) := begin rw [derivative], simp only [coeff_X_pow, coeff_sum, coeff_C_mul], rw [finsupp.sum, finset.sum_eq_single (n + 1)], simp only [nat.add_succ_sub_one, add_zero, mul_one, if_true, eq_self_iff_true], norm_cast, swap, { rw [if_pos (nat.add_sub_cancel _ _).symm, mul_one, nat.cast_add, nat.cast_one, mem_support_iff], intro h, push_neg at h, simp [h], }, { assume b, cases b, { intros, rw [nat.cast_zero, mul_zero, zero_mul], }, { intros _ H, rw [nat.succ_sub_one b, if_neg (mt (congr_arg nat.succ) H.symm), mul_zero] } } end @[simp] lemma derivative_zero : derivative (0 : polynomial R) = 0 := finsupp.sum_zero_index lemma derivative_monomial (a : R) (n : ℕ) : derivative (C a * X ^ n) = C (a * n) * X^(n - 1) := begin rw [← single_eq_C_mul_X, ← single_eq_C_mul_X, derivative, monomial, sum_single_index, single_eq_C_mul_X], simp only [zero_mul, C_0], end @[simp] lemma derivative_C {a : R} : derivative (C a) = 0 := suffices derivative (C a * X^0) = C (a * 0:R) * X ^ 0, by simpa only [mul_one, zero_mul, C_0, mul_zero, pow_zero], derivative_monomial a 0 @[simp] lemma derivative_X : derivative (X : polynomial R) = 1 := by simpa only [mul_one, one_mul, C_1, pow_one, nat.cast_one, pow_zero] using derivative_monomial (1:R) 1 @[simp] lemma derivative_one : derivative (1 : polynomial R) = 0 := derivative_C @[simp] lemma derivative_add {f g : polynomial R} : derivative (f + g) = derivative f + derivative g := by refine finsupp.sum_add_index _ _; intros; simp only [add_mul, zero_mul, C_0, C_add, C_mul] /-- The formal derivative of polynomials, as additive homomorphism. -/ def derivative_hom (R : Type*) [semiring R] : polynomial R →+ polynomial R := { to_fun := derivative, map_zero' := derivative_zero, map_add' := λ p q, derivative_add } @[simp] lemma derivative_neg {R : Type*} [ring R] (f : polynomial R) : derivative (-f) = -derivative f := (derivative_hom R).map_neg f @[simp] lemma derivative_sub {R : Type*} [ring R] (f g : polynomial R) : derivative (f - g) = derivative f - derivative g := (derivative_hom R).map_sub f g instance : is_add_monoid_hom (derivative : polynomial R → polynomial R) := (derivative_hom R).is_add_monoid_hom @[simp] lemma derivative_sum {s : finset ι} {f : ι → polynomial R} : derivative (∑ b in s, f b) = ∑ b in s, derivative (f b) := (derivative_hom R).map_sum f s @[simp] lemma derivative_smul (r : R) (p : polynomial R) : derivative (r • p) = r • derivative p := by { ext, simp only [coeff_derivative, mul_assoc, coeff_smul], } end semiring section comm_semiring variables [comm_semiring R] @[simp] lemma derivative_mul {f g : polynomial R} : derivative (f * g) = derivative f * g + f * derivative g := calc derivative (f * g) = f.sum (λn a, g.sum (λm b, C ((a * b) * (n + m : ℕ)) * X^((n + m) - 1))) : begin transitivity, exact derivative_sum, transitivity, { apply finset.sum_congr rfl, assume x hx, exact derivative_sum }, apply finset.sum_congr rfl, assume n hn, apply finset.sum_congr rfl, assume m hm, transitivity, { apply congr_arg, exact single_eq_C_mul_X }, exact derivative_monomial _ _ end ... = f.sum (λn a, g.sum (λm b, (C (a * n) * X^(n - 1)) * (C b * X^m) + (C a * X^n) * (C (b * m) * X^(m - 1)))) : sum_congr rfl $ assume n hn, sum_congr rfl $ assume m hm, by simp only [nat.cast_add, mul_add, add_mul, C_add, C_mul]; cases n; simp only [nat.succ_sub_succ, pow_zero]; cases m; simp only [nat.cast_zero, C_0, nat.succ_sub_succ, zero_mul, mul_zero, nat.sub_zero, pow_zero, pow_add, one_mul, pow_succ, mul_comm, mul_left_comm] ... = derivative f * g + f * derivative g : begin conv { to_rhs, congr, { rw [← sum_C_mul_X_eq g] }, { rw [← sum_C_mul_X_eq f] } }, unfold derivative finsupp.sum, simp only [sum_add_distrib, finset.mul_sum, finset.sum_mul] end lemma derivative_eval (p : polynomial R) (x : R) : p.derivative.eval x = p.sum (λ n a, (a * n)*x^(n-1)) := by simp [derivative, eval_sum, eval_pow, -alg_hom.map_nat_cast] theorem derivative_pow_succ (p : polynomial R) (n : ℕ) : (p ^ (n + 1)).derivative = (n + 1) * (p ^ n) * p.derivative := nat.rec_on n (by rw [pow_one, nat.cast_zero, zero_add, one_mul, pow_zero, one_mul]) $ λ n ih, by rw [pow_succ', derivative_mul, ih, mul_right_comm, ← add_mul, add_mul (n.succ : polynomial R), one_mul, pow_succ', mul_assoc, n.cast_succ] theorem derivative_pow (p : polynomial R) (n : ℕ) : (p ^ n).derivative = n * (p ^ (n - 1)) * p.derivative := nat.cases_on n (by rw [pow_zero, derivative_one, nat.cast_zero, zero_mul, zero_mul]) $ λ n, by rw [p.derivative_pow_succ n, n.succ_sub_one, n.cast_succ] theorem derivative_map [comm_semiring S] (p : polynomial R) (f : R →+* S) : (p.map f).derivative = p.derivative.map f := polynomial.induction_on p (λ r, by rw [map_C, derivative_C, derivative_C, map_zero]) (λ p q ihp ihq, by rw [map_add, derivative_add, ihp, ihq, derivative_add, map_add]) (λ n r ih, by rw [map_mul, map_C, map_pow, map_X, derivative_mul, derivative_pow_succ, derivative_C, zero_mul, zero_add, derivative_X, mul_one, derivative_mul, derivative_pow_succ, derivative_C, zero_mul, zero_add, derivative_X, mul_one, map_mul, map_C, map_mul, map_pow, map_add, map_nat_cast, map_one, map_X]) /-- Chain rule for formal derivative of polynomials. -/ theorem derivative_eval₂_C (p q : polynomial R) : (p.eval₂ C q).derivative = p.derivative.eval₂ C q * q.derivative := polynomial.induction_on p (λ r, by rw [eval₂_C, derivative_C, eval₂_zero, zero_mul]) (λ p₁ p₂ ih₁ ih₂, by rw [eval₂_add, derivative_add, ih₁, ih₂, derivative_add, eval₂_add, add_mul]) (λ n r ih, by rw [pow_succ', ← mul_assoc, eval₂_mul, eval₂_X, derivative_mul, ih, @derivative_mul _ _ _ X, derivative_X, mul_one, eval₂_add, @eval₂_mul _ _ _ _ X, eval₂_X, add_mul, mul_right_comm]) theorem of_mem_support_derivative {p : polynomial R} {n : ℕ} (h : n ∈ p.derivative.support) : n + 1 ∈ p.support := finsupp.mem_support_iff.2 $ λ (h1 : p.coeff (n+1) = 0), finsupp.mem_support_iff.1 h $ show p.derivative.coeff n = 0, by rw [coeff_derivative, h1, zero_mul] theorem degree_derivative_lt {p : polynomial R} (hp : p ≠ 0) : p.derivative.degree < p.degree := (finset.sup_lt_iff $ bot_lt_iff_ne_bot.2 $ mt degree_eq_bot.1 hp).2 $ λ n hp, lt_of_lt_of_le (with_bot.some_lt_some.2 n.lt_succ_self) $ finset.le_sup $ of_mem_support_derivative hp theorem nat_degree_derivative_lt {p : polynomial R} (hp : p.derivative ≠ 0) : p.derivative.nat_degree < p.nat_degree := have hp1 : p ≠ 0, from λ h, hp $ by rw [h, derivative_zero], with_bot.some_lt_some.1 $ by { rw [nat_degree, option.get_or_else_of_ne_none $ mt degree_eq_bot.1 hp, nat_degree, option.get_or_else_of_ne_none $ mt degree_eq_bot.1 hp1], exact degree_derivative_lt hp1 } theorem degree_derivative_le {p : polynomial R} : p.derivative.degree ≤ p.degree := if H : p = 0 then le_of_eq $ by rw [H, derivative_zero] else le_of_lt $ degree_derivative_lt H /-- The formal derivative of polynomials, as linear homomorphism. -/ def derivative_lhom (R : Type*) [comm_ring R] : polynomial R →ₗ[R] polynomial R := { to_fun := derivative, map_add' := λ p q, derivative_add, map_smul' := λ r p, derivative_smul r p } /-- If `f` is a polynomial over a field, and `a : K` satisfies `f' a ≠ 0`, then `f / (X - a)` is coprime with `X - a`. Note that we do not assume `f a = 0`, because `f / (X - a) = (f - f a) / (X - a)`. -/ lemma is_coprime_of_is_root_of_eval_derivative_ne_zero {K : Type*} [field K] (f : polynomial K) (a : K) (hf' : f.derivative.eval a ≠ 0) : is_coprime (X - C a : polynomial K) (f /ₘ (X - C a)) := begin refine or.resolve_left (dvd_or_coprime (X - C a) (f /ₘ (X - C a)) (irreducible_of_degree_eq_one (polynomial.degree_X_sub_C a))) _, contrapose! hf' with h, have key : (X - C a) * (f /ₘ (X - C a)) = f - (f %ₘ (X - C a)), { rw [eq_sub_iff_add_eq, ← eq_sub_iff_add_eq', mod_by_monic_eq_sub_mul_div], exact monic_X_sub_C a }, replace key := congr_arg derivative key, simp only [derivative_X, derivative_mul, one_mul, sub_zero, derivative_sub, mod_by_monic_X_sub_C_eq_C_eval, derivative_C] at key, have : (X - C a) ∣ derivative f := key ▸ (dvd_add h (dvd_mul_right _ _)), rw [← dvd_iff_mod_by_monic_eq_zero (monic_X_sub_C _), mod_by_monic_X_sub_C_eq_C_eval] at this, rw [← C_inj, this, C_0], end end comm_semiring section domain variables [integral_domain R] -- TODO: golf this, dunno how i broke it so bad lemma mem_support_derivative [char_zero R] (p : polynomial R) (n : ℕ) : n ∈ (derivative p).support ↔ n + 1 ∈ p.support := begin rw finsupp.mem_support_iff, split; intro h, suffices h1 : p.coeff (n+1) ≠ 0, simp; tauto, contrapose! h, convert coeff_derivative _ _, simp [h], contrapose! h, simp, suffices : p.to_fun (n + 1) * (n + 1) = 0, simp only [mul_eq_zero] at this, cases this, { exact this }, { norm_cast at this }, erw ← h, symmetry, convert coeff_derivative _ _, end @[simp] lemma degree_derivative_eq [char_zero R] (p : polynomial R) (hp : 0 < nat_degree p) : degree (derivative p) = (nat_degree p - 1 : ℕ) := le_antisymm (le_trans (degree_sum_le _ _) $ sup_le $ assume n hn, have n ≤ nat_degree p, begin rw [← with_bot.coe_le_coe, ← degree_eq_nat_degree], { refine le_degree_of_ne_zero _, simpa only [mem_support_iff] using hn }, { assume h, simpa only [h, support_zero] using hn } end, le_trans (degree_monomial_le _ _) $ with_bot.coe_le_coe.2 $ nat.sub_le_sub_right this _) begin refine le_sup _, rw [mem_support_derivative, nat.sub_add_cancel, mem_support_iff], { show ¬ leading_coeff p = 0, rw [leading_coeff_eq_zero], assume h, rw [h, nat_degree_zero] at hp, exact lt_irrefl 0 (lt_of_le_of_lt (zero_le _) hp), }, exact hp end end domain end derivative end polynomial
725aee19d70d1d9067a1d579c4cdd20b29e81cbe
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/measure_theory/measurable_space_def.lean
b7d688c5a87b16f8d09eba631de43ed70b7e39cf
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
17,486
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import algebra.indicator_function import data.equiv.encodable.lattice import data.set.countable import order.disjointed import order.filter.basic import order.symm_diff /-! # Measurable spaces and measurable functions This file defines measurable spaces and measurable functions. A measurable space is a set equipped with a σ-algebra, a collection of subsets closed under complementation and countable union. A function between measurable spaces is measurable if the preimage of each measurable subset is measurable. σ-algebras on a fixed set `α` form a complete lattice. Here we order σ-algebras by writing `m₁ ≤ m₂` if every set which is `m₁`-measurable is also `m₂`-measurable (that is, `m₁` is a subset of `m₂`). In particular, any collection of subsets of `α` generates a smallest σ-algebra which contains all of them. Do not add measurability lemmas (which could be tagged with @[measurability]) to this file, since the measurability tactic is downstream from here. Use `measure_theory.measurable_space` instead. ## References * <https://en.wikipedia.org/wiki/Measurable_space> * <https://en.wikipedia.org/wiki/Sigma-algebra> * <https://en.wikipedia.org/wiki/Dynkin_system> ## Tags measurable space, σ-algebra, measurable function -/ open set encodable function equiv open_locale classical filter variables {α β γ δ δ' : Type*} {ι : Sort*} {s t u : set α} /-- A measurable space is a space equipped with a σ-algebra. -/ structure measurable_space (α : Type*) := (measurable_set' : set α → Prop) (measurable_set_empty : measurable_set' ∅) (measurable_set_compl : ∀ s, measurable_set' s → measurable_set' sᶜ) (measurable_set_Union : ∀ f : ℕ → set α, (∀ i, measurable_set' (f i)) → measurable_set' (⋃ i, f i)) attribute [class] measurable_space instance [h : measurable_space α] : measurable_space (order_dual α) := h section variable [measurable_space α] /-- `measurable_set s` means that `s` is measurable (in the ambient measure space on `α`) -/ def measurable_set : set α → Prop := ‹measurable_space α›.measurable_set' localized "notation `measurable_set[` m `]` := @measurable_set _ m" in measure_theory @[simp] lemma measurable_set.empty : measurable_set (∅ : set α) := ‹measurable_space α›.measurable_set_empty lemma measurable_set.compl : measurable_set s → measurable_set sᶜ := ‹measurable_space α›.measurable_set_compl s lemma measurable_set.of_compl (h : measurable_set sᶜ) : measurable_set s := compl_compl s ▸ h.compl @[simp] lemma measurable_set.compl_iff : measurable_set sᶜ ↔ measurable_set s := ⟨measurable_set.of_compl, measurable_set.compl⟩ @[simp] lemma measurable_set.univ : measurable_set (univ : set α) := by simpa using (@measurable_set.empty α _).compl @[nontriviality] lemma subsingleton.measurable_set [subsingleton α] {s : set α} : measurable_set s := subsingleton.set_cases measurable_set.empty measurable_set.univ s lemma measurable_set.congr {s t : set α} (hs : measurable_set s) (h : s = t) : measurable_set t := by rwa ← h lemma measurable_set.bUnion_decode₂ [encodable β] ⦃f : β → set α⦄ (h : ∀ b, measurable_set (f b)) (n : ℕ) : measurable_set (⋃ b ∈ decode₂ β n, f b) := encodable.Union_decode₂_cases measurable_set.empty h lemma measurable_set.Union [encodable β] ⦃f : β → set α⦄ (h : ∀ b, measurable_set (f b)) : measurable_set (⋃ b, f b) := begin rw ← encodable.Union_decode₂, exact ‹measurable_space α›.measurable_set_Union _ (measurable_set.bUnion_decode₂ h) end lemma measurable_set.bUnion {f : β → set α} {s : set β} (hs : countable s) (h : ∀ b ∈ s, measurable_set (f b)) : measurable_set (⋃ b ∈ s, f b) := begin rw bUnion_eq_Union, haveI := hs.to_encodable, exact measurable_set.Union (by simpa using h) end lemma set.finite.measurable_set_bUnion {f : β → set α} {s : set β} (hs : finite s) (h : ∀ b ∈ s, measurable_set (f b)) : measurable_set (⋃ b ∈ s, f b) := measurable_set.bUnion hs.countable h lemma finset.measurable_set_bUnion {f : β → set α} (s : finset β) (h : ∀ b ∈ s, measurable_set (f b)) : measurable_set (⋃ b ∈ s, f b) := s.finite_to_set.measurable_set_bUnion h lemma measurable_set.sUnion {s : set (set α)} (hs : countable s) (h : ∀ t ∈ s, measurable_set t) : measurable_set (⋃₀ s) := by { rw sUnion_eq_bUnion, exact measurable_set.bUnion hs h } lemma set.finite.measurable_set_sUnion {s : set (set α)} (hs : finite s) (h : ∀ t ∈ s, measurable_set t) : measurable_set (⋃₀ s) := measurable_set.sUnion hs.countable h lemma measurable_set.Union_Prop {p : Prop} {f : p → set α} (hf : ∀ b, measurable_set (f b)) : measurable_set (⋃ b, f b) := by { by_cases p; simp [h, hf, measurable_set.empty] } lemma measurable_set.Inter [encodable β] {f : β → set α} (h : ∀ b, measurable_set (f b)) : measurable_set (⋂ b, f b) := measurable_set.compl_iff.1 $ by { rw compl_Inter, exact measurable_set.Union (λ b, (h b).compl) } section fintype local attribute [instance] fintype.encodable lemma measurable_set.Union_fintype [fintype β] {f : β → set α} (h : ∀ b, measurable_set (f b)) : measurable_set (⋃ b, f b) := measurable_set.Union h lemma measurable_set.Inter_fintype [fintype β] {f : β → set α} (h : ∀ b, measurable_set (f b)) : measurable_set (⋂ b, f b) := measurable_set.Inter h end fintype lemma measurable_set.bInter {f : β → set α} {s : set β} (hs : countable s) (h : ∀ b ∈ s, measurable_set (f b)) : measurable_set (⋂ b ∈ s, f b) := measurable_set.compl_iff.1 $ by { rw compl_bInter, exact measurable_set.bUnion hs (λ b hb, (h b hb).compl) } lemma set.finite.measurable_set_bInter {f : β → set α} {s : set β} (hs : finite s) (h : ∀ b ∈ s, measurable_set (f b)) : measurable_set (⋂ b ∈ s, f b) := measurable_set.bInter hs.countable h lemma finset.measurable_set_bInter {f : β → set α} (s : finset β) (h : ∀ b ∈ s, measurable_set (f b)) : measurable_set (⋂ b ∈ s, f b) := s.finite_to_set.measurable_set_bInter h lemma measurable_set.sInter {s : set (set α)} (hs : countable s) (h : ∀ t ∈ s, measurable_set t) : measurable_set (⋂₀ s) := by { rw sInter_eq_bInter, exact measurable_set.bInter hs h } lemma set.finite.measurable_set_sInter {s : set (set α)} (hs : finite s) (h : ∀ t ∈ s, measurable_set t) : measurable_set (⋂₀ s) := measurable_set.sInter hs.countable h lemma measurable_set.Inter_Prop {p : Prop} {f : p → set α} (hf : ∀ b, measurable_set (f b)) : measurable_set (⋂ b, f b) := by { by_cases p; simp [h, hf, measurable_set.univ] } @[simp] lemma measurable_set.union {s₁ s₂ : set α} (h₁ : measurable_set s₁) (h₂ : measurable_set s₂) : measurable_set (s₁ ∪ s₂) := by { rw union_eq_Union, exact measurable_set.Union (bool.forall_bool.2 ⟨h₂, h₁⟩) } @[simp] lemma measurable_set.inter {s₁ s₂ : set α} (h₁ : measurable_set s₁) (h₂ : measurable_set s₂) : measurable_set (s₁ ∩ s₂) := by { rw inter_eq_compl_compl_union_compl, exact (h₁.compl.union h₂.compl).compl } @[simp] lemma measurable_set.diff {s₁ s₂ : set α} (h₁ : measurable_set s₁) (h₂ : measurable_set s₂) : measurable_set (s₁ \ s₂) := h₁.inter h₂.compl @[simp] lemma measurable_set.symm_diff {s₁ s₂ : set α} (h₁ : measurable_set s₁) (h₂ : measurable_set s₂) : measurable_set (s₁ Δ s₂) := (h₁.diff h₂).union (h₂.diff h₁) @[simp] lemma measurable_set.ite {t s₁ s₂ : set α} (ht : measurable_set t) (h₁ : measurable_set s₁) (h₂ : measurable_set s₂) : measurable_set (t.ite s₁ s₂) := (h₁.inter ht).union (h₂.diff ht) @[simp] lemma measurable_set.cond {s₁ s₂ : set α} (h₁ : measurable_set s₁) (h₂ : measurable_set s₂) {i : bool} : measurable_set (cond i s₁ s₂) := by { cases i, exacts [h₂, h₁] } @[simp] lemma measurable_set.disjointed {f : ℕ → set α} (h : ∀ i, measurable_set (f i)) (n) : measurable_set (disjointed f n) := disjointed_rec (λ t i ht, measurable_set.diff ht $ h _) (h n) @[simp] lemma measurable_set.const (p : Prop) : measurable_set {a : α | p} := by { by_cases p; simp [h, measurable_set.empty]; apply measurable_set.univ } /-- Every set has a measurable superset. Declare this as local instance as needed. -/ lemma nonempty_measurable_superset (s : set α) : nonempty { t // s ⊆ t ∧ measurable_set t} := ⟨⟨univ, subset_univ s, measurable_set.univ⟩⟩ end @[ext] lemma measurable_space.ext : ∀ {m₁ m₂ : measurable_space α}, (∀ s : set α, m₁.measurable_set' s ↔ m₂.measurable_set' s) → m₁ = m₂ | ⟨s₁, _, _, _⟩ ⟨s₂, _, _, _⟩ h := have s₁ = s₂, from funext $ assume x, propext $ h x, by subst this @[ext] lemma measurable_space.ext_iff {m₁ m₂ : measurable_space α} : m₁ = m₂ ↔ (∀ s : set α, m₁.measurable_set' s ↔ m₂.measurable_set' s) := ⟨by { unfreezingI {rintro rfl}, intro s, refl }, measurable_space.ext⟩ /-- A typeclass mixin for `measurable_space`s such that each singleton is measurable. -/ class measurable_singleton_class (α : Type*) [measurable_space α] : Prop := (measurable_set_singleton : ∀ x, measurable_set ({x} : set α)) export measurable_singleton_class (measurable_set_singleton) attribute [simp] measurable_set_singleton section measurable_singleton_class variables [measurable_space α] [measurable_singleton_class α] lemma measurable_set_eq {a : α} : measurable_set {x | x = a} := measurable_set_singleton a lemma measurable_set.insert {s : set α} (hs : measurable_set s) (a : α) : measurable_set (insert a s) := (measurable_set_singleton a).union hs @[simp] lemma measurable_set_insert {a : α} {s : set α} : measurable_set (insert a s) ↔ measurable_set s := ⟨λ h, if ha : a ∈ s then by rwa ← insert_eq_of_mem ha else insert_diff_self_of_not_mem ha ▸ h.diff (measurable_set_singleton _), λ h, h.insert a⟩ lemma set.finite.measurable_set {s : set α} (hs : finite s) : measurable_set s := finite.induction_on hs measurable_set.empty $ λ a s ha hsf hsm, hsm.insert _ protected lemma finset.measurable_set (s : finset α) : measurable_set (↑s : set α) := s.finite_to_set.measurable_set lemma set.countable.measurable_set {s : set α} (hs : countable s) : measurable_set s := begin rw [← bUnion_of_singleton s], exact measurable_set.bUnion hs (λ b hb, measurable_set_singleton b) end end measurable_singleton_class namespace measurable_space section complete_lattice instance : partial_order (measurable_space α) := { le := λ m₁ m₂, m₁.measurable_set' ≤ m₂.measurable_set', le_refl := assume a b, le_refl _, le_trans := assume a b c, le_trans, le_antisymm := assume a b h₁ h₂, measurable_space.ext $ assume s, ⟨h₁ s, h₂ s⟩ } /-- The smallest σ-algebra containing a collection `s` of basic sets -/ inductive generate_measurable (s : set (set α)) : set α → Prop | basic : ∀ u ∈ s, generate_measurable u | empty : generate_measurable ∅ | compl : ∀ s, generate_measurable s → generate_measurable sᶜ | union : ∀ f : ℕ → set α, (∀ n, generate_measurable (f n)) → generate_measurable (⋃ i, f i) /-- Construct the smallest measure space containing a collection of basic sets -/ def generate_from (s : set (set α)) : measurable_space α := { measurable_set' := generate_measurable s, measurable_set_empty := generate_measurable.empty, measurable_set_compl := generate_measurable.compl, measurable_set_Union := generate_measurable.union } lemma measurable_set_generate_from {s : set (set α)} {t : set α} (ht : t ∈ s) : (generate_from s).measurable_set' t := generate_measurable.basic t ht lemma generate_from_le {s : set (set α)} {m : measurable_space α} (h : ∀ t ∈ s, m.measurable_set' t) : generate_from s ≤ m := assume t (ht : generate_measurable s t), ht.rec_on h (measurable_set_empty m) (assume s _ hs, measurable_set_compl m s hs) (assume f _ hf, measurable_set_Union m f hf) lemma generate_from_le_iff {s : set (set α)} (m : measurable_space α) : generate_from s ≤ m ↔ s ⊆ {t | m.measurable_set' t} := iff.intro (assume h u hu, h _ $ measurable_set_generate_from hu) (assume h, generate_from_le h) @[simp] lemma generate_from_measurable_set [measurable_space α] : generate_from {s : set α | measurable_set s} = ‹_› := le_antisymm (generate_from_le $ λ _, id) $ λ s, measurable_set_generate_from /-- If `g` is a collection of subsets of `α` such that the `σ`-algebra generated from `g` contains the same sets as `g`, then `g` was already a `σ`-algebra. -/ protected def mk_of_closure (g : set (set α)) (hg : {t | (generate_from g).measurable_set' t} = g) : measurable_space α := { measurable_set' := λ s, s ∈ g, measurable_set_empty := hg ▸ measurable_set_empty _, measurable_set_compl := hg ▸ measurable_set_compl _, measurable_set_Union := hg ▸ measurable_set_Union _ } lemma mk_of_closure_sets {s : set (set α)} {hs : {t | (generate_from s).measurable_set' t} = s} : measurable_space.mk_of_closure s hs = generate_from s := measurable_space.ext $ assume t, show t ∈ s ↔ _, by { conv_lhs { rw [← hs] }, refl } /-- We get a Galois insertion between `σ`-algebras on `α` and `set (set α)` by using `generate_from` on one side and the collection of measurable sets on the other side. -/ def gi_generate_from : galois_insertion (@generate_from α) (λ m, {t | @measurable_set α m t}) := { gc := assume s, generate_from_le_iff, le_l_u := assume m s, measurable_set_generate_from, choice := λ g hg, measurable_space.mk_of_closure g $ le_antisymm hg $ (generate_from_le_iff _).1 le_rfl, choice_eq := assume g hg, mk_of_closure_sets } instance : complete_lattice (measurable_space α) := gi_generate_from.lift_complete_lattice instance : inhabited (measurable_space α) := ⟨⊤⟩ lemma measurable_set_bot_iff {s : set α} : @measurable_set α ⊥ s ↔ (s = ∅ ∨ s = univ) := let b : measurable_space α := { measurable_set' := λ s, s = ∅ ∨ s = univ, measurable_set_empty := or.inl rfl, measurable_set_compl := by simp [or_imp_distrib] {contextual := tt}, measurable_set_Union := assume f hf, classical.by_cases (assume h : ∃i, f i = univ, let ⟨i, hi⟩ := h in or.inr $ eq_univ_of_univ_subset $ hi ▸ le_supr f i) (assume h : ¬ ∃i, f i = univ, or.inl $ eq_empty_of_subset_empty $ Union_subset $ assume i, (hf i).elim (by simp {contextual := tt}) (assume hi, false.elim $ h ⟨i, hi⟩)) } in have b = ⊥, from bot_unique $ assume s hs, hs.elim (λ s, s.symm ▸ @measurable_set_empty _ ⊥) (λ s, s.symm ▸ @measurable_set.univ _ ⊥), this ▸ iff.rfl @[simp] theorem measurable_set_top {s : set α} : @measurable_set _ ⊤ s := trivial @[simp] theorem measurable_set_inf {m₁ m₂ : measurable_space α} {s : set α} : @measurable_set _ (m₁ ⊓ m₂) s ↔ @measurable_set _ m₁ s ∧ @measurable_set _ m₂ s := iff.rfl @[simp] theorem measurable_set_Inf {ms : set (measurable_space α)} {s : set α} : @measurable_set _ (Inf ms) s ↔ ∀ m ∈ ms, @measurable_set _ m s := show s ∈ (⋂ m ∈ ms, {t | @measurable_set _ m t }) ↔ _, by simp @[simp] theorem measurable_set_infi {ι} {m : ι → measurable_space α} {s : set α} : @measurable_set _ (infi m) s ↔ ∀ i, @measurable_set _ (m i) s := show s ∈ (λ m, {s | @measurable_set _ m s }) (infi m) ↔ _, by { rw (@gi_generate_from α).gc.u_infi, simp } theorem measurable_set_sup {m₁ m₂ : measurable_space α} {s : set α} : @measurable_set _ (m₁ ⊔ m₂) s ↔ generate_measurable (m₁.measurable_set' ∪ m₂.measurable_set') s := iff.refl _ theorem measurable_set_Sup {ms : set (measurable_space α)} {s : set α} : @measurable_set _ (Sup ms) s ↔ generate_measurable {s : set α | ∃ m ∈ ms, @measurable_set _ m s} s := begin change @measurable_set' _ (generate_from $ ⋃ m ∈ ms, _) _ ↔ _, simp [generate_from, ← set_of_exists] end theorem measurable_set_supr {ι} {m : ι → measurable_space α} {s : set α} : @measurable_set _ (supr m) s ↔ generate_measurable {s : set α | ∃ i, @measurable_set _ (m i) s} s := begin convert @measurable_set_Sup _ (range m) s, simp, end end complete_lattice end measurable_space section measurable_functions open measurable_space /-- A function `f` between measurable spaces is measurable if the preimage of every measurable set is measurable. -/ def measurable [measurable_space α] [measurable_space β] (f : α → β) : Prop := ∀ ⦃t : set β⦄, measurable_set t → measurable_set (f ⁻¹' t) variables [measurable_space α] [measurable_space β] [measurable_space γ] lemma measurable_id : measurable (@id α) := λ t, id lemma measurable_id' : measurable (λ a : α, a) := measurable_id lemma measurable.comp {g : β → γ} {f : α → β} (hg : measurable g) (hf : measurable f) : measurable (g ∘ f) := λ t ht, hf (hg ht) @[simp] lemma measurable_const {a : α} : measurable (λ b : β, a) := assume s hs, measurable_set.const (a ∈ s) end measurable_functions
ae1652394e6e2d2013301c356a7808ff87129192
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/finset/sort.lean
e306fdcb623afe23ec480d7b4ff9e570abb1356f
[ "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
10,465
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import data.finset.lattice import data.multiset.sort /-! # Construct a sorted list from a finset. -/ namespace finset open multiset nat variables {α β : Type*} /-! ### sort -/ section sort variables (r : α → α → Prop) [decidable_rel r] [is_trans α r] [is_antisymm α r] [is_total α r] /-- `sort s` constructs a sorted list from the unordered set `s`. (Uses merge sort algorithm.) -/ def sort (s : finset α) : list α := sort r s.1 @[simp] theorem sort_sorted (s : finset α) : list.sorted r (sort r s) := sort_sorted _ _ @[simp] theorem sort_eq (s : finset α) : ↑(sort r s) = s.1 := sort_eq _ _ @[simp] theorem sort_nodup (s : finset α) : (sort r s).nodup := (by rw sort_eq; exact s.2 : @multiset.nodup α (sort r s)) @[simp] theorem sort_to_finset [decidable_eq α] (s : finset α) : (sort r s).to_finset = s := list.to_finset_eq (sort_nodup r s) ▸ eq_of_veq (sort_eq r s) @[simp] theorem mem_sort {s : finset α} {a : α} : a ∈ sort r s ↔ a ∈ s := multiset.mem_sort _ @[simp] theorem length_sort {s : finset α} : (sort r s).length = s.card := multiset.length_sort _ end sort section sort_linear_order variables [linear_order α] theorem sort_sorted_lt (s : finset α) : list.sorted (<) (sort (≤) s) := (sort_sorted _ _).imp₂ (@lt_of_le_of_ne _ _) (sort_nodup _ _) lemma sorted_zero_eq_min'_aux (s : finset α) (h : 0 < (s.sort (≤)).length) (H : s.nonempty) : (s.sort (≤)).nth_le 0 h = s.min' H := begin let l := s.sort (≤), apply le_antisymm, { have : s.min' H ∈ l := (finset.mem_sort (≤)).mpr (s.min'_mem H), obtain ⟨i, i_lt, hi⟩ : ∃ i (hi : i < l.length), l.nth_le i hi = s.min' H := list.mem_iff_nth_le.1 this, rw ← hi, exact list.nth_le_of_sorted_of_le (s.sort_sorted (≤)) (nat.zero_le i) }, { have : l.nth_le 0 h ∈ s := (finset.mem_sort (≤)).1 (list.nth_le_mem l 0 h), exact s.min'_le _ this } end lemma sorted_zero_eq_min' {s : finset α} {h : 0 < (s.sort (≤)).length} : (s.sort (≤)).nth_le 0 h = s.min' (card_pos.1 $ by rwa length_sort at h) := sorted_zero_eq_min'_aux _ _ _ lemma min'_eq_sorted_zero {s : finset α} {h : s.nonempty} : s.min' h = (s.sort (≤)).nth_le 0 (by { rw length_sort, exact card_pos.2 h }) := (sorted_zero_eq_min'_aux _ _ _).symm lemma sorted_last_eq_max'_aux (s : finset α) (h : (s.sort (≤)).length - 1 < (s.sort (≤)).length) (H : s.nonempty) : (s.sort (≤)).nth_le ((s.sort (≤)).length - 1) h = s.max' H := begin let l := s.sort (≤), apply le_antisymm, { have : l.nth_le ((s.sort (≤)).length - 1) h ∈ s := (finset.mem_sort (≤)).1 (list.nth_le_mem l _ h), exact s.le_max' _ this }, { have : s.max' H ∈ l := (finset.mem_sort (≤)).mpr (s.max'_mem H), obtain ⟨i, i_lt, hi⟩ : ∃ i (hi : i < l.length), l.nth_le i hi = s.max' H := list.mem_iff_nth_le.1 this, rw ← hi, have : i ≤ l.length - 1 := nat.le_pred_of_lt i_lt, exact list.nth_le_of_sorted_of_le (s.sort_sorted (≤)) (nat.le_pred_of_lt i_lt) }, end lemma sorted_last_eq_max' {s : finset α} {h : (s.sort (≤)).length - 1 < (s.sort (≤)).length} : (s.sort (≤)).nth_le ((s.sort (≤)).length - 1) h = s.max' (by { rw length_sort at h, exact card_pos.1 (lt_of_le_of_lt bot_le h) }) := sorted_last_eq_max'_aux _ _ _ lemma max'_eq_sorted_last {s : finset α} {h : s.nonempty} : s.max' h = (s.sort (≤)).nth_le ((s.sort (≤)).length - 1) (by simpa using sub_lt (card_pos.mpr h) zero_lt_one) := (sorted_last_eq_max'_aux _ _ _).symm /-- Given a finset `s` of cardinal `k` in a linear order `α`, the map `mono_of_fin s h` is the increasing bijection between `fin k` and `s` as an `α`-valued map. 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. -/ def mono_of_fin (s : finset α) {k : ℕ} (h : s.card = k) (i : fin k) : α := have A : (i : ℕ) < (s.sort (≤)).length, by simpa [h] using i.2, (s.sort (≤)).nth_le i A lemma mono_of_fin_strict_mono (s : finset α) {k : ℕ} (h : s.card = k) : strict_mono (s.mono_of_fin h) := begin assume i j hij, exact list.pairwise_iff_nth_le.1 s.sort_sorted_lt _ _ _ hij end lemma mono_of_fin_bij_on (s : finset α) {k : ℕ} (h : s.card = k) : set.bij_on (s.mono_of_fin h) set.univ ↑s := begin have A : ∀ j, j ∈ s ↔ j ∈ (s.sort (≤)) := λ j, by simp, apply set.bij_on.mk, { assume i hi, simp only [mono_of_fin, set.mem_preimage, mem_coe, list.nth_le, A], exact list.nth_le_mem _ _ _ }, { exact ((mono_of_fin_strict_mono s h).injective).inj_on _ }, { assume x hx, simp only [mem_coe, A] at hx, obtain ⟨i, il, hi⟩ : ∃ (i : ℕ) (h : i < (s.sort (≤)).length), (s.sort (≤)).nth_le i h = x := list.nth_le_of_mem hx, simp [h] at il, exact ⟨⟨i, il⟩, set.mem_univ _, hi⟩ } end lemma mono_of_fin_injective (s : finset α) {k : ℕ} (h : s.card = k) : function.injective (s.mono_of_fin h) := set.injective_iff_inj_on_univ.mpr (s.mono_of_fin_bij_on h).inj_on /-- The bijection `mono_of_fin s h` sends `0` to the minimum of `s`. -/ lemma mono_of_fin_zero {s : finset α} {k : ℕ} (h : s.card = k) (hz : 0 < k) : mono_of_fin s h ⟨0, hz⟩ = s.min' (card_pos.mp (h.symm ▸ hz)) := begin apply le_antisymm, { have : min' s _ ∈ s := min'_mem s _, rcases (mono_of_fin_bij_on s h).surj_on this with ⟨a, _, ha⟩, rw ← ha, apply (mono_of_fin_strict_mono s h).monotone, exact zero_le a.val }, { have : mono_of_fin s h ⟨0, hz⟩ ∈ s := (mono_of_fin_bij_on s h).maps_to (set.mem_univ _), exact min'_le s _ this } end /-- The bijection `mono_of_fin s h` sends `k-1` to the maximum of `s`. -/ lemma mono_of_fin_last {s : finset α} {k : ℕ} (h : s.card = k) (hz : 0 < k) : mono_of_fin s h ⟨k-1, buffer.lt_aux_2 hz⟩ = s.max' (card_pos.mp (h.symm ▸ hz)) := begin have h'' : k - 1 < k := buffer.lt_aux_2 hz, apply le_antisymm, { have : mono_of_fin s h ⟨k-1, h''⟩ ∈ s := (mono_of_fin_bij_on s h).maps_to (set.mem_univ _), exact le_max' s _ this }, { have : max' s _ ∈ s := max'_mem s _, rcases (mono_of_fin_bij_on s h).surj_on this with ⟨a, _, ha⟩, rw ← ha, apply (mono_of_fin_strict_mono s h).monotone, exact le_pred_of_lt a.2}, end /-- `mono_of_fin {a} h` sends any argument to `a`. -/ @[simp] lemma mono_of_fin_singleton (a : α) (i : fin 1) {h} : mono_of_fin {a} h i = a := by rw [subsingleton.elim i ⟨0, zero_lt_one⟩, mono_of_fin_zero h zero_lt_one, min'_singleton] /-- The range of `mono_of_fin`. -/ @[simp] lemma range_mono_of_fin {s : finset α} {k : ℕ} (h : s.card = k) : set.range (s.mono_of_fin h) = ↑s := begin rw ←set.image_univ, exact (mono_of_fin_bij_on s h).image_eq end /-- Any increasing bijection between `fin k` and a finset of cardinality `k` has to coincide with the increasing bijection `mono_of_fin s h`. For a statement assuming only that `f` maps `univ` to `s`, see `mono_of_fin_unique'`.-/ lemma mono_of_fin_unique {s : finset α} {k : ℕ} (h : s.card = k) {f : fin k → α} (hbij : set.bij_on f set.univ ↑s) (hmono : strict_mono f) : f = s.mono_of_fin h := begin ext ⟨i, hi⟩, induction i using nat.strong_induction_on with i IH, rcases lt_trichotomy (f ⟨i, hi⟩) (mono_of_fin s h ⟨i, hi⟩) with H|H|H, { have A : f ⟨i, hi⟩ ∈ ↑s := hbij.maps_to (set.mem_univ _), rcases (mono_of_fin_bij_on s h).surj_on A with ⟨j, _, hj⟩, rw ← hj at H, have ji : j < ⟨i, hi⟩ := (mono_of_fin_strict_mono s h).lt_iff_lt.1 H, have : f j = mono_of_fin s h j, by { convert IH j ji (lt_trans ji hi), rw [fin.ext_iff, fin.coe_mk] }, rw ← this at hj, exact (ne_of_lt (hmono ji) hj).elim }, { exact H }, { have A : mono_of_fin s h ⟨i, hi⟩ ∈ ↑s := (mono_of_fin_bij_on s h).maps_to (set.mem_univ _), rcases hbij.surj_on A with ⟨j, _, hj⟩, rw ← hj at H, have ji : j < ⟨i, hi⟩ := hmono.lt_iff_lt.1 H, have : f j = mono_of_fin s h j, by { convert IH j ji (lt_trans ji hi), rw [fin.ext_iff, fin.coe_mk] }, rw this at hj, exact (ne_of_lt (mono_of_fin_strict_mono s h ji) hj).elim } 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 mono_of_fin_unique' {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.fin_range k), 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 /-- Two parametrizations `mono_of_fin` of the same set take the same value on `i` and `j` if and only if `i = j`. Since they can be defined on a priori not defeq types `fin k` and `fin l` (although necessarily `k = l`), the conclusion is rather written `(i : ℕ) = (j : ℕ)`. -/ @[simp] lemma mono_of_fin_eq_mono_of_fin_iff {k l : ℕ} {s : finset α} {i : fin k} {j : fin l} {h : s.card = k} {h' : s.card = l} : s.mono_of_fin h i = s.mono_of_fin h' j ↔ (i : ℕ) = (j : ℕ) := begin have A : k = l, by rw [← h', ← h], have : s.mono_of_fin h = (s.mono_of_fin h') ∘ (λ j : (fin k), ⟨j, A ▸ j.is_lt⟩) := rfl, rw [this, function.comp_app, (s.mono_of_fin_injective h').eq_iff, fin.ext_iff, fin.coe_mk] end /-- Given a finset `s` of cardinal `k` in a linear order `α`, the equiv `mono_equiv_of_fin s h` is the increasing bijection between `fin k` and `s` as an `s`-valued map. 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 (s : finset α) {k : ℕ} (h : s.card = k) : fin k ≃ {x // x ∈ s} := (s.mono_of_fin_bij_on h).equiv _ end sort_linear_order instance [has_repr α] : has_repr (finset α) := ⟨λ s, repr s.1⟩ end finset
3e555f5d8a29b00758e142e7ed27711792680cfc
8b9f17008684d796c8022dab552e42f0cb6fb347
/hott/init/types/prod.hlean
be336c4e66abf986c1c0e311133e47595ce1cfef
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,590
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: init.types.prod Author: Leonardo de Moura, Jeremy Avigad -/ prelude import ..wf ..num definition pair := @prod.mk namespace prod notation A * B := prod A B notation A × B := prod A B namespace ops postfix `.1`:(max+1) := pr1 postfix `.2`:(max+1) := pr2 abbreviation pr₁ := @pr1 abbreviation pr₂ := @pr2 end ops namespace low_precedence_times reserve infixr `*`:30 -- conflicts with notation for multiplication infixr `*` := prod end low_precedence_times -- TODO: add lemmas about flip to hott/types/prod.hlean definition flip {A B : Type} (a : A × B) : B × A := pair (pr2 a) (pr1 a) notation `pr₁` := pr1 notation `pr₂` := pr2 -- notation for n-ary tuples notation `(` h `,` t:(foldl `,` (e r, prod.mk r e) h) `)` := t open well_founded section variables {A B : Type} variable (Ra : A → A → Type) variable (Rb : B → B → Type) -- Lexicographical order based on Ra and Rb inductive lex : A × B → A × B → Type := | left : ∀{a₁ b₁} a₂ b₂, Ra a₁ a₂ → lex (a₁, b₁) (a₂, b₂) | right : ∀a {b₁ b₂}, Rb b₁ b₂ → lex (a, b₁) (a, b₂) -- Relational product based on Ra and Rb inductive rprod : A × B → A × B → Type := intro : ∀{a₁ b₁ a₂ b₂}, Ra a₁ a₂ → Rb b₁ b₂ → rprod (a₁, b₁) (a₂, b₂) end section parameters {A B : Type} parameters {Ra : A → A → Type} {Rb : B → B → Type} local infix `≺`:50 := lex Ra Rb definition lex.accessible {a} (aca : acc Ra a) (acb : ∀b, acc Rb b): ∀b, acc (lex Ra Rb) (a, b) := acc.rec_on aca (λxa aca (iHa : ∀y, Ra y xa → ∀b, acc (lex Ra Rb) (y, b)), λb, acc.rec_on (acb b) (λxb acb (iHb : ∀y, Rb y xb → acc (lex Ra Rb) (xa, y)), acc.intro (xa, xb) (λp (lt : p ≺ (xa, xb)), have aux : xa = xa → xb = xb → acc (lex Ra Rb) p, from @prod.lex.rec_on A B Ra Rb (λp₁ p₂ h, pr₁ p₂ = xa → pr₂ p₂ = xb → acc (lex Ra Rb) p₁) p (xa, xb) lt (λa₁ b₁ a₂ b₂ (H : Ra a₁ a₂) (eq₂ : a₂ = xa) (eq₃ : b₂ = xb), show acc (lex Ra Rb) (a₁, b₁), from have Ra₁ : Ra a₁ xa, from eq.rec_on eq₂ H, iHa a₁ Ra₁ b₁) (λa b₁ b₂ (H : Rb b₁ b₂) (eq₂ : a = xa) (eq₃ : b₂ = xb), show acc (lex Ra Rb) (a, b₁), from have Rb₁ : Rb b₁ xb, from eq.rec_on eq₃ H, have eq₂' : xa = a, from eq.rec_on eq₂ rfl, eq.rec_on eq₂' (iHb b₁ Rb₁)), aux rfl rfl))) -- The lexicographical order of well founded relations is well-founded definition lex.wf (Ha : well_founded Ra) (Hb : well_founded Rb) : well_founded (lex Ra Rb) := well_founded.intro (λp, destruct p (λa b, lex.accessible (Ha a) (well_founded.apply Hb) b)) -- Relational product is a subrelation of the lex definition rprod.sub_lex : ∀ a b, rprod Ra Rb a b → lex Ra Rb a b := λa b H, prod.rprod.rec_on H (λ a₁ b₁ a₂ b₂ H₁ H₂, lex.left Rb a₂ b₂ H₁) -- The relational product of well founded relations is well-founded definition rprod.wf (Ha : well_founded Ra) (Hb : well_founded Rb) : well_founded (rprod Ra Rb) := subrelation.wf (rprod.sub_lex) (lex.wf Ha Hb) end end prod
80d983704def8fd07aca4f9279907d1d479bc0eb
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/hott/noc_list.hlean
8b7cc1b0290eac472f99c2872e37b35658a26deb
[ "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
704
hlean
set_option pp.universes true check @not inductive list (A : Type) : Type := | nil {} : list A | cons : A → list A → list A namespace list open lift theorem nil_ne_cons {A : Type} (a : A) (v : list A) : nil ≠ cons a v := λ H, down (list.no_confusion H) theorem cons.inj₁ {A : Type} (a₁ a₂ : A) (v₁ v₂ : list A) : cons a₁ v₁ = cons a₂ v₂ → a₁ = a₂ := λ H, down (list.no_confusion H (λ (h₁ : a₁ = a₂) (h₂ : v₁ = v₂), h₁)) theorem cons.inj₂ {A : Type} (a₁ a₂ : A) (v₁ v₂ : list A) : cons a₁ v₁ = cons a₂ v₂ → v₁ = v₂ := λ H, down (list.no_confusion H (λ (h₁ : a₁ = a₂) (h₂ : v₁ = v₂), h₂)) end list
be014f8f385b98205a7456edf0d040c06d5160d5
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/analysis/calculus/affine_map.lean
10a08f23164a3a954ea23294c3b65c7ab6b45e4b
[ "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
913
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import analysis.normed_space.continuous_affine_map import analysis.calculus.cont_diff /-! # Smooth affine maps This file contains results about smoothness of affine maps. ## Main definitions: * `continuous_affine_map.cont_diff`: a continuous affine map is smooth -/ namespace continuous_affine_map variables {𝕜 V W : Type*} [nontrivially_normed_field 𝕜] variables [normed_add_comm_group V] [normed_space 𝕜 V] variables [normed_add_comm_group W] [normed_space 𝕜 W] /-- A continuous affine map between normed vector spaces is smooth. -/ lemma cont_diff {n : with_top ℕ} (f : V →A[𝕜] W) : cont_diff 𝕜 n f := begin rw f.decomp, apply f.cont_linear.cont_diff.add, simp only, exact cont_diff_const, end end continuous_affine_map
004dd0b6dd862d53764875bf8a026fdb6b26ce60
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/simp_failIfUnchanged.lean
995111a73be84a1b82359a5298458bbee7ae6c3e
[ "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
879
lean
example (h : False) : False := by fail_if_success simp (config := { failIfUnchanged := true }) cases h example (h : (a :: [b]).length = 3) : False := by fail_if_success simp (config := { failIfUnchanged := true }) only at h simp (config := { failIfUnchanged := false }) only at h simp (config := { failIfUnchanged := true }) at h example (h : False) : False := by fail_if_success dsimp (config := { failIfUnchanged := true }) cases h example (_h : 37 = 37) (w : Nonempty False) : False ∨ False := by -- removes `_h` and simplifies the goal simp_all (config := { failIfUnchanged := true }) -- Now should fail, because it can't do anything. fail_if_success simp_all (config := { failIfUnchanged := true }) cases w with | intro w => cases w example (h : False) : 7 = 8 := by simp (config := { failIfUnchanged := true }) cases h
3d70fa9c826624b76619229ff7bf938853742841
f1dc39e1c68f71465c8bf79910c4664d03824751
/tests/lean/vm_override.lean
4f109fa7ffa1e143c62115d069135ff3118edffa
[ "Apache-2.0" ]
permissive
kckennylau/lean-2
6504f45da07bc98b098d726b74130103be25885c
c9a9368bc0fd600d832bd56c5cb2124b8a523ef9
refs/heads/master
1,659,140,308,864
1,589,361,166,000
1,589,361,166,000
263,748,786
0
0
null
1,589,405,915,000
1,589,405,915,000
null
UTF-8
Lean
false
false
8,738
lean
/- Author: E.W.Ayers -/ meta def hello_override := `hello_override.name @[vm_override hello_override] -- this means that the VM should replace the definition of `hello` with `hello_override` when evaluating. meta def hello := `hello.name #print hello -- should use `hello #eval hello -- should be `hello_override set_option vm_override.enabled false -- now the VM should ignore all overrides #eval hello -- should be `hello @[vm_override hello_override] meta def hello_2 := `hello_2.name #eval hello_2 -- should be `hello_2 because vm_overrides are not enabled set_option vm_override.enabled true #eval hello_2 -- should be `hello_override /- When overriding an inductive datatype, you need to provide two arguments. The first argument says what the type should be replaced with and the second argument says where the overridden recursors and constructors are. To test that vm_override works with inductive definitions we are going to introduce some dummy inductive non-meta definitions of `float` and then override them with the meta `native.float`. So this test file also indicates the danger of using vm_overrides, because it can mean that the VM evaluation and the kernel evaluation of a lean expression can be different. VM overriding also gives the user the ability to 'monkey patch' definitions in core. -/ -- should fail; `unknown declaration native.float.mk` @[vm_override native.float native.float] inductive float₀ : Type 1 | mk : ℕ → float₀ namespace native.float₁ meta def mk : ℕ → native.float := sorry -- Note that this has the wrong type to be an override of `float₁.rec`. meta def rec : ℕ := 3 end native.float₁ -- should fail: 'type mismatch with override' @[vm_override native.float native.float₁] inductive float₁ : Type 1 | mk : ℕ → float₁ namespace native.float meta def mk : ℕ → native.float | n := n meta def rec {C : native.float → Sort*} (f : Π (a : ℕ), C (native.float.mk a)) (n : native.float) : C n := sorry meta def cases_on {C : native.float → Sort*} (n : native.float) (f : Π (a : ℕ), C (native.float.mk a)) : C n := sorry end native.float @[vm_override native.float native.float] inductive float : Type 1 | mk : ℕ → float @[vm_override native.float.add] def add : float → float → float | (float.mk x) (float.mk y) := float.mk (x + y) instance : has_add float := ⟨add⟩ @[vm_override native.float.div] def div : float → float → float | (float.mk x) (float.mk y) := float.mk 5 instance : has_div float := ⟨div⟩ @[vm_override native.float.pow] def float.pow : float → float → float | (float.mk a) (float.mk b) := float.mk $ nat.cases_on b 1 (λ x, a * x) instance : has_pow float float := ⟨float.pow⟩ @[vm_override native.float.zero] def zero : float := float.mk 0 def one : float := float.mk 1 @[vm_override native.float.has_one] instance float.has_one : has_one float := ⟨one⟩ instance : has_zero float := ⟨zero⟩ @[vm_override native.float.to_repr] def to_repr (p : float) : string := repr "dummy" instance : has_repr float := ⟨to_repr⟩ set_option pp.numerals false -- our definition of `div` is silly. example (x y : float) : x / y = 5 := begin cases x, cases y, refl end -- but evaluation is using native.float and gives different answers. #eval (0.1 : float) / (0.2 : float) #eval (0.1 + 05 / 0.0000034 : float) namespace bin_example namespace bin inductive pos | one : pos | bit0 : pos → pos | bit1 : pos → pos def pos.sizeof' : pos → nat | pos.one := 1 | (pos.bit0 p) := bit0 (pos.sizeof' p) | (pos.bit1 p) := bit1 (pos.sizeof' p) instance : has_sizeof pos := ⟨ pos.sizeof' ⟩ inductive nat | zero : nat | pos : pos → nat universes l namespace pos def succ : pos → pos | one := bit0 one | (bit0 p) := bit1 p | (bit1 p) := bit0 $ succ p def pred : pos → pos | one := one | (bit0 one) := one | (bit0 p) := bit1 (pred p) | (bit1 p) := bit0 p lemma succ_pred_bit0 : ∀ p : pos, succ (pred $ bit0 p) = bit0 p | one := rfl | (bit0 p) := show bit0 _ = _, from congr_arg _ (succ_pred_bit0 _) | (bit1 p) := rfl lemma succ_pred_bit1 : ∀ p : pos, succ (pred $ bit1 p) = bit1 p | one := rfl | (bit0 p) := rfl | (bit1 p) := rfl lemma sizeof_pred_bit0_lt : ∀ p : pos, sizeof' (pred (bit0 p)) < sizeof' (bit0 p) | one := nat.one_lt_bit0 (by dsimp [pos.sizeof]; apply one_ne_zero) | (bit0 p) := nat.bit1_lt_bit0 $ sizeof_pred_bit0_lt p | (bit1 p) := nat.bit1_lt_bit0 $ nat.bit0_lt_bit1 $ le_refl _ @[inline] def rec' {C : bin.pos → Sort l} (x₀ : C bin.pos.one) (f : ∀ n, C n → C (bin.pos.succ n)) : Π (n : bin.pos), C n | bin.pos.one := x₀ | (bin.pos.bit0 p) := have sizeof' (pred (bit0 p)) < sizeof' (bit0 p), from sizeof_pred_bit0_lt _, (succ_pred_bit0 p).rec (f _ (rec' _)) | (bin.pos.bit1 p) := have sizeof' (pred (bit1 p)) < sizeof' (bit1 p), from nat.bit0_lt_bit1 (le_refl _), (succ_pred_bit1 p).rec (f _ (rec' _)) def cases_on' {C : bin.pos → Sort l} (x₀ : C bin.pos.one) (f : ∀ n, C (bin.pos.succ n)) : Π (n : bin.pos), C n | bin.pos.one := x₀ | (bin.pos.bit0 p) := have sizeof' (pred (bit0 p)) < sizeof' (bit0 p), from sizeof_pred_bit0_lt _, (succ_pred_bit0 p).rec (f _) | (bin.pos.bit1 p) := have sizeof' (pred (bit1 p)) < sizeof' (bit1 p), from nat.bit0_lt_bit1 (le_refl _), (succ_pred_bit1 p).rec (f _) end pos namespace nat_ovr def zero : nat := bin.nat.zero def succ : nat → nat | nat.zero := nat.pos pos.one | (nat.pos p) := nat.pos p.succ @[inline] def rec {C : bin.nat → Sort l} (x₀ : C bin.nat_ovr.zero) (f : ∀ n, C n → C (bin.nat_ovr.succ n)) : Π (n : bin.nat), C n | nat.zero := x₀ | (nat.pos p) := @pos.rec' (λ p, C (nat.pos p)) (f zero x₀) (λ p h, f (nat.pos p) h) _ @[inline] def cases_on {C : bin.nat → Sort l} (n : bin.nat) (x₀ : C bin.nat_ovr.zero) (x₁ : Π (a : bin.nat), C (bin.nat_ovr.succ a)) : C n := match n with | nat.zero := x₀ | nat.pos p := @pos.cases_on' (λ x, C (nat.pos x)) (x₁ nat.zero) (λ n, x₁ (nat.pos n)) _ end def repr' : bin.pos → string | bin.pos.one := "1" | (bin.pos.bit0 p) := repr' p ++ "0" | (bin.pos.bit1 p) := repr' p ++ "1" def repr : bin.nat → string | bin.nat.zero := "0" | (bin.nat.pos p) := repr' p def add' : bin.pos → bin.pos → bin.pos | pos.one p := p.succ | p pos.one := p.succ | (pos.bit0 p) (pos.bit0 p') := pos.bit0 (add' p p') | (pos.bit1 p) (pos.bit0 p') := pos.bit1 (add' p p') | (pos.bit0 p) (pos.bit1 p') := pos.bit1 (add' p p') | (pos.bit1 p) (pos.bit1 p') := pos.bit0 (add' p p'.succ) def add : bin.nat → bin.nat → bin.nat | nat.zero n := n | n nat.zero := n | (nat.pos p) (nat.pos p') := nat.pos $ add' p p' end nat_ovr end bin @[vm_override bin.nat bin_example.bin.nat_ovr] inductive un_nat | zero : un_nat | succ : un_nat → un_nat set_option trace.compiler.inline true @[vm_override bin_example.bin.nat_ovr.repr] def repr (i : un_nat) : string := "" instance : has_repr un_nat := ⟨ repr ⟩ @[vm_override bin_example.bin.nat_ovr.add] def add (n : un_nat) : un_nat → un_nat | un_nat.zero := n | (un_nat.succ m) := un_nat.succ (add m) def mk_num : ℕ → un_nat | 0 := un_nat.zero | (nat.succ n) := add (mk_num n) (mk_num n).succ def mk_num' : un_nat → un_nat | un_nat.zero := un_nat.zero | (un_nat.succ n) := add (mk_num' n) (mk_num' n).succ #eval mk_num 5 #eval mk_num' un_nat.zero.succ.succ.succ.succ.succ end bin_example namespace native.float₃ @[inline] meta def mk : ℕ → native.float := λ _, 1 @[inline] meta def {l} rec {C : native.float → Sort l} : (Π (a : ℕ), C (native.float₃.mk a)) → Π (n : native.float), C n := λ f n, unchecked_cast (f 1) @[inline] meta def {l} cases_on {C : native.float → Sort l} (n : native.float) : (Π (a : ℕ), C (native.float₃.mk a)) → C n:= λ f, unchecked_cast (f 1) end native.float₃ @[vm_override native.float native.float₃] inductive float₃ : Type 1 | mk : ℕ → float₃ set_option trace.compiler.inline true def float₃.repr : float₃ → string | ⟨n⟩ := repr n instance : has_repr float₃ := ⟨ float₃.repr ⟩ def make : ℕ → float₃ := float₃.mk #eval make 3 def get₂ : float₃ → ℕ | (float₃.mk n) := n #eval get₂ $ make 3 def {l} cases_on : Π {C : float₃ → Sort l} (n : float₃), (Π (a : ℕ), C (float₃.mk a)) → C n:= @float₃.cases_on set_option vm_override.enabled false #eval @cases_on (λ n, ℕ) (float₃.mk 3) (λ n, n) set_option vm_override.enabled true #eval @cases_on (λ n, ℕ) (float₃.mk 3) (λ n, n) #eval @float₃.rec_on (λ n, ℕ) (float₃.mk 3) (λ n, n)
a7d56055cdec3bab422ed136688b0c6b43e208fd
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/lean/run/1954.lean
48b20bb4ec838743dd4076684c6fa2036637309c
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
99
lean
def all (p : Nat → Prop) : Prop := ∀x, p x example {p : Nat → Prop} (h : all p) : p 0 := h 0
34dac5e474b61d6858b004d1c0ca911289cc022b
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/order/category/Preorder.lean
f5ad17ec3141287740a768d88fed825a2031e30f
[ "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
945
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import order.preorder_hom import category_theory.concrete_category import algebra.punit_instances /-! # Category of preorders -/ open category_theory /-- The category of preorders. -/ def Preorder := bundled preorder namespace Preorder instance : bundled_hom @preorder_hom := { to_fun := @preorder_hom.to_fun, id := @preorder_hom.id, comp := @preorder_hom.comp, hom_ext := @preorder_hom.ext } attribute [derive [large_category, concrete_category]] Preorder instance : has_coe_to_sort Preorder Type* := bundled.has_coe_to_sort /-- Construct a bundled Preorder from the underlying type and typeclass. -/ def of (α : Type*) [preorder α] : Preorder := bundled.of α instance : inhabited Preorder := ⟨of punit⟩ instance (α : Preorder) : preorder α := α.str end Preorder
7c56c2cb225c1d0e5b3619d9c537c6fde4b615f5
fa94c6d0fc6f04b86b0d3ca6e6dea9dd87d28bc8
/I.lean
3e35602f0f2653b650c65c9b92dcf78818280485
[]
no_license
tabsg/complexNoGame
5e5cc6946b8e1e41023cf4af79f06060f2b355dd
6d765d2e75e99ccab2dda70f44ff06aa286f5bdd
refs/heads/master
1,657,040,370,406
1,590,094,335,000
1,590,094,335,000
265,948,577
0
0
null
null
null
null
UTF-8
Lean
false
false
1,554
lean
/- Copyright (c) 2020 The Xena project. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Kevin Buzzard Thanks: Imperial College London, leanprover-community The complex numbers, modelled as R^2 in the obvious way. -/ import complex.basic -- tutorial level /-! # Level 1: I I find it unbelievable that we have written quite a lot of code about the complex numbers and we've still never defined i, or j, or I, or $$\sqrt{-1}$$, or whatever it's called. Why don't you supply the definition, and make the basic API? All the proofs below are sorried. You can try them in tactic mode by replacing `sorry` with `begin end` and then starting to write tactics in the `begin end` block. -/ namespace complex /-- complex.I is the square root of -1 above the imaginary axis -/ def I : ℂ := ⟨0, 1⟩ /- Easy lemmas, tagged with `simp` so Lean can prove things about `I` by equating real and imaginary parts. -/ /-- re(I) = 0 -/ @[simp] lemma I_re : re(I) = 0 := begin refl, end /-- im(I) = 1 -/ @[simp] lemma I_im : im(I) = 1 := begin refl, end /-- I*I = -1 -/ @[simp] lemma I_mul_I : I * I = -1 := begin ext; simp, end /- Bonus level. Hint: don't forget ext_iff. It's defined in complex.basic and its type is below. ext_iff : ∀ {z w : ℂ}, z = w ↔ z.re = w.re ∧ z.im = w.im -/ /-- I is non-zero -/ lemma I_ne_zero : (I : ℂ) ≠ 0 := begin intro h, rw ext_iff at h, rw I_im at h, rw zero_im at h, cases h, simp at h_right, contradiction, end end complex
edfdc0bd2a0bcaf786e32bb794fd825dcba69013
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/data/zmod/basic.lean
665af70d088d4d7bbc698ce112410be1483a6c71
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
15,358
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Chris Hughes -/ import data.int.modeq data.int.gcd data.fintype data.pnat.basic open nat nat.modeq int def zmod (n : ℕ+) := fin n namespace zmod instance (n : ℕ+) : has_neg (zmod n) := ⟨λ a, ⟨nat_mod (-(a.1 : ℤ)) n, have h : (n : ℤ) ≠ 0 := int.coe_nat_ne_zero_iff_pos.2 n.pos, have h₁ : ((n : ℕ) : ℤ) = abs n := (abs_of_nonneg (int.coe_nat_nonneg n)).symm, by rw [← int.coe_nat_lt, nat_mod, to_nat_of_nonneg (int.mod_nonneg _ h), h₁]; exact int.mod_lt _ h⟩⟩ instance (n : ℕ+) : add_comm_semigroup (zmod n) := { add_assoc := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq (show ((a + b) % n + c) ≡ (a + (b + c) % n) [MOD n], from calc ((a + b) % n + c) ≡ a + b + c [MOD n] : modeq_add (nat.mod_mod _ _) rfl ... ≡ a + (b + c) [MOD n] : by rw add_assoc ... ≡ (a + (b + c) % n) [MOD n] : modeq_add rfl (nat.mod_mod _ _).symm), add_comm := λ ⟨a, _⟩ ⟨b, _⟩, fin.eq_of_veq (show (a + b) % n = (b + a) % n, by rw add_comm), ..fin.has_add } instance (n : ℕ+) : comm_semigroup (zmod n) := { mul_assoc := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq (calc ((a * b) % n * c) ≡ a * b * c [MOD n] : modeq_mul (nat.mod_mod _ _) rfl ... ≡ a * (b * c) [MOD n] : by rw mul_assoc ... ≡ a * (b * c % n) [MOD n] : modeq_mul rfl (nat.mod_mod _ _).symm), mul_comm := λ ⟨a, _⟩ ⟨b, _⟩, fin.eq_of_veq (show (a * b) % n = (b * a) % n, by rw mul_comm), ..fin.has_mul } instance (n : ℕ+) : has_one (zmod n) := ⟨⟨(1 % n), nat.mod_lt _ n.pos⟩⟩ instance (n : ℕ+) : has_zero (zmod n) := ⟨⟨0, n.pos⟩⟩ instance zmod_one.subsingleton : subsingleton (zmod 1) := ⟨λ a b, fin.eq_of_veq (by rw [eq_zero_of_le_zero (le_of_lt_succ a.2), eq_zero_of_le_zero (le_of_lt_succ b.2)])⟩ lemma add_val {n : ℕ+} : ∀ a b : zmod n, (a + b).val = (a.val + b.val) % n | ⟨_, _⟩ ⟨_, _⟩ := rfl lemma mul_val {n : ℕ+} : ∀ a b : zmod n, (a * b).val = (a.val * b.val) % n | ⟨_, _⟩ ⟨_, _⟩ := rfl lemma one_val {n : ℕ+} : (1 : zmod n).val = 1 % n := rfl @[simp] lemma zero_val (n : ℕ+) : (0 : zmod n).val = 0 := rfl private lemma one_mul_aux (n : ℕ+) (a : zmod n) : (1 : zmod n) * a = a := begin cases n with n hn, cases n with n, { exact (lt_irrefl _ hn).elim }, { cases n with n, { exact @subsingleton.elim (zmod 1) _ _ _ }, { have h₁ : a.1 % n.succ.succ = a.1 := nat.mod_eq_of_lt a.2, have h₂ : 1 % n.succ.succ = 1 := nat.mod_eq_of_lt dec_trivial, refine fin.eq_of_veq _, simp [mul_val, one_val, h₁, h₂] } } end private lemma left_distrib_aux (n : ℕ+) : ∀ a b c : zmod n, a * (b + c) = a * b + a * c := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq (calc a * ((b + c) % n) ≡ a * (b + c) [MOD n] : modeq_mul rfl (nat.mod_mod _ _) ... ≡ a * b + a * c [MOD n] : by rw mul_add ... ≡ (a * b) % n + (a * c) % n [MOD n] : modeq_add (nat.mod_mod _ _).symm (nat.mod_mod _ _).symm) instance (n : ℕ+) : comm_ring (zmod n) := { zero_add := λ ⟨a, ha⟩, fin.eq_of_veq (show (0 + a) % n = a, by rw zero_add; exact nat.mod_eq_of_lt ha), add_zero := λ ⟨a, ha⟩, fin.eq_of_veq (nat.mod_eq_of_lt ha), add_left_neg := λ ⟨a, ha⟩, fin.eq_of_veq (show (((-a : ℤ) % n).to_nat + a) % n = 0, from int.coe_nat_inj begin have hn : (n : ℤ) ≠ 0 := (ne_of_lt (int.coe_nat_lt.2 n.pos)).symm, rw [int.coe_nat_mod, int.coe_nat_add, to_nat_of_nonneg (int.mod_nonneg _ hn), add_comm], simp, end), one_mul := one_mul_aux n, mul_one := λ a, by rw mul_comm; exact one_mul_aux n a, left_distrib := left_distrib_aux n, right_distrib := λ a b c, by rw [mul_comm, left_distrib_aux, mul_comm _ b, mul_comm]; refl, ..zmod.has_zero n, ..zmod.has_one n, ..zmod.has_neg n, ..zmod.add_comm_semigroup n, ..zmod.comm_semigroup n } lemma val_cast_nat {n : ℕ+} (a : ℕ) : (a : zmod n).val = a % n := begin induction a with a ih, { rw [nat.zero_mod]; refl }, { rw [succ_eq_add_one, nat.cast_add, add_val, ih], show (a % n + ((0 + (1 % n)) % n)) % n = (a + 1) % n, rw [zero_add, nat.mod_mod], exact nat.modeq.modeq_add (nat.mod_mod a n) (nat.mod_mod 1 n) } end lemma neg_val' {m : pnat} (n : zmod m) : (-n).val = (m - n.val) % m := have ((-n).val + n.val) % m = (m - n.val + n.val) % m, by { rw [←add_val, add_left_neg, nat.sub_add_cancel (le_of_lt n.is_lt), nat.mod_self], refl }, (nat.mod_eq_of_lt (fin.is_lt _)).symm.trans (nat.modeq.modeq_add_cancel_right rfl this) lemma neg_val {m : pnat} (n : zmod m) : (-n).val = if n = 0 then 0 else m - n.val := begin rw neg_val', by_cases h : n = 0; simp [h], cases n with n nlt; cases n; dsimp, { contradiction }, rw nat.mod_eq_of_lt, apply nat.sub_lt m.2 (nat.succ_pos _), end lemma mk_eq_cast {n : ℕ+} {a : ℕ} (h : a < n) : (⟨a, h⟩ : zmod n) = (a : zmod n) := fin.eq_of_veq (by rw [val_cast_nat, nat.mod_eq_of_lt h]) @[simp] lemma cast_self_eq_zero {n : ℕ+} : ((n : ℕ) : zmod n) = 0 := fin.eq_of_veq (show (n : zmod n).val = 0, by simp [val_cast_nat]) lemma val_cast_of_lt {n : ℕ+} {a : ℕ} (h : a < n) : (a : zmod n).val = a := by rw [val_cast_nat, nat.mod_eq_of_lt h] @[simp] lemma cast_mod_nat (n : ℕ+) (a : ℕ) : ((a % n : ℕ) : zmod n) = a := by conv {to_rhs, rw ← nat.mod_add_div a n}; simp @[simp] lemma cast_mod_nat' {n : ℕ} (hn : 0 < n) (a : ℕ) : ((a % n : ℕ) : zmod ⟨n, hn⟩) = a := cast_mod_nat _ _ @[simp] lemma cast_val {n : ℕ+} (a : zmod n) : (a.val : zmod n) = a := by cases a; simp [mk_eq_cast] @[simp] lemma cast_mod_int (n : ℕ+) (a : ℤ) : ((a % (n : ℕ) : ℤ) : zmod n) = a := by conv {to_rhs, rw ← int.mod_add_div a n}; simp @[simp] lemma cast_mod_int' {n : ℕ} (hn : 0 < n) (a : ℤ) : ((a % (n : ℕ) : ℤ) : zmod ⟨n, hn⟩) = a := cast_mod_int _ _ lemma val_cast_int {n : ℕ+} (a : ℤ) : (a : zmod n).val = (a % (n : ℕ)).nat_abs := have h : nat_abs (a % (n : ℕ)) < n := int.coe_nat_lt.1 begin rw [nat_abs_of_nonneg (mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 n.pos))], conv {to_rhs, rw ← abs_of_nonneg (int.coe_nat_nonneg n)}, exact int.mod_lt _ (int.coe_nat_ne_zero_iff_pos.2 n.pos) end, int.coe_nat_inj $ by conv {to_lhs, rw [← cast_mod_int n a, ← nat_abs_of_nonneg (mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 n.pos)), int.cast_coe_nat, val_cast_of_lt h] } lemma coe_val_cast_int {n : ℕ+} (a : ℤ) : ((a : zmod n).val : ℤ) = a % (n : ℕ) := by rw [val_cast_int, int.nat_abs_of_nonneg (mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 n.pos))] lemma eq_iff_modeq_nat {n : ℕ+} {a b : ℕ} : (a : zmod n) = b ↔ a ≡ b [MOD n] := ⟨λ h, by have := fin.veq_of_eq h; rwa [val_cast_nat, val_cast_nat] at this, λ h, fin.eq_of_veq $ by rwa [val_cast_nat, val_cast_nat]⟩ lemma eq_iff_modeq_nat' {n : ℕ} (hn : 0 < n) {a b : ℕ} : (a : zmod ⟨n, hn⟩) = b ↔ a ≡ b [MOD n] := eq_iff_modeq_nat lemma eq_iff_modeq_int {n : ℕ+} {a b : ℤ} : (a : zmod n) = b ↔ a ≡ b [ZMOD (n : ℕ)] := ⟨λ h, by have := fin.veq_of_eq h; rwa [val_cast_int, val_cast_int, ← int.coe_nat_eq_coe_nat_iff, nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 n.pos)), nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 n.pos))] at this, λ h : a % (n : ℕ) = b % (n : ℕ), by rw [← cast_mod_int n a, ← cast_mod_int n b, h]⟩ lemma eq_iff_modeq_int' {n : ℕ} (hn : 0 < n) {a b : ℤ} : (a : zmod ⟨n, hn⟩) = b ↔ a ≡ b [ZMOD (n : ℕ)] := eq_iff_modeq_int lemma eq_zero_iff_dvd_nat {n : ℕ+} {a : ℕ} : (a : zmod n) = 0 ↔ (n : ℕ) ∣ a := by rw [← @nat.cast_zero (zmod n), eq_iff_modeq_nat, nat.modeq.modeq_zero_iff] lemma eq_zero_iff_dvd_int {n : ℕ+} {a : ℤ} : (a : zmod n) = 0 ↔ ((n : ℕ) : ℤ) ∣ a := by rw [← @int.cast_zero (zmod n), eq_iff_modeq_int, int.modeq.modeq_zero_iff] instance (n : ℕ+) : fintype (zmod n) := fin.fintype _ instance decidable_eq (n : ℕ+) : decidable_eq (zmod n) := fin.decidable_eq _ instance (n : ℕ+) : has_repr (zmod n) := fin.has_repr _ lemma card_zmod (n : ℕ+) : fintype.card (zmod n) = n := fintype.card_fin n lemma le_div_two_iff_lt_neg {n : ℕ+} (hn : (n : ℕ) % 2 = 1) {x : zmod n} (hx0 : x ≠ 0) : x.1 ≤ (n / 2 : ℕ) ↔ (n / 2 : ℕ) < (-x).1 := have hn2 : (n : ℕ) / 2 < n := nat.div_lt_of_lt_mul ((lt_mul_iff_one_lt_left n.pos).2 dec_trivial), have hn2' : (n : ℕ) - n / 2 = n / 2 + 1, by conv {to_lhs, congr, rw [← succ_sub_one n, succ_sub n.pos]}; rw [← two_mul_odd_div_two hn, two_mul, ← succ_add, nat.add_sub_cancel], have hxn : (n : ℕ) - x.val < n, begin rw [nat.sub_lt_iff (le_of_lt x.2) (le_refl _), nat.sub_self], rw ← zmod.cast_val x at hx0, exact nat.pos_of_ne_zero (λ h, by simpa [h] using hx0) end, by conv {to_rhs, rw [← nat.succ_le_iff, succ_eq_add_one, ← hn2', ← zero_add (- x), ← zmod.cast_self_eq_zero, ← sub_eq_add_neg, ← zmod.cast_val x, ← nat.cast_sub (le_of_lt x.2), zmod.val_cast_nat, mod_eq_of_lt hxn, nat.sub_le_sub_left_iff (le_of_lt x.2)] } lemma ne_neg_self {n : ℕ+} (hn1 : (n : ℕ) % 2 = 1) {a : zmod n} (ha : a ≠ 0) : a ≠ -a := λ h, have a.val ≤ n / 2 ↔ (n : ℕ) / 2 < (-a).val := le_div_two_iff_lt_neg hn1 ha, by rwa [← h, ← not_lt, not_iff_self] at this @[simp] lemma cast_mul_right_val_cast {n m : ℕ+} (a : ℕ) : ((a : zmod (m * n)).val : zmod m) = (a : zmod m) := zmod.eq_iff_modeq_nat.2 (by rw zmod.val_cast_nat; exact nat.modeq.modeq_of_modeq_mul_right _ (nat.mod_mod _ _)) @[simp] lemma cast_mul_left_val_cast {n m : ℕ+} (a : ℕ) : ((a : zmod (n * m)).val : zmod m) = (a : zmod m) := zmod.eq_iff_modeq_nat.2 (by rw zmod.val_cast_nat; exact nat.modeq.modeq_of_modeq_mul_left _ (nat.mod_mod _ _)) lemma cast_val_cast_of_dvd {n m : ℕ+} (h : (m : ℕ) ∣ n) (a : ℕ) : ((a : zmod n).val : zmod m) = (a : zmod m) := let ⟨k , hk⟩ := h in zmod.eq_iff_modeq_nat.2 (nat.modeq.modeq_of_modeq_mul_right k (by rw [← hk, zmod.val_cast_nat]; exact nat.mod_mod _ _)) def units_equiv_coprime {n : ℕ+} : units (zmod n) ≃ {x : zmod n // nat.coprime x.1 n} := { to_fun := λ x, ⟨x, nat.modeq.coprime_of_mul_modeq_one (x⁻¹).1.1 begin have := units.ext_iff.1 (mul_right_inv x), rwa [← zmod.cast_val ((1 : units (zmod n)) : zmod n), units.coe_one, zmod.one_val, ← zmod.cast_val ((x * x⁻¹ : units (zmod n)) : zmod n), units.coe_mul, zmod.mul_val, zmod.cast_mod_nat, zmod.cast_mod_nat, zmod.eq_iff_modeq_nat] at this end⟩, inv_fun := λ x, have x.val * ↑(gcd_a ((x.val).val) ↑n) = 1, by rw [← zmod.cast_val x.1, ← int.cast_coe_nat, ← int.cast_one, ← int.cast_mul, zmod.eq_iff_modeq_int, ← int.coe_nat_one, ← (show nat.gcd _ _ = _, from x.2)]; simpa using int.modeq.gcd_a_modeq x.1.1 n, ⟨x.1, gcd_a x.1.1 n, this, by simpa [mul_comm] using this⟩, left_inv := λ ⟨_, _, _, _⟩, units.ext rfl, right_inv := λ ⟨_, _⟩, rfl } section variables {α : Type*} [has_zero α] [has_one α] [has_add α] {n : ℕ+} def cast : zmod n → α := nat.cast ∘ fin.val end end zmod def zmodp (p : ℕ) (hp : prime p) : Type := zmod ⟨p, hp.pos⟩ namespace zmodp variables {p : ℕ} (hp : prime p) instance : comm_ring (zmodp p hp) := zmod.comm_ring ⟨p, hp.pos⟩ instance {p : ℕ} (hp : prime p) : has_inv (zmodp p hp) := ⟨λ a, gcd_a a.1 p⟩ lemma add_val : ∀ a b : zmodp p hp, (a + b).val = (a.val + b.val) % p | ⟨_, _⟩ ⟨_, _⟩ := rfl lemma mul_val : ∀ a b : zmodp p hp, (a * b).val = (a.val * b.val) % p | ⟨_, _⟩ ⟨_, _⟩ := rfl @[simp] lemma one_val : (1 : zmodp p hp).val = 1 := nat.mod_eq_of_lt hp.gt_one @[simp] lemma zero_val : (0 : zmodp p hp).val = 0 := rfl lemma val_cast_nat (a : ℕ) : (a : zmodp p hp).val = a % p := @zmod.val_cast_nat ⟨p, hp.pos⟩ _ lemma mk_eq_cast {a : ℕ} (h : a < p) : (⟨a, h⟩ : zmodp p hp) = (a : zmodp p hp) := @zmod.mk_eq_cast ⟨p, hp.pos⟩ _ _ @[simp] lemma cast_self_eq_zero: (p : zmodp p hp) = 0 := fin.eq_of_veq $ by simp [val_cast_nat] lemma val_cast_of_lt {a : ℕ} (h : a < p) : (a : zmodp p hp).val = a := @zmod.val_cast_of_lt ⟨p, hp.pos⟩ _ h @[simp] lemma cast_mod_nat (a : ℕ) : ((a % p : ℕ) : zmodp p hp) = a := @zmod.cast_mod_nat ⟨p, hp.pos⟩ _ @[simp] lemma cast_val (a : zmodp p hp) : (a.val : zmodp p hp) = a := @zmod.cast_val ⟨p, hp.pos⟩ _ @[simp] lemma cast_mod_int (a : ℤ) : ((a % p : ℤ) : zmodp p hp) = a := @zmod.cast_mod_int ⟨p, hp.pos⟩ _ lemma val_cast_int (a : ℤ) : (a : zmodp p hp).val = (a % p).nat_abs := @zmod.val_cast_int ⟨p, hp.pos⟩ _ lemma coe_val_cast_int (a : ℤ) : ((a : zmodp p hp).val : ℤ) = a % (p : ℕ) := @zmod.coe_val_cast_int ⟨p, hp.pos⟩ _ lemma eq_iff_modeq_nat {a b : ℕ} : (a : zmodp p hp) = b ↔ a ≡ b [MOD p] := @zmod.eq_iff_modeq_nat ⟨p, hp.pos⟩ _ _ lemma eq_iff_modeq_int {a b : ℤ} : (a : zmodp p hp) = b ↔ a ≡ b [ZMOD p] := @zmod.eq_iff_modeq_int ⟨p, hp.pos⟩ _ _ lemma eq_zero_iff_dvd_nat (a : ℕ) : (a : zmodp p hp) = 0 ↔ p ∣ a := @zmod.eq_zero_iff_dvd_nat ⟨p, hp.pos⟩ _ lemma eq_zero_iff_dvd_int (a : ℤ) : (a : zmodp p hp) = 0 ↔ (p : ℤ) ∣ a := @zmod.eq_zero_iff_dvd_int ⟨p, hp.pos⟩ _ instance : fintype (zmodp p hp) := @zmod.fintype ⟨p, hp.pos⟩ instance decidable_eq : decidable_eq (zmodp p hp) := fin.decidable_eq _ instance : has_repr (zmodp p hp) := fin.has_repr _ @[simp] lemma card_zmodp : fintype.card (zmodp p hp) = p := @zmod.card_zmod ⟨p, hp.pos⟩ lemma le_div_two_iff_lt_neg {p : ℕ} (hp : prime p) (hp1 : p % 2 = 1) {x : zmodp p hp} (hx0 : x ≠ 0) : x.1 ≤ (p / 2 : ℕ) ↔ (p / 2 : ℕ) < (-x).1 := @zmod.le_div_two_iff_lt_neg ⟨p, hp.pos⟩ hp1 _ hx0 lemma ne_neg_self (hp1 : p % 2 = 1) {a : zmodp p hp} (ha : a ≠ 0) : a ≠ -a := @zmod.ne_neg_self ⟨p, hp.pos⟩ hp1 _ ha lemma prime_ne_zero {q : ℕ} (hq : prime q) (hpq : p ≠ q) : (q : zmodp p hp) ≠ 0 := by rwa [← nat.cast_zero, ne.def, zmodp.eq_iff_modeq_nat, nat.modeq.modeq_zero_iff, ← hp.coprime_iff_not_dvd, coprime_primes hp hq] lemma mul_inv_eq_gcd (a : ℕ) : (a : zmodp p hp) * a⁻¹ = nat.gcd a p := by rw [← int.cast_coe_nat (nat.gcd _ _), nat.gcd_comm, nat.gcd_rec, ← (eq_iff_modeq_int _).2 (int.modeq.gcd_a_modeq _ _)]; simp [has_inv.inv, val_cast_nat] private lemma mul_inv_cancel_aux : ∀ a : zmodp p hp, a ≠ 0 → a * a⁻¹ = 1 := λ ⟨a, hap⟩ ha0, begin rw [mk_eq_cast, ne.def, ← @nat.cast_zero (zmodp p hp), eq_iff_modeq_nat, modeq_zero_iff] at ha0, have : nat.gcd p a = 1 := (prime.coprime_iff_not_dvd hp).2 ha0, rw [mk_eq_cast _ hap, mul_inv_eq_gcd, nat.gcd_comm], simpa [nat.gcd_comm, this] end instance : discrete_field (zmodp p hp) := { zero_ne_one := fin.ne_of_vne $ show 0 ≠ 1 % p, by rw nat.mod_eq_of_lt hp.gt_one; exact zero_ne_one, mul_inv_cancel := mul_inv_cancel_aux hp, inv_mul_cancel := λ a, by rw mul_comm; exact mul_inv_cancel_aux hp _, has_decidable_eq := by apply_instance, inv_zero := show (gcd_a 0 p : zmodp p hp) = 0, by unfold gcd_a xgcd xgcd_aux; refl, ..zmodp.comm_ring hp, ..zmodp.has_inv hp } end zmodp
386276428381d2405bf821f23e2231a90ed9df0b
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/order/pilex.lean
b578712d54a89c9a084c2b6a9c504e1c5e4953f6
[ "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
4,660
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import algebra.ordered_pi import order.well_founded import algebra.order_functions /-! # Lexicographic order on Pi types This file defines the lexicographic relation for Pi types of partial orders and linear orders. We also provide a `pilex` analog of `pi.ordered_comm_group` (see `algebra.ordered_pi`). -/ variables {ι : Type*} {β : ι → Type*} (r : ι → ι → Prop) (s : Π {i}, β i → β i → Prop) /-- The lexicographic relation on `Π i : ι, β i`, where `ι` is ordered by `r`, and each `β i` is ordered by `s`. -/ def pi.lex (x y : Π i, β i) : Prop := ∃ i, (∀ j, r j i → x j = y j) ∧ s (x i) (y i) /-- The cartesian product of an indexed family, equipped with the lexicographic order. -/ def pilex (α : Type*) (β : α → Type*) : Type* := Π a, β a instance [has_lt ι] [∀ a, has_lt (β a)] : has_lt (pilex ι β) := { lt := pi.lex (<) (λ _, (<)) } instance [∀ a, inhabited (β a)] : inhabited (pilex ι β) := by unfold pilex; apply_instance set_option eqn_compiler.zeta true instance [linear_order ι] [∀ a, partial_order (β a)] : partial_order (pilex ι β) := have lt_not_symm : ∀ {x y : pilex ι β}, ¬ (x < y ∧ y < x), from λ x y ⟨⟨i, hi⟩, ⟨j, hj⟩⟩, begin obtain hij | hij | hji := lt_trichotomy i j, { exact lt_irrefl (x i) (by simpa [hj.1 _ hij] using hi.2) }, { exact not_le_of_gt hj.2 (hij ▸ le_of_lt hi.2) }, { exact lt_irrefl (x j) (by simpa [hi.1 _ hji] using hj.2) }, end, { le := λ x y, x < y ∨ x = y, le_refl := λ _, or.inr rfl, le_antisymm := λ x y hxy hyx, hxy.elim (λ hxy, hyx.elim (λ hyx, false.elim (lt_not_symm ⟨hxy, hyx⟩)) eq.symm) id, le_trans := λ x y z hxy hyz, hxy.elim (λ ⟨i, hi⟩, hyz.elim (λ ⟨j, hj⟩, or.inl ⟨by exactI min i j, by resetI; exact λ k hk, by rw [hi.1 _ (lt_min_iff.1 hk).1, hj.1 _ (lt_min_iff.1 hk).2], by resetI; exact (le_total i j).elim (λ hij, by rw [min_eq_left hij]; exact lt_of_lt_of_le hi.2 ((lt_or_eq_of_le hij).elim (λ h, le_of_eq (hj.1 _ h)) (λ h, h.symm ▸ le_of_lt hj.2))) (λ hji, by rw [min_eq_right hji]; exact lt_of_le_of_lt ((lt_or_eq_of_le hji).elim (λ h, le_of_eq (hi.1 _ h)) (λ h, h.symm ▸ le_of_lt hi.2)) hj.2)⟩) (λ hyz, hyz ▸ hxy)) (λ hxy, hxy.symm ▸ hyz), lt_iff_le_not_le := λ x y, show x < y ↔ (x < y ∨ x = y) ∧ ¬ (y < x ∨ y = x), from ⟨λ ⟨i, hi⟩, ⟨or.inl ⟨i, hi⟩, λ h, h.elim (λ ⟨j, hj⟩, begin rcases lt_trichotomy i j with hij | hij | hji, { exact lt_irrefl (x i) (by simpa [hj.1 _ hij] using hi.2) }, { exact not_le_of_gt hj.2 (hij ▸ le_of_lt hi.2) }, { exact lt_irrefl (x j) (by simpa [hi.1 _ hji] using hj.2) }, end) (λ hyx, lt_irrefl (x i) (by simpa [hyx] using hi.2))⟩, by tauto⟩, ..pilex.has_lt } /-- `pilex` is a linear order if the original order is well-founded. This cannot be an instance, since it depends on the well-foundedness of `<`. -/ protected noncomputable def pilex.linear_order [linear_order ι] (wf : well_founded ((<) : ι → ι → Prop)) [∀ a, linear_order (β a)] : linear_order (pilex ι β) := { le_total := λ x y, by classical; exact or_iff_not_imp_left.2 (λ hxy, begin have := not_or_distrib.1 hxy, let i : ι := well_founded.min wf _ (not_forall.1 (this.2 ∘ funext)), have hjiyx : ∀ j < i, y j = x j, { assume j, rw [eq_comm, ← not_imp_not], exact λ h, well_founded.not_lt_min wf _ _ h }, refine or.inl ⟨i, hjiyx, _⟩, { refine lt_of_not_ge (λ hyx, _), exact this.1 ⟨i, (λ j hj, (hjiyx j hj).symm), lt_of_le_of_ne hyx (well_founded.min_mem _ {i | x i ≠ y i} _)⟩ } end), decidable_le := classical.dec_rel _, ..pilex.partial_order } --we might want the analog of `pi.ordered_cancel_comm_monoid` as well in the future @[to_additive] instance [linear_order ι] [∀ a, ordered_comm_group (β a)] : ordered_comm_group (pilex ι β) := { mul_le_mul_left := λ x y hxy z, hxy.elim (λ ⟨i, hi⟩, or.inl ⟨i, λ j hji, show z j * x j = z j * y j, by rw hi.1 j hji, mul_lt_mul_left' hi.2 _⟩) (λ hxyz, hxyz ▸ le_refl _), ..pilex.partial_order, ..pi.comm_group }
142df0e5aae733fa53961ad75cfe6625c64efbaa
9dc8cecdf3c4634764a18254e94d43da07142918
/src/logic/equiv/embedding.lean
0d4e4832daf74c483da5b7ea840d3ee1e2a6aecd
[ "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
3,711
lean
/- Copyright (c) 2021 Eric Rodriguez. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Rodriguez -/ import logic.embedding /-! # Equivalences on embeddings This file shows some advanced equivalences on embeddings, useful for constructing larger embeddings from smaller ones. -/ open function.embedding namespace equiv /-- Embeddings from a sum type are equivalent to two separate embeddings with disjoint ranges. -/ def sum_embedding_equiv_prod_embedding_disjoint {α β γ : Type*} : ((α ⊕ β) ↪ γ) ≃ {f : (α ↪ γ) × (β ↪ γ) // disjoint (set.range f.1) (set.range f.2)} := { to_fun := λ f, ⟨(inl.trans f, inr.trans f), begin rintros _ ⟨⟨a, h⟩, ⟨b, rfl⟩⟩, simp only [trans_apply, inl_apply, inr_apply] at h, have : sum.inl a = sum.inr b := f.injective h, simp only at this, assumption end⟩, inv_fun := λ ⟨⟨f, g⟩, disj⟩, ⟨λ x, match x with | (sum.inl a) := f a | (sum.inr b) := g b end, begin rintros (a₁|b₁) (a₂|b₂) f_eq; simp only [equiv.coe_fn_symm_mk, sum.elim_inl, sum.elim_inr] at f_eq, { rw f.injective f_eq }, { simp! only at f_eq, exfalso, exact disj ⟨⟨a₁, by simp⟩, ⟨b₂, by simp [f_eq]⟩⟩ }, { simp! only at f_eq, exfalso, exact disj ⟨⟨a₂, by simp⟩, ⟨b₁, by simp [f_eq]⟩⟩ }, { rw g.injective f_eq } end⟩, left_inv := λ f, by { dsimp only, ext, cases x; simp! }, right_inv := λ ⟨⟨f, g⟩, _⟩, by { simp only [prod.mk.inj_iff], split; ext; simp! } } /-- Embeddings whose range lies within a set are equivalent to embeddings to that set. This is `function.embedding.cod_restrict` as an equiv. -/ def cod_restrict (α : Type*) {β : Type*} (bs : set β) : {f : α ↪ β // ∀ a, f a ∈ bs} ≃ (α ↪ bs) := { to_fun := λ f, (f : α ↪ β).cod_restrict bs f.prop, inv_fun := λ f, ⟨f.trans (function.embedding.subtype _), λ a, (f a).prop⟩, left_inv := λ x, by ext; refl, right_inv := λ x, by ext; refl } /-- Pairs of embeddings with disjoint ranges are equivalent to a dependent sum of embeddings, in which the second embedding cannot take values in the range of the first. -/ def prod_embedding_disjoint_equiv_sigma_embedding_restricted {α β γ : Type*} : {f : (α ↪ γ) × (β ↪ γ) // disjoint (set.range f.1) (set.range f.2)} ≃ (Σ f : α ↪ γ, β ↪ ↥((set.range f)ᶜ)) := (subtype_prod_equiv_sigma_subtype $ λ (a : α ↪ γ) (b : β ↪ _), disjoint (set.range a) (set.range b)).trans $ equiv.sigma_congr_right $ λ a, (subtype_equiv_prop $ by { ext f, rw [←set.range_subset_iff, set.subset_compl_iff_disjoint_right, disjoint.comm] }).trans (cod_restrict _ _) /-- A combination of the above results, allowing us to turn one embedding over a sum type into two dependent embeddings, the second of which avoids any members of the range of the first. This is helpful for constructing larger embeddings out of smaller ones. -/ def sum_embedding_equiv_sigma_embedding_restricted {α β γ : Type*} : ((α ⊕ β) ↪ γ) ≃ (Σ f : α ↪ γ, β ↪ ↥((set.range f)ᶜ)) := equiv.trans sum_embedding_equiv_prod_embedding_disjoint prod_embedding_disjoint_equiv_sigma_embedding_restricted /-- Embeddings from a single-member type are equivalent to members of the target type. -/ def unique_embedding_equiv_result {α β : Type*} [unique α] : (α ↪ β) ≃ β := { to_fun := λ f, f default, inv_fun := λ x, ⟨λ _, x, λ _ _ _, subsingleton.elim _ _⟩, left_inv := λ _, by { ext, simp_rw [function.embedding.coe_fn_mk], congr }, right_inv := λ _, by simp } end equiv
8079deb81e5f4629498be4abaa79d7407929dc71
d1bbf1801b3dcb214451d48214589f511061da63
/src/analysis/calculus/fderiv.lean
97f4a5a3744cd11821781f6eeec7b228ac47254c
[ "Apache-2.0" ]
permissive
cheraghchi/mathlib
5c366f8c4f8e66973b60c37881889da8390cab86
f29d1c3038422168fbbdb2526abf7c0ff13e86db
refs/heads/master
1,676,577,831,283
1,610,894,638,000
1,610,894,638,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
120,075
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Sébastien Gouëzel, Yury Kudryashov -/ import analysis.calculus.tangent_cone import analysis.normed_space.units import analysis.asymptotic_equivalent /-! # The Fréchet derivative Let `E` and `F` be normed spaces, `f : E → F`, and `f' : E →L[𝕜] F` a continuous 𝕜-linear map, where `𝕜` is a non-discrete normed field. Then `has_fderiv_within_at f f' s x` says that `f` has derivative `f'` at `x`, where the domain of interest is restricted to `s`. We also have `has_fderiv_at f f' x := has_fderiv_within_at f f' x univ` Finally, `has_strict_fderiv_at f f' x` means that `f : E → F` has derivative `f' : E →L[𝕜] F` in the sense of strict differentiability, i.e., `f y - f z - f'(y - z) = o(y - z)` as `y, z → x`. This notion is used in the inverse function theorem, and is defined here only to avoid proving theorems like `is_bounded_bilinear_map.has_fderiv_at` twice: first for `has_fderiv_at`, then for `has_strict_fderiv_at`. ## Main results In addition to the definition and basic properties of the derivative, this file contains the usual formulas (and existence assertions) for the derivative of * constants * the identity * bounded linear maps * bounded bilinear maps * sum of two functions * sum of finitely many functions * multiplication of a function by a scalar constant * negative of a function * subtraction of two functions * multiplication of a function by a scalar function * multiplication of two scalar functions * composition of functions (the chain rule) * inverse function (assuming that it exists; the inverse function theorem is in `inverse.lean`) For most binary operations we also define `const_op` and `op_const` theorems for the cases when the first or second argument is a constant. This makes writing chains of `has_deriv_at`'s easier, and they more frequently lead to the desired result. One can also interpret the derivative of a function `f : 𝕜 → E` as an element of `E` (by identifying a linear function from `𝕜` to `E` with its value at `1`). Results on the Fréchet derivative are translated to this more elementary point of view on the derivative in the file `deriv.lean`. The derivative of polynomials is handled there, as it is naturally one-dimensional. The simplifier is set up to prove automatically that some functions are differentiable, or differentiable at a point (but not differentiable on a set or within a set at a point, as checking automatically that the good domains are mapped one to the other when using composition is not something the simplifier can easily do). This means that one can write `example (x : ℝ) : differentiable ℝ (λ x, sin (exp (3 + x^2)) - 5 * cos x) := by simp`. If there are divisions, one needs to supply to the simplifier proofs that the denominators do not vanish, as in ```lean example (x : ℝ) (h : 1 + sin x ≠ 0) : differentiable_at ℝ (λ x, exp x / (1 + sin x)) x := by simp [h] ``` Of course, these examples only work once `exp`, `cos` and `sin` have been shown to be differentiable, in `analysis.special_functions.trigonometric`. The simplifier is not set up to compute the Fréchet derivative of maps (as these are in general complicated multidimensional linear maps), but it will compute one-dimensional derivatives, see `deriv.lean`. ## Implementation details The derivative is defined in terms of the `is_o` relation, but also characterized in terms of the `tendsto` relation. We also introduce predicates `differentiable_within_at 𝕜 f s x` (where `𝕜` is the base field, `f` the function to be differentiated, `x` the point at which the derivative is asserted to exist, and `s` the set along which the derivative is defined), as well as `differentiable_at 𝕜 f x`, `differentiable_on 𝕜 f s` and `differentiable 𝕜 f` to express the existence of a derivative. To be able to compute with derivatives, we write `fderiv_within 𝕜 f s x` and `fderiv 𝕜 f x` for some choice of a derivative if it exists, and the zero function otherwise. This choice only behaves well along sets for which the derivative is unique, i.e., those for which the tangent directions span a dense subset of the whole space. The predicates `unique_diff_within_at s x` and `unique_diff_on s`, defined in `tangent_cone.lean` express this property. We prove that indeed they imply the uniqueness of the derivative. This is satisfied for open subsets, and in particular for `univ`. This uniqueness only holds when the field is non-discrete, which we request at the very beginning: otherwise, a derivative can be defined, but it has no interesting properties whatsoever. To make sure that the simplifier can prove automatically that functions are differentiable, we tag many lemmas with the `simp` attribute, for instance those saying that the sum of differentiable functions is differentiable, as well as their product, their cartesian product, and so on. A notable exception is the chain rule: we do not mark as a simp lemma the fact that, if `f` and `g` are differentiable, then their composition also is: `simp` would always be able to match this lemma, by taking `f` or `g` to be the identity. Instead, for every reasonable function (say, `exp`), we add a lemma that if `f` is differentiable then so is `(λ x, exp (f x))`. This means adding some boilerplate lemmas, but these can also be useful in their own right. Tests for this ability of the simplifier (with more examples) are provided in `tests/differentiable.lean`. ## Tags derivative, differentiable, Fréchet, calculus -/ open filter asymptotics continuous_linear_map set metric open_locale topological_space classical nnreal asymptotics filter noncomputable theory section variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] variables {G : Type*} [normed_group G] [normed_space 𝕜 G] variables {G' : Type*} [normed_group G'] [normed_space 𝕜 G'] /-- A function `f` has the continuous linear map `f'` as derivative along the filter `L` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` converges along the filter `L`. This definition is designed to be specialized for `L = 𝓝 x` (in `has_fderiv_at`), giving rise to the usual notion of Fréchet derivative, and for `L = 𝓝[s] x` (in `has_fderiv_within_at`), giving rise to the notion of Fréchet derivative along the set `s`. -/ def has_fderiv_at_filter (f : E → F) (f' : E →L[𝕜] F) (x : E) (L : filter E) := is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L /-- A function `f` has the continuous linear map `f'` as derivative at `x` within a set `s` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` tends to `x` inside `s`. -/ def has_fderiv_within_at (f : E → F) (f' : E →L[𝕜] F) (s : set E) (x : E) := has_fderiv_at_filter f f' x (𝓝[s] x) /-- A function `f` has the continuous linear map `f'` as derivative at `x` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` tends to `x`. -/ def has_fderiv_at (f : E → F) (f' : E →L[𝕜] F) (x : E) := has_fderiv_at_filter f f' x (𝓝 x) /-- A function `f` has derivative `f'` at `a` in the sense of *strict differentiability* if `f x - f y - f' (x - y) = o(x - y)` as `x, y → a`. This form of differentiability is required, e.g., by the inverse function theorem. Any `C^1` function on a vector space over `ℝ` is strictly differentiable but this definition works, e.g., for vector spaces over `p`-adic numbers. -/ def has_strict_fderiv_at (f : E → F) (f' : E →L[𝕜] F) (x : E) := is_o (λ p : E × E, f p.1 - f p.2 - f' (p.1 - p.2)) (λ p : E × E, p.1 - p.2) (𝓝 (x, x)) variables (𝕜) /-- A function `f` is differentiable at a point `x` within a set `s` if it admits a derivative there (possibly non-unique). -/ def differentiable_within_at (f : E → F) (s : set E) (x : E) := ∃f' : E →L[𝕜] F, has_fderiv_within_at f f' s x /-- A function `f` is differentiable at a point `x` if it admits a derivative there (possibly non-unique). -/ def differentiable_at (f : E → F) (x : E) := ∃f' : E →L[𝕜] F, has_fderiv_at f f' x /-- If `f` has a derivative at `x` within `s`, then `fderiv_within 𝕜 f s x` is such a derivative. Otherwise, it is set to `0`. -/ def fderiv_within (f : E → F) (s : set E) (x : E) : E →L[𝕜] F := if h : ∃f', has_fderiv_within_at f f' s x then classical.some h else 0 /-- If `f` has a derivative at `x`, then `fderiv 𝕜 f x` is such a derivative. Otherwise, it is set to `0`. -/ def fderiv (f : E → F) (x : E) : E →L[𝕜] F := if h : ∃f', has_fderiv_at f f' x then classical.some h else 0 /-- `differentiable_on 𝕜 f s` means that `f` is differentiable within `s` at any point of `s`. -/ def differentiable_on (f : E → F) (s : set E) := ∀x ∈ s, differentiable_within_at 𝕜 f s x /-- `differentiable 𝕜 f` means that `f` is differentiable at any point. -/ def differentiable (f : E → F) := ∀x, differentiable_at 𝕜 f x variables {𝕜} variables {f f₀ f₁ g : E → F} variables {f' f₀' f₁' g' : E →L[𝕜] F} variables (e : E →L[𝕜] F) variables {x : E} variables {s t : set E} variables {L L₁ L₂ : filter E} lemma fderiv_within_zero_of_not_differentiable_within_at (h : ¬ differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 f s x = 0 := have ¬ ∃ f', has_fderiv_within_at f f' s x, from h, by simp [fderiv_within, this] lemma fderiv_zero_of_not_differentiable_at (h : ¬ differentiable_at 𝕜 f x) : fderiv 𝕜 f x = 0 := have ¬ ∃ f', has_fderiv_at f f' x, from h, by simp [fderiv, this] section derivative_uniqueness /- In this section, we discuss the uniqueness of the derivative. We prove that the definitions `unique_diff_within_at` and `unique_diff_on` indeed imply the uniqueness of the derivative. -/ /-- If a function f has a derivative f' at x, a rescaled version of f around x converges to f', i.e., `n (f (x + (1/n) v) - f x)` converges to `f' v`. More generally, if `c n` tends to infinity and `c n * d n` tends to `v`, then `c n * (f (x + d n) - f x)` tends to `f' v`. This lemma expresses this fact, for functions having a derivative within a set. Its specific formulation is useful for tangent cone related discussions. -/ theorem has_fderiv_within_at.lim (h : has_fderiv_within_at f f' s x) {α : Type*} (l : filter α) {c : α → 𝕜} {d : α → E} {v : E} (dtop : ∀ᶠ n in l, x + d n ∈ s) (clim : tendsto (λ n, ∥c n∥) l at_top) (cdlim : tendsto (λ n, c n • d n) l (𝓝 v)) : tendsto (λn, c n • (f (x + d n) - f x)) l (𝓝 (f' v)) := begin have tendsto_arg : tendsto (λ n, x + d n) l (𝓝[s] x), { conv in (𝓝[s] x) { rw ← add_zero x }, rw [nhds_within, tendsto_inf], split, { apply tendsto_const_nhds.add (tangent_cone_at.lim_zero l clim cdlim) }, { rwa tendsto_principal } }, have : is_o (λ y, f y - f x - f' (y - x)) (λ y, y - x) (𝓝[s] x) := h, have : is_o (λ n, f (x + d n) - f x - f' ((x + d n) - x)) (λ n, (x + d n) - x) l := this.comp_tendsto tendsto_arg, have : is_o (λ n, f (x + d n) - f x - f' (d n)) d l := by simpa only [add_sub_cancel'], have : is_o (λn, c n • (f (x + d n) - f x - f' (d n))) (λn, c n • d n) l := (is_O_refl c l).smul_is_o this, have : is_o (λn, c n • (f (x + d n) - f x - f' (d n))) (λn, (1:ℝ)) l := this.trans_is_O (is_O_one_of_tendsto ℝ cdlim), have L1 : tendsto (λn, c n • (f (x + d n) - f x - f' (d n))) l (𝓝 0) := (is_o_one_iff ℝ).1 this, have L2 : tendsto (λn, f' (c n • d n)) l (𝓝 (f' v)) := tendsto.comp f'.cont.continuous_at cdlim, have L3 : tendsto (λn, (c n • (f (x + d n) - f x - f' (d n)) + f' (c n • d n))) l (𝓝 (0 + f' v)) := L1.add L2, have : (λn, (c n • (f (x + d n) - f x - f' (d n)) + f' (c n • d n))) = (λn, c n • (f (x + d n) - f x)), by { ext n, simp [smul_add, smul_sub] }, rwa [this, zero_add] at L3 end /-- If `f'` and `f₁'` are two derivatives of `f` within `s` at `x`, then they are equal on the tangent cone to `s` at `x` -/ theorem has_fderiv_within_at.unique_on (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at f f₁' s x) : eq_on f' f₁' (tangent_cone_at 𝕜 s x) := λ y ⟨c, d, dtop, clim, cdlim⟩, tendsto_nhds_unique (hf.lim at_top dtop clim cdlim) (hg.lim at_top dtop clim cdlim) /-- `unique_diff_within_at` achieves its goal: it implies the uniqueness of the derivative. -/ theorem unique_diff_within_at.eq (H : unique_diff_within_at 𝕜 s x) (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at f f₁' s x) : f' = f₁' := continuous_linear_map.ext_on H.1 (hf.unique_on hg) theorem unique_diff_on.eq (H : unique_diff_on 𝕜 s) (hx : x ∈ s) (h : has_fderiv_within_at f f' s x) (h₁ : has_fderiv_within_at f f₁' s x) : f' = f₁' := (H x hx).eq h h₁ end derivative_uniqueness section fderiv_properties /-! ### Basic properties of the derivative -/ theorem has_fderiv_at_filter_iff_tendsto : has_fderiv_at_filter f f' x L ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (𝓝 0) := have h : ∀ x', ∥x' - x∥ = 0 → ∥f x' - f x - f' (x' - x)∥ = 0, from λ x' hx', by { rw [sub_eq_zero.1 (norm_eq_zero.1 hx')], simp }, begin unfold has_fderiv_at_filter, rw [←is_o_norm_left, ←is_o_norm_right, is_o_iff_tendsto h], exact tendsto_congr (λ _, div_eq_inv_mul), end theorem has_fderiv_within_at_iff_tendsto : has_fderiv_within_at f f' s x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (𝓝[s] x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_fderiv_at_iff_tendsto : has_fderiv_at f f' x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (𝓝 x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_fderiv_at_iff_is_o_nhds_zero : has_fderiv_at f f' x ↔ is_o (λh, f (x + h) - f x - f' h) (λh, h) (𝓝 0) := begin rw [has_fderiv_at, has_fderiv_at_filter, ← map_add_left_nhds_zero x, is_o_map], simp [(∘)] end /-- Converse to the mean value inequality: if `f` is differentiable at `x₀` and `C`-lipschitz on a neighborhood of `x₀` then it its derivative at `x₀` has norm bounded by `C`. -/ lemma has_fderiv_at.le_of_lip {f : E → F} {f' : E →L[𝕜] F} {x₀ : E} (hf : has_fderiv_at f f' x₀) {s : set E} (hs : s ∈ 𝓝 x₀) {C : ℝ≥0} (hlip : lipschitz_on_with C f s) : ∥f'∥ ≤ C := begin refine le_of_forall_pos_le_add (λ ε ε0, op_norm_le_of_nhds_zero _ _), exact add_nonneg C.coe_nonneg ε0.le, have hs' := hs, rw [← map_add_left_nhds_zero x₀, mem_map] at hs', filter_upwards [is_o_iff.1 (has_fderiv_at_iff_is_o_nhds_zero.1 hf) ε0, hs'], intros y hy hys, have := hlip.norm_sub_le hys (mem_of_nhds hs), rw add_sub_cancel' at this, calc ∥f' y∥ ≤ ∥f (x₀ + y) - f x₀∥ + ∥f (x₀ + y) - f x₀ - f' y∥ : norm_le_insert _ _ ... ≤ C * ∥y∥ + ε * ∥y∥ : add_le_add this hy ... = (C + ε) * ∥y∥ : (add_mul _ _ _).symm end theorem has_fderiv_at_filter.mono (h : has_fderiv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) : has_fderiv_at_filter f f' x L₁ := h.mono hst theorem has_fderiv_within_at.mono (h : has_fderiv_within_at f f' t x) (hst : s ⊆ t) : has_fderiv_within_at f f' s x := h.mono (nhds_within_mono _ hst) theorem has_fderiv_at.has_fderiv_at_filter (h : has_fderiv_at f f' x) (hL : L ≤ 𝓝 x) : has_fderiv_at_filter f f' x L := h.mono hL theorem has_fderiv_at.has_fderiv_within_at (h : has_fderiv_at f f' x) : has_fderiv_within_at f f' s x := h.has_fderiv_at_filter inf_le_left lemma has_fderiv_within_at.differentiable_within_at (h : has_fderiv_within_at f f' s x) : differentiable_within_at 𝕜 f s x := ⟨f', h⟩ lemma has_fderiv_at.differentiable_at (h : has_fderiv_at f f' x) : differentiable_at 𝕜 f x := ⟨f', h⟩ @[simp] lemma has_fderiv_within_at_univ : has_fderiv_within_at f f' univ x ↔ has_fderiv_at f f' x := by { simp only [has_fderiv_within_at, nhds_within_univ], refl } lemma has_strict_fderiv_at.is_O_sub (hf : has_strict_fderiv_at f f' x) : is_O (λ p : E × E, f p.1 - f p.2) (λ p : E × E, p.1 - p.2) (𝓝 (x, x)) := hf.is_O.congr_of_sub.2 (f'.is_O_comp _ _) lemma has_fderiv_at_filter.is_O_sub (h : has_fderiv_at_filter f f' x L) : is_O (λ x', f x' - f x) (λ x', x' - x) L := h.is_O.congr_of_sub.2 (f'.is_O_sub _ _) protected lemma has_strict_fderiv_at.has_fderiv_at (hf : has_strict_fderiv_at f f' x) : has_fderiv_at f f' x := begin rw [has_fderiv_at, has_fderiv_at_filter, is_o_iff], exact (λ c hc, tendsto_id.prod_mk_nhds tendsto_const_nhds (is_o_iff.1 hf hc)) end protected lemma has_strict_fderiv_at.differentiable_at (hf : has_strict_fderiv_at f f' x) : differentiable_at 𝕜 f x := hf.has_fderiv_at.differentiable_at /-- Directional derivative agrees with `has_fderiv`. -/ lemma has_fderiv_at.lim (hf : has_fderiv_at f f' x) (v : E) {α : Type*} {c : α → 𝕜} {l : filter α} (hc : tendsto (λ n, ∥c n∥) l at_top) : tendsto (λ n, (c n) • (f (x + (c n)⁻¹ • v) - f x)) l (𝓝 (f' v)) := begin refine (has_fderiv_within_at_univ.2 hf).lim _ (univ_mem_sets' (λ _, trivial)) hc _, assume U hU, refine (eventually_ne_of_tendsto_norm_at_top hc (0:𝕜)).mono (λ y hy, _), convert mem_of_nhds hU, dsimp only, rw [← mul_smul, mul_inv_cancel hy, one_smul] end theorem has_fderiv_at_unique (h₀ : has_fderiv_at f f₀' x) (h₁ : has_fderiv_at f f₁' x) : f₀' = f₁' := begin rw ← has_fderiv_within_at_univ at h₀ h₁, exact unique_diff_within_at_univ.eq h₀ h₁ end lemma has_fderiv_within_at_inter' (h : t ∈ 𝓝[s] x) : has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x := by simp [has_fderiv_within_at, nhds_within_restrict'' s h] lemma has_fderiv_within_at_inter (h : t ∈ 𝓝 x) : has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x := by simp [has_fderiv_within_at, nhds_within_restrict' s h] lemma has_fderiv_within_at.union (hs : has_fderiv_within_at f f' s x) (ht : has_fderiv_within_at f f' t x) : has_fderiv_within_at f f' (s ∪ t) x := begin simp only [has_fderiv_within_at, nhds_within_union], exact hs.join ht, end lemma has_fderiv_within_at.nhds_within (h : has_fderiv_within_at f f' s x) (ht : s ∈ 𝓝[t] x) : has_fderiv_within_at f f' t x := (has_fderiv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _)) lemma has_fderiv_within_at.has_fderiv_at (h : has_fderiv_within_at f f' s x) (hs : s ∈ 𝓝 x) : has_fderiv_at f f' x := by rwa [← univ_inter s, has_fderiv_within_at_inter hs, has_fderiv_within_at_univ] at h lemma differentiable_within_at.has_fderiv_within_at (h : differentiable_within_at 𝕜 f s x) : has_fderiv_within_at f (fderiv_within 𝕜 f s x) s x := begin dunfold fderiv_within, dunfold differentiable_within_at at h, rw dif_pos h, exact classical.some_spec h end lemma differentiable_at.has_fderiv_at (h : differentiable_at 𝕜 f x) : has_fderiv_at f (fderiv 𝕜 f x) x := begin dunfold fderiv, dunfold differentiable_at at h, rw dif_pos h, exact classical.some_spec h end lemma has_fderiv_at.fderiv (h : has_fderiv_at f f' x) : fderiv 𝕜 f x = f' := by { ext, rw has_fderiv_at_unique h h.differentiable_at.has_fderiv_at } /-- Converse to the mean value inequality: if `f` is differentiable at `x₀` and `C`-lipschitz on a neighborhood of `x₀` then it its derivative at `x₀` has norm bounded by `C`. Version using `fderiv`. -/ lemma fderiv_at.le_of_lip {f : E → F} {x₀ : E} (hf : differentiable_at 𝕜 f x₀) {s : set E} (hs : s ∈ 𝓝 x₀) {C : ℝ≥0} (hlip : lipschitz_on_with C f s) : ∥fderiv 𝕜 f x₀∥ ≤ C := hf.has_fderiv_at.le_of_lip hs hlip lemma has_fderiv_within_at.fderiv_within (h : has_fderiv_within_at f f' s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = f' := (hxs.eq h h.differentiable_within_at.has_fderiv_within_at).symm /-- If `x` is not in the closure of `s`, then `f` has any derivative at `x` within `s`, as this statement is empty. -/ lemma has_fderiv_within_at_of_not_mem_closure (h : x ∉ closure s) : has_fderiv_within_at f f' s x := begin simp only [mem_closure_iff_nhds_within_ne_bot, ne_bot, ne.def, not_not] at h, simp [has_fderiv_within_at, has_fderiv_at_filter, h, is_o, is_O_with], end lemma differentiable_within_at.mono (h : differentiable_within_at 𝕜 f t x) (st : s ⊆ t) : differentiable_within_at 𝕜 f s x := begin rcases h with ⟨f', hf'⟩, exact ⟨f', hf'.mono st⟩ end lemma differentiable_within_at_univ : differentiable_within_at 𝕜 f univ x ↔ differentiable_at 𝕜 f x := by simp only [differentiable_within_at, has_fderiv_within_at_univ, differentiable_at] lemma differentiable_within_at_inter (ht : t ∈ 𝓝 x) : differentiable_within_at 𝕜 f (s ∩ t) x ↔ differentiable_within_at 𝕜 f s x := by simp only [differentiable_within_at, has_fderiv_within_at, has_fderiv_at_filter, nhds_within_restrict' s ht] lemma differentiable_within_at_inter' (ht : t ∈ 𝓝[s] x) : differentiable_within_at 𝕜 f (s ∩ t) x ↔ differentiable_within_at 𝕜 f s x := by simp only [differentiable_within_at, has_fderiv_within_at, has_fderiv_at_filter, nhds_within_restrict'' s ht] lemma differentiable_at.differentiable_within_at (h : differentiable_at 𝕜 f x) : differentiable_within_at 𝕜 f s x := (differentiable_within_at_univ.2 h).mono (subset_univ _) lemma differentiable.differentiable_at (h : differentiable 𝕜 f) : differentiable_at 𝕜 f x := h x lemma differentiable_within_at.differentiable_at (h : differentiable_within_at 𝕜 f s x) (hs : s ∈ 𝓝 x) : differentiable_at 𝕜 f x := h.imp (λ f' hf', hf'.has_fderiv_at hs) lemma differentiable_at.fderiv_within (h : differentiable_at 𝕜 f x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = fderiv 𝕜 f x := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact h.has_fderiv_at.has_fderiv_within_at end lemma differentiable_on.mono (h : differentiable_on 𝕜 f t) (st : s ⊆ t) : differentiable_on 𝕜 f s := λx hx, (h x (st hx)).mono st lemma differentiable_on_univ : differentiable_on 𝕜 f univ ↔ differentiable 𝕜 f := by { simp [differentiable_on, differentiable_within_at_univ], refl } lemma differentiable.differentiable_on (h : differentiable 𝕜 f) : differentiable_on 𝕜 f s := (differentiable_on_univ.2 h).mono (subset_univ _) lemma differentiable_on_of_locally_differentiable_on (h : ∀x∈s, ∃u, is_open u ∧ x ∈ u ∧ differentiable_on 𝕜 f (s ∩ u)) : differentiable_on 𝕜 f s := begin assume x xs, rcases h x xs with ⟨t, t_open, xt, ht⟩, exact (differentiable_within_at_inter (mem_nhds_sets t_open xt)).1 (ht x ⟨xs, xt⟩) end lemma fderiv_within_subset (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f t x) : fderiv_within 𝕜 f s x = fderiv_within 𝕜 f t x := ((differentiable_within_at.has_fderiv_within_at h).mono st).fderiv_within ht @[simp] lemma fderiv_within_univ : fderiv_within 𝕜 f univ = fderiv 𝕜 f := begin ext x : 1, by_cases h : differentiable_at 𝕜 f x, { apply has_fderiv_within_at.fderiv_within _ unique_diff_within_at_univ, rw has_fderiv_within_at_univ, apply h.has_fderiv_at }, { have : ¬ differentiable_within_at 𝕜 f univ x, by contrapose! h; rwa ← differentiable_within_at_univ, rw [fderiv_zero_of_not_differentiable_at h, fderiv_within_zero_of_not_differentiable_within_at this] } end lemma fderiv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f (s ∩ t) x = fderiv_within 𝕜 f s x := begin by_cases h : differentiable_within_at 𝕜 f (s ∩ t) x, { apply fderiv_within_subset (inter_subset_left _ _) _ ((differentiable_within_at_inter ht).1 h), apply hs.inter ht }, { have : ¬ differentiable_within_at 𝕜 f s x, by contrapose! h; rw differentiable_within_at_inter; assumption, rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at this] } end lemma fderiv_within_of_mem_nhds (h : s ∈ 𝓝 x) : fderiv_within 𝕜 f s x = fderiv 𝕜 f x := begin have : s = univ ∩ s, by simp only [univ_inter], rw [this, ← fderiv_within_univ], exact fderiv_within_inter h (unique_diff_on_univ _ (mem_univ _)) end lemma fderiv_within_of_open (hs : is_open s) (hx : x ∈ s) : fderiv_within 𝕜 f s x = fderiv 𝕜 f x := fderiv_within_of_mem_nhds (mem_nhds_sets hs hx) lemma fderiv_within_eq_fderiv (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_at 𝕜 f x) : fderiv_within 𝕜 f s x = fderiv 𝕜 f x := begin rw ← fderiv_within_univ, exact fderiv_within_subset (subset_univ _) hs h.differentiable_within_at end lemma fderiv_mem_iff {f : E → F} {s : set (E →L[𝕜] F)} {x : E} : fderiv 𝕜 f x ∈ s ↔ (differentiable_at 𝕜 f x ∧ fderiv 𝕜 f x ∈ s) ∨ (0 : E →L[𝕜] F) ∈ s ∧ ¬differentiable_at 𝕜 f x := begin split, { intro hfx, by_cases hx : differentiable_at 𝕜 f x, { exact or.inl ⟨hx, hfx⟩ }, { rw [fderiv_zero_of_not_differentiable_at hx] at hfx, exact or.inr ⟨hfx, hx⟩ } }, { rintro (⟨hf, hf'⟩|⟨h₀, hx⟩), { exact hf' }, { rwa [fderiv_zero_of_not_differentiable_at hx] } } end end fderiv_properties section continuous /-! ### Deducing continuity from differentiability -/ theorem has_fderiv_at_filter.tendsto_nhds (hL : L ≤ 𝓝 x) (h : has_fderiv_at_filter f f' x L) : tendsto f L (𝓝 (f x)) := begin have : tendsto (λ x', f x' - f x) L (𝓝 0), { refine h.is_O_sub.trans_tendsto (tendsto.mono_left _ hL), rw ← sub_self x, exact tendsto_id.sub tendsto_const_nhds }, have := tendsto.add this tendsto_const_nhds, rw zero_add (f x) at this, exact this.congr (by simp) end theorem has_fderiv_within_at.continuous_within_at (h : has_fderiv_within_at f f' s x) : continuous_within_at f s x := has_fderiv_at_filter.tendsto_nhds inf_le_left h theorem has_fderiv_at.continuous_at (h : has_fderiv_at f f' x) : continuous_at f x := has_fderiv_at_filter.tendsto_nhds (le_refl _) h lemma differentiable_within_at.continuous_within_at (h : differentiable_within_at 𝕜 f s x) : continuous_within_at f s x := let ⟨f', hf'⟩ := h in hf'.continuous_within_at lemma differentiable_at.continuous_at (h : differentiable_at 𝕜 f x) : continuous_at f x := let ⟨f', hf'⟩ := h in hf'.continuous_at lemma differentiable_on.continuous_on (h : differentiable_on 𝕜 f s) : continuous_on f s := λx hx, (h x hx).continuous_within_at lemma differentiable.continuous (h : differentiable 𝕜 f) : continuous f := continuous_iff_continuous_at.2 $ λx, (h x).continuous_at protected lemma has_strict_fderiv_at.continuous_at (hf : has_strict_fderiv_at f f' x) : continuous_at f x := hf.has_fderiv_at.continuous_at lemma has_strict_fderiv_at.is_O_sub_rev {f' : E ≃L[𝕜] F} (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) x) : is_O (λ p : E × E, p.1 - p.2) (λ p : E × E, f p.1 - f p.2) (𝓝 (x, x)) := ((f'.is_O_comp_rev _ _).trans (hf.trans_is_O (f'.is_O_comp_rev _ _)).right_is_O_add).congr (λ _, rfl) (λ _, sub_add_cancel _ _) lemma has_fderiv_at_filter.is_O_sub_rev {f' : E ≃L[𝕜] F} (hf : has_fderiv_at_filter f (f' : E →L[𝕜] F) x L) : is_O (λ x', x' - x) (λ x', f x' - f x) L := ((f'.is_O_sub_rev _ _).trans (hf.trans_is_O (f'.is_O_sub_rev _ _)).right_is_O_add).congr (λ _, rfl) (λ _, sub_add_cancel _ _) end continuous section congr /-! ### congr properties of the derivative -/ theorem filter.eventually_eq.has_strict_fderiv_at_iff (h : f₀ =ᶠ[𝓝 x] f₁) (h' : ∀ y, f₀' y = f₁' y) : has_strict_fderiv_at f₀ f₀' x ↔ has_strict_fderiv_at f₁ f₁' x := begin refine is_o_congr ((h.prod_mk_nhds h).mono _) (eventually_of_forall $ λ _, rfl), rintros p ⟨hp₁, hp₂⟩, simp only [*] end theorem has_strict_fderiv_at.congr_of_eventually_eq (h : has_strict_fderiv_at f f' x) (h₁ : f =ᶠ[𝓝 x] f₁) : has_strict_fderiv_at f₁ f' x := (h₁.has_strict_fderiv_at_iff (λ _, rfl)).1 h theorem filter.eventually_eq.has_fderiv_at_filter_iff (h₀ : f₀ =ᶠ[L] f₁) (hx : f₀ x = f₁ x) (h₁ : ∀ x, f₀' x = f₁' x) : has_fderiv_at_filter f₀ f₀' x L ↔ has_fderiv_at_filter f₁ f₁' x L := is_o_congr (h₀.mono $ λ y hy, by simp only [hy, h₁, hx]) (eventually_of_forall $ λ _, rfl) lemma has_fderiv_at_filter.congr_of_eventually_eq (h : has_fderiv_at_filter f f' x L) (hL : f₁ =ᶠ[L] f) (hx : f₁ x = f x) : has_fderiv_at_filter f₁ f' x L := (hL.has_fderiv_at_filter_iff hx $ λ _, rfl).2 h lemma has_fderiv_within_at.congr_mono (h : has_fderiv_within_at f f' s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : has_fderiv_within_at f₁ f' t x := has_fderiv_at_filter.congr_of_eventually_eq (h.mono h₁) (filter.mem_inf_sets_of_right ht) hx lemma has_fderiv_within_at.congr (h : has_fderiv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x := h.congr_mono hs hx (subset.refl _) lemma has_fderiv_within_at.congr_of_eventually_eq (h : has_fderiv_within_at f f' s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x := has_fderiv_at_filter.congr_of_eventually_eq h h₁ hx lemma has_fderiv_at.congr_of_eventually_eq (h : has_fderiv_at f f' x) (h₁ : f₁ =ᶠ[𝓝 x] f) : has_fderiv_at f₁ f' x := has_fderiv_at_filter.congr_of_eventually_eq h h₁ (mem_of_nhds h₁ : _) lemma differentiable_within_at.congr_mono (h : differentiable_within_at 𝕜 f s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : differentiable_within_at 𝕜 f₁ t x := (has_fderiv_within_at.congr_mono h.has_fderiv_within_at ht hx h₁).differentiable_within_at lemma differentiable_within_at.congr (h : differentiable_within_at 𝕜 f s x) (ht : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x := differentiable_within_at.congr_mono h ht hx (subset.refl _) lemma differentiable_within_at.congr_of_eventually_eq (h : differentiable_within_at 𝕜 f s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x := (h.has_fderiv_within_at.congr_of_eventually_eq h₁ hx).differentiable_within_at lemma differentiable_on.congr_mono (h : differentiable_on 𝕜 f s) (h' : ∀x ∈ t, f₁ x = f x) (h₁ : t ⊆ s) : differentiable_on 𝕜 f₁ t := λ x hx, (h x (h₁ hx)).congr_mono h' (h' x hx) h₁ lemma differentiable_on.congr (h : differentiable_on 𝕜 f s) (h' : ∀x ∈ s, f₁ x = f x) : differentiable_on 𝕜 f₁ s := λ x hx, (h x hx).congr h' (h' x hx) lemma differentiable_on_congr (h' : ∀x ∈ s, f₁ x = f x) : differentiable_on 𝕜 f₁ s ↔ differentiable_on 𝕜 f s := ⟨λ h, differentiable_on.congr h (λy hy, (h' y hy).symm), λ h, differentiable_on.congr h h'⟩ lemma differentiable_at.congr_of_eventually_eq (h : differentiable_at 𝕜 f x) (hL : f₁ =ᶠ[𝓝 x] f) : differentiable_at 𝕜 f₁ x := has_fderiv_at.differentiable_at (has_fderiv_at_filter.congr_of_eventually_eq h.has_fderiv_at hL (mem_of_nhds hL : _)) lemma differentiable_within_at.fderiv_within_congr_mono (h : differentiable_within_at 𝕜 f s x) (hs : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (hxt : unique_diff_within_at 𝕜 t x) (h₁ : t ⊆ s) : fderiv_within 𝕜 f₁ t x = fderiv_within 𝕜 f s x := (has_fderiv_within_at.congr_mono h.has_fderiv_within_at hs hx h₁).fderiv_within hxt lemma filter.eventually_eq.fderiv_within_eq (hs : unique_diff_within_at 𝕜 s x) (hL : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x := if h : differentiable_within_at 𝕜 f s x then has_fderiv_within_at.fderiv_within (h.has_fderiv_within_at.congr_of_eventually_eq hL hx) hs else have h' : ¬ differentiable_within_at 𝕜 f₁ s x, from mt (λ h, h.congr_of_eventually_eq (hL.mono $ λ x, eq.symm) hx.symm) h, by rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at h'] lemma fderiv_within_congr (hs : unique_diff_within_at 𝕜 s x) (hL : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) : fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x := begin apply filter.eventually_eq.fderiv_within_eq hs _ hx, apply mem_sets_of_superset self_mem_nhds_within, exact hL end lemma filter.eventually_eq.fderiv_eq (hL : f₁ =ᶠ[𝓝 x] f) : fderiv 𝕜 f₁ x = fderiv 𝕜 f x := begin have A : f₁ x = f x := hL.eq_of_nhds, rw [← fderiv_within_univ, ← fderiv_within_univ], rw ← nhds_within_univ at hL, exact hL.fderiv_within_eq unique_diff_within_at_univ A end end congr section id /-! ### Derivative of the identity -/ theorem has_strict_fderiv_at_id (x : E) : has_strict_fderiv_at id (id 𝕜 E) x := (is_o_zero _ _).congr_left $ by simp theorem has_fderiv_at_filter_id (x : E) (L : filter E) : has_fderiv_at_filter id (id 𝕜 E) x L := (is_o_zero _ _).congr_left $ by simp theorem has_fderiv_within_at_id (x : E) (s : set E) : has_fderiv_within_at id (id 𝕜 E) s x := has_fderiv_at_filter_id _ _ theorem has_fderiv_at_id (x : E) : has_fderiv_at id (id 𝕜 E) x := has_fderiv_at_filter_id _ _ @[simp] lemma differentiable_at_id : differentiable_at 𝕜 id x := (has_fderiv_at_id x).differentiable_at @[simp] lemma differentiable_at_id' : differentiable_at 𝕜 (λ x, x) x := (has_fderiv_at_id x).differentiable_at lemma differentiable_within_at_id : differentiable_within_at 𝕜 id s x := differentiable_at_id.differentiable_within_at @[simp] lemma differentiable_id : differentiable 𝕜 (id : E → E) := λx, differentiable_at_id @[simp] lemma differentiable_id' : differentiable 𝕜 (λ (x : E), x) := λx, differentiable_at_id lemma differentiable_on_id : differentiable_on 𝕜 id s := differentiable_id.differentiable_on lemma fderiv_id : fderiv 𝕜 id x = id 𝕜 E := has_fderiv_at.fderiv (has_fderiv_at_id x) @[simp] lemma fderiv_id' : fderiv 𝕜 (λ (x : E), x) x = continuous_linear_map.id 𝕜 E := fderiv_id lemma fderiv_within_id (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 id s x = id 𝕜 E := begin rw differentiable_at.fderiv_within (differentiable_at_id) hxs, exact fderiv_id end lemma fderiv_within_id' (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λ (x : E), x) s x = continuous_linear_map.id 𝕜 E := fderiv_within_id hxs end id section const /-! ### derivative of a constant function -/ theorem has_strict_fderiv_at_const (c : F) (x : E) : has_strict_fderiv_at (λ _, c) (0 : E →L[𝕜] F) x := (is_o_zero _ _).congr_left $ λ _, by simp only [zero_apply, sub_self] theorem has_fderiv_at_filter_const (c : F) (x : E) (L : filter E) : has_fderiv_at_filter (λ x, c) (0 : E →L[𝕜] F) x L := (is_o_zero _ _).congr_left $ λ _, by simp only [zero_apply, sub_self] theorem has_fderiv_within_at_const (c : F) (x : E) (s : set E) : has_fderiv_within_at (λ x, c) (0 : E →L[𝕜] F) s x := has_fderiv_at_filter_const _ _ _ theorem has_fderiv_at_const (c : F) (x : E) : has_fderiv_at (λ x, c) (0 : E →L[𝕜] F) x := has_fderiv_at_filter_const _ _ _ @[simp] lemma differentiable_at_const (c : F) : differentiable_at 𝕜 (λx, c) x := ⟨0, has_fderiv_at_const c x⟩ lemma differentiable_within_at_const (c : F) : differentiable_within_at 𝕜 (λx, c) s x := differentiable_at.differentiable_within_at (differentiable_at_const _) lemma fderiv_const_apply (c : F) : fderiv 𝕜 (λy, c) x = 0 := has_fderiv_at.fderiv (has_fderiv_at_const c x) @[simp] lemma fderiv_const (c : F) : fderiv 𝕜 (λ (y : E), c) = 0 := by { ext m, rw fderiv_const_apply, refl } lemma fderiv_within_const_apply (c : F) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λy, c) s x = 0 := begin rw differentiable_at.fderiv_within (differentiable_at_const _) hxs, exact fderiv_const_apply _ end @[simp] lemma differentiable_const (c : F) : differentiable 𝕜 (λx : E, c) := λx, differentiable_at_const _ lemma differentiable_on_const (c : F) : differentiable_on 𝕜 (λx, c) s := (differentiable_const _).differentiable_on end const section continuous_linear_map /-! ### Continuous linear maps There are currently two variants of these in mathlib, the bundled version (named `continuous_linear_map`, and denoted `E →L[𝕜] F`), and the unbundled version (with a predicate `is_bounded_linear_map`). We give statements for both versions. -/ protected theorem continuous_linear_map.has_strict_fderiv_at {x : E} : has_strict_fderiv_at e e x := (is_o_zero _ _).congr_left $ λ x, by simp only [e.map_sub, sub_self] protected lemma continuous_linear_map.has_fderiv_at_filter : has_fderiv_at_filter e e x L := (is_o_zero _ _).congr_left $ λ x, by simp only [e.map_sub, sub_self] protected lemma continuous_linear_map.has_fderiv_within_at : has_fderiv_within_at e e s x := e.has_fderiv_at_filter protected lemma continuous_linear_map.has_fderiv_at : has_fderiv_at e e x := e.has_fderiv_at_filter @[simp] protected lemma continuous_linear_map.differentiable_at : differentiable_at 𝕜 e x := e.has_fderiv_at.differentiable_at protected lemma continuous_linear_map.differentiable_within_at : differentiable_within_at 𝕜 e s x := e.differentiable_at.differentiable_within_at @[simp] protected lemma continuous_linear_map.fderiv : fderiv 𝕜 e x = e := e.has_fderiv_at.fderiv protected lemma continuous_linear_map.fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 e s x = e := begin rw differentiable_at.fderiv_within e.differentiable_at hxs, exact e.fderiv end @[simp] protected lemma continuous_linear_map.differentiable : differentiable 𝕜 e := λx, e.differentiable_at protected lemma continuous_linear_map.differentiable_on : differentiable_on 𝕜 e s := e.differentiable.differentiable_on lemma is_bounded_linear_map.has_fderiv_at_filter (h : is_bounded_linear_map 𝕜 f) : has_fderiv_at_filter f h.to_continuous_linear_map x L := h.to_continuous_linear_map.has_fderiv_at_filter lemma is_bounded_linear_map.has_fderiv_within_at (h : is_bounded_linear_map 𝕜 f) : has_fderiv_within_at f h.to_continuous_linear_map s x := h.has_fderiv_at_filter lemma is_bounded_linear_map.has_fderiv_at (h : is_bounded_linear_map 𝕜 f) : has_fderiv_at f h.to_continuous_linear_map x := h.has_fderiv_at_filter lemma is_bounded_linear_map.differentiable_at (h : is_bounded_linear_map 𝕜 f) : differentiable_at 𝕜 f x := h.has_fderiv_at.differentiable_at lemma is_bounded_linear_map.differentiable_within_at (h : is_bounded_linear_map 𝕜 f) : differentiable_within_at 𝕜 f s x := h.differentiable_at.differentiable_within_at lemma is_bounded_linear_map.fderiv (h : is_bounded_linear_map 𝕜 f) : fderiv 𝕜 f x = h.to_continuous_linear_map := has_fderiv_at.fderiv (h.has_fderiv_at) lemma is_bounded_linear_map.fderiv_within (h : is_bounded_linear_map 𝕜 f) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = h.to_continuous_linear_map := begin rw differentiable_at.fderiv_within h.differentiable_at hxs, exact h.fderiv end lemma is_bounded_linear_map.differentiable (h : is_bounded_linear_map 𝕜 f) : differentiable 𝕜 f := λx, h.differentiable_at lemma is_bounded_linear_map.differentiable_on (h : is_bounded_linear_map 𝕜 f) : differentiable_on 𝕜 f s := h.differentiable.differentiable_on end continuous_linear_map section composition /-! ### Derivative of the composition of two functions For composition lemmas, we put x explicit to help the elaborator, as otherwise Lean tends to get confused since there are too many possibilities for composition -/ variable (x) theorem has_fderiv_at_filter.comp {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at_filter g g' (f x) (L.map f)) (hf : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (g ∘ f) (g'.comp f') x L := let eq₁ := (g'.is_O_comp _ _).trans_is_o hf in let eq₂ := (hg.comp_tendsto tendsto_map).trans_is_O hf.is_O_sub in by { refine eq₂.triangle (eq₁.congr_left (λ x', _)), simp } /- A readable version of the previous theorem, a general form of the chain rule. -/ example {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at_filter g g' (f x) (L.map f)) (hf : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (g ∘ f) (g'.comp f') x L := begin unfold has_fderiv_at_filter at hg, have : is_o (λ x', g (f x') - g (f x) - g' (f x' - f x)) (λ x', f x' - f x) L, from hg.comp_tendsto (le_refl _), have eq₁ : is_o (λ x', g (f x') - g (f x) - g' (f x' - f x)) (λ x', x' - x) L, from this.trans_is_O hf.is_O_sub, have eq₂ : is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L, from hf, have : is_O (λ x', g' (f x' - f x - f' (x' - x))) (λ x', f x' - f x - f' (x' - x)) L, from g'.is_O_comp _ _, have : is_o (λ x', g' (f x' - f x - f' (x' - x))) (λ x', x' - x) L, from this.trans_is_o eq₂, have eq₃ : is_o (λ x', g' (f x' - f x) - (g' (f' (x' - x)))) (λ x', x' - x) L, by { refine this.congr_left _, simp}, exact eq₁.triangle eq₃ end theorem has_fderiv_within_at.comp {g : F → G} {g' : F →L[𝕜] G} {t : set F} (hg : has_fderiv_within_at g g' t (f x)) (hf : has_fderiv_within_at f f' s x) (hst : s ⊆ f ⁻¹' t) : has_fderiv_within_at (g ∘ f) (g'.comp f') s x := begin apply has_fderiv_at_filter.comp _ (has_fderiv_at_filter.mono hg _) hf, calc map f (𝓝[s] x) ≤ 𝓝[f '' s] (f x) : hf.continuous_within_at.tendsto_nhds_within_image ... ≤ 𝓝[t] (f x) : nhds_within_mono _ (image_subset_iff.mpr hst) end /-- The chain rule. -/ theorem has_fderiv_at.comp {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_at f f' x) : has_fderiv_at (g ∘ f) (g'.comp f') x := (hg.mono hf.continuous_at).comp x hf theorem has_fderiv_at.comp_has_fderiv_within_at {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (g ∘ f) (g'.comp f') s x := begin rw ← has_fderiv_within_at_univ at hg, exact has_fderiv_within_at.comp x hg hf subset_preimage_univ end lemma differentiable_within_at.comp {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) (h : s ⊆ f ⁻¹' t) : differentiable_within_at 𝕜 (g ∘ f) s x := begin rcases hf with ⟨f', hf'⟩, rcases hg with ⟨g', hg'⟩, exact ⟨continuous_linear_map.comp g' f', hg'.comp x hf' h⟩ end lemma differentiable_within_at.comp' {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (g ∘ f) (s ∩ f⁻¹' t) x := hg.comp x (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _) lemma differentiable_at.comp {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (g ∘ f) x := (hg.has_fderiv_at.comp x hf.has_fderiv_at).differentiable_at lemma differentiable_at.comp_differentiable_within_at {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (g ∘ f) s x := (differentiable_within_at_univ.2 hg).comp x hf (by simp) lemma fderiv_within.comp {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) (h : maps_to f s t) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (g ∘ f) s x = (fderiv_within 𝕜 g t (f x)).comp (fderiv_within 𝕜 f s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_within_at.comp x (hg.has_fderiv_within_at) (hf.has_fderiv_within_at) h end lemma fderiv.comp {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_at 𝕜 f x) : fderiv 𝕜 (g ∘ f) x = (fderiv 𝕜 g (f x)).comp (fderiv 𝕜 f x) := begin apply has_fderiv_at.fderiv, exact has_fderiv_at.comp x hg.has_fderiv_at hf.has_fderiv_at end lemma fderiv.comp_fderiv_within {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_within_at 𝕜 f s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (g ∘ f) s x = (fderiv 𝕜 g (f x)).comp (fderiv_within 𝕜 f s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_at.comp_has_fderiv_within_at x (hg.has_fderiv_at) (hf.has_fderiv_within_at) end lemma differentiable_on.comp {g : F → G} {t : set F} (hg : differentiable_on 𝕜 g t) (hf : differentiable_on 𝕜 f s) (st : s ⊆ f ⁻¹' t) : differentiable_on 𝕜 (g ∘ f) s := λx hx, differentiable_within_at.comp x (hg (f x) (st hx)) (hf x hx) st lemma differentiable.comp {g : F → G} (hg : differentiable 𝕜 g) (hf : differentiable 𝕜 f) : differentiable 𝕜 (g ∘ f) := λx, differentiable_at.comp x (hg (f x)) (hf x) lemma differentiable.comp_differentiable_on {g : F → G} (hg : differentiable 𝕜 g) (hf : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (g ∘ f) s := (differentiable_on_univ.2 hg).comp hf (by simp) /-- The chain rule for derivatives in the sense of strict differentiability. -/ protected lemma has_strict_fderiv_at.comp {g : F → G} {g' : F →L[𝕜] G} (hg : has_strict_fderiv_at g g' (f x)) (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, g (f x)) (g'.comp f') x := ((hg.comp_tendsto (hf.continuous_at.prod_map' hf.continuous_at)).trans_is_O hf.is_O_sub).triangle $ by simpa only [g'.map_sub, f'.coe_comp'] using (g'.is_O_comp _ _).trans_is_o hf protected lemma differentiable.iterate {f : E → E} (hf : differentiable 𝕜 f) (n : ℕ) : differentiable 𝕜 (f^[n]) := nat.rec_on n differentiable_id (λ n ihn, ihn.comp hf) protected lemma differentiable_on.iterate {f : E → E} (hf : differentiable_on 𝕜 f s) (hs : maps_to f s s) (n : ℕ) : differentiable_on 𝕜 (f^[n]) s := nat.rec_on n differentiable_on_id (λ n ihn, ihn.comp hf hs) variable {x} protected lemma has_fderiv_at_filter.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_fderiv_at_filter f f' x L) (hL : tendsto f L L) (hx : f x = x) (n : ℕ) : has_fderiv_at_filter (f^[n]) (f'^n) x L := begin induction n with n ihn, { exact has_fderiv_at_filter_id x L }, { change has_fderiv_at_filter (f^[n] ∘ f) (f'^(n+1)) x L, rw [pow_succ'], refine has_fderiv_at_filter.comp x _ hf, rw hx, exact ihn.mono hL } end protected lemma has_fderiv_at.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_fderiv_at f f' x) (hx : f x = x) (n : ℕ) : has_fderiv_at (f^[n]) (f'^n) x := begin refine hf.iterate _ hx n, convert hf.continuous_at, exact hx.symm end protected lemma has_fderiv_within_at.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_fderiv_within_at f f' s x) (hx : f x = x) (hs : maps_to f s s) (n : ℕ) : has_fderiv_within_at (f^[n]) (f'^n) s x := begin refine hf.iterate _ hx n, convert tendsto_inf.2 ⟨hf.continuous_within_at, _⟩, exacts [hx.symm, (tendsto_principal_principal.2 hs).mono_left inf_le_right] end protected lemma has_strict_fderiv_at.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_strict_fderiv_at f f' x) (hx : f x = x) (n : ℕ) : has_strict_fderiv_at (f^[n]) (f'^n) x := begin induction n with n ihn, { exact has_strict_fderiv_at_id x }, { change has_strict_fderiv_at (f^[n] ∘ f) (f'^(n+1)) x, rw [pow_succ'], refine has_strict_fderiv_at.comp x _ hf, rwa hx } end protected lemma differentiable_at.iterate {f : E → E} (hf : differentiable_at 𝕜 f x) (hx : f x = x) (n : ℕ) : differentiable_at 𝕜 (f^[n]) x := exists.elim hf $ λ f' hf, (hf.iterate hx n).differentiable_at protected lemma differentiable_within_at.iterate {f : E → E} (hf : differentiable_within_at 𝕜 f s x) (hx : f x = x) (hs : maps_to f s s) (n : ℕ) : differentiable_within_at 𝕜 (f^[n]) s x := exists.elim hf $ λ f' hf, (hf.iterate hx hs n).differentiable_within_at end composition section cartesian_product /-! ### Derivative of the cartesian product of two functions -/ section prod variables {f₂ : E → G} {f₂' : E →L[𝕜] G} protected lemma has_strict_fderiv_at.prod (hf₁ : has_strict_fderiv_at f₁ f₁' x) (hf₂ : has_strict_fderiv_at f₂ f₂' x) : has_strict_fderiv_at (λx, (f₁ x, f₂ x)) (f₁'.prod f₂') x := hf₁.prod_left hf₂ lemma has_fderiv_at_filter.prod (hf₁ : has_fderiv_at_filter f₁ f₁' x L) (hf₂ : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λx, (f₁ x, f₂ x)) (f₁'.prod f₂') x L := hf₁.prod_left hf₂ lemma has_fderiv_within_at.prod (hf₁ : has_fderiv_within_at f₁ f₁' s x) (hf₂ : has_fderiv_within_at f₂ f₂' s x) : has_fderiv_within_at (λx, (f₁ x, f₂ x)) (f₁'.prod f₂') s x := hf₁.prod hf₂ lemma has_fderiv_at.prod (hf₁ : has_fderiv_at f₁ f₁' x) (hf₂ : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') x := hf₁.prod hf₂ lemma differentiable_within_at.prod (hf₁ : differentiable_within_at 𝕜 f₁ s x) (hf₂ : differentiable_within_at 𝕜 f₂ s x) : differentiable_within_at 𝕜 (λx:E, (f₁ x, f₂ x)) s x := (hf₁.has_fderiv_within_at.prod hf₂.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.prod (hf₁ : differentiable_at 𝕜 f₁ x) (hf₂ : differentiable_at 𝕜 f₂ x) : differentiable_at 𝕜 (λx:E, (f₁ x, f₂ x)) x := (hf₁.has_fderiv_at.prod hf₂.has_fderiv_at).differentiable_at lemma differentiable_on.prod (hf₁ : differentiable_on 𝕜 f₁ s) (hf₂ : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λx:E, (f₁ x, f₂ x)) s := λx hx, differentiable_within_at.prod (hf₁ x hx) (hf₂ x hx) @[simp] lemma differentiable.prod (hf₁ : differentiable 𝕜 f₁) (hf₂ : differentiable 𝕜 f₂) : differentiable 𝕜 (λx:E, (f₁ x, f₂ x)) := λ x, differentiable_at.prod (hf₁ x) (hf₂ x) lemma differentiable_at.fderiv_prod (hf₁ : differentiable_at 𝕜 f₁ x) (hf₂ : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λx:E, (f₁ x, f₂ x)) x = (fderiv 𝕜 f₁ x).prod (fderiv 𝕜 f₂ x) := (hf₁.has_fderiv_at.prod hf₂.has_fderiv_at).fderiv lemma differentiable_at.fderiv_within_prod (hf₁ : differentiable_within_at 𝕜 f₁ s x) (hf₂ : differentiable_within_at 𝕜 f₂ s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx:E, (f₁ x, f₂ x)) s x = (fderiv_within 𝕜 f₁ s x).prod (fderiv_within 𝕜 f₂ s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_within_at.prod hf₁.has_fderiv_within_at hf₂.has_fderiv_within_at end end prod section fst variables {f₂ : E → F × G} {f₂' : E →L[𝕜] F × G} {p : E × F} lemma has_strict_fderiv_at_fst : has_strict_fderiv_at prod.fst (fst 𝕜 E F) p := (fst 𝕜 E F).has_strict_fderiv_at protected lemma has_strict_fderiv_at.fst (h : has_strict_fderiv_at f₂ f₂' x) : has_strict_fderiv_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x := has_strict_fderiv_at_fst.comp x h lemma has_fderiv_at_filter_fst {L : filter (E × F)} : has_fderiv_at_filter prod.fst (fst 𝕜 E F) p L := (fst 𝕜 E F).has_fderiv_at_filter protected lemma has_fderiv_at_filter.fst (h : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x L := has_fderiv_at_filter_fst.comp x h lemma has_fderiv_at_fst : has_fderiv_at prod.fst (fst 𝕜 E F) p := has_fderiv_at_filter_fst protected lemma has_fderiv_at.fst (h : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x := h.fst lemma has_fderiv_within_at_fst {s : set (E × F)} : has_fderiv_within_at prod.fst (fst 𝕜 E F) s p := has_fderiv_at_filter_fst protected lemma has_fderiv_within_at.fst (h : has_fderiv_within_at f₂ f₂' s x) : has_fderiv_within_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') s x := h.fst lemma differentiable_at_fst : differentiable_at 𝕜 prod.fst p := has_fderiv_at_fst.differentiable_at @[simp] protected lemma differentiable_at.fst (h : differentiable_at 𝕜 f₂ x) : differentiable_at 𝕜 (λ x, (f₂ x).1) x := differentiable_at_fst.comp x h lemma differentiable_fst : differentiable 𝕜 (prod.fst : E × F → E) := λ x, differentiable_at_fst @[simp] protected lemma differentiable.fst (h : differentiable 𝕜 f₂) : differentiable 𝕜 (λ x, (f₂ x).1) := differentiable_fst.comp h lemma differentiable_within_at_fst {s : set (E × F)} : differentiable_within_at 𝕜 prod.fst s p := differentiable_at_fst.differentiable_within_at protected lemma differentiable_within_at.fst (h : differentiable_within_at 𝕜 f₂ s x) : differentiable_within_at 𝕜 (λ x, (f₂ x).1) s x := differentiable_at_fst.comp_differentiable_within_at x h lemma differentiable_on_fst {s : set (E × F)} : differentiable_on 𝕜 prod.fst s := differentiable_fst.differentiable_on protected lemma differentiable_on.fst (h : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λ x, (f₂ x).1) s := differentiable_fst.comp_differentiable_on h lemma fderiv_fst : fderiv 𝕜 prod.fst p = fst 𝕜 E F := has_fderiv_at_fst.fderiv lemma fderiv.fst (h : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λ x, (f₂ x).1) x = (fst 𝕜 F G).comp (fderiv 𝕜 f₂ x) := h.has_fderiv_at.fst.fderiv lemma fderiv_within_fst {s : set (E × F)} (hs : unique_diff_within_at 𝕜 s p) : fderiv_within 𝕜 prod.fst s p = fst 𝕜 E F := has_fderiv_within_at_fst.fderiv_within hs lemma fderiv_within.fst (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f₂ s x) : fderiv_within 𝕜 (λ x, (f₂ x).1) s x = (fst 𝕜 F G).comp (fderiv_within 𝕜 f₂ s x) := h.has_fderiv_within_at.fst.fderiv_within hs end fst section snd variables {f₂ : E → F × G} {f₂' : E →L[𝕜] F × G} {p : E × F} lemma has_strict_fderiv_at_snd : has_strict_fderiv_at prod.snd (snd 𝕜 E F) p := (snd 𝕜 E F).has_strict_fderiv_at protected lemma has_strict_fderiv_at.snd (h : has_strict_fderiv_at f₂ f₂' x) : has_strict_fderiv_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x := has_strict_fderiv_at_snd.comp x h lemma has_fderiv_at_filter_snd {L : filter (E × F)} : has_fderiv_at_filter prod.snd (snd 𝕜 E F) p L := (snd 𝕜 E F).has_fderiv_at_filter protected lemma has_fderiv_at_filter.snd (h : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x L := has_fderiv_at_filter_snd.comp x h lemma has_fderiv_at_snd : has_fderiv_at prod.snd (snd 𝕜 E F) p := has_fderiv_at_filter_snd protected lemma has_fderiv_at.snd (h : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x := h.snd lemma has_fderiv_within_at_snd {s : set (E × F)} : has_fderiv_within_at prod.snd (snd 𝕜 E F) s p := has_fderiv_at_filter_snd protected lemma has_fderiv_within_at.snd (h : has_fderiv_within_at f₂ f₂' s x) : has_fderiv_within_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') s x := h.snd lemma differentiable_at_snd : differentiable_at 𝕜 prod.snd p := has_fderiv_at_snd.differentiable_at @[simp] protected lemma differentiable_at.snd (h : differentiable_at 𝕜 f₂ x) : differentiable_at 𝕜 (λ x, (f₂ x).2) x := differentiable_at_snd.comp x h lemma differentiable_snd : differentiable 𝕜 (prod.snd : E × F → F) := λ x, differentiable_at_snd @[simp] protected lemma differentiable.snd (h : differentiable 𝕜 f₂) : differentiable 𝕜 (λ x, (f₂ x).2) := differentiable_snd.comp h lemma differentiable_within_at_snd {s : set (E × F)} : differentiable_within_at 𝕜 prod.snd s p := differentiable_at_snd.differentiable_within_at protected lemma differentiable_within_at.snd (h : differentiable_within_at 𝕜 f₂ s x) : differentiable_within_at 𝕜 (λ x, (f₂ x).2) s x := differentiable_at_snd.comp_differentiable_within_at x h lemma differentiable_on_snd {s : set (E × F)} : differentiable_on 𝕜 prod.snd s := differentiable_snd.differentiable_on protected lemma differentiable_on.snd (h : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λ x, (f₂ x).2) s := differentiable_snd.comp_differentiable_on h lemma fderiv_snd : fderiv 𝕜 prod.snd p = snd 𝕜 E F := has_fderiv_at_snd.fderiv lemma fderiv.snd (h : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λ x, (f₂ x).2) x = (snd 𝕜 F G).comp (fderiv 𝕜 f₂ x) := h.has_fderiv_at.snd.fderiv lemma fderiv_within_snd {s : set (E × F)} (hs : unique_diff_within_at 𝕜 s p) : fderiv_within 𝕜 prod.snd s p = snd 𝕜 E F := has_fderiv_within_at_snd.fderiv_within hs lemma fderiv_within.snd (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f₂ s x) : fderiv_within 𝕜 (λ x, (f₂ x).2) s x = (snd 𝕜 F G).comp (fderiv_within 𝕜 f₂ s x) := h.has_fderiv_within_at.snd.fderiv_within hs end snd section prod_map variables {f₂ : G → G'} {f₂' : G →L[𝕜] G'} {y : G} (p : E × G) -- TODO (Lean 3.8): use `prod.map f f₂`` protected theorem has_strict_fderiv_at.prod_map (hf : has_strict_fderiv_at f f' p.1) (hf₂ : has_strict_fderiv_at f₂ f₂' p.2) : has_strict_fderiv_at (λ p : E × G, (f p.1, f₂ p.2)) (f'.prod_map f₂') p := (hf.comp p has_strict_fderiv_at_fst).prod (hf₂.comp p has_strict_fderiv_at_snd) protected theorem has_fderiv_at.prod_map (hf : has_fderiv_at f f' p.1) (hf₂ : has_fderiv_at f₂ f₂' p.2) : has_fderiv_at (λ p : E × G, (f p.1, f₂ p.2)) (f'.prod_map f₂') p := (hf.comp p has_fderiv_at_fst).prod (hf₂.comp p has_fderiv_at_snd) @[simp] protected theorem differentiable_at.prod_map (hf : differentiable_at 𝕜 f p.1) (hf₂ : differentiable_at 𝕜 f₂ p.2) : differentiable_at 𝕜 (λ p : E × G, (f p.1, f₂ p.2)) p := (hf.comp p differentiable_at_fst).prod (hf₂.comp p differentiable_at_snd) end prod_map end cartesian_product section const_smul /-! ### Derivative of a function multiplied by a constant -/ theorem has_strict_fderiv_at.const_smul (h : has_strict_fderiv_at f f' x) (c : 𝕜) : has_strict_fderiv_at (λ x, c • f x) (c • f') x := (c • (1 : F →L[𝕜] F)).has_strict_fderiv_at.comp x h theorem has_fderiv_at_filter.const_smul (h : has_fderiv_at_filter f f' x L) (c : 𝕜) : has_fderiv_at_filter (λ x, c • f x) (c • f') x L := (c • (1 : F →L[𝕜] F)).has_fderiv_at_filter.comp x h theorem has_fderiv_within_at.const_smul (h : has_fderiv_within_at f f' s x) (c : 𝕜) : has_fderiv_within_at (λ x, c • f x) (c • f') s x := h.const_smul c theorem has_fderiv_at.const_smul (h : has_fderiv_at f f' x) (c : 𝕜) : has_fderiv_at (λ x, c • f x) (c • f') x := h.const_smul c lemma differentiable_within_at.const_smul (h : differentiable_within_at 𝕜 f s x) (c : 𝕜) : differentiable_within_at 𝕜 (λy, c • f y) s x := (h.has_fderiv_within_at.const_smul c).differentiable_within_at lemma differentiable_at.const_smul (h : differentiable_at 𝕜 f x) (c : 𝕜) : differentiable_at 𝕜 (λy, c • f y) x := (h.has_fderiv_at.const_smul c).differentiable_at lemma differentiable_on.const_smul (h : differentiable_on 𝕜 f s) (c : 𝕜) : differentiable_on 𝕜 (λy, c • f y) s := λx hx, (h x hx).const_smul c lemma differentiable.const_smul (h : differentiable 𝕜 f) (c : 𝕜) : differentiable 𝕜 (λy, c • f y) := λx, (h x).const_smul c lemma fderiv_within_const_smul (hxs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f s x) (c : 𝕜) : fderiv_within 𝕜 (λy, c • f y) s x = c • fderiv_within 𝕜 f s x := (h.has_fderiv_within_at.const_smul c).fderiv_within hxs lemma fderiv_const_smul (h : differentiable_at 𝕜 f x) (c : 𝕜) : fderiv 𝕜 (λy, c • f y) x = c • fderiv 𝕜 f x := (h.has_fderiv_at.const_smul c).fderiv end const_smul section add /-! ### Derivative of the sum of two functions -/ theorem has_strict_fderiv_at.add (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) : has_strict_fderiv_at (λ y, f y + g y) (f' + g') x := (hf.add hg).congr_left $ λ y, by simp; abel theorem has_fderiv_at_filter.add (hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) : has_fderiv_at_filter (λ y, f y + g y) (f' + g') x L := (hf.add hg).congr_left $ λ _, by simp; abel theorem has_fderiv_within_at.add (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) : has_fderiv_within_at (λ y, f y + g y) (f' + g') s x := hf.add hg theorem has_fderiv_at.add (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) : has_fderiv_at (λ x, f x + g x) (f' + g') x := hf.add hg lemma differentiable_within_at.add (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : differentiable_within_at 𝕜 (λ y, f y + g y) s x := (hf.has_fderiv_within_at.add hg.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : differentiable_at 𝕜 (λ y, f y + g y) x := (hf.has_fderiv_at.add hg.has_fderiv_at).differentiable_at lemma differentiable_on.add (hf : differentiable_on 𝕜 f s) (hg : differentiable_on 𝕜 g s) : differentiable_on 𝕜 (λy, f y + g y) s := λx hx, (hf x hx).add (hg x hx) @[simp] lemma differentiable.add (hf : differentiable 𝕜 f) (hg : differentiable 𝕜 g) : differentiable 𝕜 (λy, f y + g y) := λx, (hf x).add (hg x) lemma fderiv_within_add (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : fderiv_within 𝕜 (λy, f y + g y) s x = fderiv_within 𝕜 f s x + fderiv_within 𝕜 g s x := (hf.has_fderiv_within_at.add hg.has_fderiv_within_at).fderiv_within hxs lemma fderiv_add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : fderiv 𝕜 (λy, f y + g y) x = fderiv 𝕜 f x + fderiv 𝕜 g x := (hf.has_fderiv_at.add hg.has_fderiv_at).fderiv theorem has_strict_fderiv_at.add_const (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ y, f y + c) f' x := add_zero f' ▸ hf.add (has_strict_fderiv_at_const _ _) theorem has_fderiv_at_filter.add_const (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ y, f y + c) f' x L := add_zero f' ▸ hf.add (has_fderiv_at_filter_const _ _ _) theorem has_fderiv_within_at.add_const (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ y, f y + c) f' s x := hf.add_const c theorem has_fderiv_at.add_const (hf : has_fderiv_at f f' x) (c : F): has_fderiv_at (λ x, f x + c) f' x := hf.add_const c lemma differentiable_within_at.add_const (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, f y + c) s x := (hf.has_fderiv_within_at.add_const c).differentiable_within_at @[simp] lemma differentiable_within_at_add_const_iff (c : F) : differentiable_within_at 𝕜 (λ y, f y + c) s x ↔ differentiable_within_at 𝕜 f s x := ⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩ lemma differentiable_at.add_const (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, f y + c) x := (hf.has_fderiv_at.add_const c).differentiable_at @[simp] lemma differentiable_at_add_const_iff (c : F) : differentiable_at 𝕜 (λ y, f y + c) x ↔ differentiable_at 𝕜 f x := ⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩ lemma differentiable_on.add_const (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, f y + c) s := λx hx, (hf x hx).add_const c @[simp] lemma differentiable_on_add_const_iff (c : F) : differentiable_on 𝕜 (λ y, f y + c) s ↔ differentiable_on 𝕜 f s := ⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩ lemma differentiable.add_const (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, f y + c) := λx, (hf x).add_const c @[simp] lemma differentiable_add_const_iff (c : F) : differentiable 𝕜 (λ y, f y + c) ↔ differentiable 𝕜 f := ⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩ lemma fderiv_within_add_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) : fderiv_within 𝕜 (λy, f y + c) s x = fderiv_within 𝕜 f s x := if hf : differentiable_within_at 𝕜 f s x then (hf.has_fderiv_within_at.add_const c).fderiv_within hxs else by { rw [fderiv_within_zero_of_not_differentiable_within_at hf, fderiv_within_zero_of_not_differentiable_within_at], simpa } lemma fderiv_add_const (c : F) : fderiv 𝕜 (λy, f y + c) x = fderiv 𝕜 f x := by simp only [← fderiv_within_univ, fderiv_within_add_const unique_diff_within_at_univ] theorem has_strict_fderiv_at.const_add (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ y, c + f y) f' x := zero_add f' ▸ (has_strict_fderiv_at_const _ _).add hf theorem has_fderiv_at_filter.const_add (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ y, c + f y) f' x L := zero_add f' ▸ (has_fderiv_at_filter_const _ _ _).add hf theorem has_fderiv_within_at.const_add (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ y, c + f y) f' s x := hf.const_add c theorem has_fderiv_at.const_add (hf : has_fderiv_at f f' x) (c : F): has_fderiv_at (λ x, c + f x) f' x := hf.const_add c lemma differentiable_within_at.const_add (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, c + f y) s x := (hf.has_fderiv_within_at.const_add c).differentiable_within_at @[simp] lemma differentiable_within_at_const_add_iff (c : F) : differentiable_within_at 𝕜 (λ y, c + f y) s x ↔ differentiable_within_at 𝕜 f s x := ⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩ lemma differentiable_at.const_add (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, c + f y) x := (hf.has_fderiv_at.const_add c).differentiable_at @[simp] lemma differentiable_at_const_add_iff (c : F) : differentiable_at 𝕜 (λ y, c + f y) x ↔ differentiable_at 𝕜 f x := ⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩ lemma differentiable_on.const_add (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, c + f y) s := λx hx, (hf x hx).const_add c @[simp] lemma differentiable_on_const_add_iff (c : F) : differentiable_on 𝕜 (λ y, c + f y) s ↔ differentiable_on 𝕜 f s := ⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩ lemma differentiable.const_add (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, c + f y) := λx, (hf x).const_add c @[simp] lemma differentiable_const_add_iff (c : F) : differentiable 𝕜 (λ y, c + f y) ↔ differentiable 𝕜 f := ⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩ lemma fderiv_within_const_add (hxs : unique_diff_within_at 𝕜 s x) (c : F) : fderiv_within 𝕜 (λy, c + f y) s x = fderiv_within 𝕜 f s x := by simpa only [add_comm] using fderiv_within_add_const hxs c lemma fderiv_const_add (c : F) : fderiv 𝕜 (λy, c + f y) x = fderiv 𝕜 f x := by simp only [add_comm c, fderiv_add_const] end add section sum /-! ### Derivative of a finite sum of functions -/ open_locale big_operators variables {ι : Type*} {u : finset ι} {A : ι → (E → F)} {A' : ι → (E →L[𝕜] F)} theorem has_strict_fderiv_at.sum (h : ∀ i ∈ u, has_strict_fderiv_at (A i) (A' i) x) : has_strict_fderiv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := begin dsimp [has_strict_fderiv_at] at *, convert is_o.sum h, simp [finset.sum_sub_distrib, continuous_linear_map.sum_apply] end theorem has_fderiv_at_filter.sum (h : ∀ i ∈ u, has_fderiv_at_filter (A i) (A' i) x L) : has_fderiv_at_filter (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x L := begin dsimp [has_fderiv_at_filter] at *, convert is_o.sum h, simp [continuous_linear_map.sum_apply] end theorem has_fderiv_within_at.sum (h : ∀ i ∈ u, has_fderiv_within_at (A i) (A' i) s x) : has_fderiv_within_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) s x := has_fderiv_at_filter.sum h theorem has_fderiv_at.sum (h : ∀ i ∈ u, has_fderiv_at (A i) (A' i) x) : has_fderiv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := has_fderiv_at_filter.sum h theorem differentiable_within_at.sum (h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) : differentiable_within_at 𝕜 (λ y, ∑ i in u, A i y) s x := has_fderiv_within_at.differentiable_within_at $ has_fderiv_within_at.sum $ λ i hi, (h i hi).has_fderiv_within_at @[simp] theorem differentiable_at.sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) : differentiable_at 𝕜 (λ y, ∑ i in u, A i y) x := has_fderiv_at.differentiable_at $ has_fderiv_at.sum $ λ i hi, (h i hi).has_fderiv_at theorem differentiable_on.sum (h : ∀ i ∈ u, differentiable_on 𝕜 (A i) s) : differentiable_on 𝕜 (λ y, ∑ i in u, A i y) s := λ x hx, differentiable_within_at.sum $ λ i hi, h i hi x hx @[simp] theorem differentiable.sum (h : ∀ i ∈ u, differentiable 𝕜 (A i)) : differentiable 𝕜 (λ y, ∑ i in u, A i y) := λ x, differentiable_at.sum $ λ i hi, h i hi x theorem fderiv_within_sum (hxs : unique_diff_within_at 𝕜 s x) (h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) : fderiv_within 𝕜 (λ y, ∑ i in u, A i y) s x = (∑ i in u, fderiv_within 𝕜 (A i) s x) := (has_fderiv_within_at.sum (λ i hi, (h i hi).has_fderiv_within_at)).fderiv_within hxs theorem fderiv_sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) : fderiv 𝕜 (λ y, ∑ i in u, A i y) x = (∑ i in u, fderiv 𝕜 (A i) x) := (has_fderiv_at.sum (λ i hi, (h i hi).has_fderiv_at)).fderiv end sum section neg /-! ### Derivative of the negative of a function -/ theorem has_strict_fderiv_at.neg (h : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, -f x) (-f') x := (-1 : F →L[𝕜] F).has_strict_fderiv_at.comp x h theorem has_fderiv_at_filter.neg (h : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (λ x, -f x) (-f') x L := (-1 : F →L[𝕜] F).has_fderiv_at_filter.comp x h theorem has_fderiv_within_at.neg (h : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, -f x) (-f') s x := h.neg theorem has_fderiv_at.neg (h : has_fderiv_at f f' x) : has_fderiv_at (λ x, -f x) (-f') x := h.neg lemma differentiable_within_at.neg (h : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (λy, -f y) s x := h.has_fderiv_within_at.neg.differentiable_within_at @[simp] lemma differentiable_within_at_neg_iff : differentiable_within_at 𝕜 (λy, -f y) s x ↔ differentiable_within_at 𝕜 f s x := ⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩ lemma differentiable_at.neg (h : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (λy, -f y) x := h.has_fderiv_at.neg.differentiable_at @[simp] lemma differentiable_at_neg_iff : differentiable_at 𝕜 (λy, -f y) x ↔ differentiable_at 𝕜 f x := ⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩ lemma differentiable_on.neg (h : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (λy, -f y) s := λx hx, (h x hx).neg @[simp] lemma differentiable_on_neg_iff : differentiable_on 𝕜 (λy, -f y) s ↔ differentiable_on 𝕜 f s := ⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩ lemma differentiable.neg (h : differentiable 𝕜 f) : differentiable 𝕜 (λy, -f y) := λx, (h x).neg @[simp] lemma differentiable_neg_iff : differentiable 𝕜 (λy, -f y) ↔ differentiable 𝕜 f := ⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩ lemma fderiv_within_neg (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λy, -f y) s x = - fderiv_within 𝕜 f s x := if h : differentiable_within_at 𝕜 f s x then h.has_fderiv_within_at.neg.fderiv_within hxs else by { rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at, neg_zero], simpa } @[simp] lemma fderiv_neg : fderiv 𝕜 (λy, -f y) x = - fderiv 𝕜 f x := by simp only [← fderiv_within_univ, fderiv_within_neg unique_diff_within_at_univ] end neg section sub /-! ### Derivative of the difference of two functions -/ theorem has_strict_fderiv_at.sub (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) : has_strict_fderiv_at (λ x, f x - g x) (f' - g') x := by simpa only [sub_eq_add_neg] using hf.add hg.neg theorem has_fderiv_at_filter.sub (hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) : has_fderiv_at_filter (λ x, f x - g x) (f' - g') x L := by simpa only [sub_eq_add_neg] using hf.add hg.neg theorem has_fderiv_within_at.sub (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) : has_fderiv_within_at (λ x, f x - g x) (f' - g') s x := hf.sub hg theorem has_fderiv_at.sub (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) : has_fderiv_at (λ x, f x - g x) (f' - g') x := hf.sub hg lemma differentiable_within_at.sub (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : differentiable_within_at 𝕜 (λ y, f y - g y) s x := (hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : differentiable_at 𝕜 (λ y, f y - g y) x := (hf.has_fderiv_at.sub hg.has_fderiv_at).differentiable_at lemma differentiable_on.sub (hf : differentiable_on 𝕜 f s) (hg : differentiable_on 𝕜 g s) : differentiable_on 𝕜 (λy, f y - g y) s := λx hx, (hf x hx).sub (hg x hx) @[simp] lemma differentiable.sub (hf : differentiable 𝕜 f) (hg : differentiable 𝕜 g) : differentiable 𝕜 (λy, f y - g y) := λx, (hf x).sub (hg x) lemma fderiv_within_sub (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : fderiv_within 𝕜 (λy, f y - g y) s x = fderiv_within 𝕜 f s x - fderiv_within 𝕜 g s x := (hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).fderiv_within hxs lemma fderiv_sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : fderiv 𝕜 (λy, f y - g y) x = fderiv 𝕜 f x - fderiv 𝕜 g x := (hf.has_fderiv_at.sub hg.has_fderiv_at).fderiv theorem has_strict_fderiv_at.sub_const (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ x, f x - c) f' x := by simpa only [sub_eq_add_neg] using hf.add_const (-c) theorem has_fderiv_at_filter.sub_const (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ x, f x - c) f' x L := by simpa only [sub_eq_add_neg] using hf.add_const (-c) theorem has_fderiv_within_at.sub_const (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ x, f x - c) f' s x := hf.sub_const c theorem has_fderiv_at.sub_const (hf : has_fderiv_at f f' x) (c : F) : has_fderiv_at (λ x, f x - c) f' x := hf.sub_const c lemma differentiable_within_at.sub_const (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, f y - c) s x := (hf.has_fderiv_within_at.sub_const c).differentiable_within_at @[simp] lemma differentiable_within_at_sub_const_iff (c : F) : differentiable_within_at 𝕜 (λ y, f y - c) s x ↔ differentiable_within_at 𝕜 f s x := by simp only [sub_eq_add_neg, differentiable_within_at_add_const_iff] lemma differentiable_at.sub_const (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, f y - c) x := (hf.has_fderiv_at.sub_const c).differentiable_at @[simp] lemma differentiable_at_sub_const_iff (c : F) : differentiable_at 𝕜 (λ y, f y - c) x ↔ differentiable_at 𝕜 f x := by simp only [sub_eq_add_neg, differentiable_at_add_const_iff] lemma differentiable_on.sub_const (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, f y - c) s := λx hx, (hf x hx).sub_const c @[simp] lemma differentiable_on_sub_const_iff (c : F) : differentiable_on 𝕜 (λ y, f y - c) s ↔ differentiable_on 𝕜 f s := by simp only [sub_eq_add_neg, differentiable_on_add_const_iff] lemma differentiable.sub_const (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, f y - c) := λx, (hf x).sub_const c @[simp] lemma differentiable_sub_const_iff (c : F) : differentiable 𝕜 (λ y, f y - c) ↔ differentiable 𝕜 f := by simp only [sub_eq_add_neg, differentiable_add_const_iff] lemma fderiv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) : fderiv_within 𝕜 (λy, f y - c) s x = fderiv_within 𝕜 f s x := by simp only [sub_eq_add_neg, fderiv_within_add_const hxs] lemma fderiv_sub_const (c : F) : fderiv 𝕜 (λy, f y - c) x = fderiv 𝕜 f x := by simp only [sub_eq_add_neg, fderiv_add_const] theorem has_strict_fderiv_at.const_sub (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ x, c - f x) (-f') x := by simpa only [sub_eq_add_neg] using hf.neg.const_add c theorem has_fderiv_at_filter.const_sub (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ x, c - f x) (-f') x L := by simpa only [sub_eq_add_neg] using hf.neg.const_add c theorem has_fderiv_within_at.const_sub (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ x, c - f x) (-f') s x := hf.const_sub c theorem has_fderiv_at.const_sub (hf : has_fderiv_at f f' x) (c : F) : has_fderiv_at (λ x, c - f x) (-f') x := hf.const_sub c lemma differentiable_within_at.const_sub (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, c - f y) s x := (hf.has_fderiv_within_at.const_sub c).differentiable_within_at @[simp] lemma differentiable_within_at_const_sub_iff (c : F) : differentiable_within_at 𝕜 (λ y, c - f y) s x ↔ differentiable_within_at 𝕜 f s x := by simp [sub_eq_add_neg] lemma differentiable_at.const_sub (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, c - f y) x := (hf.has_fderiv_at.const_sub c).differentiable_at @[simp] lemma differentiable_at_const_sub_iff (c : F) : differentiable_at 𝕜 (λ y, c - f y) x ↔ differentiable_at 𝕜 f x := by simp [sub_eq_add_neg] lemma differentiable_on.const_sub (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, c - f y) s := λx hx, (hf x hx).const_sub c @[simp] lemma differentiable_on_const_sub_iff (c : F) : differentiable_on 𝕜 (λ y, c - f y) s ↔ differentiable_on 𝕜 f s := by simp [sub_eq_add_neg] lemma differentiable.const_sub (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, c - f y) := λx, (hf x).const_sub c @[simp] lemma differentiable_const_sub_iff (c : F) : differentiable 𝕜 (λ y, c - f y) ↔ differentiable 𝕜 f := by simp [sub_eq_add_neg] lemma fderiv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x) (c : F) : fderiv_within 𝕜 (λy, c - f y) s x = -fderiv_within 𝕜 f s x := by simp only [sub_eq_add_neg, fderiv_within_const_add, fderiv_within_neg, hxs] lemma fderiv_const_sub (c : F) : fderiv 𝕜 (λy, c - f y) x = -fderiv 𝕜 f x := by simp only [← fderiv_within_univ, fderiv_within_const_sub unique_diff_within_at_univ] end sub section bilinear_map /-! ### Derivative of a bounded bilinear map -/ variables {b : E × F → G} {u : set (E × F) } open normed_field lemma is_bounded_bilinear_map.has_strict_fderiv_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_strict_fderiv_at b (h.deriv p) p := begin rw has_strict_fderiv_at, set T := (E × F) × (E × F), have : is_o (λ q : T, b (q.1 - q.2)) (λ q : T, ∥q.1 - q.2∥ * 1) (𝓝 (p, p)), { refine (h.is_O'.comp_tendsto le_top).trans_is_o _, simp only [(∘)], refine (is_O_refl (λ q : T, ∥q.1 - q.2∥) _).mul_is_o (is_o.norm_left $ (is_o_one_iff _).2 _), rw [← sub_self p], exact continuous_at_fst.sub continuous_at_snd }, simp only [mul_one, is_o_norm_right] at this, refine (is_o.congr_of_sub _).1 this, clear this, convert_to is_o (λ q : T, h.deriv (p - q.2) (q.1 - q.2)) (λ q : T, q.1 - q.2) (𝓝 (p, p)), { ext ⟨⟨x₁, y₁⟩, ⟨x₂, y₂⟩⟩, rcases p with ⟨x, y⟩, simp only [is_bounded_bilinear_map_deriv_coe, prod.mk_sub_mk, h.map_sub_left, h.map_sub_right], abel }, have : is_o (λ q : T, p - q.2) (λ q, (1:ℝ)) (𝓝 (p, p)), from (is_o_one_iff _).2 (sub_self p ▸ tendsto_const_nhds.sub continuous_at_snd), apply is_bounded_bilinear_map_apply.is_O_comp.trans_is_o, refine is_o.trans_is_O _ (is_O_const_mul_self 1 _ _).of_norm_right, refine is_o.mul_is_O _ (is_O_refl _ _), exact (((h.is_bounded_linear_map_deriv.is_O_id ⊤).comp_tendsto le_top : _).trans_is_o this).norm_left end lemma is_bounded_bilinear_map.has_fderiv_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_fderiv_at b (h.deriv p) p := (h.has_strict_fderiv_at p).has_fderiv_at lemma is_bounded_bilinear_map.has_fderiv_within_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_fderiv_within_at b (h.deriv p) u p := (h.has_fderiv_at p).has_fderiv_within_at lemma is_bounded_bilinear_map.differentiable_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : differentiable_at 𝕜 b p := (h.has_fderiv_at p).differentiable_at lemma is_bounded_bilinear_map.differentiable_within_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : differentiable_within_at 𝕜 b u p := (h.differentiable_at p).differentiable_within_at lemma is_bounded_bilinear_map.fderiv (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : fderiv 𝕜 b p = h.deriv p := has_fderiv_at.fderiv (h.has_fderiv_at p) lemma is_bounded_bilinear_map.fderiv_within (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) (hxs : unique_diff_within_at 𝕜 u p) : fderiv_within 𝕜 b u p = h.deriv p := begin rw differentiable_at.fderiv_within (h.differentiable_at p) hxs, exact h.fderiv p end lemma is_bounded_bilinear_map.differentiable (h : is_bounded_bilinear_map 𝕜 b) : differentiable 𝕜 b := λx, h.differentiable_at x lemma is_bounded_bilinear_map.differentiable_on (h : is_bounded_bilinear_map 𝕜 b) : differentiable_on 𝕜 b u := h.differentiable.differentiable_on lemma is_bounded_bilinear_map.continuous (h : is_bounded_bilinear_map 𝕜 b) : continuous b := h.differentiable.continuous lemma is_bounded_bilinear_map.continuous_left (h : is_bounded_bilinear_map 𝕜 b) {f : F} : continuous (λe, b (e, f)) := h.continuous.comp (continuous_id.prod_mk continuous_const) lemma is_bounded_bilinear_map.continuous_right (h : is_bounded_bilinear_map 𝕜 b) {e : E} : continuous (λf, b (e, f)) := h.continuous.comp (continuous_const.prod_mk continuous_id) end bilinear_map namespace continuous_linear_equiv /-! ### The set of continuous linear equivalences between two Banach spaces is open In this section we establish that the set of continuous linear equivalences between two Banach spaces is an open subset of the space of linear maps between them. These facts are placed here because the proof uses `is_bounded_bilinear_map.continuous_left`, proved just above as a consequence of its differentiability. -/ protected lemma is_open [complete_space E] : is_open (range (coe : (E ≃L[𝕜] F) → (E →L[𝕜] F))) := begin nontriviality E, rw [is_open_iff_mem_nhds, forall_range_iff], refine λ e, mem_nhds_sets _ (mem_range_self _), let O : (E →L[𝕜] F) → (E →L[𝕜] E) := λ f, (e.symm : F →L[𝕜] E).comp f, have h_O : continuous O := is_bounded_bilinear_map_comp.continuous_left, convert units.is_open.preimage h_O using 1, ext f', split, { rintros ⟨e', rfl⟩, exact ⟨(e'.trans e.symm).to_unit, rfl⟩ }, { rintros ⟨w, hw⟩, use (units_equiv 𝕜 E w).trans e, ext x, simp [hw] } end protected lemma nhds [complete_space E] (e : E ≃L[𝕜] F) : (range (coe : (E ≃L[𝕜] F) → (E →L[𝕜] F))) ∈ 𝓝 (e : E →L[𝕜] F) := mem_nhds_sets continuous_linear_equiv.is_open (by simp) end continuous_linear_equiv section smul /-! ### Derivative of the product of a scalar-valued function and a vector-valued function -/ variables {c : E → 𝕜} {c' : E →L[𝕜] 𝕜} theorem has_strict_fderiv_at.smul (hc : has_strict_fderiv_at c c' x) (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) x := (is_bounded_bilinear_map_smul.has_strict_fderiv_at (c x, f x)).comp x $ hc.prod hf theorem has_fderiv_within_at.smul (hc : has_fderiv_within_at c c' s x) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) s x := (is_bounded_bilinear_map_smul.has_fderiv_at (c x, f x)).comp_has_fderiv_within_at x $ hc.prod hf theorem has_fderiv_at.smul (hc : has_fderiv_at c c' x) (hf : has_fderiv_at f f' x) : has_fderiv_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) x := (is_bounded_bilinear_map_smul.has_fderiv_at (c x, f x)).comp x $ hc.prod hf lemma differentiable_within_at.smul (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (λ y, c y • f y) s x := (hc.has_fderiv_within_at.smul hf.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (λ y, c y • f y) x := (hc.has_fderiv_at.smul hf.has_fderiv_at).differentiable_at lemma differentiable_on.smul (hc : differentiable_on 𝕜 c s) (hf : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (λ y, c y • f y) s := λx hx, (hc x hx).smul (hf x hx) @[simp] lemma differentiable.smul (hc : differentiable 𝕜 c) (hf : differentiable 𝕜 f) : differentiable 𝕜 (λ y, c y • f y) := λx, (hc x).smul (hf x) lemma fderiv_within_smul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 (λ y, c y • f y) s x = c x • fderiv_within 𝕜 f s x + (fderiv_within 𝕜 c s x).smul_right (f x) := (hc.has_fderiv_within_at.smul hf.has_fderiv_within_at).fderiv_within hxs lemma fderiv_smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : fderiv 𝕜 (λ y, c y • f y) x = c x • fderiv 𝕜 f x + (fderiv 𝕜 c x).smul_right (f x) := (hc.has_fderiv_at.smul hf.has_fderiv_at).fderiv theorem has_strict_fderiv_at.smul_const (hc : has_strict_fderiv_at c c' x) (f : F) : has_strict_fderiv_at (λ y, c y • f) (c'.smul_right f) x := by simpa only [smul_zero, zero_add] using hc.smul (has_strict_fderiv_at_const f x) theorem has_fderiv_within_at.smul_const (hc : has_fderiv_within_at c c' s x) (f : F) : has_fderiv_within_at (λ y, c y • f) (c'.smul_right f) s x := by simpa only [smul_zero, zero_add] using hc.smul (has_fderiv_within_at_const f x s) theorem has_fderiv_at.smul_const (hc : has_fderiv_at c c' x) (f : F) : has_fderiv_at (λ y, c y • f) (c'.smul_right f) x := by simpa only [smul_zero, zero_add] using hc.smul (has_fderiv_at_const f x) lemma differentiable_within_at.smul_const (hc : differentiable_within_at 𝕜 c s x) (f : F) : differentiable_within_at 𝕜 (λ y, c y • f) s x := (hc.has_fderiv_within_at.smul_const f).differentiable_within_at lemma differentiable_at.smul_const (hc : differentiable_at 𝕜 c x) (f : F) : differentiable_at 𝕜 (λ y, c y • f) x := (hc.has_fderiv_at.smul_const f).differentiable_at lemma differentiable_on.smul_const (hc : differentiable_on 𝕜 c s) (f : F) : differentiable_on 𝕜 (λ y, c y • f) s := λx hx, (hc x hx).smul_const f lemma differentiable.smul_const (hc : differentiable 𝕜 c) (f : F) : differentiable 𝕜 (λ y, c y • f) := λx, (hc x).smul_const f lemma fderiv_within_smul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (f : F) : fderiv_within 𝕜 (λ y, c y • f) s x = (fderiv_within 𝕜 c s x).smul_right f := (hc.has_fderiv_within_at.smul_const f).fderiv_within hxs lemma fderiv_smul_const (hc : differentiable_at 𝕜 c x) (f : F) : fderiv 𝕜 (λ y, c y • f) x = (fderiv 𝕜 c x).smul_right f := (hc.has_fderiv_at.smul_const f).fderiv end smul section mul /-! ### Derivative of the product of two scalar-valued functions -/ variables {c d : E → 𝕜} {c' d' : E →L[𝕜] 𝕜} theorem has_strict_fderiv_at.mul (hc : has_strict_fderiv_at c c' x) (hd : has_strict_fderiv_at d d' x) : has_strict_fderiv_at (λ y, c y * d y) (c x • d' + d x • c') x := by { convert hc.smul hd, ext z, apply mul_comm } theorem has_fderiv_within_at.mul (hc : has_fderiv_within_at c c' s x) (hd : has_fderiv_within_at d d' s x) : has_fderiv_within_at (λ y, c y * d y) (c x • d' + d x • c') s x := by { convert hc.smul hd, ext z, apply mul_comm } theorem has_fderiv_at.mul (hc : has_fderiv_at c c' x) (hd : has_fderiv_at d d' x) : has_fderiv_at (λ y, c y * d y) (c x • d' + d x • c') x := by { convert hc.smul hd, ext z, apply mul_comm } lemma differentiable_within_at.mul (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : differentiable_within_at 𝕜 (λ y, c y * d y) s x := (hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : differentiable_at 𝕜 (λ y, c y * d y) x := (hc.has_fderiv_at.mul hd.has_fderiv_at).differentiable_at lemma differentiable_on.mul (hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) : differentiable_on 𝕜 (λ y, c y * d y) s := λx hx, (hc x hx).mul (hd x hx) @[simp] lemma differentiable.mul (hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) : differentiable 𝕜 (λ y, c y * d y) := λx, (hc x).mul (hd x) lemma fderiv_within_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : fderiv_within 𝕜 (λ y, c y * d y) s x = c x • fderiv_within 𝕜 d s x + d x • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).fderiv_within hxs lemma fderiv_mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : fderiv 𝕜 (λ y, c y * d y) x = c x • fderiv 𝕜 d x + d x • fderiv 𝕜 c x := (hc.has_fderiv_at.mul hd.has_fderiv_at).fderiv theorem has_strict_fderiv_at.mul_const (hc : has_strict_fderiv_at c c' x) (d : 𝕜) : has_strict_fderiv_at (λ y, c y * d) (d • c') x := by simpa only [smul_zero, zero_add] using hc.mul (has_strict_fderiv_at_const d x) theorem has_fderiv_within_at.mul_const (hc : has_fderiv_within_at c c' s x) (d : 𝕜) : has_fderiv_within_at (λ y, c y * d) (d • c') s x := by simpa only [smul_zero, zero_add] using hc.mul (has_fderiv_within_at_const d x s) theorem has_fderiv_at.mul_const (hc : has_fderiv_at c c' x) (d : 𝕜) : has_fderiv_at (λ y, c y * d) (d • c') x := begin rw [← has_fderiv_within_at_univ] at *, exact hc.mul_const d end lemma differentiable_within_at.mul_const (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : differentiable_within_at 𝕜 (λ y, c y * d) s x := (hc.has_fderiv_within_at.mul_const d).differentiable_within_at lemma differentiable_at.mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : differentiable_at 𝕜 (λ y, c y * d) x := (hc.has_fderiv_at.mul_const d).differentiable_at lemma differentiable_on.mul_const (hc : differentiable_on 𝕜 c s) (d : 𝕜) : differentiable_on 𝕜 (λ y, c y * d) s := λx hx, (hc x hx).mul_const d lemma differentiable.mul_const (hc : differentiable 𝕜 c) (d : 𝕜) : differentiable 𝕜 (λ y, c y * d) := λx, (hc x).mul_const d lemma fderiv_within_mul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : fderiv_within 𝕜 (λ y, c y * d) s x = d • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.mul_const d).fderiv_within hxs lemma fderiv_mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : fderiv 𝕜 (λ y, c y * d) x = d • fderiv 𝕜 c x := (hc.has_fderiv_at.mul_const d).fderiv theorem has_strict_fderiv_at.const_mul (hc : has_strict_fderiv_at c c' x) (d : 𝕜) : has_strict_fderiv_at (λ y, d * c y) (d • c') x := begin simp only [mul_comm d], exact hc.mul_const d, end theorem has_fderiv_within_at.const_mul (hc : has_fderiv_within_at c c' s x) (d : 𝕜) : has_fderiv_within_at (λ y, d * c y) (d • c') s x := begin simp only [mul_comm d], exact hc.mul_const d, end theorem has_fderiv_at.const_mul (hc : has_fderiv_at c c' x) (d : 𝕜) : has_fderiv_at (λ y, d * c y) (d • c') x := begin simp only [mul_comm d], exact hc.mul_const d, end lemma differentiable_within_at.const_mul (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : differentiable_within_at 𝕜 (λ y, d * c y) s x := (hc.has_fderiv_within_at.const_mul d).differentiable_within_at lemma differentiable_at.const_mul (hc : differentiable_at 𝕜 c x) (d : 𝕜) : differentiable_at 𝕜 (λ y, d * c y) x := (hc.has_fderiv_at.const_mul d).differentiable_at lemma differentiable_on.const_mul (hc : differentiable_on 𝕜 c s) (d : 𝕜) : differentiable_on 𝕜 (λ y, d * c y) s := λx hx, (hc x hx).const_mul d lemma differentiable.const_mul (hc : differentiable 𝕜 c) (d : 𝕜) : differentiable 𝕜 (λ y, d * c y) := λx, (hc x).const_mul d lemma fderiv_within_const_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : fderiv_within 𝕜 (λ y, d * c y) s x = d • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.const_mul d).fderiv_within hxs lemma fderiv_const_mul (hc : differentiable_at 𝕜 c x) (d : 𝕜) : fderiv 𝕜 (λ y, d * c y) x = d • fderiv 𝕜 c x := (hc.has_fderiv_at.const_mul d).fderiv end mul section algebra_inverse variables {R : Type*} [normed_ring R] [normed_algebra 𝕜 R] [complete_space R] open normed_ring continuous_linear_map ring /-- At an invertible element `x` of a normed algebra `R`, the Fréchet derivative of the inversion operation is the linear map `λ t, - x⁻¹ * t * x⁻¹`. -/ lemma has_fderiv_at_ring_inverse (x : units R) : has_fderiv_at ring.inverse (- (lmul_right 𝕜 R ↑x⁻¹).comp (lmul_left 𝕜 R ↑x⁻¹)) x := begin have h_is_o : is_o (λ (t : R), inverse (↑x + t) - ↑x⁻¹ + ↑x⁻¹ * t * ↑x⁻¹) (λ (t : R), t) (𝓝 0), { refine (inverse_add_norm_diff_second_order x).trans_is_o ((is_o_norm_norm).mp _), simp only [normed_field.norm_pow, norm_norm], have h12 : 1 < 2 := by norm_num, convert (asymptotics.is_o_pow_pow h12).comp_tendsto tendsto_norm_zero, ext, simp }, have h_lim : tendsto (λ (y:R), y - x) (𝓝 x) (𝓝 0), { refine tendsto_zero_iff_norm_tendsto_zero.mpr _, exact tendsto_iff_norm_tendsto_zero.mp tendsto_id }, simp only [has_fderiv_at, has_fderiv_at_filter], convert h_is_o.comp_tendsto h_lim, ext y, simp only [coe_comp', function.comp_app, lmul_right_apply, lmul_left_apply, neg_apply, inverse_unit x, units.inv_mul, add_sub_cancel'_right, mul_sub, sub_mul, one_mul], abel end lemma differentiable_at_inverse (x : units R) : differentiable_at 𝕜 (@ring.inverse R _) x := (has_fderiv_at_ring_inverse x).differentiable_at lemma fderiv_inverse (x : units R) : fderiv 𝕜 (@ring.inverse R _) x = - (lmul_right 𝕜 R ↑x⁻¹).comp (lmul_left 𝕜 R ↑x⁻¹) := (has_fderiv_at_ring_inverse x).fderiv end algebra_inverse section continuous_linear_equiv /-! ### Differentiability of linear equivs, and invariance of differentiability -/ variable (iso : E ≃L[𝕜] F) protected lemma continuous_linear_equiv.has_strict_fderiv_at : has_strict_fderiv_at iso (iso : E →L[𝕜] F) x := iso.to_continuous_linear_map.has_strict_fderiv_at protected lemma continuous_linear_equiv.has_fderiv_within_at : has_fderiv_within_at iso (iso : E →L[𝕜] F) s x := iso.to_continuous_linear_map.has_fderiv_within_at protected lemma continuous_linear_equiv.has_fderiv_at : has_fderiv_at iso (iso : E →L[𝕜] F) x := iso.to_continuous_linear_map.has_fderiv_at_filter protected lemma continuous_linear_equiv.differentiable_at : differentiable_at 𝕜 iso x := iso.has_fderiv_at.differentiable_at protected lemma continuous_linear_equiv.differentiable_within_at : differentiable_within_at 𝕜 iso s x := iso.differentiable_at.differentiable_within_at protected lemma continuous_linear_equiv.fderiv : fderiv 𝕜 iso x = iso := iso.has_fderiv_at.fderiv protected lemma continuous_linear_equiv.fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 iso s x = iso := iso.to_continuous_linear_map.fderiv_within hxs protected lemma continuous_linear_equiv.differentiable : differentiable 𝕜 iso := λx, iso.differentiable_at protected lemma continuous_linear_equiv.differentiable_on : differentiable_on 𝕜 iso s := iso.differentiable.differentiable_on lemma continuous_linear_equiv.comp_differentiable_within_at_iff {f : G → E} {s : set G} {x : G} : differentiable_within_at 𝕜 (iso ∘ f) s x ↔ differentiable_within_at 𝕜 f s x := begin refine ⟨λ H, _, λ H, iso.differentiable.differentiable_at.comp_differentiable_within_at x H⟩, have : differentiable_within_at 𝕜 (iso.symm ∘ (iso ∘ f)) s x := iso.symm.differentiable.differentiable_at.comp_differentiable_within_at x H, rwa [← function.comp.assoc iso.symm iso f, iso.symm_comp_self] at this, end lemma continuous_linear_equiv.comp_differentiable_at_iff {f : G → E} {x : G} : differentiable_at 𝕜 (iso ∘ f) x ↔ differentiable_at 𝕜 f x := by rw [← differentiable_within_at_univ, ← differentiable_within_at_univ, iso.comp_differentiable_within_at_iff] lemma continuous_linear_equiv.comp_differentiable_on_iff {f : G → E} {s : set G} : differentiable_on 𝕜 (iso ∘ f) s ↔ differentiable_on 𝕜 f s := begin rw [differentiable_on, differentiable_on], simp only [iso.comp_differentiable_within_at_iff], end lemma continuous_linear_equiv.comp_differentiable_iff {f : G → E} : differentiable 𝕜 (iso ∘ f) ↔ differentiable 𝕜 f := begin rw [← differentiable_on_univ, ← differentiable_on_univ], exact iso.comp_differentiable_on_iff end lemma continuous_linear_equiv.comp_has_fderiv_within_at_iff {f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] E} : has_fderiv_within_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') s x ↔ has_fderiv_within_at f f' s x := begin refine ⟨λ H, _, λ H, iso.has_fderiv_at.comp_has_fderiv_within_at x H⟩, have A : f = iso.symm ∘ (iso ∘ f), by { rw [← function.comp.assoc, iso.symm_comp_self], refl }, have B : f' = (iso.symm : F →L[𝕜] E).comp ((iso : E →L[𝕜] F).comp f'), by rw [← continuous_linear_map.comp_assoc, iso.coe_symm_comp_coe, continuous_linear_map.id_comp], rw [A, B], exact iso.symm.has_fderiv_at.comp_has_fderiv_within_at x H end lemma continuous_linear_equiv.comp_has_strict_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} : has_strict_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_strict_fderiv_at f f' x := begin refine ⟨λ H, _, λ H, iso.has_strict_fderiv_at.comp x H⟩, convert iso.symm.has_strict_fderiv_at.comp x H; ext z; apply (iso.symm_apply_apply _).symm end lemma continuous_linear_equiv.comp_has_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} : has_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_fderiv_at f f' x := by rw [← has_fderiv_within_at_univ, ← has_fderiv_within_at_univ, iso.comp_has_fderiv_within_at_iff] lemma continuous_linear_equiv.comp_has_fderiv_within_at_iff' {f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] F} : has_fderiv_within_at (iso ∘ f) f' s x ↔ has_fderiv_within_at f ((iso.symm : F →L[𝕜] E).comp f') s x := by rw [← iso.comp_has_fderiv_within_at_iff, ← continuous_linear_map.comp_assoc, iso.coe_comp_coe_symm, continuous_linear_map.id_comp] lemma continuous_linear_equiv.comp_has_fderiv_at_iff' {f : G → E} {x : G} {f' : G →L[𝕜] F} : has_fderiv_at (iso ∘ f) f' x ↔ has_fderiv_at f ((iso.symm : F →L[𝕜] E).comp f') x := by rw [← has_fderiv_within_at_univ, ← has_fderiv_within_at_univ, iso.comp_has_fderiv_within_at_iff'] lemma continuous_linear_equiv.comp_fderiv_within {f : G → E} {s : set G} {x : G} (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (iso ∘ f) s x = (iso : E →L[𝕜] F).comp (fderiv_within 𝕜 f s x) := begin by_cases h : differentiable_within_at 𝕜 f s x, { rw [fderiv.comp_fderiv_within x iso.differentiable_at h hxs, iso.fderiv] }, { have : ¬differentiable_within_at 𝕜 (iso ∘ f) s x, from mt iso.comp_differentiable_within_at_iff.1 h, rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at this, continuous_linear_map.comp_zero] } end lemma continuous_linear_equiv.comp_fderiv {f : G → E} {x : G} : fderiv 𝕜 (iso ∘ f) x = (iso : E →L[𝕜] F).comp (fderiv 𝕜 f x) := begin rw [← fderiv_within_univ, ← fderiv_within_univ], exact iso.comp_fderiv_within unique_diff_within_at_univ, end end continuous_linear_equiv /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a` in the strict sense, then `g` has the derivative `f'⁻¹` at `a` in the strict sense. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_strict_fderiv_at.of_local_left_inverse {f : E → F} {f' : E ≃L[𝕜] F} {g : F → E} {a : F} (hg : continuous_at g a) (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) (g a)) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_strict_fderiv_at g (f'.symm : F →L[𝕜] E) a := begin replace hg := hg.prod_map' hg, replace hfg := hfg.prod_mk_nhds hfg, have : is_O (λ p : F × F, g p.1 - g p.2 - f'.symm (p.1 - p.2)) (λ p : F × F, f' (g p.1 - g p.2) - (p.1 - p.2)) (𝓝 (a, a)), { refine ((f'.symm : F →L[𝕜] E).is_O_comp _ _).congr (λ x, _) (λ _, rfl), simp }, refine this.trans_is_o _, clear this, refine ((hf.comp_tendsto hg).symm.congr' (hfg.mono _) (eventually_of_forall $ λ _, rfl)).trans_is_O _, { rintros p ⟨hp1, hp2⟩, simp [hp1, hp2] }, { refine (hf.is_O_sub_rev.comp_tendsto hg).congr' (eventually_of_forall $ λ _, rfl) (hfg.mono _), rintros p ⟨hp1, hp2⟩, simp only [(∘), hp1, hp2] } end /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a`, then `g` has the derivative `f'⁻¹` at `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_fderiv_at.of_local_left_inverse {f : E → F} {f' : E ≃L[𝕜] F} {g : F → E} {a : F} (hg : continuous_at g a) (hf : has_fderiv_at f (f' : E →L[𝕜] F) (g a)) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_fderiv_at g (f'.symm : F →L[𝕜] E) a := begin have : is_O (λ x : F, g x - g a - f'.symm (x - a)) (λ x : F, f' (g x - g a) - (x - a)) (𝓝 a), { refine ((f'.symm : F →L[𝕜] E).is_O_comp _ _).congr (λ x, _) (λ _, rfl), simp }, refine this.trans_is_o _, clear this, refine ((hf.comp_tendsto hg).symm.congr' (hfg.mono _) (eventually_of_forall $ λ _, rfl)).trans_is_O _, { rintros p hp, simp [hp, hfg.self_of_nhds] }, { refine (hf.is_O_sub_rev.comp_tendsto hg).congr' (eventually_of_forall $ λ _, rfl) (hfg.mono _), rintros p hp, simp only [(∘), hp, hfg.self_of_nhds] } end /-- If `f` is a local homeomorphism defined on a neighbourhood of `f.symm a`, and `f` has an invertible derivative `f'` in the sense of strict differentiability at `f.symm a`, then `f.symm` has the derivative `f'⁻¹` at `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ lemma local_homeomorph.has_strict_fderiv_at_symm (f : local_homeomorph E F) {f' : E ≃L[𝕜] F} {a : F} (ha : a ∈ f.target) (htff' : has_strict_fderiv_at f (f' : E →L[𝕜] F) (f.symm a)) : has_strict_fderiv_at f.symm (f'.symm : F →L[𝕜] E) a := htff'.of_local_left_inverse (f.symm.continuous_at ha) (f.eventually_right_inverse ha) /-- If `f` is a local homeomorphism defined on a neighbourhood of `f.symm a`, and `f` has an invertible derivative `f'` at `f.symm a`, then `f.symm` has the derivative `f'⁻¹` at `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ lemma local_homeomorph.has_fderiv_at_symm (f : local_homeomorph E F) {f' : E ≃L[𝕜] F} {a : F} (ha : a ∈ f.target) (htff' : has_fderiv_at f (f' : E →L[𝕜] F) (f.symm a)) : has_fderiv_at f.symm (f'.symm : F →L[𝕜] E) a := htff'.of_local_left_inverse (f.symm.continuous_at ha) (f.eventually_right_inverse ha) lemma has_fderiv_within_at.eventually_ne (h : has_fderiv_within_at f f' s x) (hf' : ∃ C, ∀ z, ∥z∥ ≤ C * ∥f' z∥) : ∀ᶠ z in 𝓝[s \ {x}] x, f z ≠ f x := begin rw [nhds_within, diff_eq, ← inf_principal, ← inf_assoc, eventually_inf_principal], have A : is_O (λ z, z - x) (λ z, f' (z - x)) (𝓝[s] x) := (is_O_iff.2 $ hf'.imp $ λ C hC, eventually_of_forall $ λ z, hC _), have : (λ z, f z - f x) ~[𝓝[s] x] (λ z, f' (z - x)) := h.trans_is_O A, simpa [not_imp_not, sub_eq_zero] using (A.trans this.is_O_symm).eq_zero_imp end lemma has_fderiv_at.eventually_ne (h : has_fderiv_at f f' x) (hf' : ∃ C, ∀ z, ∥z∥ ≤ C * ∥f' z∥) : ∀ᶠ z in 𝓝[{x}ᶜ] x, f z ≠ f x := by simpa only [compl_eq_univ_diff] using (has_fderiv_within_at_univ.2 h).eventually_ne hf' end section /- In the special case of a normed space over the reals, we can use scalar multiplication in the `tendsto` characterization of the Fréchet derivative. -/ variables {E : Type*} [normed_group E] [normed_space ℝ E] variables {F : Type*} [normed_group F] [normed_space ℝ F] variables {f : E → F} {f' : E →L[ℝ] F} {x : E} theorem has_fderiv_at_filter_real_equiv {L : filter E} : tendsto (λ x' : E, ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (𝓝 0) ↔ tendsto (λ x' : E, ∥x' - x∥⁻¹ • (f x' - f x - f' (x' - x))) L (𝓝 0) := begin symmetry, rw [tendsto_iff_norm_tendsto_zero], refine tendsto_congr (λ x', _), have : ∥x' - x∥⁻¹ ≥ 0, from inv_nonneg.mpr (norm_nonneg _), simp [norm_smul, real.norm_eq_abs, abs_of_nonneg this] end lemma has_fderiv_at.lim_real (hf : has_fderiv_at f f' x) (v : E) : tendsto (λ (c:ℝ), c • (f (x + c⁻¹ • v) - f x)) at_top (𝓝 (f' v)) := begin apply hf.lim v, rw tendsto_at_top_at_top, exact λ b, ⟨b, λ a ha, le_trans ha (le_abs_self _)⟩ end end section tangent_cone variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {f : E → F} {s : set E} {f' : E →L[𝕜] F} /-- The image of a tangent cone under the differential of a map is included in the tangent cone to the image. -/ lemma has_fderiv_within_at.maps_to_tangent_cone {x : E} (h : has_fderiv_within_at f f' s x) : maps_to f' (tangent_cone_at 𝕜 s x) (tangent_cone_at 𝕜 (f '' s) (f x)) := begin rintros v ⟨c, d, dtop, clim, cdlim⟩, refine ⟨c, (λn, f (x + d n) - f x), mem_sets_of_superset dtop _, clim, h.lim at_top dtop clim cdlim⟩, simp [-mem_image, mem_image_of_mem] {contextual := tt} end /-- If a set has the unique differentiability property at a point x, then the image of this set under a map with onto derivative has also the unique differentiability property at the image point. -/ lemma has_fderiv_within_at.unique_diff_within_at {x : E} (h : has_fderiv_within_at f f' s x) (hs : unique_diff_within_at 𝕜 s x) (h' : dense_range f') : unique_diff_within_at 𝕜 (f '' s) (f x) := begin refine ⟨h'.dense_of_maps_to f'.continuous hs.1 _, h.continuous_within_at.mem_closure_image hs.2⟩, show submodule.span 𝕜 (tangent_cone_at 𝕜 s x) ≤ (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))).comap f', rw [submodule.span_le], exact h.maps_to_tangent_cone.mono (subset.refl _) submodule.subset_span end lemma has_fderiv_within_at.unique_diff_within_at_of_continuous_linear_equiv {x : E} (e' : E ≃L[𝕜] F) (h : has_fderiv_within_at f (e' : E →L[𝕜] F) s x) (hs : unique_diff_within_at 𝕜 s x) : unique_diff_within_at 𝕜 (f '' s) (f x) := h.unique_diff_within_at hs e'.surjective.dense_range lemma continuous_linear_equiv.unique_diff_on_preimage_iff (e : F ≃L[𝕜] E) : unique_diff_on 𝕜 (e ⁻¹' s) ↔ unique_diff_on 𝕜 s := begin split, { assume hs x hx, have A : s = e '' (e.symm '' s) := (equiv.symm_image_image (e.symm.to_linear_equiv.to_equiv) s).symm, have B : e.symm '' s = e⁻¹' s := equiv.image_eq_preimage e.symm.to_linear_equiv.to_equiv s, rw [A, B, (e.apply_symm_apply x).symm], refine has_fderiv_within_at.unique_diff_within_at_of_continuous_linear_equiv e e.has_fderiv_within_at (hs _ _), rwa [mem_preimage, e.apply_symm_apply x] }, { assume hs x hx, have : e ⁻¹' s = e.symm '' s := (equiv.image_eq_preimage e.symm.to_linear_equiv.to_equiv s).symm, rw [this, (e.symm_apply_apply x).symm], exact has_fderiv_within_at.unique_diff_within_at_of_continuous_linear_equiv e.symm e.symm.has_fderiv_within_at (hs _ hx) }, end end tangent_cone section restrict_scalars /-! ### Restricting from `ℂ` to `ℝ`, or generally from `𝕜'` to `𝕜` If a function is differentiable over `ℂ`, then it is 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 𝕜] variables {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] [normed_space 𝕜' E] variables [is_scalar_tower 𝕜 𝕜' E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] [normed_space 𝕜' F] variables [is_scalar_tower 𝕜 𝕜' F] variables {f : E → F} {f' : E →L[𝕜'] F} {s : set E} {x : E} lemma has_strict_fderiv_at.restrict_scalars (h : has_strict_fderiv_at f f' x) : has_strict_fderiv_at f (f'.restrict_scalars 𝕜) x := h lemma has_fderiv_at.restrict_scalars (h : has_fderiv_at f f' x) : has_fderiv_at f (f'.restrict_scalars 𝕜) x := h lemma has_fderiv_within_at.restrict_scalars (h : has_fderiv_within_at f f' s x) : has_fderiv_within_at f (f'.restrict_scalars 𝕜) s x := h lemma differentiable_at.restrict_scalars (h : differentiable_at 𝕜' f x) : differentiable_at 𝕜 f x := (h.has_fderiv_at.restrict_scalars 𝕜).differentiable_at lemma differentiable_within_at.restrict_scalars (h : differentiable_within_at 𝕜' f s x) : differentiable_within_at 𝕜 f s x := (h.has_fderiv_within_at.restrict_scalars 𝕜).differentiable_within_at lemma differentiable_on.restrict_scalars (h : differentiable_on 𝕜' f s) : differentiable_on 𝕜 f s := λx hx, (h x hx).restrict_scalars 𝕜 lemma differentiable.restrict_scalars (h : differentiable 𝕜' f) : differentiable 𝕜 f := λx, (h x).restrict_scalars 𝕜 end restrict_scalars /-! ### Multiplying by a complex function respects real differentiability Consider two functions `c : E → ℂ` and `f : E → F` where `F` is a complex vector space. If both `c` and `f` are differentiable over `ℝ`, then so is their product. This paragraph proves this statement, in the general version where `ℝ` is replaced by a field `𝕜`, and `ℂ` is replaced by a normed algebra `𝕜'` over `𝕜`. -/ section smul_algebra variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] [normed_space 𝕜' F] variables [is_scalar_tower 𝕜 𝕜' F] variables {f : E → F} {f' : E →L[𝕜] F} {s : set E} {x : E} variables {c : E → 𝕜'} {c' : E →L[𝕜] 𝕜'} {L : filter E} theorem has_strict_fderiv_at.smul_algebra (hc : has_strict_fderiv_at c c' x) (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ y, c y • f y) (c x • f' + c'.smul_algebra_right (f x)) x := (is_bounded_bilinear_map_smul_algebra.has_strict_fderiv_at (c x, f x)).comp x $ hc.prod hf theorem has_fderiv_within_at.smul_algebra (hc : has_fderiv_within_at c c' s x) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ y, c y • f y) (c x • f' + c'.smul_algebra_right (f x)) s x := (is_bounded_bilinear_map_smul_algebra.has_fderiv_at (c x, f x)).comp_has_fderiv_within_at x $ hc.prod hf theorem has_fderiv_at.smul_algebra (hc : has_fderiv_at c c' x) (hf : has_fderiv_at f f' x) : has_fderiv_at (λ y, c y • f y) (c x • f' + c'.smul_algebra_right (f x)) x := (is_bounded_bilinear_map_smul_algebra.has_fderiv_at (c x, f x)).comp x $ hc.prod hf lemma differentiable_within_at.smul_algebra (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (λ y, c y • f y) s x := (hc.has_fderiv_within_at.smul_algebra hf.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.smul_algebra (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (λ y, c y • f y) x := (hc.has_fderiv_at.smul_algebra hf.has_fderiv_at).differentiable_at lemma differentiable_on.smul_algebra (hc : differentiable_on 𝕜 c s) (hf : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (λ y, c y • f y) s := λx hx, (hc x hx).smul_algebra (hf x hx) @[simp] lemma differentiable.smul_algebra (hc : differentiable 𝕜 c) (hf : differentiable 𝕜 f) : differentiable 𝕜 (λ y, c y • f y) := λx, (hc x).smul_algebra (hf x) lemma fderiv_within_smul_algebra (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 (λ y, c y • f y) s x = c x • fderiv_within 𝕜 f s x + (fderiv_within 𝕜 c s x).smul_algebra_right (f x) := (hc.has_fderiv_within_at.smul_algebra hf.has_fderiv_within_at).fderiv_within hxs lemma fderiv_smul_algebra (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : fderiv 𝕜 (λ y, c y • f y) x = c x • fderiv 𝕜 f x + (fderiv 𝕜 c x).smul_algebra_right (f x) := (hc.has_fderiv_at.smul_algebra hf.has_fderiv_at).fderiv theorem has_strict_fderiv_at.smul_algebra_const (hc : has_strict_fderiv_at c c' x) (f : F) : has_strict_fderiv_at (λ y, c y • f) (c'.smul_algebra_right f) x := by simpa only [smul_zero, zero_add] using hc.smul_algebra (has_strict_fderiv_at_const f x) theorem has_fderiv_within_at.smul_algebra_const (hc : has_fderiv_within_at c c' s x) (f : F) : has_fderiv_within_at (λ y, c y • f) (c'.smul_algebra_right f) s x := by simpa only [smul_zero, zero_add] using hc.smul_algebra (has_fderiv_within_at_const f x s) theorem has_fderiv_at.smul_algebra_const (hc : has_fderiv_at c c' x) (f : F) : has_fderiv_at (λ y, c y • f) (c'.smul_algebra_right f) x := by simpa only [smul_zero, zero_add] using hc.smul_algebra (has_fderiv_at_const f x) lemma differentiable_within_at.smul_algebra_const (hc : differentiable_within_at 𝕜 c s x) (f : F) : differentiable_within_at 𝕜 (λ y, c y • f) s x := (hc.has_fderiv_within_at.smul_algebra_const f).differentiable_within_at lemma differentiable_at.smul_algebra_const (hc : differentiable_at 𝕜 c x) (f : F) : differentiable_at 𝕜 (λ y, c y • f) x := (hc.has_fderiv_at.smul_algebra_const f).differentiable_at lemma differentiable_on.smul_algebra_const (hc : differentiable_on 𝕜 c s) (f : F) : differentiable_on 𝕜 (λ y, c y • f) s := λx hx, (hc x hx).smul_algebra_const f lemma differentiable.smul_algebra_const (hc : differentiable 𝕜 c) (f : F) : differentiable 𝕜 (λ y, c y • f) := λx, (hc x).smul_algebra_const f lemma fderiv_within_smul_algebra_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (f : F) : fderiv_within 𝕜 (λ y, c y • f) s x = (fderiv_within 𝕜 c s x).smul_algebra_right f := (hc.has_fderiv_within_at.smul_algebra_const f).fderiv_within hxs lemma fderiv_smul_algebra_const (hc : differentiable_at 𝕜 c x) (f : F) : fderiv 𝕜 (λ y, c y • f) x = (fderiv 𝕜 c x).smul_algebra_right f := (hc.has_fderiv_at.smul_algebra_const f).fderiv theorem has_strict_fderiv_at.const_smul_algebra (h : has_strict_fderiv_at f f' x) (c : 𝕜') : has_strict_fderiv_at (λ x, c • f x) (c • f') x := (c • (1 : F →L[𝕜] F)).has_strict_fderiv_at.comp x h theorem has_fderiv_at_filter.const_smul_algebra (h : has_fderiv_at_filter f f' x L) (c : 𝕜') : has_fderiv_at_filter (λ x, c • f x) (c • f') x L := (c • (1 : F →L[𝕜] F)).has_fderiv_at_filter.comp x h theorem has_fderiv_within_at.const_smul_algebra (h : has_fderiv_within_at f f' s x) (c : 𝕜') : has_fderiv_within_at (λ x, c • f x) (c • f') s x := h.const_smul_algebra c theorem has_fderiv_at.const_smul_algebra (h : has_fderiv_at f f' x) (c : 𝕜') : has_fderiv_at (λ x, c • f x) (c • f') x := h.const_smul_algebra c lemma differentiable_within_at.const_smul_algebra (h : differentiable_within_at 𝕜 f s x) (c : 𝕜') : differentiable_within_at 𝕜 (λy, c • f y) s x := (h.has_fderiv_within_at.const_smul_algebra c).differentiable_within_at lemma differentiable_at.const_smul_algebra (h : differentiable_at 𝕜 f x) (c : 𝕜') : differentiable_at 𝕜 (λy, c • f y) x := (h.has_fderiv_at.const_smul_algebra c).differentiable_at lemma differentiable_on.const_smul_algebra (h : differentiable_on 𝕜 f s) (c : 𝕜') : differentiable_on 𝕜 (λy, c • f y) s := λx hx, (h x hx).const_smul_algebra c lemma differentiable.const_smul_algebra (h : differentiable 𝕜 f) (c : 𝕜') : differentiable 𝕜 (λy, c • f y) := λx, (h x).const_smul_algebra c lemma fderiv_within_const_smul_algebra (hxs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f s x) (c : 𝕜') : fderiv_within 𝕜 (λy, c • f y) s x = c • fderiv_within 𝕜 f s x := (h.has_fderiv_within_at.const_smul_algebra c).fderiv_within hxs lemma fderiv_const_smul_algebra (h : differentiable_at 𝕜 f x) (c : 𝕜') : fderiv 𝕜 (λy, c • f y) x = c • fderiv 𝕜 f x := (h.has_fderiv_at.const_smul_algebra c).fderiv end smul_algebra
92654df3f33ce2747d8ad69f9b1aca95924dcbc1
7cef822f3b952965621309e88eadf618da0c8ae9
/src/category_theory/limits/shapes/constructions/limits.lean
e3d54ed670afb607430de2cbbf28efb67bd82681
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
54
lean
-- TODO construct limits from products and equalizers
d4d6076c5a2567eeb001ff93d6dc3bcd8a0f6685
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/mvar_fvar.lean
04ad2435b5a217cc8adb94253410160b1443319f
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
287
lean
import Lean new_frontend open Lean #eval (mkFVar `a).hasFVar #eval (mkApp (mkConst `foo) (mkFVar `a)).hasFVar #eval (mkApp (mkConst `foo) (mkConst `a)).hasFVar #eval (mkMVar `a).hasMVar #eval (mkApp (mkConst `foo) (mkMVar `a)).hasMVar #eval (mkApp (mkConst `foo) (mkConst `a)).hasMVar
3fd07f2c8722439f00e4afc0279197a19073552a
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/algebra/star/unitary.lean
f77c38d44449517d85191afedf8e39829c8359e6
[ "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
4,752
lean
/- Copyright (c) 2022 Frédéric Dupuis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Shing Tak Lam, Frédéric Dupuis -/ import algebra.star.basic import group_theory.submonoid.membership /-! # Unitary elements of a star monoid This file defines `unitary R`, where `R` is a star monoid, as the submonoid made of the elements that satisfy `star U * U = 1` and `U * star U = 1`, and these form a group. This includes, for instance, unitary operators on Hilbert spaces. See also `matrix.unitary_group` for specializations to `unitary (matrix n n R)`. ## Tags unitary -/ /-- In a `star_monoid R`, `unitary R` is the submonoid consisting of all the elements `U` of `R` such that `star U * U = 1` and `U * star U = 1`. -/ def unitary (R : Type*) [monoid R] [star_monoid R] : submonoid R := { carrier := {U | star U * U = 1 ∧ U * star U = 1}, one_mem' := by simp only [mul_one, and_self, set.mem_set_of_eq, star_one], mul_mem' := λ U B ⟨hA₁, hA₂⟩ ⟨hB₁, hB₂⟩, begin refine ⟨_, _⟩, { calc star (U * B) * (U * B) = star B * star U * U * B : by simp only [mul_assoc, star_mul] ... = star B * (star U * U) * B : by rw [←mul_assoc] ... = 1 : by rw [hA₁, mul_one, hB₁] }, { calc U * B * star (U * B) = U * B * (star B * star U) : by rw [star_mul] ... = U * (B * star B) * star U : by simp_rw [←mul_assoc] ... = 1 : by rw [hB₂, mul_one, hA₂] } end } variables {R : Type*} namespace unitary section monoid variables [monoid R] [star_monoid R] lemma mem_iff {U : R} : U ∈ unitary R ↔ star U * U = 1 ∧ U * star U = 1 := iff.rfl @[simp] lemma star_mul_self_of_mem {U : R} (hU : U ∈ unitary R) : star U * U = 1 := hU.1 @[simp] lemma mul_star_self_of_mem {U : R} (hU : U ∈ unitary R) : U * star U = 1 := hU.2 lemma star_mem {U : R} (hU : U ∈ unitary R) : star U ∈ unitary R := ⟨by rw [star_star, mul_star_self_of_mem hU], by rw [star_star, star_mul_self_of_mem hU]⟩ @[simp] lemma star_mem_iff {U : R} : star U ∈ unitary R ↔ U ∈ unitary R := ⟨λ h, star_star U ▸ star_mem h, star_mem⟩ instance : has_star (unitary R) := ⟨λ U, ⟨star U, star_mem U.prop⟩⟩ @[simp, norm_cast] lemma coe_star {U : unitary R} : ↑(star U) = (star U : R) := rfl lemma coe_star_mul_self (U : unitary R) : (star U : R) * U = 1 := star_mul_self_of_mem U.prop lemma coe_mul_star_self (U : unitary R) : (U : R) * star U = 1 := mul_star_self_of_mem U.prop @[simp] lemma star_mul_self (U : unitary R) : star U * U = 1 := subtype.ext $ coe_star_mul_self U @[simp] lemma mul_star_self (U : unitary R) : U * star U = 1 := subtype.ext $ coe_mul_star_self U instance : group (unitary R) := { inv := star, mul_left_inv := star_mul_self, ..submonoid.to_monoid _ } instance : has_involutive_star (unitary R) := ⟨λ _, by { ext, simp only [coe_star, star_star] }⟩ instance : star_monoid (unitary R) := ⟨λ _ _, by { ext, simp only [coe_star, submonoid.coe_mul, star_mul] }⟩ instance : inhabited (unitary R) := ⟨1⟩ lemma star_eq_inv (U : unitary R) : star U = U⁻¹ := rfl lemma star_eq_inv' : (star : unitary R → unitary R) = has_inv.inv := rfl /-- The unitary elements embed into the units. -/ @[simps] def to_units : unitary R →* Rˣ := { to_fun := λ x, ⟨x, ↑(x⁻¹), coe_mul_star_self x, coe_star_mul_self x⟩, map_one' := units.ext rfl, map_mul' := λ x y, units.ext rfl } lemma to_units_injective : function.injective (to_units : unitary R → Rˣ) := λ x y h, subtype.ext $ units.ext_iff.mp h end monoid section comm_monoid variables [comm_monoid R] [star_monoid R] instance : comm_group (unitary R) := { ..unitary.group, ..submonoid.to_comm_monoid _ } lemma mem_iff_star_mul_self {U : R} : U ∈ unitary R ↔ star U * U = 1 := mem_iff.trans $ and_iff_left_of_imp $ λ h, mul_comm (star U) U ▸ h lemma mem_iff_self_mul_star {U : R} : U ∈ unitary R ↔ U * star U = 1 := mem_iff.trans $ and_iff_right_of_imp $ λ h, mul_comm U (star U) ▸ h end comm_monoid section group_with_zero variables [group_with_zero R] [star_monoid R] @[norm_cast] lemma coe_inv (U : unitary R) : ↑(U⁻¹) = (U⁻¹ : R) := eq_inv_of_mul_right_eq_one (coe_mul_star_self _) @[norm_cast] lemma coe_div (U₁ U₂ : unitary R) : ↑(U₁ / U₂) = (U₁ / U₂ : R) := by simp only [div_eq_mul_inv, coe_inv, submonoid.coe_mul] @[norm_cast] lemma coe_zpow (U : unitary R) (z : ℤ) : ↑(U ^ z) = (U ^ z : R) := begin induction z, { simp [submonoid.coe_pow], }, { simp [coe_inv] }, end end group_with_zero end unitary
4c6d76a6f984374708580a82f35612b90db53abe
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/linear_algebra/linear_pmap.lean
121830900998db281bd2cc308caa3ca2c03a8ba6
[ "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
29,896
lean
/- Copyright (c) 2020 Yury Kudryashov All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Moritz Doll -/ import linear_algebra.basic import linear_algebra.prod /-! # Partially defined linear maps A `linear_pmap R E F` or `E →ₗ.[R] F` is a linear map from a submodule of `E` to `F`. We define a `semilattice_inf` with `order_bot` instance on this this, and define three operations: * `mk_span_singleton` defines a partial linear map defined on the span of a singleton. * `sup` takes two partial linear maps `f`, `g` that agree on the intersection of their domains, and returns the unique partial linear map on `f.domain ⊔ g.domain` that extends both `f` and `g`. * `Sup` takes a `directed_on (≤)` set of partial linear maps, and returns the unique partial linear map on the `Sup` of their domains that extends all these maps. Moreover, we define * `linear_pmap.graph` is the graph of the partial linear map viewed as a submodule of `E × F`. Partially defined maps are currently used in `mathlib` to prove Hahn-Banach theorem and its variations. Namely, `linear_pmap.Sup` implies that every chain of `linear_pmap`s is bounded above. They are also the basis for the theory of unbounded operators. -/ open set universes u v w /-- A `linear_pmap R E F` or `E →ₗ.[R] F` is a linear map from a submodule of `E` to `F`. -/ structure linear_pmap (R : Type u) [ring R] (E : Type v) [add_comm_group E] [module R E] (F : Type w) [add_comm_group F] [module R F] := (domain : submodule R E) (to_fun : domain →ₗ[R] F) notation E ` →ₗ.[`:25 R:25 `] `:0 F:0 := linear_pmap R E F variables {R : Type*} [ring R] {E : Type*} [add_comm_group E] [module R E] {F : Type*} [add_comm_group F] [module R F] {G : Type*} [add_comm_group G] [module R G] namespace linear_pmap open submodule instance : has_coe_to_fun (E →ₗ.[R] F) (λ f : E →ₗ.[R] F, f.domain → F) := ⟨λ f, f.to_fun⟩ @[simp] lemma to_fun_eq_coe (f : E →ₗ.[R] F) (x : f.domain) : f.to_fun x = f x := rfl @[ext] lemma ext {f g : E →ₗ.[R] F} (h : f.domain = g.domain) (h' : ∀ ⦃x : f.domain⦄ ⦃y : g.domain⦄ (h : (x:E) = y), f x = g y) : f = g := begin rcases f with ⟨f_dom, f⟩, rcases g with ⟨g_dom, g⟩, obtain rfl : f_dom = g_dom := h, obtain rfl : f = g := linear_map.ext (λ x, h' rfl), refl, end @[simp] lemma map_zero (f : E →ₗ.[R] F) : f 0 = 0 := f.to_fun.map_zero lemma ext_iff {f g : E →ₗ.[R] F} : f = g ↔ ∃ (domain_eq : f.domain = g.domain), ∀ ⦃x : f.domain⦄ ⦃y : g.domain⦄ (h : (x:E) = y), f x = g y := ⟨λ EQ, EQ ▸ ⟨rfl, λ x y h, by { congr, exact_mod_cast h }⟩, λ ⟨deq, feq⟩, ext deq feq⟩ lemma ext' {s : submodule R E} {f g : s →ₗ[R] F} (h : f = g) : mk s f = mk s g := h ▸ rfl lemma map_add (f : E →ₗ.[R] F) (x y : f.domain) : f (x + y) = f x + f y := f.to_fun.map_add x y lemma map_neg (f : E →ₗ.[R] F) (x : f.domain) : f (-x) = -f x := f.to_fun.map_neg x lemma map_sub (f : E →ₗ.[R] F) (x y : f.domain) : f (x - y) = f x - f y := f.to_fun.map_sub x y lemma map_smul (f : E →ₗ.[R] F) (c : R) (x : f.domain) : f (c • x) = c • f x := f.to_fun.map_smul c x @[simp] lemma mk_apply (p : submodule R E) (f : p →ₗ[R] F) (x : p) : mk p f x = f x := rfl /-- The unique `linear_pmap` on `R ∙ x` that sends `x` to `y`. This version works for modules over rings, and requires a proof of `∀ c, c • x = 0 → c • y = 0`. -/ noncomputable def mk_span_singleton' (x : E) (y : F) (H : ∀ c : R, c • x = 0 → c • y = 0) : E →ₗ.[R] F := { domain := R ∙ x, to_fun := have H : ∀ c₁ c₂ : R, c₁ • x = c₂ • x → c₁ • y = c₂ • y, { intros c₁ c₂ h, rw [← sub_eq_zero, ← sub_smul] at h ⊢, exact H _ h }, { to_fun := λ z, (classical.some (mem_span_singleton.1 z.prop) • y), map_add' := λ y z, begin rw [← add_smul], apply H, simp only [add_smul, sub_smul, classical.some_spec (mem_span_singleton.1 _)], apply coe_add end, map_smul' := λ c z, begin rw [smul_smul], apply H, simp only [mul_smul, classical.some_spec (mem_span_singleton.1 _)], apply coe_smul end } } @[simp] lemma domain_mk_span_singleton (x : E) (y : F) (H : ∀ c : R, c • x = 0 → c • y = 0) : (mk_span_singleton' x y H).domain = R ∙ x := rfl @[simp] lemma mk_span_singleton'_apply (x : E) (y : F) (H : ∀ c : R, c • x = 0 → c • y = 0) (c : R) (h) : mk_span_singleton' x y H ⟨c • x, h⟩ = c • y := begin dsimp [mk_span_singleton'], rw [← sub_eq_zero, ← sub_smul], apply H, simp only [sub_smul, one_smul, sub_eq_zero], apply classical.some_spec (mem_span_singleton.1 h), end @[simp] lemma mk_span_singleton'_apply_self (x : E) (y : F) (H : ∀ c : R, c • x = 0 → c • y = 0) (h) : mk_span_singleton' x y H ⟨x, h⟩ = y := by convert mk_span_singleton'_apply x y H 1 _; rwa one_smul /-- The unique `linear_pmap` on `span R {x}` that sends a non-zero vector `x` to `y`. This version works for modules over division rings. -/ @[reducible] noncomputable def mk_span_singleton {K E F : Type*} [division_ring K] [add_comm_group E] [module K E] [add_comm_group F] [module K F] (x : E) (y : F) (hx : x ≠ 0) : E →ₗ.[K] F := mk_span_singleton' x y $ λ c hc, (smul_eq_zero.1 hc).elim (λ hc, by rw [hc, zero_smul]) (λ hx', absurd hx' hx) lemma mk_span_singleton_apply (K : Type*) {E F : Type*} [division_ring K] [add_comm_group E] [module K E] [add_comm_group F] [module K F] {x : E} (hx : x ≠ 0) (y : F) : mk_span_singleton x y hx ⟨x, (submodule.mem_span_singleton_self x : x ∈ submodule.span K {x})⟩ = y := linear_pmap.mk_span_singleton'_apply_self _ _ _ _ /-- Projection to the first coordinate as a `linear_pmap` -/ protected def fst (p : submodule R E) (p' : submodule R F) : (E × F) →ₗ.[R] E := { domain := p.prod p', to_fun := (linear_map.fst R E F).comp (p.prod p').subtype } @[simp] lemma fst_apply (p : submodule R E) (p' : submodule R F) (x : p.prod p') : linear_pmap.fst p p' x = (x : E × F).1 := rfl /-- Projection to the second coordinate as a `linear_pmap` -/ protected def snd (p : submodule R E) (p' : submodule R F) : (E × F) →ₗ.[R] F := { domain := p.prod p', to_fun := (linear_map.snd R E F).comp (p.prod p').subtype } @[simp] lemma snd_apply (p : submodule R E) (p' : submodule R F) (x : p.prod p') : linear_pmap.snd p p' x = (x : E × F).2 := rfl instance : has_neg (E →ₗ.[R] F) := ⟨λ f, ⟨f.domain, -f.to_fun⟩⟩ @[simp] lemma neg_apply (f : E →ₗ.[R] F) (x) : (-f) x = -(f x) := rfl instance : has_le (E →ₗ.[R] F) := ⟨λ f g, f.domain ≤ g.domain ∧ ∀ ⦃x : f.domain⦄ ⦃y : g.domain⦄ (h : (x:E) = y), f x = g y⟩ lemma apply_comp_of_le {T S : E →ₗ.[R] F} (h : T ≤ S) (x : T.domain) : T x = S (submodule.of_le h.1 x) := h.2 rfl lemma exists_of_le {T S : E →ₗ.[R] F} (h : T ≤ S) (x : T.domain) : ∃ (y : S.domain), (x : E) = y ∧ T x = S y := ⟨⟨x.1, h.1 x.2⟩, ⟨rfl, h.2 rfl⟩⟩ lemma eq_of_le_of_domain_eq {f g : E →ₗ.[R] F} (hle : f ≤ g) (heq : f.domain = g.domain) : f = g := ext heq hle.2 /-- Given two partial linear maps `f`, `g`, the set of points `x` such that both `f` and `g` are defined at `x` and `f x = g x` form a submodule. -/ def eq_locus (f g : E →ₗ.[R] F) : submodule R E := { carrier := {x | ∃ (hf : x ∈ f.domain) (hg : x ∈ g.domain), f ⟨x, hf⟩ = g ⟨x, hg⟩}, zero_mem' := ⟨zero_mem _, zero_mem _, f.map_zero.trans g.map_zero.symm⟩, add_mem' := λ x y ⟨hfx, hgx, hx⟩ ⟨hfy, hgy, hy⟩, ⟨add_mem hfx hfy, add_mem hgx hgy, by erw [f.map_add ⟨x, hfx⟩ ⟨y, hfy⟩, g.map_add ⟨x, hgx⟩ ⟨y, hgy⟩, hx, hy]⟩, smul_mem' := λ c x ⟨hfx, hgx, hx⟩, ⟨smul_mem _ c hfx, smul_mem _ c hgx, by erw [f.map_smul c ⟨x, hfx⟩, g.map_smul c ⟨x, hgx⟩, hx]⟩ } instance : has_inf (E →ₗ.[R] F) := ⟨λ f g, ⟨f.eq_locus g, f.to_fun.comp $ of_le $ λ x hx, hx.fst⟩⟩ instance : has_bot (E →ₗ.[R] F) := ⟨⟨⊥, 0⟩⟩ instance : inhabited (E →ₗ.[R] F) := ⟨⊥⟩ instance : semilattice_inf (E →ₗ.[R] F) := { le := (≤), le_refl := λ f, ⟨le_refl f.domain, λ x y h, subtype.eq h ▸ rfl⟩, le_trans := λ f g h ⟨fg_le, fg_eq⟩ ⟨gh_le, gh_eq⟩, ⟨le_trans fg_le gh_le, λ x z hxz, have hxy : (x:E) = of_le fg_le x, from rfl, (fg_eq hxy).trans (gh_eq $ hxy.symm.trans hxz)⟩, le_antisymm := λ f g fg gf, eq_of_le_of_domain_eq fg (le_antisymm fg.1 gf.1), inf := (⊓), le_inf := λ f g h ⟨fg_le, fg_eq⟩ ⟨fh_le, fh_eq⟩, ⟨λ x hx, ⟨fg_le hx, fh_le hx, by refine (fg_eq _).symm.trans (fh_eq _); [exact ⟨x, hx⟩, refl, refl]⟩, λ x ⟨y, yg, hy⟩ h, by { apply fg_eq, exact h }⟩, inf_le_left := λ f g, ⟨λ x hx, hx.fst, λ x y h, congr_arg f $ subtype.eq $ by exact h⟩, inf_le_right := λ f g, ⟨λ x hx, hx.snd.fst, λ ⟨x, xf, xg, hx⟩ y h, hx.trans $ congr_arg g $ subtype.eq $ by exact h⟩ } instance : order_bot (E →ₗ.[R] F) := { bot := ⊥, bot_le := λ f, ⟨bot_le, λ x y h, have hx : x = 0, from subtype.eq ((mem_bot R).1 x.2), have hy : y = 0, from subtype.eq (h.symm.trans (congr_arg _ hx)), by rw [hx, hy, map_zero, map_zero]⟩ } lemma le_of_eq_locus_ge {f g : E →ₗ.[R] F} (H : f.domain ≤ f.eq_locus g) : f ≤ g := suffices f ≤ f ⊓ g, from le_trans this inf_le_right, ⟨H, λ x y hxy, ((inf_le_left : f ⊓ g ≤ f).2 hxy.symm).symm⟩ lemma domain_mono : strict_mono (@domain R _ E _ _ F _ _) := λ f g hlt, lt_of_le_of_ne hlt.1.1 $ λ heq, ne_of_lt hlt $ eq_of_le_of_domain_eq (le_of_lt hlt) heq private lemma sup_aux (f g : E →ₗ.[R] F) (h : ∀ (x : f.domain) (y : g.domain), (x:E) = y → f x = g y) : ∃ fg : ↥(f.domain ⊔ g.domain) →ₗ[R] F, ∀ (x : f.domain) (y : g.domain) (z), (x:E) + y = ↑z → fg z = f x + g y := begin choose x hx y hy hxy using λ z : f.domain ⊔ g.domain, mem_sup.1 z.prop, set fg := λ z, f ⟨x z, hx z⟩ + g ⟨y z, hy z⟩, have fg_eq : ∀ (x' : f.domain) (y' : g.domain) (z' : f.domain ⊔ g.domain) (H : (x':E) + y' = z'), fg z' = f x' + g y', { intros x' y' z' H, dsimp [fg], rw [add_comm, ← sub_eq_sub_iff_add_eq_add, eq_comm, ← map_sub, ← map_sub], apply h, simp only [← eq_sub_iff_add_eq] at hxy, simp only [add_subgroup_class.coe_sub, coe_mk, coe_mk, hxy, ← sub_add, ← sub_sub, sub_self, zero_sub, ← H], apply neg_add_eq_sub }, refine ⟨{ to_fun := fg, .. }, fg_eq⟩, { rintros ⟨z₁, hz₁⟩ ⟨z₂, hz₂⟩, rw [← add_assoc, add_right_comm (f _), ← map_add, add_assoc, ← map_add], apply fg_eq, simp only [coe_add, coe_mk, ← add_assoc], rw [add_right_comm (x _), hxy, add_assoc, hxy, coe_mk, coe_mk] }, { intros c z, rw [smul_add, ← map_smul, ← map_smul], apply fg_eq, simp only [coe_smul, coe_mk, ← smul_add, hxy, ring_hom.id_apply] }, end /-- Given two partial linear maps that agree on the intersection of their domains, `f.sup g h` is the unique partial linear map on `f.domain ⊔ g.domain` that agrees with `f` and `g`. -/ protected noncomputable def sup (f g : E →ₗ.[R] F) (h : ∀ (x : f.domain) (y : g.domain), (x:E) = y → f x = g y) : E →ₗ.[R] F := ⟨_, classical.some (sup_aux f g h)⟩ @[simp] lemma domain_sup (f g : E →ₗ.[R] F) (h : ∀ (x : f.domain) (y : g.domain), (x:E) = y → f x = g y) : (f.sup g h).domain = f.domain ⊔ g.domain := rfl lemma sup_apply {f g : E →ₗ.[R] F} (H : ∀ (x : f.domain) (y : g.domain), (x:E) = y → f x = g y) (x y z) (hz : (↑x:E) + ↑y = ↑z) : f.sup g H z = f x + g y := classical.some_spec (sup_aux f g H) x y z hz protected lemma left_le_sup (f g : E →ₗ.[R] F) (h : ∀ (x : f.domain) (y : g.domain), (x:E) = y → f x = g y) : f ≤ f.sup g h := begin refine ⟨le_sup_left, λ z₁ z₂ hz, _⟩, rw [← add_zero (f _), ← g.map_zero], refine (sup_apply h _ _ _ _).symm, simpa end protected lemma right_le_sup (f g : E →ₗ.[R] F) (h : ∀ (x : f.domain) (y : g.domain), (x:E) = y → f x = g y) : g ≤ f.sup g h := begin refine ⟨le_sup_right, λ z₁ z₂ hz, _⟩, rw [← zero_add (g _), ← f.map_zero], refine (sup_apply h _ _ _ _).symm, simpa end protected lemma sup_le {f g h : E →ₗ.[R] F} (H : ∀ (x : f.domain) (y : g.domain), (x:E) = y → f x = g y) (fh : f ≤ h) (gh : g ≤ h) : f.sup g H ≤ h := have Hf : f ≤ (f.sup g H) ⊓ h, from le_inf (f.left_le_sup g H) fh, have Hg : g ≤ (f.sup g H) ⊓ h, from le_inf (f.right_le_sup g H) gh, le_of_eq_locus_ge $ sup_le Hf.1 Hg.1 /-- Hypothesis for `linear_pmap.sup` holds, if `f.domain` is disjoint with `g.domain`. -/ lemma sup_h_of_disjoint (f g : E →ₗ.[R] F) (h : disjoint f.domain g.domain) (x : f.domain) (y : g.domain) (hxy : (x:E) = y) : f x = g y := begin rw [disjoint_def] at h, have hy : y = 0, from subtype.eq (h y (hxy ▸ x.2) y.2), have hx : x = 0, from subtype.eq (hxy.trans $ congr_arg _ hy), simp [*] end section smul variables {M N : Type*} [monoid M] [distrib_mul_action M F] [smul_comm_class R M F] variables [monoid N] [distrib_mul_action N F] [smul_comm_class R N F] instance : has_smul M (E →ₗ.[R] F) := ⟨λ a f, { domain := f.domain, to_fun := a • f.to_fun }⟩ @[simp] lemma smul_domain (a : M) (f : E →ₗ.[R] F) : (a • f).domain = f.domain := rfl lemma smul_apply (a : M) (f : E →ₗ.[R] F) (x : ((a • f).domain)) : (a • f) x = a • f x := rfl @[simp] lemma coe_smul (a : M) (f : E →ₗ.[R] F) : ⇑(a • f) = a • f := rfl instance [smul_comm_class M N F] : smul_comm_class M N (E →ₗ.[R] F) := ⟨λ a b f, ext' $ smul_comm a b f.to_fun⟩ instance [has_smul M N] [is_scalar_tower M N F] : is_scalar_tower M N (E →ₗ.[R] F) := ⟨λ a b f, ext' $ smul_assoc a b f.to_fun⟩ instance : mul_action M (E →ₗ.[R] F) := { smul := (•), one_smul := λ ⟨s, f⟩, ext' $ one_smul M f, mul_smul := λ a b f, ext' $ mul_smul a b f.to_fun } end smul section vadd instance : has_vadd (E →ₗ[R] F) (E →ₗ.[R] F) := ⟨λ f g, { domain := g.domain, to_fun := f.comp g.domain.subtype + g.to_fun }⟩ @[simp] lemma vadd_domain (f : E →ₗ[R] F) (g : E →ₗ.[R] F) : (f +ᵥ g).domain = g.domain := rfl lemma vadd_apply (f : E →ₗ[R] F) (g : E →ₗ.[R] F) (x : (f +ᵥ g).domain) : (f +ᵥ g) x = f x + g x := rfl @[simp] lemma coe_vadd (f : E →ₗ[R] F) (g : E →ₗ.[R] F) : ⇑(f +ᵥ g) = f.comp g.domain.subtype + g := rfl instance : add_action (E →ₗ[R] F) (E →ₗ.[R] F) := { vadd := (+ᵥ), zero_vadd := λ ⟨s, f⟩, ext' $ zero_add _, add_vadd := λ f₁ f₂ ⟨s, g⟩, ext' $ linear_map.ext $ λ x, add_assoc _ _ _ } end vadd section variables {K : Type*} [division_ring K] [module K E] [module K F] /-- Extend a `linear_pmap` to `f.domain ⊔ K ∙ x`. -/ noncomputable def sup_span_singleton (f : E →ₗ.[K] F) (x : E) (y : F) (hx : x ∉ f.domain) : E →ₗ.[K] F := f.sup (mk_span_singleton x y (λ h₀, hx $ h₀.symm ▸ f.domain.zero_mem)) $ sup_h_of_disjoint _ _ $ by simpa [disjoint_span_singleton] @[simp] lemma domain_sup_span_singleton (f : E →ₗ.[K] F) (x : E) (y : F) (hx : x ∉ f.domain) : (f.sup_span_singleton x y hx).domain = f.domain ⊔ K ∙ x := rfl @[simp] lemma sup_span_singleton_apply_mk (f : E →ₗ.[K] F) (x : E) (y : F) (hx : x ∉ f.domain) (x' : E) (hx' : x' ∈ f.domain) (c : K) : f.sup_span_singleton x y hx ⟨x' + c • x, mem_sup.2 ⟨x', hx', _, mem_span_singleton.2 ⟨c, rfl⟩, rfl⟩⟩ = f ⟨x', hx'⟩ + c • y := begin erw [sup_apply _ ⟨x', hx'⟩ ⟨c • x, _⟩, mk_span_singleton'_apply], refl, exact mem_span_singleton.2 ⟨c, rfl⟩ end end private lemma Sup_aux (c : set (E →ₗ.[R] F)) (hc : directed_on (≤) c) : ∃ f : ↥(Sup (domain '' c)) →ₗ[R] F, (⟨_, f⟩ : E →ₗ.[R] F) ∈ upper_bounds c := begin cases c.eq_empty_or_nonempty with ceq cne, { subst c, simp }, have hdir : directed_on (≤) (domain '' c), from directed_on_image.2 (hc.mono domain_mono.monotone), have P : Π x : Sup (domain '' c), {p : c // (x : E) ∈ p.val.domain }, { rintros x, apply classical.indefinite_description, have := (mem_Sup_of_directed (cne.image _) hdir).1 x.2, rwa [bex_image_iff, set_coe.exists'] at this }, set f : Sup (domain '' c) → F := λ x, (P x).val.val ⟨x, (P x).property⟩, have f_eq : ∀ (p : c) (x : Sup (domain '' c)) (y : p.1.1) (hxy : (x : E) = y), f x = p.1 y, { intros p x y hxy, rcases hc (P x).1.1 (P x).1.2 p.1 p.2 with ⟨q, hqc, hxq, hpq⟩, refine (hxq.2 _).trans (hpq.2 _).symm, exacts [of_le hpq.1 y, hxy, rfl] }, refine ⟨{ to_fun := f, .. }, _⟩, { intros x y, rcases hc (P x).1.1 (P x).1.2 (P y).1.1 (P y).1.2 with ⟨p, hpc, hpx, hpy⟩, set x' := of_le hpx.1 ⟨x, (P x).2⟩, set y' := of_le hpy.1 ⟨y, (P y).2⟩, rw [f_eq ⟨p, hpc⟩ x x' rfl, f_eq ⟨p, hpc⟩ y y' rfl, f_eq ⟨p, hpc⟩ (x + y) (x' + y') rfl, map_add] }, { intros c x, simp [f_eq (P x).1 (c • x) (c • ⟨x, (P x).2⟩) rfl, ← map_smul] }, { intros p hpc, refine ⟨le_Sup $ mem_image_of_mem domain hpc, λ x y hxy, eq.symm _⟩, exact f_eq ⟨p, hpc⟩ _ _ hxy.symm } end /-- Glue a collection of partially defined linear maps to a linear map defined on `Sup` of these submodules. -/ protected noncomputable def Sup (c : set (E →ₗ.[R] F)) (hc : directed_on (≤) c) : E →ₗ.[R] F := ⟨_, classical.some $ Sup_aux c hc⟩ protected lemma le_Sup {c : set (E →ₗ.[R] F)} (hc : directed_on (≤) c) {f : E →ₗ.[R] F} (hf : f ∈ c) : f ≤ linear_pmap.Sup c hc := classical.some_spec (Sup_aux c hc) hf protected lemma Sup_le {c : set (E →ₗ.[R] F)} (hc : directed_on (≤) c) {g : E →ₗ.[R] F} (hg : ∀ f ∈ c, f ≤ g) : linear_pmap.Sup c hc ≤ g := le_of_eq_locus_ge $ Sup_le $ λ _ ⟨f, hf, eq⟩, eq ▸ have f ≤ (linear_pmap.Sup c hc) ⊓ g, from le_inf (linear_pmap.le_Sup _ hf) (hg f hf), this.1 protected lemma Sup_apply {c : set (E →ₗ.[R] F)} (hc : directed_on (≤) c) {l : E →ₗ.[R] F} (hl : l ∈ c) (x : l.domain) : (linear_pmap.Sup c hc) ⟨x, (linear_pmap.le_Sup hc hl).1 x.2⟩ = l x := begin symmetry, apply (classical.some_spec (Sup_aux c hc) hl).2, refl, end end linear_pmap namespace linear_map /-- Restrict a linear map to a submodule, reinterpreting the result as a `linear_pmap`. -/ def to_pmap (f : E →ₗ[R] F) (p : submodule R E) : E →ₗ.[R] F := ⟨p, f.comp p.subtype⟩ @[simp] lemma to_pmap_apply (f : E →ₗ[R] F) (p : submodule R E) (x : p) : f.to_pmap p x = f x := rfl /-- Compose a linear map with a `linear_pmap` -/ def comp_pmap (g : F →ₗ[R] G) (f : E →ₗ.[R] F) : E →ₗ.[R] G := { domain := f.domain, to_fun := g.comp f.to_fun } @[simp] lemma comp_pmap_apply (g : F →ₗ[R] G) (f : E →ₗ.[R] F) (x) : g.comp_pmap f x = g (f x) := rfl end linear_map namespace linear_pmap /-- Restrict codomain of a `linear_pmap` -/ def cod_restrict (f : E →ₗ.[R] F) (p : submodule R F) (H : ∀ x, f x ∈ p) : E →ₗ.[R] p := { domain := f.domain, to_fun := f.to_fun.cod_restrict p H } /-- Compose two `linear_pmap`s -/ def comp (g : F →ₗ.[R] G) (f : E →ₗ.[R] F) (H : ∀ x : f.domain, f x ∈ g.domain) : E →ₗ.[R] G := g.to_fun.comp_pmap $ f.cod_restrict _ H /-- `f.coprod g` is the partially defined linear map defined on `f.domain × g.domain`, and sending `p` to `f p.1 + g p.2`. -/ def coprod (f : E →ₗ.[R] G) (g : F →ₗ.[R] G) : (E × F) →ₗ.[R] G := { domain := f.domain.prod g.domain, to_fun := (f.comp (linear_pmap.fst f.domain g.domain) (λ x, x.2.1)).to_fun + (g.comp (linear_pmap.snd f.domain g.domain) (λ x, x.2.2)).to_fun } @[simp] lemma coprod_apply (f : E →ₗ.[R] G) (g : F →ₗ.[R] G) (x) : f.coprod g x = f ⟨(x : E × F).1, x.2.1⟩ + g ⟨(x : E × F).2, x.2.2⟩ := rfl /-- Restrict a partially defined linear map to a submodule of `E` contained in `f.domain`. -/ def dom_restrict (f : E →ₗ.[R] F) (S : submodule R E) : E →ₗ.[R] F := ⟨S ⊓ f.domain, f.to_fun.comp (submodule.of_le (by simp))⟩ @[simp] lemma dom_restrict_domain (f : E →ₗ.[R] F) {S : submodule R E} : (f.dom_restrict S).domain = S ⊓ f.domain := rfl lemma dom_restrict_apply {f : E →ₗ.[R] F} {S : submodule R E} ⦃x : S ⊓ f.domain⦄ ⦃y : f.domain⦄ (h : (x : E) = y) : f.dom_restrict S x = f y := begin have : submodule.of_le (by simp) x = y := by { ext, simp[h] }, rw ←this, exact linear_pmap.mk_apply _ _ _, end lemma dom_restrict_le {f : E →ₗ.[R] F} {S : submodule R E} : f.dom_restrict S ≤ f := ⟨by simp, λ x y hxy, dom_restrict_apply hxy⟩ /-! ### Graph -/ section graph /-- The graph of a `linear_pmap` viewed as a submodule on `E × F`. -/ def graph (f : E →ₗ.[R] F) : submodule R (E × F) := f.to_fun.graph.map (f.domain.subtype.prod_map (linear_map.id : F →ₗ[R] F)) lemma mem_graph_iff' (f : E →ₗ.[R] F) {x : E × F} : x ∈ f.graph ↔ ∃ y : f.domain, (↑y, f y) = x := by simp [graph] @[simp] lemma mem_graph_iff (f : E →ₗ.[R] F) {x : E × F} : x ∈ f.graph ↔ ∃ y : f.domain, (↑y : E) = x.1 ∧ f y = x.2 := by { cases x, simp_rw [mem_graph_iff', prod.mk.inj_iff] } /-- The tuple `(x, f x)` is contained in the graph of `f`. -/ lemma mem_graph (f : E →ₗ.[R] F) (x : domain f) : ((x : E), f x) ∈ f.graph := by simp variables {M : Type*} [monoid M] [distrib_mul_action M F] [smul_comm_class R M F] (y : M) /-- The graph of `z • f` as a pushforward. -/ lemma smul_graph (f : E →ₗ.[R] F) (z : M) : (z • f).graph = f.graph.map ((linear_map.id : E →ₗ[R] E).prod_map (z • (linear_map.id : F →ₗ[R] F))) := begin ext x, cases x, split; intros h, { rw mem_graph_iff at h, rcases h with ⟨y, hy, h⟩, rw linear_pmap.smul_apply at h, rw submodule.mem_map, simp only [mem_graph_iff, linear_map.prod_map_apply, linear_map.id_coe, id.def, linear_map.smul_apply, prod.mk.inj_iff, prod.exists, exists_exists_and_eq_and], use [x_fst, y], simp [hy, h] }, rw submodule.mem_map at h, rcases h with ⟨x', hx', h⟩, cases x', simp only [linear_map.prod_map_apply, linear_map.id_coe, id.def, linear_map.smul_apply, prod.mk.inj_iff] at h, rw mem_graph_iff at hx' ⊢, rcases hx' with ⟨y, hy, hx'⟩, use y, rw [←h.1, ←h.2], simp[hy, hx'], end /-- The graph of `-f` as a pushforward. -/ lemma neg_graph (f : E →ₗ.[R] F) : (-f).graph = f.graph.map ((linear_map.id : E →ₗ[R] E).prod_map (-(linear_map.id : F →ₗ[R] F))) := begin ext, cases x, split; intros h, { rw mem_graph_iff at h, rcases h with ⟨y, hy, h⟩, rw linear_pmap.neg_apply at h, rw submodule.mem_map, simp only [mem_graph_iff, linear_map.prod_map_apply, linear_map.id_coe, id.def, linear_map.neg_apply, prod.mk.inj_iff, prod.exists, exists_exists_and_eq_and], use [x_fst, y], simp [hy, h] }, rw submodule.mem_map at h, rcases h with ⟨x', hx', h⟩, cases x', simp only [linear_map.prod_map_apply, linear_map.id_coe, id.def, linear_map.neg_apply, prod.mk.inj_iff] at h, rw mem_graph_iff at hx' ⊢, rcases hx' with ⟨y, hy, hx'⟩, use y, rw [←h.1, ←h.2], simp [hy, hx'], end lemma mem_graph_snd_inj (f : E →ₗ.[R] F) {x y : E} {x' y' : F} (hx : (x,x') ∈ f.graph) (hy : (y,y') ∈ f.graph) (hxy : x = y) : x' = y' := begin rw [mem_graph_iff] at hx hy, rcases hx with ⟨x'', hx1, hx2⟩, rcases hy with ⟨y'', hy1, hy2⟩, simp only at hx1 hx2 hy1 hy2, rw [←hx1, ←hy1, set_like.coe_eq_coe] at hxy, rw [←hx2, ←hy2, hxy], end lemma mem_graph_snd_inj' (f : E →ₗ.[R] F) {x y : E × F} (hx : x ∈ f.graph) (hy : y ∈ f.graph) (hxy : x.1 = y.1) : x.2 = y.2 := by { cases x, cases y, exact f.mem_graph_snd_inj hx hy hxy } /-- The property that `f 0 = 0` in terms of the graph. -/ lemma graph_fst_eq_zero_snd (f : E →ₗ.[R] F) {x : E} {x' : F} (h : (x,x') ∈ f.graph) (hx : x = 0) : x' = 0 := f.mem_graph_snd_inj h f.graph.zero_mem hx lemma mem_domain_iff {f : E →ₗ.[R] F} {x : E} : x ∈ f.domain ↔ ∃ y : F, (x,y) ∈ f.graph := begin split; intro h, { use f ⟨x, h⟩, exact f.mem_graph ⟨x, h⟩ }, cases h with y h, rw mem_graph_iff at h, cases h with x' h, simp only at h, rw ←h.1, simp, end lemma mem_domain_of_mem_graph {f : E →ₗ.[R] F} {x : E} {y : F} (h : (x,y) ∈ f.graph) : x ∈ f.domain := by { rw mem_domain_iff, exact ⟨y, h⟩ } lemma image_iff {f : E →ₗ.[R] F} {x : E} {y : F} (hx : x ∈ f.domain) : y = f ⟨x, hx⟩ ↔ (x, y) ∈ f.graph := begin rw mem_graph_iff, split; intro h, { use ⟨x, hx⟩, simp [h] }, rcases h with ⟨⟨x', hx'⟩, ⟨h1, h2⟩⟩, simp only [submodule.coe_mk] at h1 h2, simp only [←h2, h1], end lemma mem_range_iff {f : E →ₗ.[R] F} {y : F} : y ∈ set.range f ↔ ∃ x : E, (x,y) ∈ f.graph := begin split; intro h, { rw set.mem_range at h, rcases h with ⟨⟨x, hx⟩, h⟩, use x, rw ←h, exact f.mem_graph ⟨x, hx⟩ }, cases h with x h, rw mem_graph_iff at h, cases h with x h, rw set.mem_range, use x, simp only at h, rw h.2, end lemma mem_domain_iff_of_eq_graph {f g : E →ₗ.[R] F} (h : f.graph = g.graph) {x : E} : x ∈ f.domain ↔ x ∈ g.domain := by simp_rw [mem_domain_iff, h] lemma le_of_le_graph {f g : E →ₗ.[R] F} (h : f.graph ≤ g.graph) : f ≤ g := begin split, { intros x hx, rw mem_domain_iff at hx ⊢, cases hx with y hx, use y, exact h hx }, rintros ⟨x, hx⟩ ⟨y, hy⟩ hxy, rw image_iff, refine h _, simp only [submodule.coe_mk] at hxy, rw hxy at hx, rw ←image_iff hx, simp [hxy], end lemma le_graph_of_le {f g : E →ₗ.[R] F} (h : f ≤ g) : f.graph ≤ g.graph := begin intros x hx, rw mem_graph_iff at hx ⊢, cases hx with y hx, use y, { exact h.1 y.2 }, simp only [hx, submodule.coe_mk, eq_self_iff_true, true_and], convert hx.2, refine (h.2 _).symm, simp only [hx.1, submodule.coe_mk], end lemma le_graph_iff {f g : E →ₗ.[R] F} : f.graph ≤ g.graph ↔ f ≤ g := ⟨le_of_le_graph, le_graph_of_le⟩ lemma eq_of_eq_graph {f g : E →ₗ.[R] F} (h : f.graph = g.graph) : f = g := by {ext, exact mem_domain_iff_of_eq_graph h, exact (le_of_le_graph h.le).2 } end graph end linear_pmap namespace submodule section submodule_to_linear_pmap lemma exists_unique_from_graph {g : submodule R (E × F)} (hg : ∀ {x : E × F} (hx : x ∈ g) (hx' : x.fst = 0), x.snd = 0) {a : E} (ha : a ∈ g.map (linear_map.fst R E F)) : ∃! (b : F), (a,b) ∈ g := begin refine exists_unique_of_exists_of_unique _ _, { convert ha, simp }, intros y₁ y₂ hy₁ hy₂, have hy : ((0 : E), y₁ - y₂) ∈ g := begin convert g.sub_mem hy₁ hy₂, exact (sub_self _).symm, end, exact sub_eq_zero.mp (hg hy (by simp)), end /-- Auxiliary definition to unfold the existential quantifier. -/ noncomputable def val_from_graph {g : submodule R (E × F)} (hg : ∀ (x : E × F) (hx : x ∈ g) (hx' : x.fst = 0), x.snd = 0) {a : E} (ha : a ∈ g.map (linear_map.fst R E F)) : F := (exists_of_exists_unique (exists_unique_from_graph hg ha)).some lemma val_from_graph_mem {g : submodule R (E × F)} (hg : ∀ (x : E × F) (hx : x ∈ g) (hx' : x.fst = 0), x.snd = 0) {a : E} (ha : a ∈ g.map (linear_map.fst R E F)) : (a, val_from_graph hg ha) ∈ g := (exists_of_exists_unique (exists_unique_from_graph hg ha)).some_spec /-- Define a `linear_pmap` from its graph. -/ noncomputable def to_linear_pmap (g : submodule R (E × F)) (hg : ∀ (x : E × F) (hx : x ∈ g) (hx' : x.fst = 0), x.snd = 0) : E →ₗ.[R] F := { domain := g.map (linear_map.fst R E F), to_fun := { to_fun := λ x, val_from_graph hg x.2, map_add' := λ v w, begin have hadd := (g.map (linear_map.fst R E F)).add_mem v.2 w.2, have hvw := val_from_graph_mem hg hadd, have hvw' := g.add_mem (val_from_graph_mem hg v.2) (val_from_graph_mem hg w.2), rw [prod.mk_add_mk] at hvw', exact (exists_unique_from_graph hg hadd).unique hvw hvw', end, map_smul' := λ a v, begin have hsmul := (g.map (linear_map.fst R E F)).smul_mem a v.2, have hav := val_from_graph_mem hg hsmul, have hav' := g.smul_mem a (val_from_graph_mem hg v.2), rw [prod.smul_mk] at hav', exact (exists_unique_from_graph hg hsmul).unique hav hav', end } } lemma mem_graph_to_linear_pmap (g : submodule R (E × F)) (hg : ∀ (x : E × F) (hx : x ∈ g) (hx' : x.fst = 0), x.snd = 0) (x : g.map (linear_map.fst R E F)) : (x.val, g.to_linear_pmap hg x) ∈ g := val_from_graph_mem hg x.2 @[simp] lemma to_linear_pmap_graph_eq (g : submodule R (E × F)) (hg : ∀ (x : E × F) (hx : x ∈ g) (hx' : x.fst = 0), x.snd = 0) : (g.to_linear_pmap hg).graph = g := begin ext, split; intro hx, { rw [linear_pmap.mem_graph_iff] at hx, rcases hx with ⟨y,hx1,hx2⟩, convert g.mem_graph_to_linear_pmap hg y, rw [subtype.val_eq_coe], exact prod.ext hx1.symm hx2.symm }, rw linear_pmap.mem_graph_iff, cases x, have hx_fst : x_fst ∈ g.map (linear_map.fst R E F) := begin simp only [mem_map, linear_map.fst_apply, prod.exists, exists_and_distrib_right, exists_eq_right], exact ⟨x_snd, hx⟩, end, refine ⟨⟨x_fst, hx_fst⟩, subtype.coe_mk x_fst hx_fst, _⟩, exact (exists_unique_from_graph hg hx_fst).unique (val_from_graph_mem hg hx_fst) hx, end end submodule_to_linear_pmap end submodule
33a4b6621421e541a5982249d1a0a5a45362e3c0
367134ba5a65885e863bdc4507601606690974c1
/src/category_theory/concrete_category/basic.lean
aec43f92176106992c4bd40af2355510a1241581
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
6,927
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Johannes Hölzl, Reid Barton, Sean Leather, Yury Kudryashov -/ import category_theory.types import category_theory.epi_mono /-! # Concrete categories A concrete category is a category `C` with a fixed faithful functor `forget : C ⥤ Type*`. We define concrete categories using `class concrete_category`. In particular, we impose no restrictions on the carrier type `C`, so `Type` is a concrete category with the identity forgetful functor. Each concrete category `C` comes with a canonical faithful functor `forget C : C ⥤ Type*`. We say that a concrete category `C` admits a *forgetful functor* to a concrete category `D`, if it has a functor `forget₂ C D : C ⥤ D` such that `(forget₂ C D) ⋙ (forget D) = forget C`, see `class has_forget₂`. Due to `faithful.div_comp`, it suffices to verify that `forget₂.obj` and `forget₂.map` agree with the equality above; then `forget₂` will satisfy the functor laws automatically, see `has_forget₂.mk'`. Two classes helping construct concrete categories in the two most common cases are provided in the files `bundled_hom` and `unbundled_hom`, see their documentation for details. ## References See [Ahrens and Lumsdaine, *Displayed Categories*][ahrens2017] for related work. -/ universes w v v' u namespace category_theory /-- A concrete category is a category `C` with a fixed faithful functor `forget : C ⥤ Type`. Note that `concrete_category` potentially depends on three independent universe levels, * the universe level `w` appearing in `forget : C ⥤ Type w` * the universe level `v` of the morphisms (i.e. we have a `category.{v} C`) * the universe level `u` of the objects (i.e `C : Type u`) They are specified that order, to avoid unnecessary universe annotations. -/ class concrete_category (C : Type u) [category.{v} C] := (forget [] : C ⥤ Type w) [forget_faithful : faithful forget] attribute [instance] concrete_category.forget_faithful /-- The forgetful functor from a concrete category to `Type u`. -/ @[reducible] def forget (C : Type v) [category C] [concrete_category.{u} C] : C ⥤ Type u := concrete_category.forget C /-- Provide a coercion to `Type u` for a concrete category. This is not marked as an instance as it could potentially apply to every type, and so is too expensive in typeclass search. You can use it on particular examples as: ``` instance : has_coe_to_sort X := concrete_category.has_coe_to_sort X ``` -/ def concrete_category.has_coe_to_sort (C : Type v) [category C] [concrete_category C] : has_coe_to_sort C := { S := Type u, coe := (concrete_category.forget C).obj } section local attribute [instance] concrete_category.has_coe_to_sort variables {C : Type v} [category C] [concrete_category C] @[simp] lemma forget_obj_eq_coe {X : C} : (forget C).obj X = X := rfl /-- Usually a bundled hom structure already has a coercion to function that works with different universes. So we don't use this as a global instance. -/ def concrete_category.has_coe_to_fun {X Y : C} : has_coe_to_fun (X ⟶ Y) := { F := λ f, X → Y, coe := λ f, (forget _).map f } local attribute [instance] concrete_category.has_coe_to_fun /-- In any concrete category, we can test equality of morphisms by pointwise evaluations.-/ lemma concrete_category.hom_ext {X Y : C} (f g : X ⟶ Y) (w : ∀ x : X, f x = g x) : f = g := begin apply faithful.map_injective (forget C), ext, exact w x, end @[simp] lemma forget_map_eq_coe {X Y : C} (f : X ⟶ Y) : (forget C).map f = f := rfl @[simp] lemma coe_id {X : C} (x : X) : ((𝟙 X) : X → X) x = x := congr_fun ((forget _).map_id X) x @[simp] lemma coe_comp {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) (x : X) : (f ≫ g) x = g (f x) := congr_fun ((forget _).map_comp _ _) x @[simp] lemma coe_hom_inv_id {X Y : C} (f : X ≅ Y) (x : X) : f.inv (f.hom x) = x := congr_fun ((forget C).map_iso f).hom_inv_id x @[simp] lemma coe_inv_hom_id {X Y : C} (f : X ≅ Y) (y : Y) : f.hom (f.inv y) = y := congr_fun ((forget C).map_iso f).inv_hom_id y /-- In any concrete category, injective morphisms are monomorphisms. -/ lemma concrete_category.mono_of_injective {X Y : C} (f : X ⟶ Y) (i : function.injective f) : mono f := faithful_reflects_mono (forget C) ((mono_iff_injective f).2 i) /-- In any concrete category, surjective morphisms are epimorphisms. -/ lemma concrete_category.epi_of_surjective {X Y : C} (f : X ⟶ Y) (s : function.surjective f) : epi f := faithful_reflects_epi (forget C) ((epi_iff_surjective f).2 s) end instance concrete_category.types : concrete_category (Type u) := { forget := 𝟭 _ } /-- `has_forget₂ C D`, where `C` and `D` are both concrete categories, provides a functor `forget₂ C D : C ⥤ D` and a proof that `forget₂ ⋙ (forget D) = forget C`. -/ class has_forget₂ (C : Type v) (D : Type v') [category C] [concrete_category.{u} C] [category D] [concrete_category.{u} D] := (forget₂ : C ⥤ D) (forget_comp : forget₂ ⋙ (forget D) = forget C . obviously) /-- The forgetful functor `C ⥤ D` between concrete categories for which we have an instance `has_forget₂ C `. -/ @[reducible] def forget₂ (C : Type v) (D : Type v') [category C] [concrete_category C] [category D] [concrete_category D] [has_forget₂ C D] : C ⥤ D := has_forget₂.forget₂ instance forget_faithful (C : Type v) (D : Type v') [category C] [concrete_category C] [category D] [concrete_category D] [has_forget₂ C D] : faithful (forget₂ C D) := has_forget₂.forget_comp.faithful_of_comp instance induced_category.concrete_category {C : Type v} {D : Type v'} [category D] [concrete_category D] (f : C → D) : concrete_category (induced_category D f) := { forget := induced_functor f ⋙ forget D } instance induced_category.has_forget₂ {C : Type v} {D : Type v'} [category D] [concrete_category D] (f : C → D) : has_forget₂ (induced_category D f) D := { forget₂ := induced_functor f, forget_comp := rfl } /-- In order to construct a “partially forgetting” functor, we do not need to verify functor laws; it suffices to ensure that compositions agree with `forget₂ C D ⋙ forget D = forget C`. -/ def has_forget₂.mk' {C : Type v} {D : Type v'} [category C] [concrete_category C] [category D] [concrete_category D] (obj : C → D) (h_obj : ∀ X, (forget D).obj (obj X) = (forget C).obj X) (map : Π {X Y}, (X ⟶ Y) → (obj X ⟶ obj Y)) (h_map : ∀ {X Y} {f : X ⟶ Y}, (forget D).map (map f) == (forget C).map f) : has_forget₂ C D := { forget₂ := faithful.div _ _ _ @h_obj _ @h_map, forget_comp := by apply faithful.div_comp } instance has_forget_to_Type (C : Type v) [category C] [concrete_category C] : has_forget₂ C (Type u) := { forget₂ := forget C, forget_comp := functor.comp_id _ } end category_theory
7eab86e11472b2fdecc082cb5bbaba828a8d56a4
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/src/Init/Data/Random.lean
235ad0c6a025e52a8f72dfc5c0c2354a06bded8e
[ "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
4,119
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.System.IO import Init.Data.Int universes u /- Basic random number generator support based on the one available on the Haskell library -/ /- Interface for random number generators. -/ class RandomGen (g : Type u) where /- `range` returns the range of values returned by the generator. -/ range : g → Nat × Nat /- `next` operation returns a natural number that is uniformly distributed the range returned by `range` (including both end points), and a new generator. -/ next : g → Nat × g /- The 'split' operation allows one to obtain two distinct random number generators. This is very useful in functional programs (for example, when passing a random number generator down to recursive calls). -/ split : g → g × g /- "Standard" random number generator. -/ structure StdGen where s1 : Nat s2 : Nat instance : Inhabited StdGen := ⟨{ s1 := 0, s2 := 0 }⟩ def stdRange := (1, 2147483562) instance : Repr StdGen where reprPrec | ⟨s1, s2⟩, _ => Std.Format.bracket "⟨" (repr s1 ++ ", " ++ repr s2) "⟩" def stdNext : StdGen → Nat × StdGen | ⟨s1, s2⟩ => let s1 : Int := s1 let s2 : Int := s2 let k : Int := s1 / 53668 let s1' : Int := 40014 * ((s1 : Int) - k * 53668) - k * 12211 let s1'' : Int := if s1' < 0 then s1' + 2147483563 else s1' let k' : Int := s2 / 52774 let s2' : Int := 40692 * ((s2 : Int) - k' * 52774) - k' * 3791 let s2'' : Int := if s2' < 0 then s2' + 2147483399 else s2' let z : Int := s1'' - s2'' let z' : Int := if z < 1 then z + 2147483562 else z % 2147483562 (z'.toNat, ⟨s1''.toNat, s2''.toNat⟩) def stdSplit : StdGen → StdGen × StdGen | g@⟨s1, s2⟩ => let newS1 := if s1 = 2147483562 then 1 else s1 + 1 let newS2 := if s2 = 1 then 2147483398 else s2 - 1 let newG := (stdNext g).2 let leftG := StdGen.mk newS1 newG.2 let rightG := StdGen.mk newG.1 newS2 (leftG, rightG) instance : RandomGen StdGen := { range := fun _ => stdRange, next := stdNext, split := stdSplit } /-- Return a standard number generator. -/ def mkStdGen (s : Nat := 0) : StdGen := let q := s / 2147483562 let s1 := s % 2147483562 let s2 := q % 2147483398 ⟨s1 + 1, s2 + 1⟩ /- Auxiliary function for randomNatVal. Generate random values until we exceed the target magnitude. `genLo` and `genMag` are the generator lower bound and magnitude. The parameter `r` is the "remaining" magnitude. -/ private partial def randNatAux {gen : Type u} [RandomGen gen] (genLo genMag : Nat) : Nat → (Nat × gen) → Nat × gen | 0, (v, g) => (v, g) | r'@(r+1), (v, g) => let (x, g') := RandomGen.next g let v' := v*genMag + (x - genLo) randNatAux genLo genMag (r' / genMag - 1) (v', g') /-- Generate a random natural number in the interval [lo, hi]. -/ def randNat {gen : Type u} [RandomGen gen] (g : gen) (lo hi : Nat) : Nat × gen := let lo' := if lo > hi then hi else lo let hi' := if lo > hi then lo else hi let (genLo, genHi) := RandomGen.range g let genMag := genHi - genLo + 1 /- Probabilities of the most likely and least likely result will differ at most by a factor of (1 +- 1/q). Assuming the RandomGen is uniform, of course -/ let q := 1000 let k := hi' - lo' + 1 let tgtMag := k * q let (v, g') := randNatAux genLo genMag tgtMag (0, g) let v' := lo' + (v % k) (v', g') /-- Generate a random Boolean. -/ def randBool {gen : Type u} [RandomGen gen] (g : gen) : Bool × gen := let (v, g') := randNat g 0 1 (v = 1, g') initialize IO.stdGenRef : IO.Ref StdGen ← IO.mkRef mkStdGen def IO.setRandSeed (n : Nat) : IO Unit := IO.stdGenRef.set (mkStdGen n) def IO.rand (lo hi : Nat) : IO Nat := do let gen ← IO.stdGenRef.get let (r, gen) := randNat gen lo hi IO.stdGenRef.set gen pure r
03fd7848f17b3bb82cc1f755f53012819dd91938
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/measure_theory/measure/lebesgue.lean
c6977362895d192baae005c730932ee3d159a6fb
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,539
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Yury Kudryashov -/ import measure_theory.constructions.pi import measure_theory.measure.stieltjes import linear_algebra.matrix.transvection import dynamics.ergodic.measure_preserving import linear_algebra.determinant /-! # Lebesgue measure on the real line and on `ℝⁿ` We construct Lebesgue measure on the real line, as a particular case of Stieltjes measure associated to the function `x ↦ x`. We obtain as a consequence Lebesgue measure on `ℝⁿ`. We prove that they are translation invariant. We show that, on `ℝⁿ`, a linear map acts on Lebesgue measure by rescaling it through the absolute value of its determinant, in `real.map_linear_map_volume_pi_eq_smul_volume_pi`. More properties of the Lebesgue measure are deduced from this in `haar_lebesgue.lean`, where they are proved more generally for any additive Haar measure on a finite-dimensional real vector space. -/ noncomputable theory open classical set filter measure_theory open ennreal (of_real) open_locale big_operators ennreal nnreal topological_space /-! ### Definition of the Lebesgue measure and lengths of intervals -/ /-- Lebesgue measure on the Borel sigma algebra, giving measure `b - a` to the interval `[a, b]`. -/ instance real.measure_space : measure_space ℝ := ⟨stieltjes_function.id.measure⟩ namespace real variables {ι : Type*} [fintype ι] open_locale topological_space theorem volume_val (s) : volume s = stieltjes_function.id.measure s := rfl @[simp] lemma volume_Ico {a b : ℝ} : volume (Ico a b) = of_real (b - a) := by simp [volume_val] @[simp] lemma volume_Icc {a b : ℝ} : volume (Icc a b) = of_real (b - a) := by simp [volume_val] @[simp] lemma volume_Ioo {a b : ℝ} : volume (Ioo a b) = of_real (b - a) := by simp [volume_val] @[simp] lemma volume_Ioc {a b : ℝ} : volume (Ioc a b) = of_real (b - a) := by simp [volume_val] @[simp] lemma volume_singleton {a : ℝ} : volume ({a} : set ℝ) = 0 := by simp [volume_val] @[simp] lemma volume_univ : volume (univ : set ℝ) = ∞ := ennreal.eq_top_of_forall_nnreal_le $ λ r, calc (r : ℝ≥0∞) = volume (Icc (0 : ℝ) r) : by simp ... ≤ volume univ : measure_mono (subset_univ _) @[simp] lemma volume_ball (a r : ℝ) : volume (metric.ball a r) = of_real (2 * r) := by rw [ball_eq, volume_Ioo, ← sub_add, add_sub_cancel', two_mul] @[simp] lemma volume_closed_ball (a r : ℝ) : volume (metric.closed_ball a r) = of_real (2 * r) := by rw [closed_ball_eq, volume_Icc, ← sub_add, add_sub_cancel', two_mul] @[simp] lemma volume_emetric_ball (a : ℝ) (r : ℝ≥0∞) : volume (emetric.ball a r) = 2 * r := begin rcases eq_or_ne r ∞ with rfl|hr, { rw [metric.emetric_ball_top, volume_univ, two_mul, ennreal.top_add] }, { lift r to ℝ≥0 using hr, rw [metric.emetric_ball_nnreal, volume_ball, two_mul, ← nnreal.coe_add, ennreal.of_real_coe_nnreal, ennreal.coe_add, two_mul] } end @[simp] lemma volume_emetric_closed_ball (a : ℝ) (r : ℝ≥0∞) : volume (emetric.closed_ball a r) = 2 * r := begin rcases eq_or_ne r ∞ with rfl|hr, { rw [emetric.closed_ball_top, volume_univ, two_mul, ennreal.top_add] }, { lift r to ℝ≥0 using hr, rw [metric.emetric_closed_ball_nnreal, volume_closed_ball, two_mul, ← nnreal.coe_add, ennreal.of_real_coe_nnreal, ennreal.coe_add, two_mul] } end instance has_no_atoms_volume : has_no_atoms (volume : measure ℝ) := ⟨λ x, volume_singleton⟩ @[simp] lemma volume_interval {a b : ℝ} : volume (interval a b) = of_real (|b - a|) := by rw [interval, volume_Icc, max_sub_min_eq_abs] @[simp] lemma volume_Ioi {a : ℝ} : volume (Ioi a) = ∞ := top_unique $ le_of_tendsto' ennreal.tendsto_nat_nhds_top $ λ n, calc (n : ℝ≥0∞) = volume (Ioo a (a + n)) : by simp ... ≤ volume (Ioi a) : measure_mono Ioo_subset_Ioi_self @[simp] lemma volume_Ici {a : ℝ} : volume (Ici a) = ∞ := by simp [← measure_congr Ioi_ae_eq_Ici] @[simp] lemma volume_Iio {a : ℝ} : volume (Iio a) = ∞ := top_unique $ le_of_tendsto' ennreal.tendsto_nat_nhds_top $ λ n, calc (n : ℝ≥0∞) = volume (Ioo (a - n) a) : by simp ... ≤ volume (Iio a) : measure_mono Ioo_subset_Iio_self @[simp] lemma volume_Iic {a : ℝ} : volume (Iic a) = ∞ := by simp [← measure_congr Iio_ae_eq_Iic] instance locally_finite_volume : is_locally_finite_measure (volume : measure ℝ) := ⟨λ x, ⟨Ioo (x - 1) (x + 1), is_open.mem_nhds is_open_Ioo ⟨sub_lt_self _ zero_lt_one, lt_add_of_pos_right _ zero_lt_one⟩, by simp only [real.volume_Ioo, ennreal.of_real_lt_top]⟩⟩ instance is_finite_measure_restrict_Icc (x y : ℝ) : is_finite_measure (volume.restrict (Icc x y)) := ⟨by simp⟩ instance is_finite_measure_restrict_Ico (x y : ℝ) : is_finite_measure (volume.restrict (Ico x y)) := ⟨by simp⟩ instance is_finite_measure_restrict_Ioc (x y : ℝ) : is_finite_measure (volume.restrict (Ioc x y)) := ⟨by simp⟩ instance is_finite_measure_restrict_Ioo (x y : ℝ) : is_finite_measure (volume.restrict (Ioo x y)) := ⟨by simp⟩ /-! ### Volume of a box in `ℝⁿ` -/ lemma volume_Icc_pi {a b : ι → ℝ} : volume (Icc a b) = ∏ i, ennreal.of_real (b i - a i) := begin rw [← pi_univ_Icc, volume_pi_pi], { simp only [real.volume_Icc] }, { exact λ i, measurable_set_Icc } end @[simp] lemma volume_Icc_pi_to_real {a b : ι → ℝ} (h : a ≤ b) : (volume (Icc a b)).to_real = ∏ i, (b i - a i) := by simp only [volume_Icc_pi, ennreal.to_real_prod, ennreal.to_real_of_real (sub_nonneg.2 (h _))] lemma volume_pi_Ioo {a b : ι → ℝ} : volume (pi univ (λ i, Ioo (a i) (b i))) = ∏ i, ennreal.of_real (b i - a i) := (measure_congr measure.univ_pi_Ioo_ae_eq_Icc).trans volume_Icc_pi @[simp] lemma volume_pi_Ioo_to_real {a b : ι → ℝ} (h : a ≤ b) : (volume (pi univ (λ i, Ioo (a i) (b i)))).to_real = ∏ i, (b i - a i) := by simp only [volume_pi_Ioo, ennreal.to_real_prod, ennreal.to_real_of_real (sub_nonneg.2 (h _))] lemma volume_pi_Ioc {a b : ι → ℝ} : volume (pi univ (λ i, Ioc (a i) (b i))) = ∏ i, ennreal.of_real (b i - a i) := (measure_congr measure.univ_pi_Ioc_ae_eq_Icc).trans volume_Icc_pi @[simp] lemma volume_pi_Ioc_to_real {a b : ι → ℝ} (h : a ≤ b) : (volume (pi univ (λ i, Ioc (a i) (b i)))).to_real = ∏ i, (b i - a i) := by simp only [volume_pi_Ioc, ennreal.to_real_prod, ennreal.to_real_of_real (sub_nonneg.2 (h _))] lemma volume_pi_Ico {a b : ι → ℝ} : volume (pi univ (λ i, Ico (a i) (b i))) = ∏ i, ennreal.of_real (b i - a i) := (measure_congr measure.univ_pi_Ico_ae_eq_Icc).trans volume_Icc_pi @[simp] lemma volume_pi_Ico_to_real {a b : ι → ℝ} (h : a ≤ b) : (volume (pi univ (λ i, Ico (a i) (b i)))).to_real = ∏ i, (b i - a i) := by simp only [volume_pi_Ico, ennreal.to_real_prod, ennreal.to_real_of_real (sub_nonneg.2 (h _))] @[simp] lemma volume_pi_ball (a : ι → ℝ) {r : ℝ} (hr : 0 < r) : volume (metric.ball a r) = ennreal.of_real ((2 * r) ^ fintype.card ι) := begin simp only [volume_pi_ball a hr, volume_ball, finset.prod_const], exact (ennreal.of_real_pow (mul_nonneg zero_le_two hr.le) _).symm end @[simp] lemma volume_pi_closed_ball (a : ι → ℝ) {r : ℝ} (hr : 0 ≤ r) : volume (metric.closed_ball a r) = ennreal.of_real ((2 * r) ^ fintype.card ι) := begin simp only [volume_pi_closed_ball a hr, volume_closed_ball, finset.prod_const], exact (ennreal.of_real_pow (mul_nonneg zero_le_two hr) _).symm end lemma volume_le_diam (s : set ℝ) : volume s ≤ emetric.diam s := begin by_cases hs : metric.bounded s, { rw [real.ediam_eq hs, ← volume_Icc], exact volume.mono (real.subset_Icc_Inf_Sup_of_bounded hs) }, { rw metric.ediam_of_unbounded hs, exact le_top } end lemma volume_pi_le_prod_diam (s : set (ι → ℝ)) : volume s ≤ ∏ i : ι, emetric.diam (function.eval i '' s) := calc volume s ≤ volume (pi univ (λ i, closure (function.eval i '' s))) : volume.mono $ subset.trans (subset_pi_eval_image univ s) $ pi_mono $ λ i hi, subset_closure ... = ∏ i, volume (closure $ function.eval i '' s) : volume_pi_pi _ $ λ i, measurable_set_closure ... ≤ ∏ i : ι, emetric.diam (function.eval i '' s) : finset.prod_le_prod' $ λ i hi, (volume_le_diam _).trans_eq (emetric.diam_closure _) lemma volume_pi_le_diam_pow (s : set (ι → ℝ)) : volume s ≤ emetric.diam s ^ fintype.card ι := calc volume s ≤ ∏ i : ι, emetric.diam (function.eval i '' s) : volume_pi_le_prod_diam s ... ≤ ∏ i : ι, (1 : ℝ≥0) * emetric.diam s : finset.prod_le_prod' $ λ i hi, (lipschitz_with.eval i).ediam_image_le s ... = emetric.diam s ^ fintype.card ι : by simp only [ennreal.coe_one, one_mul, finset.prod_const, fintype.card] /-! ### Images of the Lebesgue measure under translation/multiplication in ℝ -/ lemma map_volume_add_left (a : ℝ) : measure.map ((+) a) volume = volume := eq.symm $ real.measure_ext_Ioo_rat $ λ p q, by simp [measure.map_apply (measurable_const_add a) measurable_set_Ioo, sub_sub_sub_cancel_right] @[simp] lemma volume_preimage_add_left (a : ℝ) (s : set ℝ) : volume (((+) a) ⁻¹' s) = volume s := calc volume (((+) a) ⁻¹' s) = measure.map ((+) a) volume s : ((homeomorph.add_left a).to_measurable_equiv.map_apply s).symm ... = volume s : by rw map_volume_add_left lemma map_volume_add_right (a : ℝ) : measure.map (+ a) volume = volume := by simpa only [add_comm] using real.map_volume_add_left a @[simp] lemma volume_preimage_add_right (a : ℝ) (s : set ℝ) : volume ((+ a) ⁻¹' s) = volume s := calc volume ((+ a) ⁻¹' s) = measure.map (+ a) volume s : ((homeomorph.add_right a).to_measurable_equiv.map_apply s).symm ... = volume s : by rw map_volume_add_right lemma smul_map_volume_mul_left {a : ℝ} (h : a ≠ 0) : ennreal.of_real (|a|) • measure.map ((*) a) volume = volume := begin refine (real.measure_ext_Ioo_rat $ λ p q, _).symm, cases lt_or_gt_of_ne h with h h, { simp only [real.volume_Ioo, measure.smul_apply, ← ennreal.of_real_mul (le_of_lt $ neg_pos.2 h), measure.map_apply (measurable_const_mul a) measurable_set_Ioo, neg_sub_neg, ← neg_mul_eq_neg_mul, preimage_const_mul_Ioo_of_neg _ _ h, abs_of_neg h, mul_sub, mul_div_cancel' _ (ne_of_lt h)] }, { simp only [real.volume_Ioo, measure.smul_apply, ← ennreal.of_real_mul (le_of_lt h), measure.map_apply (measurable_const_mul a) measurable_set_Ioo, preimage_const_mul_Ioo _ _ h, abs_of_pos h, mul_sub, mul_div_cancel' _ (ne_of_gt h)] } end lemma map_volume_mul_left {a : ℝ} (h : a ≠ 0) : measure.map ((*) a) volume = ennreal.of_real (|a⁻¹|) • volume := by conv_rhs { rw [← real.smul_map_volume_mul_left h, smul_smul, ← ennreal.of_real_mul (abs_nonneg _), ← abs_mul, inv_mul_cancel h, abs_one, ennreal.of_real_one, one_smul] } @[simp] lemma volume_preimage_mul_left {a : ℝ} (h : a ≠ 0) (s : set ℝ) : volume (((*) a) ⁻¹' s) = ennreal.of_real (abs a⁻¹) * volume s := calc volume (((*) a) ⁻¹' s) = measure.map ((*) a) volume s : ((homeomorph.mul_left₀ a h).to_measurable_equiv.map_apply s).symm ... = ennreal.of_real (abs a⁻¹) * volume s : by { rw map_volume_mul_left h, refl } lemma smul_map_volume_mul_right {a : ℝ} (h : a ≠ 0) : ennreal.of_real (|a|) • measure.map (* a) volume = volume := by simpa only [mul_comm] using real.smul_map_volume_mul_left h lemma map_volume_mul_right {a : ℝ} (h : a ≠ 0) : measure.map (* a) volume = ennreal.of_real (|a⁻¹|) • volume := by simpa only [mul_comm] using real.map_volume_mul_left h @[simp] lemma volume_preimage_mul_right {a : ℝ} (h : a ≠ 0) (s : set ℝ) : volume ((* a) ⁻¹' s) = ennreal.of_real (abs a⁻¹) * volume s := calc volume ((* a) ⁻¹' s) = measure.map (* a) volume s : ((homeomorph.mul_right₀ a h).to_measurable_equiv.map_apply s).symm ... = ennreal.of_real (abs a⁻¹) * volume s : by { rw map_volume_mul_right h, refl } @[simp] lemma map_volume_neg : measure.map has_neg.neg (volume : measure ℝ) = volume := eq.symm $ real.measure_ext_Ioo_rat $ λ p q, by simp [show measure.map has_neg.neg volume (Ioo (p : ℝ) q) = _, from measure.map_apply measurable_neg measurable_set_Ioo] /-! ### Images of the Lebesgue measure under translation/linear maps in ℝⁿ -/ lemma map_volume_pi_add_left (a : ι → ℝ) : measure.map ((+) a) volume = volume := begin refine (measure.pi_eq (λ s hs, _)).symm, have A : has_add.add a ⁻¹' (set.pi univ (λ (i : ι), s i)) = set.pi univ (λ (i : ι), ((+) (a i)) ⁻¹' (s i)), by { ext, simp }, rw [measure.map_apply (measurable_const_add a) (measurable_set.univ_pi_fintype hs), A, volume_pi_pi], { simp only [volume_preimage_add_left] }, { exact λ i, measurable_const_add (a i) (hs i) } end @[simp] lemma volume_pi_preimage_add_left (a : ι → ℝ) (s : set (ι → ℝ)) : volume (((+) a) ⁻¹' s) = volume s := calc volume (((+) a) ⁻¹' s) = measure.map ((+) a) volume s : ((homeomorph.add_left a).to_measurable_equiv.map_apply s).symm ... = volume s : by rw map_volume_pi_add_left open matrix /-- A diagonal matrix rescales Lebesgue according to its determinant. This is a special case of `real.map_matrix_volume_pi_eq_smul_volume_pi`, that one should use instead (and whose proof uses this particular case). -/ lemma smul_map_diagonal_volume_pi [decidable_eq ι] {D : ι → ℝ} (h : det (diagonal D) ≠ 0) : ennreal.of_real (abs (det (diagonal D))) • measure.map ((diagonal D).to_lin') volume = volume := begin refine (measure.pi_eq (λ s hs, _)).symm, simp only [det_diagonal, measure.coe_smul, algebra.id.smul_eq_mul, pi.smul_apply], rw [measure.map_apply _ (measurable_set.univ_pi_fintype hs)], swap, { exact continuous.measurable (linear_map.continuous_on_pi _) }, have : (matrix.to_lin' (diagonal D)) ⁻¹' (set.pi set.univ (λ (i : ι), s i)) = set.pi set.univ (λ (i : ι), ((*) (D i)) ⁻¹' (s i)), { ext f, simp only [linear_map.coe_proj, algebra.id.smul_eq_mul, linear_map.smul_apply, mem_univ_pi, mem_preimage, linear_map.pi_apply, diagonal_to_lin'] }, have B : ∀ i, of_real (abs (D i)) * volume (has_mul.mul (D i) ⁻¹' s i) = volume (s i), { assume i, have A : D i ≠ 0, { simp only [det_diagonal, ne.def] at h, exact finset.prod_ne_zero_iff.1 h i (finset.mem_univ i) }, rw [volume_preimage_mul_left A, ← mul_assoc, ← ennreal.of_real_mul (abs_nonneg _), ← abs_mul, mul_inv_cancel A, abs_one, ennreal.of_real_one, one_mul] }, rw [this, volume_pi_pi, finset.abs_prod, ennreal.of_real_prod_of_nonneg (λ i hi, abs_nonneg (D i)), ← finset.prod_mul_distrib], { simp only [B] }, { exact λ i, measurable_const_mul _ (hs i) }, end /-- A transvection preserves Lebesgue measure. -/ lemma map_transvection_volume_pi [decidable_eq ι] (t : transvection_struct ι ℝ) : measure.map (t.to_matrix.to_lin') volume = volume := begin /- We separate the coordinate along which there is a shearing from the other ones, and apply Fubini. Along this coordinate (and when all the other coordinates are fixed), it acts like a translation, and therefore preserves Lebesgue. -/ suffices H : measure_preserving t.to_matrix.to_lin' volume volume, by exact H.2, let p : ι → Prop := λ i, i ≠ t.i, let α : Type* := {x // p x}, let β : Type* := {x // ¬ (p x)}, let g : (α → ℝ) → (β → ℝ) → (β → ℝ) := λ a b, (λ x, t.c * a ⟨t.j, t.hij.symm⟩) + b, let F : (α → ℝ) × (β → ℝ) → (α → ℝ) × (β → ℝ) := λ p, (id p.1, g p.1 p.2), let e := equiv.pi_equiv_pi_subtype_prod p (λ (i : ι), ℝ), have : (t.to_matrix.to_lin' : (ι → ℝ) → (ι → ℝ)) = e.symm ∘ F ∘ e, { cases t, ext f k, simp only [linear_equiv.map_smul, dite_eq_ite, linear_map.id_coe, p, ite_not, algebra.id.smul_eq_mul, one_mul, dot_product, std_basis_matrix, equiv.pi_equiv_pi_subtype_prod_symm_apply, id.def, transvection, pi.add_apply, zero_mul, linear_map.smul_apply, function.comp_app, equiv.pi_equiv_pi_subtype_prod_apply, matrix.transvection_struct.to_matrix_mk, matrix.mul_vec, linear_equiv.map_add, ite_mul, e, matrix.to_lin'_apply, pi.smul_apply, subtype.coe_mk, g, linear_map.add_apply, finset.sum_congr, matrix.to_lin'_one], by_cases h : t_i = k, { simp only [h, true_and, finset.mem_univ, if_true, eq_self_iff_true, finset.sum_ite_eq, one_apply, boole_mul, add_comm], }, { simp only [h, ne.symm h, add_zero, if_false, finset.sum_const_zero, false_and, mul_zero] } }, rw this, have A : measure_preserving e volume volume := ⟨ measurable_pi_equiv_pi_subtype_prod (λ i, ℝ) _, (measure.map_pi_equiv_pi_subtype_prod (λ i, (volume : measure ℝ)) p : _) ⟩, have B : measure_preserving F volume volume, { have g_meas : measurable (function.uncurry g), { have : measurable (λ (c : (α → ℝ)), c ⟨t.j, t.hij.symm⟩) := measurable_pi_apply ⟨t.j, t.hij.symm⟩, refine measurable.add (measurable_pi_lambda _ (λ i, measurable.const_mul _ _)) measurable_snd, exact this.comp measurable_fst }, exact measure_preserving.skew_product (measure_preserving.id _) g_meas (eventually_of_forall (λ a, map_volume_pi_add_left _)) }, have C : measure_preserving e.symm volume volume := ⟨ (measurable_pi_equiv_pi_subtype_prod_symm (λ (i : ι), ℝ) p : _), (measure.map_pi_equiv_pi_subtype_prod_symm (λ (i : ι), volume) p : _) ⟩, exact (C.comp B).comp A, end /-- Any invertible matrix rescales Lebesgue measure through the absolute value of its determinant. -/ lemma map_matrix_volume_pi_eq_smul_volume_pi [decidable_eq ι] {M : matrix ι ι ℝ} (hM : det M ≠ 0) : measure.map (M.to_lin') volume = ennreal.of_real (abs (det M)⁻¹) • volume := begin -- This follows from the cases we have already proved, of diagonal matrices and transvections, -- as these matrices generate all invertible matrices. apply diagonal_transvection_induction_of_det_ne_zero _ M hM (λ D hD, _) (λ t, _) (λ A B hA hB IHA IHB, _), { conv_rhs { rw [← smul_map_diagonal_volume_pi hD] }, rw [smul_smul, ← ennreal.of_real_mul (abs_nonneg _), ← abs_mul, inv_mul_cancel hD, abs_one, ennreal.of_real_one, one_smul] }, { simp only [matrix.transvection_struct.det, ennreal.of_real_one, map_transvection_volume_pi, one_smul, _root_.inv_one, abs_one] }, { rw [to_lin'_mul, det_mul, linear_map.coe_comp, ← measure.map_map, IHB, linear_map.map_smul, IHA, smul_smul, ← ennreal.of_real_mul (abs_nonneg _), ← abs_mul, mul_comm, mul_inv₀], { apply continuous.measurable, apply linear_map.continuous_on_pi }, { apply continuous.measurable, apply linear_map.continuous_on_pi } } end /-- Any invertible linear map rescales Lebesgue measure through the absolute value of its determinant. -/ lemma map_linear_map_volume_pi_eq_smul_volume_pi {f : (ι → ℝ) →ₗ[ℝ] (ι → ℝ)} (hf : f.det ≠ 0) : measure.map f volume = ennreal.of_real (abs (f.det)⁻¹) • volume := begin -- this is deduced from the matrix case classical, let M := f.to_matrix', have A : f.det = det M, by simp only [linear_map.det_to_matrix'], have B : f = M.to_lin', by simp only [to_lin'_to_matrix'], rw [A, B], apply map_matrix_volume_pi_eq_smul_volume_pi, rwa A at hf end end real open_locale topological_space lemma filter.eventually.volume_pos_of_nhds_real {p : ℝ → Prop} {a : ℝ} (h : ∀ᶠ x in 𝓝 a, p x) : (0 : ℝ≥0∞) < volume {x | p x} := begin rcases h.exists_Ioo_subset with ⟨l, u, hx, hs⟩, refine lt_of_lt_of_le _ (measure_mono hs), simpa [-mem_Ioo] using hx.1.trans hx.2 end section region_between open_locale classical variable {α : Type*} /-- The region between two real-valued functions on an arbitrary set. -/ def region_between (f g : α → ℝ) (s : set α) : set (α × ℝ) := {p : α × ℝ | p.1 ∈ s ∧ p.2 ∈ Ioo (f p.1) (g p.1)} lemma region_between_subset (f g : α → ℝ) (s : set α) : region_between f g s ⊆ s.prod univ := by simpa only [prod_univ, region_between, set.preimage, set_of_subset_set_of] using λ a, and.left variables [measurable_space α] {μ : measure α} {f g : α → ℝ} {s : set α} /-- The region between two measurable functions on a measurable set is measurable. -/ lemma measurable_set_region_between (hf : measurable f) (hg : measurable g) (hs : measurable_set s) : measurable_set (region_between f g s) := begin dsimp only [region_between, Ioo, mem_set_of_eq, set_of_and], refine measurable_set.inter _ ((measurable_set_lt (hf.comp measurable_fst) measurable_snd).inter (measurable_set_lt measurable_snd (hg.comp measurable_fst))), convert hs.prod measurable_set.univ, simp only [and_true, mem_univ], end theorem volume_region_between_eq_lintegral' (hf : measurable f) (hg : measurable g) (hs : measurable_set s) : μ.prod volume (region_between f g s) = ∫⁻ y in s, ennreal.of_real ((g - f) y) ∂μ := begin rw measure.prod_apply, { have h : (λ x, volume {a | x ∈ s ∧ a ∈ Ioo (f x) (g x)}) = s.indicator (λ x, ennreal.of_real (g x - f x)), { funext x, rw indicator_apply, split_ifs, { have hx : {a | x ∈ s ∧ a ∈ Ioo (f x) (g x)} = Ioo (f x) (g x) := by simp [h, Ioo], simp only [hx, real.volume_Ioo, sub_zero] }, { have hx : {a | x ∈ s ∧ a ∈ Ioo (f x) (g x)} = ∅ := by simp [h], simp only [hx, measure_empty] } }, dsimp only [region_between, preimage_set_of_eq], rw [h, lintegral_indicator]; simp only [hs, pi.sub_apply] }, { exact measurable_set_region_between hf hg hs }, end /-- The volume of the region between two almost everywhere measurable functions on a measurable set can be represented as a Lebesgue integral. -/ theorem volume_region_between_eq_lintegral [sigma_finite μ] (hf : ae_measurable f (μ.restrict s)) (hg : ae_measurable g (μ.restrict s)) (hs : measurable_set s) : μ.prod volume (region_between f g s) = ∫⁻ y in s, ennreal.of_real ((g - f) y) ∂μ := begin have h₁ : (λ y, ennreal.of_real ((g - f) y)) =ᵐ[μ.restrict s] λ y, ennreal.of_real ((ae_measurable.mk g hg - ae_measurable.mk f hf) y) := (hg.ae_eq_mk.sub hf.ae_eq_mk).fun_comp _, have h₂ : (μ.restrict s).prod volume (region_between f g s) = (μ.restrict s).prod volume (region_between (ae_measurable.mk f hf) (ae_measurable.mk g hg) s), { apply measure_congr, apply eventually_eq.rfl.inter, exact ((ae_eq_comp' measurable_fst hf.ae_eq_mk measure.prod_fst_absolutely_continuous).comp₂ _ eventually_eq.rfl).inter (eventually_eq.rfl.comp₂ _ (ae_eq_comp' measurable_fst hg.ae_eq_mk measure.prod_fst_absolutely_continuous)) }, rw [lintegral_congr_ae h₁, ← volume_region_between_eq_lintegral' hf.measurable_mk hg.measurable_mk hs], convert h₂ using 1, { rw measure.restrict_prod_eq_prod_univ, exacts [ (measure.restrict_eq_self' (hs.prod measurable_set.univ) (region_between_subset f g s)).symm, hs], }, { rw measure.restrict_prod_eq_prod_univ, exacts [(measure.restrict_eq_self' (hs.prod measurable_set.univ) (region_between_subset (ae_measurable.mk f hf) (ae_measurable.mk g hg) s)).symm, hs] }, end theorem volume_region_between_eq_integral' [sigma_finite μ] (f_int : integrable_on f s μ) (g_int : integrable_on g s μ) (hs : measurable_set s) (hfg : f ≤ᵐ[μ.restrict s] g ) : μ.prod volume (region_between f g s) = ennreal.of_real (∫ y in s, (g - f) y ∂μ) := begin have h : g - f =ᵐ[μ.restrict s] (λ x, real.to_nnreal (g x - f x)), from hfg.mono (λ x hx, (real.coe_to_nnreal _ $ sub_nonneg.2 hx).symm), rw [volume_region_between_eq_lintegral f_int.ae_measurable g_int.ae_measurable hs, integral_congr_ae h, lintegral_congr_ae, lintegral_coe_eq_integral _ ((integrable_congr h).mp (g_int.sub f_int))], simpa only, end /-- If two functions are integrable on a measurable set, and one function is less than or equal to the other on that set, then the volume of the region between the two functions can be represented as an integral. -/ theorem volume_region_between_eq_integral [sigma_finite μ] (f_int : integrable_on f s μ) (g_int : integrable_on g s μ) (hs : measurable_set s) (hfg : ∀ x ∈ s, f x ≤ g x) : μ.prod volume (region_between f g s) = ennreal.of_real (∫ y in s, (g - f) y ∂μ) := volume_region_between_eq_integral' f_int g_int hs ((ae_restrict_iff' hs).mpr (eventually_of_forall hfg)) end region_between /- section vitali def vitali_aux_h (x : ℝ) (h : x ∈ Icc (0:ℝ) 1) : ∃ y ∈ Icc (0:ℝ) 1, ∃ q:ℚ, ↑q = x - y := ⟨x, h, 0, by simp⟩ def vitali_aux (x : ℝ) (h : x ∈ Icc (0:ℝ) 1) : ℝ := classical.some (vitali_aux_h x h) theorem vitali_aux_mem (x : ℝ) (h : x ∈ Icc (0:ℝ) 1) : vitali_aux x h ∈ Icc (0:ℝ) 1 := Exists.fst (classical.some_spec (vitali_aux_h x h):_) theorem vitali_aux_rel (x : ℝ) (h : x ∈ Icc (0:ℝ) 1) : ∃ q:ℚ, ↑q = x - vitali_aux x h := Exists.snd (classical.some_spec (vitali_aux_h x h):_) def vitali : set ℝ := {x | ∃ h, x = vitali_aux x h} theorem vitali_nonmeasurable : ¬ null_measurable_set measure_space.μ vitali := sorry end vitali -/
066c028a3a0b38a69a6817e3050e88d5f444e225
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/finite/card.lean
e916fa3a0192777e3639afd6dd0432ff4a9aa973
[ "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,432
lean
/- Copyright (c) 2022 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import set_theory.cardinal.finite /-! # Cardinality of finite types The cardinality of a finite type `α` is given by `nat.card α`. This function has the "junk value" of `0` for infinite types, but to ensure the function has valid output, one just needs to know that it's possible to produce a `finite` instance for the type. (Note: we could have defined a `finite.card` that required you to supply a `finite` instance, but (a) the function would be `noncomputable` anyway so there is no need to supply the instance and (b) the function would have a more complicated dependent type that easily leads to "motive not type correct" errors.) ## Implementation notes Theorems about `nat.card` are sometimes incidentally true for both finite and infinite types. If removing a finiteness constraint results in no loss in legibility, we remove it. We generally put such theorems into the `set_theory.cardinal.finite` module. -/ noncomputable theory open_locale classical variables {α β γ : Type*} /-- There is (noncomputably) an equivalence between a finite type `α` and `fin (nat.card α)`. -/ def finite.equiv_fin (α : Type*) [finite α] : α ≃ fin (nat.card α) := begin have := (finite.exists_equiv_fin α).some_spec.some, rwa nat.card_eq_of_equiv_fin this, end /-- Similar to `finite.equiv_fin` but with control over the term used for the cardinality. -/ def finite.equiv_fin_of_card_eq [finite α] {n : ℕ} (h : nat.card α = n) : α ≃ fin n := by { subst h, apply finite.equiv_fin } lemma nat.card_eq (α : Type*) : nat.card α = if h : finite α then by exactI @fintype.card α (fintype.of_finite α) else 0 := begin casesI finite_or_infinite α, { letI := fintype.of_finite α, simp only [*, nat.card_eq_fintype_card, dif_pos] }, { simp [*, not_finite_iff_infinite.mpr h] }, end lemma finite.card_pos_iff [finite α] : 0 < nat.card α ↔ nonempty α := begin haveI := fintype.of_finite α, rw [nat.card_eq_fintype_card, fintype.card_pos_iff], end lemma finite.card_pos [finite α] [h : nonempty α] : 0 < nat.card α := finite.card_pos_iff.mpr h namespace finite lemma cast_card_eq_mk {α : Type*} [finite α] : ↑(nat.card α) = cardinal.mk α := cardinal.cast_to_nat_of_lt_aleph_0 (cardinal.lt_aleph_0_of_finite α) lemma card_eq [finite α] [finite β] : nat.card α = nat.card β ↔ nonempty (α ≃ β) := by { haveI := fintype.of_finite α, haveI := fintype.of_finite β, simp [fintype.card_eq] } lemma card_le_one_iff_subsingleton [finite α] : nat.card α ≤ 1 ↔ subsingleton α := by { haveI := fintype.of_finite α, simp [fintype.card_le_one_iff_subsingleton] } lemma one_lt_card_iff_nontrivial [finite α] : 1 < nat.card α ↔ nontrivial α := by { haveI := fintype.of_finite α, simp [fintype.one_lt_card_iff_nontrivial] } lemma one_lt_card [finite α] [h : nontrivial α] : 1 < nat.card α := one_lt_card_iff_nontrivial.mpr h @[simp] lemma card_option [finite α] : nat.card (option α) = nat.card α + 1 := by { haveI := fintype.of_finite α, simp } lemma card_le_of_injective [finite β] (f : α → β) (hf : function.injective f) : nat.card α ≤ nat.card β := by { haveI := fintype.of_finite β, haveI := fintype.of_injective f hf, simpa using fintype.card_le_of_injective f hf } lemma card_le_of_embedding [finite β] (f : α ↪ β) : nat.card α ≤ nat.card β := card_le_of_injective _ f.injective lemma card_le_of_surjective [finite α] (f : α → β) (hf : function.surjective f) : nat.card β ≤ nat.card α := by { haveI := fintype.of_finite α, haveI := fintype.of_surjective f hf, simpa using fintype.card_le_of_surjective f hf } lemma card_eq_zero_iff [finite α] : nat.card α = 0 ↔ is_empty α := by { haveI := fintype.of_finite α, simp [fintype.card_eq_zero_iff] } /-- If `f` is injective, then `nat.card α ≤ nat.card β`. We must also assume `nat.card β = 0 → nat.card α = 0` since `nat.card` is defined to be `0` for infinite types. -/ lemma card_le_of_injective' {f : α → β} (hf : function.injective f) (h : nat.card β = 0 → nat.card α = 0) : nat.card α ≤ nat.card β := (or_not_of_imp h).cases_on (λ h, le_of_eq_of_le h zero_le') (λ h, @card_le_of_injective α β (nat.finite_of_card_ne_zero h) f hf) /-- If `f` is an embedding, then `nat.card α ≤ nat.card β`. We must also assume `nat.card β = 0 → nat.card α = 0` since `nat.card` is defined to be `0` for infinite types. -/ lemma card_le_of_embedding' (f : α ↪ β) (h : nat.card β = 0 → nat.card α = 0) : nat.card α ≤ nat.card β := card_le_of_injective' f.2 h /-- If `f` is surjective, then `nat.card β ≤ nat.card α`. We must also assume `nat.card α = 0 → nat.card β = 0` since `nat.card` is defined to be `0` for infinite types. -/ lemma card_le_of_surjective' {f : α → β} (hf : function.surjective f) (h : nat.card α = 0 → nat.card β = 0) : nat.card β ≤ nat.card α := (or_not_of_imp h).cases_on (λ h, le_of_eq_of_le h zero_le') (λ h, @card_le_of_surjective α β (nat.finite_of_card_ne_zero h) f hf) /-- NB: `nat.card` is defined to be `0` for infinite types. -/ lemma card_eq_zero_of_surjective {f : α → β} (hf : function.surjective f) (h : nat.card β = 0) : nat.card α = 0 := begin casesI finite_or_infinite β, { haveI := card_eq_zero_iff.mp h, haveI := function.is_empty f, exact nat.card_of_is_empty }, { haveI := infinite.of_surjective f hf, exact nat.card_eq_zero_of_infinite }, end /-- NB: `nat.card` is defined to be `0` for infinite types. -/ lemma card_eq_zero_of_injective [nonempty α] {f : α → β} (hf : function.injective f) (h : nat.card α = 0) : nat.card β = 0 := card_eq_zero_of_surjective (function.inv_fun_surjective hf) h /-- NB: `nat.card` is defined to be `0` for infinite types. -/ lemma card_eq_zero_of_embedding [nonempty α] (f : α ↪ β) (h : nat.card α = 0) : nat.card β = 0 := card_eq_zero_of_injective f.2 h lemma card_sum [finite α] [finite β] : nat.card (α ⊕ β) = nat.card α + nat.card β := by { haveI := fintype.of_finite α, haveI := fintype.of_finite β, simp } lemma card_image_le {s : set α} [finite s] (f : α → β) : nat.card (f '' s) ≤ nat.card s := card_le_of_surjective _ set.surjective_onto_image lemma card_range_le [finite α] (f : α → β) : nat.card (set.range f) ≤ nat.card α := card_le_of_surjective _ set.surjective_onto_range theorem card_subtype_le [finite α] (p : α → Prop) : nat.card {x // p x} ≤ nat.card α := by { haveI := fintype.of_finite α, simpa using fintype.card_subtype_le p } theorem card_subtype_lt [finite α] {p : α → Prop} {x : α} (hx : ¬ p x) : nat.card {x // p x} < nat.card α := by { haveI := fintype.of_finite α, simpa using fintype.card_subtype_lt hx } end finite namespace set lemma card_union_le (s t : set α) : nat.card ↥(s ∪ t) ≤ nat.card s + nat.card t := begin casesI _root_.finite_or_infinite ↥(s ∪ t) with h h, { rw [finite_coe_iff, finite_union, ←finite_coe_iff, ←finite_coe_iff] at h, casesI h, rw [←cardinal.nat_cast_le, nat.cast_add, finite.cast_card_eq_mk, finite.cast_card_eq_mk, finite.cast_card_eq_mk], exact cardinal.mk_union_le s t }, { exact nat.card_eq_zero_of_infinite.trans_le (zero_le _) }, end end set
acbae331bf4306ce0495727d181e720224996dd5
3dd1b66af77106badae6edb1c4dea91a146ead30
/tests/lean/hott/uuu.lean
d05878e5cec9fbcc79477833435f6f39ef335454
[ "Apache-2.0" ]
permissive
silky/lean
79c20c15c93feef47bb659a2cc139b26f3614642
df8b88dca2f8da1a422cb618cd476ef5be730546
refs/heads/master
1,610,737,587,697
1,406,574,534,000
1,406,574,534,000
22,362,176
1
0
null
null
null
null
UTF-8
Lean
false
false
5,313
lean
-- Porting Vladimir's file to Lean notation `assume` binders `,` r:(scoped f, f) := r notation `take` binders `,` r:(scoped f, f) := r inductive empty : Type inductive unit : Type := | tt : unit inductive nat : Type := | O : nat | S : nat → nat inductive paths {A : Type} (a : A) : A → Type := | idpath : paths a a inductive sum (A : Type) (B : Type) : Type := | inl : A -> sum A B | inr : B -> sum A B definition coprod := sum definition ii1fun {A : Type} (B : Type) (a : A) := inl B a definition ii2fun (A : Type) {B : Type} (b : B) := inr A b definition ii1 {A : Type} {B : Type} (a : A) := inl B a definition ii2 {A : Type} {B : Type} (b : B) := inl A b inductive total2 {T: Type} (P: T → Type) : Type := | tpair : Π (t : T) (tp : P t), total2 P definition pr1 {T : Type} {P : T → Type} (tp : total2 P) : T := total2_rec (λ a b, a) tp definition pr2 {T : Type} {P : T → Type} (tp : total2 P) : P (pr1 tp) := total2_rec (λ a b, b) tp inductive Phant (T : Type) : Type := | phant : Phant T definition fromempty {X : Type} : empty → X := λe, empty_rec (λe, X) e definition tounit {X : Type} : X → unit := λx, tt definition termfun {X : Type} (x : X) : unit → X := λt, x abbreviation idfun (T : Type) := λt : T, t abbreviation funcomp {X : Type} {Y : Type} {Z : Type} (f : X → Y) (g : Y → Z) := λx, g (f x) infixl `∘`:60 := funcomp definition iteration {T : Type} (f : T → T) (n : nat) : T → T := nat_rec (idfun T) (λ m fm, funcomp fm f) n definition adjev {X : Type} {Y : Type} (x : X) (f : X → Y) := f x definition adjev2 {X : Type} {Y : Type} (phi : ((X → Y) → Y ) → Y ) : X → Y := λx, phi (λf, f x) definition dirprod (X : Type) (Y : Type) := total2 (λ x : X, Y) definition dirprodpair {X : Type} {Y : Type} := @tpair _ (λ x : X, Y) definition dirprodadj {X : Type} {Y : Type} {Z : Type} (f : dirprod X Y → Z ) : X → Y → Z := λx y, f (dirprodpair x y) definition dirprodf {X : Type} {Y : Type} {X' : Type} {Y' : Type} (f : X → Y) (f' : X' → Y') (xx' : dirprod X X') : dirprod Y Y' := dirprodpair (f (pr1 xx')) (f' (pr2 xx')) definition ddualand {X : Type} {Y : Type} {P : Type} (xp : (X → P) → P) (yp : (Y → P) → P) : (dirprod X Y → P) → P := λ X0, let int1 [fact] := λ (ypp : (Y → P) → P) (x : X), yp (λ y : Y, X0 (dirprodpair x y)) in xp (int1 yp) definition neg (X : Type) : Type := X → empty definition negf {X : Type} {Y : Type} (f : X → Y) : neg Y → neg X := λ (phi : Y → empty) (x : X), phi (f x) definition dneg (X : Type) : Type := (X → empty) → empty definition dnegf {X : Type} {Y : Type} (f : X → Y) : dneg X → dneg Y := negf (negf f) definition todneg (X : Type) : X → dneg X := adjev definition dnegnegtoneg {X : Type} : dneg (neg X) → neg X := adjev2 lemma dneganddnegl1 {X : Type} {Y : Type} (dnx : dneg X) (dny : dneg Y) : neg (X → neg Y) := take X2 : X → neg Y, have X3 : dneg X → neg Y, from take xx : dneg X, dnegnegtoneg (dnegf X2 xx), dny (X3 dnx) definition logeq (X : Type) (Y : Type) := dirprod (X → Y) (Y → X) infix `<->`:25 := logeq infix `↔`:25 := logeq definition logeqnegs {X : Type} {Y : Type} (l : X ↔ Y) : (neg X) ↔ (neg Y) := dirprodpair (negf (pr2 l)) (negf (pr1 l)) infix `=`:50 := paths definition pathscomp0 {X : Type} {a b c : X} (e1 : a = b) (e2 : b = c) : a = c := paths_rec e1 e2 definition pathscomp0rid {X : Type} {a b : X} (e1 : a = b) : pathscomp0 e1 (idpath b) = e1 := idpath _ definition pathsinv0 {X : Type} {a b : X} (e : a = b) : b = a := paths_rec (idpath _) e definition transport {A : Type} {a b : A} {P : A → Type} (H1 : a = b) (H2 : P a) : P b := paths_rec H2 H1 infixr `▸`:75 := transport infixr `⬝`:75 := pathscomp0 postfix `⁻¹`:100 := pathsinv0 definition idinv {X : Type} (x : X) : (idpath x)⁻¹ = idpath x := idpath (idpath x) definition idtrans {A : Type} (x : A) : (idpath x) ⬝ (idpath x) = (idpath x) := idpath (idpath x) definition pathsinv0l {X : Type} {a b : X} (e : a = b) : e⁻¹ ⬝ e = idpath b := paths_rec (idinv a⁻¹ ▸ idtrans a) e definition pathsinv0r {A : Type} {x y : A} (p : x = y) : p⁻¹ ⬝ p = idpath y := paths_rec (idinv x⁻¹ ▸ idtrans x) p definition pathsinv0inv0 {A : Type} {x y : A} (p : x = y) : (p⁻¹)⁻¹ = p := paths_rec (idpath (idpath x)) p definition pathsdirprod {X : Type} {Y : Type} {x1 x2 : X} {y1 y2 : Y} (ex : x1 = x2) (ey : y1 = y2 ) : dirprodpair x1 y1 = dirprodpair x2 y2 := ex ▸ ey ▸ idpath (dirprodpair x1 y1) definition maponpaths {T1 : Type} {T2 : Type} (f : T1 → T2) {t1 t2 : T1} (e : t1 = t2) : f t1 = f t2 := e ▸ idpath (f t1) definition ap {T1 : Type} {T2 : Type} := @maponpaths T1 T2 definition maponpathscomp0 {X : Type} {Y : Type} {x y z : X} (f : X → Y) (p : x = y) (q : y = z) : ap f (p ⬝ q) = (ap f p) ⬝ (ap f q) := paths_rec (idpath _) q definition maponpathsinv0 {X : Type} {Y : Type} (f : X → Y) {x1 x2 : X} (e : x1 = x2 ) : ap f (e⁻¹) = (ap f e)⁻¹ := paths_rec (idpath _) e lemma maponpathsidfun {X : Type} {x x' : X} (e : x = x') : ap (idfun X) e = e := paths_rec (idpath _) e lemma maponpathscomp {X : Type} {Y : Type} {Z : Type} {x x' : X} (f : X → Y) (g : Y → Z) (e : x = x') : ap g (ap f e) = ap (f ∘ g) e := paths_rec (idpath _) e
04e5194dbf0b7e20ebc111529179b4a5369e50bd
80746c6dba6a866de5431094bf9f8f841b043d77
/src/data/list/alist.lean
2e6ef05795c540184e1e5e23a682364de81c3619
[ "Apache-2.0" ]
permissive
leanprover-fork/mathlib-backup
8b5c95c535b148fca858f7e8db75a76252e32987
0eb9db6a1a8a605f0cf9e33873d0450f9f0ae9b0
refs/heads/master
1,585,156,056,139
1,548,864,430,000
1,548,864,438,000
143,964,213
0
0
Apache-2.0
1,550,795,966,000
1,533,705,322,000
Lean
UTF-8
Lean
false
false
6,135
lean
/- Copyright (c) 2018 Sean Leather. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sean Leather, Mario Carneiro Association lists. -/ import data.list.sigma universes u v w open list /-- `alist α β` is a key-value map stored as a linked list. It is a wrapper around certain `list` functions with the added constraint that the list have unique keys. -/ structure alist (α : Type u) (β : α → Type v) : Type (max u v) := (entries : list (sigma β)) (nodupkeys : entries.nodupkeys) namespace alist variables {α : Type u} {β : α → Type v} @[extensionality] theorem ext : ∀ {s t : alist α β}, s.entries = t.entries → s = t | ⟨l₁, h₁⟩ ⟨l₂, h₂⟩ H := by congr' /-- The predicate `a ∈ s` means that `s` has a value associated to the key `a`. -/ instance : has_mem α (alist α β) := ⟨λ a s, ∃ b : β a, sigma.mk a b ∈ s.entries⟩ theorem mem_def {a : α} {s : alist α β} : a ∈ s ↔ ∃ b : β a, sigma.mk a b ∈ s.entries := iff.rfl theorem mem_of_perm {a : α} {s₁ s₂ : alist α β} (p : s₁.entries ~ s₂.entries) : a ∈ s₁ ↔ a ∈ s₂ := exists_congr $ λ b, mem_of_perm p /-- The list of keys of an association list. -/ def keys (s : alist α β) : list α := s.entries.map sigma.fst theorem mem_keys {a : α} {s : alist α β} : a ∈ s.keys ↔ a ∈ s := by rw [keys, mem_map]; exact ⟨λ ⟨⟨_, b⟩, h, rfl⟩, ⟨b, h⟩, λ ⟨b, h⟩, ⟨_, h, rfl⟩⟩ theorem keys_nodup (s : alist α β) : s.keys.nodup := s.nodupkeys /-- The empty association list. -/ instance : has_emptyc (alist α β) := ⟨⟨[], nodupkeys_nil⟩⟩ theorem not_mem_empty_entries {s : sigma β} : s ∉ (∅ : alist α β).entries := not_mem_nil _ theorem not_mem_empty {a : α} : a ∉ (∅ : alist α β) := λ ⟨b, h⟩, not_mem_empty_entries h @[simp] theorem keys_empty : (∅ : alist α β).keys = [] := rfl /-- The singleton association list. -/ def singleton (a : α) (b : β a) : alist α β := ⟨[⟨a, b⟩], nodupkeys_singleton _⟩ @[simp] theorem keys_singleton (a : α) (b : β a) : (singleton a b).keys = [a] := rfl variables [decidable_eq α] /-- Look up the value associated to a key in an association list. -/ def lookup (a : α) (s : alist α β) : option (β a) := s.entries.lookup a theorem lookup_is_some {a : α} {s : alist α β} : (s.lookup a).is_some ↔ a ∈ s := lookup_is_some theorem perm_lookup {a : α} {s₁ s₂ : alist α β} (p : s₁.entries ~ s₂.entries) : s₁.lookup a = s₂.lookup a := perm_lookup _ s₁.nodupkeys s₂.nodupkeys p instance (a : α) (s : alist α β) : decidable (a ∈ s) := decidable_of_iff _ lookup_is_some /-- Insert a key-value pair into an association list. If the key is already present it does nothing. -/ def insert (a : α) (b : β a) (s : alist α β) : alist α β := if h : a ∈ s then s else ⟨⟨a, b⟩ :: s.entries, nodup_cons.2 ⟨mt mem_keys.1 h, s.nodupkeys⟩⟩ @[simp] theorem insert_of_pos {a : α} {b : β a} {s : alist α β} (h : a ∈ s) : insert a b s = s := dif_pos h theorem insert_entries_of_neg {a : α} {b : β a} {s : alist α β} (h : a ∉ s) : (insert a b s).entries = ⟨a, b⟩ :: s.entries := by simp [insert, h] @[simp] theorem keys_insert (a : α) (b : β a) (s : alist α β) : (insert a b s).keys = _root_.insert a s.keys := begin by_cases a ∈ s, { simp [h, mem_keys.2 h] }, { simp [keys, insert_entries_of_neg h], exact (insert_of_not_mem (mt mem_keys.1 h)).symm } end @[simp] theorem mem_insert {a a' : α} {b : β a} {s : alist α β} : a' ∈ insert a b s ↔ a' = a ∨ a' ∈ s := by rw [← mem_keys, ← mem_keys]; simp theorem perm_insert {a : α} {b : β a} {s₁ s₂ : alist α β} (p : s₁.entries ~ s₂.entries) : (insert a b s₁).entries ~ (insert a b s₂).entries := begin by_cases a ∈ s₁, { simp [h, (mem_of_perm p).1 h, p] }, { simp [insert_entries_of_neg h, insert_entries_of_neg (mt (mem_of_perm p).2 h)], exact p.skip _ } end /-- Replace a key with a given value in an association list. If the key is not present it does nothing. -/ def replace (a : α) (b : β a) (s : alist α β) : alist α β := ⟨kreplace a b s.entries, (kreplace_nodupkeys a b).2 s.nodupkeys⟩ @[simp] theorem keys_replace (a : α) (b : β a) (s : alist α β) : (replace a b s).keys = s.keys := kreplace_map_fst _ _ _ @[simp] theorem mem_replace {a a' : α} {b : β a} {s : alist α β} : a' ∈ replace a b s ↔ a' ∈ s := by rw [← mem_keys, keys_replace, mem_keys] theorem perm_replace {a : α} {b : β a} {s₁ s₂ : alist α β} : s₁.entries ~ s₂.entries → (replace a b s₁).entries ~ (replace a b s₂).entries := perm_kreplace s₁.nodupkeys /-- Fold a function over the key-value pairs in the map. -/ def foldl {δ : Type w} (f : δ → Π a, β a → δ) (d : δ) (m : alist α β) : δ := m.entries.foldl (λ r a, f r a.1 a.2) d /-- Erase a key from the map. If the key is not present it does nothing. -/ def erase (a : α) (s : alist α β) : alist α β := ⟨kerase a s.entries, kerase_nodupkeys _ s.nodupkeys⟩ @[simp] theorem keys_erase (a : α) (s : alist α β) : (erase a s).keys = s.keys.erase a := by rw [erase_eq_erasep, keys, keys, erasep_map]; refl @[simp] theorem mem_erase {a a' : α} {s : alist α β} : a' ∈ erase a s ↔ a' ≠ a ∧ a' ∈ s := by rw [← mem_keys, keys_erase, mem_erase_iff_of_nodup s.keys_nodup, mem_keys] theorem perm_erase {a : α} {s₁ s₂ : alist α β} : s₁.entries ~ s₂.entries → (erase a s₁).entries ~ (erase a s₂).entries := perm_kerase s₁.nodupkeys /-- Erase a key from the map, and return the corresponding value, if found. -/ def extract (a : α) (s : alist α β) : option (β a) × alist α β := have (kextract a s.entries).2.nodupkeys, by rw [kextract_eq_lookup_kerase]; exact kerase_nodupkeys _ s.nodupkeys, match kextract a s.entries, this with | (b, l), h := (b, ⟨l, h⟩) end @[simp] theorem extract_eq_lookup_erase (a : α) (s : alist α β) : extract a s = (lookup a s, erase a s) := by simp [extract]; split; refl end alist
217ef8b183da0a67e69ec34343ed3ef8b644f682
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/topology/Top/epi_mono.lean
4a501ce34e30bff6c65e0eb848421eff3219ffdd
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
874
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton -/ import topology.Top.adjunctions import category_theory.epi_mono universe u open category_theory open Top namespace Top lemma epi_iff_surjective {X Y : Top.{u}} (f : X ⟶ Y) : epi f ↔ function.surjective f := begin suffices : epi f ↔ epi (forget.map f), { rw [this, category_theory.epi_iff_surjective], refl }, split, { apply left_adjoint_preserves_epi adj₂ }, { apply faithful_reflects_epi } end lemma mono_iff_injective {X Y : Top.{u}} (f : X ⟶ Y) : mono f ↔ function.injective f := begin suffices : mono f ↔ mono (forget.map f), { rw [this, category_theory.mono_iff_injective], refl }, split, { apply right_adjoint_preserves_mono adj₁ }, { apply faithful_reflects_mono } end end Top
d68eabe2b1f90df1ec29a0976f54fdac2896a0f7
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/combinatorics/simple_graph/coloring.lean
7f71a8f81b713de492777d7782985e7470e89f73
[ "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
15,599
lean
/- Copyright (c) 2021 Arthur Paulino. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Arthur Paulino, Kyle Miller -/ import combinatorics.simple_graph.clique import data.nat.lattice import data.setoid.partition import order.antichain /-! # Graph Coloring > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This module defines colorings of simple graphs (also known as proper colorings in the literature). A graph coloring is the attribution of "colors" to all of its vertices such that adjacent vertices have different colors. A coloring can be represented as a homomorphism into a complete graph, whose vertices represent the colors. ## Main definitions * `G.coloring α` is the type of `α`-colorings of a simple graph `G`, with `α` being the set of available colors. The type is defined to be homomorphisms from `G` into the complete graph on `α`, and colorings have a coercion to `V → α`. * `G.colorable n` is the proposition that `G` is `n`-colorable, which is whether there exists a coloring with at most *n* colors. * `G.chromatic_number` is the minimal `n` such that `G` is `n`-colorable, or `0` if it cannot be colored with finitely many colors. * `C.color_class c` is the set of vertices colored by `c : α` in the coloring `C : G.coloring α`. * `C.color_classes` is the set containing all color classes. ## Todo: * Gather material from: * https://github.com/leanprover-community/mathlib/blob/simple_graph_matching/src/combinatorics/simple_graph/coloring.lean * https://github.com/kmill/lean-graphcoloring/blob/master/src/graph.lean * Trees * Planar graphs * Chromatic polynomials * develop API for partial colorings, likely as colorings of subgraphs (`H.coe.coloring α`) -/ universes u v namespace simple_graph variables {V : Type u} (G : simple_graph V) /-- An `α`-coloring of a simple graph `G` is a homomorphism of `G` into the complete graph on `α`. This is also known as a proper coloring. -/ abbreviation coloring (α : Type v) := G →g (⊤ : simple_graph α) variables {G} {α : Type v} (C : G.coloring α) lemma coloring.valid {v w : V} (h : G.adj v w) : C v ≠ C w := C.map_rel h /-- Construct a term of `simple_graph.coloring` using a function that assigns vertices to colors and a proof that it is as proper coloring. (Note: this is a definitionally the constructor for `simple_graph.hom`, but with a syntactically better proper coloring hypothesis.) -/ @[pattern] def coloring.mk (color : V → α) (valid : ∀ {v w : V}, G.adj v w → color v ≠ color w) : G.coloring α := ⟨color, @valid⟩ /-- The color class of a given color. -/ def coloring.color_class (c : α) : set V := {v : V | C v = c} /-- The set containing all color classes. -/ def coloring.color_classes : set (set V) := (setoid.ker C).classes lemma coloring.mem_color_class (v : V) : v ∈ C.color_class (C v) := by exact rfl lemma coloring.color_classes_is_partition : setoid.is_partition C.color_classes := setoid.is_partition_classes (setoid.ker C) lemma coloring.mem_color_classes {v : V} : C.color_class (C v) ∈ C.color_classes := ⟨v, rfl⟩ lemma coloring.color_classes_finite [finite α] : C.color_classes.finite := setoid.finite_classes_ker _ lemma coloring.card_color_classes_le [fintype α] [fintype C.color_classes] : fintype.card C.color_classes ≤ fintype.card α := setoid.card_classes_ker_le C lemma coloring.not_adj_of_mem_color_class {c : α} {v w : V} (hv : v ∈ C.color_class c) (hw : w ∈ C.color_class c) : ¬G.adj v w := λ h, C.valid h (eq.trans hv (eq.symm hw)) lemma coloring.color_classes_independent (c : α) : is_antichain G.adj (C.color_class c) := λ v hv w hw h, C.not_adj_of_mem_color_class hv hw -- TODO make this computable noncomputable instance [fintype V] [fintype α] : fintype (coloring G α) := begin classical, change fintype (rel_hom G.adj (⊤ : simple_graph α).adj), apply fintype.of_injective _ rel_hom.coe_fn_injective, apply_instance, end variables (G) /-- Whether a graph can be colored by at most `n` colors. -/ def colorable (n : ℕ) : Prop := nonempty (G.coloring (fin n)) /-- The coloring of an empty graph. -/ def coloring_of_is_empty [is_empty V] : G.coloring α := coloring.mk is_empty_elim (λ v, is_empty_elim) lemma colorable_of_is_empty [is_empty V] (n : ℕ) : G.colorable n := ⟨G.coloring_of_is_empty⟩ lemma is_empty_of_colorable_zero (h : G.colorable 0) : is_empty V := begin split, intro v, obtain ⟨i, hi⟩ := h.some v, exact nat.not_lt_zero _ hi, end /-- The "tautological" coloring of a graph, using the vertices of the graph as colors. -/ def self_coloring : G.coloring V := coloring.mk id (λ v w, G.ne_of_adj) /-- The chromatic number of a graph is the minimal number of colors needed to color it. If `G` isn't colorable with finitely many colors, this will be 0. -/ noncomputable def chromatic_number : ℕ := Inf { n : ℕ | G.colorable n } /-- Given an embedding, there is an induced embedding of colorings. -/ def recolor_of_embedding {α β : Type*} (f : α ↪ β) : G.coloring α ↪ G.coloring β := { to_fun := λ C, (embedding.complete_graph f).to_hom.comp C, inj' := begin -- this was strangely painful; seems like missing lemmas about embeddings intros C C' h, dsimp only at h, ext v, apply (embedding.complete_graph f).inj', change ((embedding.complete_graph f).to_hom.comp C) v = _, rw h, refl, end } /-- Given an equivalence, there is an induced equivalence between colorings. -/ def recolor_of_equiv {α β : Type*} (f : α ≃ β) : G.coloring α ≃ G.coloring β := { to_fun := G.recolor_of_embedding f.to_embedding, inv_fun := G.recolor_of_embedding f.symm.to_embedding, left_inv := λ C, by { ext v, apply equiv.symm_apply_apply }, right_inv := λ C, by { ext v, apply equiv.apply_symm_apply } } /-- There is a noncomputable embedding of `α`-colorings to `β`-colorings if `β` has at least as large a cardinality as `α`. -/ noncomputable def recolor_of_card_le {α β : Type*} [fintype α] [fintype β] (hn : fintype.card α ≤ fintype.card β) : G.coloring α ↪ G.coloring β := G.recolor_of_embedding $ (function.embedding.nonempty_of_card_le hn).some variables {G} lemma colorable.mono {n m : ℕ} (h : n ≤ m) (hc : G.colorable n) : G.colorable m := ⟨G.recolor_of_card_le (by simp [h]) hc.some⟩ lemma coloring.to_colorable [fintype α] (C : G.coloring α) : G.colorable (fintype.card α) := ⟨G.recolor_of_card_le (by simp) C⟩ lemma colorable_of_fintype (G : simple_graph V) [fintype V] : G.colorable (fintype.card V) := G.self_coloring.to_colorable /-- Noncomputably get a coloring from colorability. -/ noncomputable def colorable.to_coloring [fintype α] {n : ℕ} (hc : G.colorable n) (hn : n ≤ fintype.card α) : G.coloring α := begin rw ←fintype.card_fin n at hn, exact G.recolor_of_card_le hn hc.some, end lemma colorable.of_embedding {V' : Type*} {G' : simple_graph V'} (f : G ↪g G') {n : ℕ} (h : G'.colorable n) : G.colorable n := ⟨(h.to_coloring (by simp)).comp f⟩ lemma colorable_iff_exists_bdd_nat_coloring (n : ℕ) : G.colorable n ↔ ∃ (C : G.coloring ℕ), ∀ v, C v < n := begin split, { rintro hc, have C : G.coloring (fin n) := hc.to_coloring (by simp), let f := embedding.complete_graph fin.coe_embedding, use f.to_hom.comp C, intro v, cases C with color valid, exact fin.is_lt (color v), }, { rintro ⟨C, Cf⟩, refine ⟨coloring.mk _ _⟩, { exact λ v, ⟨C v, Cf v⟩, }, { rintro v w hvw, simp only [fin.mk_eq_mk, ne.def], exact C.valid hvw, } } end lemma colorable_set_nonempty_of_colorable {n : ℕ} (hc : G.colorable n) : {n : ℕ | G.colorable n}.nonempty := ⟨n, hc⟩ lemma chromatic_number_bdd_below : bdd_below {n : ℕ | G.colorable n} := ⟨0, λ _ _, zero_le _⟩ lemma chromatic_number_le_of_colorable {n : ℕ} (hc : G.colorable n) : G.chromatic_number ≤ n := begin rw chromatic_number, apply cInf_le chromatic_number_bdd_below, fsplit, exact classical.choice hc, end lemma chromatic_number_le_card [fintype α] (C : G.coloring α) : G.chromatic_number ≤ fintype.card α := cInf_le chromatic_number_bdd_below C.to_colorable lemma colorable_chromatic_number {m : ℕ} (hc : G.colorable m) : G.colorable G.chromatic_number := begin dsimp only [chromatic_number], rw nat.Inf_def, apply nat.find_spec, exact colorable_set_nonempty_of_colorable hc, end lemma colorable_chromatic_number_of_fintype (G : simple_graph V) [finite V] : G.colorable G.chromatic_number := by { casesI nonempty_fintype V, exact colorable_chromatic_number G.colorable_of_fintype } lemma chromatic_number_le_one_of_subsingleton (G : simple_graph V) [subsingleton V] : G.chromatic_number ≤ 1 := begin rw chromatic_number, apply cInf_le chromatic_number_bdd_below, fsplit, refine coloring.mk (λ _, 0) _, intros v w, rw subsingleton.elim v w, simp, end lemma chromatic_number_eq_zero_of_isempty (G : simple_graph V) [is_empty V] : G.chromatic_number = 0 := begin rw ←nonpos_iff_eq_zero, apply cInf_le chromatic_number_bdd_below, apply colorable_of_is_empty, end lemma is_empty_of_chromatic_number_eq_zero (G : simple_graph V) [finite V] (h : G.chromatic_number = 0) : is_empty V := begin have h' := G.colorable_chromatic_number_of_fintype, rw h at h', exact G.is_empty_of_colorable_zero h', end lemma chromatic_number_pos [nonempty V] {n : ℕ} (hc : G.colorable n) : 0 < G.chromatic_number := begin apply le_cInf (colorable_set_nonempty_of_colorable hc), intros m hm, by_contra h', simp only [not_le, nat.lt_one_iff] at h', subst h', obtain ⟨i, hi⟩ := hm.some (classical.arbitrary V), exact nat.not_lt_zero _ hi, end lemma colorable_of_chromatic_number_pos (h : 0 < G.chromatic_number) : G.colorable G.chromatic_number := begin obtain ⟨h, hn⟩ := nat.nonempty_of_pos_Inf h, exact colorable_chromatic_number hn, end lemma colorable.mono_left {G' : simple_graph V} (h : G ≤ G') {n : ℕ} (hc : G'.colorable n) : G.colorable n := ⟨hc.some.comp (hom.map_spanning_subgraphs h)⟩ lemma colorable.chromatic_number_le_of_forall_imp {V' : Type*} {G' : simple_graph V'} {m : ℕ} (hc : G'.colorable m) (h : ∀ n, G'.colorable n → G.colorable n) : G.chromatic_number ≤ G'.chromatic_number := begin apply cInf_le chromatic_number_bdd_below, apply h, apply colorable_chromatic_number hc, end lemma colorable.chromatic_number_mono (G' : simple_graph V) {m : ℕ} (hc : G'.colorable m) (h : G ≤ G') : G.chromatic_number ≤ G'.chromatic_number := hc.chromatic_number_le_of_forall_imp (λ n, colorable.mono_left h) lemma colorable.chromatic_number_mono_of_embedding {V' : Type*} {G' : simple_graph V'} {n : ℕ} (h : G'.colorable n) (f : G ↪g G') : G.chromatic_number ≤ G'.chromatic_number := h.chromatic_number_le_of_forall_imp (λ _, colorable.of_embedding f) lemma chromatic_number_eq_card_of_forall_surj [fintype α] (C : G.coloring α) (h : ∀ (C' : G.coloring α), function.surjective C') : G.chromatic_number = fintype.card α := begin apply le_antisymm, { apply chromatic_number_le_card C, }, { by_contra hc, rw not_le at hc, obtain ⟨n, cn, hc⟩ := exists_lt_of_cInf_lt (colorable_set_nonempty_of_colorable C.to_colorable) hc, rw ←fintype.card_fin n at hc, have f := (function.embedding.nonempty_of_card_le (le_of_lt hc)).some, have C' := cn.some, specialize h (G.recolor_of_embedding f C'), change function.surjective (f ∘ C') at h, have h1 : function.surjective f := function.surjective.of_comp h, have h2 := fintype.card_le_of_surjective _ h1, exact nat.lt_le_antisymm hc h2, }, end lemma chromatic_number_bot [nonempty V] : (⊥ : simple_graph V).chromatic_number = 1 := begin let C : (⊥ : simple_graph V).coloring (fin 1) := coloring.mk (λ _, 0) (λ v w h, false.elim h), apply le_antisymm, { exact chromatic_number_le_card C, }, { exact chromatic_number_pos C.to_colorable, }, end @[simp] lemma chromatic_number_top [fintype V] : (⊤ : simple_graph V).chromatic_number = fintype.card V := begin apply chromatic_number_eq_card_of_forall_surj (self_coloring _), intro C, rw ←finite.injective_iff_surjective, intros v w, contrapose, intro h, exact C.valid h, end lemma chromatic_number_top_eq_zero_of_infinite (V : Type*) [infinite V] : (⊤ : simple_graph V).chromatic_number = 0 := begin let n := (⊤ : simple_graph V).chromatic_number, by_contra hc, replace hc := pos_iff_ne_zero.mpr hc, apply nat.not_succ_le_self n, convert_to (⊤ : simple_graph {m | m < n + 1}).chromatic_number ≤ _, { simp, }, refine (colorable_of_chromatic_number_pos hc).chromatic_number_mono_of_embedding _, apply embedding.complete_graph, exact (function.embedding.subtype _).trans (infinite.nat_embedding V), end /-- The bicoloring of a complete bipartite graph using whether a vertex is on the left or on the right. -/ def complete_bipartite_graph.bicoloring (V W : Type*) : (complete_bipartite_graph V W).coloring bool := coloring.mk (λ v, v.is_right) begin intros v w, cases v; cases w; simp, end lemma complete_bipartite_graph.chromatic_number {V W : Type*} [nonempty V] [nonempty W] : (complete_bipartite_graph V W).chromatic_number = 2 := begin apply chromatic_number_eq_card_of_forall_surj (complete_bipartite_graph.bicoloring V W), intros C b, have v := classical.arbitrary V, have w := classical.arbitrary W, have h : (complete_bipartite_graph V W).adj (sum.inl v) (sum.inr w) := by simp, have hn := C.valid h, by_cases he : C (sum.inl v) = b, { exact ⟨_, he⟩ }, { by_cases he' : C (sum.inr w) = b, { exact ⟨_, he'⟩ }, { exfalso, cases b; simp only [eq_tt_eq_not_eq_ff, eq_ff_eq_not_eq_tt] at he he'; rw [he, he'] at hn; contradiction }, }, end /-! ### Cliques -/ lemma is_clique.card_le_of_coloring {s : finset V} (h : G.is_clique s) [fintype α] (C : G.coloring α) : s.card ≤ fintype.card α := begin rw is_clique_iff_induce_eq at h, have f : G.induce ↑s ↪g G := embedding.induce ↑s, rw h at f, convert fintype.card_le_of_injective _ (C.comp f.to_hom).injective_of_top_hom using 1, simp, end lemma is_clique.card_le_of_colorable {s : finset V} (h : G.is_clique s) {n : ℕ} (hc : G.colorable n) : s.card ≤ n := begin convert h.card_le_of_coloring hc.some, simp, end -- TODO eliminate `finite V` constraint once chromatic numbers are refactored. -- This is just to ensure the chromatic number exists. lemma is_clique.card_le_chromatic_number [finite V] {s : finset V} (h : G.is_clique s) : s.card ≤ G.chromatic_number := by { casesI nonempty_fintype V, exact h.card_le_of_colorable G.colorable_chromatic_number_of_fintype } protected lemma colorable.clique_free {n m : ℕ} (hc : G.colorable n) (hm : n < m) : G.clique_free m := begin by_contra h, simp only [clique_free, is_n_clique_iff, not_forall, not_not] at h, obtain ⟨s, h, rfl⟩ := h, exact nat.lt_le_antisymm hm (h.card_le_of_colorable hc), end -- TODO eliminate `finite V` constraint once chromatic numbers are refactored. -- This is just to ensure the chromatic number exists. lemma clique_free_of_chromatic_number_lt [finite V] {n : ℕ} (hc : G.chromatic_number < n) : G.clique_free n := G.colorable_chromatic_number_of_fintype.clique_free hc end simple_graph
e9054d6f1a37831c068d9da2f98d0b7cc260de11
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/algebra/category/CommRing/default.lean
d76c4f6e805cf734f71f408914b7b3732913f0ab
[ "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
166
lean
import algebra.category.CommRing.basic import algebra.category.CommRing.adjunctions import algebra.category.CommRing.limits import algebra.category.CommRing.colimits
b8d94867082199a50488dfe7819f8dd3b2be6a56
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/linear_algebra/dfinsupp.lean
f2113b76eae29122d79837073a19d53fa8478439
[]
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
5,071
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl, Kenny Lau -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.dfinsupp import Mathlib.linear_algebra.basic import Mathlib.PostPort universes u_1 u_3 u_2 u_4 namespace Mathlib /-! # Properties of the semimodule `Π₀ i, M i` Given an indexed collection of `R`-semimodules `M i`, the `R`-semimodule structure on `Π₀ i, M i` is defined in `data.dfinsupp`. In this file we define `linear_map` versions of various maps: * `dfinsupp.lsingle a : M →ₗ[R] Π₀ i, M i`: `dfinsupp.single a` as a linear map; * `dfinsupp.lmk s : (Π i : (↑s : set ι), M i) →ₗ[R] Π₀ i, M i`: `dfinsupp.single a` as a linear map; * `dfinsupp.lapply i : (Π₀ i, M i) →ₗ[R] M`: the map `λ f, f i` as a linear map; * `dfinsupp.lsum`: `dfinsupp.sum` or `dfinsupp.lift_add_hom` as a `linear_map`; ## Implementation notes This file should try to mirror `linear_algebra.finsupp` where possible. The API of `finsupp` is much more developed, but many lemmas in that file should be eligible to copy over. ## Tags function with finite support, semimodule, linear algebra -/ namespace dfinsupp /-- `dfinsupp.mk` as a `linear_map`. -/ def lmk {ι : Type u_1} {R : Type u_2} {M : ι → Type u_3} [dec_ι : DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] (s : finset ι) : linear_map R ((i : ↥↑s) → M ↑i) (dfinsupp fun (i : ι) => M i) := linear_map.mk (mk s) sorry sorry /-- `dfinsupp.single` as a `linear_map` -/ def lsingle {ι : Type u_1} {R : Type u_2} {M : ι → Type u_3} [dec_ι : DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] (i : ι) : linear_map R (M i) (dfinsupp fun (i : ι) => M i) := linear_map.mk (single i) sorry sorry /-- Two `R`-linear maps from `Π₀ i, M i` which agree on each `single i x` agree everywhere. -/ theorem lhom_ext {ι : Type u_1} {R : Type u_2} {M : ι → Type u_3} {N : Type u_4} [dec_ι : DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] [add_comm_monoid N] [semimodule R N] {φ : linear_map R (dfinsupp fun (i : ι) => M i) N} {ψ : linear_map R (dfinsupp fun (i : ι) => M i) N} (h : ∀ (i : ι) (x : M i), coe_fn φ (single i x) = coe_fn ψ (single i x)) : φ = ψ := linear_map.to_add_monoid_hom_injective (add_hom_ext h) /-- Two `R`-linear maps from `Π₀ i, M i` which agree on each `single i x` agree everywhere. See note [partially-applied ext lemmas]. After apply this lemma, if `M = R` then it suffices to verify `φ (single a 1) = ψ (single a 1)`. -/ theorem lhom_ext' {ι : Type u_1} {R : Type u_2} {M : ι → Type u_3} {N : Type u_4} [dec_ι : DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] [add_comm_monoid N] [semimodule R N] {φ : linear_map R (dfinsupp fun (i : ι) => M i) N} {ψ : linear_map R (dfinsupp fun (i : ι) => M i) N} (h : ∀ (i : ι), linear_map.comp φ (lsingle i) = linear_map.comp ψ (lsingle i)) : φ = ψ := lhom_ext fun (i : ι) => linear_map.congr_fun (h i) /-- Interpret `λ (f : Π₀ i, M i), f i` as a linear map. -/ def lapply {ι : Type u_1} {R : Type u_2} {M : ι → Type u_3} [semiring R] [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] (i : ι) : linear_map R (dfinsupp fun (i : ι) => M i) (M i) := linear_map.mk (fun (f : dfinsupp fun (i : ι) => M i) => coe_fn f i) sorry sorry @[simp] theorem lmk_apply {ι : Type u_1} {R : Type u_2} {M : ι → Type u_3} [dec_ι : DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] (s : finset ι) (x : (i : ↥↑s) → (fun (i : ι) => M i) ↑i) : coe_fn (lmk s) x = mk s x := rfl @[simp] theorem lsingle_apply {ι : Type u_1} {R : Type u_2} {M : ι → Type u_3} [dec_ι : DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] (i : ι) (x : M i) : coe_fn (lsingle i) x = single i x := rfl @[simp] theorem lapply_apply {ι : Type u_1} {R : Type u_2} {M : ι → Type u_3} [semiring R] [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] (i : ι) (f : dfinsupp fun (i : ι) => M i) : coe_fn (lapply i) f = coe_fn f i := rfl /-- The `dfinsupp` version of `finsupp.lsum`. -/ def lsum {ι : Type u_1} {R : Type u_2} {M : ι → Type u_3} {N : Type u_4} [dec_ι : DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] [add_comm_monoid N] [semimodule R N] : ((i : ι) → linear_map R (M i) N) ≃+ linear_map R (dfinsupp fun (i : ι) => M i) N := add_equiv.mk (fun (F : (i : ι) → linear_map R (M i) N) => linear_map.mk ⇑(sum_add_hom fun (i : ι) => linear_map.to_add_monoid_hom (F i)) sorry sorry) (fun (F : linear_map R (dfinsupp fun (i : ι) => M i) N) (i : ι) => linear_map.comp F (lsingle i)) sorry sorry sorry
b2ee49ac012d04f16fbc741c2935be5694c7c90b
6e9cd8d58e550c481a3b45806bd34a3514c6b3e0
/src/group_theory/subgroup.lean
4310560c371ec4f42717f1ffaa8cc8f66daa8b6d
[ "Apache-2.0" ]
permissive
sflicht/mathlib
220fd16e463928110e7b0a50bbed7b731979407f
1b2048d7195314a7e34e06770948ee00f0ac3545
refs/heads/master
1,665,934,056,043
1,591,373,803,000
1,591,373,803,000
269,815,267
0
0
Apache-2.0
1,591,402,068,000
1,591,402,067,000
null
UTF-8
Lean
false
false
31,663
lean
/- Copyright (c) 2020 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import group_theory.submonoid /-! # Subgroups This file defines multiplicative and additive subgroups as an extension of submonoids, in a bundled form (unbundled subgroups are in `deprecated/subgroups.lean`). We prove subgroups of a group form a complete lattice, and results about images and preimages of subgroups under group homomorphisms. The bundled subgroups use bundled monoid homomorphisms. There are also theorems about the subgroups generated by an element or a subset of a group, defined both inductively and as the infimum of the set of subgroups containing a given element/subset. Special thanks goes to Amelia Livingston and Yury Kudryashov for their help and inspiration. ## Main definitions Notation used here: - `G N` are groups - `A` is an add_group - `H K` are subgroups of `G` or add_subgroups of `A` - `x` is an element of type `G` or type `A` - `f g : N →* G` are group homomorphisms - `s k` are sets of elements of type `G` Definitions in the file: * `subgroup G` : the type of subgroups of a group `G` * `add_subgroup A` : the type of subgroups of an additive group `A` * `complete_lattice (subgroup G)` : the subgroups of `G` form a complete lattice * `closure k` : the minimal subgroup that includes the set `k` * `subtype` : the natural group homomorphism from a subgroup of group `G` to `G` * `gi` : `closure` forms a Galois insertion with the coercion to set * `comap H f` : the preimage of a subgroup `H` along the group homomorphism `f` is also a subgroup * `map f H` : the image of a subgroup `H` along the group homomorphism `f` is also a subgroup * `prod H K` : the product of subgroups `H`, `K` of groups `G`, `N` respectively, `H × K` is a subgroup of `G × N` * `monoid_hom.range f` : the range of the group homomorphism `f` is a subgroup * `monoid_hom.ker f` : the kernel of a group homomorphism `f` is the subgroup of elements `x : G` such that `f x = 1` * `monoid_hom.eq_locus f g` : given group homomorphisms `f`, `g`, the elements of `G` such that `f x = g x` form a subgroup of `G` ## Implementation notes Subgroup inclusion is denoted `≤` rather than `⊆`, although `∈` is defined as membership of a subgroup's underlying set. ## Tags subgroup, subgroups -/ variables {G : Type*} [group G] variables {A : Type*} [add_group A] set_option old_structure_cmd true /-- A subgroup of a group `G` is a subset containing 1, closed under multiplication and closed under multiplicative inverse. -/ structure subgroup (G : Type*) [group G] extends submonoid G := (inv_mem' {x} : x ∈ carrier → x⁻¹ ∈ carrier) /-- An additive subgroup of an additive group `G` is a subset containing 0, closed under addition and additive inverse. -/ structure add_subgroup (G : Type*) [add_group G] extends add_submonoid G:= (neg_mem' {x} : x ∈ carrier → -x ∈ carrier) attribute [to_additive add_subgroup] subgroup attribute [to_additive add_subgroup.to_add_submonoid] subgroup.to_submonoid /-- Reinterpret a `subgroup` as a `submonoid`. -/ add_decl_doc subgroup.to_submonoid /-- Reinterpret an `add_subgroup` as an `add_submonoid`. -/ add_decl_doc add_subgroup.to_add_submonoid /-- Map from subgroups of group `G` to `add_subgroup`s of `additive G`. -/ def subgroup.to_add_subgroup {G : Type*} [group G] (H : subgroup G) : add_subgroup (additive G) := { neg_mem' := H.inv_mem', .. submonoid.to_add_submonoid H.to_submonoid} /-- Map from `add_subgroup`s of `additive G` to subgroups of `G`. -/ def subgroup.of_add_subgroup {G : Type*} [group G] (H : add_subgroup (additive G)) : subgroup G := { inv_mem' := H.neg_mem', .. submonoid.of_add_submonoid H.to_add_submonoid} /-- Map from `add_subgroup`s of `add_group G` to subgroups of `multiplicative G`. -/ def add_subgroup.to_subgroup {G : Type*} [add_group G] (H : add_subgroup G) : subgroup (multiplicative G) := { inv_mem' := H.neg_mem', .. add_submonoid.to_submonoid H.to_add_submonoid} /-- Map from subgroups of `multiplicative G` to `add_subgroup`s of `add_group G`. -/ def add_subgroup.of_subgroup {G : Type*} [add_group G] (H : subgroup (multiplicative G)) : add_subgroup G := { neg_mem' := H.inv_mem', .. add_submonoid.of_submonoid H.to_submonoid } /-- Subgroups of group `G` are isomorphic to additive subgroups of `additive G`. -/ def subgroup.add_subgroup_equiv (G : Type*) [group G] : subgroup G ≃ add_subgroup (additive G) := { to_fun := subgroup.to_add_subgroup, inv_fun := subgroup.of_add_subgroup, left_inv := λ x, by cases x; refl, right_inv := λ x, by cases x; refl } namespace subgroup @[to_additive] instance : has_coe (subgroup G) (set G) := { coe := subgroup.carrier } @[simp, to_additive] lemma coe_to_submonoid (K : subgroup G) : (K.to_submonoid : set G) = K := rfl @[to_additive] instance : has_mem G (subgroup G) := ⟨λ m K, m ∈ (K : set G)⟩ @[to_additive] instance : has_coe_to_sort (subgroup G) := ⟨_, λ G, (G : Type*)⟩ @[simp, norm_cast, to_additive] lemma mem_coe {K : subgroup G} [g : G] : g ∈ (K : set G) ↔ g ∈ K := iff.rfl @[simp, norm_cast, to_additive] lemma coe_coe (K : subgroup G) : ↥(K : set G) = K := rfl attribute [norm_cast] add_subgroup.mem_coe attribute [norm_cast] add_subgroup.coe_coe end subgroup @[to_additive] protected lemma subgroup.exists {K : subgroup G} {p : K → Prop} : (∃ x : K, p x) ↔ ∃ x ∈ K, p ⟨x, ‹x ∈ K›⟩ := set_coe.exists @[to_additive] protected lemma subgroup.forall {K : subgroup G} {p : K → Prop} : (∀ x : K, p x) ↔ ∀ x ∈ K, p ⟨x, ‹x ∈ K›⟩ := set_coe.forall namespace subgroup variables (H K : subgroup G) /-- Copy of a subgroup with a new `carrier` equal to the old one. Useful to fix definitional equalities.-/ @[to_additive "Copy of an additive subgroup with a new `carrier` equal to the old one. Useful to fix definitional equalities"] protected def copy (K : subgroup G) (s : set G) (hs : s = K) : subgroup G := { carrier := s, one_mem' := hs.symm ▸ K.one_mem', mul_mem' := hs.symm ▸ K.mul_mem', inv_mem' := hs.symm ▸ K.inv_mem' } /- Two subgroups are equal if the underlying set are the same. -/ @[to_additive "Two `add_group`s are equal if the underlying subsets are equal."] theorem ext' {H K : subgroup G} (h : (H : set G) = K) : H = K := by { cases H, cases K, congr, exact h } /- Two subgroups are equal if and only if the underlying subsets are equal. -/ @[to_additive "Two `add_subgroup`s are equal if and only if the underlying subsets are equal."] protected theorem ext'_iff {H K : subgroup G} : H = K ↔ (H : set G) = K := ⟨λ h, h ▸ rfl, ext'⟩ /-- Two subgroups are equal if they have the same elements. -/ @[ext, to_additive "Two `add_subgroup`s are equal if they have the same elements."] theorem ext {H K : subgroup G} (h : ∀ x, x ∈ H ↔ x ∈ K) : H = K := ext' $ set.ext h attribute [ext] subgroup.ext /-- A subgroup contains the group's 1. -/ @[to_additive "An `add_subgroup` contains the group's 0."] theorem one_mem : (1 : G) ∈ H := H.one_mem' /-- A subgroup is closed under multiplication. -/ @[to_additive "An `add_subgroup` is closed under addition."] theorem mul_mem {x y : G} : x ∈ H → y ∈ H → x * y ∈ H := λ hx hy, H.mul_mem' hx hy /-- A subgroup is closed under inverse. -/ @[to_additive "An `add_subgroup` is closed under inverse."] theorem inv_mem {x : G} : x ∈ H → x⁻¹ ∈ H := λ hx, H.inv_mem' hx @[to_additive] lemma mul_mem_cancel_left {x y : G} (h : x ∈ H) : y * x ∈ H ↔ y ∈ H := ⟨λ hba, by simpa using H.mul_mem hba (H.inv_mem h), λ hb, H.mul_mem hb h⟩ @[to_additive] lemma mul_mem_cancel_right {x y : G} (h : x ∈ H) : x * y ∈ H ↔ y ∈ H := ⟨λ hab, by simpa using H.mul_mem (H.inv_mem h) hab, H.mul_mem h⟩ /-- Product of a list of elements in a subgroup is in the subgroup. -/ @[to_additive "Sum of a list of elements in an `add_subgroup` is in the `add_subgroup`."] lemma list_prod_mem {l : list G} : (∀ x ∈ l, x ∈ K) → l.prod ∈ K := K.to_submonoid.list_prod_mem /-- Product of a multiset of elements in a subgroup of a `comm_group` is in the subgroup. -/ @[to_additive "Sum of a multiset of elements in an `add_subgroup` of an `add_comm_group` is in the `add_subgroup`."] lemma multiset_prod_mem {G} [comm_group G] (K : subgroup G) (g : multiset G) : (∀ a ∈ g, a ∈ K) → g.prod ∈ K := K.to_submonoid.multiset_prod_mem g /-- Product of elements of a subgroup of a `comm_group` indexed by a `finset` is in the subgroup. -/ @[to_additive "Sum of elements in an `add_subgroup` of an `add_comm_group` indexed by a `finset` is in the `add_subgroup`."] lemma prod_mem {G : Type*} [comm_group G] (K : subgroup G) {ι : Type*} {t : finset ι} {f : ι → G} (h : ∀ c ∈ t, f c ∈ K) : t.prod f ∈ K := K.to_submonoid.prod_mem h lemma pow_mem {x : G} (hx : x ∈ K) : ∀ n : ℕ, x ^ n ∈ K := K.to_submonoid.pow_mem hx lemma gpow_mem {x : G} (hx : x ∈ K) : ∀ n : ℤ, x ^ n ∈ K | (int.of_nat n) := pow_mem _ hx n | -[1+ n] := K.inv_mem $ K.pow_mem hx n.succ /-- A subgroup of a group inherits a multiplication. -/ @[to_additive "An `add_subgroup` of an `add_group` inherits an addition."] instance has_mul : has_mul H := H.to_submonoid.has_mul /-- A subgroup of a group inherits a 1. -/ @[to_additive "An `add_subgroup` of an `add_group` inherits a zero."] instance has_one : has_one H := H.to_submonoid.has_one /-- A subgroup of a group inherits an inverse. -/ @[to_additive "A `add_subgroup` of a `add_group` inherits an inverse."] instance has_inv : has_inv H := ⟨λ a, ⟨a⁻¹, H.inv_mem a.2⟩⟩ @[simp, to_additive] lemma coe_mul (x y : H) : (↑(x * y) : G) = ↑x * ↑y := rfl @[simp, to_additive] lemma coe_one : ((1 : H) : G) = 1 := rfl @[simp, to_additive] lemma coe_inv (x : H) : ↑(x⁻¹ : H) = (x⁻¹ : G) := rfl @[simp, to_additive] lemma coe_mk (x : G) (hx : x ∈ H) : ((⟨x, hx⟩ : H) : G) = x := rfl /-- A subgroup of a group inherits a group structure. -/ @[to_additive to_add_group "An `add_subgroup` of an `add_group` inherits an `add_group` structure."] instance to_group {G : Type*} [group G] (H : subgroup G) : group H := { inv := has_inv.inv, mul_left_inv := λ x, subtype.eq $ mul_left_inv x, .. H.to_submonoid.to_monoid } /-- A subgroup of a `comm_group` is a `comm_group`. -/ @[to_additive to_add_comm_group "An `add_subgroup` of an `add_comm_group` is an `add_comm_group`."] instance to_comm_group {G : Type*} [comm_group G] (H : subgroup G) : comm_group H := { mul_comm := λ _ _, subtype.eq $ mul_comm _ _, .. H.to_group} /-- The natural group hom from a subgroup of group `G` to `G`. -/ @[to_additive "The natural group hom from an `add_subgroup` of `add_group` `G` to `G`."] def subtype : H →* G := ⟨coe, rfl, λ _ _, rfl⟩ @[simp, to_additive] theorem coe_subtype : ⇑H.subtype = coe := rfl @[to_additive] instance : has_le (subgroup G) := ⟨λ H K, ∀ ⦃x⦄, x ∈ H → x ∈ K⟩ @[to_additive] lemma le_def {H K : subgroup G} : H ≤ K ↔ ∀ ⦃x : G⦄, x ∈ H → x ∈ K := iff.rfl @[simp, to_additive] lemma coe_subset_coe {H K : subgroup G} : (H : set G) ⊆ K ↔ H ≤ K := iff.rfl @[to_additive] instance : partial_order (subgroup G) := { le := (≤), .. partial_order.lift (coe : subgroup G → set G) (λ a b, ext') infer_instance } /-- The subgroup `G` of the group `G`. -/ @[to_additive "The `add_subgroup G` of the `add_group G`."] instance : has_top (subgroup G) := ⟨{ inv_mem' := λ _ _, set.mem_univ _ , .. (⊤ : submonoid G) }⟩ /-- The trivial subgroup `{1}` of an group `G`. -/ @[to_additive "The trivial `add_subgroup` `{0}` of an `add_group` `G`."] instance : has_bot (subgroup G) := ⟨{ inv_mem' := λ _, by simp *, .. (⊥ : submonoid G) }⟩ @[to_additive] instance : inhabited (subgroup G) := ⟨⊥⟩ @[simp, to_additive] lemma mem_bot {x : G} : x ∈ (⊥ : subgroup G) ↔ x = 1 := set.mem_singleton_iff @[simp, to_additive] lemma mem_top (x : G) : x ∈ (⊤ : subgroup G) := set.mem_univ x @[simp, to_additive] lemma coe_top : ((⊤ : subgroup G) : set G) = set.univ := rfl @[simp, to_additive] lemma coe_bot : ((⊥ : subgroup G) : set G) = {1} := rfl /-- The inf of two subgroups is their intersection. -/ @[to_additive "The inf of two `add_subgroups`s is their intersection."] instance : has_inf (subgroup G) := ⟨λ H₁ H₂, { inv_mem' := λ _ ⟨hx, hx'⟩, ⟨H₁.inv_mem hx, H₂.inv_mem hx'⟩, .. H₁.to_submonoid ⊓ H₂.to_submonoid }⟩ @[simp, to_additive] lemma coe_inf (p p' : subgroup G) : ((p ⊓ p' : subgroup G) : set G) = p ∩ p' := rfl @[simp, to_additive] lemma mem_inf {p p' : subgroup G} {x : G} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl @[to_additive] instance : has_Inf (subgroup G) := ⟨λ s, { inv_mem' := λ x hx, set.mem_bInter $ λ i h, i.inv_mem (by apply set.mem_bInter_iff.1 hx i h), .. (⨅ S ∈ s, subgroup.to_submonoid S).copy (⋂ S ∈ s, ↑S) (by simp) }⟩ @[simp, to_additive] lemma coe_Inf (H : set (subgroup G)) : ((Inf H : subgroup G) : set G) = ⋂ s ∈ H, ↑s := rfl attribute [norm_cast] coe_Inf add_subgroup.coe_Inf @[simp, to_additive] lemma mem_Inf {S : set (subgroup G)} {x : G} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff /-- Subgroups of a group form a complete lattice. -/ @[to_additive "The `add_subgroup`s of an `add_group` form a complete lattice."] instance : complete_lattice (subgroup G) := { bot := (⊥), bot_le := λ S x hx, (mem_bot.1 hx).symm ▸ S.one_mem, top := (⊤), le_top := λ S x hx, mem_top x, inf := (⊓), le_inf := λ a b c ha hb x hx, ⟨ha hx, hb hx⟩, inf_le_left := λ a b x, and.left, inf_le_right := λ a b x, and.right, .. complete_lattice_of_Inf (subgroup G) $ λ s, is_glb.of_image (λ H K, show (H : set G) ≤ K ↔ H ≤ K, from coe_subset_coe) is_glb_binfi } /-- The `subgroup` generated by a set. -/ @[to_additive "The `add_subgroup` generated by a set"] def closure (k : set G) : subgroup G := Inf {K | k ⊆ K} variable {k : set G} @[to_additive] lemma mem_closure {x : G} : x ∈ closure k ↔ ∀ K : subgroup G, k ⊆ K → x ∈ K := mem_Inf /-- The subgroup generated by a set includes the set. -/ @[simp, to_additive "The `add_subgroup` generated by a set includes the set."] lemma subset_closure : k ⊆ closure k := λ x hx, mem_closure.2 $ λ K hK, hK hx open set /-- A subgroup `K` includes `closure k` if and only if it includes `k`. -/ @[simp, to_additive "An additive subgroup `K` includes `closure k` if and only if it includes `k`"] lemma closure_le : closure k ≤ K ↔ k ⊆ K := ⟨subset.trans subset_closure, λ h, Inf_le h⟩ @[to_additive] lemma closure_eq_of_le (h₁ : k ⊆ K) (h₂ : K ≤ closure k) : closure k = K := le_antisymm ((closure_le $ K).2 h₁) h₂ /-- An induction principle for closure membership. If `p` holds for `1` and all elements of `k`, and is preserved under multiplication and inverse, then `p` holds for all elements of the closure of `k`. -/ @[to_additive "An induction principle for additive closure membership. If `p` holds for `0` and all elements of `k`, and is preserved under addition and isvers, then `p` holds for all elements of the additive closure of `k`."] lemma closure_induction {p : G → Prop} {x} (h : x ∈ closure k) (Hk : ∀ x ∈ k, p x) (H1 : p 1) (Hmul : ∀ x y, p x → p y → p (x * y)) (Hinv : ∀ x, p x → p x⁻¹) : p x := (@closure_le _ _ ⟨p, H1, Hmul, Hinv⟩ _).2 Hk h attribute [elab_as_eliminator] subgroup.closure_induction add_subgroup.closure_induction variable (G) /-- `closure` forms a Galois insertion with the coercion to set. -/ @[to_additive "`closure` forms a Galois insertion with the coercion to set."] protected def gi : galois_insertion (@closure G _) coe := { choice := λ s _, closure s, gc := λ s t, @closure_le _ _ t s, le_l_u := λ s, subset_closure, choice_eq := λ s h, rfl } variable {G} /-- Subgroup closure of a set is monotone in its argument: if `h ⊆ k`, then `closure h ≤ closure k`. -/ @[to_additive "Additive subgroup closure of a set is monotone in its argument: if `h ⊆ k`, then `closure h ≤ closure k`"] lemma closure_mono ⦃h k : set G⦄ (h' : h ⊆ k) : closure h ≤ closure k := (subgroup.gi G).gc.monotone_l h' /-- Closure of a subgroup `K` equals `K`. -/ @[simp, to_additive "Additive closure of an additive subgroup `K` equals `K`"] lemma closure_eq : closure (K : set G) = K := (subgroup.gi G).l_u_eq K @[simp, to_additive] lemma closure_empty : closure (∅ : set G) = ⊥ := (subgroup.gi G).gc.l_bot @[simp, to_additive] lemma closure_univ : closure (univ : set G) = ⊤ := @coe_top G _ ▸ closure_eq ⊤ @[to_additive] lemma closure_union (s t : set G) : closure (s ∪ t) = closure s ⊔ closure t := (subgroup.gi G).gc.l_sup @[to_additive] lemma closure_Union {ι} (s : ι → set G) : closure (⋃ i, s i) = ⨆ i, closure (s i) := (subgroup.gi G).gc.l_supr /-- The subgroup generated by an element of a group equals the set of integer number powers of the element. -/ lemma mem_closure_singleton {x y : G} : y ∈ closure ({x} : set G) ↔ ∃ n : ℤ, x ^ n = y := begin refine ⟨λ hy, closure_induction hy _ _ _ _, λ ⟨n, hn⟩, hn ▸ gpow_mem _ (subset_closure $ mem_singleton x) n⟩, { intros y hy, rw [eq_of_mem_singleton hy], exact ⟨1, gpow_one x⟩ }, { exact ⟨0, rfl⟩ }, { rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩, exact ⟨n + m, gpow_add x n m⟩ }, rintros _ ⟨n, rfl⟩, exact ⟨-n, gpow_neg x n⟩ end @[to_additive] lemma mem_supr_of_directed {ι} [hι : nonempty ι] {K : ι → subgroup G} (hK : directed (≤) K) {x : G} : x ∈ (supr K : subgroup G) ↔ ∃ i, x ∈ K i := begin refine ⟨_, λ ⟨i, hi⟩, (le_def.1 $ le_supr K i) hi⟩, suffices : x ∈ closure (⋃ i, (K i : set G)) → ∃ i, x ∈ K i, by simpa only [closure_Union, closure_eq (K _)] using this, refine (λ hx, closure_induction hx (λ _, mem_Union.1) _ _ _), { exact hι.elim (λ i, ⟨i, (K i).one_mem⟩) }, { rintros x y ⟨i, hi⟩ ⟨j, hj⟩, rcases hK i j with ⟨k, hki, hkj⟩, exact ⟨k, (K k).mul_mem (hki hi) (hkj hj)⟩ }, rintros _ ⟨i, hi⟩, exact ⟨i, inv_mem (K i) hi⟩ end @[to_additive] lemma mem_Sup_of_directed_on {K : set (subgroup G)} (Kne : K.nonempty) (hK : directed_on (≤) K) {x : G} : x ∈ Sup K ↔ ∃ s ∈ K, x ∈ s := begin haveI : nonempty K := Kne.to_subtype, rw [Sup_eq_supr, supr_subtype', mem_supr_of_directed, subtype.exists], exact (directed_on_iff_directed _).1 hK end variables {N : Type*} [group N] {P : Type*} [group P] /-- The preimage of a subgroup along a monoid homomorphism is a subgroup. -/ @[to_additive "The preimage of an `add_subgroup` along an `add_monoid` homomorphism is an `add_subgroup`."] def comap {N : Type*} [group N] (f : G →* N) (H : subgroup N) : subgroup G := { carrier := (f ⁻¹' H), inv_mem' := λ a ha, show f a⁻¹ ∈ H, by rw f.map_inv; exact H.inv_mem ha, .. H.to_submonoid.comap f } @[simp, to_additive] lemma coe_comap (K : subgroup N) (f : G →* N) : (K.comap f : set G) = f ⁻¹' K := rfl @[simp, to_additive] lemma mem_comap {K : subgroup N} {f : G →* N} {x : G} : x ∈ K.comap f ↔ f x ∈ K := iff.rfl @[to_additive] lemma comap_comap (K : subgroup P) (g : N →* P) (f : G →* N) : (K.comap g).comap f = K.comap (g.comp f) := rfl /-- The image of a subgroup along a monoid homomorphism is a subgroup. -/ @[to_additive "The image of an `add_subgroup` along an `add_monoid` homomorphism is an `add_subgroup`."] def map (f : G →* N) (H : subgroup G) : subgroup N := { carrier := (f '' H), inv_mem' := by { rintros _ ⟨x, hx, rfl⟩, exact ⟨x⁻¹, H.inv_mem hx, f.map_inv x⟩ }, .. H.to_submonoid.map f } @[simp, to_additive] lemma coe_map (f : G →* N) (K : subgroup G) : (K.map f : set N) = f '' K := rfl @[simp, to_additive] lemma mem_map {f : G →* N} {K : subgroup G} {y : N} : y ∈ K.map f ↔ ∃ x ∈ K, f x = y := mem_image_iff_bex @[to_additive] lemma map_map (g : N →* P) (f : G →* N) : (K.map f).map g = K.map (g.comp f) := ext' $ image_image _ _ _ @[to_additive] lemma map_le_iff_le_comap {f : G →* N} {K : subgroup G} {H : subgroup N} : K.map f ≤ H ↔ K ≤ H.comap f := image_subset_iff @[to_additive] lemma gc_map_comap (f : G →* N) : galois_connection (map f) (comap f) := λ _ _, map_le_iff_le_comap @[to_additive] lemma map_sup (H K : subgroup G) (f : G →* N) : (H ⊔ K).map f = H.map f ⊔ K.map f := (gc_map_comap f).l_sup @[to_additive] lemma map_supr {ι : Sort*} (f : G →* N) (s : ι → subgroup G) : (supr s).map f = ⨆ i, (s i).map f := (gc_map_comap f).l_supr @[to_additive] lemma comap_inf (H K : subgroup N) (f : G →* N) : (H ⊓ K).comap f = H.comap f ⊓ K.comap f := (gc_map_comap f).u_inf @[to_additive] lemma comap_infi {ι : Sort*} (f : G →* N) (s : ι → subgroup N) : (infi s).comap f = ⨅ i, (s i).comap f := (gc_map_comap f).u_infi @[simp, to_additive] lemma map_bot (f : G →* N) : (⊥ : subgroup G).map f = ⊥ := (gc_map_comap f).l_bot @[simp, to_additive] lemma comap_top (f : G →* N) : (⊤ : subgroup N).comap f = ⊤ := (gc_map_comap f).u_top /-- Given `subgroup`s `H`, `K` of groups `G`, `N` respectively, `H × K` as a subgroup of `G × N`. -/ @[to_additive prod "Given `add_subgroup`s `H`, `K` of `add_group`s `A`, `B` respectively, `H × K` as an `add_subgroup` of `A × B`."] def prod (H : subgroup G) (K : subgroup N) : subgroup (G × N) := { inv_mem' := λ _ hx, ⟨H.inv_mem' hx.1, K.inv_mem' hx.2⟩, .. submonoid.prod H.to_submonoid K.to_submonoid} @[to_additive coe_prod] lemma coe_prod (H : subgroup G) (K : subgroup N) : (H.prod K : set (G × N)) = (H : set G).prod (K : set N) := rfl @[to_additive mem_prod] lemma mem_prod {H : subgroup G} {K : subgroup N} {p : G × N} : p ∈ H.prod K ↔ p.1 ∈ H ∧ p.2 ∈ K := iff.rfl @[to_additive prod_mono] lemma prod_mono : ((≤) ⇒ (≤) ⇒ (≤)) (@prod G _ N _) (@prod G _ N _) := λ s s' hs t t' ht, set.prod_mono hs ht @[to_additive prod_mono_right] lemma prod_mono_right (K : subgroup G) : monotone (λ t : subgroup N, K.prod t) := prod_mono (le_refl K) @[to_additive prod_mono_left] lemma prod_mono_left (H : subgroup N) : monotone (λ K : subgroup G, K.prod H) := λ s₁ s₂ hs, prod_mono hs (le_refl H) @[to_additive prod_top] lemma prod_top (K : subgroup G) : K.prod (⊤ : subgroup N) = K.comap (monoid_hom.fst G N) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst] @[to_additive top_prod] lemma top_prod (H : subgroup N) : (⊤ : subgroup G).prod H = H.comap (monoid_hom.snd G N) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd] @[simp, to_additive top_prod_top] lemma top_prod_top : (⊤ : subgroup G).prod (⊤ : subgroup N) = ⊤ := (top_prod _).trans $ comap_top _ @[to_additive] lemma bot_prod_bot : (⊥ : subgroup G).prod (⊥ : subgroup N) = ⊥ := ext' $ by simp [coe_prod, prod.one_eq_mk] /-- Product of subgroups is isomorphic to their product as groups. -/ @[to_additive prod_equiv "Product of additive subgroups is isomorphic to their product as additive groups"] def prod_equiv (H : subgroup G) (K : subgroup N) : H.prod K ≃* H × K := { map_mul' := λ x y, rfl, .. equiv.set.prod ↑H ↑K } /-- A subgroup is normal if whenever `n ∈ H`, then `g * n * g⁻¹ ∈ H` for every `g : G` -/ @[class, to_additive "An add_subgroup is normal if whenever `n ∈ H`, then `g + n - g ∈ H` for every `g : G` "] def normal : Prop := ∀ n, n ∈ H → ∀ g : G, g * n * g⁻¹ ∈ H variable {H} @[instance, priority 100, to_additive] lemma normal_of_comm {G : Type*} [comm_group G] (H : subgroup G) : H.normal := by simp [normal, mul_comm, mul_left_comm] namespace normal variable nH : H.normal @[to_additive] lemma conj_mem : ∀ n, n ∈ H → ∀ g : G, g * n * g⁻¹ ∈ H := nH @[to_additive] lemma mem_comm {a b : G} (h : a * b ∈ H) : b * a ∈ H := have a⁻¹ * (a * b) * a⁻¹⁻¹ ∈ H, from nH (a * b) h a⁻¹, by simpa @[to_additive] lemma mem_comm_iff {a b : G} : a * b ∈ H ↔ b * a ∈ H := ⟨nH.mem_comm, nH.mem_comm⟩ end normal @[instance, priority 100, to_additive] lemma bot_normal : normal (⊥ : subgroup G) := by simp [normal] variable (G) /-- The center of a group `G` is the set of elements that commute with everything in `G` -/ @[to_additive "The center of a group `G` is the set of elements that commute with everything in `G`"] def center : subgroup G := { carrier := {z | ∀ g, g * z = z * g}, one_mem' := by simp, mul_mem' := λ a b (ha : ∀ g, g * a = a * g) (hb : ∀ g, g * b = b * g) g, by assoc_rw [ha, hb g], inv_mem' := λ a (ha : ∀ g, g * a = a * g) g, by rw [← inv_inj', mul_inv_rev, inv_inv, ← ha, mul_inv_rev, inv_inv] } variable {G} @[to_additive] lemma mem_center_iff {z : G} : z ∈ center G ↔ ∀ g, g * z = z * g := iff.rfl @[instance, priority 100, to_additive] lemma center_normal : (center G).normal := begin assume n hn g h, assoc_rw [hn (h * g), hn g], simp end variables {G} (H) /-- The `normalizer` of `H` is the smallest subgroup of `G` inside which `H` is normal. -/ @[to_additive "The `normalizer` of `H` is the smallest subgroup of `G` inside which `H` is normal."] def normalizer : subgroup G := { carrier := {g : G | ∀ n, n ∈ H ↔ g * n * g⁻¹ ∈ H}, one_mem' := by simp, mul_mem' := λ a b (ha : ∀ n, n ∈ H ↔ a * n * a⁻¹ ∈ H) (hb : ∀ n, n ∈ H ↔ b * n * b⁻¹ ∈ H) n, by { rw [hb, ha], simp [mul_assoc] }, inv_mem' := λ a (ha : ∀ n, n ∈ H ↔ a * n * a⁻¹ ∈ H) n, by { rw [ha (a⁻¹ * n * a⁻¹⁻¹)], simp [mul_assoc] } } variable {H} @[to_additive] lemma mem_normalizer_iff {g : G} : g ∈ normalizer H ↔ ∀ n, n ∈ H ↔ g * n * g⁻¹ ∈ H := iff.rfl @[to_additive] lemma le_normalizer : H ≤ normalizer H := λ x xH n, by rw [H.mul_mem_cancel_left (H.inv_mem xH), H.mul_mem_cancel_right xH] @[instance, priority 100, to_additive] lemma normal_in_normalizer : (H.comap H.normalizer.subtype).normal := λ x xH g, by simpa using (g.2 x).1 xH open_locale classical lemma le_normalizer_of_normal (hK : (H.comap K.subtype).normal) (HK : H ≤ K) : K ≤ H.normalizer := λ x hx y, ⟨λ yH, hK.conj_mem ⟨y, HK yH⟩ yH ⟨x, hx⟩, λ yH, by simpa [mem_comap, mul_assoc] using hK.conj_mem ⟨x * y * x⁻¹, HK yH⟩ yH ⟨x⁻¹, K.inv_mem hx⟩⟩ end subgroup namespace add_subgroup open set lemma gsmul_mem (H : add_subgroup A) {x : A} (hx : x ∈ H) : ∀ n : ℤ, gsmul n x ∈ H | (int.of_nat n) := add_submonoid.smul_mem H.to_add_submonoid hx n | -[1+ n] := H.neg_mem' $ H.add_mem hx $ add_submonoid.smul_mem H.to_add_submonoid hx n lemma sub_mem (H : add_subgroup A) {x y : A} (hx : x ∈ H) (hy : y ∈ H) : x - y ∈ H := H.add_mem hx (H.neg_mem hy) /-- The `add_subgroup` generated by an element of an `add_group` equals the set of natural number multiples of the element. -/ lemma mem_closure_singleton {x y : A} : y ∈ closure ({x} : set A) ↔ ∃ n : ℤ, gsmul n x = y := begin refine ⟨λ hy, closure_induction hy _ _ _ _, λ ⟨n, hn⟩, hn ▸ gsmul_mem _ (subset_closure $ mem_singleton x) n⟩, { intros y hy, rw [eq_of_mem_singleton hy], exact ⟨1, one_gsmul x⟩ }, { exact ⟨0, rfl⟩ }, { rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩, exact ⟨n + m, add_gsmul x n m⟩ }, { rintros _ ⟨n, rfl⟩, refine ⟨-n, neg_gsmul x n⟩ } end end add_subgroup namespace monoid_hom variables {N : Type*} {P : Type*} [group N] [group P] (K : subgroup G) open subgroup /-- The range of a monoid homomorphism from a group is a subgroup. -/ @[to_additive "The range of an `add_monoid_hom` from an `add_group` is an `add_subgroup`."] def range (f : G →* N) : subgroup N := (⊤ : subgroup G).map f @[simp, to_additive] lemma coe_range (f : G →* N) : (f.range : set N) = set.range f := set.image_univ @[simp, to_additive] lemma mem_range {f : G →* N} {y : N} : y ∈ f.range ↔ ∃ x, f x = y := by simp [range] @[to_additive] lemma map_range (g : N →* P) (f : G →* N) : f.range.map g = (g.comp f).range := (⊤ : subgroup G).map_map g f @[to_additive] lemma range_top_iff_surjective {N} [group N] {f : G →* N} : f.range = (⊤ : subgroup N) ↔ function.surjective f := subgroup.ext'_iff.trans $ iff.trans (by rw [coe_range, coe_top]) set.range_iff_surjective /-- The range of a surjective monoid homomorphism is the whole of the codomain. -/ @[to_additive "The range of a surjective `add_monoid` homomorphism is the whole of the codomain."] lemma range_top_of_surjective {N} [group N] (f : G →* N) (hf : function.surjective f) : f.range = (⊤ : subgroup N) := range_top_iff_surjective.2 hf /-- The multiplicative kernel of a monoid homomorphism is the subgroup of elements `x : G` such that `f x = 1` -/ @[to_additive "The additive kernel of an `add_monoid` homomorphism is the `add_subgroup` of elements such that `f x = 0`"] def ker (f : G →* N) := (⊥ : subgroup N).comap f @[to_additive] lemma mem_ker {f : G →* N} {x : G} : x ∈ f.ker ↔ f x = 1 := subgroup.mem_bot @[to_additive] lemma comap_ker (g : N →* P) (f : G →* N) : g.ker.comap f = (g.comp f).ker := rfl @[instance, priority 100, to_additive] lemma normal_ker (f : G →* N) : f.ker.normal := λ _, by simp [mem_ker] { contextual := tt } /-- The subgroup of elements `x : G` such that `f x = g x` -/ @[to_additive "The additive subgroup of elements `x : G` such that `f x = g x`"] def eq_locus (f g : G →* N) : subgroup G := { inv_mem' := λ x (hx : f x = g x), show f x⁻¹ = g x⁻¹, by rw [f.map_inv, g.map_inv, hx], .. eq_mlocus f g} /-- If two monoid homomorphisms are equal on a set, then they are equal on its subgroup closure. -/ @[to_additive] lemma eq_on_closure {f g : G →* N} {s : set G} (h : set.eq_on f g s) : set.eq_on f g (closure s) := show closure s ≤ f.eq_locus g, from (closure_le _).2 h @[to_additive] lemma eq_of_eq_on_top {f g : G →* N} (h : set.eq_on f g (⊤ : subgroup G)) : f = g := ext $ λ x, h trivial @[to_additive] lemma eq_of_eq_on_dense {s : set G} (hs : closure s = ⊤) {f g : G →* N} (h : s.eq_on f g) : f = g := eq_of_eq_on_top $ hs ▸ eq_on_closure h @[to_additive] lemma gclosure_preimage_le (f : G →* N) (s : set N) : closure (f ⁻¹' s) ≤ (closure s).comap f := (closure_le _).2 $ λ x hx, by rw [mem_coe, mem_comap]; exact subset_closure hx /-- The image under a monoid homomorphism of the subgroup generated by a set equals the subgroup generated by the image of the set. -/ @[to_additive "The image under an `add_monoid` hom of the `add_subgroup` generated by a set equals the `add_subgroup` generated by the image of the set."] lemma map_closure (f : G →* N) (s : set G) : (closure s).map f = closure (f '' s) := le_antisymm (map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image f s) (gclosure_preimage_le _ _)) ((closure_le _).2 $ set.image_subset _ subset_closure) end monoid_hom namespace mul_equiv variables {H K : subgroup G} /-- Makes the identity isomorphism from a proof two subgroups of a multiplicative group are equal. -/ @[to_additive add_subgroup_congr "Makes the identity additive isomorphism from a proof two subgroups of an additive group are equal."] def subgroup_congr (h : H = K) : H ≃* K := { map_mul' := λ _ _, rfl, ..equiv.set_congr $ subgroup.ext'_iff.1 h } end mul_equiv
1519b27fe2c220bdccce6b5e56da2c6b0594e37e
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/loop3.lean
66fa873577545d73699a5bce56d34e06c8b3f217
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
1,202
lean
variable vec : Nat → Type variable concat {n m : Nat} (v : vec n) (w : vec m) : vec (n + m) infixl 65 ; : concat axiom concat_assoc {n1 n2 n3 : Nat} (v1 : vec n1) (v2 : vec n2) (v3 : vec n3) : (v1 ; v2) ; v3 = cast (to_heq (congr2 vec (symm (Nat::add_assoc n1 n2 n3)))) (v1 ; (v2 ; v3)) variable empty : vec 0 axiom concat_empty {n : Nat} (v : vec n) : v ; empty = cast (to_heq (congr2 vec (symm (Nat::add_zeror n)))) v rewrite_set simple add_rewrite Nat::add_assoc Nat::add_zeror eq_id : simple add_rewrite concat_assoc concat_empty Nat::add_assoc Nat::add_zeror : simple (* local opts = options({"simplifier", "heq"}, true) local t = parse_lean('∀ (n : Nat) (v : vec (n + 0)) (w : vec n), v = w ; empty') print(t) local t2, pr = simplify(t, "simple", heq) print("====>") print(t2) get_environment():type_check(pr) *) print "STEP 1" print "STEP 2" (* local opts = options({"simplifier", "heq"}, true) local t = parse_lean('λ n : Nat, ∃ (v : vec (n + 0)) (w : vec n), v ≠ w ; empty') print(t) local t2, pr = simplify(t, "simple", opts) print("====>") print(t2) get_environment():type_check(pr) *)
76a941cb361825da1ae4831b7994c98b4c106375
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/logic/equiv/fin.lean
a5b14633c839716e9718708b56054b616850a179
[ "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
17,688
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 data.fin.vec_notation import logic.equiv.defs /-! # Equivalences for `fin n` -/ universes u variables {m n : ℕ} /-- Equivalence between `fin 0` and `empty`. -/ def fin_zero_equiv : fin 0 ≃ empty := equiv.equiv_empty _ /-- Equivalence between `fin 0` and `pempty`. -/ def fin_zero_equiv' : fin 0 ≃ pempty.{u} := equiv.equiv_pempty _ /-- Equivalence between `fin 1` and `unit`. -/ def fin_one_equiv : fin 1 ≃ unit := equiv.equiv_punit _ /-- Equivalence between `fin 2` and `bool`. -/ def fin_two_equiv : fin 2 ≃ bool := { to_fun := ![ff, tt], inv_fun := λ b, cond b 1 0, left_inv := fin.forall_fin_two.2 $ by simp, right_inv := bool.forall_bool.2 $ by simp } /-- `Π i : fin 2, α i` is equivalent to `α 0 × α 1`. See also `fin_two_arrow_equiv` for a non-dependent version and `prod_equiv_pi_fin_two` for a version with inputs `α β : Type u`. -/ @[simps {fully_applied := ff}] def pi_fin_two_equiv (α : fin 2 → Type u) : (Π i, α i) ≃ α 0 × α 1 := { to_fun := λ f, (f 0, f 1), inv_fun := λ p, fin.cons p.1 $ fin.cons p.2 fin_zero_elim, left_inv := λ f, funext $ fin.forall_fin_two.2 ⟨rfl, rfl⟩, right_inv := λ ⟨x, y⟩, rfl } lemma fin.preimage_apply_01_prod {α : fin 2 → Type u} (s : set (α 0)) (t : set (α 1)) : (λ f : Π i, α i, (f 0, f 1)) ⁻¹' s ×ˢ t = set.pi set.univ (fin.cons s $ fin.cons t fin.elim0) := begin ext f, have : (fin.cons s (fin.cons t fin.elim0) : Π i, set (α i)) 1 = t := rfl, simp [fin.forall_fin_two, this] end lemma fin.preimage_apply_01_prod' {α : Type u} (s t : set α) : (λ f : fin 2 → α, (f 0, f 1)) ⁻¹' s ×ˢ t = set.pi set.univ ![s, t] := fin.preimage_apply_01_prod s t /-- A product space `α × β` is equivalent to the space `Π i : fin 2, γ i`, where `γ = fin.cons α (fin.cons β fin_zero_elim)`. See also `pi_fin_two_equiv` and `fin_two_arrow_equiv`. -/ @[simps {fully_applied := ff }] def prod_equiv_pi_fin_two (α β : Type u) : α × β ≃ Π i : fin 2, ![α, β] i := (pi_fin_two_equiv (fin.cons α (fin.cons β fin_zero_elim))).symm /-- The space of functions `fin 2 → α` is equivalent to `α × α`. See also `pi_fin_two_equiv` and `prod_equiv_pi_fin_two`. -/ @[simps { fully_applied := ff }] def fin_two_arrow_equiv (α : Type*) : (fin 2 → α) ≃ α × α := { inv_fun := λ x, ![x.1, x.2], .. pi_fin_two_equiv (λ _, α) } /-- `Π i : fin 2, α i` is order equivalent to `α 0 × α 1`. See also `order_iso.fin_two_arrow_equiv` for a non-dependent version. -/ def order_iso.pi_fin_two_iso (α : fin 2 → Type u) [Π i, preorder (α i)] : (Π i, α i) ≃o α 0 × α 1 := { to_equiv := pi_fin_two_equiv α, map_rel_iff' := λ f g, iff.symm fin.forall_fin_two } /-- The space of functions `fin 2 → α` is order equivalent to `α × α`. See also `order_iso.pi_fin_two_iso`. -/ def order_iso.fin_two_arrow_iso (α : Type*) [preorder α] : (fin 2 → α) ≃o α × α := { to_equiv := fin_two_arrow_equiv α, .. order_iso.pi_fin_two_iso (λ _, α) } /-- The 'identity' equivalence between `fin n` and `fin m` when `n = m`. -/ def fin_congr {n m : ℕ} (h : n = m) : fin n ≃ fin m := (fin.cast h).to_equiv @[simp] lemma fin_congr_apply_mk {n m : ℕ} (h : n = m) (k : ℕ) (w : k < n) : fin_congr h ⟨k, w⟩ = ⟨k, by { subst h, exact w }⟩ := rfl @[simp] lemma fin_congr_symm {n m : ℕ} (h : n = m) : (fin_congr h).symm = fin_congr h.symm := rfl @[simp] lemma fin_congr_apply_coe {n m : ℕ} (h : n = m) (k : fin n) : (fin_congr h k : ℕ) = k := by { cases k, refl, } lemma fin_congr_symm_apply_coe {n m : ℕ} (h : n = m) (k : fin m) : ((fin_congr h).symm k : ℕ) = k := by { cases k, refl, } /-- An equivalence that removes `i` and maps it to `none`. This is a version of `fin.pred_above` that produces `option (fin n)` instead of mapping both `i.cast_succ` and `i.succ` to `i`. -/ def fin_succ_equiv' {n : ℕ} (i : fin (n + 1)) : fin (n + 1) ≃ option (fin n) := { to_fun := i.insert_nth none some, inv_fun := λ x, x.cases_on' i (fin.succ_above i), left_inv := λ x, fin.succ_above_cases i (by simp) (λ j, by simp) x, right_inv := λ x, by cases x; dsimp; simp } @[simp] lemma fin_succ_equiv'_at {n : ℕ} (i : fin (n + 1)) : (fin_succ_equiv' i) i = none := by simp [fin_succ_equiv'] @[simp] lemma fin_succ_equiv'_succ_above {n : ℕ} (i : fin (n + 1)) (j : fin n) : fin_succ_equiv' i (i.succ_above j) = some j := @fin.insert_nth_apply_succ_above n (λ _, option (fin n)) i _ _ _ lemma fin_succ_equiv'_below {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : m.cast_succ < i) : (fin_succ_equiv' i) m.cast_succ = some m := by rw [← fin.succ_above_below _ _ h, fin_succ_equiv'_succ_above] lemma fin_succ_equiv'_above {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : i ≤ m.cast_succ) : (fin_succ_equiv' i) m.succ = some m := by rw [← fin.succ_above_above _ _ h, fin_succ_equiv'_succ_above] @[simp] lemma fin_succ_equiv'_symm_none {n : ℕ} (i : fin (n + 1)) : (fin_succ_equiv' i).symm none = i := rfl @[simp] lemma fin_succ_equiv'_symm_some {n : ℕ} (i : fin (n + 1)) (j : fin n) : (fin_succ_equiv' i).symm (some j) = i.succ_above j := rfl lemma fin_succ_equiv'_symm_some_below {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : m.cast_succ < i) : (fin_succ_equiv' i).symm (some m) = m.cast_succ := fin.succ_above_below i m h lemma fin_succ_equiv'_symm_some_above {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : i ≤ m.cast_succ) : (fin_succ_equiv' i).symm (some m) = m.succ := fin.succ_above_above i m h lemma fin_succ_equiv'_symm_coe_below {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : m.cast_succ < i) : (fin_succ_equiv' i).symm m = m.cast_succ := fin_succ_equiv'_symm_some_below h lemma fin_succ_equiv'_symm_coe_above {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : i ≤ m.cast_succ) : (fin_succ_equiv' i).symm m = m.succ := fin_succ_equiv'_symm_some_above h /-- Equivalence between `fin (n + 1)` and `option (fin n)`. This is a version of `fin.pred` that produces `option (fin n)` instead of requiring a proof that the input is not `0`. -/ def fin_succ_equiv (n : ℕ) : fin (n + 1) ≃ option (fin n) := fin_succ_equiv' 0 @[simp] lemma fin_succ_equiv_zero {n : ℕ} : (fin_succ_equiv n) 0 = none := rfl @[simp] lemma fin_succ_equiv_succ {n : ℕ} (m : fin n): (fin_succ_equiv n) m.succ = some m := fin_succ_equiv'_above (fin.zero_le _) @[simp] lemma fin_succ_equiv_symm_none {n : ℕ} : (fin_succ_equiv n).symm none = 0 := fin_succ_equiv'_symm_none _ @[simp] lemma fin_succ_equiv_symm_some {n : ℕ} (m : fin n) : (fin_succ_equiv n).symm (some m) = m.succ := congr_fun fin.succ_above_zero m @[simp] lemma fin_succ_equiv_symm_coe {n : ℕ} (m : fin n) : (fin_succ_equiv n).symm m = m.succ := fin_succ_equiv_symm_some m /-- The equiv version of `fin.pred_above_zero`. -/ lemma fin_succ_equiv'_zero {n : ℕ} : fin_succ_equiv' (0 : fin (n + 1)) = fin_succ_equiv n := rfl lemma fin_succ_equiv'_last_apply {n : ℕ} {i : fin (n + 1)} (h : i ≠ fin.last n) : fin_succ_equiv' (fin.last n) i = fin.cast_lt i (lt_of_le_of_ne (fin.le_last _) (fin.coe_injective.ne_iff.2 h) : ↑i < n) := begin have h' : ↑i < n := lt_of_le_of_ne (fin.le_last _) (fin.coe_injective.ne_iff.2 h), conv_lhs { rw ←fin.cast_succ_cast_lt i h' }, convert fin_succ_equiv'_below _, rw fin.cast_succ_cast_lt i h', exact h' end lemma fin_succ_equiv'_ne_last_apply {i j : fin (n + 1)} (hi : i ≠ fin.last n) (hj : j ≠ i) : fin_succ_equiv' i j = (i.cast_lt (lt_of_le_of_ne (fin.le_last _) (fin.coe_injective.ne_iff.2 hi) : ↑i < n)).pred_above j := begin rw [fin.pred_above], have hi' : ↑i < n := lt_of_le_of_ne (fin.le_last _) (fin.coe_injective.ne_iff.2 hi), rcases hj.lt_or_lt with hij | hij, { simp only [hij.not_lt, fin.cast_succ_cast_lt, not_false_iff, dif_neg], convert fin_succ_equiv'_below _, { simp }, { exact hij } }, { simp only [hij, fin.cast_succ_cast_lt, dif_pos], convert fin_succ_equiv'_above _, { simp }, { simp [fin.le_cast_succ_iff, hij] } } end /-- `succ_above` as an order isomorphism between `fin n` and `{x : fin (n + 1) // x ≠ p}`. -/ def fin_succ_above_equiv (p : fin (n + 1)) : fin n ≃o {x : fin (n + 1) // x ≠ p} := { map_rel_iff' := λ _ _, p.succ_above.map_rel_iff', ..equiv.option_subtype p ⟨(fin_succ_equiv' p).symm, rfl⟩ } lemma fin_succ_above_equiv_apply (p : fin (n + 1)) (i : fin n) : fin_succ_above_equiv p i = ⟨p.succ_above i, p.succ_above_ne i⟩ := rfl lemma fin_succ_above_equiv_symm_apply_last (x : {x : fin (n + 1) // x ≠ fin.last n}) : (fin_succ_above_equiv (fin.last n)).symm x = fin.cast_lt (x : fin (n + 1)) (lt_of_le_of_ne (fin.le_last _) (fin.coe_injective.ne_iff.2 x.property)) := begin rw [←option.some_inj, ←option.coe_def], simpa [fin_succ_above_equiv, order_iso.symm] using fin_succ_equiv'_last_apply x.property, end lemma fin_succ_above_equiv_symm_apply_ne_last {p : fin (n + 1)} (h : p ≠ fin.last n) (x : {x : fin (n + 1) // x ≠ p}) : (fin_succ_above_equiv p).symm x = (p.cast_lt (lt_of_le_of_ne (fin.le_last _) (fin.coe_injective.ne_iff.2 h))).pred_above x := begin rw [←option.some_inj, ←option.coe_def], simpa [fin_succ_above_equiv, order_iso.symm] using fin_succ_equiv'_ne_last_apply h x.property end /-- `equiv` between `fin (n + 1)` and `option (fin n)` sending `fin.last n` to `none` -/ def fin_succ_equiv_last {n : ℕ} : fin (n + 1) ≃ option (fin n) := fin_succ_equiv' (fin.last n) @[simp] lemma fin_succ_equiv_last_cast_succ {n : ℕ} (i : fin n) : fin_succ_equiv_last i.cast_succ = some i := fin_succ_equiv'_below i.2 @[simp] lemma fin_succ_equiv_last_last {n : ℕ} : fin_succ_equiv_last (fin.last n) = none := by simp [fin_succ_equiv_last] @[simp] lemma fin_succ_equiv_last_symm_some {n : ℕ} (i : fin n) : fin_succ_equiv_last.symm (some i) = i.cast_succ := fin_succ_equiv'_symm_some_below i.2 @[simp] lemma fin_succ_equiv_last_symm_coe {n : ℕ} (i : fin n) : fin_succ_equiv_last.symm ↑i = i.cast_succ := fin_succ_equiv'_symm_some_below i.2 @[simp] lemma fin_succ_equiv_last_symm_none {n : ℕ} : fin_succ_equiv_last.symm none = fin.last n := fin_succ_equiv'_symm_none _ /-- Equivalence between `Π j : fin (n + 1), α j` and `α i × Π j : fin n, α (fin.succ_above i j)`. -/ @[simps { fully_applied := ff}] def equiv.pi_fin_succ_above_equiv {n : ℕ} (α : fin (n + 1) → Type u) (i : fin (n + 1)) : (Π j, α j) ≃ α i × (Π j, α (i.succ_above j)) := { to_fun := λ f, (f i, λ j, f (i.succ_above j)), inv_fun := λ f, i.insert_nth f.1 f.2, left_inv := λ f, by simp [fin.insert_nth_eq_iff], right_inv := λ f, by simp } /-- Order isomorphism between `Π j : fin (n + 1), α j` and `α i × Π j : fin n, α (fin.succ_above i j)`. -/ def order_iso.pi_fin_succ_above_iso {n : ℕ} (α : fin (n + 1) → Type u) [Π i, has_le (α i)] (i : fin (n + 1)) : (Π j, α j) ≃o α i × (Π j, α (i.succ_above j)) := { to_equiv := equiv.pi_fin_succ_above_equiv α i, map_rel_iff' := λ f g, i.forall_iff_succ_above.symm } /-- Equivalence between `fin (n + 1) → β` and `β × (fin n → β)`. -/ @[simps { fully_applied := ff}] def equiv.pi_fin_succ (n : ℕ) (β : Type u) : (fin (n+1) → β) ≃ β × (fin n → β) := equiv.pi_fin_succ_above_equiv (λ _, β) 0 /-- Equivalence between `fin m ⊕ fin n` and `fin (m + n)` -/ def fin_sum_fin_equiv : fin m ⊕ fin n ≃ fin (m + n) := { to_fun := sum.elim (fin.cast_add n) (fin.nat_add m), inv_fun := λ i, @fin.add_cases m n (λ _, fin m ⊕ fin n) sum.inl sum.inr i, left_inv := λ x, by { cases x with y y; dsimp; simp }, right_inv := λ x, by refine fin.add_cases (λ i, _) (λ i, _) x; simp } @[simp] lemma fin_sum_fin_equiv_apply_left (i : fin m) : (fin_sum_fin_equiv (sum.inl i) : fin (m + n)) = fin.cast_add n i := rfl @[simp] lemma fin_sum_fin_equiv_apply_right (i : fin n) : (fin_sum_fin_equiv (sum.inr i) : fin (m + n)) = fin.nat_add m i := rfl @[simp] lemma fin_sum_fin_equiv_symm_apply_cast_add (x : fin m) : fin_sum_fin_equiv.symm (fin.cast_add n x) = sum.inl x := fin_sum_fin_equiv.symm_apply_apply (sum.inl x) @[simp] lemma fin_sum_fin_equiv_symm_apply_nat_add (x : fin n) : fin_sum_fin_equiv.symm (fin.nat_add m x) = sum.inr x := fin_sum_fin_equiv.symm_apply_apply (sum.inr x) @[simp] lemma fin_sum_fin_equiv_symm_last : fin_sum_fin_equiv.symm (fin.last n) = sum.inr 0 := fin_sum_fin_equiv_symm_apply_nat_add 0 /-- The equivalence between `fin (m + n)` and `fin (n + m)` which rotates by `n`. -/ def fin_add_flip : fin (m + n) ≃ fin (n + m) := (fin_sum_fin_equiv.symm.trans (equiv.sum_comm _ _)).trans fin_sum_fin_equiv @[simp] lemma fin_add_flip_apply_cast_add (k : fin m) (n : ℕ) : fin_add_flip (fin.cast_add n k) = fin.nat_add n k := by simp [fin_add_flip] @[simp] lemma fin_add_flip_apply_nat_add (k : fin n) (m : ℕ) : fin_add_flip (fin.nat_add m k) = fin.cast_add m k := by simp [fin_add_flip] @[simp] lemma fin_add_flip_apply_mk_left {k : ℕ} (h : k < m) (hk : k < m + n := nat.lt_add_right k m n h) (hnk : n + k < n + m := add_lt_add_left h n) : fin_add_flip (⟨k, hk⟩ : fin (m + n)) = ⟨n + k, hnk⟩ := by convert fin_add_flip_apply_cast_add ⟨k, h⟩ n @[simp] lemma fin_add_flip_apply_mk_right {k : ℕ} (h₁ : m ≤ k) (h₂ : k < m + n) : fin_add_flip (⟨k, h₂⟩ : fin (m + n)) = ⟨k - m, tsub_le_self.trans_lt $ add_comm m n ▸ h₂⟩ := begin convert fin_add_flip_apply_nat_add ⟨k - m, (tsub_lt_iff_right h₁).2 _⟩ m, { simp [add_tsub_cancel_of_le h₁] }, { rwa add_comm } end /-- Rotate `fin n` one step to the right. -/ def fin_rotate : Π n, equiv.perm (fin n) | 0 := equiv.refl _ | (n+1) := fin_add_flip.trans (fin_congr (add_comm _ _)) lemma fin_rotate_of_lt {k : ℕ} (h : k < n) : fin_rotate (n+1) ⟨k, lt_of_lt_of_le h (nat.le_succ _)⟩ = ⟨k + 1, nat.succ_lt_succ h⟩ := begin dsimp [fin_rotate], simp [h, add_comm], end lemma fin_rotate_last' : fin_rotate (n+1) ⟨n, lt_add_one _⟩ = ⟨0, nat.zero_lt_succ _⟩ := begin dsimp [fin_rotate], rw fin_add_flip_apply_mk_right, simp, end lemma fin_rotate_last : fin_rotate (n+1) (fin.last _) = 0 := fin_rotate_last' lemma fin.snoc_eq_cons_rotate {α : Type*} (v : fin n → α) (a : α) : @fin.snoc _ (λ _, α) v a = (λ i, @fin.cons _ (λ _, α) a v (fin_rotate _ i)) := begin ext ⟨i, h⟩, by_cases h' : i < n, { rw [fin_rotate_of_lt h', fin.snoc, fin.cons, dif_pos h'], refl, }, { have h'' : n = i, { simp only [not_lt] at h', exact (nat.eq_of_le_of_lt_succ h' h).symm, }, subst h'', rw [fin_rotate_last', fin.snoc, fin.cons, dif_neg (lt_irrefl _)], refl, } end @[simp] lemma fin_rotate_zero : fin_rotate 0 = equiv.refl _ := rfl @[simp] lemma fin_rotate_one : fin_rotate 1 = equiv.refl _ := subsingleton.elim _ _ @[simp] lemma fin_rotate_succ_apply {n : ℕ} (i : fin n.succ) : fin_rotate n.succ i = i + 1 := begin cases n, { simp }, rcases i.le_last.eq_or_lt with rfl|h, { simp [fin_rotate_last] }, { cases i, simp only [fin.lt_iff_coe_lt_coe, fin.coe_last, fin.coe_mk] at h, simp [fin_rotate_of_lt h, fin.eq_iff_veq, fin.add_def, nat.mod_eq_of_lt (nat.succ_lt_succ h)] }, end @[simp] lemma fin_rotate_apply_zero {n : ℕ} : fin_rotate n.succ 0 = 1 := by rw [fin_rotate_succ_apply, zero_add] lemma coe_fin_rotate_of_ne_last {n : ℕ} {i : fin n.succ} (h : i ≠ fin.last n) : (fin_rotate n.succ i : ℕ) = i + 1 := begin rw fin_rotate_succ_apply, have : (i : ℕ) < n := lt_of_le_of_ne (nat.succ_le_succ_iff.mp i.2) (fin.coe_injective.ne h), exact fin.coe_add_one_of_lt this end lemma coe_fin_rotate {n : ℕ} (i : fin n.succ) : (fin_rotate n.succ i : ℕ) = if i = fin.last n then 0 else i + 1 := by rw [fin_rotate_succ_apply, fin.coe_add_one i] /-- Equivalence between `fin m × fin n` and `fin (m * n)` -/ @[simps] def fin_prod_fin_equiv : fin m × fin n ≃ fin (m * n) := { to_fun := λ x, ⟨x.2 + n * x.1, calc x.2.1 + n * x.1.1 + 1 = x.1.1 * n + x.2.1 + 1 : by ac_refl ... ≤ x.1.1 * n + n : nat.add_le_add_left x.2.2 _ ... = (x.1.1 + 1) * n : eq.symm $ nat.succ_mul _ _ ... ≤ m * n : nat.mul_le_mul_right _ x.1.2⟩, inv_fun := λ x, (x.div_nat, x.mod_nat), left_inv := λ ⟨x, y⟩, have H : 0 < n, from nat.pos_of_ne_zero $ λ H, nat.not_lt_zero y.1 $ H ▸ y.2, prod.ext (fin.eq_of_veq $ calc (y.1 + n * x.1) / n = y.1 / n + x.1 : nat.add_mul_div_left _ _ H ... = 0 + x.1 : by rw nat.div_eq_of_lt y.2 ... = x.1 : nat.zero_add x.1) (fin.eq_of_veq $ calc (y.1 + n * x.1) % n = y.1 % n : nat.add_mul_mod_self_left _ _ _ ... = y.1 : nat.mod_eq_of_lt y.2), right_inv := λ x, fin.eq_of_veq $ nat.mod_add_div _ _ } /-- Promote a `fin n` into a larger `fin m`, as a subtype where the underlying values are retained. This is the `order_iso` version of `fin.cast_le`. -/ @[simps apply symm_apply] def fin.cast_le_order_iso {n m : ℕ} (h : n ≤ m) : fin n ≃o {i : fin m // (i : ℕ) < n} := { to_fun := λ i, ⟨fin.cast_le h i, by simp⟩, inv_fun := λ i, ⟨i, i.prop⟩, left_inv := λ _, by simp, right_inv := λ _, by simp, map_rel_iff' := λ _ _, by simp } /-- `fin 0` is a subsingleton. -/ instance subsingleton_fin_zero : subsingleton (fin 0) := fin_zero_equiv.subsingleton /-- `fin 1` is a subsingleton. -/ instance subsingleton_fin_one : subsingleton (fin 1) := fin_one_equiv.subsingleton
9d91c0b450777773cb45468d264d552dad398dce
2c096fdfecf64e46ea7bc6ce5521f142b5926864
/src/Lean/Elab/Command.lean
14754ed5a90d1da6bc292e3c394e004ab4cca164
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
Kha/lean4
1005785d2c8797ae266a303968848e5f6ce2fe87
b99e11346948023cd6c29d248cd8f3e3fb3474cf
refs/heads/master
1,693,355,498,027
1,669,080,461,000
1,669,113,138,000
184,748,176
0
0
Apache-2.0
1,665,995,520,000
1,556,884,930,000
Lean
UTF-8
Lean
false
false
20,777
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.Elab.Binders import Lean.Elab.SyntheticMVars namespace Lean.Elab.Command structure Scope where header : String opts : Options := {} currNamespace : Name := Name.anonymous openDecls : List OpenDecl := [] levelNames : List Name := [] /-- section variables -/ varDecls : Array (TSyntax ``Parser.Term.bracketedBinder) := #[] /-- Globally unique internal identifiers for the `varDecls` -/ varUIds : Array Name := #[] /-- noncomputable sections automatically add the `noncomputable` modifier to any declaration we cannot generate code for. -/ isNoncomputable : Bool := false deriving Inhabited structure State where env : Environment messages : MessageLog := {} scopes : List Scope := [{ header := "" }] nextMacroScope : Nat := firstFrontendMacroScope + 1 maxRecDepth : Nat nextInstIdx : Nat := 1 -- for generating anonymous instance names ngen : NameGenerator := {} infoState : InfoState := {} traceState : TraceState := {} deriving Inhabited structure Context where fileName : String fileMap : FileMap currRecDepth : Nat := 0 cmdPos : String.Pos := 0 macroStack : MacroStack := [] currMacroScope : MacroScope := firstFrontendMacroScope ref : Syntax := Syntax.missing tacticCache? : Option (IO.Ref Tactic.Cache) abbrev CommandElabCoreM (ε) := ReaderT Context $ StateRefT State $ EIO ε abbrev CommandElabM := CommandElabCoreM Exception abbrev CommandElab := Syntax → CommandElabM Unit abbrev Linter := Syntax → CommandElabM Unit /- 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`. Remark: see comment at TermElabM -/ @[always_inline] instance : Monad CommandElabM := let i := inferInstanceAs (Monad CommandElabM); { pure := i.pure, bind := i.bind } def mkState (env : Environment) (messages : MessageLog := {}) (opts : Options := {}) : State := { env := env messages := messages scopes := [{ header := "", opts := opts }] maxRecDepth := maxRecDepth.get opts } /- Linters should be loadable as plugins, so store in a global IO ref instead of an attribute managed by the environment (which only contains `import`ed objects). -/ builtin_initialize lintersRef : IO.Ref (Array Linter) ← IO.mkRef #[] def addLinter (l : Linter) : IO Unit := do let ls ← lintersRef.get lintersRef.set (ls.push l) instance : MonadInfoTree CommandElabM where getInfoState := return (← get).infoState modifyInfoState f := modify fun s => { s with infoState := f s.infoState } instance : MonadEnv CommandElabM where getEnv := do pure (← get).env modifyEnv f := modify fun s => { s with env := f s.env } @[always_inline] instance : MonadOptions CommandElabM where getOptions := do pure (← get).scopes.head!.opts protected def getRef : CommandElabM Syntax := return (← read).ref instance : AddMessageContext CommandElabM where addMessageContext := addMessageContextPartial instance : MonadRef CommandElabM where getRef := Command.getRef withRef ref x := withReader (fun ctx => { ctx with ref := ref }) x instance : MonadTrace CommandElabM where getTraceState := return (← get).traceState modifyTraceState f := modify fun s => { s with traceState := f s.traceState } instance : AddErrorMessageContext CommandElabM where add ref msg := do let ctx ← read let ref := getBetterRef ref ctx.macroStack let msg ← addMessageContext msg let msg ← addMacroStack msg ctx.macroStack return (ref, msg) def mkMessageAux (ctx : Context) (ref : Syntax) (msgData : MessageData) (severity : MessageSeverity) : Message := let pos := ref.getPos?.getD ctx.cmdPos let endPos := ref.getTailPos?.getD pos mkMessageCore ctx.fileName ctx.fileMap msgData severity pos endPos private def mkCoreContext (ctx : Context) (s : State) (heartbeats : Nat) : Core.Context := let scope := s.scopes.head! { fileName := ctx.fileName fileMap := ctx.fileMap options := scope.opts currRecDepth := ctx.currRecDepth maxRecDepth := s.maxRecDepth ref := ctx.ref currNamespace := scope.currNamespace openDecls := scope.openDecls initHeartbeats := heartbeats currMacroScope := ctx.currMacroScope } private def addTraceAsMessagesCore (ctx : Context) (log : MessageLog) (traceState : TraceState) : MessageLog := Id.run do if traceState.traces.isEmpty then return log let mut traces : HashMap (String.Pos × String.Pos) (Array MessageData) := ∅ for traceElem in traceState.traces do let ref := replaceRef traceElem.ref ctx.ref let pos := ref.getPos?.getD 0 let endPos := ref.getTailPos?.getD pos traces := traces.insert (pos, endPos) <| traces.findD (pos, endPos) #[] |>.push traceElem.msg let mut log := log let traces' := traces.toArray.qsort fun ((a, _), _) ((b, _), _) => a < b for ((pos, endPos), traceMsg) in traces' do log := log.add <| mkMessageCore ctx.fileName ctx.fileMap (.joinSep traceMsg.toList "\n") .information pos endPos return log private def addTraceAsMessages : CommandElabM Unit := do let ctx ← read modify fun s => { s with messages := addTraceAsMessagesCore ctx s.messages s.traceState traceState.traces := {} } def liftCoreM (x : CoreM α) : CommandElabM α := do let s ← get let ctx ← read let heartbeats ← IO.getNumHeartbeats let Eα := Except Exception α let x : CoreM Eα := try let a ← x; pure <| Except.ok a catch ex => pure <| Except.error ex let x : EIO Exception (Eα × Core.State) := (ReaderT.run x (mkCoreContext ctx s heartbeats)).run { env := s.env, ngen := s.ngen, traceState := s.traceState, messages := {}, infoState.enabled := s.infoState.enabled } let (ea, coreS) ← liftM x modify fun s => { s with env := coreS.env ngen := coreS.ngen messages := addTraceAsMessagesCore ctx (s.messages ++ coreS.messages) coreS.traceState traceState := coreS.traceState infoState.trees := s.infoState.trees.append coreS.infoState.trees } match ea with | Except.ok a => pure a | Except.error e => throw e private def ioErrorToMessage (ctx : Context) (ref : Syntax) (err : IO.Error) : Message := let ref := getBetterRef ref ctx.macroStack mkMessageAux ctx ref (toString err) MessageSeverity.error @[inline] def liftEIO {α} (x : EIO Exception α) : CommandElabM α := liftM x @[inline] def liftIO {α} (x : IO α) : CommandElabM α := do let ctx ← read IO.toEIO (fun (ex : IO.Error) => Exception.error ctx.ref ex.toString) x instance : MonadLiftT IO CommandElabM where monadLift := liftIO def getScope : CommandElabM Scope := do pure (← get).scopes.head! instance : MonadResolveName CommandElabM where getCurrNamespace := return (← getScope).currNamespace getOpenDecls := return (← getScope).openDecls instance : MonadLog CommandElabM where getRef := getRef getFileMap := return (← read).fileMap getFileName := return (← read).fileName hasErrors := return (← get).messages.hasErrors logMessage msg := do let currNamespace ← getCurrNamespace let openDecls ← getOpenDecls let msg := { msg with data := MessageData.withNamingContext { currNamespace := currNamespace, openDecls := openDecls } msg.data } modify fun s => { s with messages := s.messages.add msg } def runLinters (stx : Syntax) : CommandElabM Unit := do profileitM Exception "linting" (← getOptions) do let linters ← lintersRef.get unless linters.isEmpty do for linter in linters do let savedState ← get try linter stx catch ex => logException ex finally modify fun s => { savedState with messages := s.messages } protected def getCurrMacroScope : CommandElabM Nat := do pure (← read).currMacroScope protected def getMainModule : CommandElabM Name := do pure (← getEnv).mainModule protected def withFreshMacroScope {α} (x : CommandElabM α) : CommandElabM α := do let fresh ← modifyGet (fun st => (st.nextMacroScope, { st with nextMacroScope := st.nextMacroScope + 1 })) withReader (fun ctx => { ctx with currMacroScope := fresh }) x instance : MonadQuotation CommandElabM where getCurrMacroScope := Command.getCurrMacroScope getMainModule := Command.getMainModule withFreshMacroScope := Command.withFreshMacroScope unsafe def mkCommandElabAttributeUnsafe (ref : Name) : IO (KeyedDeclsAttribute CommandElab) := mkElabAttribute CommandElab `builtin_command_elab `command_elab `Lean.Parser.Command `Lean.Elab.Command.CommandElab "command" ref @[implemented_by mkCommandElabAttributeUnsafe] opaque mkCommandElabAttribute (ref : Name) : IO (KeyedDeclsAttribute CommandElab) builtin_initialize commandElabAttribute : KeyedDeclsAttribute CommandElab ← mkCommandElabAttribute decl_name% private def mkInfoTree (elaborator : Name) (stx : Syntax) (trees : PersistentArray InfoTree) : CommandElabM InfoTree := do let ctx ← read let s ← get let scope := s.scopes.head! let tree := InfoTree.node (Info.ofCommandInfo { elaborator, stx }) trees return InfoTree.context { env := s.env, fileMap := ctx.fileMap, mctx := {}, currNamespace := scope.currNamespace, openDecls := scope.openDecls, options := scope.opts, ngen := s.ngen } tree private def elabCommandUsing (s : State) (stx : Syntax) : List (KeyedDeclsAttribute.AttributeEntry CommandElab) → CommandElabM Unit | [] => withInfoTreeContext (mkInfoTree := mkInfoTree `no_elab stx) <| throwError "unexpected syntax{indentD stx}" | (elabFn::elabFns) => catchInternalId unsupportedSyntaxExceptionId (withInfoTreeContext (mkInfoTree := mkInfoTree elabFn.declName stx) <| elabFn.value stx) (fun _ => do set s; elabCommandUsing s stx elabFns) /-- Elaborate `x` with `stx` on the macro stack -/ def withMacroExpansion {α} (beforeStx afterStx : Syntax) (x : CommandElabM α) : CommandElabM α := withInfoContext (mkInfo := pure <| .ofMacroExpansionInfo { stx := beforeStx, output := afterStx, lctx := .empty }) do withReader (fun ctx => { ctx with macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack }) x instance : MonadMacroAdapter CommandElabM where getCurrMacroScope := getCurrMacroScope getNextMacroScope := return (← get).nextMacroScope setNextMacroScope next := modify fun s => { s with nextMacroScope := next } instance : MonadRecDepth CommandElabM where withRecDepth d x := withReader (fun ctx => { ctx with currRecDepth := d }) x getRecDepth := return (← read).currRecDepth getMaxRecDepth := return (← get).maxRecDepth register_builtin_option showPartialSyntaxErrors : Bool := { defValue := false descr := "show elaboration errors from partial syntax trees (i.e. after parser recovery)" } builtin_initialize registerTraceClass `Elab.command partial def elabCommand (stx : Syntax) : CommandElabM Unit := do withLogging <| withRef stx <| withIncRecDepth <| withFreshMacroScope do match stx with | Syntax.node _ k args => if k == nullKind then -- list of commands => elaborate in order -- The parser will only ever return a single command at a time, but syntax quotations can return multiple ones args.forM elabCommand else do trace `Elab.command fun _ => stx; let s ← get match (← liftMacroM <| expandMacroImpl? s.env stx) with | some (decl, stxNew?) => withInfoTreeContext (mkInfoTree := mkInfoTree decl stx) do let stxNew ← liftMacroM <| liftExcept stxNew? withMacroExpansion stx stxNew do elabCommand stxNew | _ => match commandElabAttribute.getEntries s.env k with | [] => withInfoTreeContext (mkInfoTree := mkInfoTree `no_elab stx) <| throwError "elaboration function for '{k}' has not been implemented" | elabFns => elabCommandUsing s stx elabFns | _ => throwError "unexpected command" builtin_initialize registerTraceClass `Elab.input /-- `elabCommand` wrapper that should be used for the initial invocation, not for recursive calls after macro expansion etc. -/ def elabCommandTopLevel (stx : Syntax) : CommandElabM Unit := withRef stx do trace[Elab.input] stx let initMsgs ← modifyGet fun st => (st.messages, { st with messages := {} }) let initInfoTrees ← getResetInfoTrees -- We should *not* factor out `elabCommand`'s `withLogging` to here since it would make its error -- recovery more coarse. In particular, If `c` in `set_option ... in $c` fails, the remaining -- `end` command of the `in` macro would be skipped and the option would be leaked to the outside! elabCommand stx withLogging do runLinters stx -- note the order: first process current messages & info trees, then add back old messages & trees, -- then convert new traces to messages let mut msgs := (← get).messages -- `stx.hasMissing` should imply `initMsgs.hasErrors`, but the latter should be cheaper to check in general if !showPartialSyntaxErrors.get (← getOptions) && initMsgs.hasErrors && stx.hasMissing then -- discard elaboration errors, except for a few important and unlikely misleading ones, on parse error msgs := ⟨msgs.msgs.filter fun msg => msg.data.hasTag (fun tag => tag == `Elab.synthPlaceholder || tag == `Tactic.unsolvedGoals || (`_traceMsg).isSuffixOf tag)⟩ for tree in (← getInfoTrees) do trace[Elab.info] (← tree.format) modify fun st => { st with messages := initMsgs ++ msgs infoState := { st.infoState with trees := initInfoTrees ++ st.infoState.trees } } addTraceAsMessages /-- Adapt a syntax transformation to a regular, command-producing elaborator. -/ def adaptExpander (exp : Syntax → CommandElabM Syntax) : CommandElab := fun stx => do let stx' ← exp stx withMacroExpansion stx stx' <| elabCommand stx' private def getVarDecls (s : State) : Array Syntax := s.scopes.head!.varDecls instance {α} : Inhabited (CommandElabM α) where default := throw default private def mkMetaContext : Meta.Context := { config := { foApprox := true, ctxApprox := true, quasiPatternApprox := true } } open Lean.Parser.Term in /-- Return identifier names in the given bracketed binder. -/ def getBracketedBinderIds : Syntax → Array Name | `(bracketedBinderF|($ids* $[: $ty?]? $(_annot?)?)) => ids.map Syntax.getId | `(bracketedBinderF|{$ids* $[: $ty?]?}) => ids.map Syntax.getId | `(bracketedBinderF|[$id : $_]) => #[id.getId] | `(bracketedBinderF|[$_]) => #[Name.anonymous] | _ => #[] private def mkTermContext (ctx : Context) (s : State) : Term.Context := Id.run do let scope := s.scopes.head! let mut sectionVars := {} for id in scope.varDecls.concatMap getBracketedBinderIds, uid in scope.varUIds do sectionVars := sectionVars.insert id uid { macroStack := ctx.macroStack sectionVars := sectionVars isNoncomputableSection := scope.isNoncomputable tacticCache? := ctx.tacticCache? } /-- Lift the `TermElabM` monadic action `x` into a `CommandElabM` monadic action. Note that `x` is executed with an empty message log. Thus, `x` cannot modify/view messages produced by previous commands. If you need to access the free variables corresponding to the ones declared using the `variable` command, consider using `runTermElabM`. Recall that `TermElabM` actions can automatically lift `MetaM` and `CoreM` actions. Example: ``` import Lean open Lean Elab Command Meta def printExpr (e : Expr) : MetaM Unit := do IO.println s!"{← ppExpr e} : {← ppExpr (← inferType e)}" #eval liftTermElabM do printExpr (mkConst ``Nat) ``` -/ def liftTermElabM (x : TermElabM α) : CommandElabM α := do let ctx ← read let s ← get let heartbeats ← IO.getNumHeartbeats -- dbg_trace "heartbeats: {heartbeats}" let scope := s.scopes.head! -- We execute `x` with an empty message log. Thus, `x` cannot modify/view messages produced by previous commands. -- This is useful for implementing `runTermElabM` where we use `Term.resetMessageLog` let x : TermElabM _ := withSaveInfoContext x let x : MetaM _ := (observing x).run (mkTermContext ctx s) { levelNames := scope.levelNames } let x : CoreM _ := x.run mkMetaContext {} let x : EIO _ _ := x.run (mkCoreContext ctx s heartbeats) { env := s.env, ngen := s.ngen, nextMacroScope := s.nextMacroScope, infoState.enabled := s.infoState.enabled } let (((ea, _), _), coreS) ← liftEIO x modify fun s => { s with env := coreS.env nextMacroScope := coreS.nextMacroScope ngen := coreS.ngen infoState.trees := s.infoState.trees.append coreS.infoState.trees messages := addTraceAsMessagesCore ctx (s.messages ++ coreS.messages) coreS.traceState } match ea with | Except.ok a => pure a | Except.error ex => throw ex /-- Execute the monadic action `elabFn xs` as a `CommandElabM` monadic action, where `xs` are free variables corresponding to all active scoped variables declared using the `variable` command. This method is similar to `liftTermElabM`, but it elaborates all scoped variables declared using the `variable` command. Example: ``` import Lean open Lean Elab Command Meta variable {α : Type u} {f : α → α} variable (n : Nat) #eval runTermElabM fun xs => do for x in xs do IO.println s!"{← ppExpr x} : {← ppExpr (← inferType x)}" ``` -/ def runTermElabM (elabFn : Array Expr → TermElabM α) : CommandElabM α := do let scope ← getScope liftTermElabM <| Term.withAutoBoundImplicit <| Term.elabBinders scope.varDecls fun xs => do -- We need to synthesize postponed terms because this is a checkpoint for the auto-bound implicit feature -- If we don't use this checkpoint here, then auto-bound implicits in the postponed terms will not be handled correctly. Term.synthesizeSyntheticMVarsNoPostponing let mut sectionFVars := {} for uid in scope.varUIds, x in xs do sectionFVars := sectionFVars.insert uid x withReader ({ · with sectionFVars := sectionFVars }) do -- We don't want to store messages produced when elaborating `(getVarDecls s)` because they have already been saved when we elaborated the `variable`(s) command. -- So, we use `Core.resetMessageLog`. Core.resetMessageLog let someType := mkSort levelZero Term.addAutoBoundImplicits' xs someType fun xs _ => Term.withoutAutoBoundImplicit <| elabFn xs @[inline] def catchExceptions (x : CommandElabM Unit) : CommandElabCoreM Empty Unit := fun ctx ref => EIO.catchExceptions (withLogging x ctx ref) (fun _ => pure ()) private def liftAttrM {α} (x : AttrM α) : CommandElabM α := do liftCoreM x def getScopes : CommandElabM (List Scope) := do pure (← get).scopes def modifyScope (f : Scope → Scope) : CommandElabM Unit := modify fun s => { s with scopes := match s.scopes with | h::t => f h :: t | [] => unreachable! } def withScope (f : Scope → Scope) (x : CommandElabM α) : CommandElabM α := do match (← get).scopes with | [] => x | h :: t => try modify fun s => { s with scopes := f h :: t } x finally modify fun s => { s with scopes := h :: t } def getLevelNames : CommandElabM (List Name) := return (← getScope).levelNames def addUnivLevel (idStx : Syntax) : CommandElabM Unit := withRef idStx do let id := idStx.getId let levelNames ← getLevelNames if levelNames.elem id then throwAlreadyDeclaredUniverseLevel id else modifyScope fun scope => { scope with levelNames := id :: scope.levelNames } def expandDeclId (declId : Syntax) (modifiers : Modifiers) : CommandElabM ExpandDeclIdResult := do let currNamespace ← getCurrNamespace let currLevelNames ← getLevelNames let r ← Elab.expandDeclId currNamespace currLevelNames declId modifiers for id in (← getScope).varDecls.concatMap getBracketedBinderIds do if id == r.shortName then throwError "invalid declaration name '{r.shortName}', there is a section variable with the same name" return r end Elab.Command export Elab.Command (Linter addLinter) end Lean
7b3a90146b90bd17acdb82e776b37ac9d3e01a2e
367134ba5a65885e863bdc4507601606690974c1
/src/tactic/squeeze.lean
f684679e9cfec8a68c9d65abdde173929a7e23b7
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
14,732
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon -/ import control.traversable.basic import tactic.simpa open interactive interactive.types lean.parser private meta def loc.to_string_aux : option name → string | none := "⊢" | (some x) := to_string x /-- pretty print a `loc` -/ meta def loc.to_string : loc → string | (loc.ns []) := "" | (loc.ns [none]) := "" | (loc.ns ls) := string.join $ list.intersperse " " (" at" :: ls.map loc.to_string_aux) | loc.wildcard := " at *" /-- shift `pos` `n` columns to the left -/ meta def pos.move_left (p : pos) (n : ℕ) : pos := { line := p.line, column := p.column - n } namespace tactic open list /-- parse structure instance of the shape `{ field1 := value1, .. , field2 := value2 }` -/ meta def struct_inst : lean.parser pexpr := do tk "{", ls ← sep_by (skip_info (tk ",")) ( sum.inl <$> (tk ".." *> texpr) <|> sum.inr <$> (prod.mk <$> ident <* tk ":=" <*> texpr)), tk "}", let (srcs,fields) := partition_map id ls, let (names,values) := unzip fields, pure $ pexpr.mk_structure_instance { field_names := names, field_values := values, sources := srcs } /-- pretty print structure instance -/ meta def struct.to_tactic_format (e : pexpr) : tactic format := do r ← e.get_structure_instance_info, fs ← mzip_with (λ n v, do v ← to_expr v >>= pp, pure $ format!"{n} := {v}" ) r.field_names r.field_values, let ss := r.sources.map (λ s, format!" .. {s}"), let x : format := format.join $ list.intersperse ", " (fs ++ ss), pure format!" {{{x}}" /-- Attribute containing a table that accumulates multiple `squeeze_simp` suggestions -/ @[user_attribute] private meta def squeeze_loc_attr : user_attribute unit (option (list (pos × string × list simp_arg_type × string))) := { name := `_squeeze_loc, parser := fail "this attribute should not be used", descr := "table to accumulate multiple `squeeze_simp` suggestions" } /-- dummy declaration used as target of `squeeze_loc` attribute -/ def squeeze_loc_attr_carrier := () run_cmd squeeze_loc_attr.set ``squeeze_loc_attr_carrier none tt /-- Format a list of arguments for use with `simp` and friends. This omits the list entirely if it is empty. -/ meta def render_simp_arg_list : list simp_arg_type → tactic format | [] := pure "" | args := (++) " " <$> to_line_wrap_format <$> args.mmap pp /-- Emit a suggestion to the user. If inside a `squeeze_scope` block, the suggestions emitted through `mk_suggestion` will be aggregated so that every tactic that makes a suggestion can consider multiple execution of the same invocation. If `at_pos` is true, make the suggestion at `p` instead of the current position. -/ meta def mk_suggestion (p : pos) (pre post : string) (args : list simp_arg_type) (at_pos := ff) : tactic unit := do xs ← squeeze_loc_attr.get_param ``squeeze_loc_attr_carrier, match xs with | none := do args ← render_simp_arg_list args, if at_pos then @scope_trace _ p.line p.column $ λ _, _root_.trace sformat!"{pre}{args}{post}" (pure () : tactic unit) else trace sformat!"{pre}{args}{post}" | some xs := do squeeze_loc_attr.set ``squeeze_loc_attr_carrier ((p,pre,args,post) :: xs) ff end local postfix `?`:9001 := optional /-- translate a `pexpr` into a `simp` configuration -/ meta def parse_config : option pexpr → tactic (simp_config_ext × format) | none := pure ({}, "") | (some cfg) := do e ← to_expr ``(%%cfg : simp_config_ext), fmt ← has_to_tactic_format.to_tactic_format cfg, prod.mk <$> eval_expr simp_config_ext e <*> struct.to_tactic_format cfg /-- translate a `pexpr` into a `dsimp` configuration -/ meta def parse_dsimp_config : option pexpr → tactic (dsimp_config × format) | none := pure ({}, "") | (some cfg) := do e ← to_expr ``(%%cfg : simp_config_ext), fmt ← has_to_tactic_format.to_tactic_format cfg, prod.mk <$> eval_expr dsimp_config e <*> struct.to_tactic_format cfg /-- `same_result proof tac` runs tactic `tac` and checks if the proof produced by `tac` is equivalent to `proof`. -/ meta def same_result (pr : proof_state) (tac : tactic unit) : tactic bool := do s ← get_proof_state_after tac, pure $ some pr = s private meta def filter_simp_set_aux (tac : bool → list simp_arg_type → tactic unit) (args : list simp_arg_type) (pr : proof_state) : list simp_arg_type → list simp_arg_type → list simp_arg_type → tactic (list simp_arg_type × list simp_arg_type) | [] ys ds := pure (ys.reverse, ds.reverse) | (x :: xs) ys ds := do b ← same_result pr (tac tt (args ++ xs ++ ys)), if b then filter_simp_set_aux xs ys (x:: ds) else filter_simp_set_aux xs (x :: ys) ds declare_trace squeeze.deleted /-- `filter_simp_set g call_simp user_args simp_args` returns `args'` such that, when calling `call_simp tt /- only -/ args'` on the goal `g` (`g` is a meta var) we end up in the same state as if we had called `call_simp ff (user_args ++ simp_args)` and removing any one element of `args'` changes the resulting proof. -/ meta def filter_simp_set (tac : bool → list simp_arg_type → tactic unit) (user_args simp_args : list simp_arg_type) : tactic (list simp_arg_type) := do some s ← get_proof_state_after (tac ff (user_args ++ simp_args)), (simp_args', _) ← filter_simp_set_aux tac user_args s simp_args [] [], (user_args', ds) ← filter_simp_set_aux tac simp_args' s user_args [] [], when (is_trace_enabled_for `squeeze.deleted = tt ∧ ¬ ds.empty) trace!"deleting provided arguments {ds}", pure (user_args' ++ simp_args') /-- make a `simp_arg_type` that references the name given as an argument -/ meta def name.to_simp_args (n : name) : tactic simp_arg_type := do e ← resolve_name' n, pure $ simp_arg_type.expr e /-- tactic combinator to create a `simp`-like tactic that minimizes its argument list. * `slow`: adds all rfl-lemmas from the environment to the initial list (this is a slower but more accurate strategy) * `no_dflt`: did the user use the `only` keyword? * `args`: list of `simp` arguments * `tac`: how to invoke the underlying `simp` tactic -/ meta def squeeze_simp_core (slow no_dflt : bool) (args : list simp_arg_type) (tac : Π (no_dflt : bool) (args : list simp_arg_type), tactic unit) (mk_suggestion : list simp_arg_type → tactic unit) : tactic unit := do v ← target >>= mk_meta_var, args ← if slow then do simp_set ← attribute.get_instances `simp, simp_set ← simp_set.mfilter $ has_attribute' `_refl_lemma, simp_set ← simp_set.mmap $ resolve_name' >=> pure ∘ simp_arg_type.expr, pure $ args ++ simp_set else pure args, g ← retrieve $ do { g ← main_goal, tac no_dflt args, instantiate_mvars g }, let vs := g.list_constant, vs ← vs.mfilter is_simp_lemma, vs ← vs.mmap strip_prefix, vs ← vs.to_list.mmap name.to_simp_args, with_local_goals' [v] (filter_simp_set tac args vs) >>= mk_suggestion, tac no_dflt args namespace interactive attribute [derive decidable_eq] simp_arg_type /-- Turn a `simp_arg_type` into a string. -/ meta instance simp_arg_type.has_to_string : has_to_string simp_arg_type := ⟨λ a, match a with | simp_arg_type.all_hyps := "*" | (simp_arg_type.except n) := "-" ++ to_string n | (simp_arg_type.expr e) := to_string e | (simp_arg_type.symm_expr e) := "←" ++ to_string e end⟩ /-- combinator meant to aggregate the suggestions issued by multiple calls of `squeeze_simp` (due, for instance, to `;`). Can be used as: ```lean example {α β} (xs ys : list α) (f : α → β) : (xs ++ ys.tail).map f = xs.map f ∧ (xs.tail.map f).length = xs.length := begin have : xs = ys, admit, squeeze_scope { split; squeeze_simp, -- `squeeze_simp` is run twice, the first one requires -- `list.map_append` and the second one -- `[list.length_map, list.length_tail]` -- prints only one message and combine the suggestions: -- > Try this: simp only [list.length_map, list.length_tail, list.map_append] squeeze_simp [this] -- `squeeze_simp` is run only once -- prints: -- > Try this: simp only [this] }, end ``` -/ meta def squeeze_scope (tac : itactic) : tactic unit := do none ← squeeze_loc_attr.get_param ``squeeze_loc_attr_carrier | pure (), squeeze_loc_attr.set ``squeeze_loc_attr_carrier (some []) ff, finally tac $ do some xs ← squeeze_loc_attr.get_param ``squeeze_loc_attr_carrier | fail "invalid state", let m := native.rb_lmap.of_list xs, squeeze_loc_attr.set ``squeeze_loc_attr_carrier none ff, m.to_list.reverse.mmap' $ λ ⟨p,suggs⟩, do { let ⟨pre,_,post⟩ := suggs.head, let suggs : list (list simp_arg_type) := suggs.map $ prod.fst ∘ prod.snd, mk_suggestion p pre post (suggs.foldl list.union []) tt, pure () } /-- `squeeze_simp`, `squeeze_simpa` and `squeeze_dsimp` perform the same task with the difference that `squeeze_simp` relates to `simp` while `squeeze_simpa` relates to `simpa` and `squeeze_dsimp` relates to `dsimp`. The following applies to `squeeze_simp`, `squeeze_simpa` and `squeeze_dsimp`. `squeeze_simp` behaves like `simp` (including all its arguments) and prints a `simp only` invocation to skip the search through the `simp` lemma list. For instance, the following is easily solved with `simp`: ```lean example : 0 + 1 = 1 + 0 := by simp ``` To guide the proof search and speed it up, we may replace `simp` with `squeeze_simp`: ```lean example : 0 + 1 = 1 + 0 := by squeeze_simp -- prints: -- Try this: simp only [add_zero, eq_self_iff_true, zero_add] ``` `squeeze_simp` suggests a replacement which we can use instead of `squeeze_simp`. ```lean example : 0 + 1 = 1 + 0 := by simp only [add_zero, eq_self_iff_true, zero_add] ``` `squeeze_simp only` prints nothing as it already skips the `simp` list. This tactic is useful for speeding up the compilation of a complete file. Steps: 1. search and replace ` simp` with ` squeeze_simp` (the space helps avoid the replacement of `simp` in `@[simp]`) throughout the file. 2. Starting at the beginning of the file, go to each printout in turn, copy the suggestion in place of `squeeze_simp`. 3. after all the suggestions were applied, search and replace `squeeze_simp` with `simp` to remove the occurrences of `squeeze_simp` that did not produce a suggestion. Known limitation(s): * in cases where `squeeze_simp` is used after a `;` (e.g. `cases x; squeeze_simp`), `squeeze_simp` will produce as many suggestions as the number of goals it is applied to. It is likely that none of the suggestion is a good replacement but they can all be combined by concatenating their list of lemmas. `squeeze_scope` can be used to combine the suggestions: `by squeeze_scope { cases x; squeeze_simp }` * sometimes, `simp` lemmas are also `_refl_lemma` and they can be used without appearing in the resulting proof. `squeeze_simp` won't know to try that lemma unless it is called as `squeeze_simp?` -/ meta def squeeze_simp (key : parse cur_pos) (slow_and_accurate : parse (tk "?")?) (use_iota_eqn : parse (tk "!")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (locat : parse location) (cfg : parse struct_inst?) : tactic unit := do (cfg',c) ← parse_config cfg, squeeze_simp_core slow_and_accurate.is_some no_dflt hs (λ l_no_dft l_args, simp use_iota_eqn none l_no_dft l_args attr_names locat cfg') (λ args, let use_iota_eqn := if use_iota_eqn.is_some then "!" else "", attrs := if attr_names.empty then "" else string.join (list.intersperse " " (" with" :: attr_names.map to_string)), loc := loc.to_string locat in mk_suggestion (key.move_left 1) sformat!"Try this: simp{use_iota_eqn} only" sformat!"{attrs}{loc}{c}" args) /-- see `squeeze_simp` -/ meta def squeeze_simpa (key : parse cur_pos) (slow_and_accurate : parse (tk "?")?) (use_iota_eqn : parse (tk "!")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (tgt : parse (tk "using" *> texpr)?) (cfg : parse struct_inst?) : tactic unit := do (cfg',c) ← parse_config cfg, tgt' ← traverse (λ t, do t ← to_expr t >>= pp, pure format!" using {t}") tgt, squeeze_simp_core slow_and_accurate.is_some no_dflt hs (λ l_no_dft l_args, simpa use_iota_eqn none l_no_dft l_args attr_names tgt cfg') (λ args, let use_iota_eqn := if use_iota_eqn.is_some then "!" else "", attrs := if attr_names.empty then "" else string.join (list.intersperse " " (" with" :: attr_names.map to_string)), tgt' := tgt'.get_or_else "" in mk_suggestion (key.move_left 1) sformat!"Try this: simpa{use_iota_eqn} only" sformat!"{attrs}{tgt'}{c}" args) /-- `squeeze_dsimp` behaves like `dsimp` (including all its arguments) and prints a `dsimp only` invocation to skip the search through the `simp` lemma list. See the doc string of `squeeze_simp` for examples. -/ meta def squeeze_dsimp (key : parse cur_pos) (slow_and_accurate : parse (tk "?")?) (use_iota_eqn : parse (tk "!")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (locat : parse location) (cfg : parse struct_inst?) : tactic unit := do (cfg',c) ← parse_dsimp_config cfg, squeeze_simp_core slow_and_accurate.is_some no_dflt hs (λ l_no_dft l_args, dsimp l_no_dft l_args attr_names locat cfg') (λ args, let use_iota_eqn := if use_iota_eqn.is_some then "!" else "", attrs := if attr_names.empty then "" else string.join (list.intersperse " " (" with" :: attr_names.map to_string)), loc := loc.to_string locat in mk_suggestion (key.move_left 1) sformat!"Try this: dsimp{use_iota_eqn} only" sformat!"{attrs}{loc}{c}" args) end interactive end tactic open tactic.interactive add_tactic_doc { name := "squeeze_simp / squeeze_simpa / squeeze_dsimp / squeeze_scope", category := doc_category.tactic, decl_names := [``squeeze_simp, ``squeeze_dsimp, ``squeeze_simpa, ``squeeze_scope], tags := ["simplification", "Try this"], inherit_description_from := ``squeeze_simp }
b1a57b1923607a827b77919fae1cc91995261280
b9a81ebb9de684db509231c4469a7d2c88915808
/src/super/simp.lean
508ce93041d49712c9c32c5f1a4be40a8723e752
[]
no_license
leanprover/super
3dd81ce8d9ac3cba20bce55e84833fadb2f5716e
47b107b4cec8f3b41d72daba9cbda2f9d54025de
refs/heads/master
1,678,482,996,979
1,676,526,367,000
1,676,526,367,000
92,215,900
12
6
null
1,513,327,539,000
1,495,570,640,000
Lean
UTF-8
Lean
false
false
1,505
lean
/- Copyright (c) 2017 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import .clause_ops .prover_state open tactic monad namespace super meta def prove_using_assumption : tactic unit := do tgt ← target, ass ← mk_local_def `h tgt, exact ass meta def simplify_capturing_assumptions (type : expr) : tactic (expr × expr × list expr) := do S ← simp_lemmas.mk_default, (type', heq, _) ← simplify S [] type, hyps ← return $ contained_lconsts type, hyps' ← return $ contained_lconsts_list [type', heq], add_hyps ← return $ list.filter (λn : expr, ¬hyps.contains n.local_uniq_name) hyps'.values, return (type', heq, add_hyps) meta def try_simplify_left (c : clause) (i : ℕ) : tactic (list clause) := on_left_at c i $ λtype, do (type', heq, add_hyps) ← simplify_capturing_assumptions type, hyp ← mk_local_def `h type', prf ← mk_eq_mpr heq hyp, return [(hyp::add_hyps, prf)] meta def try_simplify_right (c : clause) (i : ℕ) : tactic (list clause) := on_right_at' c i $ λhyp, do (type', heq, add_hyps) ← simplify_capturing_assumptions hyp.local_type, heqtype ← infer_type heq, heqsymm ← mk_eq_symm heq, prf ← mk_eq_mpr heqsymm hyp, return [(add_hyps, prf)] meta def simp_inf : inf_decl := inf_decl.mk 40 $ assume given, sequence' $ do r ← [try_simplify_right, try_simplify_left], i ← list.range given.c.num_lits, [inf_if_successful 2 given (r given.c i)] end super
f98c5d775dbcb35f725d1437cef97a09ffcc5365
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Data/Xml.lean
8c6ad55a2fc687ca9dda37b5913c2b2dc68ae99a
[ "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
55
lean
import Lean.Data.Xml.Basic import Lean.Data.Xml.Parser
6aa320abd4fbe5a5f6bd43f04a639a21a617252c
4727251e0cd73359b15b664c3170e5d754078599
/src/geometry/manifold/smooth_manifold_with_corners.lean
3d2d6e9dd857a75af0b9f1d22348a028c406b21a
[ "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
41,232
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.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. * `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 (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 (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 𝕜 to_local_equiv.target) (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_local_equiv := local_equiv.refl E, source_eq := rfl, unique_diff' := 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) namespace model_with_corners instance : has_coe_to_fun (model_with_corners 𝕜 E H) (λ _, H → E) := ⟨λ e, e.to_fun⟩ /-- The inverse to a model with corners, only registered as a local equiv. -/ protected def 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 to_local_equiv_coe : (I.to_local_equiv : H → E) = I := rfl @[simp, mfld_simps] lemma 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 to_local_equiv_coe_symm : (I.to_local_equiv.symm : E → H) = I.symm := rfl @[simp, mfld_simps] lemma mk_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.symm := rfl @[continuity] protected lemma continuous : continuous I := I.continuous_to_fun protected lemma continuous_at {x} : continuous_at I x := I.continuous.continuous_at protected lemma continuous_within_at {s x} : continuous_within_at I s x := I.continuous_at.continuous_within_at @[continuity] lemma continuous_symm : continuous I.symm := I.continuous_inv_fun lemma continuous_at_symm {x} : continuous_at I.symm x := I.continuous_symm.continuous_at lemma continuous_within_at_symm {s x} : continuous_within_at I.symm s x := I.continuous_symm.continuous_within_at lemma continuous_on_symm {s} : continuous_on I.symm s := I.continuous_symm.continuous_on @[simp, mfld_simps] lemma 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 } protected lemma unique_diff : unique_diff_on 𝕜 (range I) := I.target_eq ▸ I.unique_diff' @[simp, mfld_simps] protected lemma left_inv (x : H) : I.symm (I x) = x := by { refine I.left_inv' _, simp } protected lemma left_inverse : function.left_inverse I.symm I := I.left_inv @[simp, mfld_simps] lemma symm_comp_self : I.symm ∘ I = id := I.left_inverse.comp_eq_id protected lemma right_inv_on : right_inv_on I.symm I (range I) := I.left_inverse.right_inv_on_range @[simp, mfld_simps] protected lemma right_inv {x : E} (hx : x ∈ range I) : I (I.symm x) = x := I.right_inv_on hx protected lemma image_eq (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 closed_embedding : closed_embedding I := I.left_inverse.closed_embedding I.continuous_symm I.continuous lemma closed_range : is_closed (range I) := I.closed_embedding.closed_range lemma map_nhds_eq (x : H) : map I (𝓝 x) = 𝓝[range I] (I x) := I.closed_embedding.to_embedding.map_nhds_eq x lemma 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 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 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 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 unique_diff_at_image {x : H} : unique_diff_within_at 𝕜 (range I) (I x) := I.unique_diff _ (mem_range_self _) protected lemma 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 open topological_space protected lemma second_countable_topology [second_countable_topology E] (I : model_with_corners 𝕜 E H) : second_countable_topology H := I.closed_embedding.to_embedding.second_countable_topology end model_with_corners 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 : (𝓘(𝕜, E)).to_local_equiv = local_equiv.refl E := rfl @[simp, mfld_simps] lemma model_with_corners_self_coe : (𝓘(𝕜, E) : E → E) = id := rfl @[simp, mfld_simps] lemma model_with_corners_self_coe_symm : (𝓘(𝕜, E).symm : E → E) = id := rfl 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', model_prod 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)`. See note [Manifold type tags] for explanation about `model_prod H H'` vs `H × H'`. -/ 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 := λ x, (I x.1, I' x.2), inv_fun := λ x, (I.symm x.1, I'.symm x.2), source := {x | x.1 ∈ I.source ∧ x.2 ∈ I'.source}, source_eq := by simp only [set_of_true] with mfld_simps, unique_diff' := I.unique_diff'.prod I'.unique_diff', continuous_to_fun := I.continuous_to_fun.prod_map I'.continuous_to_fun, continuous_inv_fun := I.continuous_inv_fun.prod_map I'.continuous_inv_fun, .. I.to_local_equiv.prod I'.to_local_equiv } /-- Given a finite family of `model_with_corners` `I i` on `(E i, H i)`, we define the model with corners `pi I` on `(Π i, E i, model_pi H)`. See note [Manifold type tags] for explanation about `model_pi H`. -/ def model_with_corners.pi {𝕜 : Type u} [nondiscrete_normed_field 𝕜] {ι : Type v} [fintype ι] {E : ι → Type w} [Π i, normed_group (E i)] [Π i, normed_space 𝕜 (E i)] {H : ι → Type u'} [Π i, topological_space (H i)] (I : Π i, model_with_corners 𝕜 (E i) (H i)) : model_with_corners 𝕜 (Π i, E i) (model_pi H) := { to_local_equiv := local_equiv.pi (λ i, (I i).to_local_equiv), source_eq := by simp only [set.pi_univ] with mfld_simps, unique_diff' := unique_diff_on.pi ι E _ _ (λ i _, (I i).unique_diff'), continuous_to_fun := continuous_pi $ λ i, (I i).continuous.comp (continuous_apply i), continuous_inv_fun := continuous_pi $ λ i, (I i).continuous_symm.comp (continuous_apply i) } /-- 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 (𝓘(𝕜, 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) := rfl @[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 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 cont_diff_groupoid : structure_groupoid H := pregroupoid.groupoid { property := λf s, 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 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 cont_diff_on.congr (cont_diff_id.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 cont_diff_on_of_locally_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 cont_diff_groupoid_le (h : m ≤ n) : cont_diff_groupoid n I ≤ cont_diff_groupoid m I := begin rw [cont_diff_groupoid, cont_diff_groupoid], apply groupoid_of_pregroupoid_le, assume f s hfs, exact 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 cont_diff_groupoid_zero_eq : 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 `cont_diff_groupoid 0 I`, -- by unfolding its definition change u ∈ cont_diff_groupoid 0 I, rw [cont_diff_groupoid, mem_groupoid_of_pregroupoid], simp only [cont_diff_on_zero], split, { refine I.continuous.comp_continuous_on (u.continuous_on.comp I.continuous_on_symm _), exact (maps_to_preimage _ _).mono_left (inter_subset_left _ _) }, { refine I.continuous.comp_continuous_on (u.symm.continuous_on.comp I.continuous_on_symm _), exact (maps_to_preimage _ _).mono_left (inter_subset_left _ _) }, end variable (n) /-- An identity local homeomorphism belongs to the `C^n` groupoid. -/ lemma of_set_mem_cont_diff_groupoid {s : set H} (hs : is_open s) : local_homeomorph.of_set s hs ∈ cont_diff_groupoid n I := begin rw [cont_diff_groupoid, mem_groupoid_of_pregroupoid], suffices h : cont_diff_on 𝕜 n (I ∘ I.symm) (I.symm ⁻¹' s ∩ range I), by simp [h], have : cont_diff_on 𝕜 n id (univ : set E) := cont_diff_id.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_cont_diff_groupoid (e : local_homeomorph M H) : e.symm.trans e ∈ 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_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 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 ∈ cont_diff_groupoid ⊤ I) (he' : e' ∈ cont_diff_groupoid ⊤ I') : e.prod e' ∈ 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 := cont_diff_on.prod_map he he', rw [← I.image_eq, ← I'.image_eq, set.prod_image_image_eq] at h3, rw ← (I.prod I').image_eq, exact h3, }, { have h3 := cont_diff_on.prod_map he_symm he'_symm, rw [← I.image_eq, ← I'.image_eq, set.prod_image_image_eq] at h3, rw ← (I.prod I').image_eq, exact h3, } end /-- The `C^n` groupoid is closed under restriction. -/ instance : closed_under_restriction (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 (cont_diff_groupoid n I).eq_on_source' _ _ _ hes, exact of_set_mem_cont_diff_groupoid n I hs, end end cont_diff_groupoid end model_with_corners section smooth_manifold_with_corners /-! ### Smooth manifolds with corners -/ /-- 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 (cont_diff_groupoid ∞ I) : Prop lemma smooth_manifold_with_corners.mk' {𝕜 : 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] [gr : has_groupoid M (cont_diff_groupoid ∞ I)] : smooth_manifold_with_corners I M := { ..gr } lemma smooth_manifold_with_corners_of_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 → 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 (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 `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 := (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' ∈ 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, f2, hf1, hf2, rfl⟩ ⟨g1, g2, hg1, hg2, rfl⟩, rw [local_homeomorph.prod_symm, local_homeomorph.prod_trans], have h1 := has_groupoid.compatible (cont_diff_groupoid ⊤ I) hf1 hg1, have h2 := has_groupoid.compatible (cont_diff_groupoid ⊤ I') hf2 hg2, exact cont_diff_groupoid_prod h1 h2, end } end smooth_manifold_with_corners lemma local_homeomorph.singleton_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] (e : local_homeomorph M H) (h : e.source = set.univ) : @smooth_manifold_with_corners 𝕜 _ E _ _ H _ I M _ (e.singleton_charted_space h) := @smooth_manifold_with_corners.mk' _ _ _ _ _ _ _ _ _ _ (id _) $ e.singleton_has_groupoid h (cont_diff_groupoid ∞ I) lemma open_embedding.singleton_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] [nonempty M] {f : M → H} (h : open_embedding f) : @smooth_manifold_with_corners 𝕜 _ E _ _ H _ I M _ h.singleton_charted_space := (h.to_local_homeomorph f).singleton_smooth_manifold_with_corners I (by simp) namespace topological_space.opens open 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] [smooth_manifold_with_corners I M] (s : opens M) instance : smooth_manifold_with_corners I s := { ..s.has_groupoid (cont_diff_groupoid ∞ I) } end topological_space.opens 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_coe : ⇑(ext_chart_at I x) = I ∘ chart_at H x := rfl lemma ext_chart_at_coe_symm : ⇑(ext_chart_at I x).symm = (chart_at H x).symm ∘ I.symm := rfl 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 [ext_chart_at_source, mem_chart_source] lemma ext_chart_at_to_inv : (ext_chart_at I x).symm ((ext_chart_at I x) x) = x := (ext_chart_at I x).left_inv (mem_ext_chart_source I x) lemma ext_chart_at_source_mem_nhds' {x' : M} (h : x' ∈ (ext_chart_at I x).source) : (ext_chart_at I x).source ∈ 𝓝 x' := is_open.mem_nhds (ext_chart_at_open_source I x) h lemma ext_chart_at_source_mem_nhds : (ext_chart_at I x).source ∈ 𝓝 x := ext_chart_at_source_mem_nhds' I x (mem_ext_chart_source I x) lemma ext_chart_at_source_mem_nhds_within' {x' : M} (h : x' ∈ (ext_chart_at I x).source) : (ext_chart_at I x).source ∈ 𝓝[s] x' := mem_nhds_within_of_mem_nhds (ext_chart_at_source_mem_nhds' I x h) lemma ext_chart_at_source_mem_nhds_within : (ext_chart_at I x).source ∈ 𝓝[s] x := mem_nhds_within_of_mem_nhds (ext_chart_at_source_mem_nhds I x) lemma ext_chart_at_continuous_on : continuous_on (ext_chart_at I x) (ext_chart_at I x).source := begin refine I.continuous.comp_continuous_on _, rw ext_chart_at_source, exact (chart_at H x).continuous_on end lemma ext_chart_at_continuous_at' {x' : M} (h : x' ∈ (ext_chart_at I x).source) : continuous_at (ext_chart_at I x) x' := (ext_chart_at_continuous_on I x).continuous_at $ ext_chart_at_source_mem_nhds' I x h lemma ext_chart_at_continuous_at : continuous_at (ext_chart_at I x) x := ext_chart_at_continuous_at' _ _ (mem_ext_chart_source I x) lemma ext_chart_at_continuous_on_symm : continuous_on (ext_chart_at I x).symm (ext_chart_at I x).target := (chart_at H x).continuous_on_symm.comp I.continuous_on_symm $ (maps_to_preimage _ _).mono_left (inter_subset_right _ _) lemma ext_chart_at_map_nhds' {x y : M} (hy : y ∈ (ext_chart_at I x).source) : map (ext_chart_at I x) (𝓝 y) = 𝓝[range I] (ext_chart_at I x y) := begin rw [ext_chart_at_coe, (∘), ← I.map_nhds_eq, ← (chart_at H x).map_nhds_eq, map_map], rwa ext_chart_at_source at hy end lemma ext_chart_at_map_nhds : map (ext_chart_at I x) (𝓝 x) = 𝓝[range I] (ext_chart_at I x x) := ext_chart_at_map_nhds' I $ mem_ext_chart_source I x lemma ext_chart_at_target_mem_nhds_within' {y : M} (hy : y ∈ (ext_chart_at I x).source) : (ext_chart_at I x).target ∈ 𝓝[range I] (ext_chart_at I x y) := begin rw [← local_equiv.image_source_eq_target, ← ext_chart_at_map_nhds' I hy], exact image_mem_map (ext_chart_at_source_mem_nhds' _ _ hy) end lemma ext_chart_at_target_mem_nhds_within : (ext_chart_at I x).target ∈ 𝓝[range I] (ext_chart_at I x x) := ext_chart_at_target_mem_nhds_within' I x (mem_ext_chart_source I x) lemma ext_chart_at_target_subset_range : (ext_chart_at I x).target ⊆ range I := by simp only with mfld_simps lemma nhds_within_ext_chart_target_eq' {y : M} (hy : y ∈ (ext_chart_at I x).source) : 𝓝[(ext_chart_at I x).target] (ext_chart_at I x y) = 𝓝[range I] (ext_chart_at I x y) := (nhds_within_mono _ (ext_chart_at_target_subset_range _ _)).antisymm $ nhds_within_le_of_mem (ext_chart_at_target_mem_nhds_within' _ _ hy) 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) := nhds_within_ext_chart_target_eq' I x (mem_ext_chart_source I x) lemma ext_chart_continuous_at_symm'' {y : E} (h : y ∈ (ext_chart_at I x).target) : continuous_at (ext_chart_at I x).symm y := continuous_at.comp ((chart_at H x).continuous_at_symm h.2) (I.continuous_symm.continuous_at) 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') := ext_chart_continuous_at_symm'' I _ $ (ext_chart_at I x).map_source h 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) lemma ext_chart_continuous_on_symm : continuous_on (ext_chart_at I x).symm (ext_chart_at I x).target := λ y hy, (ext_chart_continuous_at_symm'' _ _ hy).continuous_within_at lemma ext_chart_preimage_open_of_open' {s : set E} (hs : is_open s) : is_open ((ext_chart_at I x).source ∩ ext_chart_at I x ⁻¹' s) := (ext_chart_at_continuous_on I x).preimage_open_of_open (ext_chart_at_open_source _ _) hs lemma ext_chart_preimage_open_of_open {s : set E} (hs : is_open s) : is_open ((chart_at H x).source ∩ ext_chart_at I x ⁻¹' s) := by { rw ← ext_chart_at_source I, exact ext_chart_preimage_open_of_open' I x hs } lemma ext_chart_at_map_nhds_within_eq_image' {y : M} (hy : y ∈ (ext_chart_at I x).source) : map (ext_chart_at I x) (𝓝[s] y) = 𝓝[ext_chart_at I x '' ((ext_chart_at I x).source ∩ s)] (ext_chart_at I x y) := by set e := ext_chart_at I x; calc map e (𝓝[s] y) = map e (𝓝[e.source ∩ s] y) : congr_arg (map e) (nhds_within_inter_of_mem (ext_chart_at_source_mem_nhds_within' I x hy)).symm ... = 𝓝[e '' (e.source ∩ s)] (e y) : ((ext_chart_at I x).left_inv_on.mono $ inter_subset_left _ _).map_nhds_within_eq ((ext_chart_at I x).left_inv hy) (ext_chart_continuous_at_symm' I x hy).continuous_within_at (ext_chart_at_continuous_at' I x hy).continuous_within_at lemma ext_chart_at_map_nhds_within_eq_image : map (ext_chart_at I x) (𝓝[s] x) = 𝓝[ext_chart_at I x '' ((ext_chart_at I x).source ∩ s)] (ext_chart_at I x x) := ext_chart_at_map_nhds_within_eq_image' I x (mem_ext_chart_source I x) lemma ext_chart_at_map_nhds_within' {y : M} (hy : y ∈ (ext_chart_at I x).source) : map (ext_chart_at I x) (𝓝[s] y) = 𝓝[(ext_chart_at I x).symm ⁻¹' s ∩ range I] (ext_chart_at I x y) := by rw [ext_chart_at_map_nhds_within_eq_image' I x hy, nhds_within_inter, ← nhds_within_ext_chart_target_eq' _ _ hy, ← nhds_within_inter, (ext_chart_at I x).image_source_inter_eq', inter_comm] lemma ext_chart_at_map_nhds_within : map (ext_chart_at I x) (𝓝[s] x) = 𝓝[(ext_chart_at I x).symm ⁻¹' s ∩ range I] (ext_chart_at I x x) := ext_chart_at_map_nhds_within' I x (mem_ext_chart_source I x) lemma ext_chart_at_symm_map_nhds_within' {y : M} (hy : y ∈ (ext_chart_at I x).source) : map (ext_chart_at I x).symm (𝓝[(ext_chart_at I x).symm ⁻¹' s ∩ range I] (ext_chart_at I x y)) = 𝓝[s] y := begin rw [← ext_chart_at_map_nhds_within' I x hy, map_map, map_congr, map_id], exact (ext_chart_at I x).left_inv_on.eq_on.eventually_eq_of_mem (ext_chart_at_source_mem_nhds_within' _ _ hy) end lemma ext_chart_at_symm_map_nhds_within_range' {y : M} (hy : y ∈ (ext_chart_at I x).source) : map (ext_chart_at I x).symm (𝓝[range I] (ext_chart_at I x y)) = 𝓝 y := by rw [← nhds_within_univ, ← ext_chart_at_symm_map_nhds_within' I x hy, preimage_univ, univ_inter] lemma ext_chart_at_symm_map_nhds_within : map (ext_chart_at I x).symm (𝓝[(ext_chart_at I x).symm ⁻¹' s ∩ range I] (ext_chart_at I x x)) = 𝓝[s] x := ext_chart_at_symm_map_nhds_within' I x (mem_ext_chart_source I x) lemma ext_chart_at_symm_map_nhds_within_range : map (ext_chart_at I x).symm (𝓝[range I] (ext_chart_at I x x)) = 𝓝 x := ext_chart_at_symm_map_nhds_within_range' 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') := by rwa [← ext_chart_at_symm_map_nhds_within' I x h, mem_map] at ht /-- 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
27f5aa038115582a8b1843acfdcf39b34c8a5fba
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/topology/sheaves/local_predicate.lean
a56463cec91acb6168bb7979052b35d54cfbb264
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
11,649
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 topology.sheaves.sheaf_of_functions import topology.sheaves.stalks import topology.local_homeomorph import topology.sheaves.sheaf_condition.unique_gluing /-! # Functions satisfying a local predicate form a sheaf. At this stage, in `topology/sheaves/sheaf_of_functions.lean` we've proved that not-necessarily-continuous functions from a topological space into some type (or type family) form a sheaf. Why do the continuous functions form a sheaf? The point is just that continuity is a local condition, so one can use the lifting condition for functions to provide a candidate lift, then verify that the lift is actually continuous by using the factorisation condition for the lift (which guarantees that on each open set it agrees with the functions being lifted, which were assumed to be continuous). This file abstracts this argument to work for any collection of dependent functions on a topological space satisfying a "local predicate". As an application, we check that continuity is a local predicate in this sense, and provide * `Top.sheaf_to_Top`: continuous functions into a topological space form a sheaf A sheaf constructed in this way has a natural map `stalk_to_fiber` from the stalks to the types in the ambient type family. We give conditions sufficient to show that this map is injective and/or surjective. -/ universe v noncomputable theory variables {X : Top.{v}} variables (T : X → Type v) open topological_space open opposite open category_theory open category_theory.limits open category_theory.limits.types namespace Top /-- Given a topological space `X : Top` and a type family `T : X → Type`, a `P : prelocal_predicate T` consists of: * a family of predicates `P.pred`, one for each `U : opens X`, of the form `(Π x : U, T x) → Prop` * a proof that if `f : Π x : V, T x` satisfies the predicate on `V : opens X`, then the restriction of `f` to any open subset `U` also satisfies the predicate. -/ structure prelocal_predicate := (pred : Π {U : opens X}, (Π x : U, T x) → Prop) (res : ∀ {U V : opens X} (i : U ⟶ V) (f : Π x : V, T x) (h : pred f), pred (λ x : U, f (i x))) variables (X) /-- Continuity is a "prelocal" predicate on functions to a fixed topological space `T`. -/ @[simps] def continuous_prelocal (T : Top.{v}) : prelocal_predicate (λ x : X, T) := { pred := λ U f, continuous f, res := λ U V i f h, continuous.comp h (opens.open_embedding_of_le i.le).continuous, } /-- Satisfying the inhabited linter. -/ instance inhabited_prelocal_predicate (T : Top.{v}) : inhabited (prelocal_predicate (λ x : X, T)) := ⟨continuous_prelocal X T⟩ variables {X} /-- Given a topological space `X : Top` and a type family `T : X → Type`, a `P : local_predicate T` consists of: * a family of predicates `P.pred`, one for each `U : opens X`, of the form `(Π x : U, T x) → Prop` * a proof that if `f : Π x : V, T x` satisfies the predicate on `V : opens X`, then the restriction of `f` to any open subset `U` also satisfies the predicate, and * a proof that given some `f : Π x : U, T x`, if for every `x : U` we can find an open set `x ∈ V ≤ U` so that the restriction of `f` to `V` satisfies the predicate, then `f` itself satisfies the predicate. -/ structure local_predicate extends prelocal_predicate T := (locality : ∀ {U : opens X} (f : Π x : U, T x) (w : ∀ x : U, ∃ (V : opens X) (m : x.1 ∈ V) (i : V ⟶ U), pred (λ x : V, f (i x : U))), pred f) variables (X) /-- Continuity is a "local" predicate on functions to a fixed topological space `T`. -/ def continuous_local (T : Top.{v}) : local_predicate (λ x : X, T) := { locality := λ U f w, begin apply continuous_iff_continuous_at.2, intro x, specialize w x, rcases w with ⟨V, m, i, w⟩, dsimp at w, rw continuous_iff_continuous_at at w, specialize w ⟨x, m⟩, simpa using (opens.open_embedding_of_le i.le).continuous_at_iff.1 w, end, ..continuous_prelocal X T } /-- Satisfying the inhabited linter. -/ instance inhabited_local_predicate (T : Top.{v}) : inhabited (local_predicate _) := ⟨continuous_local X T⟩ variables {X T} /-- Given a `P : prelocal_predicate`, we can always construct a `local_predicate` by asking that the condition from `P` holds locally near every point. -/ def prelocal_predicate.sheafify {T : X → Type v} (P : prelocal_predicate T) : local_predicate T := { pred := λ U f, ∀ x : U, ∃ (V : opens X) (m : x.1 ∈ V) (i : V ⟶ U), P.pred (λ x : V, f (i x : U)), res := λ V U i f w x, begin specialize w (i x), rcases w with ⟨V', m', i', p⟩, refine ⟨V ⊓ V', ⟨x.2,m'⟩, opens.inf_le_left _ _, _⟩, convert P.res (opens.inf_le_right V V') _ p, end, locality := λ U f w x, begin specialize w x, rcases w with ⟨V, m, i, p⟩, specialize p ⟨x.1, m⟩, rcases p with ⟨V', m', i', p'⟩, exact ⟨V', m', i' ≫ i, p'⟩, end } lemma prelocal_predicate.sheafify_of {T : X → Type v} {P : prelocal_predicate T} {U : opens X} {f : Π x : U, T x} (h : P.pred f) : P.sheafify.pred f := λ x, ⟨U, x.2, 𝟙 _, by { convert h, ext ⟨y, w⟩, refl, }⟩ /-- The subpresheaf of dependent functions on `X` satisfying the "pre-local" predicate `P`. -/ @[simps] def subpresheaf_to_Types (P : prelocal_predicate T) : presheaf (Type v) X := { obj := λ U, { f : Π x : unop U, T x // P.pred f }, map := λ U V i f, ⟨λ x, f.1 (i.unop x), P.res i.unop f.1 f.2⟩ }. namespace subpresheaf_to_Types variables (P : prelocal_predicate T) /-- The natural transformation including the subpresheaf of functions satisfying a local predicate into the presheaf of all functions. -/ def subtype : subpresheaf_to_Types P ⟶ presheaf_to_Types X T := { app := λ U f, f.1 } open Top.presheaf /-- The functions satisfying a local predicate satisfy the sheaf condition. -/ lemma is_sheaf (P : local_predicate T) : (subpresheaf_to_Types P.to_prelocal_predicate).is_sheaf := presheaf.is_sheaf_of_is_sheaf_unique_gluing_types _ $ λ ι U sf sf_comp, begin -- We show the sheaf condition in terms of unique gluing. -- First we obtain a family of sections for the underlying sheaf of functions, -- by forgetting that the prediacte holds let sf' : Π i : ι, (presheaf_to_Types X T).obj (op (U i)) := λ i, (sf i).val, -- Since our original family is compatible, this one is as well have sf'_comp : (presheaf_to_Types X T).is_compatible U sf' := λ i j, congr_arg subtype.val (sf_comp i j), -- So, we can obtain a unique gluing obtain ⟨gl,gl_spec,gl_uniq⟩ := (sheaf_to_Types X T).exists_unique_gluing U sf' sf'_comp, refine ⟨⟨gl,_⟩,_,_⟩, { -- Our first goal is to show that this chosen gluing satisfies the -- predicate. Of course, we use locality of the predicate. apply P.locality, rintros ⟨x, mem⟩, -- Once we're at a particular point `x`, we can select some open set `x ∈ U i`. choose i hi using opens.mem_supr.mp mem, -- We claim that the predicate holds in `U i` use [U i, hi, opens.le_supr U i], -- This follows, since our original family `sf` satisfies the predicate convert (sf i).property, exact gl_spec i }, -- It remains to show that the chosen lift is really a gluing for the subsheaf and -- that it is unique. Both of which follow immediately from the corresponding facts -- in the sheaf of functions without the local predicate. { intro i, ext1, exact (gl_spec i) }, { intros gl' hgl', ext1, exact gl_uniq gl'.1 (λ i, congr_arg subtype.val (hgl' i)) }, end end subpresheaf_to_Types /-- The subsheaf of the sheaf of all dependently typed functions satisfying the local predicate `P`. -/ @[simps] def subsheaf_to_Types (P : local_predicate T) : sheaf (Type v) X := ⟨subpresheaf_to_Types P.to_prelocal_predicate, subpresheaf_to_Types.is_sheaf P⟩ /-- There is a canonical map from the stalk to the original fiber, given by evaluating sections. -/ def stalk_to_fiber (P : local_predicate T) (x : X) : (subsheaf_to_Types P).1.stalk x ⟶ T x := begin refine colimit.desc _ { X := T x, ι := { app := λ U f, _, naturality' := _ } }, { exact f.1 ⟨x, (unop U).2⟩, }, { tidy, } end @[simp] lemma stalk_to_fiber_germ (P : local_predicate T) (U : opens X) (x : U) (f) : stalk_to_fiber P x ((subsheaf_to_Types P).1.germ x f) = f.1 x := begin dsimp [presheaf.germ, stalk_to_fiber], cases x, simp, refl, end /-- The `stalk_to_fiber` map is surjective at `x` if every point in the fiber `T x` has an allowed section passing through it. -/ lemma stalk_to_fiber_surjective (P : local_predicate T) (x : X) (w : ∀ (t : T x), ∃ (U : open_nhds x) (f : Π y : U.1, T y) (h : P.pred f), f ⟨x, U.2⟩ = t) : function.surjective (stalk_to_fiber P x) := λ t, begin rcases w t with ⟨U, f, h, rfl⟩, fsplit, { exact (subsheaf_to_Types P).1.germ ⟨x, U.2⟩ ⟨f, h⟩, }, { exact stalk_to_fiber_germ _ U.1 ⟨x, U.2⟩ ⟨f, h⟩, } end /-- The `stalk_to_fiber` map is injective at `x` if any two allowed sections which agree at `x` agree on some neighborhood of `x`. -/ lemma stalk_to_fiber_injective (P : local_predicate T) (x : X) (w : ∀ (U V : open_nhds x) (fU : Π y : U.1, T y) (hU : P.pred fU) (fV : Π y : V.1, T y) (hV : P.pred fV) (e : fU ⟨x, U.2⟩ = fV ⟨x, V.2⟩), ∃ (W : open_nhds x) (iU : W ⟶ U) (iV : W ⟶ V), ∀ (w : W.1), fU (iU w : U.1) = fV (iV w : V.1)) : function.injective (stalk_to_fiber P x) := λ tU tV h, begin -- We promise to provide all the ingredients of the proof later: let Q : ∃ (W : (open_nhds x)ᵒᵖ) (s : Π w : (unop W).1, T w) (hW : P.pred s), tU = (subsheaf_to_Types P).1.germ ⟨x, (unop W).2⟩ ⟨s, hW⟩ ∧ tV = (subsheaf_to_Types P).1.germ ⟨x, (unop W).2⟩ ⟨s, hW⟩ := _, { choose W s hW e using Q, exact e.1.trans e.2.symm, }, -- Then use induction to pick particular representatives of `tU tV : stalk x` obtain ⟨U, ⟨fU, hU⟩, rfl⟩ := jointly_surjective' tU, obtain ⟨V, ⟨fV, hV⟩, rfl⟩ := jointly_surjective' tV, { -- Decompose everything into its constituent parts: dsimp, simp only [stalk_to_fiber, types.colimit.ι_desc_apply] at h, specialize w (unop U) (unop V) fU hU fV hV h, rcases w with ⟨W, iU, iV, w⟩, -- and put it back together again in the correct order. refine ⟨(op W), (λ w, fU (iU w : (unop U).1)), P.res _ _ hU, _⟩, rcases W with ⟨W, m⟩, exact ⟨colimit_sound iU.op (subtype.eq rfl), colimit_sound iV.op (subtype.eq (funext w).symm)⟩, }, end /-- Some repackaging: the presheaf of functions satisfying `continuous_prelocal` is just the same thing as the presheaf of continuous functions. -/ def subpresheaf_continuous_prelocal_iso_presheaf_to_Top (T : Top.{v}) : subpresheaf_to_Types (continuous_prelocal X T) ≅ presheaf_to_Top X T := nat_iso.of_components (λ X, { hom := by { rintro ⟨f, c⟩, exact ⟨f, c⟩, }, inv := by { rintro ⟨f, c⟩, exact ⟨f, c⟩, }, hom_inv_id' := by { ext ⟨f, p⟩ x, refl, }, inv_hom_id' := by { ext ⟨f, p⟩ x, refl, }, }) (by tidy) /-- The sheaf of continuous functions on `X` with values in a space `T`. -/ def sheaf_to_Top (T : Top.{v}) : sheaf (Type v) X := ⟨presheaf_to_Top X T, presheaf.is_sheaf_of_iso (subpresheaf_continuous_prelocal_iso_presheaf_to_Top T) (subpresheaf_to_Types.is_sheaf (continuous_local X T))⟩ end Top
52536da17efe46536ab23092f26c726a8c5f1a8d
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/analysis/calculus/fderiv.lean
762bbff7d4bd99e05dd5078c79d02e19abdecbb7
[ "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
122,202
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Sébastien Gouëzel, Yury Kudryashov -/ import analysis.calculus.tangent_cone import analysis.normed_space.units import analysis.asymptotics.asymptotic_equivalent import analysis.analytic.basic /-! # The Fréchet derivative Let `E` and `F` be normed spaces, `f : E → F`, and `f' : E →L[𝕜] F` a continuous 𝕜-linear map, where `𝕜` is a non-discrete normed field. Then `has_fderiv_within_at f f' s x` says that `f` has derivative `f'` at `x`, where the domain of interest is restricted to `s`. We also have `has_fderiv_at f f' x := has_fderiv_within_at f f' x univ` Finally, `has_strict_fderiv_at f f' x` means that `f : E → F` has derivative `f' : E →L[𝕜] F` in the sense of strict differentiability, i.e., `f y - f z - f'(y - z) = o(y - z)` as `y, z → x`. This notion is used in the inverse function theorem, and is defined here only to avoid proving theorems like `is_bounded_bilinear_map.has_fderiv_at` twice: first for `has_fderiv_at`, then for `has_strict_fderiv_at`. ## Main results In addition to the definition and basic properties of the derivative, this file contains the usual formulas (and existence assertions) for the derivative of * constants * the identity * bounded linear maps * bounded bilinear maps * sum of two functions * sum of finitely many functions * multiplication of a function by a scalar constant * negative of a function * subtraction of two functions * multiplication of a function by a scalar function * multiplication of two scalar functions * composition of functions (the chain rule) * inverse function (assuming that it exists; the inverse function theorem is in `inverse.lean`) For most binary operations we also define `const_op` and `op_const` theorems for the cases when the first or second argument is a constant. This makes writing chains of `has_deriv_at`'s easier, and they more frequently lead to the desired result. One can also interpret the derivative of a function `f : 𝕜 → E` as an element of `E` (by identifying a linear function from `𝕜` to `E` with its value at `1`). Results on the Fréchet derivative are translated to this more elementary point of view on the derivative in the file `deriv.lean`. The derivative of polynomials is handled there, as it is naturally one-dimensional. The simplifier is set up to prove automatically that some functions are differentiable, or differentiable at a point (but not differentiable on a set or within a set at a point, as checking automatically that the good domains are mapped one to the other when using composition is not something the simplifier can easily do). This means that one can write `example (x : ℝ) : differentiable ℝ (λ x, sin (exp (3 + x^2)) - 5 * cos x) := by simp`. If there are divisions, one needs to supply to the simplifier proofs that the denominators do not vanish, as in ```lean example (x : ℝ) (h : 1 + sin x ≠ 0) : differentiable_at ℝ (λ x, exp x / (1 + sin x)) x := by simp [h] ``` Of course, these examples only work once `exp`, `cos` and `sin` have been shown to be differentiable, in `analysis.special_functions.trigonometric`. The simplifier is not set up to compute the Fréchet derivative of maps (as these are in general complicated multidimensional linear maps), but it will compute one-dimensional derivatives, see `deriv.lean`. ## Implementation details The derivative is defined in terms of the `is_o` relation, but also characterized in terms of the `tendsto` relation. We also introduce predicates `differentiable_within_at 𝕜 f s x` (where `𝕜` is the base field, `f` the function to be differentiated, `x` the point at which the derivative is asserted to exist, and `s` the set along which the derivative is defined), as well as `differentiable_at 𝕜 f x`, `differentiable_on 𝕜 f s` and `differentiable 𝕜 f` to express the existence of a derivative. To be able to compute with derivatives, we write `fderiv_within 𝕜 f s x` and `fderiv 𝕜 f x` for some choice of a derivative if it exists, and the zero function otherwise. This choice only behaves well along sets for which the derivative is unique, i.e., those for which the tangent directions span a dense subset of the whole space. The predicates `unique_diff_within_at s x` and `unique_diff_on s`, defined in `tangent_cone.lean` express this property. We prove that indeed they imply the uniqueness of the derivative. This is satisfied for open subsets, and in particular for `univ`. This uniqueness only holds when the field is non-discrete, which we request at the very beginning: otherwise, a derivative can be defined, but it has no interesting properties whatsoever. To make sure that the simplifier can prove automatically that functions are differentiable, we tag many lemmas with the `simp` attribute, for instance those saying that the sum of differentiable functions is differentiable, as well as their product, their cartesian product, and so on. A notable exception is the chain rule: we do not mark as a simp lemma the fact that, if `f` and `g` are differentiable, then their composition also is: `simp` would always be able to match this lemma, by taking `f` or `g` to be the identity. Instead, for every reasonable function (say, `exp`), we add a lemma that if `f` is differentiable then so is `(λ x, exp (f x))`. This means adding some boilerplate lemmas, but these can also be useful in their own right. Tests for this ability of the simplifier (with more examples) are provided in `tests/differentiable.lean`. ## Tags derivative, differentiable, Fréchet, calculus -/ open filter asymptotics continuous_linear_map set metric open_locale topological_space classical nnreal asymptotics filter ennreal noncomputable theory section variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] variables {G : Type*} [normed_group G] [normed_space 𝕜 G] variables {G' : Type*} [normed_group G'] [normed_space 𝕜 G'] /-- A function `f` has the continuous linear map `f'` as derivative along the filter `L` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` converges along the filter `L`. This definition is designed to be specialized for `L = 𝓝 x` (in `has_fderiv_at`), giving rise to the usual notion of Fréchet derivative, and for `L = 𝓝[s] x` (in `has_fderiv_within_at`), giving rise to the notion of Fréchet derivative along the set `s`. -/ def has_fderiv_at_filter (f : E → F) (f' : E →L[𝕜] F) (x : E) (L : filter E) := is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L /-- A function `f` has the continuous linear map `f'` as derivative at `x` within a set `s` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` tends to `x` inside `s`. -/ def has_fderiv_within_at (f : E → F) (f' : E →L[𝕜] F) (s : set E) (x : E) := has_fderiv_at_filter f f' x (𝓝[s] x) /-- A function `f` has the continuous linear map `f'` as derivative at `x` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` tends to `x`. -/ def has_fderiv_at (f : E → F) (f' : E →L[𝕜] F) (x : E) := has_fderiv_at_filter f f' x (𝓝 x) /-- A function `f` has derivative `f'` at `a` in the sense of *strict differentiability* if `f x - f y - f' (x - y) = o(x - y)` as `x, y → a`. This form of differentiability is required, e.g., by the inverse function theorem. Any `C^1` function on a vector space over `ℝ` is strictly differentiable but this definition works, e.g., for vector spaces over `p`-adic numbers. -/ def has_strict_fderiv_at (f : E → F) (f' : E →L[𝕜] F) (x : E) := is_o (λ p : E × E, f p.1 - f p.2 - f' (p.1 - p.2)) (λ p : E × E, p.1 - p.2) (𝓝 (x, x)) variables (𝕜) /-- A function `f` is differentiable at a point `x` within a set `s` if it admits a derivative there (possibly non-unique). -/ def differentiable_within_at (f : E → F) (s : set E) (x : E) := ∃f' : E →L[𝕜] F, has_fderiv_within_at f f' s x /-- A function `f` is differentiable at a point `x` if it admits a derivative there (possibly non-unique). -/ def differentiable_at (f : E → F) (x : E) := ∃f' : E →L[𝕜] F, has_fderiv_at f f' x /-- If `f` has a derivative at `x` within `s`, then `fderiv_within 𝕜 f s x` is such a derivative. Otherwise, it is set to `0`. -/ def fderiv_within (f : E → F) (s : set E) (x : E) : E →L[𝕜] F := if h : ∃f', has_fderiv_within_at f f' s x then classical.some h else 0 /-- If `f` has a derivative at `x`, then `fderiv 𝕜 f x` is such a derivative. Otherwise, it is set to `0`. -/ def fderiv (f : E → F) (x : E) : E →L[𝕜] F := if h : ∃f', has_fderiv_at f f' x then classical.some h else 0 /-- `differentiable_on 𝕜 f s` means that `f` is differentiable within `s` at any point of `s`. -/ def differentiable_on (f : E → F) (s : set E) := ∀x ∈ s, differentiable_within_at 𝕜 f s x /-- `differentiable 𝕜 f` means that `f` is differentiable at any point. -/ def differentiable (f : E → F) := ∀x, differentiable_at 𝕜 f x variables {𝕜} variables {f f₀ f₁ g : E → F} variables {f' f₀' f₁' g' : E →L[𝕜] F} variables (e : E →L[𝕜] F) variables {x : E} variables {s t : set E} variables {L L₁ L₂ : filter E} lemma fderiv_within_zero_of_not_differentiable_within_at (h : ¬ differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 f s x = 0 := have ¬ ∃ f', has_fderiv_within_at f f' s x, from h, by simp [fderiv_within, this] lemma fderiv_zero_of_not_differentiable_at (h : ¬ differentiable_at 𝕜 f x) : fderiv 𝕜 f x = 0 := have ¬ ∃ f', has_fderiv_at f f' x, from h, by simp [fderiv, this] section derivative_uniqueness /- In this section, we discuss the uniqueness of the derivative. We prove that the definitions `unique_diff_within_at` and `unique_diff_on` indeed imply the uniqueness of the derivative. -/ /-- If a function f has a derivative f' at x, a rescaled version of f around x converges to f', i.e., `n (f (x + (1/n) v) - f x)` converges to `f' v`. More generally, if `c n` tends to infinity and `c n * d n` tends to `v`, then `c n * (f (x + d n) - f x)` tends to `f' v`. This lemma expresses this fact, for functions having a derivative within a set. Its specific formulation is useful for tangent cone related discussions. -/ theorem has_fderiv_within_at.lim (h : has_fderiv_within_at f f' s x) {α : Type*} (l : filter α) {c : α → 𝕜} {d : α → E} {v : E} (dtop : ∀ᶠ n in l, x + d n ∈ s) (clim : tendsto (λ n, ∥c n∥) l at_top) (cdlim : tendsto (λ n, c n • d n) l (𝓝 v)) : tendsto (λn, c n • (f (x + d n) - f x)) l (𝓝 (f' v)) := begin have tendsto_arg : tendsto (λ n, x + d n) l (𝓝[s] x), { conv in (𝓝[s] x) { rw ← add_zero x }, rw [nhds_within, tendsto_inf], split, { apply tendsto_const_nhds.add (tangent_cone_at.lim_zero l clim cdlim) }, { rwa tendsto_principal } }, have : is_o (λ y, f y - f x - f' (y - x)) (λ y, y - x) (𝓝[s] x) := h, have : is_o (λ n, f (x + d n) - f x - f' ((x + d n) - x)) (λ n, (x + d n) - x) l := this.comp_tendsto tendsto_arg, have : is_o (λ n, f (x + d n) - f x - f' (d n)) d l := by simpa only [add_sub_cancel'], have : is_o (λn, c n • (f (x + d n) - f x - f' (d n))) (λn, c n • d n) l := (is_O_refl c l).smul_is_o this, have : is_o (λn, c n • (f (x + d n) - f x - f' (d n))) (λn, (1:ℝ)) l := this.trans_is_O (is_O_one_of_tendsto ℝ cdlim), have L1 : tendsto (λn, c n • (f (x + d n) - f x - f' (d n))) l (𝓝 0) := (is_o_one_iff ℝ).1 this, have L2 : tendsto (λn, f' (c n • d n)) l (𝓝 (f' v)) := tendsto.comp f'.cont.continuous_at cdlim, have L3 : tendsto (λn, (c n • (f (x + d n) - f x - f' (d n)) + f' (c n • d n))) l (𝓝 (0 + f' v)) := L1.add L2, have : (λn, (c n • (f (x + d n) - f x - f' (d n)) + f' (c n • d n))) = (λn, c n • (f (x + d n) - f x)), by { ext n, simp [smul_add, smul_sub] }, rwa [this, zero_add] at L3 end /-- If `f'` and `f₁'` are two derivatives of `f` within `s` at `x`, then they are equal on the tangent cone to `s` at `x` -/ theorem has_fderiv_within_at.unique_on (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at f f₁' s x) : eq_on f' f₁' (tangent_cone_at 𝕜 s x) := λ y ⟨c, d, dtop, clim, cdlim⟩, tendsto_nhds_unique (hf.lim at_top dtop clim cdlim) (hg.lim at_top dtop clim cdlim) /-- `unique_diff_within_at` achieves its goal: it implies the uniqueness of the derivative. -/ theorem unique_diff_within_at.eq (H : unique_diff_within_at 𝕜 s x) (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at f f₁' s x) : f' = f₁' := continuous_linear_map.ext_on H.1 (hf.unique_on hg) theorem unique_diff_on.eq (H : unique_diff_on 𝕜 s) (hx : x ∈ s) (h : has_fderiv_within_at f f' s x) (h₁ : has_fderiv_within_at f f₁' s x) : f' = f₁' := (H x hx).eq h h₁ end derivative_uniqueness section fderiv_properties /-! ### Basic properties of the derivative -/ theorem has_fderiv_at_filter_iff_tendsto : has_fderiv_at_filter f f' x L ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (𝓝 0) := have h : ∀ x', ∥x' - x∥ = 0 → ∥f x' - f x - f' (x' - x)∥ = 0, from λ x' hx', by { rw [sub_eq_zero.1 (norm_eq_zero.1 hx')], simp }, begin unfold has_fderiv_at_filter, rw [←is_o_norm_left, ←is_o_norm_right, is_o_iff_tendsto h], exact tendsto_congr (λ _, div_eq_inv_mul), end theorem has_fderiv_within_at_iff_tendsto : has_fderiv_within_at f f' s x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (𝓝[s] x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_fderiv_at_iff_tendsto : has_fderiv_at f f' x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (𝓝 x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_fderiv_at_iff_is_o_nhds_zero : has_fderiv_at f f' x ↔ is_o (λh, f (x + h) - f x - f' h) (λh, h) (𝓝 0) := begin rw [has_fderiv_at, has_fderiv_at_filter, ← map_add_left_nhds_zero x, is_o_map], simp [(∘)] end /-- Converse to the mean value inequality: if `f` is differentiable at `x₀` and `C`-lipschitz on a neighborhood of `x₀` then it its derivative at `x₀` has norm bounded by `C`. -/ lemma has_fderiv_at.le_of_lip {f : E → F} {f' : E →L[𝕜] F} {x₀ : E} (hf : has_fderiv_at f f' x₀) {s : set E} (hs : s ∈ 𝓝 x₀) {C : ℝ≥0} (hlip : lipschitz_on_with C f s) : ∥f'∥ ≤ C := begin refine le_of_forall_pos_le_add (λ ε ε0, op_norm_le_of_nhds_zero _ _), exact add_nonneg C.coe_nonneg ε0.le, have hs' := hs, rw [← map_add_left_nhds_zero x₀, mem_map] at hs', filter_upwards [is_o_iff.1 (has_fderiv_at_iff_is_o_nhds_zero.1 hf) ε0, hs'], intros y hy hys, have := hlip.norm_sub_le hys (mem_of_mem_nhds hs), rw add_sub_cancel' at this, calc ∥f' y∥ ≤ ∥f (x₀ + y) - f x₀∥ + ∥f (x₀ + y) - f x₀ - f' y∥ : norm_le_insert _ _ ... ≤ C * ∥y∥ + ε * ∥y∥ : add_le_add this hy ... = (C + ε) * ∥y∥ : (add_mul _ _ _).symm end theorem has_fderiv_at_filter.mono (h : has_fderiv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) : has_fderiv_at_filter f f' x L₁ := h.mono hst theorem has_fderiv_within_at.mono (h : has_fderiv_within_at f f' t x) (hst : s ⊆ t) : has_fderiv_within_at f f' s x := h.mono (nhds_within_mono _ hst) theorem has_fderiv_at.has_fderiv_at_filter (h : has_fderiv_at f f' x) (hL : L ≤ 𝓝 x) : has_fderiv_at_filter f f' x L := h.mono hL theorem has_fderiv_at.has_fderiv_within_at (h : has_fderiv_at f f' x) : has_fderiv_within_at f f' s x := h.has_fderiv_at_filter inf_le_left lemma has_fderiv_within_at.differentiable_within_at (h : has_fderiv_within_at f f' s x) : differentiable_within_at 𝕜 f s x := ⟨f', h⟩ lemma has_fderiv_at.differentiable_at (h : has_fderiv_at f f' x) : differentiable_at 𝕜 f x := ⟨f', h⟩ @[simp] lemma has_fderiv_within_at_univ : has_fderiv_within_at f f' univ x ↔ has_fderiv_at f f' x := by { simp only [has_fderiv_within_at, nhds_within_univ], refl } lemma has_strict_fderiv_at.is_O_sub (hf : has_strict_fderiv_at f f' x) : is_O (λ p : E × E, f p.1 - f p.2) (λ p : E × E, p.1 - p.2) (𝓝 (x, x)) := hf.is_O.congr_of_sub.2 (f'.is_O_comp _ _) lemma has_fderiv_at_filter.is_O_sub (h : has_fderiv_at_filter f f' x L) : is_O (λ x', f x' - f x) (λ x', x' - x) L := h.is_O.congr_of_sub.2 (f'.is_O_sub _ _) protected lemma has_strict_fderiv_at.has_fderiv_at (hf : has_strict_fderiv_at f f' x) : has_fderiv_at f f' x := begin rw [has_fderiv_at, has_fderiv_at_filter, is_o_iff], exact (λ c hc, tendsto_id.prod_mk_nhds tendsto_const_nhds (is_o_iff.1 hf hc)) end protected lemma has_strict_fderiv_at.differentiable_at (hf : has_strict_fderiv_at f f' x) : differentiable_at 𝕜 f x := hf.has_fderiv_at.differentiable_at /-- Directional derivative agrees with `has_fderiv`. -/ lemma has_fderiv_at.lim (hf : has_fderiv_at f f' x) (v : E) {α : Type*} {c : α → 𝕜} {l : filter α} (hc : tendsto (λ n, ∥c n∥) l at_top) : tendsto (λ n, (c n) • (f (x + (c n)⁻¹ • v) - f x)) l (𝓝 (f' v)) := begin refine (has_fderiv_within_at_univ.2 hf).lim _ (univ_mem_sets' (λ _, trivial)) hc _, assume U hU, refine (eventually_ne_of_tendsto_norm_at_top hc (0:𝕜)).mono (λ y hy, _), convert mem_of_mem_nhds hU, dsimp only, rw [← mul_smul, mul_inv_cancel hy, one_smul] end theorem has_fderiv_at.unique (h₀ : has_fderiv_at f f₀' x) (h₁ : has_fderiv_at f f₁' x) : f₀' = f₁' := begin rw ← has_fderiv_within_at_univ at h₀ h₁, exact unique_diff_within_at_univ.eq h₀ h₁ end lemma has_fderiv_within_at_inter' (h : t ∈ 𝓝[s] x) : has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x := by simp [has_fderiv_within_at, nhds_within_restrict'' s h] lemma has_fderiv_within_at_inter (h : t ∈ 𝓝 x) : has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x := by simp [has_fderiv_within_at, nhds_within_restrict' s h] lemma has_fderiv_within_at.union (hs : has_fderiv_within_at f f' s x) (ht : has_fderiv_within_at f f' t x) : has_fderiv_within_at f f' (s ∪ t) x := begin simp only [has_fderiv_within_at, nhds_within_union], exact hs.join ht, end lemma has_fderiv_within_at.nhds_within (h : has_fderiv_within_at f f' s x) (ht : s ∈ 𝓝[t] x) : has_fderiv_within_at f f' t x := (has_fderiv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _)) lemma has_fderiv_within_at.has_fderiv_at (h : has_fderiv_within_at f f' s x) (hs : s ∈ 𝓝 x) : has_fderiv_at f f' x := by rwa [← univ_inter s, has_fderiv_within_at_inter hs, has_fderiv_within_at_univ] at h lemma differentiable_within_at.has_fderiv_within_at (h : differentiable_within_at 𝕜 f s x) : has_fderiv_within_at f (fderiv_within 𝕜 f s x) s x := begin dunfold fderiv_within, dunfold differentiable_within_at at h, rw dif_pos h, exact classical.some_spec h end lemma differentiable_at.has_fderiv_at (h : differentiable_at 𝕜 f x) : has_fderiv_at f (fderiv 𝕜 f x) x := begin dunfold fderiv, dunfold differentiable_at at h, rw dif_pos h, exact classical.some_spec h end lemma has_fderiv_at.fderiv (h : has_fderiv_at f f' x) : fderiv 𝕜 f x = f' := by { ext, rw h.unique h.differentiable_at.has_fderiv_at } /-- Converse to the mean value inequality: if `f` is differentiable at `x₀` and `C`-lipschitz on a neighborhood of `x₀` then it its derivative at `x₀` has norm bounded by `C`. Version using `fderiv`. -/ lemma fderiv_at.le_of_lip {f : E → F} {x₀ : E} (hf : differentiable_at 𝕜 f x₀) {s : set E} (hs : s ∈ 𝓝 x₀) {C : ℝ≥0} (hlip : lipschitz_on_with C f s) : ∥fderiv 𝕜 f x₀∥ ≤ C := hf.has_fderiv_at.le_of_lip hs hlip lemma has_fderiv_within_at.fderiv_within (h : has_fderiv_within_at f f' s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = f' := (hxs.eq h h.differentiable_within_at.has_fderiv_within_at).symm /-- If `x` is not in the closure of `s`, then `f` has any derivative at `x` within `s`, as this statement is empty. -/ lemma has_fderiv_within_at_of_not_mem_closure (h : x ∉ closure s) : has_fderiv_within_at f f' s x := begin simp only [mem_closure_iff_nhds_within_ne_bot, ne_bot_iff, ne.def, not_not] at h, simp [has_fderiv_within_at, has_fderiv_at_filter, h, is_o, is_O_with], end lemma differentiable_within_at.mono (h : differentiable_within_at 𝕜 f t x) (st : s ⊆ t) : differentiable_within_at 𝕜 f s x := begin rcases h with ⟨f', hf'⟩, exact ⟨f', hf'.mono st⟩ end lemma differentiable_within_at_univ : differentiable_within_at 𝕜 f univ x ↔ differentiable_at 𝕜 f x := by simp only [differentiable_within_at, has_fderiv_within_at_univ, differentiable_at] lemma differentiable_within_at_inter (ht : t ∈ 𝓝 x) : differentiable_within_at 𝕜 f (s ∩ t) x ↔ differentiable_within_at 𝕜 f s x := by simp only [differentiable_within_at, has_fderiv_within_at, has_fderiv_at_filter, nhds_within_restrict' s ht] lemma differentiable_within_at_inter' (ht : t ∈ 𝓝[s] x) : differentiable_within_at 𝕜 f (s ∩ t) x ↔ differentiable_within_at 𝕜 f s x := by simp only [differentiable_within_at, has_fderiv_within_at, has_fderiv_at_filter, nhds_within_restrict'' s ht] lemma differentiable_at.differentiable_within_at (h : differentiable_at 𝕜 f x) : differentiable_within_at 𝕜 f s x := (differentiable_within_at_univ.2 h).mono (subset_univ _) lemma differentiable.differentiable_at (h : differentiable 𝕜 f) : differentiable_at 𝕜 f x := h x lemma differentiable_within_at.differentiable_at (h : differentiable_within_at 𝕜 f s x) (hs : s ∈ 𝓝 x) : differentiable_at 𝕜 f x := h.imp (λ f' hf', hf'.has_fderiv_at hs) lemma differentiable_at.fderiv_within (h : differentiable_at 𝕜 f x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = fderiv 𝕜 f x := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact h.has_fderiv_at.has_fderiv_within_at end lemma differentiable_on.mono (h : differentiable_on 𝕜 f t) (st : s ⊆ t) : differentiable_on 𝕜 f s := λx hx, (h x (st hx)).mono st lemma differentiable_on_univ : differentiable_on 𝕜 f univ ↔ differentiable 𝕜 f := by { simp [differentiable_on, differentiable_within_at_univ], refl } lemma differentiable.differentiable_on (h : differentiable 𝕜 f) : differentiable_on 𝕜 f s := (differentiable_on_univ.2 h).mono (subset_univ _) lemma differentiable_on_of_locally_differentiable_on (h : ∀x∈s, ∃u, is_open u ∧ x ∈ u ∧ differentiable_on 𝕜 f (s ∩ u)) : differentiable_on 𝕜 f s := begin assume x xs, rcases h x xs with ⟨t, t_open, xt, ht⟩, exact (differentiable_within_at_inter (is_open.mem_nhds t_open xt)).1 (ht x ⟨xs, xt⟩) end lemma fderiv_within_subset (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f t x) : fderiv_within 𝕜 f s x = fderiv_within 𝕜 f t x := ((differentiable_within_at.has_fderiv_within_at h).mono st).fderiv_within ht @[simp] lemma fderiv_within_univ : fderiv_within 𝕜 f univ = fderiv 𝕜 f := begin ext x : 1, by_cases h : differentiable_at 𝕜 f x, { apply has_fderiv_within_at.fderiv_within _ unique_diff_within_at_univ, rw has_fderiv_within_at_univ, apply h.has_fderiv_at }, { have : ¬ differentiable_within_at 𝕜 f univ x, by contrapose! h; rwa ← differentiable_within_at_univ, rw [fderiv_zero_of_not_differentiable_at h, fderiv_within_zero_of_not_differentiable_within_at this] } end lemma fderiv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f (s ∩ t) x = fderiv_within 𝕜 f s x := begin by_cases h : differentiable_within_at 𝕜 f (s ∩ t) x, { apply fderiv_within_subset (inter_subset_left _ _) _ ((differentiable_within_at_inter ht).1 h), apply hs.inter ht }, { have : ¬ differentiable_within_at 𝕜 f s x, by contrapose! h; rw differentiable_within_at_inter; assumption, rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at this] } end lemma fderiv_within_of_mem_nhds (h : s ∈ 𝓝 x) : fderiv_within 𝕜 f s x = fderiv 𝕜 f x := begin have : s = univ ∩ s, by simp only [univ_inter], rw [this, ← fderiv_within_univ], exact fderiv_within_inter h (unique_diff_on_univ _ (mem_univ _)) end lemma fderiv_within_of_open (hs : is_open s) (hx : x ∈ s) : fderiv_within 𝕜 f s x = fderiv 𝕜 f x := fderiv_within_of_mem_nhds (is_open.mem_nhds hs hx) lemma fderiv_within_eq_fderiv (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_at 𝕜 f x) : fderiv_within 𝕜 f s x = fderiv 𝕜 f x := begin rw ← fderiv_within_univ, exact fderiv_within_subset (subset_univ _) hs h.differentiable_within_at end lemma fderiv_mem_iff {f : E → F} {s : set (E →L[𝕜] F)} {x : E} : fderiv 𝕜 f x ∈ s ↔ (differentiable_at 𝕜 f x ∧ fderiv 𝕜 f x ∈ s) ∨ (0 : E →L[𝕜] F) ∈ s ∧ ¬differentiable_at 𝕜 f x := begin split, { intro hfx, by_cases hx : differentiable_at 𝕜 f x, { exact or.inl ⟨hx, hfx⟩ }, { rw [fderiv_zero_of_not_differentiable_at hx] at hfx, exact or.inr ⟨hfx, hx⟩ } }, { rintro (⟨hf, hf'⟩|⟨h₀, hx⟩), { exact hf' }, { rwa [fderiv_zero_of_not_differentiable_at hx] } } end end fderiv_properties section continuous /-! ### Deducing continuity from differentiability -/ theorem has_fderiv_at_filter.tendsto_nhds (hL : L ≤ 𝓝 x) (h : has_fderiv_at_filter f f' x L) : tendsto f L (𝓝 (f x)) := begin have : tendsto (λ x', f x' - f x) L (𝓝 0), { refine h.is_O_sub.trans_tendsto (tendsto.mono_left _ hL), rw ← sub_self x, exact tendsto_id.sub tendsto_const_nhds }, have := tendsto.add this tendsto_const_nhds, rw zero_add (f x) at this, exact this.congr (by simp) end theorem has_fderiv_within_at.continuous_within_at (h : has_fderiv_within_at f f' s x) : continuous_within_at f s x := has_fderiv_at_filter.tendsto_nhds inf_le_left h theorem has_fderiv_at.continuous_at (h : has_fderiv_at f f' x) : continuous_at f x := has_fderiv_at_filter.tendsto_nhds (le_refl _) h lemma differentiable_within_at.continuous_within_at (h : differentiable_within_at 𝕜 f s x) : continuous_within_at f s x := let ⟨f', hf'⟩ := h in hf'.continuous_within_at lemma differentiable_at.continuous_at (h : differentiable_at 𝕜 f x) : continuous_at f x := let ⟨f', hf'⟩ := h in hf'.continuous_at lemma differentiable_on.continuous_on (h : differentiable_on 𝕜 f s) : continuous_on f s := λx hx, (h x hx).continuous_within_at lemma differentiable.continuous (h : differentiable 𝕜 f) : continuous f := continuous_iff_continuous_at.2 $ λx, (h x).continuous_at protected lemma has_strict_fderiv_at.continuous_at (hf : has_strict_fderiv_at f f' x) : continuous_at f x := hf.has_fderiv_at.continuous_at lemma has_strict_fderiv_at.is_O_sub_rev {f' : E ≃L[𝕜] F} (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) x) : is_O (λ p : E × E, p.1 - p.2) (λ p : E × E, f p.1 - f p.2) (𝓝 (x, x)) := ((f'.is_O_comp_rev _ _).trans (hf.trans_is_O (f'.is_O_comp_rev _ _)).right_is_O_add).congr (λ _, rfl) (λ _, sub_add_cancel _ _) lemma has_fderiv_at_filter.is_O_sub_rev {f' : E ≃L[𝕜] F} (hf : has_fderiv_at_filter f (f' : E →L[𝕜] F) x L) : is_O (λ x', x' - x) (λ x', f x' - f x) L := ((f'.is_O_sub_rev _ _).trans (hf.trans_is_O (f'.is_O_sub_rev _ _)).right_is_O_add).congr (λ _, rfl) (λ _, sub_add_cancel _ _) end continuous section congr /-! ### congr properties of the derivative -/ theorem filter.eventually_eq.has_strict_fderiv_at_iff (h : f₀ =ᶠ[𝓝 x] f₁) (h' : ∀ y, f₀' y = f₁' y) : has_strict_fderiv_at f₀ f₀' x ↔ has_strict_fderiv_at f₁ f₁' x := begin refine is_o_congr ((h.prod_mk_nhds h).mono _) (eventually_of_forall $ λ _, rfl), rintros p ⟨hp₁, hp₂⟩, simp only [*] end theorem has_strict_fderiv_at.congr_of_eventually_eq (h : has_strict_fderiv_at f f' x) (h₁ : f =ᶠ[𝓝 x] f₁) : has_strict_fderiv_at f₁ f' x := (h₁.has_strict_fderiv_at_iff (λ _, rfl)).1 h theorem filter.eventually_eq.has_fderiv_at_filter_iff (h₀ : f₀ =ᶠ[L] f₁) (hx : f₀ x = f₁ x) (h₁ : ∀ x, f₀' x = f₁' x) : has_fderiv_at_filter f₀ f₀' x L ↔ has_fderiv_at_filter f₁ f₁' x L := is_o_congr (h₀.mono $ λ y hy, by simp only [hy, h₁, hx]) (eventually_of_forall $ λ _, rfl) lemma has_fderiv_at_filter.congr_of_eventually_eq (h : has_fderiv_at_filter f f' x L) (hL : f₁ =ᶠ[L] f) (hx : f₁ x = f x) : has_fderiv_at_filter f₁ f' x L := (hL.has_fderiv_at_filter_iff hx $ λ _, rfl).2 h lemma has_fderiv_within_at.congr_mono (h : has_fderiv_within_at f f' s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : has_fderiv_within_at f₁ f' t x := has_fderiv_at_filter.congr_of_eventually_eq (h.mono h₁) (filter.mem_inf_sets_of_right ht) hx lemma has_fderiv_within_at.congr (h : has_fderiv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x := h.congr_mono hs hx (subset.refl _) lemma has_fderiv_within_at.congr' (h : has_fderiv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x) (hx : x ∈ s) : has_fderiv_within_at f₁ f' s x := h.congr hs (hs x hx) lemma has_fderiv_within_at.congr_of_eventually_eq (h : has_fderiv_within_at f f' s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x := has_fderiv_at_filter.congr_of_eventually_eq h h₁ hx lemma has_fderiv_at.congr_of_eventually_eq (h : has_fderiv_at f f' x) (h₁ : f₁ =ᶠ[𝓝 x] f) : has_fderiv_at f₁ f' x := has_fderiv_at_filter.congr_of_eventually_eq h h₁ (mem_of_mem_nhds h₁ : _) lemma differentiable_within_at.congr_mono (h : differentiable_within_at 𝕜 f s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : differentiable_within_at 𝕜 f₁ t x := (has_fderiv_within_at.congr_mono h.has_fderiv_within_at ht hx h₁).differentiable_within_at lemma differentiable_within_at.congr (h : differentiable_within_at 𝕜 f s x) (ht : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x := differentiable_within_at.congr_mono h ht hx (subset.refl _) lemma differentiable_within_at.congr_of_eventually_eq (h : differentiable_within_at 𝕜 f s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x := (h.has_fderiv_within_at.congr_of_eventually_eq h₁ hx).differentiable_within_at lemma differentiable_on.congr_mono (h : differentiable_on 𝕜 f s) (h' : ∀x ∈ t, f₁ x = f x) (h₁ : t ⊆ s) : differentiable_on 𝕜 f₁ t := λ x hx, (h x (h₁ hx)).congr_mono h' (h' x hx) h₁ lemma differentiable_on.congr (h : differentiable_on 𝕜 f s) (h' : ∀x ∈ s, f₁ x = f x) : differentiable_on 𝕜 f₁ s := λ x hx, (h x hx).congr h' (h' x hx) lemma differentiable_on_congr (h' : ∀x ∈ s, f₁ x = f x) : differentiable_on 𝕜 f₁ s ↔ differentiable_on 𝕜 f s := ⟨λ h, differentiable_on.congr h (λy hy, (h' y hy).symm), λ h, differentiable_on.congr h h'⟩ lemma differentiable_at.congr_of_eventually_eq (h : differentiable_at 𝕜 f x) (hL : f₁ =ᶠ[𝓝 x] f) : differentiable_at 𝕜 f₁ x := has_fderiv_at.differentiable_at (has_fderiv_at_filter.congr_of_eventually_eq h.has_fderiv_at hL (mem_of_mem_nhds hL : _)) lemma differentiable_within_at.fderiv_within_congr_mono (h : differentiable_within_at 𝕜 f s x) (hs : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (hxt : unique_diff_within_at 𝕜 t x) (h₁ : t ⊆ s) : fderiv_within 𝕜 f₁ t x = fderiv_within 𝕜 f s x := (has_fderiv_within_at.congr_mono h.has_fderiv_within_at hs hx h₁).fderiv_within hxt lemma filter.eventually_eq.fderiv_within_eq (hs : unique_diff_within_at 𝕜 s x) (hL : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x := if h : differentiable_within_at 𝕜 f s x then has_fderiv_within_at.fderiv_within (h.has_fderiv_within_at.congr_of_eventually_eq hL hx) hs else have h' : ¬ differentiable_within_at 𝕜 f₁ s x, from mt (λ h, h.congr_of_eventually_eq (hL.mono $ λ x, eq.symm) hx.symm) h, by rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at h'] lemma fderiv_within_congr (hs : unique_diff_within_at 𝕜 s x) (hL : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) : fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x := begin apply filter.eventually_eq.fderiv_within_eq hs _ hx, apply mem_sets_of_superset self_mem_nhds_within, exact hL end lemma filter.eventually_eq.fderiv_eq (hL : f₁ =ᶠ[𝓝 x] f) : fderiv 𝕜 f₁ x = fderiv 𝕜 f x := begin have A : f₁ x = f x := hL.eq_of_nhds, rw [← fderiv_within_univ, ← fderiv_within_univ], rw ← nhds_within_univ at hL, exact hL.fderiv_within_eq unique_diff_within_at_univ A end end congr section id /-! ### Derivative of the identity -/ theorem has_strict_fderiv_at_id (x : E) : has_strict_fderiv_at id (id 𝕜 E) x := (is_o_zero _ _).congr_left $ by simp theorem has_fderiv_at_filter_id (x : E) (L : filter E) : has_fderiv_at_filter id (id 𝕜 E) x L := (is_o_zero _ _).congr_left $ by simp theorem has_fderiv_within_at_id (x : E) (s : set E) : has_fderiv_within_at id (id 𝕜 E) s x := has_fderiv_at_filter_id _ _ theorem has_fderiv_at_id (x : E) : has_fderiv_at id (id 𝕜 E) x := has_fderiv_at_filter_id _ _ @[simp] lemma differentiable_at_id : differentiable_at 𝕜 id x := (has_fderiv_at_id x).differentiable_at @[simp] lemma differentiable_at_id' : differentiable_at 𝕜 (λ x, x) x := (has_fderiv_at_id x).differentiable_at lemma differentiable_within_at_id : differentiable_within_at 𝕜 id s x := differentiable_at_id.differentiable_within_at @[simp] lemma differentiable_id : differentiable 𝕜 (id : E → E) := λx, differentiable_at_id @[simp] lemma differentiable_id' : differentiable 𝕜 (λ (x : E), x) := λx, differentiable_at_id lemma differentiable_on_id : differentiable_on 𝕜 id s := differentiable_id.differentiable_on lemma fderiv_id : fderiv 𝕜 id x = id 𝕜 E := has_fderiv_at.fderiv (has_fderiv_at_id x) @[simp] lemma fderiv_id' : fderiv 𝕜 (λ (x : E), x) x = continuous_linear_map.id 𝕜 E := fderiv_id lemma fderiv_within_id (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 id s x = id 𝕜 E := begin rw differentiable_at.fderiv_within (differentiable_at_id) hxs, exact fderiv_id end lemma fderiv_within_id' (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λ (x : E), x) s x = continuous_linear_map.id 𝕜 E := fderiv_within_id hxs end id section const /-! ### derivative of a constant function -/ theorem has_strict_fderiv_at_const (c : F) (x : E) : has_strict_fderiv_at (λ _, c) (0 : E →L[𝕜] F) x := (is_o_zero _ _).congr_left $ λ _, by simp only [zero_apply, sub_self] theorem has_fderiv_at_filter_const (c : F) (x : E) (L : filter E) : has_fderiv_at_filter (λ x, c) (0 : E →L[𝕜] F) x L := (is_o_zero _ _).congr_left $ λ _, by simp only [zero_apply, sub_self] theorem has_fderiv_within_at_const (c : F) (x : E) (s : set E) : has_fderiv_within_at (λ x, c) (0 : E →L[𝕜] F) s x := has_fderiv_at_filter_const _ _ _ theorem has_fderiv_at_const (c : F) (x : E) : has_fderiv_at (λ x, c) (0 : E →L[𝕜] F) x := has_fderiv_at_filter_const _ _ _ @[simp] lemma differentiable_at_const (c : F) : differentiable_at 𝕜 (λx, c) x := ⟨0, has_fderiv_at_const c x⟩ lemma differentiable_within_at_const (c : F) : differentiable_within_at 𝕜 (λx, c) s x := differentiable_at.differentiable_within_at (differentiable_at_const _) lemma fderiv_const_apply (c : F) : fderiv 𝕜 (λy, c) x = 0 := has_fderiv_at.fderiv (has_fderiv_at_const c x) @[simp] lemma fderiv_const (c : F) : fderiv 𝕜 (λ (y : E), c) = 0 := by { ext m, rw fderiv_const_apply, refl } lemma fderiv_within_const_apply (c : F) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λy, c) s x = 0 := begin rw differentiable_at.fderiv_within (differentiable_at_const _) hxs, exact fderiv_const_apply _ end @[simp] lemma differentiable_const (c : F) : differentiable 𝕜 (λx : E, c) := λx, differentiable_at_const _ lemma differentiable_on_const (c : F) : differentiable_on 𝕜 (λx, c) s := (differentiable_const _).differentiable_on end const section continuous_linear_map /-! ### Continuous linear maps There are currently two variants of these in mathlib, the bundled version (named `continuous_linear_map`, and denoted `E →L[𝕜] F`), and the unbundled version (with a predicate `is_bounded_linear_map`). We give statements for both versions. -/ protected theorem continuous_linear_map.has_strict_fderiv_at {x : E} : has_strict_fderiv_at e e x := (is_o_zero _ _).congr_left $ λ x, by simp only [e.map_sub, sub_self] protected lemma continuous_linear_map.has_fderiv_at_filter : has_fderiv_at_filter e e x L := (is_o_zero _ _).congr_left $ λ x, by simp only [e.map_sub, sub_self] protected lemma continuous_linear_map.has_fderiv_within_at : has_fderiv_within_at e e s x := e.has_fderiv_at_filter protected lemma continuous_linear_map.has_fderiv_at : has_fderiv_at e e x := e.has_fderiv_at_filter @[simp] protected lemma continuous_linear_map.differentiable_at : differentiable_at 𝕜 e x := e.has_fderiv_at.differentiable_at protected lemma continuous_linear_map.differentiable_within_at : differentiable_within_at 𝕜 e s x := e.differentiable_at.differentiable_within_at @[simp] protected lemma continuous_linear_map.fderiv : fderiv 𝕜 e x = e := e.has_fderiv_at.fderiv protected lemma continuous_linear_map.fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 e s x = e := begin rw differentiable_at.fderiv_within e.differentiable_at hxs, exact e.fderiv end @[simp] protected lemma continuous_linear_map.differentiable : differentiable 𝕜 e := λx, e.differentiable_at protected lemma continuous_linear_map.differentiable_on : differentiable_on 𝕜 e s := e.differentiable.differentiable_on lemma is_bounded_linear_map.has_fderiv_at_filter (h : is_bounded_linear_map 𝕜 f) : has_fderiv_at_filter f h.to_continuous_linear_map x L := h.to_continuous_linear_map.has_fderiv_at_filter lemma is_bounded_linear_map.has_fderiv_within_at (h : is_bounded_linear_map 𝕜 f) : has_fderiv_within_at f h.to_continuous_linear_map s x := h.has_fderiv_at_filter lemma is_bounded_linear_map.has_fderiv_at (h : is_bounded_linear_map 𝕜 f) : has_fderiv_at f h.to_continuous_linear_map x := h.has_fderiv_at_filter lemma is_bounded_linear_map.differentiable_at (h : is_bounded_linear_map 𝕜 f) : differentiable_at 𝕜 f x := h.has_fderiv_at.differentiable_at lemma is_bounded_linear_map.differentiable_within_at (h : is_bounded_linear_map 𝕜 f) : differentiable_within_at 𝕜 f s x := h.differentiable_at.differentiable_within_at lemma is_bounded_linear_map.fderiv (h : is_bounded_linear_map 𝕜 f) : fderiv 𝕜 f x = h.to_continuous_linear_map := has_fderiv_at.fderiv (h.has_fderiv_at) lemma is_bounded_linear_map.fderiv_within (h : is_bounded_linear_map 𝕜 f) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = h.to_continuous_linear_map := begin rw differentiable_at.fderiv_within h.differentiable_at hxs, exact h.fderiv end lemma is_bounded_linear_map.differentiable (h : is_bounded_linear_map 𝕜 f) : differentiable 𝕜 f := λx, h.differentiable_at lemma is_bounded_linear_map.differentiable_on (h : is_bounded_linear_map 𝕜 f) : differentiable_on 𝕜 f s := h.differentiable.differentiable_on end continuous_linear_map section analytic variables {p : formal_multilinear_series 𝕜 E F} {r : ℝ≥0∞} lemma has_fpower_series_at.has_strict_fderiv_at (h : has_fpower_series_at f p x) : has_strict_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p 1)) x := begin refine h.is_O_image_sub_norm_mul_norm_sub.trans_is_o (is_o.of_norm_right _), refine is_o_iff_exists_eq_mul.2 ⟨λ y, ∥y - (x, x)∥, _, eventually_eq.rfl⟩, refine (continuous_id.sub continuous_const).norm.tendsto' _ _ _, rw [_root_.id, sub_self, norm_zero] end lemma has_fpower_series_at.has_fderiv_at (h : has_fpower_series_at f p x) : has_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p 1)) x := h.has_strict_fderiv_at.has_fderiv_at lemma has_fpower_series_at.differentiable_at (h : has_fpower_series_at f p x) : differentiable_at 𝕜 f x := h.has_fderiv_at.differentiable_at lemma analytic_at.differentiable_at : analytic_at 𝕜 f x → differentiable_at 𝕜 f x | ⟨p, hp⟩ := hp.differentiable_at lemma analytic_at.differentiable_within_at (h : analytic_at 𝕜 f x) : differentiable_within_at 𝕜 f s x := h.differentiable_at.differentiable_within_at lemma has_fpower_series_at.fderiv (h : has_fpower_series_at f p x) : fderiv 𝕜 f x = continuous_multilinear_curry_fin1 𝕜 E F (p 1) := h.has_fderiv_at.fderiv lemma has_fpower_series_on_ball.differentiable_on [complete_space F] (h : has_fpower_series_on_ball f p x r) : differentiable_on 𝕜 f (emetric.ball x r) := λ y hy, (h.analytic_at_of_mem hy).differentiable_within_at end analytic section composition /-! ### Derivative of the composition of two functions For composition lemmas, we put x explicit to help the elaborator, as otherwise Lean tends to get confused since there are too many possibilities for composition -/ variable (x) theorem has_fderiv_at_filter.comp {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at_filter g g' (f x) (L.map f)) (hf : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (g ∘ f) (g'.comp f') x L := let eq₁ := (g'.is_O_comp _ _).trans_is_o hf in let eq₂ := (hg.comp_tendsto tendsto_map).trans_is_O hf.is_O_sub in by { refine eq₂.triangle (eq₁.congr_left (λ x', _)), simp } /- A readable version of the previous theorem, a general form of the chain rule. -/ example {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at_filter g g' (f x) (L.map f)) (hf : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (g ∘ f) (g'.comp f') x L := begin unfold has_fderiv_at_filter at hg, have : is_o (λ x', g (f x') - g (f x) - g' (f x' - f x)) (λ x', f x' - f x) L, from hg.comp_tendsto (le_refl _), have eq₁ : is_o (λ x', g (f x') - g (f x) - g' (f x' - f x)) (λ x', x' - x) L, from this.trans_is_O hf.is_O_sub, have eq₂ : is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L, from hf, have : is_O (λ x', g' (f x' - f x - f' (x' - x))) (λ x', f x' - f x - f' (x' - x)) L, from g'.is_O_comp _ _, have : is_o (λ x', g' (f x' - f x - f' (x' - x))) (λ x', x' - x) L, from this.trans_is_o eq₂, have eq₃ : is_o (λ x', g' (f x' - f x) - (g' (f' (x' - x)))) (λ x', x' - x) L, by { refine this.congr_left _, simp}, exact eq₁.triangle eq₃ end theorem has_fderiv_within_at.comp {g : F → G} {g' : F →L[𝕜] G} {t : set F} (hg : has_fderiv_within_at g g' t (f x)) (hf : has_fderiv_within_at f f' s x) (hst : s ⊆ f ⁻¹' t) : has_fderiv_within_at (g ∘ f) (g'.comp f') s x := begin apply has_fderiv_at_filter.comp _ (has_fderiv_at_filter.mono hg _) hf, calc map f (𝓝[s] x) ≤ 𝓝[f '' s] (f x) : hf.continuous_within_at.tendsto_nhds_within_image ... ≤ 𝓝[t] (f x) : nhds_within_mono _ (image_subset_iff.mpr hst) end /-- The chain rule. -/ theorem has_fderiv_at.comp {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_at f f' x) : has_fderiv_at (g ∘ f) (g'.comp f') x := (hg.mono hf.continuous_at).comp x hf theorem has_fderiv_at.comp_has_fderiv_within_at {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (g ∘ f) (g'.comp f') s x := begin rw ← has_fderiv_within_at_univ at hg, exact has_fderiv_within_at.comp x hg hf subset_preimage_univ end lemma differentiable_within_at.comp {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) (h : s ⊆ f ⁻¹' t) : differentiable_within_at 𝕜 (g ∘ f) s x := begin rcases hf with ⟨f', hf'⟩, rcases hg with ⟨g', hg'⟩, exact ⟨continuous_linear_map.comp g' f', hg'.comp x hf' h⟩ end lemma differentiable_within_at.comp' {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (g ∘ f) (s ∩ f⁻¹' t) x := hg.comp x (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _) lemma differentiable_at.comp {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (g ∘ f) x := (hg.has_fderiv_at.comp x hf.has_fderiv_at).differentiable_at lemma differentiable_at.comp_differentiable_within_at {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (g ∘ f) s x := (differentiable_within_at_univ.2 hg).comp x hf (by simp) lemma fderiv_within.comp {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) (h : maps_to f s t) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (g ∘ f) s x = (fderiv_within 𝕜 g t (f x)).comp (fderiv_within 𝕜 f s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_within_at.comp x (hg.has_fderiv_within_at) (hf.has_fderiv_within_at) h end lemma fderiv.comp {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_at 𝕜 f x) : fderiv 𝕜 (g ∘ f) x = (fderiv 𝕜 g (f x)).comp (fderiv 𝕜 f x) := begin apply has_fderiv_at.fderiv, exact has_fderiv_at.comp x hg.has_fderiv_at hf.has_fderiv_at end lemma fderiv.comp_fderiv_within {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_within_at 𝕜 f s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (g ∘ f) s x = (fderiv 𝕜 g (f x)).comp (fderiv_within 𝕜 f s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_at.comp_has_fderiv_within_at x (hg.has_fderiv_at) (hf.has_fderiv_within_at) end lemma differentiable_on.comp {g : F → G} {t : set F} (hg : differentiable_on 𝕜 g t) (hf : differentiable_on 𝕜 f s) (st : s ⊆ f ⁻¹' t) : differentiable_on 𝕜 (g ∘ f) s := λx hx, differentiable_within_at.comp x (hg (f x) (st hx)) (hf x hx) st lemma differentiable.comp {g : F → G} (hg : differentiable 𝕜 g) (hf : differentiable 𝕜 f) : differentiable 𝕜 (g ∘ f) := λx, differentiable_at.comp x (hg (f x)) (hf x) lemma differentiable.comp_differentiable_on {g : F → G} (hg : differentiable 𝕜 g) (hf : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (g ∘ f) s := (differentiable_on_univ.2 hg).comp hf (by simp) /-- The chain rule for derivatives in the sense of strict differentiability. -/ protected lemma has_strict_fderiv_at.comp {g : F → G} {g' : F →L[𝕜] G} (hg : has_strict_fderiv_at g g' (f x)) (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, g (f x)) (g'.comp f') x := ((hg.comp_tendsto (hf.continuous_at.prod_map' hf.continuous_at)).trans_is_O hf.is_O_sub).triangle $ by simpa only [g'.map_sub, f'.coe_comp'] using (g'.is_O_comp _ _).trans_is_o hf protected lemma differentiable.iterate {f : E → E} (hf : differentiable 𝕜 f) (n : ℕ) : differentiable 𝕜 (f^[n]) := nat.rec_on n differentiable_id (λ n ihn, ihn.comp hf) protected lemma differentiable_on.iterate {f : E → E} (hf : differentiable_on 𝕜 f s) (hs : maps_to f s s) (n : ℕ) : differentiable_on 𝕜 (f^[n]) s := nat.rec_on n differentiable_on_id (λ n ihn, ihn.comp hf hs) variable {x} protected lemma has_fderiv_at_filter.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_fderiv_at_filter f f' x L) (hL : tendsto f L L) (hx : f x = x) (n : ℕ) : has_fderiv_at_filter (f^[n]) (f'^n) x L := begin induction n with n ihn, { exact has_fderiv_at_filter_id x L }, { change has_fderiv_at_filter (f^[n] ∘ f) (f'^(n+1)) x L, rw [pow_succ'], refine has_fderiv_at_filter.comp x _ hf, rw hx, exact ihn.mono hL } end protected lemma has_fderiv_at.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_fderiv_at f f' x) (hx : f x = x) (n : ℕ) : has_fderiv_at (f^[n]) (f'^n) x := begin refine hf.iterate _ hx n, convert hf.continuous_at, exact hx.symm end protected lemma has_fderiv_within_at.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_fderiv_within_at f f' s x) (hx : f x = x) (hs : maps_to f s s) (n : ℕ) : has_fderiv_within_at (f^[n]) (f'^n) s x := begin refine hf.iterate _ hx n, convert tendsto_inf.2 ⟨hf.continuous_within_at, _⟩, exacts [hx.symm, (tendsto_principal_principal.2 hs).mono_left inf_le_right] end protected lemma has_strict_fderiv_at.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_strict_fderiv_at f f' x) (hx : f x = x) (n : ℕ) : has_strict_fderiv_at (f^[n]) (f'^n) x := begin induction n with n ihn, { exact has_strict_fderiv_at_id x }, { change has_strict_fderiv_at (f^[n] ∘ f) (f'^(n+1)) x, rw [pow_succ'], refine has_strict_fderiv_at.comp x _ hf, rwa hx } end protected lemma differentiable_at.iterate {f : E → E} (hf : differentiable_at 𝕜 f x) (hx : f x = x) (n : ℕ) : differentiable_at 𝕜 (f^[n]) x := exists.elim hf $ λ f' hf, (hf.iterate hx n).differentiable_at protected lemma differentiable_within_at.iterate {f : E → E} (hf : differentiable_within_at 𝕜 f s x) (hx : f x = x) (hs : maps_to f s s) (n : ℕ) : differentiable_within_at 𝕜 (f^[n]) s x := exists.elim hf $ λ f' hf, (hf.iterate hx hs n).differentiable_within_at end composition section cartesian_product /-! ### Derivative of the cartesian product of two functions -/ section prod variables {f₂ : E → G} {f₂' : E →L[𝕜] G} protected lemma has_strict_fderiv_at.prod (hf₁ : has_strict_fderiv_at f₁ f₁' x) (hf₂ : has_strict_fderiv_at f₂ f₂' x) : has_strict_fderiv_at (λx, (f₁ x, f₂ x)) (f₁'.prod f₂') x := hf₁.prod_left hf₂ lemma has_fderiv_at_filter.prod (hf₁ : has_fderiv_at_filter f₁ f₁' x L) (hf₂ : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λx, (f₁ x, f₂ x)) (f₁'.prod f₂') x L := hf₁.prod_left hf₂ lemma has_fderiv_within_at.prod (hf₁ : has_fderiv_within_at f₁ f₁' s x) (hf₂ : has_fderiv_within_at f₂ f₂' s x) : has_fderiv_within_at (λx, (f₁ x, f₂ x)) (f₁'.prod f₂') s x := hf₁.prod hf₂ lemma has_fderiv_at.prod (hf₁ : has_fderiv_at f₁ f₁' x) (hf₂ : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') x := hf₁.prod hf₂ lemma differentiable_within_at.prod (hf₁ : differentiable_within_at 𝕜 f₁ s x) (hf₂ : differentiable_within_at 𝕜 f₂ s x) : differentiable_within_at 𝕜 (λx:E, (f₁ x, f₂ x)) s x := (hf₁.has_fderiv_within_at.prod hf₂.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.prod (hf₁ : differentiable_at 𝕜 f₁ x) (hf₂ : differentiable_at 𝕜 f₂ x) : differentiable_at 𝕜 (λx:E, (f₁ x, f₂ x)) x := (hf₁.has_fderiv_at.prod hf₂.has_fderiv_at).differentiable_at lemma differentiable_on.prod (hf₁ : differentiable_on 𝕜 f₁ s) (hf₂ : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λx:E, (f₁ x, f₂ x)) s := λx hx, differentiable_within_at.prod (hf₁ x hx) (hf₂ x hx) @[simp] lemma differentiable.prod (hf₁ : differentiable 𝕜 f₁) (hf₂ : differentiable 𝕜 f₂) : differentiable 𝕜 (λx:E, (f₁ x, f₂ x)) := λ x, differentiable_at.prod (hf₁ x) (hf₂ x) lemma differentiable_at.fderiv_prod (hf₁ : differentiable_at 𝕜 f₁ x) (hf₂ : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λx:E, (f₁ x, f₂ x)) x = (fderiv 𝕜 f₁ x).prod (fderiv 𝕜 f₂ x) := (hf₁.has_fderiv_at.prod hf₂.has_fderiv_at).fderiv lemma differentiable_at.fderiv_within_prod (hf₁ : differentiable_within_at 𝕜 f₁ s x) (hf₂ : differentiable_within_at 𝕜 f₂ s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx:E, (f₁ x, f₂ x)) s x = (fderiv_within 𝕜 f₁ s x).prod (fderiv_within 𝕜 f₂ s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_within_at.prod hf₁.has_fderiv_within_at hf₂.has_fderiv_within_at end end prod section fst variables {f₂ : E → F × G} {f₂' : E →L[𝕜] F × G} {p : E × F} lemma has_strict_fderiv_at_fst : has_strict_fderiv_at (fst 𝕜 E F) (fst 𝕜 E F) p := (fst 𝕜 E F).has_strict_fderiv_at protected lemma has_strict_fderiv_at.fst (h : has_strict_fderiv_at f₂ f₂' x) : has_strict_fderiv_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x := has_strict_fderiv_at_fst.comp x h lemma has_fderiv_at_filter_fst {L : filter (E × F)} : has_fderiv_at_filter (fst 𝕜 E F) (fst 𝕜 E F) p L := (fst 𝕜 E F).has_fderiv_at_filter protected lemma has_fderiv_at_filter.fst (h : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x L := has_fderiv_at_filter_fst.comp x h lemma has_fderiv_at_fst : has_fderiv_at (fst 𝕜 E F) (fst 𝕜 E F) p := has_fderiv_at_filter_fst protected lemma has_fderiv_at.fst (h : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x := h.fst lemma has_fderiv_within_at_fst {s : set (E × F)} : has_fderiv_within_at (fst 𝕜 E F) (fst 𝕜 E F) s p := has_fderiv_at_filter_fst protected lemma has_fderiv_within_at.fst (h : has_fderiv_within_at f₂ f₂' s x) : has_fderiv_within_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') s x := h.fst lemma differentiable_at_fst : differentiable_at 𝕜 prod.fst p := has_fderiv_at_fst.differentiable_at @[simp] protected lemma differentiable_at.fst (h : differentiable_at 𝕜 f₂ x) : differentiable_at 𝕜 (λ x, (f₂ x).1) x := differentiable_at_fst.comp x h lemma differentiable_fst : differentiable 𝕜 (prod.fst : E × F → E) := λ x, differentiable_at_fst @[simp] protected lemma differentiable.fst (h : differentiable 𝕜 f₂) : differentiable 𝕜 (λ x, (f₂ x).1) := differentiable_fst.comp h lemma differentiable_within_at_fst {s : set (E × F)} : differentiable_within_at 𝕜 prod.fst s p := differentiable_at_fst.differentiable_within_at protected lemma differentiable_within_at.fst (h : differentiable_within_at 𝕜 f₂ s x) : differentiable_within_at 𝕜 (λ x, (f₂ x).1) s x := differentiable_at_fst.comp_differentiable_within_at x h lemma differentiable_on_fst {s : set (E × F)} : differentiable_on 𝕜 prod.fst s := differentiable_fst.differentiable_on protected lemma differentiable_on.fst (h : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λ x, (f₂ x).1) s := differentiable_fst.comp_differentiable_on h lemma fderiv_fst : fderiv 𝕜 prod.fst p = fst 𝕜 E F := has_fderiv_at_fst.fderiv lemma fderiv.fst (h : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λ x, (f₂ x).1) x = (fst 𝕜 F G).comp (fderiv 𝕜 f₂ x) := h.has_fderiv_at.fst.fderiv lemma fderiv_within_fst {s : set (E × F)} (hs : unique_diff_within_at 𝕜 s p) : fderiv_within 𝕜 prod.fst s p = fst 𝕜 E F := has_fderiv_within_at_fst.fderiv_within hs lemma fderiv_within.fst (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f₂ s x) : fderiv_within 𝕜 (λ x, (f₂ x).1) s x = (fst 𝕜 F G).comp (fderiv_within 𝕜 f₂ s x) := h.has_fderiv_within_at.fst.fderiv_within hs end fst section snd variables {f₂ : E → F × G} {f₂' : E →L[𝕜] F × G} {p : E × F} lemma has_strict_fderiv_at_snd : has_strict_fderiv_at (snd 𝕜 E F) (snd 𝕜 E F) p := (snd 𝕜 E F).has_strict_fderiv_at protected lemma has_strict_fderiv_at.snd (h : has_strict_fderiv_at f₂ f₂' x) : has_strict_fderiv_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x := has_strict_fderiv_at_snd.comp x h lemma has_fderiv_at_filter_snd {L : filter (E × F)} : has_fderiv_at_filter (snd 𝕜 E F) (snd 𝕜 E F) p L := (snd 𝕜 E F).has_fderiv_at_filter protected lemma has_fderiv_at_filter.snd (h : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x L := has_fderiv_at_filter_snd.comp x h lemma has_fderiv_at_snd : has_fderiv_at (snd 𝕜 E F) (snd 𝕜 E F) p := has_fderiv_at_filter_snd protected lemma has_fderiv_at.snd (h : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x := h.snd lemma has_fderiv_within_at_snd {s : set (E × F)} : has_fderiv_within_at (snd 𝕜 E F) (snd 𝕜 E F) s p := has_fderiv_at_filter_snd protected lemma has_fderiv_within_at.snd (h : has_fderiv_within_at f₂ f₂' s x) : has_fderiv_within_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') s x := h.snd lemma differentiable_at_snd : differentiable_at 𝕜 prod.snd p := has_fderiv_at_snd.differentiable_at @[simp] protected lemma differentiable_at.snd (h : differentiable_at 𝕜 f₂ x) : differentiable_at 𝕜 (λ x, (f₂ x).2) x := differentiable_at_snd.comp x h lemma differentiable_snd : differentiable 𝕜 (prod.snd : E × F → F) := λ x, differentiable_at_snd @[simp] protected lemma differentiable.snd (h : differentiable 𝕜 f₂) : differentiable 𝕜 (λ x, (f₂ x).2) := differentiable_snd.comp h lemma differentiable_within_at_snd {s : set (E × F)} : differentiable_within_at 𝕜 prod.snd s p := differentiable_at_snd.differentiable_within_at protected lemma differentiable_within_at.snd (h : differentiable_within_at 𝕜 f₂ s x) : differentiable_within_at 𝕜 (λ x, (f₂ x).2) s x := differentiable_at_snd.comp_differentiable_within_at x h lemma differentiable_on_snd {s : set (E × F)} : differentiable_on 𝕜 prod.snd s := differentiable_snd.differentiable_on protected lemma differentiable_on.snd (h : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λ x, (f₂ x).2) s := differentiable_snd.comp_differentiable_on h lemma fderiv_snd : fderiv 𝕜 prod.snd p = snd 𝕜 E F := has_fderiv_at_snd.fderiv lemma fderiv.snd (h : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λ x, (f₂ x).2) x = (snd 𝕜 F G).comp (fderiv 𝕜 f₂ x) := h.has_fderiv_at.snd.fderiv lemma fderiv_within_snd {s : set (E × F)} (hs : unique_diff_within_at 𝕜 s p) : fderiv_within 𝕜 prod.snd s p = snd 𝕜 E F := has_fderiv_within_at_snd.fderiv_within hs lemma fderiv_within.snd (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f₂ s x) : fderiv_within 𝕜 (λ x, (f₂ x).2) s x = (snd 𝕜 F G).comp (fderiv_within 𝕜 f₂ s x) := h.has_fderiv_within_at.snd.fderiv_within hs end snd section prod_map variables {f₂ : G → G'} {f₂' : G →L[𝕜] G'} {y : G} (p : E × G) -- TODO (Lean 3.8): use `prod.map f f₂`` protected theorem has_strict_fderiv_at.prod_map (hf : has_strict_fderiv_at f f' p.1) (hf₂ : has_strict_fderiv_at f₂ f₂' p.2) : has_strict_fderiv_at (λ p : E × G, (f p.1, f₂ p.2)) (f'.prod_map f₂') p := (hf.comp p has_strict_fderiv_at_fst).prod (hf₂.comp p has_strict_fderiv_at_snd) protected theorem has_fderiv_at.prod_map (hf : has_fderiv_at f f' p.1) (hf₂ : has_fderiv_at f₂ f₂' p.2) : has_fderiv_at (λ p : E × G, (f p.1, f₂ p.2)) (f'.prod_map f₂') p := (hf.comp p has_fderiv_at_fst).prod (hf₂.comp p has_fderiv_at_snd) @[simp] protected theorem differentiable_at.prod_map (hf : differentiable_at 𝕜 f p.1) (hf₂ : differentiable_at 𝕜 f₂ p.2) : differentiable_at 𝕜 (λ p : E × G, (f p.1, f₂ p.2)) p := (hf.comp p differentiable_at_fst).prod (hf₂.comp p differentiable_at_snd) end prod_map end cartesian_product section const_smul /-! ### Derivative of a function multiplied by a constant -/ theorem has_strict_fderiv_at.const_smul (h : has_strict_fderiv_at f f' x) (c : 𝕜) : has_strict_fderiv_at (λ x, c • f x) (c • f') x := (c • (1 : F →L[𝕜] F)).has_strict_fderiv_at.comp x h theorem has_fderiv_at_filter.const_smul (h : has_fderiv_at_filter f f' x L) (c : 𝕜) : has_fderiv_at_filter (λ x, c • f x) (c • f') x L := (c • (1 : F →L[𝕜] F)).has_fderiv_at_filter.comp x h theorem has_fderiv_within_at.const_smul (h : has_fderiv_within_at f f' s x) (c : 𝕜) : has_fderiv_within_at (λ x, c • f x) (c • f') s x := h.const_smul c theorem has_fderiv_at.const_smul (h : has_fderiv_at f f' x) (c : 𝕜) : has_fderiv_at (λ x, c • f x) (c • f') x := h.const_smul c lemma differentiable_within_at.const_smul (h : differentiable_within_at 𝕜 f s x) (c : 𝕜) : differentiable_within_at 𝕜 (λy, c • f y) s x := (h.has_fderiv_within_at.const_smul c).differentiable_within_at lemma differentiable_at.const_smul (h : differentiable_at 𝕜 f x) (c : 𝕜) : differentiable_at 𝕜 (λy, c • f y) x := (h.has_fderiv_at.const_smul c).differentiable_at lemma differentiable_on.const_smul (h : differentiable_on 𝕜 f s) (c : 𝕜) : differentiable_on 𝕜 (λy, c • f y) s := λx hx, (h x hx).const_smul c lemma differentiable.const_smul (h : differentiable 𝕜 f) (c : 𝕜) : differentiable 𝕜 (λy, c • f y) := λx, (h x).const_smul c lemma fderiv_within_const_smul (hxs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f s x) (c : 𝕜) : fderiv_within 𝕜 (λy, c • f y) s x = c • fderiv_within 𝕜 f s x := (h.has_fderiv_within_at.const_smul c).fderiv_within hxs lemma fderiv_const_smul (h : differentiable_at 𝕜 f x) (c : 𝕜) : fderiv 𝕜 (λy, c • f y) x = c • fderiv 𝕜 f x := (h.has_fderiv_at.const_smul c).fderiv end const_smul section add /-! ### Derivative of the sum of two functions -/ theorem has_strict_fderiv_at.add (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) : has_strict_fderiv_at (λ y, f y + g y) (f' + g') x := (hf.add hg).congr_left $ λ y, by simp; abel theorem has_fderiv_at_filter.add (hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) : has_fderiv_at_filter (λ y, f y + g y) (f' + g') x L := (hf.add hg).congr_left $ λ _, by simp; abel theorem has_fderiv_within_at.add (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) : has_fderiv_within_at (λ y, f y + g y) (f' + g') s x := hf.add hg theorem has_fderiv_at.add (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) : has_fderiv_at (λ x, f x + g x) (f' + g') x := hf.add hg lemma differentiable_within_at.add (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : differentiable_within_at 𝕜 (λ y, f y + g y) s x := (hf.has_fderiv_within_at.add hg.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : differentiable_at 𝕜 (λ y, f y + g y) x := (hf.has_fderiv_at.add hg.has_fderiv_at).differentiable_at lemma differentiable_on.add (hf : differentiable_on 𝕜 f s) (hg : differentiable_on 𝕜 g s) : differentiable_on 𝕜 (λy, f y + g y) s := λx hx, (hf x hx).add (hg x hx) @[simp] lemma differentiable.add (hf : differentiable 𝕜 f) (hg : differentiable 𝕜 g) : differentiable 𝕜 (λy, f y + g y) := λx, (hf x).add (hg x) lemma fderiv_within_add (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : fderiv_within 𝕜 (λy, f y + g y) s x = fderiv_within 𝕜 f s x + fderiv_within 𝕜 g s x := (hf.has_fderiv_within_at.add hg.has_fderiv_within_at).fderiv_within hxs lemma fderiv_add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : fderiv 𝕜 (λy, f y + g y) x = fderiv 𝕜 f x + fderiv 𝕜 g x := (hf.has_fderiv_at.add hg.has_fderiv_at).fderiv theorem has_strict_fderiv_at.add_const (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ y, f y + c) f' x := add_zero f' ▸ hf.add (has_strict_fderiv_at_const _ _) theorem has_fderiv_at_filter.add_const (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ y, f y + c) f' x L := add_zero f' ▸ hf.add (has_fderiv_at_filter_const _ _ _) theorem has_fderiv_within_at.add_const (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ y, f y + c) f' s x := hf.add_const c theorem has_fderiv_at.add_const (hf : has_fderiv_at f f' x) (c : F): has_fderiv_at (λ x, f x + c) f' x := hf.add_const c lemma differentiable_within_at.add_const (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, f y + c) s x := (hf.has_fderiv_within_at.add_const c).differentiable_within_at @[simp] lemma differentiable_within_at_add_const_iff (c : F) : differentiable_within_at 𝕜 (λ y, f y + c) s x ↔ differentiable_within_at 𝕜 f s x := ⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩ lemma differentiable_at.add_const (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, f y + c) x := (hf.has_fderiv_at.add_const c).differentiable_at @[simp] lemma differentiable_at_add_const_iff (c : F) : differentiable_at 𝕜 (λ y, f y + c) x ↔ differentiable_at 𝕜 f x := ⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩ lemma differentiable_on.add_const (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, f y + c) s := λx hx, (hf x hx).add_const c @[simp] lemma differentiable_on_add_const_iff (c : F) : differentiable_on 𝕜 (λ y, f y + c) s ↔ differentiable_on 𝕜 f s := ⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩ lemma differentiable.add_const (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, f y + c) := λx, (hf x).add_const c @[simp] lemma differentiable_add_const_iff (c : F) : differentiable 𝕜 (λ y, f y + c) ↔ differentiable 𝕜 f := ⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩ lemma fderiv_within_add_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) : fderiv_within 𝕜 (λy, f y + c) s x = fderiv_within 𝕜 f s x := if hf : differentiable_within_at 𝕜 f s x then (hf.has_fderiv_within_at.add_const c).fderiv_within hxs else by { rw [fderiv_within_zero_of_not_differentiable_within_at hf, fderiv_within_zero_of_not_differentiable_within_at], simpa } lemma fderiv_add_const (c : F) : fderiv 𝕜 (λy, f y + c) x = fderiv 𝕜 f x := by simp only [← fderiv_within_univ, fderiv_within_add_const unique_diff_within_at_univ] theorem has_strict_fderiv_at.const_add (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ y, c + f y) f' x := zero_add f' ▸ (has_strict_fderiv_at_const _ _).add hf theorem has_fderiv_at_filter.const_add (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ y, c + f y) f' x L := zero_add f' ▸ (has_fderiv_at_filter_const _ _ _).add hf theorem has_fderiv_within_at.const_add (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ y, c + f y) f' s x := hf.const_add c theorem has_fderiv_at.const_add (hf : has_fderiv_at f f' x) (c : F): has_fderiv_at (λ x, c + f x) f' x := hf.const_add c lemma differentiable_within_at.const_add (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, c + f y) s x := (hf.has_fderiv_within_at.const_add c).differentiable_within_at @[simp] lemma differentiable_within_at_const_add_iff (c : F) : differentiable_within_at 𝕜 (λ y, c + f y) s x ↔ differentiable_within_at 𝕜 f s x := ⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩ lemma differentiable_at.const_add (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, c + f y) x := (hf.has_fderiv_at.const_add c).differentiable_at @[simp] lemma differentiable_at_const_add_iff (c : F) : differentiable_at 𝕜 (λ y, c + f y) x ↔ differentiable_at 𝕜 f x := ⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩ lemma differentiable_on.const_add (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, c + f y) s := λx hx, (hf x hx).const_add c @[simp] lemma differentiable_on_const_add_iff (c : F) : differentiable_on 𝕜 (λ y, c + f y) s ↔ differentiable_on 𝕜 f s := ⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩ lemma differentiable.const_add (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, c + f y) := λx, (hf x).const_add c @[simp] lemma differentiable_const_add_iff (c : F) : differentiable 𝕜 (λ y, c + f y) ↔ differentiable 𝕜 f := ⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩ lemma fderiv_within_const_add (hxs : unique_diff_within_at 𝕜 s x) (c : F) : fderiv_within 𝕜 (λy, c + f y) s x = fderiv_within 𝕜 f s x := by simpa only [add_comm] using fderiv_within_add_const hxs c lemma fderiv_const_add (c : F) : fderiv 𝕜 (λy, c + f y) x = fderiv 𝕜 f x := by simp only [add_comm c, fderiv_add_const] end add section sum /-! ### Derivative of a finite sum of functions -/ open_locale big_operators variables {ι : Type*} {u : finset ι} {A : ι → (E → F)} {A' : ι → (E →L[𝕜] F)} theorem has_strict_fderiv_at.sum (h : ∀ i ∈ u, has_strict_fderiv_at (A i) (A' i) x) : has_strict_fderiv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := begin dsimp [has_strict_fderiv_at] at *, convert is_o.sum h, simp [finset.sum_sub_distrib, continuous_linear_map.sum_apply] end theorem has_fderiv_at_filter.sum (h : ∀ i ∈ u, has_fderiv_at_filter (A i) (A' i) x L) : has_fderiv_at_filter (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x L := begin dsimp [has_fderiv_at_filter] at *, convert is_o.sum h, simp [continuous_linear_map.sum_apply] end theorem has_fderiv_within_at.sum (h : ∀ i ∈ u, has_fderiv_within_at (A i) (A' i) s x) : has_fderiv_within_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) s x := has_fderiv_at_filter.sum h theorem has_fderiv_at.sum (h : ∀ i ∈ u, has_fderiv_at (A i) (A' i) x) : has_fderiv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := has_fderiv_at_filter.sum h theorem differentiable_within_at.sum (h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) : differentiable_within_at 𝕜 (λ y, ∑ i in u, A i y) s x := has_fderiv_within_at.differentiable_within_at $ has_fderiv_within_at.sum $ λ i hi, (h i hi).has_fderiv_within_at @[simp] theorem differentiable_at.sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) : differentiable_at 𝕜 (λ y, ∑ i in u, A i y) x := has_fderiv_at.differentiable_at $ has_fderiv_at.sum $ λ i hi, (h i hi).has_fderiv_at theorem differentiable_on.sum (h : ∀ i ∈ u, differentiable_on 𝕜 (A i) s) : differentiable_on 𝕜 (λ y, ∑ i in u, A i y) s := λ x hx, differentiable_within_at.sum $ λ i hi, h i hi x hx @[simp] theorem differentiable.sum (h : ∀ i ∈ u, differentiable 𝕜 (A i)) : differentiable 𝕜 (λ y, ∑ i in u, A i y) := λ x, differentiable_at.sum $ λ i hi, h i hi x theorem fderiv_within_sum (hxs : unique_diff_within_at 𝕜 s x) (h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) : fderiv_within 𝕜 (λ y, ∑ i in u, A i y) s x = (∑ i in u, fderiv_within 𝕜 (A i) s x) := (has_fderiv_within_at.sum (λ i hi, (h i hi).has_fderiv_within_at)).fderiv_within hxs theorem fderiv_sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) : fderiv 𝕜 (λ y, ∑ i in u, A i y) x = (∑ i in u, fderiv 𝕜 (A i) x) := (has_fderiv_at.sum (λ i hi, (h i hi).has_fderiv_at)).fderiv end sum section pi /-! ### Derivatives of functions `f : E → Π i, F' i` In this section we formulate `has_*fderiv*_pi` theorems as `iff`s, and provide two versions of each theorem: * the version without `'` deals with `φ : Π i, E → F' i` and `φ' : Π i, E →L[𝕜] F' i` and is designed to deduce differentiability of `λ x i, φ i x` from differentiability of each `φ i`; * the version with `'` deals with `Φ : E → Π i, F' i` and `Φ' : E →L[𝕜] Π i, F' i` and is designed to deduce differentiability of the components `λ x, Φ x i` from differentiability of `Φ`. -/ variables {ι : Type*} [fintype ι] {F' : ι → Type*} [Π i, normed_group (F' i)] [Π i, normed_space 𝕜 (F' i)] {φ : Π i, E → F' i} {φ' : Π i, E →L[𝕜] F' i} {Φ : E → Π i, F' i} {Φ' : E →L[𝕜] Π i, F' i} @[simp] lemma has_strict_fderiv_at_pi' : has_strict_fderiv_at Φ Φ' x ↔ ∀ i, has_strict_fderiv_at (λ x, Φ x i) ((proj i).comp Φ') x := begin simp only [has_strict_fderiv_at, continuous_linear_map.coe_pi], exact is_o_pi end @[simp] lemma has_strict_fderiv_at_pi : has_strict_fderiv_at (λ x i, φ i x) (continuous_linear_map.pi φ') x ↔ ∀ i, has_strict_fderiv_at (φ i) (φ' i) x := has_strict_fderiv_at_pi' @[simp] lemma has_fderiv_at_filter_pi' : has_fderiv_at_filter Φ Φ' x L ↔ ∀ i, has_fderiv_at_filter (λ x, Φ x i) ((proj i).comp Φ') x L := begin simp only [has_fderiv_at_filter, continuous_linear_map.coe_pi], exact is_o_pi end lemma has_fderiv_at_filter_pi : has_fderiv_at_filter (λ x i, φ i x) (continuous_linear_map.pi φ') x L ↔ ∀ i, has_fderiv_at_filter (φ i) (φ' i) x L := has_fderiv_at_filter_pi' @[simp] lemma has_fderiv_at_pi' : has_fderiv_at Φ Φ' x ↔ ∀ i, has_fderiv_at (λ x, Φ x i) ((proj i).comp Φ') x := has_fderiv_at_filter_pi' lemma has_fderiv_at_pi : has_fderiv_at (λ x i, φ i x) (continuous_linear_map.pi φ') x ↔ ∀ i, has_fderiv_at (φ i) (φ' i) x := has_fderiv_at_filter_pi @[simp] lemma has_fderiv_within_at_pi' : has_fderiv_within_at Φ Φ' s x ↔ ∀ i, has_fderiv_within_at (λ x, Φ x i) ((proj i).comp Φ') s x := has_fderiv_at_filter_pi' lemma has_fderiv_within_at_pi : has_fderiv_within_at (λ x i, φ i x) (continuous_linear_map.pi φ') s x ↔ ∀ i, has_fderiv_within_at (φ i) (φ' i) s x := has_fderiv_at_filter_pi @[simp] lemma differentiable_within_at_pi : differentiable_within_at 𝕜 Φ s x ↔ ∀ i, differentiable_within_at 𝕜 (λ x, Φ x i) s x := ⟨λ h i, (has_fderiv_within_at_pi'.1 h.has_fderiv_within_at i).differentiable_within_at, λ h, (has_fderiv_within_at_pi.2 (λ i, (h i).has_fderiv_within_at)).differentiable_within_at⟩ @[simp] lemma differentiable_at_pi : differentiable_at 𝕜 Φ x ↔ ∀ i, differentiable_at 𝕜 (λ x, Φ x i) x := ⟨λ h i, (has_fderiv_at_pi'.1 h.has_fderiv_at i).differentiable_at, λ h, (has_fderiv_at_pi.2 (λ i, (h i).has_fderiv_at)).differentiable_at⟩ lemma differentiable_on_pi : differentiable_on 𝕜 Φ s ↔ ∀ i, differentiable_on 𝕜 (λ x, Φ x i) s := ⟨λ h i x hx, differentiable_within_at_pi.1 (h x hx) i, λ h x hx, differentiable_within_at_pi.2 (λ i, h i x hx)⟩ lemma differentiable_pi : differentiable 𝕜 Φ ↔ ∀ i, differentiable 𝕜 (λ x, Φ x i) := ⟨λ h i x, differentiable_at_pi.1 (h x) i, λ h x, differentiable_at_pi.2 (λ i, h i x)⟩ -- TODO: find out which version (`φ` or `Φ`) works better with `rw`/`simp` lemma fderiv_within_pi (h : ∀ i, differentiable_within_at 𝕜 (φ i) s x) (hs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λ x i, φ i x) s x = pi (λ i, fderiv_within 𝕜 (φ i) s x) := (has_fderiv_within_at_pi.2 (λ i, (h i).has_fderiv_within_at)).fderiv_within hs lemma fderiv_pi (h : ∀ i, differentiable_at 𝕜 (φ i) x) : fderiv 𝕜 (λ x i, φ i x) x = pi (λ i, fderiv 𝕜 (φ i) x) := (has_fderiv_at_pi.2 (λ i, (h i).has_fderiv_at)).fderiv end pi section neg /-! ### Derivative of the negative of a function -/ theorem has_strict_fderiv_at.neg (h : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, -f x) (-f') x := (-1 : F →L[𝕜] F).has_strict_fderiv_at.comp x h theorem has_fderiv_at_filter.neg (h : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (λ x, -f x) (-f') x L := (-1 : F →L[𝕜] F).has_fderiv_at_filter.comp x h theorem has_fderiv_within_at.neg (h : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, -f x) (-f') s x := h.neg theorem has_fderiv_at.neg (h : has_fderiv_at f f' x) : has_fderiv_at (λ x, -f x) (-f') x := h.neg lemma differentiable_within_at.neg (h : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (λy, -f y) s x := h.has_fderiv_within_at.neg.differentiable_within_at @[simp] lemma differentiable_within_at_neg_iff : differentiable_within_at 𝕜 (λy, -f y) s x ↔ differentiable_within_at 𝕜 f s x := ⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩ lemma differentiable_at.neg (h : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (λy, -f y) x := h.has_fderiv_at.neg.differentiable_at @[simp] lemma differentiable_at_neg_iff : differentiable_at 𝕜 (λy, -f y) x ↔ differentiable_at 𝕜 f x := ⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩ lemma differentiable_on.neg (h : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (λy, -f y) s := λx hx, (h x hx).neg @[simp] lemma differentiable_on_neg_iff : differentiable_on 𝕜 (λy, -f y) s ↔ differentiable_on 𝕜 f s := ⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩ lemma differentiable.neg (h : differentiable 𝕜 f) : differentiable 𝕜 (λy, -f y) := λx, (h x).neg @[simp] lemma differentiable_neg_iff : differentiable 𝕜 (λy, -f y) ↔ differentiable 𝕜 f := ⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩ lemma fderiv_within_neg (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λy, -f y) s x = - fderiv_within 𝕜 f s x := if h : differentiable_within_at 𝕜 f s x then h.has_fderiv_within_at.neg.fderiv_within hxs else by { rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at, neg_zero], simpa } @[simp] lemma fderiv_neg : fderiv 𝕜 (λy, -f y) x = - fderiv 𝕜 f x := by simp only [← fderiv_within_univ, fderiv_within_neg unique_diff_within_at_univ] end neg section sub /-! ### Derivative of the difference of two functions -/ theorem has_strict_fderiv_at.sub (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) : has_strict_fderiv_at (λ x, f x - g x) (f' - g') x := by simpa only [sub_eq_add_neg] using hf.add hg.neg theorem has_fderiv_at_filter.sub (hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) : has_fderiv_at_filter (λ x, f x - g x) (f' - g') x L := by simpa only [sub_eq_add_neg] using hf.add hg.neg theorem has_fderiv_within_at.sub (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) : has_fderiv_within_at (λ x, f x - g x) (f' - g') s x := hf.sub hg theorem has_fderiv_at.sub (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) : has_fderiv_at (λ x, f x - g x) (f' - g') x := hf.sub hg lemma differentiable_within_at.sub (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : differentiable_within_at 𝕜 (λ y, f y - g y) s x := (hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : differentiable_at 𝕜 (λ y, f y - g y) x := (hf.has_fderiv_at.sub hg.has_fderiv_at).differentiable_at lemma differentiable_on.sub (hf : differentiable_on 𝕜 f s) (hg : differentiable_on 𝕜 g s) : differentiable_on 𝕜 (λy, f y - g y) s := λx hx, (hf x hx).sub (hg x hx) @[simp] lemma differentiable.sub (hf : differentiable 𝕜 f) (hg : differentiable 𝕜 g) : differentiable 𝕜 (λy, f y - g y) := λx, (hf x).sub (hg x) lemma fderiv_within_sub (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : fderiv_within 𝕜 (λy, f y - g y) s x = fderiv_within 𝕜 f s x - fderiv_within 𝕜 g s x := (hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).fderiv_within hxs lemma fderiv_sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : fderiv 𝕜 (λy, f y - g y) x = fderiv 𝕜 f x - fderiv 𝕜 g x := (hf.has_fderiv_at.sub hg.has_fderiv_at).fderiv theorem has_strict_fderiv_at.sub_const (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ x, f x - c) f' x := by simpa only [sub_eq_add_neg] using hf.add_const (-c) theorem has_fderiv_at_filter.sub_const (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ x, f x - c) f' x L := by simpa only [sub_eq_add_neg] using hf.add_const (-c) theorem has_fderiv_within_at.sub_const (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ x, f x - c) f' s x := hf.sub_const c theorem has_fderiv_at.sub_const (hf : has_fderiv_at f f' x) (c : F) : has_fderiv_at (λ x, f x - c) f' x := hf.sub_const c lemma differentiable_within_at.sub_const (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, f y - c) s x := (hf.has_fderiv_within_at.sub_const c).differentiable_within_at @[simp] lemma differentiable_within_at_sub_const_iff (c : F) : differentiable_within_at 𝕜 (λ y, f y - c) s x ↔ differentiable_within_at 𝕜 f s x := by simp only [sub_eq_add_neg, differentiable_within_at_add_const_iff] lemma differentiable_at.sub_const (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, f y - c) x := (hf.has_fderiv_at.sub_const c).differentiable_at @[simp] lemma differentiable_at_sub_const_iff (c : F) : differentiable_at 𝕜 (λ y, f y - c) x ↔ differentiable_at 𝕜 f x := by simp only [sub_eq_add_neg, differentiable_at_add_const_iff] lemma differentiable_on.sub_const (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, f y - c) s := λx hx, (hf x hx).sub_const c @[simp] lemma differentiable_on_sub_const_iff (c : F) : differentiable_on 𝕜 (λ y, f y - c) s ↔ differentiable_on 𝕜 f s := by simp only [sub_eq_add_neg, differentiable_on_add_const_iff] lemma differentiable.sub_const (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, f y - c) := λx, (hf x).sub_const c @[simp] lemma differentiable_sub_const_iff (c : F) : differentiable 𝕜 (λ y, f y - c) ↔ differentiable 𝕜 f := by simp only [sub_eq_add_neg, differentiable_add_const_iff] lemma fderiv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) : fderiv_within 𝕜 (λy, f y - c) s x = fderiv_within 𝕜 f s x := by simp only [sub_eq_add_neg, fderiv_within_add_const hxs] lemma fderiv_sub_const (c : F) : fderiv 𝕜 (λy, f y - c) x = fderiv 𝕜 f x := by simp only [sub_eq_add_neg, fderiv_add_const] theorem has_strict_fderiv_at.const_sub (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ x, c - f x) (-f') x := by simpa only [sub_eq_add_neg] using hf.neg.const_add c theorem has_fderiv_at_filter.const_sub (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ x, c - f x) (-f') x L := by simpa only [sub_eq_add_neg] using hf.neg.const_add c theorem has_fderiv_within_at.const_sub (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ x, c - f x) (-f') s x := hf.const_sub c theorem has_fderiv_at.const_sub (hf : has_fderiv_at f f' x) (c : F) : has_fderiv_at (λ x, c - f x) (-f') x := hf.const_sub c lemma differentiable_within_at.const_sub (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, c - f y) s x := (hf.has_fderiv_within_at.const_sub c).differentiable_within_at @[simp] lemma differentiable_within_at_const_sub_iff (c : F) : differentiable_within_at 𝕜 (λ y, c - f y) s x ↔ differentiable_within_at 𝕜 f s x := by simp [sub_eq_add_neg] lemma differentiable_at.const_sub (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, c - f y) x := (hf.has_fderiv_at.const_sub c).differentiable_at @[simp] lemma differentiable_at_const_sub_iff (c : F) : differentiable_at 𝕜 (λ y, c - f y) x ↔ differentiable_at 𝕜 f x := by simp [sub_eq_add_neg] lemma differentiable_on.const_sub (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, c - f y) s := λx hx, (hf x hx).const_sub c @[simp] lemma differentiable_on_const_sub_iff (c : F) : differentiable_on 𝕜 (λ y, c - f y) s ↔ differentiable_on 𝕜 f s := by simp [sub_eq_add_neg] lemma differentiable.const_sub (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, c - f y) := λx, (hf x).const_sub c @[simp] lemma differentiable_const_sub_iff (c : F) : differentiable 𝕜 (λ y, c - f y) ↔ differentiable 𝕜 f := by simp [sub_eq_add_neg] lemma fderiv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x) (c : F) : fderiv_within 𝕜 (λy, c - f y) s x = -fderiv_within 𝕜 f s x := by simp only [sub_eq_add_neg, fderiv_within_const_add, fderiv_within_neg, hxs] lemma fderiv_const_sub (c : F) : fderiv 𝕜 (λy, c - f y) x = -fderiv 𝕜 f x := by simp only [← fderiv_within_univ, fderiv_within_const_sub unique_diff_within_at_univ] end sub section bilinear_map /-! ### Derivative of a bounded bilinear map -/ variables {b : E × F → G} {u : set (E × F) } open normed_field lemma is_bounded_bilinear_map.has_strict_fderiv_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_strict_fderiv_at b (h.deriv p) p := begin rw has_strict_fderiv_at, set T := (E × F) × (E × F), have : is_o (λ q : T, b (q.1 - q.2)) (λ q : T, ∥q.1 - q.2∥ * 1) (𝓝 (p, p)), { refine (h.is_O'.comp_tendsto le_top).trans_is_o _, simp only [(∘)], refine (is_O_refl (λ q : T, ∥q.1 - q.2∥) _).mul_is_o (is_o.norm_left $ (is_o_one_iff _).2 _), rw [← sub_self p], exact continuous_at_fst.sub continuous_at_snd }, simp only [mul_one, is_o_norm_right] at this, refine (is_o.congr_of_sub _).1 this, clear this, convert_to is_o (λ q : T, h.deriv (p - q.2) (q.1 - q.2)) (λ q : T, q.1 - q.2) (𝓝 (p, p)), { ext ⟨⟨x₁, y₁⟩, ⟨x₂, y₂⟩⟩, rcases p with ⟨x, y⟩, simp only [is_bounded_bilinear_map_deriv_coe, prod.mk_sub_mk, h.map_sub_left, h.map_sub_right], abel }, have : is_o (λ q : T, p - q.2) (λ q, (1:ℝ)) (𝓝 (p, p)), from (is_o_one_iff _).2 (sub_self p ▸ tendsto_const_nhds.sub continuous_at_snd), apply is_bounded_bilinear_map_apply.is_O_comp.trans_is_o, refine is_o.trans_is_O _ (is_O_const_mul_self 1 _ _).of_norm_right, refine is_o.mul_is_O _ (is_O_refl _ _), exact (((h.is_bounded_linear_map_deriv.is_O_id ⊤).comp_tendsto le_top : _).trans_is_o this).norm_left end lemma is_bounded_bilinear_map.has_fderiv_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_fderiv_at b (h.deriv p) p := (h.has_strict_fderiv_at p).has_fderiv_at lemma is_bounded_bilinear_map.has_fderiv_within_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_fderiv_within_at b (h.deriv p) u p := (h.has_fderiv_at p).has_fderiv_within_at lemma is_bounded_bilinear_map.differentiable_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : differentiable_at 𝕜 b p := (h.has_fderiv_at p).differentiable_at lemma is_bounded_bilinear_map.differentiable_within_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : differentiable_within_at 𝕜 b u p := (h.differentiable_at p).differentiable_within_at lemma is_bounded_bilinear_map.fderiv (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : fderiv 𝕜 b p = h.deriv p := has_fderiv_at.fderiv (h.has_fderiv_at p) lemma is_bounded_bilinear_map.fderiv_within (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) (hxs : unique_diff_within_at 𝕜 u p) : fderiv_within 𝕜 b u p = h.deriv p := begin rw differentiable_at.fderiv_within (h.differentiable_at p) hxs, exact h.fderiv p end lemma is_bounded_bilinear_map.differentiable (h : is_bounded_bilinear_map 𝕜 b) : differentiable 𝕜 b := λx, h.differentiable_at x lemma is_bounded_bilinear_map.differentiable_on (h : is_bounded_bilinear_map 𝕜 b) : differentiable_on 𝕜 b u := h.differentiable.differentiable_on lemma is_bounded_bilinear_map.continuous (h : is_bounded_bilinear_map 𝕜 b) : continuous b := h.differentiable.continuous lemma is_bounded_bilinear_map.continuous_left (h : is_bounded_bilinear_map 𝕜 b) {f : F} : continuous (λe, b (e, f)) := h.continuous.comp (continuous_id.prod_mk continuous_const) lemma is_bounded_bilinear_map.continuous_right (h : is_bounded_bilinear_map 𝕜 b) {e : E} : continuous (λf, b (e, f)) := h.continuous.comp (continuous_const.prod_mk continuous_id) end bilinear_map namespace continuous_linear_equiv /-! ### The set of continuous linear equivalences between two Banach spaces is open In this section we establish that the set of continuous linear equivalences between two Banach spaces is an open subset of the space of linear maps between them. These facts are placed here because the proof uses `is_bounded_bilinear_map.continuous_left`, proved just above as a consequence of its differentiability. -/ protected lemma is_open [complete_space E] : is_open (range (coe : (E ≃L[𝕜] F) → (E →L[𝕜] F))) := begin nontriviality E, rw [is_open_iff_mem_nhds, forall_range_iff], refine λ e, is_open.mem_nhds _ (mem_range_self _), let O : (E →L[𝕜] F) → (E →L[𝕜] E) := λ f, (e.symm : F →L[𝕜] E).comp f, have h_O : continuous O := is_bounded_bilinear_map_comp.continuous_left, convert units.is_open.preimage h_O using 1, ext f', split, { rintros ⟨e', rfl⟩, exact ⟨(e'.trans e.symm).to_unit, rfl⟩ }, { rintros ⟨w, hw⟩, use (units_equiv 𝕜 E w).trans e, ext x, simp [hw] } end protected lemma nhds [complete_space E] (e : E ≃L[𝕜] F) : (range (coe : (E ≃L[𝕜] F) → (E →L[𝕜] F))) ∈ 𝓝 (e : E →L[𝕜] F) := is_open.mem_nhds continuous_linear_equiv.is_open (by simp) end continuous_linear_equiv section smul /-! ### Derivative of the product of a scalar-valued function and a vector-valued function If `c` is a differentiable scalar-valued function and `f` is a differentiable vector-valued function, then `λ x, c x • f x` is differentiable as well. Lemmas in this section works for function `c` taking values in the base field, as well as in a normed algebra over the base field: e.g., they work for `c : E → ℂ` and `f : E → F` provided that `F` is a complex normed vector space. -/ variables {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] [normed_space 𝕜' F] [is_scalar_tower 𝕜 𝕜' F] variables {c : E → 𝕜'} {c' : E →L[𝕜] 𝕜'} theorem has_strict_fderiv_at.smul (hc : has_strict_fderiv_at c c' x) (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) x := (is_bounded_bilinear_map_smul.has_strict_fderiv_at (c x, f x)).comp x $ hc.prod hf theorem has_fderiv_within_at.smul (hc : has_fderiv_within_at c c' s x) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) s x := (is_bounded_bilinear_map_smul.has_fderiv_at (c x, f x)).comp_has_fderiv_within_at x $ hc.prod hf theorem has_fderiv_at.smul (hc : has_fderiv_at c c' x) (hf : has_fderiv_at f f' x) : has_fderiv_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) x := (is_bounded_bilinear_map_smul.has_fderiv_at (c x, f x)).comp x $ hc.prod hf lemma differentiable_within_at.smul (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (λ y, c y • f y) s x := (hc.has_fderiv_within_at.smul hf.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (λ y, c y • f y) x := (hc.has_fderiv_at.smul hf.has_fderiv_at).differentiable_at lemma differentiable_on.smul (hc : differentiable_on 𝕜 c s) (hf : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (λ y, c y • f y) s := λx hx, (hc x hx).smul (hf x hx) @[simp] lemma differentiable.smul (hc : differentiable 𝕜 c) (hf : differentiable 𝕜 f) : differentiable 𝕜 (λ y, c y • f y) := λx, (hc x).smul (hf x) lemma fderiv_within_smul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 (λ y, c y • f y) s x = c x • fderiv_within 𝕜 f s x + (fderiv_within 𝕜 c s x).smul_right (f x) := (hc.has_fderiv_within_at.smul hf.has_fderiv_within_at).fderiv_within hxs lemma fderiv_smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : fderiv 𝕜 (λ y, c y • f y) x = c x • fderiv 𝕜 f x + (fderiv 𝕜 c x).smul_right (f x) := (hc.has_fderiv_at.smul hf.has_fderiv_at).fderiv theorem has_strict_fderiv_at.smul_const (hc : has_strict_fderiv_at c c' x) (f : F) : has_strict_fderiv_at (λ y, c y • f) (c'.smul_right f) x := by simpa only [smul_zero, zero_add] using hc.smul (has_strict_fderiv_at_const f x) theorem has_fderiv_within_at.smul_const (hc : has_fderiv_within_at c c' s x) (f : F) : has_fderiv_within_at (λ y, c y • f) (c'.smul_right f) s x := by simpa only [smul_zero, zero_add] using hc.smul (has_fderiv_within_at_const f x s) theorem has_fderiv_at.smul_const (hc : has_fderiv_at c c' x) (f : F) : has_fderiv_at (λ y, c y • f) (c'.smul_right f) x := by simpa only [smul_zero, zero_add] using hc.smul (has_fderiv_at_const f x) lemma differentiable_within_at.smul_const (hc : differentiable_within_at 𝕜 c s x) (f : F) : differentiable_within_at 𝕜 (λ y, c y • f) s x := (hc.has_fderiv_within_at.smul_const f).differentiable_within_at lemma differentiable_at.smul_const (hc : differentiable_at 𝕜 c x) (f : F) : differentiable_at 𝕜 (λ y, c y • f) x := (hc.has_fderiv_at.smul_const f).differentiable_at lemma differentiable_on.smul_const (hc : differentiable_on 𝕜 c s) (f : F) : differentiable_on 𝕜 (λ y, c y • f) s := λx hx, (hc x hx).smul_const f lemma differentiable.smul_const (hc : differentiable 𝕜 c) (f : F) : differentiable 𝕜 (λ y, c y • f) := λx, (hc x).smul_const f lemma fderiv_within_smul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (f : F) : fderiv_within 𝕜 (λ y, c y • f) s x = (fderiv_within 𝕜 c s x).smul_right f := (hc.has_fderiv_within_at.smul_const f).fderiv_within hxs lemma fderiv_smul_const (hc : differentiable_at 𝕜 c x) (f : F) : fderiv 𝕜 (λ y, c y • f) x = (fderiv 𝕜 c x).smul_right f := (hc.has_fderiv_at.smul_const f).fderiv end smul section mul /-! ### Derivative of the product of two scalar-valued functions -/ variables {c d : E → 𝕜} {c' d' : E →L[𝕜] 𝕜} theorem has_strict_fderiv_at.mul (hc : has_strict_fderiv_at c c' x) (hd : has_strict_fderiv_at d d' x) : has_strict_fderiv_at (λ y, c y * d y) (c x • d' + d x • c') x := by { convert hc.smul hd, ext z, apply mul_comm } theorem has_fderiv_within_at.mul (hc : has_fderiv_within_at c c' s x) (hd : has_fderiv_within_at d d' s x) : has_fderiv_within_at (λ y, c y * d y) (c x • d' + d x • c') s x := by { convert hc.smul hd, ext z, apply mul_comm } theorem has_fderiv_at.mul (hc : has_fderiv_at c c' x) (hd : has_fderiv_at d d' x) : has_fderiv_at (λ y, c y * d y) (c x • d' + d x • c') x := by { convert hc.smul hd, ext z, apply mul_comm } lemma differentiable_within_at.mul (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : differentiable_within_at 𝕜 (λ y, c y * d y) s x := (hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : differentiable_at 𝕜 (λ y, c y * d y) x := (hc.has_fderiv_at.mul hd.has_fderiv_at).differentiable_at lemma differentiable_on.mul (hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) : differentiable_on 𝕜 (λ y, c y * d y) s := λx hx, (hc x hx).mul (hd x hx) @[simp] lemma differentiable.mul (hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) : differentiable 𝕜 (λ y, c y * d y) := λx, (hc x).mul (hd x) lemma fderiv_within_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : fderiv_within 𝕜 (λ y, c y * d y) s x = c x • fderiv_within 𝕜 d s x + d x • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).fderiv_within hxs lemma fderiv_mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : fderiv 𝕜 (λ y, c y * d y) x = c x • fderiv 𝕜 d x + d x • fderiv 𝕜 c x := (hc.has_fderiv_at.mul hd.has_fderiv_at).fderiv theorem has_strict_fderiv_at.mul_const (hc : has_strict_fderiv_at c c' x) (d : 𝕜) : has_strict_fderiv_at (λ y, c y * d) (d • c') x := by simpa only [smul_zero, zero_add] using hc.mul (has_strict_fderiv_at_const d x) theorem has_fderiv_within_at.mul_const (hc : has_fderiv_within_at c c' s x) (d : 𝕜) : has_fderiv_within_at (λ y, c y * d) (d • c') s x := by simpa only [smul_zero, zero_add] using hc.mul (has_fderiv_within_at_const d x s) theorem has_fderiv_at.mul_const (hc : has_fderiv_at c c' x) (d : 𝕜) : has_fderiv_at (λ y, c y * d) (d • c') x := begin rw [← has_fderiv_within_at_univ] at *, exact hc.mul_const d end lemma differentiable_within_at.mul_const (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : differentiable_within_at 𝕜 (λ y, c y * d) s x := (hc.has_fderiv_within_at.mul_const d).differentiable_within_at lemma differentiable_at.mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : differentiable_at 𝕜 (λ y, c y * d) x := (hc.has_fderiv_at.mul_const d).differentiable_at lemma differentiable_on.mul_const (hc : differentiable_on 𝕜 c s) (d : 𝕜) : differentiable_on 𝕜 (λ y, c y * d) s := λx hx, (hc x hx).mul_const d lemma differentiable.mul_const (hc : differentiable 𝕜 c) (d : 𝕜) : differentiable 𝕜 (λ y, c y * d) := λx, (hc x).mul_const d lemma fderiv_within_mul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : fderiv_within 𝕜 (λ y, c y * d) s x = d • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.mul_const d).fderiv_within hxs lemma fderiv_mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : fderiv 𝕜 (λ y, c y * d) x = d • fderiv 𝕜 c x := (hc.has_fderiv_at.mul_const d).fderiv theorem has_strict_fderiv_at.const_mul (hc : has_strict_fderiv_at c c' x) (d : 𝕜) : has_strict_fderiv_at (λ y, d * c y) (d • c') x := begin simp only [mul_comm d], exact hc.mul_const d, end theorem has_fderiv_within_at.const_mul (hc : has_fderiv_within_at c c' s x) (d : 𝕜) : has_fderiv_within_at (λ y, d * c y) (d • c') s x := begin simp only [mul_comm d], exact hc.mul_const d, end theorem has_fderiv_at.const_mul (hc : has_fderiv_at c c' x) (d : 𝕜) : has_fderiv_at (λ y, d * c y) (d • c') x := begin simp only [mul_comm d], exact hc.mul_const d, end lemma differentiable_within_at.const_mul (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : differentiable_within_at 𝕜 (λ y, d * c y) s x := (hc.has_fderiv_within_at.const_mul d).differentiable_within_at lemma differentiable_at.const_mul (hc : differentiable_at 𝕜 c x) (d : 𝕜) : differentiable_at 𝕜 (λ y, d * c y) x := (hc.has_fderiv_at.const_mul d).differentiable_at lemma differentiable_on.const_mul (hc : differentiable_on 𝕜 c s) (d : 𝕜) : differentiable_on 𝕜 (λ y, d * c y) s := λx hx, (hc x hx).const_mul d lemma differentiable.const_mul (hc : differentiable 𝕜 c) (d : 𝕜) : differentiable 𝕜 (λ y, d * c y) := λx, (hc x).const_mul d lemma fderiv_within_const_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : fderiv_within 𝕜 (λ y, d * c y) s x = d • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.const_mul d).fderiv_within hxs lemma fderiv_const_mul (hc : differentiable_at 𝕜 c x) (d : 𝕜) : fderiv 𝕜 (λ y, d * c y) x = d • fderiv 𝕜 c x := (hc.has_fderiv_at.const_mul d).fderiv end mul section algebra_inverse variables {R : Type*} [normed_ring R] [normed_algebra 𝕜 R] [complete_space R] open normed_ring continuous_linear_map ring /-- At an invertible element `x` of a normed algebra `R`, the Fréchet derivative of the inversion operation is the linear map `λ t, - x⁻¹ * t * x⁻¹`. -/ lemma has_fderiv_at_ring_inverse (x : units R) : has_fderiv_at ring.inverse (-lmul_left_right 𝕜 R ↑x⁻¹ ↑x⁻¹) x := begin have h_is_o : is_o (λ (t : R), inverse (↑x + t) - ↑x⁻¹ + ↑x⁻¹ * t * ↑x⁻¹) (λ (t : R), t) (𝓝 0), { refine (inverse_add_norm_diff_second_order x).trans_is_o ((is_o_norm_norm).mp _), simp only [normed_field.norm_pow, norm_norm], have h12 : 1 < 2 := by norm_num, convert (asymptotics.is_o_pow_pow h12).comp_tendsto tendsto_norm_zero, ext, simp }, have h_lim : tendsto (λ (y:R), y - x) (𝓝 x) (𝓝 0), { refine tendsto_zero_iff_norm_tendsto_zero.mpr _, exact tendsto_iff_norm_tendsto_zero.mp tendsto_id }, simp only [has_fderiv_at, has_fderiv_at_filter], convert h_is_o.comp_tendsto h_lim, ext y, simp only [coe_comp', function.comp_app, lmul_left_right_apply, neg_apply, inverse_unit x, units.inv_mul, add_sub_cancel'_right, mul_sub, sub_mul, one_mul, sub_neg_eq_add] end lemma differentiable_at_inverse (x : units R) : differentiable_at 𝕜 (@ring.inverse R _) x := (has_fderiv_at_ring_inverse x).differentiable_at lemma fderiv_inverse (x : units R) : fderiv 𝕜 (@ring.inverse R _) x = - lmul_left_right 𝕜 R ↑x⁻¹ ↑x⁻¹ := (has_fderiv_at_ring_inverse x).fderiv end algebra_inverse namespace continuous_linear_equiv /-! ### Differentiability of linear equivs, and invariance of differentiability -/ variable (iso : E ≃L[𝕜] F) protected lemma has_strict_fderiv_at : has_strict_fderiv_at iso (iso : E →L[𝕜] F) x := iso.to_continuous_linear_map.has_strict_fderiv_at protected lemma has_fderiv_within_at : has_fderiv_within_at iso (iso : E →L[𝕜] F) s x := iso.to_continuous_linear_map.has_fderiv_within_at protected lemma has_fderiv_at : has_fderiv_at iso (iso : E →L[𝕜] F) x := iso.to_continuous_linear_map.has_fderiv_at_filter protected lemma differentiable_at : differentiable_at 𝕜 iso x := iso.has_fderiv_at.differentiable_at protected lemma differentiable_within_at : differentiable_within_at 𝕜 iso s x := iso.differentiable_at.differentiable_within_at protected lemma fderiv : fderiv 𝕜 iso x = iso := iso.has_fderiv_at.fderiv protected lemma fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 iso s x = iso := iso.to_continuous_linear_map.fderiv_within hxs protected lemma differentiable : differentiable 𝕜 iso := λx, iso.differentiable_at protected lemma differentiable_on : differentiable_on 𝕜 iso s := iso.differentiable.differentiable_on lemma comp_differentiable_within_at_iff {f : G → E} {s : set G} {x : G} : differentiable_within_at 𝕜 (iso ∘ f) s x ↔ differentiable_within_at 𝕜 f s x := begin refine ⟨λ H, _, λ H, iso.differentiable.differentiable_at.comp_differentiable_within_at x H⟩, have : differentiable_within_at 𝕜 (iso.symm ∘ (iso ∘ f)) s x := iso.symm.differentiable.differentiable_at.comp_differentiable_within_at x H, rwa [← function.comp.assoc iso.symm iso f, iso.symm_comp_self] at this, end lemma comp_differentiable_at_iff {f : G → E} {x : G} : differentiable_at 𝕜 (iso ∘ f) x ↔ differentiable_at 𝕜 f x := by rw [← differentiable_within_at_univ, ← differentiable_within_at_univ, iso.comp_differentiable_within_at_iff] lemma comp_differentiable_on_iff {f : G → E} {s : set G} : differentiable_on 𝕜 (iso ∘ f) s ↔ differentiable_on 𝕜 f s := begin rw [differentiable_on, differentiable_on], simp only [iso.comp_differentiable_within_at_iff], end lemma comp_differentiable_iff {f : G → E} : differentiable 𝕜 (iso ∘ f) ↔ differentiable 𝕜 f := begin rw [← differentiable_on_univ, ← differentiable_on_univ], exact iso.comp_differentiable_on_iff end lemma comp_has_fderiv_within_at_iff {f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] E} : has_fderiv_within_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') s x ↔ has_fderiv_within_at f f' s x := begin refine ⟨λ H, _, λ H, iso.has_fderiv_at.comp_has_fderiv_within_at x H⟩, have A : f = iso.symm ∘ (iso ∘ f), by { rw [← function.comp.assoc, iso.symm_comp_self], refl }, have B : f' = (iso.symm : F →L[𝕜] E).comp ((iso : E →L[𝕜] F).comp f'), by rw [← continuous_linear_map.comp_assoc, iso.coe_symm_comp_coe, continuous_linear_map.id_comp], rw [A, B], exact iso.symm.has_fderiv_at.comp_has_fderiv_within_at x H end lemma comp_has_strict_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} : has_strict_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_strict_fderiv_at f f' x := begin refine ⟨λ H, _, λ H, iso.has_strict_fderiv_at.comp x H⟩, convert iso.symm.has_strict_fderiv_at.comp x H; ext z; apply (iso.symm_apply_apply _).symm end lemma comp_has_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} : has_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_fderiv_at f f' x := by rw [← has_fderiv_within_at_univ, ← has_fderiv_within_at_univ, iso.comp_has_fderiv_within_at_iff] lemma comp_has_fderiv_within_at_iff' {f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] F} : has_fderiv_within_at (iso ∘ f) f' s x ↔ has_fderiv_within_at f ((iso.symm : F →L[𝕜] E).comp f') s x := by rw [← iso.comp_has_fderiv_within_at_iff, ← continuous_linear_map.comp_assoc, iso.coe_comp_coe_symm, continuous_linear_map.id_comp] lemma comp_has_fderiv_at_iff' {f : G → E} {x : G} {f' : G →L[𝕜] F} : has_fderiv_at (iso ∘ f) f' x ↔ has_fderiv_at f ((iso.symm : F →L[𝕜] E).comp f') x := by rw [← has_fderiv_within_at_univ, ← has_fderiv_within_at_univ, iso.comp_has_fderiv_within_at_iff'] lemma comp_fderiv_within {f : G → E} {s : set G} {x : G} (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (iso ∘ f) s x = (iso : E →L[𝕜] F).comp (fderiv_within 𝕜 f s x) := begin by_cases h : differentiable_within_at 𝕜 f s x, { rw [fderiv.comp_fderiv_within x iso.differentiable_at h hxs, iso.fderiv] }, { have : ¬differentiable_within_at 𝕜 (iso ∘ f) s x, from mt iso.comp_differentiable_within_at_iff.1 h, rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at this, continuous_linear_map.comp_zero] } end lemma comp_fderiv {f : G → E} {x : G} : fderiv 𝕜 (iso ∘ f) x = (iso : E →L[𝕜] F).comp (fderiv 𝕜 f x) := begin rw [← fderiv_within_univ, ← fderiv_within_univ], exact iso.comp_fderiv_within unique_diff_within_at_univ, end end continuous_linear_equiv namespace linear_isometry_equiv /-! ### Differentiability of linear isometry equivs, and invariance of differentiability -/ variable (iso : E ≃ₗᵢ[𝕜] F) protected lemma has_strict_fderiv_at : has_strict_fderiv_at iso (iso : E →L[𝕜] F) x := (iso : E ≃L[𝕜] F).has_strict_fderiv_at protected lemma has_fderiv_within_at : has_fderiv_within_at iso (iso : E →L[𝕜] F) s x := (iso : E ≃L[𝕜] F).has_fderiv_within_at protected lemma has_fderiv_at : has_fderiv_at iso (iso : E →L[𝕜] F) x := (iso : E ≃L[𝕜] F).has_fderiv_at protected lemma differentiable_at : differentiable_at 𝕜 iso x := iso.has_fderiv_at.differentiable_at protected lemma differentiable_within_at : differentiable_within_at 𝕜 iso s x := iso.differentiable_at.differentiable_within_at protected lemma fderiv : fderiv 𝕜 iso x = iso := iso.has_fderiv_at.fderiv protected lemma fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 iso s x = iso := (iso : E ≃L[𝕜] F).fderiv_within hxs protected lemma differentiable : differentiable 𝕜 iso := λx, iso.differentiable_at protected lemma differentiable_on : differentiable_on 𝕜 iso s := iso.differentiable.differentiable_on lemma comp_differentiable_within_at_iff {f : G → E} {s : set G} {x : G} : differentiable_within_at 𝕜 (iso ∘ f) s x ↔ differentiable_within_at 𝕜 f s x := (iso : E ≃L[𝕜] F).comp_differentiable_within_at_iff lemma comp_differentiable_at_iff {f : G → E} {x : G} : differentiable_at 𝕜 (iso ∘ f) x ↔ differentiable_at 𝕜 f x := (iso : E ≃L[𝕜] F).comp_differentiable_at_iff lemma comp_differentiable_on_iff {f : G → E} {s : set G} : differentiable_on 𝕜 (iso ∘ f) s ↔ differentiable_on 𝕜 f s := (iso : E ≃L[𝕜] F).comp_differentiable_on_iff lemma comp_differentiable_iff {f : G → E} : differentiable 𝕜 (iso ∘ f) ↔ differentiable 𝕜 f := (iso : E ≃L[𝕜] F).comp_differentiable_iff lemma comp_has_fderiv_within_at_iff {f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] E} : has_fderiv_within_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') s x ↔ has_fderiv_within_at f f' s x := (iso : E ≃L[𝕜] F).comp_has_fderiv_within_at_iff lemma comp_has_strict_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} : has_strict_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_strict_fderiv_at f f' x := (iso : E ≃L[𝕜] F).comp_has_strict_fderiv_at_iff lemma comp_has_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} : has_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_fderiv_at f f' x := (iso : E ≃L[𝕜] F).comp_has_fderiv_at_iff lemma comp_has_fderiv_within_at_iff' {f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] F} : has_fderiv_within_at (iso ∘ f) f' s x ↔ has_fderiv_within_at f ((iso.symm : F →L[𝕜] E).comp f') s x := (iso : E ≃L[𝕜] F).comp_has_fderiv_within_at_iff' lemma comp_has_fderiv_at_iff' {f : G → E} {x : G} {f' : G →L[𝕜] F} : has_fderiv_at (iso ∘ f) f' x ↔ has_fderiv_at f ((iso.symm : F →L[𝕜] E).comp f') x := (iso : E ≃L[𝕜] F).comp_has_fderiv_at_iff' lemma comp_fderiv_within {f : G → E} {s : set G} {x : G} (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (iso ∘ f) s x = (iso : E →L[𝕜] F).comp (fderiv_within 𝕜 f s x) := (iso : E ≃L[𝕜] F).comp_fderiv_within hxs lemma comp_fderiv {f : G → E} {x : G} : fderiv 𝕜 (iso ∘ f) x = (iso : E →L[𝕜] F).comp (fderiv 𝕜 f x) := (iso : E ≃L[𝕜] F).comp_fderiv end linear_isometry_equiv /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a` in the strict sense, then `g` has the derivative `f'⁻¹` at `a` in the strict sense. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_strict_fderiv_at.of_local_left_inverse {f : E → F} {f' : E ≃L[𝕜] F} {g : F → E} {a : F} (hg : continuous_at g a) (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) (g a)) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_strict_fderiv_at g (f'.symm : F →L[𝕜] E) a := begin replace hg := hg.prod_map' hg, replace hfg := hfg.prod_mk_nhds hfg, have : is_O (λ p : F × F, g p.1 - g p.2 - f'.symm (p.1 - p.2)) (λ p : F × F, f' (g p.1 - g p.2) - (p.1 - p.2)) (𝓝 (a, a)), { refine ((f'.symm : F →L[𝕜] E).is_O_comp _ _).congr (λ x, _) (λ _, rfl), simp }, refine this.trans_is_o _, clear this, refine ((hf.comp_tendsto hg).symm.congr' (hfg.mono _) (eventually_of_forall $ λ _, rfl)).trans_is_O _, { rintros p ⟨hp1, hp2⟩, simp [hp1, hp2] }, { refine (hf.is_O_sub_rev.comp_tendsto hg).congr' (eventually_of_forall $ λ _, rfl) (hfg.mono _), rintros p ⟨hp1, hp2⟩, simp only [(∘), hp1, hp2] } end /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a`, then `g` has the derivative `f'⁻¹` at `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_fderiv_at.of_local_left_inverse {f : E → F} {f' : E ≃L[𝕜] F} {g : F → E} {a : F} (hg : continuous_at g a) (hf : has_fderiv_at f (f' : E →L[𝕜] F) (g a)) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_fderiv_at g (f'.symm : F →L[𝕜] E) a := begin have : is_O (λ x : F, g x - g a - f'.symm (x - a)) (λ x : F, f' (g x - g a) - (x - a)) (𝓝 a), { refine ((f'.symm : F →L[𝕜] E).is_O_comp _ _).congr (λ x, _) (λ _, rfl), simp }, refine this.trans_is_o _, clear this, refine ((hf.comp_tendsto hg).symm.congr' (hfg.mono _) (eventually_of_forall $ λ _, rfl)).trans_is_O _, { rintros p hp, simp [hp, hfg.self_of_nhds] }, { refine (hf.is_O_sub_rev.comp_tendsto hg).congr' (eventually_of_forall $ λ _, rfl) (hfg.mono _), rintros p hp, simp only [(∘), hp, hfg.self_of_nhds] } end /-- If `f` is a local homeomorphism defined on a neighbourhood of `f.symm a`, and `f` has an invertible derivative `f'` in the sense of strict differentiability at `f.symm a`, then `f.symm` has the derivative `f'⁻¹` at `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ lemma local_homeomorph.has_strict_fderiv_at_symm (f : local_homeomorph E F) {f' : E ≃L[𝕜] F} {a : F} (ha : a ∈ f.target) (htff' : has_strict_fderiv_at f (f' : E →L[𝕜] F) (f.symm a)) : has_strict_fderiv_at f.symm (f'.symm : F →L[𝕜] E) a := htff'.of_local_left_inverse (f.symm.continuous_at ha) (f.eventually_right_inverse ha) /-- If `f` is a local homeomorphism defined on a neighbourhood of `f.symm a`, and `f` has an invertible derivative `f'` at `f.symm a`, then `f.symm` has the derivative `f'⁻¹` at `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ lemma local_homeomorph.has_fderiv_at_symm (f : local_homeomorph E F) {f' : E ≃L[𝕜] F} {a : F} (ha : a ∈ f.target) (htff' : has_fderiv_at f (f' : E →L[𝕜] F) (f.symm a)) : has_fderiv_at f.symm (f'.symm : F →L[𝕜] E) a := htff'.of_local_left_inverse (f.symm.continuous_at ha) (f.eventually_right_inverse ha) lemma has_fderiv_within_at.eventually_ne (h : has_fderiv_within_at f f' s x) (hf' : ∃ C, ∀ z, ∥z∥ ≤ C * ∥f' z∥) : ∀ᶠ z in 𝓝[s \ {x}] x, f z ≠ f x := begin rw [nhds_within, diff_eq, ← inf_principal, ← inf_assoc, eventually_inf_principal], have A : is_O (λ z, z - x) (λ z, f' (z - x)) (𝓝[s] x) := (is_O_iff.2 $ hf'.imp $ λ C hC, eventually_of_forall $ λ z, hC _), have : (λ z, f z - f x) ~[𝓝[s] x] (λ z, f' (z - x)) := h.trans_is_O A, simpa [not_imp_not, sub_eq_zero] using (A.trans this.is_O_symm).eq_zero_imp end lemma has_fderiv_at.eventually_ne (h : has_fderiv_at f f' x) (hf' : ∃ C, ∀ z, ∥z∥ ≤ C * ∥f' z∥) : ∀ᶠ z in 𝓝[{x}ᶜ] x, f z ≠ f x := by simpa only [compl_eq_univ_diff] using (has_fderiv_within_at_univ.2 h).eventually_ne hf' end section /- In the special case of a normed space over the reals, we can use scalar multiplication in the `tendsto` characterization of the Fréchet derivative. -/ variables {E : Type*} [normed_group E] [normed_space ℝ E] variables {F : Type*} [normed_group F] [normed_space ℝ F] variables {f : E → F} {f' : E →L[ℝ] F} {x : E} theorem has_fderiv_at_filter_real_equiv {L : filter E} : tendsto (λ x' : E, ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (𝓝 0) ↔ tendsto (λ x' : E, ∥x' - x∥⁻¹ • (f x' - f x - f' (x' - x))) L (𝓝 0) := begin symmetry, rw [tendsto_iff_norm_tendsto_zero], refine tendsto_congr (λ x', _), have : ∥x' - x∥⁻¹ ≥ 0, from inv_nonneg.mpr (norm_nonneg _), simp [norm_smul, real.norm_eq_abs, abs_of_nonneg this] end lemma has_fderiv_at.lim_real (hf : has_fderiv_at f f' x) (v : E) : tendsto (λ (c:ℝ), c • (f (x + c⁻¹ • v) - f x)) at_top (𝓝 (f' v)) := begin apply hf.lim v, rw tendsto_at_top_at_top, exact λ b, ⟨b, λ a ha, le_trans ha (le_abs_self _)⟩ end end section tangent_cone variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {f : E → F} {s : set E} {f' : E →L[𝕜] F} /-- The image of a tangent cone under the differential of a map is included in the tangent cone to the image. -/ lemma has_fderiv_within_at.maps_to_tangent_cone {x : E} (h : has_fderiv_within_at f f' s x) : maps_to f' (tangent_cone_at 𝕜 s x) (tangent_cone_at 𝕜 (f '' s) (f x)) := begin rintros v ⟨c, d, dtop, clim, cdlim⟩, refine ⟨c, (λn, f (x + d n) - f x), mem_sets_of_superset dtop _, clim, h.lim at_top dtop clim cdlim⟩, simp [-mem_image, mem_image_of_mem] {contextual := tt} end /-- If a set has the unique differentiability property at a point x, then the image of this set under a map with onto derivative has also the unique differentiability property at the image point. -/ lemma has_fderiv_within_at.unique_diff_within_at {x : E} (h : has_fderiv_within_at f f' s x) (hs : unique_diff_within_at 𝕜 s x) (h' : dense_range f') : unique_diff_within_at 𝕜 (f '' s) (f x) := begin refine ⟨h'.dense_of_maps_to f'.continuous hs.1 _, h.continuous_within_at.mem_closure_image hs.2⟩, show submodule.span 𝕜 (tangent_cone_at 𝕜 s x) ≤ (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))).comap f', rw [submodule.span_le], exact h.maps_to_tangent_cone.mono (subset.refl _) submodule.subset_span end lemma unique_diff_on.image {f' : E → E →L[𝕜] F} (hs : unique_diff_on 𝕜 s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hd : ∀ x ∈ s, dense_range (f' x)) : unique_diff_on 𝕜 (f '' s) := ball_image_iff.2 $ λ x hx, (hf' x hx).unique_diff_within_at (hs x hx) (hd x hx) lemma has_fderiv_within_at.unique_diff_within_at_of_continuous_linear_equiv {x : E} (e' : E ≃L[𝕜] F) (h : has_fderiv_within_at f (e' : E →L[𝕜] F) s x) (hs : unique_diff_within_at 𝕜 s x) : unique_diff_within_at 𝕜 (f '' s) (f x) := h.unique_diff_within_at hs e'.surjective.dense_range lemma continuous_linear_equiv.unique_diff_on_image (e : E ≃L[𝕜] F) (h : unique_diff_on 𝕜 s) : unique_diff_on 𝕜 (e '' s) := h.image (λ x _, e.has_fderiv_within_at) (λ x hx, e.surjective.dense_range) @[simp] lemma continuous_linear_equiv.unique_diff_on_image_iff (e : E ≃L[𝕜] F) : unique_diff_on 𝕜 (e '' s) ↔ unique_diff_on 𝕜 s := ⟨λ h, e.symm_image_image s ▸ e.symm.unique_diff_on_image h, e.unique_diff_on_image⟩ @[simp] lemma continuous_linear_equiv.unique_diff_on_preimage_iff (e : F ≃L[𝕜] E) : unique_diff_on 𝕜 (e ⁻¹' s) ↔ unique_diff_on 𝕜 s := by rw [← e.image_symm_eq_preimage, e.symm.unique_diff_on_image_iff] end tangent_cone section restrict_scalars /-! ### Restricting from `ℂ` to `ℝ`, or generally from `𝕜'` to `𝕜` If a function is differentiable over `ℂ`, then it is 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 𝕜] variables {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] [normed_space 𝕜' E] variables [is_scalar_tower 𝕜 𝕜' E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] [normed_space 𝕜' F] variables [is_scalar_tower 𝕜 𝕜' F] variables {f : E → F} {f' : E →L[𝕜'] F} {s : set E} {x : E} lemma has_strict_fderiv_at.restrict_scalars (h : has_strict_fderiv_at f f' x) : has_strict_fderiv_at f (f'.restrict_scalars 𝕜) x := h lemma has_fderiv_at.restrict_scalars (h : has_fderiv_at f f' x) : has_fderiv_at f (f'.restrict_scalars 𝕜) x := h lemma has_fderiv_within_at.restrict_scalars (h : has_fderiv_within_at f f' s x) : has_fderiv_within_at f (f'.restrict_scalars 𝕜) s x := h lemma differentiable_at.restrict_scalars (h : differentiable_at 𝕜' f x) : differentiable_at 𝕜 f x := (h.has_fderiv_at.restrict_scalars 𝕜).differentiable_at lemma differentiable_within_at.restrict_scalars (h : differentiable_within_at 𝕜' f s x) : differentiable_within_at 𝕜 f s x := (h.has_fderiv_within_at.restrict_scalars 𝕜).differentiable_within_at lemma differentiable_on.restrict_scalars (h : differentiable_on 𝕜' f s) : differentiable_on 𝕜 f s := λx hx, (h x hx).restrict_scalars 𝕜 lemma differentiable.restrict_scalars (h : differentiable 𝕜' f) : differentiable 𝕜 f := λx, (h x).restrict_scalars 𝕜 end restrict_scalars
4918a15841112fb882579cf95821d304e7077f13
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Compiler/LCNF/Testing.lean
c866486ee6d61659d5239328542e0f4933639af1
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
9,830
lean
/- Copyright (c) 2022 Henrik Böving. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Henrik Böving -/ import Lean.Compiler.LCNF.PassManager import Lean.Compiler.LCNF.PrettyPrinter namespace Lean.Compiler.LCNF partial def Code.containsConst (constName : Name) (code : Code) : Bool := match code with | .let decl k => goLetValue decl.value || containsConst constName k | .fun decl k => containsConst constName decl.value || containsConst constName k | .jp decl k => containsConst constName decl.value || containsConst constName k | .cases cs => cs.alts.any fun alt => containsConst constName alt.getCode | .return .. | .unreach .. | .jmp .. => false where goExpr (e : Expr) : Bool := match e with | .const name .. => name == constName | .app fn arg .. => goExpr fn || goExpr arg | .lam _ _ body .. => goExpr body | .proj _ _ struct .. => goExpr struct | .letE .. => unreachable! -- not possible in LCNF | _ => false goLetValue (l : LetValue) : Bool := match l with | .value .. | .erased | .proj .. | .fvar .. => false | .const name .. => name == constName namespace Testing structure TestInstallerContext where passUnderTestName : Name testName : Name structure TestContext where passUnderTest : Pass testName : Name structure SimpleAssertionContext where decls : Array Decl structure InOutAssertionContext where input : Array Decl output : Array Decl abbrev TestInstallerM := ReaderM TestInstallerContext abbrev TestInstaller := TestInstallerM PassInstaller abbrev TestM := ReaderT TestContext CompilerM abbrev SimpleAssertionM := ReaderT SimpleAssertionContext TestM abbrev InOutAssertionM := ReaderT InOutAssertionContext TestM abbrev SimpleTest := SimpleAssertionM Unit abbrev InOutTest := InOutAssertionM Unit def TestInstaller.install (x : TestInstaller) (passUnderTestName testName : Name) : PassInstaller := x { passUnderTestName, testName } def TestM.run (x : TestM α) (passUnderTest : Pass) (testName : Name) : CompilerM α := x { passUnderTest, testName } def SimpleAssertionM.run (x : SimpleAssertionM α) (decls : Array Decl) (passUnderTest : Pass) (testName : Name) : CompilerM α := x { decls } { passUnderTest, testName } def InOutAssertionM.run (x : InOutAssertionM α) (input output : Array Decl) (passUnderTest : Pass) (testName : Name) : CompilerM α := x { input, output } { passUnderTest, testName } def getTestName : TestM Name := do return (←read).testName def getPassUnderTest : TestM Pass := do return (←read).passUnderTest def getDecls : SimpleAssertionM (Array Decl) := do return (←read).decls def getInputDecls : InOutAssertionM (Array Decl) := do return (←read).input def getOutputDecls : InOutAssertionM (Array Decl) := do return (←read).output /-- If `property` is `false` throw an exception with `msg`. -/ def assert (property : Bool) (msg : String) : TestM Unit := do unless property do throwError msg private def assertAfterTest (test : SimpleTest) : TestInstallerM (Pass → Pass) := do let testName := (←read).testName return fun passUnderTest => { phase := passUnderTest.phase name := testName run := fun decls => do trace[Compiler.test] "Starting post condition test {testName} for {passUnderTest.name} occurrence {passUnderTest.occurrence}" test.run decls passUnderTest testName trace[Compiler.test] "Post condition test {testName} for {passUnderTest.name} occurrence {passUnderTest.occurrence} successful" return decls } /-- Install an assertion pass right after a specific occurrence of a pass, default is first. -/ def assertAfter (test : SimpleTest) (occurrence : Nat := 0): TestInstaller := do let passUnderTestName := (←read).passUnderTestName let assertion ← assertAfterTest test return .installAfter passUnderTestName assertion occurrence /-- Install an assertion pass right after each occurrence of a pass. -/ def assertAfterEachOccurrence (test : SimpleTest) : TestInstaller := do let passUnderTestName := (←read).passUnderTestName let assertion ← assertAfterTest test return .installAfterEach passUnderTestName assertion /-- Install an assertion pass right after a specific occurrence of a pass, default is first. The assertion operates on a per declaration basis. -/ def assertForEachDeclAfter (assertion : Pass → Decl → Bool) (msg : String) (occurrence : Nat := 0) : TestInstaller := let assertion := do let pass ← getPassUnderTest (←getDecls).forM (fun decl => assert (assertion pass decl) msg) assertAfter assertion occurrence /-- Install an assertion pass right after the each occurrence of a pass. The assertion operates on a per declaration basis. -/ def assertForEachDeclAfterEachOccurrence (assertion : Pass → Decl → Bool) (msg : String) : TestInstaller := assertAfterEachOccurrence <| do let pass ← getPassUnderTest (←getDecls).forM (fun decl => assert (assertion pass decl) msg) private def assertAroundTest (test : InOutTest) : TestInstallerM (Pass → Pass) := do let testName := (←read).testName return fun passUnderTest => { phase := passUnderTest.phase name := passUnderTest.name run := fun decls => do trace[Compiler.test] "Starting wrapper test {testName} for {passUnderTest.name} occurrence {passUnderTest.occurrence}" let newDecls ← passUnderTest.run decls test.run decls newDecls passUnderTest testName trace[Compiler.test] "Wrapper test {testName} for {passUnderTest.name} occurrence {passUnderTest.occurrence} successful" return newDecls } /-- Replace a specific occurrence, default is first, of a pass with a wrapper one that allows the user to provide an assertion which takes into account both the declarations that were sent to and produced by the pass under test. -/ def assertAround (test : InOutTest) (occurrence : Nat := 0) : TestInstaller := do let passUnderTestName := (←read).passUnderTestName let assertion ← assertAroundTest test return .replacePass passUnderTestName assertion occurrence /-- Replace all occurrences of a pass with a wrapper one that allows the user to provide an assertion which takes into account both the declarations that were sent to and produced by the pass under test. -/ def assertAroundEachOccurrence (test : InOutTest) : TestInstaller := do let passUnderTestName := (←read).passUnderTestName let assertion ← assertAroundTest test return .replaceEachOccurrence passUnderTestName assertion private def throwFixPointError (err : String) (firstResult secondResult : Array Decl) : CompilerM Unit := do let mut err := err err := err ++ "Result after usual run:" let folder := fun err decl => do return err ++ s!"\n{←ppDecl decl}" err ← firstResult.foldlM (init := err) folder err := err ++ "Result after further run:" err ← secondResult.foldlM (init := err) folder throwError err /-- Insert a pass after `passUnderTestName`, that ensures, that if `passUnderTestName` is executed twice in a row, no change in the resulting expression will occur, i.e. the pass is at a fix point. -/ def assertIsAtFixPoint : TestInstaller := let test := do let passUnderTest ← getPassUnderTest let decls ← getDecls let secondResult ← passUnderTest.run decls if decls.size < secondResult.size then let err := s!"Pass {passUnderTest.name} did not reach a fixpoint, it added declarations on further runs:\n" throwFixPointError err decls secondResult else if decls.size > secondResult.size then let err := s!"Pass {passUnderTest.name} did not reach a fixpoint, it removed declarations on further runs:\n" throwFixPointError err decls secondResult else if decls != secondResult then let err := s!"Pass {passUnderTest.name} did not reach a fixpoint, it either changed declarations or their order:\n" throwFixPointError err decls secondResult assertAfterEachOccurrence test /-- Compare the overall sizes of the input and output of `passUnderTest` with `assertion`. If `assertion inputSize outputSize` is `false` throw an exception with `msg`. -/ def assertSize (assertion : Nat → Nat → Bool) (msg : String) : TestInstaller := let sumDeclSizes := fun decls => decls.map Decl.size |>.foldl (init := 0) (· + ·) let assertion := (fun inputS outputS => Testing.assert (assertion inputS outputS) s!"{msg}: input size {inputS} output size {outputS}") assertAroundEachOccurrence (do assertion (sumDeclSizes (←getInputDecls)) (sumDeclSizes (←getOutputDecls))) /-- Assert that the overall size of the `Decl`s in the compilation pipeline does not change after `passUnderTestName`. -/ def assertPreservesSize (msg : String) : TestInstaller := assertSize (· == ·) msg /-- Assert that the overall size of the `Decl`s in the compilation pipeline gets reduced by `passUnderTestName`. -/ def assertReducesSize (msg : String) : TestInstaller := assertSize (· > ·) msg /-- Assert that the overall size of the `Decl`s in the compilation pipeline gets reduced or stays unchanged by `passUnderTestName`. -/ def assertReducesOrPreservesSize (msg : String) : TestInstaller := assertSize (· ≥ ·) msg /-- Assert that the pass under test produces `Decl`s that do not contain `Expr.const constName` in their `Code.let` values anymore. -/ def assertDoesNotContainConstAfter (constName : Name) (msg : String) : TestInstaller := assertForEachDeclAfterEachOccurrence (fun _ decl => !decl.value.containsConst constName) msg def assertNoFun : TestInstaller := assertAfter do for decl in (← getDecls) do decl.value.forM fun | .fun .. => throwError "declaration `{decl.name}` contains a local function declaration" | _ => return () end Testing end Lean.Compiler.LCNF
dff9dab3fca0ba180bab187676fb2b84c5bd8128
3aad12fe82645d2d3173fbedc2e5c2ba945a4d75
/src/data/pointer.lean
5a49267aa6cc114df31363898f220d575cf6ca47
[]
no_license
seanpm2001/LeanProver-Community_MathLIB-Nursery
4f88d539cb18d73a94af983092896b851e6640b5
0479b31fa5b4d39f41e89b8584c9f5bf5271e8ec
refs/heads/master
1,688,730,786,645
1,572,070,026,000
1,572,070,026,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,370
lean
import tactic import tactic.linarith import tactic.norm_num import data.sigma.fst import category.basic universes u structure ref (α : Type u) : Type u := (addr : ℕ) def value := Σ α : Type u, α namespace intl inductive st (α : Type u) : Type.{u+1} | pure (x : α) : st | new_ref {β : Type u} : β → (ref β → st) → st | read {β : Type u} : ref β → (β → st) → st | write {β : Type u} : β → ref β → (punit.{u+1} → st) → st end intl export intl (st) namespace st variables {α β : Type u} open intl.st (hiding pure) protected def bind : Π (x : st α) (f : α → st β), st β | (intl.st.pure x) f := f x | (new_ref x f) g := new_ref x $ λ r, bind (f r) g | (read r f) g := read r $ λ v, bind (f v) g | (write v r f) g := write v r $ λ v, bind (f v) g def addr : sigma ref → ℕ | ⟨_,⟨_,x⟩⟩ := x instance : monad.{u u+1} st := { pure := @intl.st.pure, bind := @st.bind } instance : is_lawful_monad.{u u+1} st := begin refine { .. }; intros; try { refl <|> dsimp [(>>=),(<$>)] }; induction x; simp [(>>=),(<$>),st.bind] with functor_norm; ext; simp *, end inductive ref_layout : list (sigma ref) → Prop | nil : ref_layout [] | cons (r : sigma ref) (xs : list (sigma ref)) : ¬ addr r ∈ xs.map addr → ref_layout xs → ref_layout (r :: xs) inductive mem_safety : list (sigma ref.{u}) → Π {α}, st.{u} α → Prop | pure (ls) {α} (x : α) : mem_safety ls (pure x) | new_ref (ls) {α β} (x : α) (f : ref α → st β) : (∀ (r : ref α), let r' := sigma.mk α r in ¬ r' ∈ ls → mem_safety (r' :: ls) (f r)) → mem_safety ls (new_ref x f) | read (ls) {β} (r : ref β) {α} (f : β → st α) : sigma.mk β r ∈ ls → (∀ x, mem_safety ls (f x)) → mem_safety ls (read r f) | write (ls) {β} (r : ref β) (x : β) {α} (f : punit → st α) : sigma.mk _ r ∈ ls → mem_safety ls (f punit.star) → mem_safety ls (write x r f) lemma mem_safety_bind {ls} {x : st β} {f : β → st α} (h₀ : mem_safety ls x) (h₁ : ∀ ls' i, ls ⊆ ls' → mem_safety ls' (f i)) : mem_safety ls (st.bind x f) := begin induction h₀ generalizing f; simp only [st.bind,pure], { apply h₁, refl }, { constructor, intros, apply h₀_ih, assumption, intros, apply h₁, transitivity ; [skip, exact a_1], apply list.subset_cons_of_subset, refl }, { constructor, assumption, intros, apply h₀_ih _ h₁, }, { constructor, assumption, apply h₀_ih h₁, }, end def alloc (α : Type u) (ls : list (sigma ref.{u})) : ref α := ⟨ _, ls.length ⟩ structure mem (ls : list (sigma ref.{u})) := (vals : array ls.length value.{u}) (valid_ptrs : ∀ x : sigma ref, x ∈ ls → x.2.addr < ls.length) (well_typed : ∀ (x : sigma ref) (h : x ∈ ls), (vals.read ⟨x.2.addr,valid_ptrs _ h⟩).1 = x.1 ) local notation `♯` := by assumption lemma same_type_of_same_addr {ls : list (sigma ref)} (m : mem ls) (r₀ ∈ ls) (r₁ ∈ ls) (h : r₀.2.addr = r₁.2.addr) : r₀.1 = r₁.1 := calc r₀.1 = (m.vals.read ⟨r₀.2.addr,m.valid_ptrs _ ♯⟩).1 : by rw m.well_typed ... = (m.vals.read ⟨r₁.2.addr,m.valid_ptrs _ ♯⟩).1 : by { casesm* [sigma _,ref _], cases h, refl } ... = r₁.1 : by rw m.well_typed def mem.read {ls : list (sigma ref.{u})} {α} (r : ref α) (h : sigma.mk α r ∈ ls) (m : mem ls) : α := cast (m.well_typed _ h) (m.vals.read ⟨r.addr,m.valid_ptrs _ h⟩).2 def mem.write {ls : list (sigma ref.{u})} {α} (x : α) (r : ref α) (h : sigma.mk _ r ∈ ls) (m : mem ls) : mem ls := { vals := m.vals.write ⟨r.addr,m.valid_ptrs _ h⟩ ⟨α,x⟩, well_typed := by { intros, by_cases h' : r.addr = (x_1.snd).addr, { cases r, cases h', rw array.read_write, exact same_type_of_same_addr m _ h _ h_1 h', }, { rw array.read_write_of_ne, apply m.well_typed, intro, injection a, contradiction } }, .. m } def mem.alloc {ls : list (sigma ref.{u})} {α} (x : α) (m : mem ls) : mem (⟨α,⟨_,ls.length⟩⟩ :: ls) := { vals := m.vals.push_back ⟨_,x⟩, valid_ptrs := by { rintro _ ⟨_ | _⟩, norm_num, dsimp, transitivity ls.length, apply m.valid_ptrs _ ♯, norm_num }, well_typed := by { rintros _ ⟨ _ | _ ⟩, { simp [array.read,array.push_back,d_array.read] }, have : (x_1.snd).addr ≠ list.length ls, { apply ne_of_lt, apply m.valid_ptrs _ h }, { simp [array.read,array.push_back,d_array.read,*], apply m.well_typed _ h, } } } lemma alloc_free {ls : list (sigma ref)} (m : mem ls) : sigma.mk α (alloc α ls) ∉ ls := begin dsimp [alloc], intro h, have := m.valid_ptrs _ h, dsimp at this, apply lt_irrefl _ this end def mem₀ : mem [] := { vals := array.nil, valid_ptrs := by rintro _ ⟨ ⟩, well_typed := by rintro _ ⟨ ⟩ } def run' {α} : Π ls (x : st α), mem ls → mem_safety ls x → α | ls (intl.st.pure a) m _ := a | ls (@new_ref _ α x f) m h := run' (sigma.mk _ _ :: ls) (f _) (m.alloc x) (by cases h; apply h_a _ (alloc_free m)) | ls (@read _ α r f) m h := run' ls (f $ m.read r $ by { cases h, assumption }) ♯ (by cases h; apply h_a_1) | ls (@write _ α x r f) m h := run' ls (f ()) (m.write x r $ by { cases h, assumption }) $ by { cases h, assumption } def run {α} (x : st α) (h : mem_safety [] x) : α := run' [] x mem₀ h run_cmd mk_simp_attr `st attribute [st] st.bind @[st] def new_ref (x : α) : st (ref α) := intl.st.new_ref x pure @[st] def write (r : ref α) (x : α) : st punit := intl.st.write x r pure @[st] def read (r : ref α) : st α := intl.st.read r pure def ex (x x' : α) : st (α × α) := do r ← new_ref x, y ← read r, write r x', prod.mk y <$> read r lemma ex_safe : ∀ x x' : α, mem_safety [] (ex x x') := begin intros, simp [ex,(>>=),(<$>),pure] with st, constructor, intros, constructor, simp, intros, constructor, simp, intros, constructor, simp, intros, constructor end #eval run (ex 1 3) (ex_safe 1 3) def swap (r r' : ref α) : st punit := do t ← read r >>= new_ref, read r' >>= write r, read t >>= write r' lemma swap_safe (ls : list $ sigma ref.{u}) : ∀ r r' : ref α, (sigma.mk _ r ∈ ls) → (sigma.mk _ r' ∈ ls) → mem_safety ls (swap r r') := begin intros, simp [swap,(>>=),(<$>),pure] with st, constructor, simpa, intros, constructor, intros, constructor, right, simpa, intros, constructor, right, simpa, intros, constructor, left, refl, intros, constructor, right, simpa, intros, constructor end def swap_if [decidable_linear_order α] (r r' : ref α) : st punit := do x ← read r, y ← read r', if y < x then swap r r' else pure punit.star lemma swap_if_safe [decidable_linear_order α] (ls : list $ sigma ref.{u}) : ∀ r r' : ref α, (sigma.mk _ r ∈ ls) → (sigma.mk _ r' ∈ ls) → mem_safety ls (swap_if r r') := begin intros, simp [swap_if,(>>=),(<$>),pure] with st, constructor, assumption, intros, constructor, assumption, intros, split_ifs, apply swap_safe; assumption, constructor, end def sort_triple [decidable_linear_order α] (x y z : α) : st (α × α × α) := do rx ← new_ref x, ry ← new_ref y, rz ← new_ref z, swap_if rx ry, swap_if ry rz, swap_if rx ry, x' ← read rx, y' ← read ry, z' ← read rz, pure (x',y',z') lemma sort_triple_safe [decidable_linear_order α] (ls : list $ sigma ref.{u}) : ∀ x y z : α, mem_safety ls (sort_triple x y z) := begin intros, simp [sort_triple,(>>=),(<$>),pure] with st, constructor, intros, constructor, intros, constructor, intros, refine mem_safety_bind _ _, apply swap_if_safe, { simp }, { simp }, intros, refine mem_safety_bind _ _, apply swap_if_safe, { apply a_3, simp }, { apply a_3, simp }, intros, refine mem_safety_bind _ _, apply swap_if_safe, { apply a_4, apply a_3, simp }, { apply a_4, apply a_3, simp }, intros, constructor, apply a_5, apply a_4, apply a_3, simp, intros, constructor, apply a_5, apply a_4, apply a_3, simp, intros, constructor, apply a_5, apply a_4, apply a_3, simp, intros, constructor, end #eval run (sort_triple 3 7 2) (sort_triple_safe _ _ _ _) end st
b0fa80dfd9d3171baba374d390a670a513ee85b6
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/ftree.lean
e1631ea0ce958f2b0b314c32d634306a14ecc8a8
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
717
lean
inductive List (T : Sort*) : Sort* | nil {} : List | cons : T → List → List namespace explicit inductive {u₁ u₂} ftree (A : Type u₁) (B : Type u₂) : Type (max 1 u₁ u₂) | leafa : A → ftree | leafb : B → ftree | node : (A → ftree) → (B → ftree) → ftree end explicit namespace implicit inductive ftree (A : Type) (B : Type) : Type | leafa : ftree | node : (A → B → ftree) → (B → ftree) → ftree set_option pp.universes true check ftree end implicit namespace implicit2 inductive ftree (A : Type) (B : Type) : Type | leafa : A → ftree | leafb : B → ftree | node : (List A → ftree) → (B → ftree) → ftree set_option pp.universes true check ftree end implicit2
be8db23c06a4a94e0f4adf553506c6e01fc8fe28
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/category_theory/limits/shapes/zero.lean
54c2a6f22020c8ef64a34c54b0682705827c53a8
[ "Apache-2.0" ]
permissive
SAAluthwela/mathlib
62044349d72dd63983a8500214736aa7779634d3
83a4b8b990907291421de54a78988c024dc8a552
refs/heads/master
1,679,433,873,417
1,615,998,031,000
1,615,998,031,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,937
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.shapes.terminal import category_theory.limits.shapes.binary_products import category_theory.limits.shapes.products import category_theory.limits.shapes.images import category_theory.isomorphism_classes /-! # Zero morphisms and zero objects A category "has zero morphisms" if there is a designated "zero morphism" in each morphism space, and compositions of zero morphisms with anything give the zero morphism. (Notice this is extra structure, not merely a property.) A category "has a zero object" if it has an object which is both initial and terminal. Having a zero object provides zero morphisms, as the unique morphisms factoring through the zero object. ## References * https://en.wikipedia.org/wiki/Zero_morphism * [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2] -/ noncomputable theory universes v u open category_theory open category_theory.category namespace category_theory.limits variables (C : Type u) [category.{v} C] /-- A category "has zero morphisms" if there is a designated "zero morphism" in each morphism space, and compositions of zero morphisms with anything give the zero morphism. -/ class has_zero_morphisms := [has_zero : Π X Y : C, has_zero (X ⟶ Y)] (comp_zero' : ∀ {X Y : C} (f : X ⟶ Y) (Z : C), f ≫ (0 : Y ⟶ Z) = (0 : X ⟶ Z) . obviously) (zero_comp' : ∀ (X : C) {Y Z : C} (f : Y ⟶ Z), (0 : X ⟶ Y) ≫ f = (0 : X ⟶ Z) . obviously) attribute [instance] has_zero_morphisms.has_zero restate_axiom has_zero_morphisms.comp_zero' restate_axiom has_zero_morphisms.zero_comp' variables {C} @[simp] lemma comp_zero [has_zero_morphisms C] {X Y : C} {f : X ⟶ Y} {Z : C} : f ≫ (0 : Y ⟶ Z) = (0 : X ⟶ Z) := has_zero_morphisms.comp_zero f Z @[simp] lemma zero_comp [has_zero_morphisms C] {X : C} {Y Z : C} {f : Y ⟶ Z} : (0 : X ⟶ Y) ≫ f = (0 : X ⟶ Z) := has_zero_morphisms.zero_comp X f instance has_zero_morphisms_pempty : has_zero_morphisms (discrete pempty) := { has_zero := by tidy } instance has_zero_morphisms_punit : has_zero_morphisms (discrete punit) := { has_zero := by tidy } namespace has_zero_morphisms variables {C} /-- This lemma will be immediately superseded by `ext`, below. -/ private lemma ext_aux (I J : has_zero_morphisms C) (w : ∀ X Y : C, (@has_zero_morphisms.has_zero _ _ I X Y).zero = (@has_zero_morphisms.has_zero _ _ J X Y).zero) : I = J := begin casesI I, casesI J, congr, { ext X Y, exact w X Y }, { apply proof_irrel_heq, }, { apply proof_irrel_heq, } end /-- If you're tempted to use this lemma "in the wild", you should probably carefully consider whether you've made a mistake in allowing two instances of `has_zero_morphisms` to exist at all. See, particularly, the note on `zero_morphisms_of_zero_object` below. -/ lemma ext (I J : has_zero_morphisms C) : I = J := begin apply ext_aux, intros X Y, rw ←@has_zero_morphisms.comp_zero _ _ I X X (@has_zero_morphisms.has_zero _ _ J X X).zero, rw @has_zero_morphisms.zero_comp _ _ J, end instance : subsingleton (has_zero_morphisms C) := ⟨ext⟩ end has_zero_morphisms open has_zero_morphisms section variables {C} [has_zero_morphisms C] lemma zero_of_comp_mono {X Y Z : C} {f : X ⟶ Y} (g : Y ⟶ Z) [mono g] (h : f ≫ g = 0) : f = 0 := by { rw [←zero_comp, cancel_mono] at h, exact h } lemma zero_of_epi_comp {X Y Z : C} (f : X ⟶ Y) {g : Y ⟶ Z} [epi f] (h : f ≫ g = 0) : g = 0 := by { rw [←comp_zero, cancel_epi] at h, exact h } lemma eq_zero_of_image_eq_zero {X Y : C} {f : X ⟶ Y} [has_image f] (w : image.ι f = 0) : f = 0 := by rw [←image.fac f, w, has_zero_morphisms.comp_zero] lemma nonzero_image_of_nonzero {X Y : C} {f : X ⟶ Y} [has_image f] (w : f ≠ 0) : image.ι f ≠ 0 := λ h, w (eq_zero_of_image_eq_zero h) end section universes v' u' variables (D : Type u') [category.{v'} D] variables [has_zero_morphisms C] [has_zero_morphisms D] lemma equivalence_preserves_zero_morphisms (F : C ≌ D) (X Y : C) : F.functor.map (0 : X ⟶ Y) = (0 : F.functor.obj X ⟶ F.functor.obj Y) := begin have t : F.functor.map (0 : X ⟶ Y) = F.functor.map (0 : X ⟶ Y) ≫ (0 : F.functor.obj Y ⟶ F.functor.obj Y), { apply faithful.map_injective (F.inverse), rw [functor.map_comp, equivalence.inv_fun_map], dsimp, rw [zero_comp, comp_zero, zero_comp], }, exact t.trans (by simp) end @[simp] lemma is_equivalence_preserves_zero_morphisms (F : C ⥤ D) [is_equivalence F] (X Y : C) : F.map (0 : X ⟶ Y) = 0 := by rw [←functor.as_equivalence_functor F, equivalence_preserves_zero_morphisms] end variables (C) /-- A category "has a zero object" if it has an object which is both initial and terminal. -/ class has_zero_object := (zero : C) (unique_to : Π X : C, unique (zero ⟶ X)) (unique_from : Π X : C, unique (X ⟶ zero)) instance has_zero_object_punit : has_zero_object (discrete punit) := { zero := punit.star, unique_to := by tidy, unique_from := by tidy, } variables {C} namespace has_zero_object variables [has_zero_object C] /-- Construct a `has_zero C` for a category with a zero object. This can not be a global instance as it will trigger for every `has_zero C` typeclass search. -/ protected def has_zero : has_zero C := { zero := has_zero_object.zero } local attribute [instance] has_zero_object.has_zero local attribute [instance] has_zero_object.unique_to has_zero_object.unique_from @[ext] lemma to_zero_ext {X : C} (f g : X ⟶ 0) : f = g := by rw [(has_zero_object.unique_from X).uniq f, (has_zero_object.unique_from X).uniq g] @[ext] lemma from_zero_ext {X : C} (f g : 0 ⟶ X) : f = g := by rw [(has_zero_object.unique_to X).uniq f, (has_zero_object.unique_to X).uniq g] instance (X : C) : subsingleton (X ≅ 0) := by tidy instance {X : C} (f : 0 ⟶ X) : mono f := { right_cancellation := λ Z g h w, by ext, } instance {X : C} (f : X ⟶ 0) : epi f := { left_cancellation := λ Z g h w, by ext, } /-- A category with a zero object has zero morphisms. It is rarely a good idea to use this. Many categories that have a zero object have zero morphisms for some other reason, for example from additivity. Library code that uses `zero_morphisms_of_zero_object` will then be incompatible with these categories because the `has_zero_morphisms` instances will not be definitionally equal. For this reason library code should generally ask for an instance of `has_zero_morphisms` separately, even if it already asks for an instance of `has_zero_objects`. -/ def zero_morphisms_of_zero_object : has_zero_morphisms C := { has_zero := λ X Y, { zero := inhabited.default (X ⟶ 0) ≫ inhabited.default (0 ⟶ Y) }, zero_comp' := λ X Y Z f, by { dunfold has_zero.zero, rw category.assoc, congr, }, comp_zero' := λ X Y Z f, by { dunfold has_zero.zero, rw ←category.assoc, congr, }} /-- A zero object is in particular initial. -/ lemma has_initial : has_initial C := has_initial_of_unique 0 /-- A zero object is in particular terminal. -/ lemma has_terminal : has_terminal C := has_terminal_of_unique 0 end has_zero_object section variables [has_zero_object C] [has_zero_morphisms C] local attribute [instance] has_zero_object.has_zero @[simp] lemma id_zero : 𝟙 (0 : C) = (0 : 0 ⟶ 0) := by ext /-- An arrow ending in the zero object is zero -/ -- This can't be a `simp` lemma because the left hand side would be a metavariable. lemma zero_of_to_zero {X : C} (f : X ⟶ 0) : f = 0 := by ext lemma zero_of_target_iso_zero {X Y : C} (f : X ⟶ Y) (i : Y ≅ 0) : f = 0 := begin have h : f = f ≫ i.hom ≫ 𝟙 0 ≫ i.inv := by simp only [iso.hom_inv_id, id_comp, comp_id], simpa using h, end /-- An arrow starting at the zero object is zero -/ lemma zero_of_from_zero {X : C} (f : 0 ⟶ X) : f = 0 := by ext lemma zero_of_source_iso_zero {X Y : C} (f : X ⟶ Y) (i : X ≅ 0) : f = 0 := begin have h : f = i.hom ≫ 𝟙 0 ≫ i.inv ≫ f := by simp only [iso.hom_inv_id_assoc, id_comp, comp_id], simpa using h, end lemma zero_of_source_iso_zero' {X Y : C} (f : X ⟶ Y) (i : is_isomorphic X 0) : f = 0 := zero_of_source_iso_zero f (nonempty.some i) lemma zero_of_target_iso_zero' {X Y : C} (f : X ⟶ Y) (i : is_isomorphic Y 0) : f = 0 := zero_of_target_iso_zero f (nonempty.some i) lemma mono_of_source_iso_zero {X Y : C} (f : X ⟶ Y) (i : X ≅ 0) : mono f := ⟨λ Z g h w, by rw [zero_of_target_iso_zero g i, zero_of_target_iso_zero h i]⟩ lemma epi_of_target_iso_zero {X Y : C} (f : X ⟶ Y) (i : Y ≅ 0) : epi f := ⟨λ Z g h w, by rw [zero_of_source_iso_zero g i, zero_of_source_iso_zero h i]⟩ /-- An object `X` has `𝟙 X = 0` if and only if it is isomorphic to the zero object. Because `X ≅ 0` contains data (even if a subsingleton), we express this `↔` as an `≃`. -/ def id_zero_equiv_iso_zero (X : C) : (𝟙 X = 0) ≃ (X ≅ 0) := { to_fun := λ h, { hom := 0, inv := 0, }, inv_fun := λ i, zero_of_target_iso_zero (𝟙 X) i, left_inv := by tidy, right_inv := by tidy, } @[simp] lemma id_zero_equiv_iso_zero_apply_hom (X : C) (h : 𝟙 X = 0) : ((id_zero_equiv_iso_zero X) h).hom = 0 := rfl @[simp] lemma id_zero_equiv_iso_zero_apply_inv (X : C) (h : 𝟙 X = 0) : ((id_zero_equiv_iso_zero X) h).inv = 0 := rfl /-- If an object `X` is isomorphic to 0, there's no need to use choice to construct an explicit isomorphism: the zero morphism suffices. -/ def iso_of_is_isomorphic_zero {X : C} (P : is_isomorphic X 0) : X ≅ 0 := { hom := 0, inv := 0, hom_inv_id' := begin casesI P, rw ←P.hom_inv_id, rw ←category.id_comp P.inv, simp, end, inv_hom_id' := by simp, } end section is_iso variables [has_zero_morphisms C] /-- A zero morphism `0 : X ⟶ Y` is an isomorphism if and only if the identities on both `X` and `Y` are zero. -/ @[simps] def is_iso_zero_equiv (X Y : C) : is_iso (0 : X ⟶ Y) ≃ (𝟙 X = 0 ∧ 𝟙 Y = 0) := { to_fun := by { introsI i, rw ←is_iso.hom_inv_id (0 : X ⟶ Y), rw ←is_iso.inv_hom_id (0 : X ⟶ Y), simp }, inv_fun := λ h, ⟨(0 : Y ⟶ X), by tidy⟩, left_inv := by tidy, right_inv := by tidy, } /-- A zero morphism `0 : X ⟶ X` is an isomorphism if and only if the identity on `X` is zero. -/ def is_iso_zero_self_equiv (X : C) : is_iso (0 : X ⟶ X) ≃ (𝟙 X = 0) := by simpa using is_iso_zero_equiv X X variables [has_zero_object C] local attribute [instance] has_zero_object.has_zero /-- A zero morphism `0 : X ⟶ Y` is an isomorphism if and only if `X` and `Y` are isomorphic to the zero object. -/ def is_iso_zero_equiv_iso_zero (X Y : C) : is_iso (0 : X ⟶ Y) ≃ (X ≅ 0) × (Y ≅ 0) := begin -- This is lame, because `prod` can't cope with `Prop`, so we can't use `equiv.prod_congr`. refine (is_iso_zero_equiv X Y).trans _, symmetry, fsplit, { rintros ⟨eX, eY⟩, fsplit, exact (id_zero_equiv_iso_zero X).symm eX, exact (id_zero_equiv_iso_zero Y).symm eY, }, { rintros ⟨hX, hY⟩, fsplit, exact (id_zero_equiv_iso_zero X) hX, exact (id_zero_equiv_iso_zero Y) hY, }, { tidy, }, { tidy, }, end /-- A zero morphism `0 : X ⟶ X` is an isomorphism if and only if `X` is isomorphic to the zero object. -/ def is_iso_zero_self_equiv_iso_zero (X : C) : is_iso (0 : X ⟶ X) ≃ (X ≅ 0) := (is_iso_zero_equiv_iso_zero X X).trans subsingleton_prod_self_equiv end is_iso /-- If there are zero morphisms, any initial object is a zero object. -/ @[priority 50] instance has_zero_object_of_has_initial_object [has_zero_morphisms C] [has_initial C] : has_zero_object C := { zero := ⊥_ C, unique_to := λ X, ⟨⟨0⟩, by tidy⟩, unique_from := λ X, ⟨⟨0⟩, λ f, calc f = f ≫ 𝟙 _ : (category.comp_id _).symm ... = f ≫ 0 : by congr ... = 0 : has_zero_morphisms.comp_zero _ _ ⟩ } /-- If there are zero morphisms, any terminal object is a zero object. -/ @[priority 50] instance has_zero_object_of_has_terminal_object [has_zero_morphisms C] [has_terminal C] : has_zero_object C := { zero := ⊤_ C, unique_from := λ X, ⟨⟨0⟩, by tidy⟩, unique_to := λ X, ⟨⟨0⟩, λ f, calc f = 𝟙 _ ≫ f : (category.id_comp _).symm ... = 0 ≫ f : by congr ... = 0 : zero_comp ⟩ } section image variable [has_zero_morphisms C] lemma image_ι_comp_eq_zero {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} [has_image f] [epi (factor_thru_image f)] (h : f ≫ g = 0) : image.ι f ≫ g = 0 := zero_of_epi_comp (factor_thru_image f) $ by simp [h] variables [has_zero_object C] local attribute [instance] has_zero_object.has_zero /-- The zero morphism has a `mono_factorisation` through the zero object. -/ @[simps] def mono_factorisation_zero (X Y : C) : mono_factorisation (0 : X ⟶ Y) := { I := 0, m := 0, e := 0, } /-- The factorisation through the zero object is an image factorisation. -/ def image_factorisation_zero (X Y : C) : image_factorisation (0 : X ⟶ Y) := { F := mono_factorisation_zero X Y, is_image := { lift := λ F', 0 } } instance has_image_zero {X Y : C} : has_image (0 : X ⟶ Y) := has_image.mk $ image_factorisation_zero _ _ /-- The image of a zero morphism is the zero object. -/ def image_zero {X Y : C} : image (0 : X ⟶ Y) ≅ 0 := is_image.iso_ext (image.is_image (0 : X ⟶ Y)) (image_factorisation_zero X Y).is_image /-- The image of a morphism which is equal to zero is the zero object. -/ def image_zero' {X Y : C} {f : X ⟶ Y} (h : f = 0) [has_image f] : image f ≅ 0 := image.eq_to_iso h ≪≫ image_zero @[simp] lemma image.ι_zero {X Y : C} [has_image (0 : X ⟶ Y)] : image.ι (0 : X ⟶ Y) = 0 := begin rw ←image.lift_fac (mono_factorisation_zero X Y), simp, end /-- If we know `f = 0`, it requires a little work to conclude `image.ι f = 0`, because `f = g` only implies `image f ≅ image g`. -/ @[simp] lemma image.ι_zero' [has_equalizers C] {X Y : C} {f : X ⟶ Y} (h : f = 0) [has_image f] : image.ι f = 0 := by { rw image.eq_fac h, simp } end image /-- In the presence of zero morphisms, coprojections into a coproduct are (split) monomorphisms. -/ instance split_mono_sigma_ι {β : Type v} [decidable_eq β] [has_zero_morphisms C] (f : β → C) [has_colimit (discrete.functor f)] (b : β) : split_mono (sigma.ι f b) := { retraction := sigma.desc (λ b', if h : b' = b then eq_to_hom (congr_arg f h) else 0), } /-- In the presence of zero morphisms, projections into a product are (split) epimorphisms. -/ instance split_epi_pi_π {β : Type v} [decidable_eq β] [has_zero_morphisms C] (f : β → C) [has_limit (discrete.functor f)] (b : β) : split_epi (pi.π f b) := { section_ := pi.lift (λ b', if h : b = b' then eq_to_hom (congr_arg f h) else 0), } /-- In the presence of zero morphisms, coprojections into a coproduct are (split) monomorphisms. -/ instance split_mono_coprod_inl [has_zero_morphisms C] {X Y : C} [has_colimit (pair X Y)] : split_mono (coprod.inl : X ⟶ X ⨿ Y) := { retraction := coprod.desc (𝟙 X) 0, } /-- In the presence of zero morphisms, coprojections into a coproduct are (split) monomorphisms. -/ instance split_mono_coprod_inr [has_zero_morphisms C] {X Y : C} [has_colimit (pair X Y)] : split_mono (coprod.inr : Y ⟶ X ⨿ Y) := { retraction := coprod.desc 0 (𝟙 Y), } /-- In the presence of zero morphisms, projections into a product are (split) epimorphisms. -/ instance split_epi_prod_fst [has_zero_morphisms C] {X Y : C} [has_limit (pair X Y)] : split_epi (prod.fst : X ⨯ Y ⟶ X) := { section_ := prod.lift (𝟙 X) 0, } /-- In the presence of zero morphisms, projections into a product are (split) epimorphisms. -/ instance split_epi_prod_snd [has_zero_morphisms C] {X Y : C} [has_limit (pair X Y)] : split_epi (prod.snd : X ⨯ Y ⟶ Y) := { section_ := prod.lift 0 (𝟙 Y), } end category_theory.limits
64aeff95da76b310c04cf9a1b65eef772196cab7
fecda8e6b848337561d6467a1e30cf23176d6ad0
/src/topology/sheaves/local_predicate.lean
889b0255bf344b2999bc03dd522adb8cd0d0f363
[ "Apache-2.0" ]
permissive
spolu/mathlib
bacf18c3d2a561d00ecdc9413187729dd1f705ed
480c92cdfe1cf3c2d083abded87e82162e8814f4
refs/heads/master
1,671,684,094,325
1,600,736,045,000
1,600,736,045,000
297,564,749
1
0
null
1,600,758,368,000
1,600,758,367,000
null
UTF-8
Lean
false
false
16,278
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 topology.sheaves.sheaf_of_functions import topology.sheaves.stalks /-! # Functions satisfying a local predicate form a sheaf. At this stage, in `topology/sheaves/sheaf_of_functions.lean` we've proved that not-necessarily-continuous functions from a topological space into some type (or type family) form a sheaf. Why do the continuous functions form a sheaf? The point is just that continuity is a local condition, so one can use the lifting condition for functions to provide a candidate lift, then verify that the lift is actually continuous by using the factorisation condition for the lift (which guarantees that on each open set it agrees with the functions being lifted, which were assumed to be continuous). This file abstracts this argument to work for any collection of dependent functions on a topological space satisfying a "local predicate". As an application, we check that continuity is a local predicate in this sense, and provide * `Top.sheaf_condition.to_Top`: continuous functions into a topological space form a sheaf A sheaf constructed in this way has a natural map `stalk_to_fiber` from the stalks to the types in the ambient type family. We give conditions sufficient to show that this map is injective and/or surjective. -/ universe v noncomputable theory variables {X : Top.{v}} variables (T : X → Type v) open topological_space open opposite open category_theory open category_theory.limits namespace Top /-- Given a topological space `X : Top` and a type family `T : X → Type`, a `P : prelocal_predicate T` consists of: * a family of predicates `P.pred`, one for each `U : opens X`, of the form `(Π x : U, T x) → Prop` * a proof that if `f : Π x : V, T x` satisfies the predicate on `V : opens X`, then the restriction of `f` to any open subset `U` also satisfies the predicate. -/ structure prelocal_predicate := (pred : Π {U : opens X}, (Π x : U, T x) → Prop) (res : ∀ {U V : opens X} (i : U ⟶ V) (f : Π x : V, T x) (h : pred f), pred (λ x : U, f (i x))) variables (X) /-- Continuity is a "prelocal" predicate on functions to a fixed topological space `T`. -/ @[simps] def continuous_prelocal (T : Top.{v}) : prelocal_predicate (λ x : X, T) := { pred := λ U f, continuous f, res := λ U V i f h, continuous.comp h (opens.open_embedding_of_le (le_of_hom i)).continuous, } /-- Satisfying the inhabited linter. -/ instance inhabited_prelocal_predicate (T : Top.{v}) : inhabited (prelocal_predicate (λ x : X, T)) := ⟨continuous_prelocal X T⟩ variables {X} /-- Given a topological space `X : Top` and a type family `T : X → Type`, a `P : local_predicate T` consists of: * a family of predicates `P.pred`, one for each `U : opens X`, of the form `(Π x : U, T x) → Prop` * a proof that if `f : Π x : V, T x` satisfies the predicate on `V : opens X`, then the restriction of `f` to any open subset `U` also satisfies the predicate, and * a proof that given some `f : Π x : U, T x`, if for every `x : U` we can find an open set `x ∈ V ≤ U` so that the restriction of `f` to `V` satisfies the predicate, then `f` itself satisfies the predicate. -/ structure local_predicate extends prelocal_predicate T := (locality : ∀ {U : opens X} (f : Π x : U, T x) (w : ∀ x : U, ∃ (V : opens X) (m : x.1 ∈ V) (i : V ⟶ U), pred (λ x : V, f (i x : U))), pred f) variables (X) /-- Continuity is a "local" predicate on functions to a fixed topological space `T`. -/ def continuous_local (T : Top.{v}) : local_predicate (λ x : X, T) := { locality := λ U f w, begin apply continuous_iff_continuous_at.2, intro x, specialize w x, rcases w with ⟨V, m, i, w⟩, dsimp at w, rw continuous_iff_continuous_at at w, specialize w ⟨x, m⟩, simpa using (opens.open_embedding_of_le (le_of_hom i)).continuous_at_iff.1 w, end, ..continuous_prelocal X T } /-- Satisfying the inhabited linter. -/ instance inhabited_local_predicate (T : Top.{v}) : inhabited (local_predicate _) := ⟨continuous_local X T⟩ variables {X T} /-- Given a `P : prelocal_predicate`, we can always construct a `local_predicate` by asking that the condition from `P` holds locally near every point. -/ def prelocal_predicate.sheafify {T : X → Type v} (P : prelocal_predicate T) : local_predicate T := { pred := λ U f, ∀ x : U, ∃ (V : opens X) (m : x.1 ∈ V) (i : V ⟶ U), P.pred (λ x : V, f (i x : U)), res := λ V U i f w x, begin specialize w (i x), rcases w with ⟨V', m', i', p⟩, refine ⟨V ⊓ V', ⟨x.2,m'⟩, opens.inf_le_left _ _, _⟩, convert P.res (opens.inf_le_right V V') _ p, end, locality := λ U f w x, begin specialize w x, rcases w with ⟨V, m, i, p⟩, specialize p ⟨x.1, m⟩, rcases p with ⟨V', m', i', p'⟩, exact ⟨V', m', i' ≫ i, p'⟩, end } lemma prelocal_predicate.sheafify_of {T : X → Type v} {P : prelocal_predicate T} {U : opens X} {f : Π x : U, T x} (h : P.pred f) : P.sheafify.pred f := λ x, ⟨U, x.2, 𝟙 _, by { convert h, ext ⟨y, w⟩, refl, }⟩ /-- The subpresheaf of dependent functions on `X` satisfying the "pre-local" predicate `P`. -/ @[simps] def subpresheaf_to_Types (P : prelocal_predicate T) : presheaf (Type v) X := { obj := λ U, { f : Π x : unop U, T x // P.pred f }, map := λ U V i f, ⟨λ x, f.1 (i.unop x), P.res i.unop f.1 f.2⟩ }. namespace subpresheaf_to_Types variables (P : prelocal_predicate T) /-- The natural transformation including the subpresheaf of functions satisfying a local predicate into the presheaf of all functions. -/ def subtype : subpresheaf_to_Types P ⟶ presheaf_to_Types X T := { app := λ U f, f.1 } open Top.sheaf_condition /-- The natural transformation from the sheaf condition diagram for functions satisfying a local predicate to the sheaf condition diagram for arbitrary functions, given by forgetting that the local predicate holds. -/ @[simps] def diagram_subtype {ι : Type v} (U : ι → opens X) : diagram (subpresheaf_to_Types P) U ⟶ diagram (presheaf_to_Types X T) U := { app := λ j, walking_parallel_pair.rec_on j (pi.map (λ i f, f.1)) (pi.map (λ p f, f.1)), naturality' := begin rintro ⟨_|_⟩ ⟨_|_⟩ ⟨⟩, { refl, }, { dsimp [left_res, subpresheaf_to_Types, presheaf_to_Types], simp only [limit.lift_map], ext1 ⟨i₁,i₂⟩, simp only [limit.lift_π, cones.postcompose_obj_π, discrete.nat_trans_app, limit.map_π_assoc, fan.mk_π_app, nat_trans.comp_app, category.assoc], ext, simp only [types_comp_apply, subtype.val_eq_coe], }, { dsimp [right_res, subpresheaf_to_Types, presheaf_to_Types], simp only [limit.lift_map], ext1 ⟨i₁,i₂⟩, simp only [limit.lift_π, cones.postcompose_obj_π, discrete.nat_trans_app, limit.map_π_assoc, fan.mk_π_app, nat_trans.comp_app, category.assoc], ext, simp only [types_comp_apply, subtype.val_eq_coe], }, { refl, }, end}. -- auxilliary lemma for `sheaf_condition` below lemma sheaf_condition_fac {P : local_predicate T} {ι : Type v} {U : ι → opens X} {s : fork (left_res (subpresheaf_to_Types P.to_prelocal_predicate) U) (right_res (subpresheaf_to_Types P.to_prelocal_predicate) U)} (i : ι) (f : s.X) (h) : limit.π (discrete.functor (λ i, { f // P.pred f })) i (res (subpresheaf_to_Types P.to_prelocal_predicate) U ⟨(to_Types X T U).lift ((cones.postcompose (diagram_subtype _ U)).obj s) f, h⟩) = limit.π (discrete.functor (λ i, { f // P.pred f })) i (s.ι f) := begin apply subtype.coe_injective, convert congr_fun ((to_Types X T U).fac ((cones.postcompose (diagram_subtype P.to_prelocal_predicate U)).obj s) walking_parallel_pair.zero =≫ pi.π (λ i, (X.presheaf_to_Types T).obj (op (U i))) i) f, { dsimp [res, presheaf_to_Types, subpresheaf_to_Types], simp only [types.pi_lift_π_apply, fan.mk_π_app, subtype.coe_mk, types.lift_π_apply], }, { dsimp, simp only [types.pi_map_π_apply, subtype.val_eq_coe], }, end -- auxilliary lemma for `sheaf_condition` below lemma sheaf_condition_uniq {P : local_predicate T} {ι : Type v} {U : ι → opens X} {s : fork (left_res (subpresheaf_to_Types P.to_prelocal_predicate) U) (right_res (subpresheaf_to_Types P.to_prelocal_predicate) U)} (m : s.X ⟶ (fork (subpresheaf_to_Types P.to_prelocal_predicate) U).X) (w : ∀ (j : walking_parallel_pair), m ≫ (fork (subpresheaf_to_Types P.to_prelocal_predicate) U).π.app j = s.π.app j) (f : s.X) (h) : m f = ⟨(to_Types X T U).lift ((cones.postcompose (diagram_subtype _ U)).obj s) f, h⟩ := begin apply subtype.coe_injective, let s' := (cones.postcompose (diagram_subtype P.to_prelocal_predicate U)).obj s, refine congr_fun ((to_Types X T U).uniq s' _ _) f, -- We "just" need to fix up our `w` to match the missing `w` argument. -- Unfortunately, it's still gross. intro j, specialize w j, dsimp [s'], rw ←w, clear w, simp only [category.assoc], rcases j with ⟨_|_⟩, { apply limit.hom_ext, intro i, simp only [category.assoc, limit.map_π], ext f' ⟨x, mem⟩, dsimp [res, subpresheaf_to_Types, presheaf_to_Types], simp only [discrete.nat_trans_app, types.map_π_apply, fan.mk_π_app, types.lift_π_apply], }, { apply limit.hom_ext, intro i, simp only [category.assoc, limit.map_π], ext f' ⟨x, mem⟩, dsimp [res, left_res, subpresheaf_to_Types, presheaf_to_Types], simp only [discrete.nat_trans_app, types.map_π_apply, types.pi_lift_π_apply, types_comp_apply, fan.mk_π_app, subtype.coe_mk, types.lift_π_apply], }, end /-- The functions satisfying a local predicate satisfy the sheaf condition. -/ def sheaf_condition (P : local_predicate T) : sheaf_condition (subpresheaf_to_Types P.to_prelocal_predicate) := λ ι U, begin refine fork.is_limit.mk _ _ _ _, { intros s f, fsplit, -- First, we use the fact that not necessarily continuous functions form a sheaf, -- to provide the lift. { let s' := (cones.postcompose (diagram_subtype P.to_prelocal_predicate U)).obj s, exact (to_Types X T U).lift s' f, }, -- Second, we need to do the actual work, proving this lift satisfies the predicate. { dsimp, -- We work locally, apply P.locality, -- so that once we're at a particular point `x`, we can select some open set `x ∈ U i`. rintro ⟨x, mem⟩, change x ∈ (supr U).val at mem, simp at mem, choose i hi using mem, use U i, use hi, use (opens.le_supr U i), -- Now our goal is to show that the previously chosen lift, -- when restricted to that `U i`, satisfies the predicate. -- This follows from the factorisation condition, and -- the fact that the underlying presheaf is a presheaf of functions satisfying the predicate. let s' := (cones.postcompose (diagram_subtype P.to_prelocal_predicate U)).obj s, have fac_i := ((to_Types X T U).fac s' walking_parallel_pair.zero) =≫ pi.π _ i, simp only [sheaf_condition.res, limit.lift_π, cones.postcompose_obj_π, sheaf_condition.fork_π_app_walking_parallel_pair_zero, fan.mk_π_app, nat_trans.comp_app, category.assoc] at fac_i, have fac_i_f := congr_fun fac_i f, simp only [diagram_subtype, discrete.nat_trans_app, types_comp_apply, presheaf_to_Types_map, limit.map_π, subtype.val_eq_coe] at fac_i_f, erw fac_i_f, apply subtype.property, }, }, { -- Proving the factorisation condition is straightforward: -- we observe that checking equality of functions satisfying a predicate reduces to -- checking equality of the underlying functions, -- and use the factorisation condition for the sheaf condition for functions. intros s, ext i f : 2, apply sheaf_condition_fac, }, { -- Similarly for proving the uniqueness condition, after a certain amount of bookkeeping. intros s m w, ext f : 1, apply sheaf_condition_uniq m w, }, end end subpresheaf_to_Types /-- The subsheaf of the sheaf of all dependently typed functions satisfying the local predicate `P`. -/ @[simps] def subsheaf_to_Types (P : local_predicate T) : sheaf (Type v) X := { presheaf := subpresheaf_to_Types P.to_prelocal_predicate, sheaf_condition := subpresheaf_to_Types.sheaf_condition P }. /-- There is a canonical map from the stalk to the original fiber, given by evaluating sections. -/ def stalk_to_fiber (P : local_predicate T) (x : X) : (subsheaf_to_Types P).presheaf.stalk x ⟶ T x := begin refine colimit.desc _ { X := T x, ι := { app := λ U f, _, naturality' := _ } }, { exact f.1 ⟨x, (unop U).2⟩, }, { tidy, } end @[simp] lemma stalk_to_fiber_germ (P : local_predicate T) (U : opens X) (x : U) (f) : stalk_to_fiber P x ((subsheaf_to_Types P).presheaf.germ x f) = f.1 x := begin dsimp [presheaf.germ, stalk_to_fiber], cases x, simp, refl, end /-- The `stalk_to_fiber` map is surjective at `x` if every point in the fiber `T x` has an allowed section passing through it. -/ lemma stalk_to_fiber_surjective (P : local_predicate T) (x : X) (w : ∀ (t : T x), ∃ (U : open_nhds x) (f : Π y : U.1, T y) (h : P.pred f), f ⟨x, U.2⟩ = t) : function.surjective (stalk_to_fiber P x) := λ t, begin rcases w t with ⟨U, f, h, rfl⟩, fsplit, { exact (subsheaf_to_Types P).presheaf.germ ⟨x, U.2⟩ ⟨f, h⟩, }, { exact stalk_to_fiber_germ _ U.1 ⟨x, U.2⟩ ⟨f, h⟩, } end /-- The `stalk_to_fiber` map is injective at `x` if any two allowed sections which agree at `x` agree on some neighborhood of `x`. -/ lemma stalk_to_fiber_injective (P : local_predicate T) (x : X) (w : ∀ (U V : open_nhds x) (fU : Π y : U.1, T y) (hU : P.pred fU) (fV : Π y : V.1, T y) (hV : P.pred fV) (e : fU ⟨x, U.2⟩ = fV ⟨x, V.2⟩), ∃ (W : open_nhds x) (iU : W ⟶ U) (iV : W ⟶ V), ∀ (w : W.1), fU (iU w : U.1) = fV (iV w : V.1)) : function.injective (stalk_to_fiber P x) := λ tU tV h, begin -- We promise to provide all the ingredients of the proof later: let Q : ∃ (W : (open_nhds x)ᵒᵖ) (s : Π w : (unop W).1, T w) (hW : P.pred s), tU = (subsheaf_to_Types P).presheaf.germ ⟨x, (unop W).2⟩ ⟨s, hW⟩ ∧ tV = (subsheaf_to_Types P).presheaf.germ ⟨x, (unop W).2⟩ ⟨s, hW⟩ := _, { choose W s hW e using Q, exact e.1.trans e.2.symm, }, -- Then use induction to pick particular representatives of `tU tV : stalk x` obtain ⟨U, ⟨fU, hU⟩, rfl⟩ := types.jointly_surjective' tU, obtain ⟨V, ⟨fV, hV⟩, rfl⟩ := types.jointly_surjective' tV, { -- Decompose everything into its constituent parts: dsimp, simp only [stalk_to_fiber, types.ι_desc_apply] at h, specialize w (unop U) (unop V) fU hU fV hV h, rcases w with ⟨W, iU, iV, w⟩, -- and put it back together again in the correct order. refine ⟨(op W), (λ w, fU (iU w : (unop U).1)), P.res _ _ hU, _⟩, rcases W with ⟨W, m⟩, exact ⟨types.colimit_sound iU.op (subtype.eq rfl), types.colimit_sound iV.op (subtype.eq (funext w).symm)⟩, }, end /-- Some repackaging: the presheaf of functions satisfying `continuous_prelocal` is just the same thing as the presheaf of continuous functions. -/ def subpresheaf_continuous_prelocal_iso_presheaf_to_Top (T : Top.{v}) : subpresheaf_to_Types (continuous_prelocal X T) ≅ presheaf_to_Top X T := nat_iso.of_components (λ X, { hom := by { rintro ⟨f, c⟩, exact ⟨f, c⟩, }, inv := by { rintro ⟨f, c⟩, exact ⟨f, c⟩, }, hom_inv_id' := by { ext ⟨f, p⟩ x, refl, }, inv_hom_id' := by { ext ⟨f, p⟩ x, refl, }, }) (by tidy) /-- The sheaf of continuous functions on `X` with values in a space `T`. -/ def sheaf_to_Top (T : Top.{v}) : sheaf (Type v) X := { presheaf := presheaf_to_Top X T, sheaf_condition := sheaf_condition_equiv_of_iso (subpresheaf_continuous_prelocal_iso_presheaf_to_Top T) (subpresheaf_to_Types.sheaf_condition (continuous_local X T)), } end Top
7181de674547eaef6b231544350d76eb87a6b50e
41ebf3cb010344adfa84907b3304db00e02db0a6
/uexp/tactic_paper_supplemental_material/robust_simp/robust_simp_caching_size.lean
beb8dbdf780f37983f24503d30fa03aac0c302de
[ "BSD-2-Clause" ]
permissive
ReinierKoops/Cosette
e061b2ba58b26f4eddf4cd052dcf7abd16dfe8fb
eb8dadd06ee05fe7b6b99de431dd7c4faef5cb29
refs/heads/master
1,686,483,953,198
1,624,293,498,000
1,624,293,498,000
378,997,885
0
0
BSD-2-Clause
1,624,293,485,000
1,624,293,484,000
null
UTF-8
Lean
false
false
3,158
lean
open tactic smt_tactic list expr /- The replace tactic above is very naive since it recomputes the size of every subterm without using any cache. This produces a quadratic behavior. The profiler will report the bottleneck at size. We can address this performance bottleneck by using a cache. -/ structure rsimp'_cfg := (max_rounds := 5) meta def collect_implied_eqs (cfg : rsimp'_cfg) : tactic cc_state := focus1 $ using_smt $ do add_lemmas_from_facts, /- Execute E-matching for at most max_rounds -/ repeat_at_most cfg.max_rounds (ematch >> try close), /- 'now' succeeds if the goal has been solved -/ (now >> return cc_state.mk) <|> /- If the goal was not solved return the state of the congruence closure procedure. -/ to_cc_state meta def sz_cache := expr_map nat meta def mk_sz_cache := expr_map.mk nat /- We could make it nicer by using the state monad -/ meta def size : expr → sz_cache → nat × sz_cache | e m := do if ¬ e.is_app then (1, m) else match m.find e with | some n := (n, m) | none := let (n₁, m₁) := size e.app_fn m, (n₂, m₂) := size e.app_arg m₁, n := n₁ + n₂ in (n, m₂.insert e n) end meta def smaller (m : sz_cache) (t s : expr) : bool × sz_cache := let (t_sz, m₁) := size t m, (s_sz, m₂) := size s m₁ in if t_sz < s_sz then (tt, m₂) else if t_sz > s_sz then (ff, m₂) else (expr.lex_lt t s, m₂) /- We use lexicographical order when t and s have the same size -/ meta def choose (ccs : cc_state) (m : sz_cache) (e : expr) : expr × sz_cache := ccs.fold_eqc e (e, m) $ λ ⟨best_so_far, m⟩ curr, let (is_smaller, new_m) := smaller m curr best_so_far in if is_smaller then (curr, new_m) else (best_so_far, new_m) meta def replace (ccs : cc_state) : tactic unit := do t ← target, (_, new_t, prf) ← simplify_top_down mk_sz_cache (λ m t, do root ← return $ ccs.root t, /- Retrieve the root of the equivalence class containing subterm 't'. -/ (repr, new_m) ← return $ choose ccs m root, /- Traverse the equivalence class and select the smallest element. -/ guard (¬ repr =ₐ t), /- (optional) Abort rewrite step if 'repr' is alpha-equivalent to 'e'. -/ prf ← ccs.eqv_proof t repr, /- Construct a proof that 't' = 'repr' -/ return (new_m, repr, prf)) t, replace_target new_t prf /- We use the rsimp' name here, since rsimp is already defined by the standard library. -/ meta def rsimp' (cfg : rsimp'_cfg := {}) : tactic unit := do ccs ← collect_implied_eqs cfg, try (replace ccs) namespace example_2 set_option profiler true axiom max_add_cancel : ∀ a b : nat, max a (a + b) = a + b constant p : nat → nat → Prop axiom pax : ∀ x, p x x attribute [simp] [ematch_lhs] max_assoc max_comm max_self max_add_cancel attribute [simp] max_left_comm example (a b c d : nat) (h : d = max c (a + b)) : p (max a (max d (b + a))) (max d (a + b)) := begin rsimp', /- The new goal is |- p d d -/ apply pax end end example_2
6bd49b4102fe07d44cad87b0ff73d43261836b28
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/pp_bug.lean
20356864773299d49587b0feb6708a2e1bda97fa
[ "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
201
lean
variables p q : Prop check ¬(p → q) check ¬p → q check (¬p) → q check ¬(p → q) check p ↔ q check ¬(p ↔ q) check ¬p ↔ q check (¬p) ↔ q check (p → q) ↔ q check p → (q ↔ q)
8c4cbd4a7c17c87d4a212c18ca28de1938cfcef8
958488bc7f3c2044206e0358e56d7690b6ae696c
/lean/hhg/constant.lean
5b366c60238c2256e99c7853685865dcec8d5068
[]
no_license
possientis/Prog
a08eec1c1b121c2fd6c70a8ae89e2fbef952adb4
d4b3debc37610a88e0dac3ac5914903604fd1d1f
refs/heads/master
1,692,263,717,723
1,691,757,179,000
1,691,757,179,000
40,361,602
3
0
null
1,679,896,438,000
1,438,953,859,000
Coq
UTF-8
Lean
false
false
239
lean
constants a b : ℤ constant f : ℤ → ℤ constant g : ℤ → ℤ → ℤ --#check λ x : ℤ, g (f (g a x)) (g x b) --#check λ x, g (f (g a x)) (g x b) constant Trool : Type constants Trool.true Trool.false Trool.maybe : Trool
5f36afa94f449342f415bc0d610380ebb0802284
130c49f47783503e462c16b2eff31933442be6ff
/src/Init/Data/Nat/Basic.lean
eeda5f150d4ab84fd62a76988aa1bd7d98f36658
[ "Apache-2.0" ]
permissive
Hazel-Brown/lean4
8aa5860e282435ffc30dcdfccd34006c59d1d39c
79e6732fc6bbf5af831b76f310f9c488d44e7a16
refs/heads/master
1,689,218,208,951
1,629,736,869,000
1,629,736,896,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,540
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Leonardo de Moura -/ prelude import Init.SimpLemmas universe u namespace Nat @[specialize] def foldAux {α : Type u} (f : Nat → α → α) (s : Nat) : Nat → α → α | 0, a => a | succ n, a => foldAux f s n (f (s - (succ n)) a) @[inline] def fold {α : Type u} (f : Nat → α → α) (n : Nat) (init : α) : α := foldAux f n n init @[inline] def foldRev {α : Type u} (f : Nat → α → α) (n : Nat) (init : α) : α := let rec @[specialize] loop | 0, a => a | succ n, a => loop n (f n a) loop n init @[specialize] def anyAux (f : Nat → Bool) (s : Nat) : Nat → Bool | 0 => false | succ n => f (s - (succ n)) || anyAux f s n /- `any f n = true` iff there is `i in [0, n-1]` s.t. `f i = true` -/ @[inline] def any (f : Nat → Bool) (n : Nat) : Bool := anyAux f n n @[inline] def all (f : Nat → Bool) (n : Nat) : Bool := !any (fun i => !f i) n @[inline] def repeat {α : Type u} (f : α → α) (n : Nat) (a : α) : α := let rec @[specialize] loop | 0, a => a | succ n, a => loop n (f a) loop n a /- Nat.add theorems -/ @[simp] theorem zero_Eq : Nat.zero = 0 := rfl @[simp] protected theorem zero_add : ∀ (n : Nat), 0 + n = n | 0 => rfl | n+1 => congrArg succ (Nat.zero_add n) theorem succ_add : ∀ (n m : Nat), (succ n) + m = succ (n + m) | n, 0 => rfl | n, m+1 => congrArg succ (succ_add n m) theorem add_succ (n m : Nat) : n + succ m = succ (n + m) := rfl theorem add_one (n : Nat) : n + 1 = succ n := rfl theorem succ_eq_add_one (n : Nat) : succ n = n + 1 := rfl protected theorem add_comm : ∀ (n m : Nat), n + m = m + n | n, 0 => Eq.symm (Nat.zero_add n) | n, m+1 => by have : succ (n + m) = succ (m + n) := by apply congrArg; apply Nat.add_comm rw [succ_add m n] apply this protected theorem add_assoc : ∀ (n m k : Nat), (n + m) + k = n + (m + k) | n, m, 0 => rfl | n, m, succ k => congrArg succ (Nat.add_assoc n m k) protected theorem add_left_comm (n m k : Nat) : n + (m + k) = m + (n + k) := by rw [← Nat.add_assoc, Nat.add_comm n m, Nat.add_assoc] protected theorem add_right_comm (n m k : Nat) : (n + m) + k = (n + k) + m := by rw [Nat.add_assoc, Nat.add_comm m k, ← Nat.add_assoc] protected theorem add_left_cancel {n m k : Nat} : n + m = n + k → m = k := by induction n with | zero => simp; intros; assumption | succ n ih => simp [succ_add]; intro h; apply ih h protected theorem add_right_cancel {n m k : Nat} (h : n + m = k + m) : n = k := by rw [Nat.add_comm n m, Nat.add_comm k m] at h apply Nat.add_left_cancel h /- Nat.mul theorems -/ @[simp] protected theorem mul_zero (n : Nat) : n * 0 = 0 := rfl theorem mul_succ (n m : Nat) : n * succ m = n * m + n := rfl @[simp] protected theorem zero_mul : ∀ (n : Nat), 0 * n = 0 | 0 => rfl | succ n => mul_succ 0 n ▸ (Nat.zero_mul n).symm ▸ rfl theorem succ_mul (n m : Nat) : (succ n) * m = (n * m) + m := by induction m with | zero => rfl | succ m ih => rw [mul_succ, add_succ, ih, mul_succ, add_succ, Nat.add_right_comm] protected theorem mul_comm : ∀ (n m : Nat), n * m = m * n | n, 0 => (Nat.zero_mul n).symm ▸ (Nat.mul_zero n).symm ▸ rfl | n, succ m => (mul_succ n m).symm ▸ (succ_mul m n).symm ▸ (Nat.mul_comm n m).symm ▸ rfl @[simp] protected theorem mul_one : ∀ (n : Nat), n * 1 = n := Nat.zero_add @[simp] protected theorem one_mul (n : Nat) : 1 * n = n := Nat.mul_comm n 1 ▸ Nat.mul_one n protected theorem left_distrib (n m k : Nat) : n * (m + k) = n * m + n * k := by induction n generalizing m k with | zero => repeat rw [Nat.zero_mul] | succ n ih => simp [succ_mul, ih]; rw [Nat.add_assoc, Nat.add_assoc (n*m)]; apply congrArg; apply Nat.add_left_comm protected theorem right_distrib (n m k : Nat) : (n + m) * k = n * k + m * k := have h₁ : (n + m) * k = k * (n + m) := Nat.mul_comm .. have h₂ : k * (n + m) = k * n + k * m := Nat.left_distrib .. have h₃ : k * n + k * m = n * k + k * m := Nat.mul_comm n k ▸ rfl have h₄ : n * k + k * m = n * k + m * k := Nat.mul_comm m k ▸ rfl ((h₁.trans h₂).trans h₃).trans h₄ protected theorem mul_assoc : ∀ (n m k : Nat), (n * m) * k = n * (m * k) | n, m, 0 => rfl | n, m, succ k => have h₁ : n * m * succ k = n * m * (k + 1) := rfl have h₂ : n * m * (k + 1) = (n * m * k) + n * m * 1 := Nat.left_distrib .. have h₃ : (n * m * k) + n * m * 1 = (n * m * k) + n * m := by rw [Nat.mul_one (n*m)] have h₄ : (n * m * k) + n * m = (n * (m * k)) + n * m := by rw [Nat.mul_assoc n m k] have h₅ : (n * (m * k)) + n * m = n * (m * k + m) := (Nat.left_distrib n (m*k) m).symm have h₆ : n * (m * k + m) = n * (m * succ k) := Nat.mul_succ m k ▸ rfl ((((h₁.trans h₂).trans h₃).trans h₄).trans h₅).trans h₆ /- Inequalities -/ theorem succ_lt_succ {n m : Nat} : n < m → succ n < succ m := succ_le_succ theorem lt_succ_of_le {n m : Nat} : n ≤ m → n < succ m := succ_le_succ @[simp] protected theorem sub_zero (n : Nat) : n - 0 = n := rfl theorem succ_sub_succ_eq_sub (n m : Nat) : succ n - succ m = n - m := by induction m with | zero => exact rfl | succ m ih => apply congrArg pred ih theorem pred_le : ∀ (n : Nat), pred n ≤ n | zero => Nat.le.refl | succ n => le_succ _ theorem pred_lt : ∀ {n : Nat}, n ≠ 0 → pred n < n | zero, h => absurd rfl h | succ n, h => lt_succ_of_le (Nat.le_refl _) theorem sub_le (n m : Nat) : n - m ≤ n := by induction m with | zero => exact Nat.le_refl (n - 0) | succ m ih => apply Nat.le_trans (pred_le (n - m)) ih theorem sub_lt : ∀ {n m : Nat}, 0 < n → 0 < m → n - m < n | 0, m, h1, h2 => absurd h1 (Nat.lt_irrefl 0) | n+1, 0, h1, h2 => absurd h2 (Nat.lt_irrefl 0) | n+1, m+1, h1, h2 => Eq.symm (succ_sub_succ_eq_sub n m) ▸ show n - m < succ n from lt_succ_of_le (sub_le n m) theorem sub_succ (n m : Nat) : n - succ m = pred (n - m) := rfl theorem succ_sub_succ (n m : Nat) : succ n - succ m = n - m := succ_sub_succ_eq_sub n m protected theorem sub_self : ∀ (n : Nat), n - n = 0 | 0 => by rw [Nat.sub_zero] | (succ n) => by rw [succ_sub_succ, Nat.sub_self n] protected theorem lt_of_lt_of_le {n m k : Nat} : n < m → m ≤ k → n < k := Nat.le_trans protected theorem lt_of_lt_of_eq {n m k : Nat} : n < m → m = k → n < k := fun h₁ h₂ => h₂ ▸ h₁ protected theorem le_of_eq {n m : Nat} (p : n = m) : n ≤ m := p ▸ Nat.le_refl n theorem le_of_succ_le {n m : Nat} (h : succ n ≤ m) : n ≤ m := Nat.le_trans (le_succ n) h protected theorem le_of_lt {n m : Nat} (h : n < m) : n ≤ m := le_of_succ_le h def lt.step {n m : Nat} : n < m → n < succ m := le_step theorem eq_zero_or_pos : ∀ (n : Nat), n = 0 ∨ n > 0 | 0 => Or.inl rfl | n+1 => Or.inr (succ_pos _) def lt.base (n : Nat) : n < succ n := Nat.le_refl (succ n) theorem lt_succ_self (n : Nat) : n < succ n := lt.base n protected theorem le_total (m n : Nat) : m ≤ n ∨ n ≤ m := match Nat.lt_or_ge m n with | Or.inl h => Or.inl (Nat.le_of_lt h) | Or.inr h => Or.inr h protected theorem lt_of_le_and_ne {m n : Nat} (h₁ : m ≤ n) (h₂ : m ≠ n) : m < n := match Nat.eq_or_lt_of_le h₁ with | Or.inl h => absurd h h₂ | Or.inr h => h theorem eq_zero_of_le_zero {n : Nat} (h : n ≤ 0) : n = 0 := Nat.le_antisymm h (zero_le _) theorem lt_of_succ_lt {n m : Nat} : succ n < m → n < m := le_of_succ_le theorem lt_of_succ_lt_succ {n m : Nat} : succ n < succ m → n < m := le_of_succ_le_succ theorem lt_of_succ_le {n m : Nat} (h : succ n ≤ m) : n < m := h theorem succ_le_of_lt {n m : Nat} (h : n < m) : succ n ≤ m := h theorem lt_or_eq_or_le_succ {m n : Nat} (h : m ≤ succ n) : m ≤ n ∨ m = succ n := Decidable.byCases (fun (h' : m = succ n) => Or.inr h') (fun (h' : m ≠ succ n) => have : m < succ n := Nat.lt_of_le_and_ne h h' have : succ m ≤ succ n := succ_le_of_lt this Or.inl (le_of_succ_le_succ this)) theorem le_add_right : ∀ (n k : Nat), n ≤ n + k | n, 0 => Nat.le_refl n | n, k+1 => le_succ_of_le (le_add_right n k) theorem le_add_left (n m : Nat): n ≤ m + n := Nat.add_comm n m ▸ le_add_right n m theorem le.dest : ∀ {n m : Nat}, n ≤ m → Exists (fun k => n + k = m) | zero, zero, h => ⟨0, rfl⟩ | zero, succ n, h => ⟨succ n, Nat.add_comm 0 (succ n) ▸ rfl⟩ | succ n, zero, h => absurd h (not_succ_le_zero _) | succ n, succ m, h => have : n ≤ m := Nat.le_of_succ_le_succ h have : Exists (fun k => n + k = m) := dest this match this with | ⟨k, h⟩ => ⟨k, show succ n + k = succ m from ((succ_add n k).symm ▸ h ▸ rfl)⟩ theorem le.intro {n m k : Nat} (h : n + k = m) : n ≤ m := h ▸ le_add_right n k protected theorem not_le_of_gt {n m : Nat} (h : n > m) : ¬ n ≤ m := fun h₁ => match Nat.lt_or_ge n m with | Or.inl h₂ => absurd (Nat.lt_trans h h₂) (Nat.lt_irrefl _) | Or.inr h₂ => have Heq : n = m := Nat.le_antisymm h₁ h₂ absurd (@Eq.subst _ _ _ _ Heq h) (Nat.lt_irrefl m) theorem gt_of_not_le {n m : Nat} (h : ¬ n ≤ m) : n > m := match Nat.lt_or_ge m n with | Or.inl h₁ => h₁ | Or.inr h₁ => absurd h₁ h protected theorem add_le_add_left {n m : Nat} (h : n ≤ m) (k : Nat) : k + n ≤ k + m := match le.dest h with | ⟨w, hw⟩ => have h₁ : k + n + w = k + (n + w) := Nat.add_assoc .. have h₂ : k + (n + w) = k + m := congrArg _ hw le.intro <| h₁.trans h₂ protected theorem add_le_add_right {n m : Nat} (h : n ≤ m) (k : Nat) : n + k ≤ m + k := by rw [Nat.add_comm n k, Nat.add_comm m k] apply Nat.add_le_add_left assumption protected theorem add_lt_add_left {n m : Nat} (h : n < m) (k : Nat) : k + n < k + m := lt_of_succ_le (add_succ k n ▸ Nat.add_le_add_left (succ_le_of_lt h) k) protected theorem add_lt_add_right {n m : Nat} (h : n < m) (k : Nat) : n + k < m + k := Nat.add_comm k m ▸ Nat.add_comm k n ▸ Nat.add_lt_add_left h k protected theorem zero_lt_one : 0 < (1:Nat) := zero_lt_succ 0 theorem add_le_add {a b c d : Nat} (h₁ : a ≤ b) (h₂ : c ≤ d) : a + c ≤ b + d := Nat.le_trans (Nat.add_le_add_right h₁ c) (Nat.add_le_add_left h₂ b) theorem add_lt_add {a b c d : Nat} (h₁ : a < b) (h₂ : c < d) : a + c < b + d := Nat.lt_trans (Nat.add_lt_add_right h₁ c) (Nat.add_lt_add_left h₂ b) /- Basic theorems for comparing numerals -/ theorem ctor_eq_zero : Nat.zero = 0 := rfl protected theorem one_ne_zero : 1 ≠ (0 : Nat) := fun h => Nat.noConfusion h protected theorem zero_ne_one : 0 ≠ (1 : Nat) := fun h => Nat.noConfusion h theorem succ_ne_zero (n : Nat) : succ n ≠ 0 := fun h => Nat.noConfusion h /- mul + order -/ theorem mul_le_mul_left {n m : Nat} (k : Nat) (h : n ≤ m) : k * n ≤ k * m := match le.dest h with | ⟨l, hl⟩ => have : k * n + k * l = k * m := Nat.left_distrib k n l ▸ hl.symm ▸ rfl le.intro this theorem mul_le_mul_right {n m : Nat} (k : Nat) (h : n ≤ m) : n * k ≤ m * k := Nat.mul_comm k m ▸ Nat.mul_comm k n ▸ mul_le_mul_left k h protected theorem mul_le_mul {n₁ m₁ n₂ m₂ : Nat} (h₁ : n₁ ≤ n₂) (h₂ : m₁ ≤ m₂) : n₁ * m₁ ≤ n₂ * m₂ := Nat.le_trans (mul_le_mul_right _ h₁) (mul_le_mul_left _ h₂) protected theorem mul_lt_mul_of_pos_left {n m k : Nat} (h : n < m) (hk : k > 0) : k * n < k * m := Nat.lt_of_lt_of_le (Nat.add_lt_add_left hk _) (Nat.mul_succ k n ▸ Nat.mul_le_mul_left k (succ_le_of_lt h)) protected theorem mul_lt_mul_of_pos_right {n m k : Nat} (h : n < m) (hk : k > 0) : n * k < m * k := Nat.mul_comm k m ▸ Nat.mul_comm k n ▸ Nat.mul_lt_mul_of_pos_left h hk protected theorem mul_pos {n m : Nat} (ha : n > 0) (hb : m > 0) : n * m > 0 := have h : 0 * m < n * m := Nat.mul_lt_mul_of_pos_right ha hb Nat.zero_mul m ▸ h /- power -/ theorem pow_succ (n m : Nat) : n^(succ m) = n^m * n := rfl theorem pow_zero (n : Nat) : n^0 = 1 := rfl theorem pow_le_pow_of_le_left {n m : Nat} (h : n ≤ m) : ∀ (i : Nat), n^i ≤ m^i | 0 => Nat.le_refl _ | succ i => Nat.mul_le_mul (pow_le_pow_of_le_left h i) h theorem pow_le_pow_of_le_right {n : Nat} (hx : n > 0) {i : Nat} : ∀ {j}, i ≤ j → n^i ≤ n^j | 0, h => have : i = 0 := eq_zero_of_le_zero h this.symm ▸ Nat.le_refl _ | succ j, h => match lt_or_eq_or_le_succ h with | Or.inl h => show n^i ≤ n^j * n from have : n^i * 1 ≤ n^j * n := Nat.mul_le_mul (pow_le_pow_of_le_right hx h) hx Nat.mul_one (n^i) ▸ this | Or.inr h => h.symm ▸ Nat.le_refl _ theorem pos_pow_of_pos {n : Nat} (m : Nat) (h : 0 < n) : 0 < n^m := pow_le_pow_of_le_right h (Nat.zero_le _) /- min/max -/ protected def min (n m : Nat) : Nat := if n ≤ m then n else m protected def max (n m : Nat) : Nat := if n ≤ m then m else n end Nat namespace Prod @[inline] def foldI {α : Type u} (f : Nat → α → α) (i : Nat × Nat) (a : α) : α := Nat.foldAux f i.2 (i.2 - i.1) a @[inline] def anyI (f : Nat → Bool) (i : Nat × Nat) : Bool := Nat.anyAux f i.2 (i.2 - i.1) @[inline] def allI (f : Nat → Bool) (i : Nat × Nat) : Bool := Nat.anyAux (fun a => !f a) i.2 (i.2 - i.1) end Prod
136ec41d46ab8d4bae4b90efbec15208bf3ef11e
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/run/format.lean
d6f61cdbfd8c05da73d401f89df02ec0f4f446ce
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
291
lean
import system.io open list vm_eval pp ([["aaa", "bbb", "ccc", "dddd", "eeeeee", "ffffff"], ["aaa", "bbb", "ccc", "dddd", "eeeeee", "ffffff"], ["aaa", "bbb", "ccc", "dddd", "eeeeee", "ffffff"], ["aaa", "bbb", "ccc", "dddd", "eeeeee", "ffffff"]], [(10:nat), 20, 30])
2c358569fbefea0b8e51f63435ab2d24f9ef25e5
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/tactic/norm_num.lean
39b3a730fb2d06082d6b1c6a1ba2337d9d788cc4
[ "Apache-2.0" ]
permissive
anrddh/mathlib
6a374da53c7e3a35cb0298b0cd67824efef362b4
a4266a01d2dcb10de19369307c986d038c7bb6a6
refs/heads/master
1,656,710,827,909
1,589,560,456,000
1,589,560,456,000
264,271,800
0
0
Apache-2.0
1,589,568,062,000
1,589,568,061,000
null
UTF-8
Lean
false
false
60,988
lean
/- Copyright (c) 2017 Simon Hudon All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Mario Carneiro -/ import data.rat.cast data.rat.meta_defs tactic.doc_commands /-! # `norm_num` Evaluating arithmetic expressions including *, +, -, ^, ≤ -/ universes u v w namespace tactic /-- Reflexivity conversion: given `e` returns `(e, ⊢ e = e)` -/ meta def refl_conv (e : expr) : tactic (expr × expr) := do p ← mk_eq_refl e, return (e, p) /-- Transitivity conversion: given two conversions (which take an expression `e` and returns `(e', ⊢ e = e')`), produces another conversion that combines them with transitivity, treating failures as reflexivity conversions. -/ meta def trans_conv (t₁ t₂ : expr → tactic (expr × expr)) (e : expr) : tactic (expr × expr) := (do (e₁, p₁) ← t₁ e, (do (e₂, p₂) ← t₂ e₁, p ← mk_eq_trans p₁ p₂, return (e₂, p)) <|> return (e₁, p₁)) <|> t₂ e namespace instance_cache /-- Faster version of `mk_app ``bit0 [e]`. -/ meta def mk_bit0 (c : instance_cache) (e : expr) : tactic (instance_cache × expr) := do (c, ai) ← c.get ``has_add, return (c, (expr.const ``bit0 [c.univ]).mk_app [c.α, ai, e]) /-- Faster version of `mk_app ``bit1 [e]`. -/ meta def mk_bit1 (c : instance_cache) (e : expr) : tactic (instance_cache × expr) := do (c, ai) ← c.get ``has_add, (c, oi) ← c.get ``has_one, return (c, (expr.const ``bit1 [c.univ]).mk_app [c.α, oi, ai, e]) end instance_cache end tactic open tactic namespace norm_num variable {α : Type u} lemma subst_into_neg {α} [has_neg α] (a ta t : α) (pra : a = ta) (prt : -ta = t) : -a = t := by simp [pra, prt] /-- The result type of `match_numeral`, either `0`, `1`, or a top level decomposition of `bit0 e` or `bit1 e`. The `other` case means it is not a numeral. -/ meta inductive match_numeral_result | zero | one | bit0 (e : expr) | bit1 (e : expr) | other /-- Unfold the top level constructor of the numeral expression. -/ meta def match_numeral : expr → match_numeral_result | `(bit0 %%e) := match_numeral_result.bit0 e | `(bit1 %%e) := match_numeral_result.bit1 e | `(@has_zero.zero _ _) := match_numeral_result.zero | `(@has_one.one _ _) := match_numeral_result.one | _ := match_numeral_result.other theorem zero_succ {α} [semiring α] : (0 + 1 : α) = 1 := zero_add _ theorem one_succ {α} [semiring α] : (1 + 1 : α) = 2 := rfl theorem bit0_succ {α} [semiring α] (a : α) : bit0 a + 1 = bit1 a := rfl theorem bit1_succ {α} [semiring α] (a b : α) (h : a + 1 = b) : bit1 a + 1 = bit0 b := h ▸ by simp [bit1, bit0, add_left_comm] section open match_numeral_result /-- Given `a`, `b` natural numerals, proves `⊢ a + 1 = b`, assuming that this is provable. (It may prove garbage instead of failing if `a + 1 = b` is false.) -/ meta def prove_succ : instance_cache → expr → expr → tactic (instance_cache × expr) | c e r := match match_numeral e with | zero := c.mk_app ``zero_succ [] | one := c.mk_app ``one_succ [] | bit0 e := c.mk_app ``bit0_succ [e] | bit1 e := do let r := r.app_arg, (c, p) ← prove_succ c e r, c.mk_app ``bit1_succ [e, r, p] | _ := failed end end theorem zero_adc {α} [semiring α] (a b : α) (h : a + 1 = b) : 0 + a + 1 = b := by rwa zero_add theorem adc_zero {α} [semiring α] (a b : α) (h : a + 1 = b) : a + 0 + 1 = b := by rwa add_zero theorem one_add {α} [semiring α] (a b : α) (h : a + 1 = b) : 1 + a = b := by rwa add_comm theorem add_bit0_bit0 {α} [semiring α] (a b c : α) (h : a + b = c) : bit0 a + bit0 b = bit0 c := h ▸ by simp [bit0, add_left_comm] theorem add_bit0_bit1 {α} [semiring α] (a b c : α) (h : a + b = c) : bit0 a + bit1 b = bit1 c := h ▸ by simp [bit0, bit1, add_left_comm] theorem add_bit1_bit0 {α} [semiring α] (a b c : α) (h : a + b = c) : bit1 a + bit0 b = bit1 c := h ▸ by simp [bit0, bit1, add_left_comm, add_comm] theorem add_bit1_bit1 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) : bit1 a + bit1 b = bit0 c := h ▸ by simp [bit0, bit1, add_left_comm, add_comm] theorem adc_one_one {α} [semiring α] : (1 + 1 + 1 : α) = 3 := rfl theorem adc_bit0_one {α} [semiring α] (a b : α) (h : a + 1 = b) : bit0 a + 1 + 1 = bit0 b := h ▸ by simp [bit0, add_left_comm] theorem adc_one_bit0 {α} [semiring α] (a b : α) (h : a + 1 = b) : 1 + bit0 a + 1 = bit0 b := h ▸ by simp [bit0, add_left_comm] theorem adc_bit1_one {α} [semiring α] (a b : α) (h : a + 1 = b) : bit1 a + 1 + 1 = bit1 b := h ▸ by simp [bit1, bit0, add_left_comm] theorem adc_one_bit1 {α} [semiring α] (a b : α) (h : a + 1 = b) : 1 + bit1 a + 1 = bit1 b := h ▸ by simp [bit1, bit0, add_left_comm] theorem adc_bit0_bit0 {α} [semiring α] (a b c : α) (h : a + b = c) : bit0 a + bit0 b + 1 = bit1 c := h ▸ by simp [bit1, bit0, add_left_comm] theorem adc_bit1_bit0 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) : bit1 a + bit0 b + 1 = bit0 c := h ▸ by simp [bit1, bit0, add_left_comm] theorem adc_bit0_bit1 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) : bit0 a + bit1 b + 1 = bit0 c := h ▸ by simp [bit1, bit0, add_left_comm] theorem adc_bit1_bit1 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) : bit1 a + bit1 b + 1 = bit1 c := h ▸ by simp [bit1, bit0, add_left_comm] section open match_numeral_result meta mutual def prove_add_nat, prove_adc_nat with prove_add_nat : instance_cache → expr → expr → expr → tactic (instance_cache × expr) | c a b r := do match match_numeral a, match_numeral b with | zero, _ := c.mk_app ``zero_add [b] | _, zero := c.mk_app ``add_zero [a] | _, one := prove_succ c a r | one, _ := do (c, p) ← prove_succ c b r, c.mk_app ``one_add [b, r, p] | bit0 a, bit0 b := do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``add_bit0_bit0 [a, b, r, p] | bit0 a, bit1 b := do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``add_bit0_bit1 [a, b, r, p] | bit1 a, bit0 b := do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``add_bit1_bit0 [a, b, r, p] | bit1 a, bit1 b := do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``add_bit1_bit1 [a, b, r, p] | _, _ := failed end with prove_adc_nat : instance_cache → expr → expr → expr → tactic (instance_cache × expr) | c a b r := do match match_numeral a, match_numeral b with | zero, _ := do (c, p) ← prove_succ c b r, c.mk_app ``zero_adc [b, r, p] | _, zero := do (c, p) ← prove_succ c b r, c.mk_app ``adc_zero [b, r, p] | one, one := c.mk_app ``adc_one_one [] | bit0 a, one := do let r := r.app_arg, (c, p) ← prove_succ c a r, c.mk_app ``adc_bit0_one [a, r, p] | one, bit0 b := do let r := r.app_arg, (c, p) ← prove_succ c b r, c.mk_app ``adc_one_bit0 [b, r, p] | bit1 a, one := do let r := r.app_arg, (c, p) ← prove_succ c a r, c.mk_app ``adc_bit1_one [a, r, p] | one, bit1 b := do let r := r.app_arg, (c, p) ← prove_succ c b r, c.mk_app ``adc_one_bit1 [b, r, p] | bit0 a, bit0 b := do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``adc_bit0_bit0 [a, b, r, p] | bit0 a, bit1 b := do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``adc_bit0_bit1 [a, b, r, p] | bit1 a, bit0 b := do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``adc_bit1_bit0 [a, b, r, p] | bit1 a, bit1 b := do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``adc_bit1_bit1 [a, b, r, p] | _, _ := failed end /-- Given `a`,`b`,`r` natural numerals, proves `⊢ a + b = r`. -/ add_decl_doc prove_add_nat /-- Given `a`,`b`,`r` natural numerals, proves `⊢ a + b + 1 = r`. -/ add_decl_doc prove_adc_nat /-- Given `a`,`b` natural numerals, returns `(r, ⊢ a + b = r)`. -/ meta def prove_add_nat' (c : instance_cache) (a b : expr) : tactic (instance_cache × expr × expr) := do na ← a.to_nat, nb ← b.to_nat, (c, r) ← c.of_nat (na + nb), (c, p) ← prove_add_nat c a b r, return (c, r, p) end theorem bit0_mul {α} [semiring α] (a b c : α) (h : a * b = c) : bit0 a * b = bit0 c := h ▸ by simp [bit0, add_mul] theorem mul_bit0' {α} [semiring α] (a b c : α) (h : a * b = c) : a * bit0 b = bit0 c := h ▸ by simp [bit0, mul_add] theorem mul_bit0_bit0 {α} [semiring α] (a b c : α) (h : a * b = c) : bit0 a * bit0 b = bit0 (bit0 c) := bit0_mul _ _ _ (mul_bit0' _ _ _ h) theorem mul_bit1_bit1 {α} [semiring α] (a b c d e : α) (hc : a * b = c) (hd : a + b = d) (he : bit0 c + d = e) : bit1 a * bit1 b = bit1 e := by rw [← he, ← hd, ← hc]; simp [bit1, bit0, mul_add, add_mul, add_left_comm] section open match_numeral_result /-- Given `a`,`b` natural numerals, returns `(r, ⊢ a * b = r)`. -/ meta def prove_mul_nat : instance_cache → expr → expr → tactic (instance_cache × expr × expr) | ic a b := match match_numeral a, match_numeral b with | zero, _ := do (ic, z) ← ic.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``zero_mul [b], return (ic, z, p) | _, zero := do (ic, z) ← ic.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``mul_zero [a], return (ic, z, p) | one, _ := do (ic, p) ← ic.mk_app ``one_mul [b], return (ic, b, p) | _, one := do (ic, p) ← ic.mk_app ``mul_one [a], return (ic, a, p) | bit0 a, bit0 b := do (ic, c, p) ← prove_mul_nat ic a b, (ic, p) ← ic.mk_app ``mul_bit0_bit0 [a, b, c, p], (ic, c') ← ic.mk_bit0 c, (ic, c') ← ic.mk_bit0 c', return (ic, c', p) | bit0 a, _ := do (ic, c, p) ← prove_mul_nat ic a b, (ic, p) ← ic.mk_app ``bit0_mul [a, b, c, p], (ic, c') ← ic.mk_bit0 c, return (ic, c', p) | _, bit0 b := do (ic, c, p) ← prove_mul_nat ic a b, (ic, p) ← ic.mk_app ``mul_bit0' [a, b, c, p], (ic, c') ← ic.mk_bit0 c, return (ic, c', p) | bit1 a, bit1 b := do (ic, c, pc) ← prove_mul_nat ic a b, (ic, d, pd) ← prove_add_nat' ic a b, (ic, c') ← ic.mk_bit0 c, (ic, e, pe) ← prove_add_nat' ic c' d, (ic, p) ← ic.mk_app ``mul_bit1_bit1 [a, b, c, d, e, pc, pd, pe], (ic, e') ← ic.mk_bit1 e, return (ic, e', p) | _, _ := failed end end section open match_numeral_result /-- Given `a` a positive natural numeral, returns `⊢ 0 < a`. -/ meta def prove_pos_nat (c : instance_cache) : expr → tactic (instance_cache × expr) | e := match match_numeral e with | one := c.mk_app ``zero_lt_one [] | bit0 e := do (c, p) ← prove_pos_nat e, c.mk_app ``bit0_pos [e, p] | bit1 e := do (c, p) ← prove_pos_nat e, c.mk_app ``bit1_pos' [e, p] | _ := failed end end /-- Given `a` a rational numeral, returns `⊢ 0 < a`. -/ meta def prove_pos (c : instance_cache) : expr → tactic (instance_cache × expr) | `(%%e₁ / %%e₂) := do (c, p₁) ← prove_pos_nat c e₁, (c, p₂) ← prove_pos_nat c e₂, c.mk_app ``div_pos_of_pos_of_pos [e₁, e₂, p₁, p₂] | e := prove_pos_nat c e /-- `match_neg (- e) = some e`, otherwise `none` -/ meta def match_neg : expr → option expr | `(- %%e) := some e | _ := none /-- `match_sign (- e) = inl e`, `match_sign 0 = inr ff`, otherwise `inr tt` -/ meta def match_sign : expr → expr ⊕ bool | `(- %%e) := sum.inl e | `(has_zero.zero) := sum.inr ff | _ := sum.inr tt theorem ne_zero_of_pos {α} [ordered_add_comm_group α] (a : α) : 0 < a → a ≠ 0 := ne_of_gt theorem ne_zero_neg {α} [add_group α] (a : α) : a ≠ 0 → -a ≠ 0 := mt neg_eq_zero.1 /-- Given `a` a rational numeral, returns `⊢ a ≠ 0`. -/ meta def prove_ne_zero (c : instance_cache) : expr → tactic (instance_cache × expr) | a := match match_neg a with | some a := do (c, p) ← prove_ne_zero a, c.mk_app ``ne_zero_neg [a, p] | none := do (c, p) ← prove_pos c a, c.mk_app ``ne_zero_of_pos [a, p] end theorem clear_denom_div {α} [division_ring α] (a b b' c d : α) (h₀ : b ≠ 0) (h₁ : b * b' = d) (h₂ : a * b' = c) : (a / b) * d = c := by rwa [← h₁, ← mul_assoc, div_mul_cancel _ h₀] /-- Given `a` nonnegative rational and `d` a natural number, returns `(b, ⊢ a * d = b)`. (`d` should be a multiple of the denominator of `a`, so that `b` is a natural number.) -/ meta def prove_clear_denom (c : instance_cache) (a d : expr) (na : ℚ) (nd : ℕ) : tactic (instance_cache × expr × expr) := if na.denom = 1 then prove_mul_nat c a d else do [_, _, a, b] ← return a.get_app_args, (c, b') ← c.of_nat (nd / na.denom), (c, p₀) ← prove_ne_zero c b, (c, _, p₁) ← prove_mul_nat c b b', (c, r, p₂) ← prove_mul_nat c a b', (c, p) ← c.mk_app ``clear_denom_div [a, b, b', r, d, p₀, p₁, p₂], return (c, r, p) theorem clear_denom_add {α} [division_ring α] (a a' b b' c c' d : α) (h₀ : d ≠ 0) (ha : a * d = a') (hb : b * d = b') (hc : c * d = c') (h : a' + b' = c') : a + b = c := mul_right_cancel' h₀ $ by rwa [add_mul, ha, hb, hc] /-- Given `a`,`b`,`c` nonnegative rational numerals, returns `⊢ a + b = c`. -/ meta def prove_add_nonneg_rat (ic : instance_cache) (a b c : expr) (na nb nc : ℚ) : tactic (instance_cache × expr) := if na.denom = 1 ∧ nb.denom = 1 then prove_add_nat ic a b c else do let nd := na.denom.lcm nb.denom, (ic, d) ← ic.of_nat nd, (ic, p₀) ← prove_ne_zero ic d, (ic, a', pa) ← prove_clear_denom ic a d na nd, (ic, b', pb) ← prove_clear_denom ic b d nb nd, (ic, c', pc) ← prove_clear_denom ic c d nc nd, (ic, p) ← prove_add_nat ic a' b' c', ic.mk_app ``clear_denom_add [a, a', b, b', c, c', d, p₀, pa, pb, pc, p] theorem add_pos_neg_pos {α} [add_group α] (a b c : α) (h : c + b = a) : a + -b = c := h ▸ by simp theorem add_pos_neg_neg {α} [add_group α] (a b c : α) (h : c + a = b) : a + -b = -c := h ▸ by simp theorem add_neg_pos_pos {α} [add_group α] (a b c : α) (h : a + c = b) : -a + b = c := h ▸ by simp theorem add_neg_pos_neg {α} [add_group α] (a b c : α) (h : b + c = a) : -a + b = -c := h ▸ by simp theorem add_neg_neg {α} [add_group α] (a b c : α) (h : b + a = c) : -a + -b = -c := h ▸ by simp /-- Given `a`,`b`,`c` rational numerals, returns `⊢ a + b = c`. -/ meta def prove_add_rat (ic : instance_cache) (ea eb ec : expr) (a b c : ℚ) : tactic (instance_cache × expr) := match match_neg ea, match_neg eb, match_neg ec with | some ea, some eb, some ec := do (ic, p) ← prove_add_nonneg_rat ic eb ea ec (-b) (-a) (-c), ic.mk_app ``add_neg_neg [ea, eb, ec, p] | some ea, none, some ec := do (ic, p) ← prove_add_nonneg_rat ic eb ec ea b (-c) (-a), ic.mk_app ``add_neg_pos_neg [ea, eb, ec, p] | some ea, none, none := do (ic, p) ← prove_add_nonneg_rat ic ea ec eb (-a) c b, ic.mk_app ``add_neg_pos_pos [ea, eb, ec, p] | none, some eb, some ec := do (ic, p) ← prove_add_nonneg_rat ic ec ea eb (-c) a (-b), ic.mk_app ``add_pos_neg_neg [ea, eb, ec, p] | none, some eb, none := do (ic, p) ← prove_add_nonneg_rat ic ec eb ea c (-b) a, ic.mk_app ``add_pos_neg_pos [ea, eb, ec, p] | _, _, _ := prove_add_nonneg_rat ic ea eb ec a b c end /-- Given `a`,`b` rational numerals, returns `(c, ⊢ a + b = c)`. -/ meta def prove_add_rat' (ic : instance_cache) (a b : expr) : tactic (instance_cache × expr × expr) := do na ← a.to_rat, nb ← b.to_rat, let nc := na + nb, (ic, c) ← ic.of_rat nc, (ic, p) ← prove_add_rat ic a b c na nb nc, return (ic, c, p) theorem clear_denom_simple_nat {α} [division_ring α] (a : α) : (1:α) ≠ 0 ∧ a * 1 = a := ⟨one_ne_zero, mul_one _⟩ theorem clear_denom_simple_div {α} [division_ring α] (a b : α) (h : b ≠ 0) : b ≠ 0 ∧ a / b * b = a := ⟨h, div_mul_cancel _ h⟩ /-- Given `a` a nonnegative rational numeral, returns `(b, c, ⊢ a * b = c)` where `b` and `c` are natural numerals. (`b` will be the denominator of `a`.) -/ meta def prove_clear_denom_simple (c : instance_cache) (a : expr) (na : ℚ) : tactic (instance_cache × expr × expr × expr) := if na.denom = 1 then do (c, d) ← c.mk_app ``has_one.one [], (c, p) ← c.mk_app ``clear_denom_simple_nat [a], return (c, d, a, p) else do [α, _, a, b] ← return a.get_app_args, (c, p₀) ← prove_ne_zero c b, (c, p) ← c.mk_app ``clear_denom_simple_div [a, b, p₀], return (c, b, a, p) theorem clear_denom_mul {α} [field α] (a a' b b' c c' d₁ d₂ d : α) (ha : d₁ ≠ 0 ∧ a * d₁ = a') (hb : d₂ ≠ 0 ∧ b * d₂ = b') (hc : c * d = c') (hd : d₁ * d₂ = d) (h : a' * b' = c') : a * b = c := mul_right_cancel' ha.1 $ mul_right_cancel' hb.1 $ by rw [mul_assoc c, hd, hc, ← h, ← ha.2, ← hb.2, ← mul_assoc, mul_right_comm a] /-- Given `a`,`b` nonnegative rational numerals, returns `(c, ⊢ a * b = c)`. -/ meta def prove_mul_nonneg_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr × expr) := if na.denom = 1 ∧ nb.denom = 1 then prove_mul_nat ic a b else do let nc := na * nb, (ic, c) ← ic.of_rat nc, (ic, d₁, a', pa) ← prove_clear_denom_simple ic a na, (ic, d₂, b', pb) ← prove_clear_denom_simple ic b nb, (ic, d, pd) ← prove_mul_nat ic d₁ d₂, nd ← d.to_nat, (ic, c', pc) ← prove_clear_denom ic c d nc nd, (ic, _, p) ← prove_mul_nat ic a' b', (ic, p) ← ic.mk_app ``clear_denom_mul [a, a', b, b', c, c', d₁, d₂, d, pa, pb, pc, pd, p], return (ic, c, p) theorem mul_neg_pos {α} [ring α] (a b c : α) (h : a * b = c) : -a * b = -c := h ▸ by simp theorem mul_pos_neg {α} [ring α] (a b c : α) (h : a * b = c) : a * -b = -c := h ▸ by simp theorem mul_neg_neg {α} [ring α] (a b c : α) (h : a * b = c) : -a * -b = c := h ▸ by simp /-- Given `a`,`b` rational numerals, returns `(c, ⊢ a * b = c)`. -/ meta def prove_mul_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr × expr) := match match_sign a, match_sign b with | sum.inl a, sum.inl b := do (ic, c, p) ← prove_mul_nonneg_rat ic a b (-na) (-nb), (ic, p) ← ic.mk_app ``mul_neg_neg [a, b, c, p], return (ic, c, p) | sum.inr ff, _ := do (ic, z) ← ic.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``zero_mul [b], return (ic, z, p) | _, sum.inr ff := do (ic, z) ← ic.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``mul_zero [a], return (ic, z, p) | sum.inl a, sum.inr tt := do (ic, c, p) ← prove_mul_nonneg_rat ic a b (-na) nb, (ic, p) ← ic.mk_app ``mul_neg_pos [a, b, c, p], (ic, c') ← ic.mk_app ``has_neg.neg [c], return (ic, c', p) | sum.inr tt, sum.inl b := do (ic, c, p) ← prove_mul_nonneg_rat ic a b na (-nb), (ic, p) ← ic.mk_app ``mul_pos_neg [a, b, c, p], (ic, c') ← ic.mk_app ``has_neg.neg [c], return (ic, c', p) | sum.inr tt, sum.inr tt := prove_mul_nonneg_rat ic a b na nb end theorem inv_neg {α} [division_ring α] (a b : α) (h : a⁻¹ = b) : (-a)⁻¹ = -b := h ▸ by simp only [inv_eq_one_div, one_div_neg_eq_neg_one_div] theorem inv_one {α} [division_ring α] : (1 : α)⁻¹ = 1 := one_inv_eq theorem inv_one_div {α} [division_ring α] (a : α) : (1 / a)⁻¹ = a := by rw [one_div_eq_inv, inv_inv'] theorem inv_div_one {α} [division_ring α] (a : α) : a⁻¹ = 1 / a := inv_eq_one_div _ theorem inv_div {α} [division_ring α] (a b : α) : (a / b)⁻¹ = b / a := by simp only [inv_eq_one_div, one_div_div] /-- Given `a` a rational numeral, returns `(b, ⊢ a⁻¹ = b)`. -/ meta def prove_inv : instance_cache → expr → ℚ → tactic (instance_cache × expr × expr) | ic e n := match match_sign e with | sum.inl e := do (ic, e', p) ← prove_inv ic e (-n), (ic, r) ← ic.mk_app ``has_neg.neg [e'], (ic, p) ← ic.mk_app ``inv_neg [e, e', p], return (ic, r, p) | sum.inr ff := do (ic, p) ← ic.mk_app ``inv_zero [], return (ic, e, p) | sum.inr tt := if n.num = 1 then if n.denom = 1 then do (ic, p) ← ic.mk_app ``one_inv_eq [], return (ic, e, p) else do let e := e.app_arg, (ic, p) ← ic.mk_app ``inv_one_div [e], return (ic, e, p) else if n.denom = 1 then do (ic, p) ← ic.mk_app ``inv_div_one [e], e ← infer_type p, return (ic, e.app_arg, p) else do [_, _, a, b] ← return e.get_app_args, (ic, e') ← ic.mk_app ``has_div.div [b, a], (ic, p) ← ic.mk_app ``inv_div [a, b], return (ic, e', p) end theorem div_eq {α} [division_ring α] (a b b' c : α) (hb : b⁻¹ = b') (h : a * b' = c) : a / b = c := by rwa ← hb at h /-- Given `a`,`b` rational numerals, returns `(c, ⊢ a / b = c)`. -/ meta def prove_div (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr × expr) := do (ic, b', pb) ← prove_inv ic b nb, (ic, c, p) ← prove_mul_rat ic a b' na nb⁻¹, (ic, p) ← ic.mk_app ``div_eq [a, b, b', c, pb, p], return (ic, c, p) /-- Given `a` a rational numeral, returns `(b, ⊢ -a = b)`. -/ meta def prove_neg (ic : instance_cache) (a : expr) : tactic (instance_cache × expr × expr) := match match_sign a with | sum.inl a := do (ic, p) ← ic.mk_app ``neg_neg [a], return (ic, a, p) | sum.inr ff := do (ic, p) ← ic.mk_app ``neg_zero [], return (ic, a, p) | sum.inr tt := do (ic, a') ← ic.mk_app ``has_neg.neg [a], p ← mk_eq_refl a', return (ic, a', p) end theorem sub_pos {α} [add_group α] (a b b' c : α) (hb : -b = b') (h : a + b' = c) : a - b = c := by rwa ← hb at h theorem sub_neg {α} [add_group α] (a b c : α) (h : a + b = c) : a - -b = c := by rwa sub_neg_eq_add /-- Given `a`,`b` rational numerals, returns `(c, ⊢ a - b = c)`. -/ meta def prove_sub (ic : instance_cache) (a b : expr) : tactic (instance_cache × expr × expr) := match match_sign b with | sum.inl b := do (ic, c, p) ← prove_add_rat' ic a b, (ic, p) ← ic.mk_app ``sub_neg [a, b, c, p], return (ic, c, p) | sum.inr ff := do (ic, p) ← ic.mk_app ``sub_zero [a], return (ic, a, p) | sum.inr tt := do (ic, b', pb) ← prove_neg ic b, (ic, c, p) ← prove_add_rat' ic a b', (ic, p) ← ic.mk_app ``sub_pos [a, b, b', c, pb, p], return (ic, c, p) end theorem sub_nat_pos (a b c : ℕ) (h : b + c = a) : a - b = c := h ▸ nat.add_sub_cancel_left _ _ theorem sub_nat_neg (a b c : ℕ) (h : a + c = b) : a - b = 0 := nat.sub_eq_zero_of_le $ h ▸ nat.le_add_right _ _ /-- Given `a : nat`,`b : nat` natural numerals, returns `(c, ⊢ a - b = c)`. -/ meta def prove_sub_nat (ic : instance_cache) (a b : expr) : tactic (expr × expr) := do na ← a.to_nat, nb ← b.to_nat, if nb ≤ na then do (ic, c) ← ic.of_nat (na - nb), (ic, p) ← prove_add_nat ic b c a, return (c, `(sub_nat_pos).mk_app [a, b, c, p]) else do (ic, c) ← ic.of_nat (nb - na), (ic, p) ← prove_add_nat ic a c b, return (`(0 : ℕ), `(sub_nat_neg).mk_app [a, b, c, p]) /-- Evaluates the basic field operations `+`,`neg`,`-`,`*`,`inv`,`/` on numerals. Also handles nat subtraction. Does not do recursive simplification; that is, `1 + 1 + 1` will not simplify but `2 + 1` will. This is handled by the top level `simp` call in `norm_num.derive`. -/ meta def eval_field : expr → tactic (expr × expr) | `(%%e₁ + %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, let n₃ := n₁ + n₂, (c, e₃) ← c.of_rat n₃, (_, p) ← prove_add_rat c e₁ e₂ e₃ n₁ n₂ n₃, return (e₃, p) | `(%%e₁ * %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, prod.snd <$> prove_mul_rat c e₁ e₂ n₁ n₂ | `(- %%e) := do c ← infer_type e >>= mk_instance_cache, prod.snd <$> prove_neg c e | `(%%a - %%b) := do α ← infer_type a, c ← mk_instance_cache α, if α = `(nat) then prove_sub_nat c a b else prod.snd <$> prove_sub c a b | `(has_inv.inv %%e) := do n ← e.to_rat, c ← infer_type e >>= mk_instance_cache, prod.snd <$> prove_inv c e n | `(%%e₁ / %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, prod.snd <$> prove_div c e₁ e₂ n₁ n₂ | _ := failed lemma pow_bit0 [monoid α] (a c' c : α) (b : ℕ) (h : a ^ b = c') (h₂ : c' * c' = c) : a ^ bit0 b = c := h₂ ▸ by simp [pow_bit0, h] lemma pow_bit1 [monoid α] (a c₁ c₂ c : α) (b : ℕ) (h : a ^ b = c₁) (h₂ : c₁ * c₁ = c₂) (h₃ : c₂ * a = c) : a ^ bit1 b = c := by rw [← h₃, ← h₂]; simp [pow_bit1, h] section open match_numeral_result /-- Given `a` a rational numeral and `b : nat`, returns `(c, ⊢ a ^ b = c)`. -/ meta def prove_pow (a : expr) (na : ℚ) : instance_cache → expr → tactic (instance_cache × expr × expr) | ic b := match match_numeral b with | zero := do (ic, p) ← ic.mk_app ``pow_zero [a], (ic, o) ← ic.mk_app ``has_one.one [], return (ic, o, p) | one := do (ic, p) ← ic.mk_app ``pow_one [a], return (ic, a, p) | bit0 b := do (ic, c', p) ← prove_pow ic b, nc' ← expr.to_rat c', (ic, c, p₂) ← prove_mul_rat ic c' c' nc' nc', (ic, p) ← ic.mk_app ``pow_bit0 [a, c', c, b, p, p₂], return (ic, c, p) | bit1 b := do (ic, c₁, p) ← prove_pow ic b, nc₁ ← expr.to_rat c₁, (ic, c₂, p₂) ← prove_mul_rat ic c₁ c₁ nc₁ nc₁, (ic, c, p₃) ← prove_mul_rat ic c₂ a (nc₁ * nc₁) na, (ic, p) ← ic.mk_app ``pow_bit1 [a, c₁, c₂, c, b, p, p₂, p₃], return (ic, c, p) | _ := failed end end lemma from_nat_pow (a b c : ℕ) (h : @has_pow.pow _ _ monoid.has_pow a b = c) : a ^ b = c := (nat.pow_eq_pow _ _).symm.trans h /-- Evaluates expressions of the form `a ^ b`, `monoid.pow a b` or `nat.pow a b`. -/ meta def eval_pow : expr → tactic (expr × expr) | `(@has_pow.pow %%α _ %%m %%e₁ %%e₂) := do n₁ ← e₁.to_rat, c ← infer_type e₁ >>= mk_instance_cache, match m with | `(@monoid.has_pow %%_ %%_) := prod.snd <$> prove_pow e₁ n₁ c e₂ | `(nat.has_pow) := do (_, c, p) ← prove_pow e₁ n₁ c e₂, return (c, `(from_nat_pow).mk_app [e₁, e₂, c, p]) | _ := failed end | `(monoid.pow %%e₁ %%e₂) := do n₁ ← e₁.to_rat, c ← infer_type e₁ >>= mk_instance_cache, prod.snd <$> prove_pow e₁ n₁ c e₂ | `(nat.pow %%e₁ %%e₂) := do n₁ ← e₁.to_rat, c ← mk_instance_cache `(ℕ), (_, c, p) ← prove_pow e₁ n₁ c e₂, return (c, `(from_nat_pow).mk_app [e₁, e₂, c, p]) | _ := failed theorem nonneg_pos {α} [ordered_cancel_add_comm_monoid α] (a : α) : 0 < a → 0 ≤ a := le_of_lt theorem lt_one_bit0 {α} [linear_ordered_semiring α] (a : α) (h : 1 ≤ a) : 1 < bit0 a := lt_of_lt_of_le one_lt_two (bit0_le_bit0.2 h) theorem lt_one_bit1 {α} [linear_ordered_semiring α] (a : α) (h : 0 < a) : 1 < bit1 a := one_lt_bit1.2 h theorem lt_bit0_bit0 {α} [linear_ordered_semiring α] (a b : α) : a < b → bit0 a < bit0 b := bit0_lt_bit0.2 theorem lt_bit0_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a ≤ b) : bit0 a < bit1 b := lt_of_le_of_lt (bit0_le_bit0.2 h) (lt_add_one _) theorem lt_bit1_bit0 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) : bit1 a < bit0 b := lt_of_lt_of_le (by simp [bit0, bit1, zero_lt_one]) (bit0_le_bit0.2 h) theorem lt_bit1_bit1 {α} [linear_ordered_semiring α] (a b : α) : a < b → bit1 a < bit1 b := bit1_lt_bit1.2 theorem le_one_bit0 {α} [linear_ordered_semiring α] (a : α) (h : 1 ≤ a) : 1 ≤ bit0 a := le_of_lt (lt_one_bit0 _ h) -- deliberately strong hypothesis because bit1 0 is not a numeral theorem le_one_bit1 {α} [linear_ordered_semiring α] (a : α) (h : 0 < a) : 1 ≤ bit1 a := le_of_lt (lt_one_bit1 _ h) theorem le_bit0_bit0 {α} [linear_ordered_semiring α] (a b : α) : a ≤ b → bit0 a ≤ bit0 b := bit0_le_bit0.2 theorem le_bit0_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a ≤ b) : bit0 a ≤ bit1 b := le_of_lt (lt_bit0_bit1 _ _ h) theorem le_bit1_bit0 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) : bit1 a ≤ bit0 b := le_of_lt (lt_bit1_bit0 _ _ h) theorem le_bit1_bit1 {α} [linear_ordered_semiring α] (a b : α) : a ≤ b → bit1 a ≤ bit1 b := bit1_le_bit1.2 theorem sle_one_bit0 {α} [linear_ordered_semiring α] (a : α) : 1 ≤ a → 1 + 1 ≤ bit0 a := bit0_le_bit0.2 theorem sle_one_bit1 {α} [linear_ordered_semiring α] (a : α) : 1 ≤ a → 1 + 1 ≤ bit1 a := le_bit0_bit1 _ _ theorem sle_bit0_bit0 {α} [linear_ordered_semiring α] (a b : α) : a + 1 ≤ b → bit0 a + 1 ≤ bit0 b := le_bit1_bit0 _ _ theorem sle_bit0_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a ≤ b) : bit0 a + 1 ≤ bit1 b := bit1_le_bit1.2 h theorem sle_bit1_bit0 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) : bit1 a + 1 ≤ bit0 b := (bit1_succ a _ rfl).symm ▸ bit0_le_bit0.2 h theorem sle_bit1_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) : bit1 a + 1 ≤ bit1 b := (bit1_succ a _ rfl).symm ▸ le_bit0_bit1 _ _ h /-- Given `a` a rational numeral, returns `⊢ 0 ≤ a`. -/ meta def prove_nonneg (ic : instance_cache) : expr → tactic (instance_cache × expr) | e@`(has_zero.zero) := ic.mk_app ``le_refl [e] | e := if ic.α = `(ℕ) then return (ic, `(nat.zero_le).mk_app [e]) else do (ic, p) ← prove_pos ic e, ic.mk_app ``nonneg_pos [e, p] section open match_numeral_result /-- Given `a` a rational numeral, returns `⊢ 1 ≤ a`. -/ meta def prove_one_le_nat (ic : instance_cache) : expr → tactic (instance_cache × expr) | a := match match_numeral a with | one := ic.mk_app ``le_refl [a] | bit0 a := do (ic, p) ← prove_one_le_nat a, ic.mk_app ``le_one_bit0 [a, p] | bit1 a := do (ic, p) ← prove_pos_nat ic a, ic.mk_app ``le_one_bit1 [a, p] | _ := failed end meta mutual def prove_le_nat, prove_sle_nat (ic : instance_cache) with prove_le_nat : expr → expr → tactic (instance_cache × expr) | a b := if a = b then ic.mk_app ``le_refl [a] else match match_numeral a, match_numeral b with | zero, _ := prove_nonneg ic b | one, bit0 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``le_one_bit0 [b, p] | one, bit1 b := do (ic, p) ← prove_pos_nat ic b, ic.mk_app ``le_one_bit1 [b, p] | bit0 a, bit0 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``le_bit0_bit0 [a, b, p] | bit0 a, bit1 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``le_bit0_bit1 [a, b, p] | bit1 a, bit0 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``le_bit1_bit0 [a, b, p] | bit1 a, bit1 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``le_bit1_bit1 [a, b, p] | _, _ := failed end with prove_sle_nat : expr → expr → tactic (instance_cache × expr) | a b := match match_numeral a, match_numeral b with | zero, _ := prove_nonneg ic b | one, bit0 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``sle_one_bit0 [b, p] | one, bit1 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``sle_one_bit1 [b, p] | bit0 a, bit0 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``sle_bit0_bit0 [a, b, p] | bit0 a, bit1 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``sle_bit0_bit1 [a, b, p] | bit1 a, bit0 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``sle_bit1_bit0 [a, b, p] | bit1 a, bit1 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``sle_bit1_bit1 [a, b, p] | _, _ := failed end /-- Given `a`,`b` natural numerals, proves `⊢ a ≤ b`. -/ add_decl_doc prove_le_nat /-- Given `a`,`b` natural numerals, proves `⊢ a + 1 ≤ b`. -/ add_decl_doc prove_sle_nat /-- Given `a`,`b` natural numerals, proves `⊢ a < b`. -/ meta def prove_lt_nat (ic : instance_cache) : expr → expr → tactic (instance_cache × expr) | a b := match match_numeral a, match_numeral b with | zero, _ := prove_pos ic b | one, bit0 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``lt_one_bit0 [b, p] | one, bit1 b := do (ic, p) ← prove_pos_nat ic b, ic.mk_app ``lt_one_bit1 [b, p] | bit0 a, bit0 b := do (ic, p) ← prove_lt_nat a b, ic.mk_app ``lt_bit0_bit0 [a, b, p] | bit0 a, bit1 b := do (ic, p) ← prove_le_nat ic a b, ic.mk_app ``lt_bit0_bit1 [a, b, p] | bit1 a, bit0 b := do (ic, p) ← prove_sle_nat ic a b, ic.mk_app ``lt_bit1_bit0 [a, b, p] | bit1 a, bit1 b := do (ic, p) ← prove_lt_nat a b, ic.mk_app ``lt_bit1_bit1 [a, b, p] | _, _ := failed end end theorem clear_denom_lt {α} [linear_ordered_semiring α] (a a' b b' d : α) (h₀ : 0 < d) (ha : a * d = a') (hb : b * d = b') (h : a' < b') : a < b := lt_of_mul_lt_mul_right (by rwa [ha, hb]) (le_of_lt h₀) /-- Given `a`,`b` nonnegative rational numerals, proves `⊢ a < b`. -/ meta def prove_lt_nonneg_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr) := if na.denom = 1 ∧ nb.denom = 1 then prove_lt_nat ic a b else do let nd := na.denom.lcm nb.denom, (ic, d) ← ic.of_nat nd, (ic, p₀) ← prove_pos ic d, (ic, a', pa) ← prove_clear_denom ic a d na nd, (ic, b', pb) ← prove_clear_denom ic b d nb nd, (ic, p) ← prove_lt_nat ic a' b', ic.mk_app ``clear_denom_lt [a, a', b, b', d, p₀, pa, pb, p] lemma lt_neg_pos {α} [ordered_add_comm_group α] (a b : α) (ha : 0 < a) (hb : 0 < b) : -a < b := lt_trans (neg_neg_of_pos ha) hb /-- Given `a`,`b` rational numerals, proves `⊢ a < b`. -/ meta def prove_lt_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr) := match match_sign a, match_sign b with | sum.inl a, sum.inl b := do (ic, p) ← prove_lt_nonneg_rat ic a b (-na) (-nb), ic.mk_app ``neg_lt_neg [a, b, p] | sum.inl a, sum.inr ff := do (ic, p) ← prove_pos ic a, ic.mk_app ``neg_neg_of_pos [a, p] | sum.inl a, sum.inr tt := do (ic, pa) ← prove_pos ic a, (ic, pb) ← prove_pos ic b, ic.mk_app ``lt_neg_pos [a, b, pa, pb] | sum.inr ff, _ := prove_pos ic b | sum.inr tt, _ := prove_lt_nonneg_rat ic a b na nb end theorem clear_denom_le {α} [linear_ordered_semiring α] (a a' b b' d : α) (h₀ : 0 < d) (ha : a * d = a') (hb : b * d = b') (h : a' ≤ b') : a ≤ b := le_of_mul_le_mul_right (by rwa [ha, hb]) h₀ /-- Given `a`,`b` nonnegative rational numerals, proves `⊢ a ≤ b`. -/ meta def prove_le_nonneg_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr) := if na.denom = 1 ∧ nb.denom = 1 then prove_le_nat ic a b else do let nd := na.denom.lcm nb.denom, (ic, d) ← ic.of_nat nd, (ic, p₀) ← prove_pos ic d, (ic, a', pa) ← prove_clear_denom ic a d na nd, (ic, b', pb) ← prove_clear_denom ic b d nb nd, (ic, p) ← prove_le_nat ic a' b', ic.mk_app ``clear_denom_le [a, a', b, b', d, p₀, pa, pb, p] lemma le_neg_pos {α} [ordered_add_comm_group α] (a b : α) (ha : 0 ≤ a) (hb : 0 ≤ b) : -a ≤ b := le_trans (neg_nonpos_of_nonneg ha) hb /-- Given `a`,`b` rational numerals, proves `⊢ a ≤ b`. -/ meta def prove_le_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr) := match match_sign a, match_sign b with | sum.inl a, sum.inl b := do (ic, p) ← prove_le_nonneg_rat ic a b (-na) (-nb), ic.mk_app ``neg_le_neg [a, b, p] | sum.inl a, sum.inr ff := do (ic, p) ← prove_nonneg ic a, ic.mk_app ``neg_nonpos_of_nonneg [a, p] | sum.inl a, sum.inr tt := do (ic, pa) ← prove_nonneg ic a, (ic, pb) ← prove_nonneg ic b, ic.mk_app ``le_neg_pos [a, b, pa, pb] | sum.inr ff, _ := prove_nonneg ic b | sum.inr tt, _ := prove_le_nonneg_rat ic a b na nb end /-- Given `a`,`b` rational numerals, proves `⊢ a ≠ b`. This version tries to prove `⊢ a < b` or `⊢ b < a`, and so is not appropriate for types without an order relation. -/ meta def prove_ne_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr) := if na < nb then do (ic, p) ← prove_lt_rat ic a b na nb, ic.mk_app ``ne_of_lt [a, b, p] else do (ic, p) ← prove_lt_rat ic b a nb na, ic.mk_app ``ne_of_gt [a, b, p] theorem nat_cast_zero {α} [semiring α] : ↑(0 : ℕ) = (0 : α) := nat.cast_zero theorem nat_cast_one {α} [semiring α] : ↑(1 : ℕ) = (1 : α) := nat.cast_one theorem nat_cast_bit0 {α} [semiring α] (a : ℕ) (a' : α) (h : ↑a = a') : ↑(bit0 a) = bit0 a' := h ▸ nat.cast_bit0 _ theorem nat_cast_bit1 {α} [semiring α] (a : ℕ) (a' : α) (h : ↑a = a') : ↑(bit1 a) = bit1 a' := h ▸ nat.cast_bit1 _ theorem int_cast_zero {α} [ring α] : ↑(0 : ℤ) = (0 : α) := int.cast_zero theorem int_cast_one {α} [ring α] : ↑(1 : ℤ) = (1 : α) := int.cast_one theorem int_cast_bit0 {α} [ring α] (a : ℤ) (a' : α) (h : ↑a = a') : ↑(bit0 a) = bit0 a' := h ▸ int.cast_bit0 _ theorem int_cast_bit1 {α} [ring α] (a : ℤ) (a' : α) (h : ↑a = a') : ↑(bit1 a) = bit1 a' := h ▸ int.cast_bit1 _ theorem rat_cast_bit0 {α} [division_ring α] [char_zero α] (a : ℚ) (a' : α) (h : ↑a = a') : ↑(bit0 a) = bit0 a' := h ▸ rat.cast_bit0 _ theorem rat_cast_bit1 {α} [division_ring α] [char_zero α] (a : ℚ) (a' : α) (h : ↑a = a') : ↑(bit1 a) = bit1 a' := h ▸ rat.cast_bit1 _ /-- Given `a' : α` a natural numeral, returns `(a : ℕ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_nat_uncast (ic nc : instance_cache) : ∀ (a' : expr), tactic (instance_cache × instance_cache × expr × expr) | a' := match match_numeral a' with | match_numeral_result.zero := do (nc, e) ← nc.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``nat_cast_zero [], return (ic, nc, e, p) | match_numeral_result.one := do (nc, e) ← nc.mk_app ``has_one.one [], (ic, p) ← ic.mk_app ``nat_cast_one [], return (ic, nc, e, p) | match_numeral_result.bit0 a' := do (ic, nc, a, p) ← prove_nat_uncast a', (nc, a0) ← nc.mk_bit0 a, (ic, p) ← ic.mk_app ``nat_cast_bit0 [a, a', p], return (ic, nc, a0, p) | match_numeral_result.bit1 a' := do (ic, nc, a, p) ← prove_nat_uncast a', (nc, a1) ← nc.mk_bit1 a, (ic, p) ← ic.mk_app ``nat_cast_bit1 [a, a', p], return (ic, nc, a1, p) | _ := failed end /-- Given `a' : α` a natural numeral, returns `(a : ℤ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_int_uncast_nat (ic zc : instance_cache) : ∀ (a' : expr), tactic (instance_cache × instance_cache × expr × expr) | a' := match match_numeral a' with | match_numeral_result.zero := do (zc, e) ← zc.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``int_cast_zero [], return (ic, zc, e, p) | match_numeral_result.one := do (zc, e) ← zc.mk_app ``has_one.one [], (ic, p) ← ic.mk_app ``int_cast_one [], return (ic, zc, e, p) | match_numeral_result.bit0 a' := do (ic, zc, a, p) ← prove_int_uncast_nat a', (zc, a0) ← zc.mk_bit0 a, (ic, p) ← ic.mk_app ``int_cast_bit0 [a, a', p], return (ic, zc, a0, p) | match_numeral_result.bit1 a' := do (ic, zc, a, p) ← prove_int_uncast_nat a', (zc, a1) ← zc.mk_bit1 a, (ic, p) ← ic.mk_app ``int_cast_bit1 [a, a', p], return (ic, zc, a1, p) | _ := failed end /-- Given `a' : α` a natural numeral, returns `(a : ℚ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_rat_uncast_nat (ic qc : instance_cache) (cz_inst : expr) : ∀ (a' : expr), tactic (instance_cache × instance_cache × expr × expr) | a' := match match_numeral a' with | match_numeral_result.zero := do (qc, e) ← qc.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``rat.cast_zero [cz_inst], return (ic, qc, e, p) | match_numeral_result.one := do (qc, e) ← qc.mk_app ``has_one.one [], (ic, p) ← ic.mk_app ``rat.cast_one [], return (ic, qc, e, p) | match_numeral_result.bit0 a' := do (ic, qc, a, p) ← prove_rat_uncast_nat a', (qc, a0) ← qc.mk_bit0 a, (ic, p) ← ic.mk_app ``rat_cast_bit0 [cz_inst, a, a', p], return (ic, qc, a0, p) | match_numeral_result.bit1 a' := do (ic, qc, a, p) ← prove_rat_uncast_nat a', (qc, a1) ← qc.mk_bit1 a, (ic, p) ← ic.mk_app ``rat_cast_bit1 [cz_inst, a, a', p], return (ic, qc, a1, p) | _ := failed end theorem rat_cast_div {α} [division_ring α] [char_zero α] (a b : ℚ) (a' b' : α) (ha : ↑a = a') (hb : ↑b = b') : ↑(a / b) = a' / b' := ha ▸ hb ▸ rat.cast_div _ _ /-- Given `a' : α` a nonnegative rational numeral, returns `(a : ℚ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_rat_uncast_nonneg (ic qc : instance_cache) (cz_inst a' : expr) (na' : ℚ) : tactic (instance_cache × instance_cache × expr × expr) := if na'.denom = 1 then prove_rat_uncast_nat ic qc cz_inst a' else do [_, _, a', b'] ← return a'.get_app_args, (ic, qc, a, pa) ← prove_rat_uncast_nat ic qc cz_inst a', (ic, qc, b, pb) ← prove_rat_uncast_nat ic qc cz_inst b', (qc, e) ← qc.mk_app ``has_div.div [a, b], (ic, p) ← ic.mk_app ``rat_cast_div [cz_inst, a, b, a', b', pa, pb], return (ic, qc, e, p) theorem int_cast_neg {α} [ring α] (a : ℤ) (a' : α) (h : ↑a = a') : ↑-a = -a' := h ▸ int.cast_neg _ theorem rat_cast_neg {α} [division_ring α] (a : ℚ) (a' : α) (h : ↑a = a') : ↑-a = -a' := h ▸ rat.cast_neg _ /-- Given `a' : α` an integer numeral, returns `(a : ℤ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_int_uncast (ic zc : instance_cache) (a' : expr) : tactic (instance_cache × instance_cache × expr × expr) := match match_neg a' with | some a' := do (ic, zc, a, p) ← prove_int_uncast_nat ic zc a', (zc, e) ← zc.mk_app ``has_neg.neg [a], (ic, p) ← ic.mk_app ``int_cast_neg [a, a', p], return (ic, zc, e, p) | none := prove_int_uncast_nat ic zc a' end /-- Given `a' : α` a rational numeral, returns `(a : ℚ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_rat_uncast (ic qc : instance_cache) (cz_inst a' : expr) (na' : ℚ) : tactic (instance_cache × instance_cache × expr × expr) := match match_neg a' with | some a' := do (ic, qc, a, p) ← prove_rat_uncast_nonneg ic qc cz_inst a' (-na'), (qc, e) ← qc.mk_app ``has_neg.neg [a], (ic, p) ← ic.mk_app ``rat_cast_neg [a, a', p], return (ic, qc, e, p) | none := prove_rat_uncast_nonneg ic qc cz_inst a' na' end theorem nat_cast_ne {α} [semiring α] [char_zero α] (a b : ℕ) (a' b' : α) (ha : ↑a = a') (hb : ↑b = b') (h : a ≠ b) : a' ≠ b' := ha ▸ hb ▸ mt nat.cast_inj.1 h theorem int_cast_ne {α} [ring α] [char_zero α] (a b : ℤ) (a' b' : α) (ha : ↑a = a') (hb : ↑b = b') (h : a ≠ b) : a' ≠ b' := ha ▸ hb ▸ mt int.cast_inj.1 h theorem rat_cast_ne {α} [division_ring α] [char_zero α] (a b : ℚ) (a' b' : α) (ha : ↑a = a') (hb : ↑b = b') (h : a ≠ b) : a' ≠ b' := ha ▸ hb ▸ mt rat.cast_inj.1 h /-- Given `a`,`b` rational numerals, proves `⊢ a ≠ b`. Currently it tries two methods: * Prove `⊢ a < b` or `⊢ b < a`, if the base type has an order * Embed `↑(a':ℚ) = a` and `↑(b':ℚ) = b`, and then prove `a' ≠ b'`. This requires that the base type be `char_zero`, and also that it be a `division_ring` so that the coercion from `ℚ` is well defined. We may also add coercions to `ℤ` and `ℕ` as well in order to support `char_zero` rings and semirings. -/ meta def prove_ne : instance_cache → expr → expr → ℚ → ℚ → tactic (instance_cache × expr) | ic a b na nb := prove_ne_rat ic a b na nb <|> do cz_inst ← mk_mapp ``char_zero [ic.α, none, none] >>= mk_instance, if na.denom = 1 ∧ nb.denom = 1 then if na ≥ 0 ∧ nb ≥ 0 then do guard (ic.α ≠ `(ℕ)), nc ← mk_instance_cache `(ℕ), (ic, nc, a', pa) ← prove_nat_uncast ic nc a, (ic, nc, b', pb) ← prove_nat_uncast ic nc b, (nc, p) ← prove_ne_rat nc a' b' na nb, ic.mk_app ``nat_cast_ne [cz_inst, a', b', a, b, pa, pb, p] else do guard (ic.α ≠ `(ℤ)), zc ← mk_instance_cache `(ℤ), (ic, zc, a', pa) ← prove_int_uncast ic zc a, (ic, zc, b', pb) ← prove_int_uncast ic zc b, (zc, p) ← prove_ne_rat zc a' b' na nb, ic.mk_app ``int_cast_ne [cz_inst, a', b', a, b, pa, pb, p] else do guard (ic.α ≠ `(ℚ)), qc ← mk_instance_cache `(ℚ), (ic, qc, a', pa) ← prove_rat_uncast ic qc cz_inst a na, (ic, qc, b', pb) ← prove_rat_uncast ic qc cz_inst b nb, (qc, p) ← prove_ne_rat qc a' b' na nb, ic.mk_app ``rat_cast_ne [cz_inst, a', b', a, b, pa, pb, p] /-- Given `∣- p`, returns `(true, ⊢ p = true)`. -/ meta def true_intro (p : expr) : tactic (expr × expr) := prod.mk `(true) <$> mk_app ``eq_true_intro [p] /-- Given `∣- ¬ p`, returns `(false, ⊢ p = false)`. -/ meta def false_intro (p : expr) : tactic (expr × expr) := prod.mk `(false) <$> mk_app ``eq_false_intro [p] theorem not_refl_false_intro {α} (a : α) : (a ≠ a) = false := eq_false_intro $ not_not_intro rfl /-- Evaluates the inequality operations `=`,`<`,`>`,`≤`,`≥`,`≠` on numerals. -/ meta def eval_ineq : expr → tactic (expr × expr) | `(%%e₁ < %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ < n₂ then do (_, p) ← prove_lt_rat c e₁ e₂ n₁ n₂, true_intro p else if n₁ = n₂ then do (_, p) ← c.mk_app ``lt_irrefl [e₁], false_intro p else do (c, p') ← prove_lt_rat c e₂ e₁ n₂ n₁, (_, p) ← c.mk_app ``not_lt_of_gt [e₁, e₂, p'], false_intro p | `(%%e₁ ≤ %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ ≤ n₂ then do (_, p) ← if n₁ = n₂ then c.mk_app ``le_refl [e₁] else prove_le_rat c e₁ e₂ n₁ n₂, true_intro p else do (c, p) ← prove_lt_rat c e₂ e₁ n₂ n₁, (_, p) ← c.mk_app ``not_le_of_gt [e₁, e₂, p], false_intro p | `(%%e₁ = %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ = n₂ then mk_eq_refl e₁ >>= true_intro else do (_, p) ← prove_ne c e₁ e₂ n₁ n₂, false_intro p | `(%%e₁ > %%e₂) := mk_app ``has_lt.lt [e₂, e₁] >>= eval_ineq | `(%%e₁ ≥ %%e₂) := mk_app ``has_le.le [e₂, e₁] >>= eval_ineq | `(%%e₁ ≠ %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ = n₂ then prod.mk `(false) <$> mk_app ``not_refl_false_intro [e₁] else do (_, p) ← prove_ne c e₁ e₂ n₁ n₂, true_intro p | _ := failed theorem nat_succ_eq (a b c : ℕ) (h₁ : a = b) (h₂ : b + 1 = c) : nat.succ a = c := by rwa h₁ /-- Evaluates the expression `nat.succ ... (nat.succ n)` where `n` is a natural numeral. (We could also just handle `nat.succ n` here and rely on `simp` to work bottom up, but we figure that towers of successors coming from e.g. `induction` are a common case.) -/ meta def prove_nat_succ (ic : instance_cache) : expr → tactic (instance_cache × ℕ × expr × expr) | `(nat.succ %%a) := do (ic, n, b, p₁) ← prove_nat_succ a, let n' := n + 1, (ic, c) ← ic.of_nat n', (ic, p₂) ← prove_add_nat ic b `(1) c, return (ic, n', c, `(nat_succ_eq).mk_app [a, b, c, p₁, p₂]) | e := do n ← e.to_nat, p ← mk_eq_refl e, return (ic, n, e, p) lemma nat_div (a b q r m : ℕ) (hm : q * b = m) (h : r + m = a) (h₂ : r < b) : a / b = q := by rw [← h, ← hm, nat.add_mul_div_right _ _ (lt_of_le_of_lt (nat.zero_le _) h₂), nat.div_eq_of_lt h₂, zero_add] lemma int_div (a b q r m : ℤ) (hm : q * b = m) (h : r + m = a) (h₁ : 0 ≤ r) (h₂ : r < b) : a / b = q := by rw [← h, ← hm, int.add_mul_div_right _ _ (ne_of_gt (lt_of_le_of_lt h₁ h₂)), int.div_eq_zero_of_lt h₁ h₂, zero_add] lemma nat_mod (a b q r m : ℕ) (hm : q * b = m) (h : r + m = a) (h₂ : r < b) : a % b = r := by rw [← h, ← hm, nat.add_mul_mod_self_right, nat.mod_eq_of_lt h₂] lemma int_mod (a b q r m : ℤ) (hm : q * b = m) (h : r + m = a) (h₁ : 0 ≤ r) (h₂ : r < b) : a % b = r := by rw [← h, ← hm, int.add_mul_mod_self, int.mod_eq_of_lt h₁ h₂] lemma int_div_neg (a b c' c : ℤ) (h : a / b = c') (h₂ : -c' = c) : a / -b = c := h₂ ▸ h ▸ int.div_neg _ _ lemma int_mod_neg (a b c : ℤ) (h : a % b = c) : a % -b = c := (int.mod_neg _ _).trans h /-- Given `a`,`b` numerals in `nat` or `int`, * `prove_div_mod ic a b ff` returns `(c, ⊢ a / b = c)` * `prove_div_mod ic a b tt` returns `(c, ⊢ a % b = c)` -/ meta def prove_div_mod (ic : instance_cache) : expr → expr → bool → tactic (instance_cache × expr × expr) | a b mod := match match_neg b with | some b := do (ic, c', p) ← prove_div_mod a b mod, if mod then return (ic, c', `(int_mod_neg).mk_app [a, b, c', p]) else do (ic, c, p₂) ← prove_neg ic c', return (ic, c, `(int_div_neg).mk_app [a, b, c', c, p, p₂]) | none := do n₂ ← b.to_nat, n₁ ← a.to_nat, let nq := n₁ / n₂, let nr := n₁ % n₂, let nm := nq * nr, (ic, q) ← ic.of_nat nq, (ic, r) ← ic.of_nat nr, (ic, m, pm) ← prove_mul_nat ic q b, (ic, p) ← prove_add_nat ic r m a, (ic, p') ← prove_lt_nat ic r b, if ic.α = `(nat) then if mod then return (ic, r, `(nat_mod).mk_app [a, b, q, r, m, pm, p, p']) else return (ic, q, `(nat_div).mk_app [a, b, q, r, m, pm, p, p']) else if ic.α = `(int) then do (ic, p₀) ← prove_nonneg ic r, if mod then return (ic, r, `(int_mod).mk_app [a, b, q, r, m, pm, p, p₀, p']) else return (ic, q, `(int_div).mk_app [a, b, q, r, m, pm, p, p₀, p']) else failed end theorem dvd_eq_nat (a b c : ℕ) (p) (h₁ : b % a = c) (h₂ : (c = 0) = p) : (a ∣ b) = p := (propext $ by rw [← h₁, nat.dvd_iff_mod_eq_zero]).trans h₂ theorem dvd_eq_int (a b c : ℤ) (p) (h₁ : b % a = c) (h₂ : (c = 0) = p) : (a ∣ b) = p := (propext $ by rw [← h₁, int.dvd_iff_mod_eq_zero]).trans h₂ /-- Evaluates some extra numeric operations on `nat` and `int`, specifically `nat.succ`, `/` and `%`, and `∣` (divisibility). -/ meta def eval_nat_int_ext : expr → tactic (expr × expr) | e@`(nat.succ _) := do ic ← mk_instance_cache `(ℕ), (_, _, ep) ← prove_nat_succ ic e, return ep | `(%%a / %%b) := do c ← infer_type a >>= mk_instance_cache, prod.snd <$> prove_div_mod c a b ff | `(%%a % %%b) := do c ← infer_type a >>= mk_instance_cache, prod.snd <$> prove_div_mod c a b tt | `(%%a ∣ %%b) := do α ← infer_type a, ic ← mk_instance_cache α, th ← if α = `(nat) then return (`(dvd_eq_nat):expr) else if α = `(int) then return `(dvd_eq_int) else failed, (ic, c, p₁) ← prove_div_mod ic b a tt, (ic, z) ← ic.mk_app ``has_zero.zero [], (e', p₂) ← mk_app ``eq [c, z] >>= eval_ineq, return (e', th.mk_app [a, b, c, e', p₁, p₂]) | _ := failed lemma not_prime_helper (a b n : ℕ) (h : a * b = n) (h₁ : 1 < a) (h₂ : 1 < b) : ¬ nat.prime n := by rw ← h; exact nat.not_prime_mul h₁ h₂ lemma is_prime_helper (n : ℕ) (h₁ : 1 < n) (h₂ : nat.min_fac n = n) : nat.prime n := nat.prime_def_min_fac.2 ⟨h₁, h₂⟩ lemma min_fac_bit0 (n : ℕ) : nat.min_fac (bit0 n) = 2 := by simp [nat.min_fac_eq, show 2 ∣ bit0 n, by simp [bit0_eq_two_mul n]] /-- A predicate representing partial progress in a proof of `min_fac`. -/ def min_fac_helper (n k : ℕ) : Prop := 0 < k ∧ bit1 k ≤ nat.min_fac (bit1 n) theorem min_fac_helper.n_pos {n k : ℕ} (h : min_fac_helper n k) : 0 < n := nat.pos_iff_ne_zero.2 $ λ e, by rw e at h; exact not_le_of_lt (nat.bit1_lt h.1) h.2 lemma min_fac_ne_bit0 {n k : ℕ} : nat.min_fac (bit1 n) ≠ bit0 k := by rw bit0_eq_two_mul; exact λ e, absurd ((nat.dvd_add_iff_right (by simp [bit0_eq_two_mul n])).2 (dvd_trans ⟨_, e⟩ (nat.min_fac_dvd _))) dec_trivial lemma min_fac_helper_0 (n : ℕ) (h : 0 < n) : min_fac_helper n 1 := begin refine ⟨zero_lt_one, lt_of_le_of_ne _ min_fac_ne_bit0.symm⟩, refine @lt_of_le_of_ne ℕ _ _ _ (nat.min_fac_pos _) _, intro e, have := nat.min_fac_prime _, { rw ← e at this, exact nat.not_prime_one this }, { exact ne_of_gt (nat.bit1_lt h) } end lemma min_fac_helper_1 {n k k' : ℕ} (e : k + 1 = k') (np : nat.min_fac (bit1 n) ≠ bit1 k) (h : min_fac_helper n k) : min_fac_helper n k' := begin rw ← e, refine ⟨nat.succ_pos _, (lt_of_le_of_ne (lt_of_le_of_ne _ _ : k+1+k < _) min_fac_ne_bit0.symm : bit0 (k+1) < _)⟩, { rw add_right_comm, exact h.2 }, { rw add_right_comm, exact np.symm } end lemma min_fac_helper_2 (n k k' : ℕ) (e : k + 1 = k') (np : ¬ nat.prime (bit1 k)) (h : min_fac_helper n k) : min_fac_helper n k' := begin refine min_fac_helper_1 e _ h, intro e₁, rw ← e₁ at np, exact np (nat.min_fac_prime $ ne_of_gt $ nat.bit1_lt h.n_pos) end lemma min_fac_helper_3 (n k k' c : ℕ) (e : k + 1 = k') (nc : bit1 n % bit1 k = c) (c0 : 0 < c) (h : min_fac_helper n k) : min_fac_helper n k' := begin refine min_fac_helper_1 e _ h, refine mt _ (ne_of_gt c0), intro e₁, rw [← nc, ← nat.dvd_iff_mod_eq_zero, ← e₁], apply nat.min_fac_dvd end lemma min_fac_helper_4 (n k : ℕ) (hd : bit1 n % bit1 k = 0) (h : min_fac_helper n k) : nat.min_fac (bit1 n) = bit1 k := by rw ← nat.dvd_iff_mod_eq_zero at hd; exact le_antisymm (nat.min_fac_le_of_dvd (nat.bit1_lt h.1) hd) h.2 lemma min_fac_helper_5 (n k k' : ℕ) (e : bit1 k * bit1 k = k') (hd : bit1 n < k') (h : min_fac_helper n k) : nat.min_fac (bit1 n) = bit1 n := begin refine (nat.prime_def_min_fac.1 (nat.prime_def_le_sqrt.2 ⟨nat.bit1_lt h.n_pos, _⟩)).2, rw ← e at hd, intros m m2 hm md, have := le_trans h.2 (le_trans (nat.min_fac_le_of_dvd m2 md) hm), rw nat.le_sqrt at this, exact not_le_of_lt hd this end /-- Given `e` a natural numeral and `d : nat` a factor of it, return `⊢ ¬ prime e`. -/ meta def prove_non_prime (e : expr) (n d₁ : ℕ) : tactic expr := do let e₁ := reflect d₁, c ← mk_instance_cache `(nat), (c, p₁) ← prove_lt_nat c `(1) e₁, let d₂ := n / d₁, let e₂ := reflect d₂, (c, e', p) ← prove_mul_nat c e₁ e₂, guard (e' =ₐ e), (c, p₂) ← prove_lt_nat c `(1) e₂, return $ `(not_prime_helper).mk_app [e₁, e₂, e, p, p₁, p₂] /-- Given `a`,`a1 := bit1 a`, `n1` the value of `a1`, `b` and `p : min_fac_helper a b`, returns `(c, ⊢ min_fac a1 = c)`. -/ meta def prove_min_fac_aux (a a1 : expr) (n1 : ℕ) : instance_cache → expr → expr → tactic (instance_cache × expr × expr) | ic b p := do k ← b.to_nat, let k1 := bit1 k, let b1 := `(bit1:ℕ→ℕ).mk_app [b], if n1 < k1*k1 then do (ic, e', p₁) ← prove_mul_nat ic b1 b1, (ic, p₂) ← prove_lt_nat ic a1 e', return (ic, a1, `(min_fac_helper_5).mk_app [a, b, e', p₁, p₂, p]) else let d := k1.min_fac in if to_bool (d < k1) then do let k' := k+1, let e' := reflect k', (ic, p₁) ← prove_succ ic b e', p₂ ← prove_non_prime b1 k1 d, prove_min_fac_aux ic e' $ `(min_fac_helper_2).mk_app [a, b, e', p₁, p₂, p] else do let nc := n1 % k1, (ic, c, pc) ← prove_div_mod ic a1 b1 tt, if nc = 0 then return (ic, b1, `(min_fac_helper_4).mk_app [a, b, pc, p]) else do (ic, p₀) ← prove_pos ic c, let k' := k+1, let e' := reflect k', (ic, p₁) ← prove_succ ic b e', prove_min_fac_aux ic e' $ `(min_fac_helper_3).mk_app [a, b, e', c, p₁, pc, p₀, p] /-- Given `a` a natural numeral, returns `(b, ⊢ min_fac a = b)`. -/ meta def prove_min_fac (ic : instance_cache) (e : expr) : tactic (instance_cache × expr × expr) := match match_numeral e with | match_numeral_result.zero := return (ic, `(2:ℕ), `(nat.min_fac_zero)) | match_numeral_result.one := return (ic, `(1:ℕ), `(nat.min_fac_one)) | match_numeral_result.bit0 e := return (ic, `(2), `(min_fac_bit0).mk_app [e]) | match_numeral_result.bit1 e := do n ← e.to_nat, c ← mk_instance_cache `(nat), (c, p) ← prove_pos c e, let a1 := `(bit1:ℕ→ℕ).mk_app [e], prove_min_fac_aux e a1 (bit1 n) c `(1) (`(min_fac_helper_0).mk_app [e, p]) | _ := failed end /-- Evaluates the `prime` and `min_fac` functions. -/ meta def eval_prime : expr → tactic (expr × expr) | `(nat.prime %%e) := do n ← e.to_nat, match n with | 0 := false_intro `(nat.not_prime_zero) | 1 := false_intro `(nat.not_prime_one) | _ := let d₁ := n.min_fac in if d₁ < n then prove_non_prime e n d₁ >>= false_intro else do let e₁ := reflect d₁, c ← mk_instance_cache `(nat), (c, p₁) ← prove_lt_nat c `(1) e₁, (c, e₁, p) ← prove_min_fac c e, true_intro $ `(is_prime_helper).mk_app [e, p₁, p] end | `(nat.min_fac %%e) := do ic ← mk_instance_cache `(ℕ), prod.snd <$> prove_min_fac ic e | _ := failed /-- This version of `derive` does not fail when the input is already a numeral -/ meta def derive' (e : expr) : tactic (expr × expr) := eval_field e <|> eval_nat_int_ext e <|> eval_pow e <|> eval_ineq e <|> eval_prime e meta def derive : expr → tactic (expr × expr) | e := do e ← instantiate_mvars e, (_, e', pr) ← ext_simplify_core () {} simp_lemmas.mk (λ _, failed) (λ _ _ _ _ _, failed) (λ _ _ _ _ e, do (new_e, pr) ← derive' e, guard (¬ new_e =ₐ e), return ((), new_e, some pr, tt)) `eq e, return (e', pr) end norm_num namespace tactic.interactive open norm_num interactive interactive.types /-- Basic version of `norm_num` that does not call `simp`. -/ meta def norm_num1 (loc : parse location) : tactic unit := do ns ← loc.get_locals, tt ← tactic.replace_at derive ns loc.include_goal | fail "norm_num failed to simplify", when loc.include_goal $ try tactic.triv, when (¬ ns.empty) $ try tactic.contradiction /-- Normalize numerical expressions. Supports the operations `+` `-` `*` `/` `^` and `%` over numerical types such as `ℕ`, `ℤ`, `ℚ`, `ℝ`, `ℂ` and some general algebraic types, and can prove goals of the form `A = B`, `A ≠ B`, `A < B` and `A ≤ B`, where `A` and `B` are numerical expressions. It also has a relatively simple primality prover. -/ meta def norm_num (hs : parse simp_arg_list) (l : parse location) : tactic unit := repeat1 $ orelse' (norm_num1 l) $ simp_core {} (norm_num1 (loc.ns [none])) ff hs [] l add_hint_tactic "norm_num" /-- Normalizes a numerical expression and tries to close the goal with the result. -/ meta def apply_normed (x : parse texpr) : tactic unit := do x₁ ← to_expr x, (x₂,_) ← derive x₁, tactic.exact x₂ /-- Normalises numerical expressions. It supports the operations `+` `-` `*` `/` `^` and `%` over numerical types such as `ℕ`, `ℤ`, `ℚ`, `ℝ`, `ℂ`, and can prove goals of the form `A = B`, `A ≠ B`, `A < B` and `A ≤ B`, where `A` and `B` are numerical expressions. It also has a relatively simple primality prover. ```lean import data.real.basic example : (2 : ℝ) + 2 = 4 := by norm_num example : (12345.2 : ℝ) ≠ 12345.3 := by norm_num example : (73 : ℝ) < 789/2 := by norm_num example : 123456789 + 987654321 = 1111111110 := by norm_num example (R : Type*) [ring R] : (2 : R) + 2 = 4 := by norm_num example (F : Type*) [linear_ordered_field F] : (2 : F) + 2 < 5 := by norm_num example : nat.prime (2^13 - 1) := by norm_num example : ¬ nat.prime (2^11 - 1) := by norm_num example (x : ℝ) (h : x = 123 + 456) : x = 579 := by norm_num at h; assumption ``` The variant `norm_num1` does not call `simp`. Both `norm_num` and `norm_num1` can be called inside the `conv` tactic. The tactic `apply_normed` normalises a numerical expression and tries to close the goal with the result. Compare: ```lean def a : ℕ := 2^100 #print a -- 2 ^ 100 def normed_a : ℕ := by apply_normed 2^100 #print normed_a -- 1267650600228229401496703205376 ``` -/ add_tactic_doc { name := "norm_num", category := doc_category.tactic, decl_names := [`tactic.interactive.norm_num1, `tactic.interactive.norm_num, `tactic.interactive.apply_normed], tags := ["arithmetic", "decision procedure"] } end tactic.interactive namespace conv.interactive open conv interactive tactic.interactive open norm_num (derive) /-- Basic version of `norm_num` that does not call `simp`. -/ meta def norm_num1 : conv unit := replace_lhs derive /-- Normalize numerical expressions. Supports the operations `+` `-` `*` `/` `^` and `%` over numerical types such as `ℕ`, `ℤ`, `ℚ`, `ℝ`, `ℂ` and some general algebraic types, and can prove goals of the form `A = B`, `A ≠ B`, `A < B` and `A ≤ B`, where `A` and `B` are numerical expressions. It also has a relatively simple primality prover. -/ meta def norm_num (hs : parse simp_arg_list) : conv unit := repeat1 $ orelse' norm_num1 $ simp_core {} norm_num1 ff hs [] (loc.ns [none]) end conv.interactive
e55de74b3f57c55984948a561d11d655e9d655f0
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Elab/ParseImportsFast.lean
bcb5d83427a078e9896593d89cdf541b55257bbb
[ "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
7,562
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Parser.Module namespace Lean namespace ParseImports structure State where imports : Array Import := #[] pos : String.Pos := 0 error? : Option String := none deriving Inhabited def Parser := String → State → State instance : Inhabited Parser where default := fun _ s => s @[inline] def State.setPos (s : State) (pos : String.Pos) : State := { s with pos := pos } @[inline] def State.mkError (s : State) (msg : String) : State := { s with error? := some msg } def State.mkEOIError (s : State) : State := s.mkError "unexpected end of input" @[inline] def State.next (s : State) (input : String) (pos : String.Pos) : State := { s with pos := input.next pos } @[inline] def State.next' (s : State) (input : String) (pos : String.Pos) (h : ¬ input.atEnd pos): State := { s with pos := input.next' pos h } partial def finishCommentBlock (nesting : Nat) : Parser := fun input s => let input := input let i := s.pos if h : input.atEnd i then eoi s else let curr := input.get' i h let i := input.next' i h if curr == '-' then if h : input.atEnd i then eoi s else let curr := input.get' i h if curr == '/' then -- "-/" end of comment if nesting == 1 then s.next input i else finishCommentBlock (nesting-1) input (s.next' input i h) else finishCommentBlock nesting input (s.next' input i h) else if curr == '/' then if h : input.atEnd i then eoi s else let curr := input.get' i h if curr == '-' then finishCommentBlock (nesting+1) input (s.next' input i h) else finishCommentBlock nesting input (s.setPos i) else finishCommentBlock nesting input (s.setPos i) where eoi s := s.mkError "unterminated comment" @[specialize] partial def takeUntil (p : Char → Bool) : Parser := fun input s => let i := s.pos if h : input.atEnd i then s else if p (input.get' i h) then s else takeUntil p input (s.next' input i h) @[inline] def takeWhile (p : Char → Bool) : Parser := takeUntil (fun c => !p c) @[inline] def andthen (p q : Parser) : Parser := fun input s => let s := p input s if s.error? matches some .. then s else q input s instance : AndThen Parser where andThen p q := andthen p (q ()) partial def whitespace : Parser := fun input s => let i := s.pos if h : input.atEnd i then s else let curr := input.get' i h if curr == '\t' then s.mkError "tabs are not allowed; please configure your editor to expand them" else if curr.isWhitespace then whitespace input (s.next input i) else if curr == '-' then let i := input.next' i h let curr := input.get i if curr == '-' then andthen (takeUntil (fun c => c = '\n')) whitespace input (s.next input i) else s else if curr == '/' then let i := input.next' i h let curr := input.get i if curr == '-' then let i := input.next i let curr := input.get i if curr == '-' || curr == '!' then s -- "/--" and "/-!" doc comment are actual tokens else andthen (finishCommentBlock 1) whitespace input (s.next input i) else s else s @[inline] partial def keywordCore (k : String) (failure : Parser) (success : Parser) : Parser := fun input s => let rec @[specialize] go (i j : String.Pos) : State := if h₁ : k.atEnd i then success input <| whitespace input (s.setPos j) else if h₂ : input.atEnd j then failure input s else let curr₁ := k.get' i h₁ let curr₂ := input.get' j h₂ if curr₁ != curr₂ then failure input s else go (k.next' i h₁) (input.next' j h₂) go 0 s.pos @[inline] partial def keyword (k : String) : Parser := keywordCore k (fun _ s => s.mkError s!"`{k}` expected") (fun _ s => s) @[inline] def isIdCont : String → State → Bool := fun input s => let i := s.pos let curr := input.get i if curr == '.' then let i := input.next i if h : input.atEnd i then false else let curr := input.get' i h isIdFirst curr || isIdBeginEscape curr else false def State.pushModule (module : Name) (runtimeOnly : Bool) (s : State) : State := { s with imports := s.imports.push { module, runtimeOnly } } @[inline] def isIdRestCold (c : Char) : Bool := c = '_' || c = '\'' || c == '!' || c == '?' || isLetterLike c || isSubScriptAlnum c @[inline] def isIdRestFast (c : Char) : Bool := c.isAlphanum || (c != '.' && c != '\n' && c != ' ' && isIdRestCold c) partial def moduleIdent (runtimeOnly : Bool) : Parser := fun input s => let rec parse (module : Name) (s : State) := let i := s.pos if h : input.atEnd i then s.mkEOIError else let curr := input.get' i h if isIdBeginEscape curr then let startPart := input.next' i h let s := takeUntil isIdEndEscape input (s.setPos startPart) if h : input.atEnd s.pos then s.mkError "unterminated identifier escape" else let stopPart := s.pos let s := s.next' input s.pos h let module := .str module (input.extract startPart stopPart) if isIdCont input s then let s := s.next input s.pos parse module s else whitespace input (s.pushModule module runtimeOnly) else if isIdFirst curr then let startPart := i let s := takeWhile isIdRestFast input (s.next' input i h) let stopPart := s.pos let module := .str module (input.extract startPart stopPart) if isIdCont input s then let s := s.next input s.pos parse module s else whitespace input (s.pushModule module runtimeOnly) else s.mkError "expected identifier" parse .anonymous s @[specialize] partial def many (p : Parser) : Parser := fun input s => let pos := s.pos let size := s.imports.size let s := p input s match s.error? with | none => many p input s | some _ => { pos, error? := none, imports := s.imports.shrink size } @[inline] partial def preludeOpt (k : String) : Parser := keywordCore k (fun _ s => s.pushModule `Init false) (fun _ s => s) def main : Parser := preludeOpt "prelude" >> many (keyword "import" >> keywordCore "runtime" (moduleIdent false) (moduleIdent true)) end ParseImports /-- Simpler and faster version of `parseImports`. We use it to implement Lake. -/ def parseImports' (input : String) (fileName : String) : IO (Array Lean.Import) := do let s := ParseImports.main input (ParseImports.whitespace input {}) match s.error? with | none => return s.imports | some err => throw <| IO.userError s!"{fileName}: {err}" deriving instance ToJson for Import structure PrintImportResult where imports? : Option (Array Import) := none errors : Array String := #[] deriving ToJson structure PrintImportsResult where imports : Array PrintImportResult deriving ToJson @[export lean_print_imports_json] def printImportsJson (fileNames : Array String) : IO Unit := do let rs ← fileNames.mapM fun fn => do try let deps ← parseImports' (← IO.FS.readFile ⟨fn⟩) fn return { imports? := some deps } catch e => return { errors := #[e.toString] } IO.println (toJson { imports := rs : PrintImportsResult } |>.compress) end Lean
1a9562af48aeba93fdff5fd23e7b3d29aed47c15
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/dedekind_domain/factorization.lean
ad23edb9a51f3a477007a938daa1f4a2a923591e
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
8,375
lean
/- Copyright (c) 2022 María Inés de Frutos-Fernández. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: María Inés de Frutos-Fernández -/ import ring_theory.dedekind_domain.ideal /-! # Factorization of ideals of Dedekind domains > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Every nonzero ideal `I` of a Dedekind domain `R` can be factored as a product `∏_v v^{n_v}` over the maximal ideals of `R`, where the exponents `n_v` are natural numbers. TODO: Extend the results in this file to fractional ideals of `R`. ## Main results - `ideal.finite_factors` : Only finitely many maximal ideals of `R` divide a given nonzero ideal. - `ideal.finprod_height_one_spectrum_factorization` : The ideal `I` equals the finprod `∏_v v^(val_v(I))`,where `val_v(I)` denotes the multiplicity of `v` in the factorization of `I` and `v` runs over the maximal ideals of `R`. ## Tags dedekind domain, ideal, factorization -/ noncomputable theory open_locale big_operators classical non_zero_divisors open set function unique_factorization_monoid is_dedekind_domain is_dedekind_domain.height_one_spectrum /-! ### Factorization of ideals of Dedekind domains -/ variables {R : Type*} [comm_ring R] [is_domain R] [is_dedekind_domain R] {K : Type*} [field K] [algebra R K] [is_fraction_ring R K] (v : height_one_spectrum R) /-- Given a maximal ideal `v` and an ideal `I` of `R`, `max_pow_dividing` returns the maximal power of `v` dividing `I`. -/ def is_dedekind_domain.height_one_spectrum.max_pow_dividing (I : ideal R) : ideal R := v.as_ideal^(associates.mk v.as_ideal).count (associates.mk I).factors /-- Only finitely many maximal ideals of `R` divide a given nonzero ideal. -/ lemma ideal.finite_factors {I : ideal R} (hI : I ≠ 0) : {v : height_one_spectrum R | v.as_ideal ∣ I}.finite := begin rw [← set.finite_coe_iff, set.coe_set_of], haveI h_fin := fintype_subtype_dvd I hI, refine finite.of_injective (λ v, (⟨(v : height_one_spectrum R).as_ideal, v.2⟩ : {x // x ∣ I})) _, intros v w hvw, simp only at hvw, exact subtype.coe_injective ((height_one_spectrum.ext_iff ↑v ↑w).mpr hvw) end /-- For every nonzero ideal `I` of `v`, there are finitely many maximal ideals `v` such that the multiplicity of `v` in the factorization of `I`, denoted `val_v(I)`, is nonzero. -/ lemma associates.finite_factors {I : ideal R} (hI : I ≠ 0) : ∀ᶠ (v : height_one_spectrum R) in filter.cofinite, ((associates.mk v.as_ideal).count (associates.mk I).factors : ℤ) = 0 := begin have h_supp : {v : height_one_spectrum R | ¬((associates.mk v.as_ideal).count (associates.mk I).factors : ℤ) = 0} = {v : height_one_spectrum R | v.as_ideal ∣ I}, { ext v, simp_rw int.coe_nat_eq_zero, exact associates.count_ne_zero_iff_dvd hI v.irreducible, }, rw [filter.eventually_cofinite, h_supp], exact ideal.finite_factors hI, end namespace ideal /-- For every nonzero ideal `I` of `v`, there are finitely many maximal ideals `v` such that `v^(val_v(I))` is not the unit ideal. -/ lemma finite_mul_support {I : ideal R} (hI : I ≠ 0) : (mul_support (λ (v : height_one_spectrum R), v.max_pow_dividing I)).finite := begin have h_subset : {v : height_one_spectrum R | v.max_pow_dividing I ≠ 1} ⊆ {v : height_one_spectrum R | ((associates.mk v.as_ideal).count (associates.mk I).factors : ℤ) ≠ 0}, { intros v hv h_zero, have hv' : v.max_pow_dividing I = 1, { rw [is_dedekind_domain.height_one_spectrum.max_pow_dividing, int.coe_nat_eq_zero.mp h_zero, pow_zero _] }, exact hv hv', }, exact finite.subset (filter.eventually_cofinite.mp (associates.finite_factors hI)) h_subset, end /-- For every nonzero ideal `I` of `v`, there are finitely many maximal ideals `v` such that `v^(val_v(I))`, regarded as a fractional ideal, is not `(1)`. -/ lemma finite_mul_support_coe {I : ideal R} (hI : I ≠ 0) : (mul_support (λ (v : height_one_spectrum R), (v.as_ideal : fractional_ideal R⁰ K) ^ ((associates.mk v.as_ideal).count (associates.mk I).factors : ℤ))).finite := begin rw mul_support, simp_rw [ne.def, zpow_coe_nat, ← fractional_ideal.coe_ideal_pow, fractional_ideal.coe_ideal_eq_one], exact finite_mul_support hI, end /-- For every nonzero ideal `I` of `v`, there are finitely many maximal ideals `v` such that `v^-(val_v(I))` is not the unit ideal. -/ lemma finite_mul_support_inv {I : ideal R} (hI : I ≠ 0) : (mul_support (λ (v : height_one_spectrum R), (v.as_ideal : fractional_ideal R⁰ K) ^ -((associates.mk v.as_ideal).count (associates.mk I).factors : ℤ))).finite := begin rw mul_support, simp_rw [zpow_neg, ne.def, inv_eq_one], exact finite_mul_support_coe hI, end /-- For every nonzero ideal `I` of `v`, `v^(val_v(I) + 1)` does not divide `∏_v v^(val_v(I))`. -/ lemma finprod_not_dvd (I : ideal R) (hI : I ≠ 0) : ¬ (v.as_ideal) ^ ((associates.mk v.as_ideal).count (associates.mk I).factors + 1) ∣ (∏ᶠ (v : height_one_spectrum R), v.max_pow_dividing I) := begin have hf := finite_mul_support hI, have h_ne_zero : v.max_pow_dividing I ≠ 0 := pow_ne_zero _ v.ne_bot, rw [← mul_finprod_cond_ne v hf, pow_add, pow_one, finprod_cond_ne _ _ hf], intro h_contr, have hv_prime : prime v.as_ideal := ideal.prime_of_is_prime v.ne_bot v.is_prime, obtain ⟨w, hw, hvw'⟩ := prime.exists_mem_finset_dvd hv_prime ((mul_dvd_mul_iff_left h_ne_zero).mp h_contr), have hw_prime : prime w.as_ideal := ideal.prime_of_is_prime w.ne_bot w.is_prime, have hvw := prime.dvd_of_dvd_pow hv_prime hvw', rw [prime.dvd_prime_iff_associated hv_prime hw_prime, associated_iff_eq] at hvw, exact (finset.mem_erase.mp hw).1 (height_one_spectrum.ext w v (eq.symm hvw)), end end ideal lemma associates.finprod_ne_zero (I : ideal R) : associates.mk (∏ᶠ (v : height_one_spectrum R), v.max_pow_dividing I) ≠ 0 := begin rw [associates.mk_ne_zero, finprod_def], split_ifs, { rw finset.prod_ne_zero_iff, intros v hv, apply pow_ne_zero _ v.ne_bot, }, { exact one_ne_zero, } end namespace ideal /-- The multiplicity of `v` in `∏_v v^(val_v(I))` equals `val_v(I)`. -/ lemma finprod_count (I : ideal R) (hI : I ≠ 0) : (associates.mk v.as_ideal).count (associates.mk (∏ᶠ (v : height_one_spectrum R), v.max_pow_dividing I)).factors = (associates.mk v.as_ideal).count (associates.mk I).factors := begin have h_ne_zero := associates.finprod_ne_zero I, have hv : irreducible (associates.mk v.as_ideal) := v.associates_irreducible, have h_dvd := finprod_mem_dvd v (ideal.finite_mul_support hI), have h_not_dvd := ideal.finprod_not_dvd v I hI, simp only [is_dedekind_domain.height_one_spectrum.max_pow_dividing] at h_dvd h_ne_zero h_not_dvd, rw [← associates.mk_dvd_mk, associates.dvd_eq_le, associates.mk_pow, associates.prime_pow_dvd_iff_le h_ne_zero hv] at h_dvd h_not_dvd, rw not_le at h_not_dvd, apply nat.eq_of_le_of_lt_succ h_dvd h_not_dvd, end /-- The ideal `I` equals the finprod `∏_v v^(val_v(I))`. -/ lemma finprod_height_one_spectrum_factorization (I : ideal R) (hI : I ≠ 0) : ∏ᶠ (v : height_one_spectrum R), v.max_pow_dividing I = I := begin rw [← associated_iff_eq, ← associates.mk_eq_mk_iff_associated], apply associates.eq_of_eq_counts, { apply associates.finprod_ne_zero I }, { apply associates.mk_ne_zero.mpr hI }, intros v hv, obtain ⟨J, hJv⟩ := associates.exists_rep v, rw [← hJv, associates.irreducible_mk] at hv, rw ← hJv, apply ideal.finprod_count ⟨J, ideal.is_prime_of_prime (irreducible_iff_prime.mp hv), irreducible.ne_zero hv⟩ I hI, end /-- The ideal `I` equals the finprod `∏_v v^(val_v(I))`, when both sides are regarded as fractional ideals of `R`. -/ lemma finprod_height_one_spectrum_factorization_coe (I : ideal R) (hI : I ≠ 0) : ∏ᶠ (v : height_one_spectrum R), (v.as_ideal : fractional_ideal R⁰ K) ^ ((associates.mk v.as_ideal).count (associates.mk I).factors : ℤ) = I := begin conv_rhs { rw ← ideal.finprod_height_one_spectrum_factorization I hI }, rw fractional_ideal.coe_ideal_finprod R⁰ K (le_refl _), simp_rw [is_dedekind_domain.height_one_spectrum.max_pow_dividing, fractional_ideal.coe_ideal_pow, zpow_coe_nat], end end ideal
6c030cbe56823c41424f94e120cc43cb32392e99
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/analysis/convex/basic.lean
3dad458141c3a2775f2eeda5a97b424b450eb230
[ "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
59,463
lean
/- Copyright (c) 2019 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp, Yury Kudriashov, Yaël Dillies -/ import data.complex.module import data.set.intervals.image_preimage import linear_algebra.affine_space.affine_map import order.closure /-! # Convex sets and functions in vector spaces In a 𝕜-vector space, we define the following objects and properties. * `segment 𝕜 x y` is the closed segment joining `x` and `y`. * `open_segment 𝕜 x y` is the open segment joining `x` and `y`. * A set `s` is `convex` if for any two points `x y ∈ s` it includes `segment 𝕜 x y`. * A function `f : E → β` is `convex_on` a set `s` if `s` is itself a convex set, and for any two points `x y ∈ s` the segment joining `(x, f x)` to `(y, f y)` is (non-strictly) above the graph of `f`; equivalently, `convex_on f s` means that the epigraph `{p : E × β | p.1 ∈ s ∧ f p.1 ≤ p.2}` is a convex set; * Convex hull of a set `s` is the minimal convex set that includes `s`. * Standard simplex `std_simplex ι [fintype ι]` is the intersection of the positive quadrant with the hyperplane `s.sum = 1` in the space `ι → ℝ`. We also provide various equivalent versions of the definitions above, prove that some specific sets are convex. Note: To define convexity for functions `f : E → β`, we need `β` to be an ordered vector space, defined using the instance `ordered_smul 𝕜 β`. ## Notations We provide the following notation: * `[x -[𝕜] y] = segment 𝕜 x y` in locale `convex` ## Implementation notes `convex_hull` is defined as a closure operator. This gives access to the `closure_operator` API while the impact on writing code is minimal as `convex_hull s` is automatically elaborated as `⇑convex_hull s`. ## TODO Generalize all this file to affine spaces. Should we rename `segment` and `open_segment` to `convex.Icc` and `convex.Ioo`? Should we also define `clopen_segment`/`convex.Ico`/`convex.Ioc`? -/ universes u u' variables (𝕜 : Type*) {E F : Type*} open linear_map set open_locale big_operators classical pointwise /-! ### Segment -/ /-- Segments in a vector space. -/ def segment [add_comm_monoid E] [ordered_semiring 𝕜] [has_scalar 𝕜 E] (x y : E) : set E := {z : E | ∃ (a b : 𝕜) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1), a • x + b • y = z} /-- Open segment in a vector space. Note that `open_segment 𝕜 x x = {x}` instead of being `∅` when the base semiring has some element between `0` and `1`. -/ def open_segment [add_comm_monoid E] [ordered_semiring 𝕜] [has_scalar 𝕜 E] (x y : E) : set E := {z : E | ∃ (a b : 𝕜) (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1), a • x + b • y = z} localized "notation `[` x ` -[` 𝕜 `] ` y `]` := segment 𝕜 x y" in convex section ordered_semiring variables [add_comm_monoid E] [ordered_semiring 𝕜] [module 𝕜 E] lemma segment_symm (x y : E) : [x -[𝕜] y] = [y -[𝕜] x] := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩, λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩⟩ lemma open_segment_symm (x y : E) : open_segment 𝕜 x y = open_segment 𝕜 y x := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩, λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩⟩ lemma left_mem_segment (x y : E) : x ∈ [x -[𝕜] y] := ⟨1, 0, zero_le_one, le_refl 0, add_zero 1, by rw [zero_smul, one_smul, add_zero]⟩ lemma right_mem_segment (x y : E) : y ∈ [x -[𝕜] y] := segment_symm 𝕜 y x ▸ left_mem_segment 𝕜 y x lemma segment_same (x : E) : [x -[𝕜] x] = {x} := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, by simpa only [(add_smul _ _ _).symm, mem_singleton_iff, hab, one_smul, eq_comm] using hz, λ h, mem_singleton_iff.1 h ▸ left_mem_segment 𝕜 z z⟩ lemma open_segment_subset_segment (x y : E) : open_segment 𝕜 x y ⊆ [x -[𝕜] y] := λ z ⟨a, b, ha, hb, hab, hz⟩, ⟨a, b, ha.le, hb.le, hab, hz⟩ lemma mem_open_segment_of_ne_left_right {x y z : E} (hx : x ≠ z) (hy : y ≠ z) (hz : z ∈ [x -[𝕜] y]) : z ∈ open_segment 𝕜 x y := begin obtain ⟨a, b, ha, hb, hab, hz⟩ := hz, by_cases ha' : a = 0, { rw [ha', zero_add] at hab, rw [ha', hab, zero_smul, one_smul, zero_add] at hz, exact (hy hz).elim }, by_cases hb' : b = 0, { rw [hb', add_zero] at hab, rw [hb', hab, zero_smul, one_smul, add_zero] at hz, exact (hx hz).elim }, exact ⟨a, b, ha.lt_of_ne (ne.symm ha'), hb.lt_of_ne (ne.symm hb'), hab, hz⟩, end variables {𝕜} lemma open_segment_subset_iff_segment_subset {x y : E} {s : set E} (hx : x ∈ s) (hy : y ∈ s) : open_segment 𝕜 x y ⊆ s ↔ [x -[𝕜] y] ⊆ s := begin refine ⟨λ h z hz, _, (open_segment_subset_segment 𝕜 x y).trans⟩, obtain rfl | hxz := eq_or_ne x z, { exact hx }, obtain rfl | hyz := eq_or_ne y z, { exact hy }, exact h (mem_open_segment_of_ne_left_right 𝕜 hxz hyz hz), end lemma convex.combo_self {x y : 𝕜} (h : x + y = 1) (a : 𝕜) : x • a + y • a = a := by rw [←add_smul, h, one_smul] end ordered_semiring section ordered_ring variables [ordered_ring 𝕜] section add_comm_monoid variables [add_comm_monoid E] [module 𝕜 E] [add_comm_monoid F] [module 𝕜 F] section densely_ordered variables [nontrivial 𝕜] [densely_ordered 𝕜] @[simp] lemma open_segment_same (x : E) : open_segment 𝕜 x x = {x} := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, by simpa only [← add_smul, mem_singleton_iff, hab, one_smul, eq_comm] using hz, λ (h : z = x), begin obtain ⟨a, ha₀, ha₁⟩ := densely_ordered.dense (0 : 𝕜) 1 zero_lt_one, refine ⟨a, 1 - a, ha₀, sub_pos_of_lt ha₁, add_sub_cancel'_right _ _, _⟩, rw [←add_smul, add_sub_cancel'_right, one_smul, h], end⟩ end densely_ordered lemma segment_eq_image (x y : E) : [x -[𝕜] y] = (λ θ : 𝕜, (1 - θ) • x + θ • y) '' Icc (0 : 𝕜) 1 := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, ⟨b, ⟨hb, hab ▸ le_add_of_nonneg_left ha⟩, hab ▸ hz ▸ by simp only [add_sub_cancel]⟩, λ ⟨θ, ⟨hθ₀, hθ₁⟩, hz⟩, ⟨1-θ, θ, sub_nonneg.2 hθ₁, hθ₀, sub_add_cancel _ _, hz⟩⟩ lemma segment_eq_image₂ (x y : E) : [x -[𝕜] y] = (λ p : 𝕜 × 𝕜, p.1 • x + p.2 • y) '' {p | 0 ≤ p.1 ∧ 0 ≤ p.2 ∧ p.1 + p.2 = 1} := by simp only [segment, image, prod.exists, mem_set_of_eq, exists_prop, and_assoc] lemma open_segment_eq_image (x y : E) : open_segment 𝕜 x y = (λ (θ : 𝕜), (1 - θ) • x + θ • y) '' Ioo (0 : 𝕜) 1 := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, ⟨b, ⟨hb, hab ▸ lt_add_of_pos_left _ ha⟩, hab ▸ hz ▸ by simp only [add_sub_cancel]⟩, λ ⟨θ, ⟨hθ₀, hθ₁⟩, hz⟩, ⟨1 - θ, θ, sub_pos.2 hθ₁, hθ₀, sub_add_cancel _ _, hz⟩⟩ lemma open_segment_eq_image₂ (x y : E) : open_segment 𝕜 x y = (λ p : 𝕜 × 𝕜, p.1 • x + p.2 • y) '' {p | 0 < p.1 ∧ 0 < p.2 ∧ p.1 + p.2 = 1} := by simp only [open_segment, image, prod.exists, mem_set_of_eq, exists_prop, and_assoc] lemma segment_image (f : E →ₗ[𝕜] F) (a b : E) : f '' [a -[𝕜] b] = [f a -[𝕜] f b] := set.ext (λ x, by simp_rw [segment_eq_image, mem_image, exists_exists_and_eq_and, map_add, map_smul]) @[simp] lemma open_segment_image (f : E →ₗ[𝕜] F) (a b : E) : f '' open_segment 𝕜 a b = open_segment 𝕜 (f a) (f b) := set.ext (λ x, by simp_rw [open_segment_eq_image, mem_image, exists_exists_and_eq_and, map_add, map_smul]) end add_comm_monoid section add_comm_group variables [add_comm_group E] [module 𝕜 E] lemma segment_eq_image' (x y : E) : [x -[𝕜] y] = (λ (θ : 𝕜), x + θ • (y - x)) '' Icc (0 : 𝕜) 1 := by { convert segment_eq_image 𝕜 x y, ext θ, simp only [smul_sub, sub_smul, one_smul], abel } lemma open_segment_eq_image' (x y : E) : open_segment 𝕜 x y = (λ (θ : 𝕜), x + θ • (y - x)) '' Ioo (0 : 𝕜) 1 := by { convert open_segment_eq_image 𝕜 x y, ext θ, simp only [smul_sub, sub_smul, one_smul], abel } lemma mem_segment_translate (a : E) {x b c} : a + x ∈ [a + b -[𝕜] a + c] ↔ x ∈ [b -[𝕜] c] := begin rw [segment_eq_image', segment_eq_image'], refine exists_congr (λ θ, and_congr iff.rfl _), simp only [add_sub_add_left_eq_sub, add_assoc, add_right_inj], end @[simp] lemma mem_open_segment_translate (a : E) {x b c : E} : a + x ∈ open_segment 𝕜 (a + b) (a + c) ↔ x ∈ open_segment 𝕜 b c := begin rw [open_segment_eq_image', open_segment_eq_image'], refine exists_congr (λ θ, and_congr iff.rfl _), simp only [add_sub_add_left_eq_sub, add_assoc, add_right_inj], end lemma segment_translate_preimage (a b c : E) : (λ x, a + x) ⁻¹' [a + b -[𝕜] a + c] = [b -[𝕜] c] := set.ext $ λ x, mem_segment_translate 𝕜 a lemma open_segment_translate_preimage (a b c : E) : (λ x, a + x) ⁻¹' open_segment 𝕜 (a + b) (a + c) = open_segment 𝕜 b c := set.ext $ λ x, mem_open_segment_translate 𝕜 a lemma segment_translate_image (a b c : E) : (λ x, a + x) '' [b -[𝕜] c] = [a + b -[𝕜] a + c] := segment_translate_preimage 𝕜 a b c ▸ image_preimage_eq _ $ add_left_surjective a lemma open_segment_translate_image (a b c : E) : (λ x, a + x) '' open_segment 𝕜 b c = open_segment 𝕜 (a + b) (a + c) := open_segment_translate_preimage 𝕜 a b c ▸ image_preimage_eq _ $ add_left_surjective a end add_comm_group end ordered_ring section linear_ordered_field variables [linear_ordered_field 𝕜] section add_comm_group variables [add_comm_group E] [module 𝕜 E] [add_comm_group F] [module 𝕜 F] {𝕜} @[simp] lemma left_mem_open_segment_iff [no_zero_smul_divisors 𝕜 E] {x y : E} : x ∈ open_segment 𝕜 x y ↔ x = y := begin split, { rintro ⟨a, b, ha, hb, hab, hx⟩, refine smul_right_injective _ hb.ne' ((add_right_inj (a • x)).1 _), rw [hx, ←add_smul, hab, one_smul] }, { rintro rfl, rw open_segment_same, exact mem_singleton _ } end @[simp] lemma right_mem_open_segment_iff {x y : E} : y ∈ open_segment 𝕜 x y ↔ x = y := by rw [open_segment_symm, left_mem_open_segment_iff, eq_comm] end add_comm_group end linear_ordered_field /-! #### Segments in an ordered space Relates `segment`, `open_segment` and `set.Icc`, `set.Ico`, `set.Ioc`, `set.Ioo` -/ section ordered_semiring variables [ordered_semiring 𝕜] section ordered_add_comm_monoid variables [ordered_add_comm_monoid E] [module 𝕜 E] [ordered_smul 𝕜 E] {𝕜} lemma segment_subset_Icc {x y : E} (h : x ≤ y) : [x -[𝕜] y] ⊆ Icc x y := begin rintro z ⟨a, b, ha, hb, hab, rfl⟩, split, calc x = a • x + b • x : by rw [←add_smul, hab, one_smul] ... ≤ a • x + b • y : add_le_add_left (smul_le_smul_of_nonneg h hb) _, calc a • x + b • y ≤ a • y + b • y : add_le_add_right (smul_le_smul_of_nonneg h ha) _ ... = y : by rw [←add_smul, hab, one_smul], end end ordered_add_comm_monoid section ordered_cancel_add_comm_monoid variables [ordered_cancel_add_comm_monoid E] [module 𝕜 E] [ordered_smul 𝕜 E] {𝕜} lemma open_segment_subset_Ioo {x y : E} (h : x < y) : open_segment 𝕜 x y ⊆ Ioo x y := begin rintro z ⟨a, b, ha, hb, hab, rfl⟩, split, calc x = a • x + b • x : by rw [←add_smul, hab, one_smul] ... < a • x + b • y : add_lt_add_left (smul_lt_smul_of_pos h hb) _, calc a • x + b • y < a • y + b • y : add_lt_add_right (smul_lt_smul_of_pos h ha) _ ... = y : by rw [←add_smul, hab, one_smul], end end ordered_cancel_add_comm_monoid end ordered_semiring section linear_ordered_field variables [linear_ordered_field 𝕜] {𝕜} lemma Icc_subset_segment {x y : 𝕜} : Icc x y ⊆ [x -[𝕜] y] := begin rintro z ⟨hxz, hyz⟩, obtain rfl | h := (hxz.trans hyz).eq_or_lt, { rw segment_same, exact hyz.antisymm hxz }, rw ←sub_nonneg at hxz hyz, rw ←sub_pos at h, refine ⟨(y - z) / (y - x), (z - x) / (y - x), div_nonneg hyz h.le, div_nonneg hxz h.le, _, _⟩, { rw [←add_div, sub_add_sub_cancel, div_self h.ne'] }, { rw [smul_eq_mul, smul_eq_mul, ←mul_div_right_comm, ←mul_div_right_comm, ←add_div, div_eq_iff h.ne', add_comm, sub_mul, sub_mul, mul_comm x, sub_add_sub_cancel, mul_sub] } end @[simp] lemma segment_eq_Icc {x y : 𝕜} (h : x ≤ y) : [x -[𝕜] y] = Icc x y := (segment_subset_Icc h).antisymm Icc_subset_segment lemma Ioo_subset_open_segment {x y : 𝕜} : Ioo x y ⊆ open_segment 𝕜 x y := λ z hz, mem_open_segment_of_ne_left_right _ hz.1.ne hz.2.ne' (Icc_subset_segment $ Ioo_subset_Icc_self hz) @[simp] lemma open_segment_eq_Ioo {x y : 𝕜} (h : x < y) : open_segment 𝕜 x y = Ioo x y := (open_segment_subset_Ioo h).antisymm Ioo_subset_open_segment lemma segment_eq_Icc' (x y : 𝕜) : [x -[𝕜] y] = Icc (min x y) (max x y) := begin cases le_total x y, { rw [segment_eq_Icc h, max_eq_right h, min_eq_left h] }, { rw [segment_symm, segment_eq_Icc h, max_eq_left h, min_eq_right h] } end lemma open_segment_eq_Ioo' {x y : 𝕜} (hxy : x ≠ y) : open_segment 𝕜 x y = Ioo (min x y) (max x y) := begin cases hxy.lt_or_lt, { rw [open_segment_eq_Ioo h, max_eq_right h.le, min_eq_left h.le] }, { rw [open_segment_symm, open_segment_eq_Ioo h, max_eq_left h.le, min_eq_right h.le] } end lemma segment_eq_interval (x y : 𝕜) : [x -[𝕜] y] = interval x y := segment_eq_Icc' _ _ /-- A point is in an `Icc` iff it can be expressed as a convex combination of the endpoints. -/ lemma convex.mem_Icc {x y : 𝕜} (h : x ≤ y) {z : 𝕜} : z ∈ Icc x y ↔ ∃ (a b : 𝕜), 0 ≤ a ∧ 0 ≤ b ∧ a + b = 1 ∧ a * x + b * y = z := begin rw ←segment_eq_Icc h, simp_rw [←exists_prop], refl, end /-- A point is in an `Ioo` iff it can be expressed as a strict convex combination of the endpoints. -/ lemma convex.mem_Ioo {x y : 𝕜} (h : x < y) {z : 𝕜} : z ∈ Ioo x y ↔ ∃ (a b : 𝕜), 0 < a ∧ 0 < b ∧ a + b = 1 ∧ a * x + b * y = z := begin rw ←open_segment_eq_Ioo h, simp_rw [←exists_prop], refl, end /-- A point is in an `Ioc` iff it can be expressed as a semistrict convex combination of the endpoints. -/ lemma convex.mem_Ioc {x y : 𝕜} (h : x < y) {z : 𝕜} : z ∈ Ioc x y ↔ ∃ (a b : 𝕜), 0 ≤ a ∧ 0 < b ∧ a + b = 1 ∧ a * x + b * y = z := begin split, { rintro hz, obtain ⟨a, b, ha, hb, hab, rfl⟩ := (convex.mem_Icc h.le).1 (Ioc_subset_Icc_self hz), obtain rfl | hb' := hb.eq_or_lt, { rw add_zero at hab, rw [hab, one_mul, zero_mul, add_zero] at hz, exact (hz.1.ne rfl).elim }, { exact ⟨a, b, ha, hb', hab, rfl⟩ } }, { rintro ⟨a, b, ha, hb, hab, rfl⟩, obtain rfl | ha' := ha.eq_or_lt, { rw zero_add at hab, rwa [hab, one_mul, zero_mul, zero_add, right_mem_Ioc] }, { exact Ioo_subset_Ioc_self ((convex.mem_Ioo h).2 ⟨a, b, ha', hb, hab, rfl⟩) } } end /-- A point is in an `Ico` iff it can be expressed as a semistrict convex combination of the endpoints. -/ lemma convex.mem_Ico {x y : 𝕜} (h : x < y) {z : 𝕜} : z ∈ Ico x y ↔ ∃ (a b : 𝕜), 0 < a ∧ 0 ≤ b ∧ a + b = 1 ∧ a * x + b * y = z := begin split, { rintro hz, obtain ⟨a, b, ha, hb, hab, rfl⟩ := (convex.mem_Icc h.le).1 (Ico_subset_Icc_self hz), obtain rfl | ha' := ha.eq_or_lt, { rw zero_add at hab, rw [hab, one_mul, zero_mul, zero_add] at hz, exact (hz.2.ne rfl).elim }, { exact ⟨a, b, ha', hb, hab, rfl⟩ } }, { rintro ⟨a, b, ha, hb, hab, rfl⟩, obtain rfl | hb' := hb.eq_or_lt, { rw add_zero at hab, rwa [hab, one_mul, zero_mul, add_zero, left_mem_Ico] }, { exact Ioo_subset_Ico_self ((convex.mem_Ioo h).2 ⟨a, b, ha, hb', hab, rfl⟩) } } end end linear_ordered_field /-! ### Convexity of sets -/ variables {ι ι' : Type*} [add_comm_group E] [module ℝ E] [add_comm_group F] [module ℝ F] {s : set E} /-- Convexity of sets. -/ def convex (s : set E) := ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → a • x + b • y ∈ s lemma convex_iff_forall_pos : convex s ↔ ∀ ⦃x y⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 < a → 0 < b → a + b = 1 → a • x + b • y ∈ s := begin refine ⟨λ h x y hx hy a b ha hb hab, h hx hy (le_of_lt ha) (le_of_lt hb) hab, _⟩, intros h x y hx hy a b ha hb hab, cases eq_or_lt_of_le ha with ha ha, { subst a, rw [zero_add] at hab, simp [hab, hy] }, cases eq_or_lt_of_le hb with hb hb, { subst b, rw [add_zero] at hab, simp [hab, hx] }, exact h hx hy ha hb hab end lemma convex_iff_segment_subset : convex s ↔ ∀ ⦃x y⦄, x ∈ s → y ∈ s → [x -[ℝ] y] ⊆ s := by simp only [convex, segment_eq_image₂, subset_def, ball_image_iff, prod.forall, mem_set_of_eq, and_imp] lemma convex_iff_open_segment_subset : convex s ↔ ∀ ⦃x y⦄, x ∈ s → y ∈ s → open_segment ℝ x y ⊆ s := by simp only [convex_iff_forall_pos, open_segment_eq_image₂, subset_def, ball_image_iff, prod.forall, mem_set_of_eq, and_imp] lemma convex.segment_subset (h : convex s) {x y : E} (hx : x ∈ s) (hy : y ∈ s) : [x -[ℝ] y] ⊆ s := convex_iff_segment_subset.1 h hx hy lemma convex.open_segment_subset (h : convex s) {x y : E} (hx : x ∈ s) (hy : y ∈ s) : open_segment ℝ x y ⊆ s := convex_iff_open_segment_subset.1 h hx hy lemma convex.add_smul_sub_mem (h : convex s) {x y : E} (hx : x ∈ s) (hy : y ∈ s) {t : ℝ} (ht : t ∈ Icc (0 : ℝ) 1) : x + t • (y - x) ∈ s := begin apply h.segment_subset hx hy, rw segment_eq_image', apply mem_image_of_mem, exact ht end lemma convex.add_smul_mem (h : convex s) {x y : E} (hx : x ∈ s) (hy : x + y ∈ s) {t : ℝ} (ht : t ∈ Icc (0 : ℝ) 1) : x + t • y ∈ s := by { convert h.add_smul_sub_mem hx hy ht, abel } lemma convex.smul_mem_of_zero_mem (h : convex s) {x : E} (zero_mem : (0:E) ∈ s) (hx : x ∈ s) {t : ℝ} (ht : t ∈ Icc (0 : ℝ) 1) : t • x ∈ s := by simpa using h.add_smul_mem zero_mem (by simpa using hx) ht lemma convex.mem_smul_of_zero_mem (h : convex s) {x : E} (zero_mem : (0:E) ∈ s) (hx : x ∈ s) {t : ℝ} (ht : 1 ≤ t) : x ∈ t • s := begin rw mem_smul_set_iff_inv_smul_mem (zero_lt_one.trans_le ht).ne', exact h.smul_mem_of_zero_mem zero_mem hx ⟨inv_nonneg.2 (zero_le_one.trans ht), inv_le_one ht⟩, end /-- Alternative definition of set convexity, in terms of pointwise set operations. -/ lemma convex_iff_pointwise_add_subset: convex s ↔ ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → a • s + b • s ⊆ s := iff.intro begin rintros hA a b ha hb hab w ⟨au, bv, ⟨u, hu, rfl⟩, ⟨v, hv, rfl⟩, rfl⟩, exact hA hu hv ha hb hab end (λ h x y hx hy a b ha hb hab, (h ha hb hab) (set.add_mem_add ⟨_, hx, rfl⟩ ⟨_, hy, rfl⟩)) /-- Alternative definition of set convexity, using division. -/ lemma convex_iff_div: convex s ↔ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → 0 < a + b → (a/(a+b)) • x + (b/(a+b)) • y ∈ s := ⟨begin assume h x y hx hy a b ha hb hab, apply h hx hy, have ha', from mul_le_mul_of_nonneg_left ha (le_of_lt (inv_pos.2 hab)), rwa [mul_zero, ←div_eq_inv_mul] at ha', have hb', from mul_le_mul_of_nonneg_left hb (le_of_lt (inv_pos.2 hab)), rwa [mul_zero, ←div_eq_inv_mul] at hb', rw [←add_div], exact div_self (ne_of_lt hab).symm end, begin assume h x y hx hy a b ha hb hab, have h', from h hx hy ha hb, rw [hab, div_one, div_one] at h', exact h' zero_lt_one end⟩ /-! ### Examples of convex sets -/ lemma convex_empty : convex (∅ : set E) := by finish lemma convex_singleton (c : E) : convex ({c} : set E) := begin intros x y hx hy a b ha hb hab, rw [set.eq_of_mem_singleton hx, set.eq_of_mem_singleton hy, ←add_smul, hab, one_smul], exact mem_singleton c end lemma convex_univ : convex (set.univ : set E) := λ _ _ _ _ _ _ _ _ _, trivial lemma convex.inter {t : set E} (hs: convex s) (ht: convex t) : convex (s ∩ t) := λ x y (hx : x ∈ s ∩ t) (hy : y ∈ s ∩ t) a b (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1), ⟨hs hx.left hy.left ha hb hab, ht hx.right hy.right ha hb hab⟩ lemma convex_sInter {S : set (set E)} (h : ∀ s ∈ S, convex s) : convex (⋂₀ S) := assume x y hx hy a b ha hb hab s hs, h s hs (hx s hs) (hy s hs) ha hb hab lemma convex_Inter {ι : Sort*} {s : ι → set E} (h : ∀ i : ι, convex (s i)) : convex (⋂ i, s i) := (sInter_range s) ▸ convex_sInter $ forall_range_iff.2 h lemma convex.prod {s : set E} {t : set F} (hs : convex s) (ht : convex t) : convex (s.prod t) := begin intros x y hx hy a b ha hb hab, apply mem_prod.2, exact ⟨hs (mem_prod.1 hx).1 (mem_prod.1 hy).1 ha hb hab, ht (mem_prod.1 hx).2 (mem_prod.1 hy).2 ha hb hab⟩ end lemma directed.convex_Union {ι : Sort*} {s : ι → set E} (hdir : directed has_subset.subset s) (hc : ∀ ⦃i : ι⦄, convex (s i)) : convex (⋃ i, s i) := begin rintro x y hx hy a b ha hb hab, rw mem_Union at ⊢ hx hy, obtain ⟨i, hx⟩ := hx, obtain ⟨j, hy⟩ := hy, obtain ⟨k, hik, hjk⟩ := hdir i j, exact ⟨k, hc (hik hx) (hjk hy) ha hb hab⟩, end lemma directed_on.convex_sUnion {c : set (set E)} (hdir : directed_on has_subset.subset c) (hc : ∀ ⦃A : set E⦄, A ∈ c → convex A) : convex (⋃₀c) := begin rw sUnion_eq_Union, exact (directed_on_iff_directed.1 hdir).convex_Union (λ A, hc A.2), end lemma convex.combo_to_vadd {a b : ℝ} {x y : E} (h : a + b = 1) : a • x + b • y = b • (y - x) + x := calc a • x + b • y = (b • y - b • x) + (a • x + b • x) : by abel ... = b • (y - x) + (a + b) • x : by rw [smul_sub, add_smul] ... = b • (y - x) + (1 : ℝ) • x : by rw [h] ... = b • (y - x) + x : by rw [one_smul] /-- Applying an affine map to an affine combination of two points yields an affine combination of the images. -/ lemma convex.combo_affine_apply {a b : ℝ} {x y : E} {f : E →ᵃ[ℝ] F} (h : a + b = 1) : f (a • x + b • y) = a • f x + b • f y := begin simp only [convex.combo_to_vadd h, ← vsub_eq_sub], exact f.apply_line_map _ _ _, end /-- The preimage of a convex set under an affine map is convex. -/ lemma convex.affine_preimage (f : E →ᵃ[ℝ] F) {s : set F} (hs : convex s) : convex (f ⁻¹' s) := begin intros x y xs ys a b ha hb hab, rw [mem_preimage, convex.combo_affine_apply hab], exact hs xs ys ha hb hab, end /-- The image of a convex set under an affine map is convex. -/ lemma convex.affine_image (f : E →ᵃ[ℝ] F) {s : set E} (hs : convex s) : convex (f '' s) := begin rintros x y ⟨x', ⟨hx', hx'f⟩⟩ ⟨y', ⟨hy', hy'f⟩⟩ a b ha hb hab, refine ⟨a • x' + b • y', ⟨hs hx' hy' ha hb hab, _⟩⟩, rw [convex.combo_affine_apply hab, hx'f, hy'f] end lemma convex.linear_image (hs : convex s) (f : E →ₗ[ℝ] F) : convex (image f s) := hs.affine_image f.to_affine_map lemma convex.is_linear_image (hs : convex s) {f : E → F} (hf : is_linear_map ℝ f) : convex (f '' s) := hs.linear_image $ hf.mk' f lemma convex.linear_preimage {s : set F} (hs : convex s) (f : E →ₗ[ℝ] F) : convex (preimage f s) := hs.affine_preimage f.to_affine_map lemma convex.is_linear_preimage {s : set F} (hs : convex s) {f : E → F} (hf : is_linear_map ℝ f) : convex (preimage f s) := hs.linear_preimage $ hf.mk' f lemma convex.neg (hs : convex s) : convex ((λ z, -z) '' s) := hs.is_linear_image is_linear_map.is_linear_map_neg lemma convex.neg_preimage (hs : convex s) : convex ((λ z, -z) ⁻¹' s) := hs.is_linear_preimage is_linear_map.is_linear_map_neg lemma convex.smul (c : ℝ) (hs : convex s) : convex (c • s) := hs.linear_image (linear_map.lsmul _ _ c) lemma convex.smul_preimage (c : ℝ) (hs : convex s) : convex ((λ z, c • z) ⁻¹' s) := hs.linear_preimage (linear_map.lsmul _ _ c) lemma convex.add {t : set E} (hs : convex s) (ht : convex t) : convex (s + t) := by { rw ← add_image_prod, exact (hs.prod ht).is_linear_image is_linear_map.is_linear_map_add } lemma convex.sub {t : set E} (hs : convex s) (ht : convex t) : convex ((λx : E × E, x.1 - x.2) '' (s.prod t)) := (hs.prod ht).is_linear_image is_linear_map.is_linear_map_sub lemma convex.add_smul (h_conv : convex s) {p q : ℝ} (hple : 0 ≤ p) (hqle : 0 ≤ q) : (p + q) • s = p • s + q • s := begin rcases hple.lt_or_eq with hp | rfl, rcases hqle.lt_or_eq with hq | rfl, { have hpq : 0 < p + q, from add_pos hp hq, ext, split; intro h, { rcases h with ⟨v, hv, rfl⟩, use [p • v, q • v], refine ⟨smul_mem_smul_set hv, smul_mem_smul_set hv, _⟩, rw add_smul, }, { rcases h with ⟨v₁, v₂, ⟨v₁₁, h₁₂, rfl⟩, ⟨v₂₁, h₂₂, rfl⟩, rfl⟩, have := h_conv h₁₂ h₂₂ (le_of_lt $ div_pos hp hpq) (le_of_lt $ div_pos hq hpq) (by {field_simp, rw [div_self (ne_of_gt hpq)]} : p / (p + q) + q / (p + q) = 1), rw mem_smul_set, refine ⟨_, this, _⟩, simp only [← mul_smul, smul_add, mul_div_cancel' _ hpq.ne'], }, }, all_goals { rcases s.eq_empty_or_nonempty with rfl | hne, { simp, }, rw zero_smul_set hne, simp, }, end lemma convex.translate (hs : convex s) (z : E) : convex ((λx, z + x) '' s) := hs.affine_image $ affine_map.const ℝ E z +ᵥ affine_map.id ℝ E /-- The translation of a convex set is also convex. -/ lemma convex.translate_preimage_right (hs : convex s) (a : E) : convex ((λ z, a + z) ⁻¹' s) := hs.affine_preimage $ affine_map.const ℝ E a +ᵥ affine_map.id ℝ E /-- The translation of a convex set is also convex. -/ lemma convex.translate_preimage_left (hs : convex s) (a : E) : convex ((λ z, z + a) ⁻¹' s) := by simpa only [add_comm] using hs.translate_preimage_right a lemma convex.affinity (hs : convex s) (z : E) (c : ℝ) : convex ((λx, z + c • x) '' s) := hs.affine_image $ affine_map.const ℝ E z +ᵥ c • affine_map.id ℝ E lemma real.convex_iff_ord_connected {s : set ℝ} : convex s ↔ ord_connected s := begin simp only [convex_iff_segment_subset, segment_eq_interval, ord_connected_iff_interval_subset], exact forall_congr (λ x, forall_swap) end alias real.convex_iff_ord_connected ↔ convex.ord_connected set.ord_connected.convex lemma convex_Iio (r : ℝ) : convex (Iio r) := ord_connected_Iio.convex lemma convex_Ioi (r : ℝ) : convex (Ioi r) := ord_connected_Ioi.convex lemma convex_Iic (r : ℝ) : convex (Iic r) := ord_connected_Iic.convex lemma convex_Ici (r : ℝ) : convex (Ici r) := ord_connected_Ici.convex lemma convex_Ioo (r s : ℝ) : convex (Ioo r s) := ord_connected_Ioo.convex lemma convex_Ico (r s : ℝ) : convex (Ico r s) := ord_connected_Ico.convex lemma convex_Ioc (r : ℝ) (s : ℝ) : convex (Ioc r s) := ord_connected_Ioc.convex lemma convex_Icc (r : ℝ) (s : ℝ) : convex (Icc r s) := ord_connected_Icc.convex lemma convex_interval (r : ℝ) (s : ℝ) : convex (interval r s) := ord_connected_interval.convex lemma convex_segment (a b : E) : convex [a -[ℝ] b] := begin have : (λ (t : ℝ), a + t • (b - a)) = (λ z : E, a + z) ∘ (λ t : ℝ, t • (b - a)) := rfl, rw [segment_eq_image', this, image_comp], refine ((convex_Icc _ _).is_linear_image _).translate _, exact is_linear_map.is_linear_map_smul' _ end lemma convex_open_segment (a b : E) : convex (open_segment ℝ a b) := begin have : (λ (t : ℝ), a + t • (b - a)) = (λ z : E, a + z) ∘ (λ t : ℝ, t • (b - a)) := rfl, rw [open_segment_eq_image', this, image_comp], refine ((convex_Ioo _ _).is_linear_image _).translate _, exact is_linear_map.is_linear_map_smul' _, end lemma convex_halfspace_lt {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | f w < r} := (convex_Iio r).is_linear_preimage h lemma convex_halfspace_le {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | f w ≤ r} := (convex_Iic r).is_linear_preimage h lemma convex_halfspace_gt {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | r < f w} := (convex_Ioi r).is_linear_preimage h lemma convex_halfspace_ge {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | r ≤ f w} := (convex_Ici r).is_linear_preimage h lemma convex_hyperplane {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | f w = r} := begin show convex (f ⁻¹' {p | p = r}), rw set_of_eq_eq_singleton, exact (convex_singleton r).is_linear_preimage h end lemma convex_halfspace_re_lt (r : ℝ) : convex {c : ℂ | c.re < r} := convex_halfspace_lt (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_re_le (r : ℝ) : convex {c : ℂ | c.re ≤ r} := convex_halfspace_le (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_re_gt (r : ℝ) : convex {c : ℂ | r < c.re } := convex_halfspace_gt (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_re_lge (r : ℝ) : convex {c : ℂ | r ≤ c.re} := convex_halfspace_ge (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_im_lt (r : ℝ) : convex {c : ℂ | c.im < r} := convex_halfspace_lt (is_linear_map.mk complex.add_im complex.smul_im) _ lemma convex_halfspace_im_le (r : ℝ) : convex {c : ℂ | c.im ≤ r} := convex_halfspace_le (is_linear_map.mk complex.add_im complex.smul_im) _ lemma convex_halfspace_im_gt (r : ℝ) : convex {c : ℂ | r < c.im } := convex_halfspace_gt (is_linear_map.mk complex.add_im complex.smul_im) _ lemma convex_halfspace_im_lge (r : ℝ) : convex {c : ℂ | r ≤ c.im} := convex_halfspace_ge (is_linear_map.mk complex.add_im complex.smul_im) _ section submodule open submodule lemma submodule.convex (K : submodule ℝ E) : convex (↑K : set E) := by { repeat {intro}, refine add_mem _ (smul_mem _ _ _) (smul_mem _ _ _); assumption } lemma subspace.convex (K : subspace ℝ E) : convex (↑K : set E) := K.convex end submodule /-! ### Convex and concave functions -/ section functions variables {β : Type*} [ordered_add_comm_monoid β] [module ℝ β] local notation `[`x `, ` y `]` := segment x y /-- Convexity of functions -/ def convex_on (s : set E) (f : E → β) : Prop := convex s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → f (a • x + b • y) ≤ a • f x + b • f y /-- Concavity of functions -/ def concave_on (s : set E) (f : E → β) : Prop := convex s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → a • f x + b • f y ≤ f (a • x + b • y) section variables [ordered_smul ℝ β] /-- A function `f` is concave iff `-f` is convex. -/ @[simp] lemma neg_convex_on_iff {γ : Type*} [ordered_add_comm_group γ] [module ℝ γ] (s : set E) (f : E → γ) : convex_on s (-f) ↔ concave_on s f := begin split, { rintros ⟨hconv, h⟩, refine ⟨hconv, _⟩, intros x y xs ys a b ha hb hab, specialize h xs ys ha hb hab, simp [neg_apply, neg_le, add_comm] at h, exact h }, { rintros ⟨hconv, h⟩, refine ⟨hconv, _⟩, intros x y xs ys a b ha hb hab, specialize h xs ys ha hb hab, simp [neg_apply, neg_le, add_comm, h] } end /-- A function `f` is concave iff `-f` is convex. -/ @[simp] lemma neg_concave_on_iff {γ : Type*} [ordered_add_comm_group γ] [module ℝ γ] (s : set E) (f : E → γ) : concave_on s (-f) ↔ convex_on s f:= by rw [← neg_convex_on_iff s (-f), neg_neg f] end lemma convex_on_id {s : set ℝ} (hs : convex s) : convex_on s id := ⟨hs, by { intros, refl }⟩ lemma concave_on_id {s : set ℝ} (hs : convex s) : concave_on s id := ⟨hs, by { intros, refl }⟩ lemma convex_on_const (c : β) (hs : convex s) : convex_on s (λ x:E, c) := ⟨hs, by { intros, simp only [← add_smul, *, one_smul] }⟩ lemma concave_on_const (c : β) (hs : convex s) : concave_on s (λ x:E, c) := @convex_on_const _ _ _ _ (order_dual β) _ _ c hs variables {t : set E} lemma convex_on_iff_div {f : E → β} : convex_on s f ↔ convex s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → 0 < a + b → f ((a/(a+b)) • x + (b/(a+b)) • y) ≤ (a/(a+b)) • f x + (b/(a+b)) • f y := and_congr iff.rfl ⟨begin intros h x y hx hy a b ha hb hab, apply h hx hy (div_nonneg ha $ le_of_lt hab) (div_nonneg hb $ le_of_lt hab), rw [←add_div], exact div_self (ne_of_gt hab) end, begin intros h x y hx hy a b ha hb hab, simpa [hab, zero_lt_one] using h hx hy ha hb, end⟩ lemma concave_on_iff_div {f : E → β} : concave_on s f ↔ convex s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → 0 < a + b → (a/(a+b)) • f x + (b/(a+b)) • f y ≤ f ((a/(a+b)) • x + (b/(a+b)) • y) := @convex_on_iff_div _ _ _ _ (order_dual β) _ _ _ /-- For a function on a convex set in a linear ordered space, in order to prove that it is convex it suffices to verify the inequality `f (a • x + b • y) ≤ a • f x + b • f y` only for `x < y` and positive `a`, `b`. The main use case is `E = ℝ` however one can apply it, e.g., to `ℝ^n` with lexicographic order. -/ lemma linear_order.convex_on_of_lt {f : E → β} [linear_order E] (hs : convex s) (hf : ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x < y → ∀ ⦃a b : ℝ⦄, 0 < a → 0 < b → a + b = 1 → f (a • x + b • y) ≤ a • f x + b • f y) : convex_on s f := begin use hs, intros x y hx hy a b ha hb hab, wlog hxy : x<=y using [x y a b, y x b a], { exact le_total _ _ }, { cases eq_or_lt_of_le hxy with hxy hxy, by { subst y, rw [← add_smul, ← add_smul, hab, one_smul, one_smul] }, cases eq_or_lt_of_le ha with ha ha, by { subst a, rw [zero_add] at hab, subst b, simp }, cases eq_or_lt_of_le hb with hb hb, by { subst b, rw [add_zero] at hab, subst a, simp }, exact hf hx hy hxy ha hb hab } end /-- For a function on a convex set in a linear ordered space, in order to prove that it is concave it suffices to verify the inequality `a • f x + b • f y ≤ f (a • x + b • y)` only for `x < y` and positive `a`, `b`. The main use case is `E = ℝ` however one can apply it, e.g., to `ℝ^n` with lexicographic order. -/ lemma linear_order.concave_on_of_lt {f : E → β} [linear_order E] (hs : convex s) (hf : ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x < y → ∀ ⦃a b : ℝ⦄, 0 < a → 0 < b → a + b = 1 → a • f x + b • f y ≤ f (a • x + b • y)) : concave_on s f := @linear_order.convex_on_of_lt _ _ _ _ (order_dual β) _ _ f _ hs hf /-- For a function `f` defined on a convex subset `D` of `ℝ`, if for any three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is less than or equal to the slope of the secant line of `f` on `[x, z]`, then `f` is convex on `D`. This way of proving convexity of a function is used in the proof of convexity of a function with a monotone derivative. -/ lemma convex_on_real_of_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ → ℝ} (hf : ∀ {x y z : ℝ}, x ∈ s → z ∈ s → x < y → y < z → (f y - f x) / (y - x) ≤ (f z - f y) / (z - y)) : convex_on s f := linear_order.convex_on_of_lt hs begin assume x z hx hz hxz a b ha hb hab, let y := a * x + b * z, have hxy : x < y, { rw [← one_mul x, ← hab, add_mul], exact add_lt_add_left ((mul_lt_mul_left hb).2 hxz) _ }, have hyz : y < z, { rw [← one_mul z, ← hab, add_mul], exact add_lt_add_right ((mul_lt_mul_left ha).2 hxz) _ }, have : (f y - f x) * (z - y) ≤ (f z - f y) * (y - x), from (div_le_div_iff (sub_pos.2 hxy) (sub_pos.2 hyz)).1 (hf hx hz hxy hyz), have A : z - y + (y - x) = z - x, by abel, have B : 0 < z - x, from sub_pos.2 (lt_trans hxy hyz), rw [sub_mul, sub_mul, sub_le_iff_le_add', ← add_sub_assoc, le_sub_iff_add_le, ← mul_add, A, ← le_div_iff B, add_div, mul_div_assoc, mul_div_assoc, mul_comm (f x), mul_comm (f z)] at this, rw [eq_comm, ← sub_eq_iff_eq_add] at hab; subst a, convert this; symmetry; simp only [div_eq_iff (ne_of_gt B), y]; ring end /-- For a function `f` defined on a subset `D` of `ℝ`, if `f` is convex on `D`, then for any three points `x<y<z`, the slope of the secant line of `f` on `[x, y]` is less than or equal to the slope of the secant line of `f` on `[x, z]`. -/ lemma convex_on.slope_mono_adjacent {s : set ℝ} {f : ℝ → ℝ} (hf : convex_on s f) {x y z : ℝ} (hx : x ∈ s) (hz : z ∈ s) (hxy : x < y) (hyz : y < z) : (f y - f x) / (y - x) ≤ (f z - f y) / (z - y) := begin have h₁ : 0 < y - x := by linarith, have h₂ : 0 < z - y := by linarith, have h₃ : 0 < z - x := by linarith, suffices : f y / (y - x) + f y / (z - y) ≤ f x / (y - x) + f z / (z - y), by { ring_nf at this ⊢, linarith }, set a := (z - y) / (z - x), set b := (y - x) / (z - x), have heqz : a • x + b • z = y, by { field_simp, rw div_eq_iff; [ring, linarith], }, have key, from hf.2 hx hz (show 0 ≤ a, by apply div_nonneg; linarith) (show 0 ≤ b, by apply div_nonneg; linarith) (show a + b = 1, by { field_simp, rw div_eq_iff; [ring, linarith], }), rw heqz at key, replace key := mul_le_mul_of_nonneg_left key (le_of_lt h₃), field_simp [ne_of_gt h₁, ne_of_gt h₂, ne_of_gt h₃, mul_comm (z - x) _] at key ⊢, rw div_le_div_right, { linarith, }, { nlinarith, }, end /-- For a function `f` defined on a convex subset `D` of `ℝ`, `f` is convex on `D` iff for any three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is less than or equal to the slope of the secant line of `f` on `[x, z]`. -/ lemma convex_on_real_iff_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ → ℝ} : convex_on s f ↔ (∀ {x y z : ℝ}, x ∈ s → z ∈ s → x < y → y < z → (f y - f x) / (y - x) ≤ (f z - f y) / (z - y)) := ⟨convex_on.slope_mono_adjacent, convex_on_real_of_slope_mono_adjacent hs⟩ /-- For a function `f` defined on a convex subset `D` of `ℝ`, if for any three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is greater than or equal to the slope of the secant line of `f` on `[x, z]`, then `f` is concave on `D`. -/ lemma concave_on_real_of_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ → ℝ} (hf : ∀ {x y z : ℝ}, x ∈ s → z ∈ s → x < y → y < z → (f z - f y) / (z - y) ≤ (f y - f x) / (y - x)) : concave_on s f := begin rw [←neg_convex_on_iff], apply convex_on_real_of_slope_mono_adjacent hs, intros x y z xs zs xy yz, rw [←neg_le_neg_iff, ←neg_div, ←neg_div, neg_sub, neg_sub], simp only [hf xs zs xy yz, neg_sub_neg, pi.neg_apply], end /-- For a function `f` defined on a subset `D` of `ℝ`, if `f` is concave on `D`, then for any three points `x<y<z`, the slope of the secant line of `f` on `[x, y]` is greater than or equal to the slope of the secant line of `f` on `[x, z]`. -/ lemma concave_on.slope_mono_adjacent {s : set ℝ} {f : ℝ → ℝ} (hf : concave_on s f) {x y z : ℝ} (hx : x ∈ s) (hz : z ∈ s) (hxy : x < y) (hyz : y < z) : (f z - f y) / (z - y) ≤ (f y - f x) / (y - x) := begin rw [←neg_le_neg_iff, ←neg_div, ←neg_div, neg_sub, neg_sub], rw [←neg_sub_neg (f y), ←neg_sub_neg (f z)], simp_rw [←pi.neg_apply], rw [←neg_convex_on_iff] at hf, apply convex_on.slope_mono_adjacent hf; assumption, end /-- For a function `f` defined on a convex subset `D` of `ℝ`, `f` is concave on `D` iff for any three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is greater than or equal to the slope of the secant line of `f` on `[x, z]`. -/ lemma concave_on_real_iff_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ → ℝ} : concave_on s f ↔ (∀ {x y z : ℝ}, x ∈ s → z ∈ s → x < y → y < z → (f z - f y) / (z - y) ≤ (f y - f x) / (y - x)) := ⟨concave_on.slope_mono_adjacent, concave_on_real_of_slope_mono_adjacent hs⟩ lemma convex_on.subset {f : E → β} (h_convex_on : convex_on t f) (h_subset : s ⊆ t) (h_convex : convex s) : convex_on s f := begin apply and.intro h_convex, intros x y hx hy, exact h_convex_on.2 (h_subset hx) (h_subset hy), end lemma concave_on.subset {f : E → β} (h_concave_on : concave_on t f) (h_subset : s ⊆ t) (h_convex : convex s) : concave_on s f := @convex_on.subset _ _ _ _ (order_dual β) _ _ t f h_concave_on h_subset h_convex lemma convex_on.add {f g : E → β} (hf : convex_on s f) (hg : convex_on s g) : convex_on s (λx, f x + g x) := begin apply and.intro hf.1, intros x y hx hy a b ha hb hab, calc f (a • x + b • y) + g (a • x + b • y) ≤ (a • f x + b • f y) + (a • g x + b • g y) : add_le_add (hf.2 hx hy ha hb hab) (hg.2 hx hy ha hb hab) ... = a • f x + a • g x + b • f y + b • g y : by abel ... = a • (f x + g x) + b • (f y + g y) : by simp [smul_add, add_assoc] end lemma concave_on.add {f g : E → β} (hf : concave_on s f) (hg : concave_on s g) : concave_on s (λx, f x + g x) := @convex_on.add _ _ _ _ (order_dual β) _ _ f g hf hg lemma convex_on.smul [ordered_smul ℝ β] {f : E → β} {c : ℝ} (hc : 0 ≤ c) (hf : convex_on s f) : convex_on s (λx, c • f x) := begin apply and.intro hf.1, intros x y hx hy a b ha hb hab, calc c • f (a • x + b • y) ≤ c • (a • f x + b • f y) : smul_le_smul_of_nonneg (hf.2 hx hy ha hb hab) hc ... = a • (c • f x) + b • (c • f y) : by simp only [smul_add, smul_comm c] end lemma concave_on.smul [ordered_smul ℝ β] {f : E → β} {c : ℝ} (hc : 0 ≤ c) (hf : concave_on s f) : concave_on s (λx, c • f x) := @convex_on.smul _ _ _ _ (order_dual β) _ _ _ f c hc hf section linear_order section monoid variables {γ : Type*} [linear_ordered_add_comm_monoid γ] [module ℝ γ] [ordered_smul ℝ γ] {f g : E → γ} /-- The pointwise maximum of convex functions is convex. -/ lemma convex_on.sup (hf : convex_on s f) (hg : convex_on s g) : convex_on s (f ⊔ g) := begin refine ⟨hf.left, λ x y hx hy a b ha hb hab, sup_le _ _⟩, { calc f (a • x + b • y) ≤ a • f x + b • f y : hf.right hx hy ha hb hab ... ≤ a • (f x ⊔ g x) + b • (f y ⊔ g y) : add_le_add (smul_le_smul_of_nonneg le_sup_left ha) (smul_le_smul_of_nonneg le_sup_left hb) }, { calc g (a • x + b • y) ≤ a • g x + b • g y : hg.right hx hy ha hb hab ... ≤ a • (f x ⊔ g x) + b • (f y ⊔ g y) : add_le_add (smul_le_smul_of_nonneg le_sup_right ha) (smul_le_smul_of_nonneg le_sup_right hb) } end /-- The pointwise minimum of concave functions is concave. -/ lemma concave_on.inf (hf : concave_on s f) (hg : concave_on s g) : concave_on s (f ⊓ g) := @convex_on.sup _ _ _ _ (order_dual γ) _ _ _ _ _ hf hg /-- A convex function on a segment is upper-bounded by the max of its endpoints. -/ lemma convex_on.le_on_segment' (hf : convex_on s f) {x y : E} {a b : ℝ} (hx : x ∈ s) (hy : y ∈ s) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) : f (a • x + b • y) ≤ max (f x) (f y) := calc f (a • x + b • y) ≤ a • f x + b • f y : hf.2 hx hy ha hb hab ... ≤ a • max (f x) (f y) + b • max (f x) (f y) : add_le_add (smul_le_smul_of_nonneg (le_max_left _ _) ha) (smul_le_smul_of_nonneg (le_max_right _ _) hb) ... = max (f x) (f y) : by rw [←add_smul, hab, one_smul] /-- A concave function on a segment is lower-bounded by the min of its endpoints. -/ lemma concave_on.le_on_segment' (hf : concave_on s f) {x y : E} {a b : ℝ} (hx : x ∈ s) (hy : y ∈ s) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) : min (f x) (f y) ≤ f (a • x + b • y) := @convex_on.le_on_segment' _ _ _ _ (order_dual γ) _ _ _ f hf x y a b hx hy ha hb hab /-- A convex function on a segment is upper-bounded by the max of its endpoints. -/ lemma convex_on.le_on_segment (hf : convex_on s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ [x -[ℝ] y]) : f z ≤ max (f x) (f y) := let ⟨a, b, ha, hb, hab, hz⟩ := hz in hz ▸ hf.le_on_segment' hx hy ha hb hab /-- A concave function on a segment is lower-bounded by the min of its endpoints. -/ lemma concave_on.le_on_segment {f : E → γ} (hf : concave_on s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ [x -[ℝ] y]) : min (f x) (f y) ≤ f z := @convex_on.le_on_segment _ _ _ _ (order_dual γ) _ _ _ f hf x y z hx hy hz end monoid variables {γ : Type*} [linear_ordered_cancel_add_comm_monoid γ] [module ℝ γ] [ordered_smul ℝ γ] {f : E → γ} -- could be shown without contradiction but yeah lemma convex_on.le_left_of_right_le' (hf : convex_on s f) {x y : E} {a b : ℝ} (hx : x ∈ s) (hy : y ∈ s) (ha : 0 < a) (hb : 0 ≤ b) (hab : a + b = 1) (hxy : f y ≤ f (a • x + b • y)) : f (a • x + b • y) ≤ f x := begin apply le_of_not_lt (λ h, lt_irrefl (f (a • x + b • y)) _), calc f (a • x + b • y) ≤ a • f x + b • f y : hf.2 hx hy ha.le hb hab ... < a • f (a • x + b • y) + b • f (a • x + b • y) : add_lt_add_of_lt_of_le (smul_lt_smul_of_pos h ha) (smul_le_smul_of_nonneg hxy hb) ... = f (a • x + b • y) : by rw [←add_smul, hab, one_smul], end lemma concave_on.left_le_of_le_right' (hf : concave_on s f) {x y : E} {a b : ℝ} (hx : x ∈ s) (hy : y ∈ s) (ha : 0 < a) (hb : 0 ≤ b) (hab : a + b = 1) (hxy : f (a • x + b • y) ≤ f y) : f x ≤ f (a • x + b • y) := @convex_on.le_left_of_right_le' _ _ _ _ (order_dual γ) _ _ _ f hf x y a b hx hy ha hb hab hxy lemma convex_on.le_right_of_left_le' (hf : convex_on s f) {x y : E} {a b : ℝ} (hx : x ∈ s) (hy : y ∈ s) (ha : 0 ≤ a) (hb : 0 < b) (hab : a + b = 1) (hxy : f x ≤ f (a • x + b • y)) : f (a • x + b • y) ≤ f y := begin rw add_comm at ⊢ hab hxy, exact hf.le_left_of_right_le' hy hx hb ha hab hxy, end lemma concave_on.le_right_of_left_le' (hf : concave_on s f) {x y : E} {a b : ℝ} (hx : x ∈ s) (hy : y ∈ s) (ha : 0 ≤ a) (hb : 0 < b) (hab : a + b = 1) (hxy : f (a • x + b • y) ≤ f x) : f y ≤ f (a • x + b • y) := @convex_on.le_right_of_left_le' _ _ _ _ (order_dual γ) _ _ _ f hf x y a b hx hy ha hb hab hxy lemma convex_on.le_left_of_right_le (hf : convex_on s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ open_segment ℝ x y) (hyz : f y ≤ f z) : f z ≤ f x := begin obtain ⟨a, b, ha, hb, hab, rfl⟩ := hz, exact hf.le_left_of_right_le' hx hy ha hb.le hab hyz, end lemma concave_on.left_le_of_le_right (hf : concave_on s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ open_segment ℝ x y) (hyz : f z ≤ f y) : f x ≤ f z := @convex_on.le_left_of_right_le _ _ _ _ (order_dual γ) _ _ _ f hf x y z hx hy hz hyz lemma convex_on.le_right_of_left_le (hf : convex_on s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ open_segment ℝ x y) (hxz : f x ≤ f z) : f z ≤ f y := begin obtain ⟨a, b, ha, hb, hab, rfl⟩ := hz, exact hf.le_right_of_left_le' hx hy ha.le hb hab hxz, end lemma concave_on.le_right_of_left_le (hf : concave_on s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ open_segment ℝ x y) (hxz : f z ≤ f x) : f y ≤ f z := @convex_on.le_right_of_left_le _ _ _ _ (order_dual γ) _ _ _ f hf x y z hx hy hz hxz end linear_order lemma convex_on.convex_le [ordered_smul ℝ β] {f : E → β} (hf : convex_on s f) (r : β) : convex {x ∈ s | f x ≤ r} := λ x y hx hy a b ha hb hab, begin refine ⟨hf.1 hx.1 hy.1 ha hb hab, _⟩, calc f (a • x + b • y) ≤ a • (f x) + b • (f y) : hf.2 hx.1 hy.1 ha hb hab ... ≤ a • r + b • r : add_le_add (smul_le_smul_of_nonneg hx.2 ha) (smul_le_smul_of_nonneg hy.2 hb) ... ≤ r : by simp [←add_smul, hab] end lemma concave_on.concave_le [ordered_smul ℝ β] {f : E → β} (hf : concave_on s f) (r : β) : convex {x ∈ s | r ≤ f x} := @convex_on.convex_le _ _ _ _ (order_dual β) _ _ _ f hf r lemma convex_on.convex_lt {γ : Type*} [ordered_cancel_add_comm_monoid γ] [module ℝ γ] [ordered_smul ℝ γ] {f : E → γ} (hf : convex_on s f) (r : γ) : convex {x ∈ s | f x < r} := begin intros a b as bs xa xb hxa hxb hxaxb, refine ⟨hf.1 as.1 bs.1 hxa hxb hxaxb, _⟩, by_cases H : xa = 0, { have H' : xb = 1 := by rwa [H, zero_add] at hxaxb, rw [H, H', zero_smul, one_smul, zero_add], exact bs.2 }, { calc f (xa • a + xb • b) ≤ xa • (f a) + xb • (f b) : hf.2 as.1 bs.1 hxa hxb hxaxb ... < xa • r + xb • (f b) : (add_lt_add_iff_right (xb • (f b))).mpr (smul_lt_smul_of_pos as.2 (lt_of_le_of_ne hxa (ne.symm H))) ... ≤ xa • r + xb • r : (add_le_add_iff_left (xa • r)).mpr (smul_le_smul_of_nonneg bs.2.le hxb) ... = r : by simp only [←add_smul, hxaxb, one_smul] } end lemma concave_on.convex_lt {γ : Type*} [ordered_cancel_add_comm_monoid γ] [module ℝ γ] [ordered_smul ℝ γ] {f : E → γ} (hf : concave_on s f) (r : γ) : convex {x ∈ s | r < f x} := @convex_on.convex_lt _ _ _ _ (order_dual γ) _ _ _ f hf r lemma convex_on.convex_epigraph {γ : Type*} [ordered_add_comm_group γ] [module ℝ γ] [ordered_smul ℝ γ] {f : E → γ} (hf : convex_on s f) : convex {p : E × γ | p.1 ∈ s ∧ f p.1 ≤ p.2} := begin rintros ⟨x, r⟩ ⟨y, t⟩ ⟨hx, hr⟩ ⟨hy, ht⟩ a b ha hb hab, refine ⟨hf.1 hx hy ha hb hab, _⟩, calc f (a • x + b • y) ≤ a • f x + b • f y : hf.2 hx hy ha hb hab ... ≤ a • r + b • t : add_le_add (smul_le_smul_of_nonneg hr ha) (smul_le_smul_of_nonneg ht hb) end lemma concave_on.convex_hypograph {γ : Type*} [ordered_add_comm_group γ] [module ℝ γ] [ordered_smul ℝ γ] {f : E → γ} (hf : concave_on s f) : convex {p : E × γ | p.1 ∈ s ∧ p.2 ≤ f p.1} := @convex_on.convex_epigraph _ _ _ _ (order_dual γ) _ _ _ f hf lemma convex_on_iff_convex_epigraph {γ : Type*} [ordered_add_comm_group γ] [module ℝ γ] [ordered_smul ℝ γ] {f : E → γ} : convex_on s f ↔ convex {p : E × γ | p.1 ∈ s ∧ f p.1 ≤ p.2} := begin refine ⟨convex_on.convex_epigraph, λ h, ⟨_, _⟩⟩, { assume x y hx hy a b ha hb hab, exact (@h (x, f x) (y, f y) ⟨hx, le_refl _⟩ ⟨hy, le_refl _⟩ a b ha hb hab).1 }, { assume x y hx hy a b ha hb hab, exact (@h (x, f x) (y, f y) ⟨hx, le_refl _⟩ ⟨hy, le_refl _⟩ a b ha hb hab).2 } end lemma concave_on_iff_convex_hypograph {γ : Type*} [ordered_add_comm_group γ] [module ℝ γ] [ordered_smul ℝ γ] {f : E → γ} : concave_on s f ↔ convex {p : E × γ | p.1 ∈ s ∧ p.2 ≤ f p.1} := @convex_on_iff_convex_epigraph _ _ _ _ (order_dual γ) _ _ _ f /- A linear map is convex. -/ lemma linear_map.convex_on (f : E →ₗ[ℝ] β) {s : set E} (hs : convex s) : convex_on s f := ⟨hs, λ _ _ _ _ _ _ _ _ _, by rw [f.map_add, f.map_smul, f.map_smul]⟩ /- A linear map is concave. -/ lemma linear_map.concave_on (f : E →ₗ[ℝ] β) {s : set E} (hs : convex s) : concave_on s f := ⟨hs, λ _ _ _ _ _ _ _ _ _, by rw [f.map_add, f.map_smul, f.map_smul]⟩ /-- If a function is convex on `s`, it remains convex when precomposed by an affine map. -/ lemma convex_on.comp_affine_map {f : F → β} (g : E →ᵃ[ℝ] F) {s : set F} (hf : convex_on s f) : convex_on (g ⁻¹' s) (f ∘ g) := begin refine ⟨hf.1.affine_preimage _,_⟩, intros x y xs ys a b ha hb hab, calc (f ∘ g) (a • x + b • y) = f (g (a • x + b • y)) : rfl ... = f (a • (g x) + b • (g y)) : by rw [convex.combo_affine_apply hab] ... ≤ a • f (g x) + b • f (g y) : hf.2 xs ys ha hb hab ... = a • (f ∘ g) x + b • (f ∘ g) y : rfl end /-- If a function is concave on `s`, it remains concave when precomposed by an affine map. -/ lemma concave_on.comp_affine_map {f : F → β} (g : E →ᵃ[ℝ] F) {s : set F} (hf : concave_on s f) : concave_on (g ⁻¹' s) (f ∘ g) := @convex_on.comp_affine_map _ _ _ _ _ _ (order_dual β) _ _ f g s hf /-- If `g` is convex on `s`, so is `(g ∘ f)` on `f ⁻¹' s` for a linear `f`. -/ lemma convex_on.comp_linear_map {g : F → β} {s : set F} (hg : convex_on s g) (f : E →ₗ[ℝ] F) : convex_on (f ⁻¹' s) (g ∘ f) := hg.comp_affine_map f.to_affine_map /-- If `g` is concave on `s`, so is `(g ∘ f)` on `f ⁻¹' s` for a linear `f`. -/ lemma concave_on.comp_linear_map {g : F → β} {s : set F} (hg : concave_on s g) (f : E →ₗ[ℝ] F) : concave_on (f ⁻¹' s) (g ∘ f) := hg.comp_affine_map f.to_affine_map /-- If a function is convex on `s`, it remains convex after a translation. -/ lemma convex_on.translate_right {f : E → β} {s : set E} {a : E} (hf : convex_on s f) : convex_on ((λ z, a + z) ⁻¹' s) (f ∘ (λ z, a + z)) := hf.comp_affine_map $ affine_map.const ℝ E a +ᵥ affine_map.id ℝ E /-- If a function is concave on `s`, it remains concave after a translation. -/ lemma concave_on.translate_right {f : E → β} {s : set E} {a : E} (hf : concave_on s f) : concave_on ((λ z, a + z) ⁻¹' s) (f ∘ (λ z, a + z)) := hf.comp_affine_map $ affine_map.const ℝ E a +ᵥ affine_map.id ℝ E /-- If a function is convex on `s`, it remains convex after a translation. -/ lemma convex_on.translate_left {f : E → β} {s : set E} {a : E} (hf : convex_on s f) : convex_on ((λ z, a + z) ⁻¹' s) (f ∘ (λ z, z + a)) := by simpa only [add_comm] using hf.translate_right /-- If a function is concave on `s`, it remains concave after a translation. -/ lemma concave_on.translate_left {f : E → β} {s : set E} {a : E} (hf : concave_on s f) : concave_on ((λ z, a + z) ⁻¹' s) (f ∘ (λ z, z + a)) := by simpa only [add_comm] using hf.translate_right end functions /-! ### Convex hull -/ section convex_hull variable {t : set E} /-- The convex hull of a set `s` is the minimal convex set that includes `s`. -/ def convex_hull : closure_operator (set E) := closure_operator.mk₃ (λ s, ⋂ (t : set E) (hst : s ⊆ t) (ht : convex t), t) convex (λ s, set.subset_Inter (λ t, set.subset_Inter $ λ hst, set.subset_Inter $ λ ht, hst)) (λ s, convex_Inter $ λ t, convex_Inter $ λ ht, convex_Inter id) (λ s t hst ht, set.Inter_subset_of_subset t $ set.Inter_subset_of_subset hst $ set.Inter_subset _ ht) variable (s) lemma subset_convex_hull : s ⊆ convex_hull s := convex_hull.le_closure s lemma convex_convex_hull : convex (convex_hull s) := closure_operator.closure_mem_mk₃ s variable {s} lemma convex_hull_min (hst : s ⊆ t) (ht : convex t) : convex_hull s ⊆ t := closure_operator.closure_le_mk₃_iff (show s ≤ t, from hst) ht lemma convex_hull_mono (hst : s ⊆ t) : convex_hull s ⊆ convex_hull t := convex_hull.monotone hst lemma convex.convex_hull_eq {s : set E} (hs : convex s) : convex_hull s = s := closure_operator.mem_mk₃_closed hs @[simp] lemma convex_hull_empty : convex_hull (∅ : set E) = ∅ := convex_empty.convex_hull_eq @[simp] lemma convex_hull_empty_iff : convex_hull s = ∅ ↔ s = ∅ := begin split, { intro h, rw [←set.subset_empty_iff, ←h], exact subset_convex_hull _ }, { rintro rfl, exact convex_hull_empty } end @[simp] lemma convex_hull_nonempty_iff : (convex_hull s).nonempty ↔ s.nonempty := begin rw [←ne_empty_iff_nonempty, ←ne_empty_iff_nonempty, ne.def, ne.def], exact not_congr convex_hull_empty_iff, end @[simp] lemma convex_hull_singleton {x : E} : convex_hull ({x} : set E) = {x} := (convex_singleton x).convex_hull_eq lemma convex.convex_remove_iff_not_mem_convex_hull_remove {s : set E} (hs : convex s) (x : E) : convex (s \ {x}) ↔ x ∉ convex_hull (s \ {x}) := begin split, { rintro hsx hx, rw hsx.convex_hull_eq at hx, exact hx.2 (mem_singleton _) }, rintro hx, suffices h : s \ {x} = convex_hull (s \ {x}), { convert convex_convex_hull _ }, exact subset.antisymm (subset_convex_hull _) (λ y hy, ⟨convex_hull_min (diff_subset _ _) hs hy, by { rintro (rfl : y = x), exact hx hy }⟩), end lemma affine_map.image_convex_hull (f : E →ᵃ[ℝ] F) : f '' (convex_hull s) = convex_hull (f '' s) := begin apply set.subset.antisymm, { rw set.image_subset_iff, refine convex_hull_min _ ((convex_convex_hull (⇑f '' s)).affine_preimage f), rw ← set.image_subset_iff, exact subset_convex_hull (f '' s), }, { refine convex_hull_min _ ((convex_convex_hull s).affine_image f), apply set.image_subset, exact subset_convex_hull s, }, end lemma linear_map.image_convex_hull (f : E →ₗ[ℝ] F) : f '' (convex_hull s) = convex_hull (f '' s) := f.to_affine_map.image_convex_hull lemma is_linear_map.image_convex_hull {f : E → F} (hf : is_linear_map ℝ f) : f '' (convex_hull s) = convex_hull (f '' s) := (hf.mk' f).image_convex_hull lemma is_linear_map.convex_hull_image {f : E → F} (hf : is_linear_map ℝ f) (s : set E) : convex_hull (f '' s) = f '' convex_hull s := set.subset.antisymm (convex_hull_min (image_subset _ (subset_convex_hull s)) $ (convex_convex_hull s).is_linear_image hf) (image_subset_iff.2 $ convex_hull_min (image_subset_iff.1 $ subset_convex_hull _) ((convex_convex_hull _).is_linear_preimage hf)) lemma linear_map.convex_hull_image (f : E →ₗ[ℝ] F) (s : set E) : convex_hull (f '' s) = f '' convex_hull s := f.is_linear.convex_hull_image s end convex_hull /-! ### Simplex -/ section simplex variables (ι) [fintype ι] {f : ι → ℝ} /-- The standard simplex in the space of functions `ι → ℝ` is the set of vectors with non-negative coordinates with total sum `1`. -/ def std_simplex (ι : Type*) [fintype ι] : set (ι → ℝ) := {f | (∀ x, 0 ≤ f x) ∧ ∑ x, f x = 1} lemma std_simplex_eq_inter : std_simplex ι = (⋂ x, {f | 0 ≤ f x}) ∩ {f | ∑ x, f x = 1} := by { ext f, simp only [std_simplex, set.mem_inter_eq, set.mem_Inter, set.mem_set_of_eq] } lemma convex_std_simplex : convex (std_simplex ι) := begin refine λ f g hf hg a b ha hb hab, ⟨λ x, _, _⟩, { apply_rules [add_nonneg, mul_nonneg, hf.1, hg.1] }, { erw [finset.sum_add_distrib, ← finset.smul_sum, ← finset.smul_sum, hf.2, hg.2, smul_eq_mul, smul_eq_mul, mul_one, mul_one], exact hab } end variable {ι} lemma ite_eq_mem_std_simplex (i : ι) : (λ j, ite (i = j) (1:ℝ) 0) ∈ std_simplex ι := ⟨λ j, by simp only; split_ifs; norm_num, by rw [finset.sum_ite_eq, if_pos (finset.mem_univ _)]⟩ end simplex