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
03db9d68190e9eac218febcb0cd0ad4c0c83b160
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebraic_geometry/locally_ringed_space.lean
a41496ec741f5c445a3c5a3d4aa59d75c30900b4
[]
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
7,415
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebraic_geometry.sheafed_space import Mathlib.algebra.category.CommRing.limits import Mathlib.algebra.category.CommRing.colimits import Mathlib.algebraic_geometry.stalks import Mathlib.ring_theory.ideal.basic import Mathlib.PostPort universes u_1 l u namespace Mathlib /-! # The category of locally ringed spaces We define (bundled) locally ringed spaces (as `SheafedSpace CommRing` along with the fact that the stalks are local rings), and morphisms between these (morphisms in `SheafedSpace` with `is_local_ring_hom` on the stalk maps). ## Future work * Define the restriction along an open embedding -/ namespace algebraic_geometry /-- A `LocallyRingedSpace` is a topological space equipped with a sheaf of commutative rings such that all the stalks are local rings. A morphism of locally ringed spaces is a morphism of ringed spaces such that the morphims induced on stalks are local ring homomorphisms. -/ structure LocallyRingedSpace extends SheafedSpace CommRing where local_ring : ∀ (x : ↥(PresheafedSpace.carrier (SheafedSpace.to_PresheafedSpace _to_SheafedSpace))), local_ring ↥(Top.presheaf.stalk (PresheafedSpace.presheaf (SheafedSpace.to_PresheafedSpace _to_SheafedSpace)) x) namespace LocallyRingedSpace /-- The underlying topological space of a locally ringed space. -/ def to_Top (X : LocallyRingedSpace) : Top := PresheafedSpace.carrier (SheafedSpace.to_PresheafedSpace (to_SheafedSpace X)) protected instance has_coe_to_sort : has_coe_to_sort LocallyRingedSpace := has_coe_to_sort.mk (Type u) fun (X : LocallyRingedSpace) => ↥(to_Top X) -- PROJECT: how about a typeclass "has_structure_sheaf" to mediate the 𝒪 notation, rather -- than defining it over and over for PresheafedSpace, LRS, Scheme, etc. /-- The structure sheaf of a locally ringed space. -/ def 𝒪 (X : LocallyRingedSpace) : Top.sheaf CommRing (to_Top X) := SheafedSpace.sheaf (to_SheafedSpace X) /-- A morphism of locally ringed spaces is a morphism of ringed spaces such that the morphims induced on stalks are local ring homomorphisms. -/ def hom (X : LocallyRingedSpace) (Y : LocallyRingedSpace) := Subtype fun (f : to_SheafedSpace X ⟶ to_SheafedSpace Y) => ∀ (x : ↥(SheafedSpace.to_PresheafedSpace (to_SheafedSpace X))), is_local_ring_hom (PresheafedSpace.stalk_map f x) protected instance category_theory.has_hom : category_theory.has_hom LocallyRingedSpace := category_theory.has_hom.mk hom theorem hom_ext {X : LocallyRingedSpace} {Y : LocallyRingedSpace} (f : hom X Y) (g : hom X Y) (w : subtype.val f = subtype.val g) : f = g := subtype.eq w /-- The stalk of a locally ringed space, just as a `CommRing`. -/ -- TODO perhaps we should make a bundled `LocalRing` and return one here? -- TODO define `sheaf.stalk` so we can write `X.𝒪.stalk` here? def stalk (X : LocallyRingedSpace) (x : ↥X) : CommRing := Top.presheaf.stalk (PresheafedSpace.presheaf (SheafedSpace.to_PresheafedSpace (to_SheafedSpace X))) x /-- A morphism of locally ringed spaces `f : X ⟶ Y` induces a local ring homomorphism from `Y.stalk (f x)` to `X.stalk x` for any `x : X`. -/ def stalk_map {X : LocallyRingedSpace} {Y : LocallyRingedSpace} (f : X ⟶ Y) (x : ↥X) : stalk Y (coe_fn (PresheafedSpace.hom.base (subtype.val f)) x) ⟶ stalk X x := PresheafedSpace.stalk_map (subtype.val f) x protected instance stalk_map.is_local_ring_hom {X : LocallyRingedSpace} {Y : LocallyRingedSpace} (f : X ⟶ Y) (x : ↥X) : is_local_ring_hom (stalk_map f x) := subtype.property f x /-- The identity morphism on a locally ringed space. -/ def id (X : LocallyRingedSpace) : hom X X := { val := 𝟙, property := sorry } protected instance hom.inhabited (X : LocallyRingedSpace) : Inhabited (hom X X) := { default := id X } /-- Composition of morphisms of locally ringed spaces. -/ def comp {X : LocallyRingedSpace} {Y : LocallyRingedSpace} {Z : LocallyRingedSpace} (f : hom X Y) (g : hom Y Z) : hom X Z := { val := subtype.val f ≫ subtype.val g, property := sorry } /-- The category of locally ringed spaces. -/ protected instance category_theory.category : category_theory.category LocallyRingedSpace := category_theory.category.mk /-- The forgetful functor from `LocallyRingedSpace` to `SheafedSpace CommRing`. -/ def forget_to_SheafedSpace : LocallyRingedSpace ⥤ SheafedSpace CommRing := category_theory.functor.mk (fun (X : LocallyRingedSpace) => to_SheafedSpace X) fun (X Y : LocallyRingedSpace) (f : X ⟶ Y) => subtype.val f protected instance forget_to_SheafedSpace.category_theory.faithful : category_theory.faithful forget_to_SheafedSpace := category_theory.faithful.mk -- PROJECT: once we have `PresheafedSpace.restrict_stalk_iso` -- (that restriction doesn't change stalks) we can uncomment this. /- def restrict {U : Top} (X : LocallyRingedSpace) (f : U ⟶ X.to_Top) (h : open_embedding f) : LocallyRingedSpace := { local_ring := begin intro x, dsimp at *, -- We show that the stalk of the restriction is isomorphic to the original stalk, have := X.to_SheafedSpace.to_PresheafedSpace.restrict_stalk_iso f h x, -- and then transfer `local_ring` across the ring equivalence. apply (this.CommRing_iso_to_ring_equiv).local_ring, -- import data.equiv.transfer_instance apply X.local_ring, end, .. X.to_SheafedSpace.restrict _ f h } -/ /-- The global sections, notated Gamma. -/ def Γ : LocallyRingedSpaceᵒᵖ ⥤ CommRing := category_theory.functor.op forget_to_SheafedSpace ⋙ SheafedSpace.Γ theorem Γ_def : Γ = category_theory.functor.op forget_to_SheafedSpace ⋙ SheafedSpace.Γ := rfl @[simp] theorem Γ_obj (X : LocallyRingedSpaceᵒᵖ) : category_theory.functor.obj Γ X = category_theory.functor.obj (PresheafedSpace.presheaf (SheafedSpace.to_PresheafedSpace (to_SheafedSpace (opposite.unop X)))) (opposite.op ⊤) := rfl theorem Γ_obj_op (X : LocallyRingedSpace) : category_theory.functor.obj Γ (opposite.op X) = category_theory.functor.obj (PresheafedSpace.presheaf (SheafedSpace.to_PresheafedSpace (to_SheafedSpace X))) (opposite.op ⊤) := rfl @[simp] theorem Γ_map {X : LocallyRingedSpaceᵒᵖ} {Y : LocallyRingedSpaceᵒᵖ} (f : X ⟶ Y) : category_theory.functor.map Γ f = category_theory.nat_trans.app (PresheafedSpace.hom.c (subtype.val (category_theory.has_hom.hom.unop f))) (opposite.op ⊤) ≫ category_theory.functor.map (PresheafedSpace.presheaf (SheafedSpace.to_PresheafedSpace (to_SheafedSpace (opposite.unop Y)))) (category_theory.has_hom.hom.op (topological_space.opens.le_map_top (PresheafedSpace.hom.base (subtype.val (category_theory.has_hom.hom.unop f))) ⊤)) := rfl theorem Γ_map_op {X : LocallyRingedSpace} {Y : LocallyRingedSpace} (f : X ⟶ Y) : category_theory.functor.map Γ (category_theory.has_hom.hom.op f) = category_theory.nat_trans.app (PresheafedSpace.hom.c (subtype.val f)) (opposite.op ⊤) ≫ category_theory.functor.map (PresheafedSpace.presheaf (SheafedSpace.to_PresheafedSpace (to_SheafedSpace X))) (category_theory.has_hom.hom.op (topological_space.opens.le_map_top (PresheafedSpace.hom.base (subtype.val f)) ⊤)) := rfl
f394e581695aa32b4b2f44e363768be02e2a5b62
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/show_goal.lean
6480a347a8d96e1b55b50e99f7d1bb3e52112540
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
962
lean
open tactic lemma ex1 (a b c : nat) : a + 0 = 0 + a ∧ 0 + b = b ∧ c + b = b + c := begin repeat {any_goals {constructor}}, show c + b = b + c, { apply add_comm }, show a + 0 = 0 + a, { simp }, show 0 + b = b, { rw [zero_add] } end /- Same example, but the local context of each goal is different -/ lemma ex3 : (∀ a : nat, a + 0 = 0 + a) ∧ (∀ b : nat, 0 + b = b) ∧ (∀ b c : nat, c + b = b + c) := begin repeat {any_goals {constructor}}, all_goals {intros}, show c + b = b + c, { apply add_comm }, show a + 0 = 0 + a, { simp }, show 0 + b = b, { rw [zero_add] } end /- Same example, but the local context of each goal is different -/ lemma ex4 : (∀ a : nat, a + 0 = 0 + a) ∧ (∀ b : nat, 0 + b = b) ∧ (∀ b c : nat, c + b = b + c) := begin repeat {any_goals {constructor}}, all_goals {intros}, show c + b = _, { apply add_comm }, show a + _ = 0 + a, { simp }, show _ = b, { rw [zero_add] } end
80ccdeb15ea30a3ec96cb8e8ff0fa1e927a109da
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/finset/sym.lean
83c74fe19d923bf40fe8857be4a8122c7dfe9e30
[ "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
5,819
lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.finset.prod import data.sym.sym2 /-! # Symmetric powers of a finset This file defines the symmetric powers of a finset as `finset (sym α n)` and `finset (sym2 α)`. ## Main declarations * `finset.sym`: The symmetric power of a finset. `s.sym n` is all the multisets of cardinality `n` whose elements are in `s`. * `finset.sym2`: The symmetric square of a finset. `s.sym2` is all the pairs whose elements are in `s`. ## TODO `finset.sym` forms a Galois connection between `finset α` and `finset (sym α n)`. Similar for `finset.sym2`. -/ namespace finset variables {α : Type*} [decidable_eq α] {s t : finset α} {a b : α} lemma is_diag_mk_of_mem_diag {a : α × α} (h : a ∈ s.diag) : sym2.is_diag ⟦a⟧ := (sym2.is_diag_iff_proj_eq _).2 ((mem_diag _ _).1 h).2 lemma not_is_diag_mk_of_mem_off_diag {a : α × α} (h : a ∈ s.off_diag) : ¬ sym2.is_diag ⟦a⟧ := by { rw sym2.is_diag_iff_proj_eq, exact ((mem_off_diag _ _).1 h).2.2 } section sym2 variables {m : sym2 α} /-- Lifts a finset to `sym2 α`. `s.sym2` is the finset of all pairs with elements in `s`. -/ protected def sym2 (s : finset α) : finset (sym2 α) := (s ×ˢ s).image quotient.mk @[simp] lemma mem_sym2_iff : m ∈ s.sym2 ↔ ∀ a ∈ m, a ∈ s := begin refine mem_image.trans ⟨_, λ h, ⟨m.out, mem_product.2 ⟨h _ m.out_fst_mem, h _ m.out_snd_mem⟩, m.out_eq⟩⟩, rintro ⟨⟨a, b⟩, h, rfl⟩, rw sym2.ball, rwa mem_product at h, end lemma mk_mem_sym2_iff : ⟦(a, b)⟧ ∈ s.sym2 ↔ a ∈ s ∧ b ∈ s := by rw [mem_sym2_iff, sym2.ball] @[simp] lemma sym2_empty : (∅ : finset α).sym2 = ∅ := rfl @[simp] lemma sym2_eq_empty : s.sym2 = ∅ ↔ s = ∅ := by rw [finset.sym2, image_eq_empty, product_eq_empty, or_self] @[simp] lemma sym2_nonempty : s.sym2.nonempty ↔ s.nonempty := by rw [finset.sym2, nonempty.image_iff, nonempty_product, and_self] alias sym2_nonempty ↔ _ nonempty.sym2 attribute [protected] nonempty.sym2 @[simp] lemma sym2_univ [fintype α] : (univ : finset α).sym2 = univ := rfl @[simp] lemma sym2_singleton (a : α) : ({a} : finset α).sym2 = {sym2.diag a} := by rw [finset.sym2, singleton_product_singleton, image_singleton, sym2.diag] @[simp] lemma diag_mem_sym2_iff : sym2.diag a ∈ s.sym2 ↔ a ∈ s := mk_mem_sym2_iff.trans $ and_self _ @[simp] lemma sym2_mono (h : s ⊆ t) : s.sym2 ⊆ t.sym2 := λ m he, mem_sym2_iff.2 $ λ a ha, h $ mem_sym2_iff.1 he _ ha lemma image_diag_union_image_off_diag : s.diag.image quotient.mk ∪ s.off_diag.image quotient.mk = s.sym2 := by { rw [←image_union, diag_union_off_diag], refl } end sym2 section sym variables {n : ℕ} {m : sym α n} /-- Lifts a finset to `sym α n`. `s.sym n` is the finset of all unordered tuples of cardinality `n` with elements in `s`. -/ protected def sym (s : finset α) : Π n, finset (sym α n) | 0 := {∅} | (n + 1) := s.sup $ λ a, (sym n).image $ _root_.sym.cons a @[simp] lemma sym_zero : s.sym 0 = {∅} := rfl @[simp] lemma sym_succ : s.sym (n + 1) = s.sup (λ a, (s.sym n).image $ sym.cons a) := rfl @[simp] lemma mem_sym_iff : m ∈ s.sym n ↔ ∀ a ∈ m, a ∈ s := begin induction n with n ih, { refine mem_singleton.trans ⟨_, λ _, sym.eq_nil_of_card_zero _⟩, rintro rfl, exact λ a ha, ha.elim }, refine mem_sup.trans ⟨_, λ h, _⟩, { rintro ⟨a, ha, he⟩ b hb, rw mem_image at he, obtain ⟨m, he, rfl⟩ := he, rw sym.mem_cons at hb, obtain rfl | hb := hb, { exact ha }, { exact ih.1 he _ hb } }, { obtain ⟨a, m, rfl⟩ := m.exists_eq_cons_of_succ, exact ⟨a, h _ $ sym.mem_cons_self _ _, mem_image_of_mem _ $ ih.2 $ λ b hb, h _ $ sym.mem_cons_of_mem hb⟩ } end @[simp] lemma sym_empty (n : ℕ) : (∅ : finset α).sym (n + 1) = ∅ := rfl lemma repeat_mem_sym (ha : a ∈ s) (n : ℕ) : sym.repeat a n ∈ s.sym n := mem_sym_iff.2 $ λ b hb, by rwa (sym.mem_repeat.1 hb).2 protected lemma nonempty.sym (h : s.nonempty) (n : ℕ) : (s.sym n).nonempty := let ⟨a, ha⟩ := h in ⟨_, repeat_mem_sym ha n⟩ @[simp] lemma sym_singleton (a : α) (n : ℕ) : ({a} : finset α).sym n = {sym.repeat a n} := eq_singleton_iff_nonempty_unique_mem.2 ⟨(singleton_nonempty _).sym n, λ s hs, sym.eq_repeat_iff.2 $ λ b hb, eq_of_mem_singleton $ mem_sym_iff.1 hs _ hb⟩ lemma eq_empty_of_sym_eq_empty (h : s.sym n = ∅) : s = ∅ := begin rw ←not_nonempty_iff_eq_empty at ⊢ h, exact λ hs, h (hs.sym _), end @[simp] lemma sym_eq_empty : s.sym n = ∅ ↔ n ≠ 0 ∧ s = ∅ := begin cases n, { exact iff_of_false (singleton_ne_empty _) (λ h, (h.1 rfl).elim) }, { refine ⟨λ h, ⟨n.succ_ne_zero, eq_empty_of_sym_eq_empty h⟩, _⟩, rintro ⟨_, rfl⟩, exact sym_empty _ } end @[simp] lemma sym_nonempty : (s.sym n).nonempty ↔ n = 0 ∨ s.nonempty := by simp_rw [nonempty_iff_ne_empty, ne.def, sym_eq_empty, not_and_distrib, not_ne_iff] alias sym2_nonempty ↔ _ nonempty.sym2 attribute [protected] nonempty.sym2 @[simp] lemma sym_univ [fintype α] (n : ℕ) : (univ : finset α).sym n = univ := eq_univ_iff_forall.2 $ λ s, mem_sym_iff.2 $ λ a _, mem_univ _ @[simp] lemma sym_mono (h : s ⊆ t) (n : ℕ): s.sym n ⊆ t.sym n := λ m hm, mem_sym_iff.2 $ λ a ha, h $ mem_sym_iff.1 hm _ ha @[simp] lemma sym_inter (s t : finset α) (n : ℕ) : (s ∩ t).sym n = s.sym n ∩ t.sym n := by { ext m, simp only [mem_inter, mem_sym_iff, imp_and_distrib, forall_and_distrib] } @[simp] lemma sym_union (s t : finset α) (n : ℕ) : s.sym n ∪ t.sym n ⊆ (s ∪ t).sym n := union_subset (sym_mono (subset_union_left s t) n) (sym_mono (subset_union_right s t) n) end sym end finset
d4d6ba81785cbda7d7364a1c868f558bf91bde91
da23b545e1653cafd4ab88b3a42b9115a0b1355f
/src/tidy/rewrite_search/engine.lean
83bd12ffd777244f1832fa64720891e77d413753
[]
no_license
minchaowu/lean-tidy
137f5058896e0e81dae84bf8d02b74101d21677a
2d4c52d66cf07c59f8746e405ba861b4fa0e3835
refs/heads/master
1,585,283,406,120
1,535,094,033,000
1,535,094,033,000
145,945,792
0
0
null
null
null
null
UTF-8
Lean
false
false
20,167
lean
import data.list import data.option import tidy.lib import tidy.pretty_print import tidy.rewrite_all open tactic namespace tidy.rewrite_search inductive how | rewrite (rule_index : ℕ) (side : side) (location : ℕ) : how | defeq meta inductive search_result | success (proof : expr) (steps : list how) : search_result | failure (message : string) : search_result -- meta def bound_numeric := ℕ inductive bound_progress (β : Type) | exactly : ℕ → β → bound_progress | at_least : ℕ → β → bound_progress open bound_progress def bound_progress.bound {β : Type} : bound_progress β → ℕ | (exactly n _) := n | (at_least n _) := n def bound_progress.sure {β : Type} : bound_progress β → bool | (exactly _ _) := tt | (at_least _ _) := ff def bound_progress.to_string {β : Type} : bound_progress β → string | (exactly n _) := "= " ++ to_string n | (at_least n _) := "≥ " ++ to_string n def vertex_ref : Type := ℕ def vertex_ref_from_nat (r : ℕ) : vertex_ref := r def vertex_ref.to_nat (r : vertex_ref) : ℕ := r def vertex_ref.to_string (r : vertex_ref) : string := to_string r.to_nat def vertex_ref.next (r : vertex_ref) : vertex_ref := vertex_ref_from_nat (r + 1) def mk_vertex_ref_null : vertex_ref := vertex_ref_from_nat 0x8FFFFFFF def mk_vertex_ref_first : vertex_ref := vertex_ref_from_nat 0 meta structure edge := (f t : vertex_ref) (proof : expr) (how : how) meta structure vertex := (id : vertex_ref) (exp : expr) (pp : string) (tokens : list string) (root : bool) (visited : bool) (s : side) (parent : option edge) (adj : list edge) meta def vertex.same_side (a b : vertex) : bool := a.s = b.s meta def vertex.to_string (v : vertex) : string := v.s.to_string ++ v.pp meta def null_expr : expr := default expr meta def mk_null_vertex : vertex := ⟨ mk_vertex_ref_null, null_expr, "__NULLEXPR", [], ff, ff, side.L, none, [] ⟩ meta instance : inhabited vertex := ⟨mk_null_vertex⟩ structure dist_estimate (state_type : Type) := (l r : vertex_ref) (bnd : bound_progress state_type) def dist_estimate.side {α : Type} (de : dist_estimate α) (s : side) : vertex_ref := match s with | side.L := de.l | side.R := de.r end def dist_estimate.to_string {α : Type} (de : dist_estimate α) : string := (de.l.to_string) ++ "-" ++ (de.r.to_string) ++ "Δ" ++ de.bnd.to_string meta def init_bound_fn (β : Type) := vertex → vertex → bound_progress β meta def improve_estimate_fn (β : Type) := ℕ → vertex → vertex → bound_progress β → bound_progress β meta inductive status | going : ℕ → status | done : edge → status | abort : string → status meta def status.next_itr : status → status | (status.going n) := status.going (n + 1) | other := other meta structure global_state (α β : Type) := (next_id : vertex_ref) (vertices : list vertex) -- FIXME use array (estimates : list (dist_estimate β)) (interesting_pairs : list (dist_estimate β)) (solving_edge : option edge) (internal_strat_state : α) namespace global_state variables {α β : Type} (g : global_state α β) meta def mutate_strategy (new_state : α) : global_state α β := { g with internal_strat_state := new_state } -- Retrieve the vertex with the given ref, or the null vertex if it is not -- present. meta def get_vertex (r : vertex_ref) : vertex := list.at g.vertices r meta def set_vertex (v : vertex) : (global_state α β) := { g with vertices := list.set_at g.vertices v.id v } meta def get_endpoints (e : edge) : vertex × vertex := (g.get_vertex e.f, g.get_vertex e.t) meta def get_estimate_verts (de : dist_estimate β) : vertex × vertex := (g.get_vertex de.l, g.get_vertex de.r) -- Forcibly add a new vertex to the vertex table. Probably should never be -- called by a strategy and add_vertex to should used instead. meta def do_alloc_vertex (e : expr) (root : bool) (s : side) : tactic (global_state α β × vertex) := do (pp, tokens) ← tokenise_expr e, let v : vertex := ⟨ g.next_id, e, pp, tokens, root, ff, s, none, [] ⟩, return ({ g with next_id := g.next_id.next, vertices := g.vertices.concat v }, v) -- Forcibly add a new pair to the interesting pair list. Probably should never be -- called by a strategy and add_vertex to should used instead. meta def do_alloc_pair (de : dist_estimate β) : global_state α β := {g with estimates := g.estimates.concat de, interesting_pairs := g.interesting_pairs.concat de} meta def remove_interesting_pair (de : dist_estimate β) : global_state α β := let new := g.interesting_pairs.erase_first_such_that (λ de', de'.l = de.l ∧ de'.r = de.r) in {g with interesting_pairs := new} private meta def find_vertex_aux (pp : string) : list vertex → option vertex | [] := none | (a :: rest) := if a.pp = pp then some a else find_vertex_aux rest -- Find the vertex with the given (e : expr), or return the null verterx if not -- found. meta def find_vertex (e : expr) : tactic (option vertex) := do pp ← pretty_print e, return (find_vertex_aux pp g.vertices) private meta def find_pair_aux {β : Type} (l r : vertex_ref) : list (dist_estimate β) → option (dist_estimate β) | [] := none | (a :: rest) := if (a.l = l ∧ a.r = r) ∨ (a.l = r ∧ a.r = l) then some a else find_pair_aux rest -- Find the vertex with the given (e : expr), or return the null verterx if not -- found. meta def find_pair (l r : vertex_ref) : option (dist_estimate β) := find_pair_aux l r g.estimates meta def register_solved (e : edge) : global_state α β := { g with solving_edge := some e } meta def add_adj (v : vertex) (e : edge) : global_state α β × vertex := let v : vertex := { v with adj := v.adj.concat e } in (g.set_vertex v, v) meta def publish_parent (f t : vertex) (e : edge) : global_state α β × vertex := if t.root then (g, t) else match t.parent with | some parent := (g, t) | none := let t : vertex := { t with parent := some e } in (g.set_vertex t, t) end meta def mark_vertex_visited (vr : vertex_ref) : global_state α β := g.set_vertex { g.get_vertex vr with visited := tt} -- updates rival's estimate trying to beat candidate's estimate, stopping if we do or we can't -- go any further. We return true if we were able to beat candidate. private meta def try_to_beat (fn : improve_estimate_fn β) (candidate rival : bound_progress β) (rival_l rival_r : vertex) : bound_progress β × bool := let m := candidate.bound in match rival with | exactly n _ := (rival, n <= m) | at_least n p := let attempt := fn m rival_l rival_r rival in (attempt, attempt.bound < m) end -- First is closer private meta def sort_most_interesting (fn : improve_estimate_fn β) : dist_estimate β → dist_estimate β → dist_estimate β × dist_estimate β | a b := do match try_to_beat fn a.bnd b.bnd (g.get_vertex b.l) (g.get_vertex b.r) with -- b is guarenteed closer, so return it: | (new_b, tt) := ({ b with bnd := new_b }, a) -- otherwise: | (new_b, ff) := match a.bnd with -- b is further than the current estimate for a and the estimate for a is exact: | exactly k _ := (a, { b with bnd := new_b }) -- or, b is futher than the current estimate for a but a might actually be worse, so check: | at_least k p := sort_most_interesting { b with bnd := new_b } a end end private meta def find_most_interesting_aux (fn : improve_estimate_fn β) : dist_estimate β → list (dist_estimate β) → list (dist_estimate β) → dist_estimate β × list (dist_estimate β) | current_best seen [] := (current_best, seen) | current_best seen (a :: rest) := let (better, worse) := sort_most_interesting g fn current_best a in find_most_interesting_aux better (worse :: seen) rest meta def find_most_interesting (fn : improve_estimate_fn β) : global_state α β := match g.interesting_pairs with | [] := g | (a :: rest) := let (best, others) := find_most_interesting_aux g fn a [] rest in { g with interesting_pairs := (best :: others) } end end global_state meta def refresh_fn (α β : Type) : Type := global_state α β → global_state α β meta inductive strategy_action {α β : Type} | examine : dist_estimate β → strategy_action | refresh : refresh_fn α β → strategy_action | abort : string → strategy_action open strategy_action meta def step_fn (α β : Type) : Type := global_state α β → ℕ → global_state α β × (@strategy_action α β) meta structure strategy (α β : Type) := (init : α) (step : step_fn α β) (init_bound : init_bound_fn β) (improve_estimate_over : improve_estimate_fn β) inductive init_result (α : Type) | success : α → init_result | failure : string → init_result meta structure tracer (γ : Type) := (init : tactic (init_result γ)) (publish_vertex : γ → vertex → tactic unit) (publish_edge : γ → edge → tactic unit) (publish_pair : γ → vertex_ref → vertex_ref → tactic unit) (publish_visited : γ → vertex → tactic unit) (publish_finished : γ → list edge → tactic unit) (dump : γ → string → tactic unit) (pause : γ → tactic unit) meta structure tracer_state (γ : Type) := (tr : tracer γ) (internal : γ) -- FIXME doesn't `unify` do exactly this?? meta def attempt_refl (lhs rhs : expr) : tactic expr := lock_tactic_state $ do gs ← get_goals, m ← to_expr ``(%%lhs = %%rhs) >>= mk_meta_var, set_goals [m], refl ← mk_const `eq.refl, tactic.apply_core refl {new_goals := new_goals.non_dep_only}, instantiate_mvars m meta def pick_default_tracer : tactic unit := `[exact tidy.rewrite_search.tracer.unit_tracer] meta def pick_default_strategy : tactic unit := `[exact tidy.rewrite_search.strategy.edit_distance_strategy] meta structure config (α β γ : Type) extends rewrite_all_cfg := (strategy : strategy α β . pick_default_strategy) (view : tracer γ . pick_default_tracer) (trace : bool := ff) (trace_summary : bool := ff) (trace_result : bool := ff) (exhaustive : bool := ff) meta structure inst (α β γ : Type) := (conf : config α β γ) (rs : list (expr × bool)) (g : global_state α β) (tr_state : γ) namespace inst variables {α β γ : Type} (i : inst α β γ) meta def mutate (g : global_state α β) : inst α β γ:= { i with g := g} meta def trace {δ : Type} [has_to_tactic_format δ] (s : δ) : tactic unit := if i.conf.trace then tactic.trace s else tactic.skip meta def tracer_vertex_added (v : vertex) : tactic unit := do --FIXME guard all of these with an if (to prevent pointless string building) i.trace format!"addV({v.id.to_string}): {v.pp}", i.conf.view.publish_vertex i.tr_state v meta def tracer_edge_added (e : edge) : tactic unit := do --FIXME guard all of these with an if (to prevent pointless string building) i.trace format!"addE: {e.f.to_string}→{e.t.to_string}", i.conf.view.publish_edge i.tr_state e meta def tracer_pair_added (l r : vertex_ref) : tactic unit := do --FIXME guard all of these with an if (to prevent pointless string building) i.trace format!"addP: {l.to_string}→{r.to_string}", i.conf.view.publish_pair i.tr_state l r meta def tracer_dump {δ : Type} [has_to_tactic_format δ] (s : δ) : tactic unit := do --FIXME guard all of these with an if (to prevent pointless string building) fmt ← has_to_tactic_format.to_tactic_format s, str ← pure (to_string fmt), i.trace str, i.conf.view.dump i.tr_state str meta def tracer_visited (v : vertex) : tactic unit := i.conf.view.publish_visited i.tr_state v meta def tracer_search_finished (es : list edge) : tactic unit := do --FIXME guard all of these with an if (to prevent pointless string building) i.trace format!"DONE!", i.conf.view.publish_finished i.tr_state es meta def dump_rws : list (expr × expr × ℕ × ℕ) → tactic unit | [] := tactic.skip | (a :: rest) := do tactic.trace format!"→{a.1}\nPF:{a.2}", dump_rws rest meta def dump_vertices : list vertex → tactic unit | [] := tactic.skip | (a :: rest) := do let pfx : string := match a.parent with | none := "?" | some p := p.f.to_string end, tracer_dump i (to_string format!"V{a.id.to_string}:{a.pp}<-{pfx}:{a.root}"), dump_vertices rest meta def dump_edges : list edge → tactic unit | [] := tactic.skip | (a :: rest) := do let (vf, vt) := i.g.get_endpoints a, tracer_dump i format!"E:{vf.pp}→{vt.pp}", dump_edges rest meta def dump_estimates : list (dist_estimate β) → tactic unit | [] := tactic.trace "" | (a :: rest) := do tracer_dump i format!"I{(i.g.get_vertex a.l).pp}-{(i.g.get_vertex a.r).pp}:{a.bnd.bound}", dump_estimates rest -- Look up the given vertex associated to (e : expr), or create it if it is -- not already present. meta def add_vertex_aux (e : expr) (root : bool) (s : side) : tactic (inst α β γ × vertex) := do maybe_v ← i.g.find_vertex e, match maybe_v with | none := do (g, v) ← i.g.do_alloc_vertex e root s, tracer_vertex_added i v, return (i.mutate g, v) | (some v) := return (i, v) end meta def add_vertex (e : expr) (s : side) := i.add_vertex_aux e ff s meta def add_root_vertex (e : expr) (s : side) := i.add_vertex_aux e tt s meta def add_edge (f t : vertex) (proof : expr) (how : how) : tactic (inst α β γ × edge) := do let new_edge : edge := ⟨ f.id, t.id, proof, how ⟩, tracer_edge_added i new_edge, let g := i.g, let (g, f) := g.add_adj f new_edge, let (g, t) := g.add_adj t new_edge, let (g, t) := g.publish_parent f t new_edge, if ¬(vertex.same_side f t) then return (i.mutate (g.register_solved new_edge), new_edge) else return (i.mutate g, new_edge) -- Add an "interesting pair" to the global state meta def add_pair (l r : vertex) : tactic (inst α β γ) := do tracer_pair_added i l.id r.id, match i.g.find_pair l.id r.id with | some de := return i | none := return (i.mutate (i.g.do_alloc_pair ⟨ l.id, r.id, i.conf.strategy.init_bound l r ⟩)) end meta def remove_interesting_pair (de : dist_estimate β) : inst α β γ := i.mutate (i.g.remove_interesting_pair de) meta def find_most_interesting : inst α β γ := i.mutate (i.g.find_most_interesting i.conf.strategy.improve_estimate_over) meta def process_new_rewrites (f : vertex) : inst α β γ → list (expr × expr × how) → tactic (inst α β γ × list vertex × list edge) | i [] := return (i, [], []) | i ((new_expr, prf, how) :: rest) := do (i, v) ← i.add_vertex new_expr f.s, (i, e) ← i.add_edge f v prf how, (i, vs, es) ← process_new_rewrites i rest, return (i, (v :: vs), (e :: es)) meta def add_new_interestings (v : vertex) : inst α β γ → list vertex → tactic (inst α β γ) | i [] := return i | i (a :: rest) := do i ← i.add_pair v a, add_new_interestings i rest /-- Check if `eq.refl _` suffices to prove the two sides are equal. -/ meta def unify (de : dist_estimate β) : tactic (inst α β γ) := do let (lhs, rhs) := i.g.get_estimate_verts de, prf ← attempt_refl lhs.exp rhs.exp, -- success! we're done (i, _) ← i.add_edge lhs rhs prf how.defeq, return i meta def find_neighbours (v : vertex) : tactic ((inst α β γ) × (list vertex)) := do match v.visited with | tt := do let vertices := v.adj.map (λ e, i.g.get_vertex e.t), return (i, vertices) | ff := do all_rws ← all_rewrites_list i.rs ff v.exp i.conf.to_rewrite_all_cfg, let all_rws := all_rws.map (λ t, (t.1, t.2.1, how.rewrite t.2.2.1 v.s t.2.2.2)), (i, adjacent_vertices, _) ← i.process_new_rewrites v all_rws, i ← pure (i.mutate (i.g.mark_vertex_visited v.id)), i.tracer_visited v, return (i, adjacent_vertices) end -- My job is to examine the specified vertex and blow it up meta def examine_one (de : dist_estimate β) (s : side) : tactic (inst α β γ) := do let v := i.g.get_vertex (de.side s), (i, nbhd) ← i.find_neighbours v, i ← i.add_new_interestings (i.g.get_vertex (de.side s.other)) nbhd, return i meta def examine_both (de : dist_estimate β) : tactic (inst α β γ ) := do i ← i.examine_one de side.L, i ← i.examine_one de side.R, -- FIXME this feels a bit silly: isn't `de` always the head of the list? pure (i.remove_interesting_pair de).find_most_interesting meta def step_once (itr : ℕ) : tactic (inst α β γ × status) := match i.g.solving_edge with | some e := return (i, status.done e) | none := let (g, action) := i.conf.strategy.step i.g itr in let i := i.mutate g in match action with | examine de := do (lhs, rhs) ← pure (g.get_estimate_verts de), i.trace format!"examine({lhs.id.to_nat}, {rhs.id.to_nat}) distance {de.bnd.to_string}: ({lhs.pp}) = ({rhs.pp})", i ← (i.unify de) <|> (i.examine_both de), return (i, status.going (itr + 1)) | refresh ref_fn := do i.trace format!"refresh", return (i.mutate (ref_fn i.g), status.going (itr + 1)) | abort reason := do i.trace format!"abort: {reason}", return (i, status.abort reason) end end -- Find a vertex we haven't visited, and visit it. The bool is true if there might -- be any more unvisited vertices. meta def exhaust_one : list vertex → tactic (inst α β γ × bool) | [] := return (i, ff) | (v :: rest) := if v.visited then exhaust_one rest else do (i, _) ← i.find_neighbours v, return (i, tt) meta def exhaust_all : inst α β γ → tactic (inst α β γ) := λ i, do (i, more_left) ← i.exhaust_one i.g.vertices, if more_left then i.exhaust_all else return i meta def backtrack : vertex → option edge → tactic (option expr × list edge) | v e := match e with | none := return (none, []) | (some e) := do let w : vertex := i.g.get_vertex e.f, (prf_o, edges) ← backtrack w w.parent, match prf_o with | none := return (some e.proof, [e]) | (some prf) := do new_prf ← tactic.mk_eq_trans prf e.proof, return (some new_prf, e :: edges) end end meta def combine_proofs : option expr → option expr → tactic expr | none none := fail "unreachable code!" | (some a) none := return a | none (some b) := mk_eq_symm b | (some a) (some b) := do b' ← mk_eq_symm b, mk_eq_trans a b' meta def solve_goal (e : edge) : tactic (expr × list edge) := do let (from_vertex, to_vertex) := i.g.get_endpoints e, (from_prf, from_edges) ← i.backtrack to_vertex e, (to_prf, to_edges) ← i.backtrack to_vertex to_vertex.parent, proof ← match from_vertex.s with | side.L := combine_proofs from_prf to_prf | side.R := combine_proofs to_prf from_prf end, let edges := match from_vertex.s with | side.L := (to_edges ++ from_edges).reverse | side.R := (from_edges ++ to_edges).reverse end, -- This must be called before i.exhaust_all i.tracer_search_finished edges, i.trace from_vertex.to_string, i.trace to_vertex.to_string, if i.conf.trace_summary then do let saw := i.g.vertices.length, let visited := (i.g.vertices.filter (λ v : vertex, v.visited)).length, name ← decl_name, tactic.trace format!"rewrite_search (saw/visited/used) {saw}/{visited}/{edges.length} expressions during proof of {name}" else skip, i ← if i.conf.exhaustive then i.exhaust_all else pure i, return (proof, edges) meta def search_until_solved_aux : inst α β γ → ℕ → tactic search_result | i itr := do (i, s) ← i.step_once itr, match s with | status.going k := search_until_solved_aux i (itr + 1) | status.abort r := return (search_result.failure ("aborted: " ++ r)) | status.done e := do (proof, edges) ← i.solve_goal e, return (search_result.success proof (edges.map edge.how)) end meta def search_until_solved : tactic search_result := i.search_until_solved_aux 0 end inst end tidy.rewrite_search
8c1281f620e22e68e650d5f2a15793f4afc474c5
367134ba5a65885e863bdc4507601606690974c1
/src/data/multiset/basic.lean
75171e968cfa86a2b5c928ba297d967855f71c61
[ "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
93,057
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import data.list.perm import algebra.group_power /-! # Multisets These are implemented as the quotient of a list by permutations. ## Notation We define the global infix notation `::ₘ` for `multiset.cons`. -/ open list subtype nat variables {α : Type*} {β : Type*} {γ : Type*} /-- `multiset α` is the quotient of `list α` by list permutation. The result is a type of finite sets with duplicates allowed. -/ def {u} multiset (α : Type u) : Type u := quotient (list.is_setoid α) namespace multiset instance : has_coe (list α) (multiset α) := ⟨quot.mk _⟩ @[simp] theorem quot_mk_to_coe (l : list α) : @eq (multiset α) ⟦l⟧ l := rfl @[simp] theorem quot_mk_to_coe' (l : list α) : @eq (multiset α) (quot.mk (≈) l) l := rfl @[simp] theorem quot_mk_to_coe'' (l : list α) : @eq (multiset α) (quot.mk setoid.r l) l := rfl @[simp] theorem coe_eq_coe {l₁ l₂ : list α} : (l₁ : multiset α) = l₂ ↔ l₁ ~ l₂ := quotient.eq instance has_decidable_eq [decidable_eq α] : decidable_eq (multiset α) | s₁ s₂ := quotient.rec_on_subsingleton₂ s₁ s₂ $ λ l₁ l₂, decidable_of_iff' _ quotient.eq /-- defines a size for a multiset by referring to the size of the underlying list -/ protected def sizeof [has_sizeof α] (s : multiset α) : ℕ := quot.lift_on s sizeof $ λ l₁ l₂, perm.sizeof_eq_sizeof instance has_sizeof [has_sizeof α] : has_sizeof (multiset α) := ⟨multiset.sizeof⟩ /-! ### Empty multiset -/ /-- `0 : multiset α` is the empty set -/ protected def zero : multiset α := @nil α instance : has_zero (multiset α) := ⟨multiset.zero⟩ instance : has_emptyc (multiset α) := ⟨0⟩ instance : inhabited (multiset α) := ⟨0⟩ @[simp] theorem coe_nil_eq_zero : (@nil α : multiset α) = 0 := rfl @[simp] theorem empty_eq_zero : (∅ : multiset α) = 0 := rfl theorem coe_eq_zero (l : list α) : (l : multiset α) = 0 ↔ l = [] := iff.trans coe_eq_coe perm_nil /-! ### `multiset.cons` -/ /-- `cons a s` is the multiset which contains `s` plus one more instance of `a`. -/ def cons (a : α) (s : multiset α) : multiset α := quot.lift_on s (λ l, (a :: l : multiset α)) (λ l₁ l₂ p, quot.sound (p.cons a)) infixr ` ::ₘ `:67 := multiset.cons instance : has_insert α (multiset α) := ⟨cons⟩ @[simp] theorem insert_eq_cons (a : α) (s : multiset α) : insert a s = a ::ₘ s := rfl @[simp] theorem cons_coe (a : α) (l : list α) : (a ::ₘ l : multiset α) = (a::l : list α) := rfl theorem singleton_coe (a : α) : (a ::ₘ 0 : multiset α) = ([a] : list α) := rfl @[simp] theorem cons_inj_left {a b : α} (s : multiset α) : a ::ₘ s = b ::ₘ s ↔ a = b := ⟨quot.induction_on s $ λ l e, have [a] ++ l ~ [b] ++ l, from quotient.exact e, singleton_perm_singleton.1 $ (perm_append_right_iff _).1 this, congr_arg _⟩ @[simp] theorem cons_inj_right (a : α) : ∀{s t : multiset α}, a ::ₘ s = a ::ₘ t ↔ s = t := by rintros ⟨l₁⟩ ⟨l₂⟩; simp @[recursor 5] protected theorem induction {p : multiset α → Prop} (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a ::ₘ s)) : ∀s, p s := by rintros ⟨l⟩; induction l with _ _ ih; [exact h₁, exact h₂ ih] @[elab_as_eliminator] protected theorem induction_on {p : multiset α → Prop} (s : multiset α) (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a ::ₘ s)) : p s := multiset.induction h₁ h₂ s theorem cons_swap (a b : α) (s : multiset α) : a ::ₘ b ::ₘ s = b ::ₘ a ::ₘ s := quot.induction_on s $ λ l, quotient.sound $ perm.swap _ _ _ section rec variables {C : multiset α → Sort*} /-- Dependent recursor on multisets. TODO: should be @[recursor 6], but then the definition of `multiset.pi` fails with a stack overflow in `whnf`. -/ protected def rec (C_0 : C 0) (C_cons : Πa m, C m → C (a ::ₘ m)) (C_cons_heq : ∀ a a' m b, C_cons a (a' ::ₘ m) (C_cons a' m b) == C_cons a' (a ::ₘ m) (C_cons a m b)) (m : multiset α) : C m := quotient.hrec_on m (@list.rec α (λl, C ⟦l⟧) C_0 (λa l b, C_cons a ⟦l⟧ b)) $ assume l l' h, h.rec_heq (assume a l l' b b' hl, have ⟦l⟧ = ⟦l'⟧, from quot.sound hl, by cc) (assume a a' l, C_cons_heq a a' ⟦l⟧) @[elab_as_eliminator] protected def rec_on (m : multiset α) (C_0 : C 0) (C_cons : Πa m, C m → C (a ::ₘ m)) (C_cons_heq : ∀a a' m b, C_cons a (a' ::ₘ m) (C_cons a' m b) == C_cons a' (a ::ₘ m) (C_cons a m b)) : C m := multiset.rec C_0 C_cons C_cons_heq m variables {C_0 : C 0} {C_cons : Πa m, C m → C (a ::ₘ m)} {C_cons_heq : ∀a a' m b, C_cons a (a' ::ₘ m) (C_cons a' m b) == C_cons a' (a ::ₘ m) (C_cons a m b)} @[simp] lemma rec_on_0 : @multiset.rec_on α C (0:multiset α) C_0 C_cons C_cons_heq = C_0 := rfl @[simp] lemma rec_on_cons (a : α) (m : multiset α) : (a ::ₘ m).rec_on C_0 C_cons C_cons_heq = C_cons a m (m.rec_on C_0 C_cons C_cons_heq) := quotient.induction_on m $ assume l, rfl end rec section mem /-- `a ∈ s` means that `a` has nonzero multiplicity in `s`. -/ def mem (a : α) (s : multiset α) : Prop := quot.lift_on s (λ l, a ∈ l) (λ l₁ l₂ (e : l₁ ~ l₂), propext $ e.mem_iff) instance : has_mem α (multiset α) := ⟨mem⟩ @[simp] lemma mem_coe {a : α} {l : list α} : a ∈ (l : multiset α) ↔ a ∈ l := iff.rfl instance decidable_mem [decidable_eq α] (a : α) (s : multiset α) : decidable (a ∈ s) := quot.rec_on_subsingleton s $ list.decidable_mem a @[simp] theorem mem_cons {a b : α} {s : multiset α} : a ∈ b ::ₘ s ↔ a = b ∨ a ∈ s := quot.induction_on s $ λ l, iff.rfl lemma mem_cons_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ b ::ₘ s := mem_cons.2 $ or.inr h @[simp] theorem mem_cons_self (a : α) (s : multiset α) : a ∈ a ::ₘ s := mem_cons.2 (or.inl rfl) theorem forall_mem_cons {p : α → Prop} {a : α} {s : multiset α} : (∀ x ∈ (a ::ₘ s), p x) ↔ p a ∧ ∀ x ∈ s, p x := quotient.induction_on' s $ λ L, list.forall_mem_cons theorem exists_cons_of_mem {s : multiset α} {a : α} : a ∈ s → ∃ t, s = a ::ₘ t := quot.induction_on s $ λ l (h : a ∈ l), let ⟨l₁, l₂, e⟩ := mem_split h in e.symm ▸ ⟨(l₁++l₂ : list α), quot.sound perm_middle⟩ @[simp] theorem not_mem_zero (a : α) : a ∉ (0 : multiset α) := id theorem eq_zero_of_forall_not_mem {s : multiset α} : (∀x, x ∉ s) → s = 0 := quot.induction_on s $ λ l H, by rw eq_nil_iff_forall_not_mem.mpr H; refl theorem eq_zero_iff_forall_not_mem {s : multiset α} : s = 0 ↔ ∀ a, a ∉ s := ⟨λ h, h.symm ▸ λ _, not_false, eq_zero_of_forall_not_mem⟩ theorem exists_mem_of_ne_zero {s : multiset α} : s ≠ 0 → ∃ a : α, a ∈ s := quot.induction_on s $ assume l hl, match l, hl with | [] := assume h, false.elim $ h rfl | (a :: l) := assume _, ⟨a, by simp⟩ end @[simp] lemma zero_ne_cons {a : α} {m : multiset α} : 0 ≠ a ::ₘ m := assume h, have a ∈ (0:multiset α), from h.symm ▸ mem_cons_self _ _, not_mem_zero _ this @[simp] lemma cons_ne_zero {a : α} {m : multiset α} : a ::ₘ m ≠ 0 := zero_ne_cons.symm lemma cons_eq_cons {a b : α} {as bs : multiset α} : a ::ₘ as = b ::ₘ bs ↔ ((a = b ∧ as = bs) ∨ (a ≠ b ∧ ∃cs, as = b ::ₘ cs ∧ bs = a ::ₘ cs)) := begin haveI : decidable_eq α := classical.dec_eq α, split, { assume eq, by_cases a = b, { subst h, simp * at * }, { have : a ∈ b ::ₘ bs, from eq ▸ mem_cons_self _ _, have : a ∈ bs, by simpa [h], rcases exists_cons_of_mem this with ⟨cs, hcs⟩, simp [h, hcs], have : a ::ₘ as = b ::ₘ a ::ₘ cs, by simp [eq, hcs], have : a ::ₘ as = a ::ₘ b ::ₘ cs, by rwa [cons_swap], simpa using this } }, { assume h, rcases h with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩, { simp * }, { simp [*, cons_swap a b] } } end end mem /-! ### `multiset.subset` -/ section subset /-- `s ⊆ t` is the lift of the list subset relation. It means that any element with nonzero multiplicity in `s` has nonzero multiplicity in `t`, but it does not imply that the multiplicity of `a` in `s` is less or equal than in `t`; see `s ≤ t` for this relation. -/ protected def subset (s t : multiset α) : Prop := ∀ ⦃a : α⦄, a ∈ s → a ∈ t instance : has_subset (multiset α) := ⟨multiset.subset⟩ @[simp] theorem coe_subset {l₁ l₂ : list α} : (l₁ : multiset α) ⊆ l₂ ↔ l₁ ⊆ l₂ := iff.rfl @[simp] theorem subset.refl (s : multiset α) : s ⊆ s := λ a h, h theorem subset.trans {s t u : multiset α} : s ⊆ t → t ⊆ u → s ⊆ u := λ h₁ h₂ a m, h₂ (h₁ m) theorem subset_iff {s t : multiset α} : s ⊆ t ↔ (∀⦃x⦄, x ∈ s → x ∈ t) := iff.rfl theorem mem_of_subset {s t : multiset α} {a : α} (h : s ⊆ t) : a ∈ s → a ∈ t := @h _ @[simp] theorem zero_subset (s : multiset α) : 0 ⊆ s := λ a, (not_mem_nil a).elim @[simp] theorem cons_subset {a : α} {s t : multiset α} : (a ::ₘ s) ⊆ t ↔ a ∈ t ∧ s ⊆ t := by simp [subset_iff, or_imp_distrib, forall_and_distrib] theorem eq_zero_of_subset_zero {s : multiset α} (h : s ⊆ 0) : s = 0 := eq_zero_of_forall_not_mem h theorem subset_zero {s : multiset α} : s ⊆ 0 ↔ s = 0 := ⟨eq_zero_of_subset_zero, λ xeq, xeq.symm ▸ subset.refl 0⟩ lemma induction_on' {p : multiset α → Prop} (S : multiset α) (h₁ : p ∅) (h₂ : ∀ {a s}, a ∈ S → s ⊆ S → p s → p (insert a s)) : p S := @multiset.induction_on α (λ T, T ⊆ S → p T) S (λ _, h₁) (λ a s hps hs, let ⟨hS, sS⟩ := cons_subset.1 hs in h₂ hS sS (hps sS)) (subset.refl S) end subset section to_list /-- Produces a list of the elements in the multiset using choice. -/ @[reducible] noncomputable def to_list {α : Type*} (s : multiset α) := classical.some (quotient.exists_rep s) @[simp] lemma to_list_zero {α : Type*} : (multiset.to_list 0 : list α) = [] := (multiset.coe_eq_zero _).1 (classical.some_spec (quotient.exists_rep multiset.zero)) lemma coe_to_list {α : Type*} (s : multiset α) : (s.to_list : multiset α) = s := classical.some_spec (quotient.exists_rep _) lemma mem_to_list {α : Type*} (a : α) (s : multiset α) : a ∈ s.to_list ↔ a ∈ s := by rw [←multiset.mem_coe, multiset.coe_to_list] end to_list /-! ### Partial order on `multiset`s -/ /-- `s ≤ t` means that `s` is a sublist of `t` (up to permutation). Equivalently, `s ≤ t` means that `count a s ≤ count a t` for all `a`. -/ protected def le (s t : multiset α) : Prop := quotient.lift_on₂ s t (<+~) $ λ v₁ v₂ w₁ w₂ p₁ p₂, propext (p₂.subperm_left.trans p₁.subperm_right) instance : partial_order (multiset α) := { le := multiset.le, le_refl := by rintros ⟨l⟩; exact subperm.refl _, le_trans := by rintros ⟨l₁⟩ ⟨l₂⟩ ⟨l₃⟩; exact @subperm.trans _ _ _ _, le_antisymm := by rintros ⟨l₁⟩ ⟨l₂⟩ h₁ h₂; exact quot.sound (subperm.antisymm h₁ h₂) } theorem subset_of_le {s t : multiset α} : s ≤ t → s ⊆ t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm.subset theorem mem_of_le {s t : multiset α} {a : α} (h : s ≤ t) : a ∈ s → a ∈ t := mem_of_subset (subset_of_le h) @[simp] theorem coe_le {l₁ l₂ : list α} : (l₁ : multiset α) ≤ l₂ ↔ l₁ <+~ l₂ := iff.rfl @[elab_as_eliminator] theorem le_induction_on {C : multiset α → multiset α → Prop} {s t : multiset α} (h : s ≤ t) (H : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → C l₁ l₂) : C s t := quotient.induction_on₂ s t (λ l₁ l₂ ⟨l, p, s⟩, (show ⟦l⟧ = ⟦l₁⟧, from quot.sound p) ▸ H s) h theorem zero_le (s : multiset α) : 0 ≤ s := quot.induction_on s $ λ l, (nil_sublist l).subperm theorem le_zero {s : multiset α} : s ≤ 0 ↔ s = 0 := ⟨λ h, le_antisymm h (zero_le _), le_of_eq⟩ theorem lt_cons_self (s : multiset α) (a : α) : s < a ::ₘ s := quot.induction_on s $ λ l, suffices l <+~ a :: l ∧ (¬l ~ a :: l), by simpa [lt_iff_le_and_ne], ⟨(sublist_cons _ _).subperm, λ p, ne_of_lt (lt_succ_self (length l)) p.length_eq⟩ theorem le_cons_self (s : multiset α) (a : α) : s ≤ a ::ₘ s := le_of_lt $ lt_cons_self _ _ theorem cons_le_cons_iff (a : α) {s t : multiset α} : a ::ₘ s ≤ a ::ₘ t ↔ s ≤ t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_cons a theorem cons_le_cons (a : α) {s t : multiset α} : s ≤ t → a ::ₘ s ≤ a ::ₘ t := (cons_le_cons_iff a).2 theorem le_cons_of_not_mem {a : α} {s t : multiset α} (m : a ∉ s) : s ≤ a ::ₘ t ↔ s ≤ t := begin refine ⟨_, λ h, le_trans h $ le_cons_self _ _⟩, suffices : ∀ {t'} (_ : s ≤ t') (_ : a ∈ t'), a ::ₘ s ≤ t', { exact λ h, (cons_le_cons_iff a).1 (this h (mem_cons_self _ _)) }, introv h, revert m, refine le_induction_on h _, introv s m₁ m₂, rcases mem_split m₂ with ⟨r₁, r₂, rfl⟩, exact perm_middle.subperm_left.2 ((subperm_cons _).2 $ ((sublist_or_mem_of_sublist s).resolve_right m₁).subperm) end /-! ### Additive monoid -/ /-- The sum of two multisets is the lift of the list append operation. This adds the multiplicities of each element, i.e. `count a (s + t) = count a s + count a t`. -/ protected def add (s₁ s₂ : multiset α) : multiset α := quotient.lift_on₂ s₁ s₂ (λ l₁ l₂, ((l₁ ++ l₂ : list α) : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ p₁.append p₂ instance : has_add (multiset α) := ⟨multiset.add⟩ @[simp] theorem coe_add (s t : list α) : (s + t : multiset α) = (s ++ t : list α) := rfl protected theorem add_comm (s t : multiset α) : s + t = t + s := quotient.induction_on₂ s t $ λ l₁ l₂, quot.sound perm_append_comm protected theorem zero_add (s : multiset α) : 0 + s = s := quot.induction_on s $ λ l, rfl theorem singleton_add (a : α) (s : multiset α) : ↑[a] + s = a ::ₘ s := rfl protected theorem add_le_add_left (s) {t u : multiset α} : s + t ≤ s + u ↔ t ≤ u := quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, subperm_append_left _ protected theorem add_left_cancel (s) {t u : multiset α} (h : s + t = s + u) : t = u := le_antisymm ((multiset.add_le_add_left _).1 (le_of_eq h)) ((multiset.add_le_add_left _).1 (le_of_eq h.symm)) instance : ordered_cancel_add_comm_monoid (multiset α) := { zero := 0, add := (+), add_comm := multiset.add_comm, add_assoc := λ s₁ s₂ s₃, quotient.induction_on₃ s₁ s₂ s₃ $ λ l₁ l₂ l₃, congr_arg coe $ append_assoc l₁ l₂ l₃, zero_add := multiset.zero_add, add_zero := λ s, by rw [multiset.add_comm, multiset.zero_add], add_left_cancel := multiset.add_left_cancel, add_right_cancel := λ s₁ s₂ s₃ h, multiset.add_left_cancel s₂ $ by simpa [multiset.add_comm] using h, add_le_add_left := λ s₁ s₂ h s₃, (multiset.add_le_add_left _).2 h, le_of_add_le_add_left := λ s₁ s₂ s₃, (multiset.add_le_add_left _).1, ..@multiset.partial_order α } theorem le_add_right (s t : multiset α) : s ≤ s + t := by simpa using add_le_add_left (zero_le t) s theorem le_add_left (s t : multiset α) : s ≤ t + s := by simpa using add_le_add_right (zero_le t) s theorem le_iff_exists_add {s t : multiset α} : s ≤ t ↔ ∃ u, t = s + u := ⟨λ h, le_induction_on h $ λ l₁ l₂ s, let ⟨l, p⟩ := s.exists_perm_append in ⟨l, quot.sound p⟩, λ ⟨u, e⟩, e.symm ▸ le_add_right _ _⟩ instance : canonically_ordered_add_monoid (multiset α) := { lt_of_add_lt_add_left := @lt_of_add_lt_add_left _ _, le_iff_exists_add := @le_iff_exists_add _, bot := 0, bot_le := multiset.zero_le, ..multiset.ordered_cancel_add_comm_monoid } @[simp] theorem cons_add (a : α) (s t : multiset α) : a ::ₘ s + t = a ::ₘ (s + t) := by rw [← singleton_add, ← singleton_add, add_assoc] @[simp] theorem add_cons (a : α) (s t : multiset α) : s + a ::ₘ t = a ::ₘ (s + t) := by rw [add_comm, cons_add, add_comm] @[simp] theorem mem_add {a : α} {s t : multiset α} : a ∈ s + t ↔ a ∈ s ∨ a ∈ t := quotient.induction_on₂ s t $ λ l₁ l₂, mem_append /-! ### Cardinality -/ /-- The cardinality of a multiset is the sum of the multiplicities of all its elements, or simply the length of the underlying list. -/ def card : multiset α →+ ℕ := { to_fun := λ s, quot.lift_on s length $ λ l₁ l₂, perm.length_eq, map_zero' := rfl, map_add' := λ s t, quotient.induction_on₂ s t length_append } @[simp] theorem coe_card (l : list α) : card (l : multiset α) = length l := rfl @[simp] theorem card_zero : @card α 0 = 0 := rfl theorem card_add (s t : multiset α) : card (s + t) = card s + card t := card.map_add s t lemma card_smul (s : multiset α) (n : ℕ) : (n •ℕ s).card = n * s.card := by rw [card.map_nsmul s n, nat.nsmul_eq_mul] @[simp] theorem card_cons (a : α) (s : multiset α) : card (a ::ₘ s) = card s + 1 := quot.induction_on s $ λ l, rfl @[simp] theorem card_singleton (a : α) : card (a ::ₘ 0) = 1 := by simp theorem card_le_of_le {s t : multiset α} (h : s ≤ t) : card s ≤ card t := le_induction_on h $ λ l₁ l₂, length_le_of_sublist theorem eq_of_le_of_card_le {s t : multiset α} (h : s ≤ t) : card t ≤ card s → s = t := le_induction_on h $ λ l₁ l₂ s h₂, congr_arg coe $ eq_of_sublist_of_length_le s h₂ theorem card_lt_of_lt {s t : multiset α} (h : s < t) : card s < card t := lt_of_not_ge $ λ h₂, ne_of_lt h $ eq_of_le_of_card_le (le_of_lt h) h₂ theorem lt_iff_cons_le {s t : multiset α} : s < t ↔ ∃ a, a ::ₘ s ≤ t := ⟨quotient.induction_on₂ s t $ λ l₁ l₂ h, subperm.exists_of_length_lt (le_of_lt h) (card_lt_of_lt h), λ ⟨a, h⟩, lt_of_lt_of_le (lt_cons_self _ _) h⟩ @[simp] theorem card_eq_zero {s : multiset α} : card s = 0 ↔ s = 0 := ⟨λ h, (eq_of_le_of_card_le (zero_le _) (le_of_eq h)).symm, λ e, by simp [e]⟩ theorem card_pos {s : multiset α} : 0 < card s ↔ s ≠ 0 := pos_iff_ne_zero.trans $ not_congr card_eq_zero theorem card_pos_iff_exists_mem {s : multiset α} : 0 < card s ↔ ∃ a, a ∈ s := quot.induction_on s $ λ l, length_pos_iff_exists_mem @[elab_as_eliminator] def strong_induction_on {p : multiset α → Sort*} : ∀ (s : multiset α), (∀ s, (∀t < s, p t) → p s) → p s | s := λ ih, ih s $ λ t h, have card t < card s, from card_lt_of_lt h, strong_induction_on t ih using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf card⟩]} theorem strong_induction_eq {p : multiset α → Sort*} (s : multiset α) (H) : @strong_induction_on _ p s H = H s (λ t h, @strong_induction_on _ p t H) := by rw [strong_induction_on] @[elab_as_eliminator] lemma case_strong_induction_on {p : multiset α → Prop} (s : multiset α) (h₀ : p 0) (h₁ : ∀ a s, (∀t ≤ s, p t) → p (a ::ₘ s)) : p s := multiset.strong_induction_on s $ assume s, multiset.induction_on s (λ _, h₀) $ λ a s _ ih, h₁ _ _ $ λ t h, ih _ $ lt_of_le_of_lt h $ lt_cons_self _ _ /-! ### Singleton -/ instance : has_singleton α (multiset α) := ⟨λ a, a ::ₘ 0⟩ instance : is_lawful_singleton α (multiset α) := ⟨λ a, rfl⟩ @[simp] theorem singleton_eq_singleton (a : α) : singleton a = a ::ₘ 0 := rfl @[simp] theorem mem_singleton {a b : α} : b ∈ a ::ₘ 0 ↔ b = a := by simp theorem mem_singleton_self (a : α) : a ∈ (a ::ₘ 0 : multiset α) := mem_cons_self _ _ theorem singleton_inj {a b : α} : a ::ₘ 0 = b ::ₘ 0 ↔ a = b := cons_inj_left _ @[simp] theorem singleton_ne_zero (a : α) : a ::ₘ 0 ≠ 0 := ne_of_gt (lt_cons_self _ _) @[simp] theorem singleton_le {a : α} {s : multiset α} : a ::ₘ 0 ≤ s ↔ a ∈ s := ⟨λ h, mem_of_le h (mem_singleton_self _), λ h, let ⟨t, e⟩ := exists_cons_of_mem h in e.symm ▸ cons_le_cons _ (zero_le _)⟩ theorem card_eq_one {s : multiset α} : card s = 1 ↔ ∃ a, s = a ::ₘ 0 := ⟨quot.induction_on s $ λ l h, (list.length_eq_one.1 h).imp $ λ a, congr_arg coe, λ ⟨a, e⟩, e.symm ▸ rfl⟩ /-! ### `multiset.repeat` -/ /-- `repeat a n` is the multiset containing only `a` with multiplicity `n`. -/ def repeat (a : α) (n : ℕ) : multiset α := repeat a n @[simp] lemma repeat_zero (a : α) : repeat a 0 = 0 := rfl @[simp] lemma repeat_succ (a : α) (n) : repeat a (n+1) = a ::ₘ repeat a n := by simp [repeat] @[simp] lemma repeat_one (a : α) : repeat a 1 = a ::ₘ 0 := by simp @[simp] lemma card_repeat : ∀ (a : α) n, card (repeat a n) = n := length_repeat theorem eq_of_mem_repeat {a b : α} {n} : b ∈ repeat a n → b = a := eq_of_mem_repeat theorem eq_repeat' {a : α} {s : multiset α} : s = repeat a s.card ↔ ∀ b ∈ s, b = a := quot.induction_on s $ λ l, iff.trans ⟨λ h, (perm_repeat.1 $ (quotient.exact h)), congr_arg coe⟩ eq_repeat' theorem eq_repeat_of_mem {a : α} {s : multiset α} : (∀ b ∈ s, b = a) → s = repeat a s.card := eq_repeat'.2 theorem eq_repeat {a : α} {n} {s : multiset α} : s = repeat a n ↔ card s = n ∧ ∀ b ∈ s, b = a := ⟨λ h, h.symm ▸ ⟨card_repeat _ _, λ b, eq_of_mem_repeat⟩, λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩ theorem repeat_subset_singleton : ∀ (a : α) n, repeat a n ⊆ a ::ₘ 0 := repeat_subset_singleton theorem repeat_le_coe {a : α} {n} {l : list α} : repeat a n ≤ l ↔ list.repeat a n <+ l := ⟨λ ⟨l', p, s⟩, (perm_repeat.1 p) ▸ s, sublist.subperm⟩ /-! ### Erasing one copy of an element -/ section erase variables [decidable_eq α] {s t : multiset α} {a b : α} /-- `erase s a` is the multiset that subtracts 1 from the multiplicity of `a`. -/ def erase (s : multiset α) (a : α) : multiset α := quot.lift_on s (λ l, (l.erase a : multiset α)) (λ l₁ l₂ p, quot.sound (p.erase a)) @[simp] theorem coe_erase (l : list α) (a : α) : erase (l : multiset α) a = l.erase a := rfl @[simp] theorem erase_zero (a : α) : (0 : multiset α).erase a = 0 := rfl @[simp] theorem erase_cons_head (a : α) (s : multiset α) : (a ::ₘ s).erase a = s := quot.induction_on s $ λ l, congr_arg coe $ erase_cons_head a l @[simp, priority 990] theorem erase_cons_tail {a b : α} (s : multiset α) (h : b ≠ a) : (b ::ₘ s).erase a = b ::ₘ s.erase a := quot.induction_on s $ λ l, congr_arg coe $ erase_cons_tail l h @[simp, priority 980] theorem erase_of_not_mem {a : α} {s : multiset α} : a ∉ s → s.erase a = s := quot.induction_on s $ λ l h, congr_arg coe $ erase_of_not_mem h @[simp, priority 980] theorem cons_erase {s : multiset α} {a : α} : a ∈ s → a ::ₘ s.erase a = s := quot.induction_on s $ λ l h, quot.sound (perm_cons_erase h).symm theorem le_cons_erase (s : multiset α) (a : α) : s ≤ a ::ₘ s.erase a := if h : a ∈ s then le_of_eq (cons_erase h).symm else by rw erase_of_not_mem h; apply le_cons_self theorem erase_add_left_pos {a : α} {s : multiset α} (t) : a ∈ s → (s + t).erase a = s.erase a + t := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_left l₂ h theorem erase_add_right_pos {a : α} (s) {t : multiset α} (h : a ∈ t) : (s + t).erase a = s + t.erase a := by rw [add_comm, erase_add_left_pos s h, add_comm] theorem erase_add_right_neg {a : α} {s : multiset α} (t) : a ∉ s → (s + t).erase a = s + t.erase a := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_right l₂ h theorem erase_add_left_neg {a : α} (s) {t : multiset α} (h : a ∉ t) : (s + t).erase a = s.erase a + t := by rw [add_comm, erase_add_right_neg s h, add_comm] theorem erase_le (a : α) (s : multiset α) : s.erase a ≤ s := quot.induction_on s $ λ l, (erase_sublist a l).subperm @[simp] theorem erase_lt {a : α} {s : multiset α} : s.erase a < s ↔ a ∈ s := ⟨λ h, not_imp_comm.1 erase_of_not_mem (ne_of_lt h), λ h, by simpa [h] using lt_cons_self (s.erase a) a⟩ theorem erase_subset (a : α) (s : multiset α) : s.erase a ⊆ s := subset_of_le (erase_le a s) theorem mem_erase_of_ne {a b : α} {s : multiset α} (ab : a ≠ b) : a ∈ s.erase b ↔ a ∈ s := quot.induction_on s $ λ l, list.mem_erase_of_ne ab theorem mem_of_mem_erase {a b : α} {s : multiset α} : a ∈ s.erase b → a ∈ s := mem_of_subset (erase_subset _ _) theorem erase_comm (s : multiset α) (a b : α) : (s.erase a).erase b = (s.erase b).erase a := quot.induction_on s $ λ l, congr_arg coe $ l.erase_comm a b theorem erase_le_erase {s t : multiset α} (a : α) (h : s ≤ t) : s.erase a ≤ t.erase a := le_induction_on h $ λ l₁ l₂ h, (h.erase _).subperm theorem erase_le_iff_le_cons {s t : multiset α} {a : α} : s.erase a ≤ t ↔ s ≤ a ::ₘ t := ⟨λ h, le_trans (le_cons_erase _ _) (cons_le_cons _ h), λ h, if m : a ∈ s then by rw ← cons_erase m at h; exact (cons_le_cons_iff _).1 h else le_trans (erase_le _ _) ((le_cons_of_not_mem m).1 h)⟩ @[simp] theorem card_erase_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) = pred (card s) := quot.induction_on s $ λ l, length_erase_of_mem theorem card_erase_lt_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) < card s := λ h, card_lt_of_lt (erase_lt.mpr h) theorem card_erase_le {a : α} {s : multiset α} : card (s.erase a) ≤ card s := card_le_of_le (erase_le a s) end erase @[simp] theorem coe_reverse (l : list α) : (reverse l : multiset α) = l := quot.sound $ reverse_perm _ /-! ### `multiset.map` -/ /-- `map f s` is the lift of the list `map` operation. The multiplicity of `b` in `map f s` is the number of `a ∈ s` (counting multiplicity) such that `f a = b`. -/ def map (f : α → β) (s : multiset α) : multiset β := quot.lift_on s (λ l : list α, (l.map f : multiset β)) (λ l₁ l₂ p, quot.sound (p.map f)) theorem forall_mem_map_iff {f : α → β} {p : β → Prop} {s : multiset α} : (∀ y ∈ s.map f, p y) ↔ (∀ x ∈ s, p (f x)) := quotient.induction_on' s $ λ L, list.forall_mem_map_iff @[simp] theorem coe_map (f : α → β) (l : list α) : map f ↑l = l.map f := rfl @[simp] theorem map_zero (f : α → β) : map f 0 = 0 := rfl @[simp] theorem map_cons (f : α → β) (a s) : map f (a ::ₘ s) = f a ::ₘ map f s := quot.induction_on s $ λ l, rfl lemma map_singleton (f : α → β) (a : α) : ({a} : multiset α).map f = {f a} := rfl theorem map_repeat (f : α → β) (a : α) (k : ℕ) : (repeat a k).map f = repeat (f a) k := by { induction k, simp, simpa } @[simp] theorem map_add (f : α → β) (s t) : map f (s + t) = map f s + map f t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ map_append _ _ _ instance (f : α → β) : is_add_monoid_hom (map f) := { map_add := map_add _, map_zero := map_zero _ } theorem map_nsmul (f : α → β) (n s) : map f (n •ℕ s) = n •ℕ map f s := (add_monoid_hom.of (map f)).map_nsmul _ _ @[simp] theorem mem_map {f : α → β} {b : β} {s : multiset α} : b ∈ map f s ↔ ∃ a, a ∈ s ∧ f a = b := quot.induction_on s $ λ l, mem_map @[simp] theorem card_map (f : α → β) (s) : card (map f s) = card s := quot.induction_on s $ λ l, length_map _ _ @[simp] theorem map_eq_zero {s : multiset α} {f : α → β} : s.map f = 0 ↔ s = 0 := by rw [← multiset.card_eq_zero, multiset.card_map, multiset.card_eq_zero] theorem mem_map_of_mem (f : α → β) {a : α} {s : multiset α} (h : a ∈ s) : f a ∈ map f s := mem_map.2 ⟨_, h, rfl⟩ theorem mem_map_of_injective {f : α → β} (H : function.injective f) {a : α} {s : multiset α} : f a ∈ map f s ↔ a ∈ s := quot.induction_on s $ λ l, mem_map_of_injective H @[simp] theorem map_map (g : β → γ) (f : α → β) (s : multiset α) : map g (map f s) = map (g ∘ f) s := quot.induction_on s $ λ l, congr_arg coe $ list.map_map _ _ _ theorem map_id (s : multiset α) : map id s = s := quot.induction_on s $ λ l, congr_arg coe $ map_id _ @[simp] lemma map_id' (s : multiset α) : map (λx, x) s = s := map_id s @[simp] theorem map_const (s : multiset α) (b : β) : map (function.const α b) s = repeat b s.card := quot.induction_on s $ λ l, congr_arg coe $ map_const _ _ @[congr] theorem map_congr {f g : α → β} {s : multiset α} : (∀ x ∈ s, f x = g x) → map f s = map g s := quot.induction_on s $ λ l H, congr_arg coe $ map_congr H lemma map_hcongr {β' : Type*} {m : multiset α} {f : α → β} {f' : α → β'} (h : β = β') (hf : ∀a∈m, f a == f' a) : map f m == map f' m := begin subst h, simp at hf, simp [map_congr hf] end theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ := eq_of_mem_repeat $ by rwa map_const at h @[simp] theorem map_le_map {f : α → β} {s t : multiset α} (h : s ≤ t) : map f s ≤ map f t := le_induction_on h $ λ l₁ l₂ h, (h.map f).subperm @[simp] theorem map_subset_map {f : α → β} {s t : multiset α} (H : s ⊆ t) : map f s ⊆ map f t := λ b m, let ⟨a, h, e⟩ := mem_map.1 m in mem_map.2 ⟨a, H h, e⟩ /-! ### `multiset.fold` -/ /-- `foldl f H b s` is the lift of the list operation `foldl f b l`, which folds `f` over the multiset. It is well defined when `f` is right-commutative, that is, `f (f b a₁) a₂ = f (f b a₂) a₁`. -/ def foldl (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : β := quot.lift_on s (λ l, foldl f b l) (λ l₁ l₂ p, p.foldl_eq H b) @[simp] theorem foldl_zero (f : β → α → β) (H b) : foldl f H b 0 = b := rfl @[simp] theorem foldl_cons (f : β → α → β) (H b a s) : foldl f H b (a ::ₘ s) = foldl f H (f b a) s := quot.induction_on s $ λ l, rfl @[simp] theorem foldl_add (f : β → α → β) (H b s t) : foldl f H b (s + t) = foldl f H (foldl f H b s) t := quotient.induction_on₂ s t $ λ l₁ l₂, foldl_append _ _ _ _ /-- `foldr f H b s` is the lift of the list operation `foldr f b l`, which folds `f` over the multiset. It is well defined when `f` is left-commutative, that is, `f a₁ (f a₂ b) = f a₂ (f a₁ b)`. -/ def foldr (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : β := quot.lift_on s (λ l, foldr f b l) (λ l₁ l₂ p, p.foldr_eq H b) @[simp] theorem foldr_zero (f : α → β → β) (H b) : foldr f H b 0 = b := rfl @[simp] theorem foldr_cons (f : α → β → β) (H b a s) : foldr f H b (a ::ₘ s) = f a (foldr f H b s) := quot.induction_on s $ λ l, rfl @[simp] theorem foldr_add (f : α → β → β) (H b s t) : foldr f H b (s + t) = foldr f H (foldr f H b t) s := quotient.induction_on₂ s t $ λ l₁ l₂, foldr_append _ _ _ _ @[simp] theorem coe_foldr (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) : foldr f H b l = l.foldr f b := rfl @[simp] theorem coe_foldl (f : β → α → β) (H : right_commutative f) (b : β) (l : list α) : foldl f H b l = l.foldl f b := rfl theorem coe_foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) : foldr f H b l = l.foldl (λ x y, f y x) b := (congr_arg (foldr f H b) (coe_reverse l)).symm.trans $ foldr_reverse _ _ _ theorem foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : foldr f H b s = foldl (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s := quot.induction_on s $ λ l, coe_foldr_swap _ _ _ _ theorem foldl_swap (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : foldl f H b s = foldr (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s := (foldr_swap _ _ _ _).symm lemma foldr_induction' (f : α → β → β) (H : left_commutative f) (x : β) (q : α → Prop) (p : β → Prop) (s : multiset α) (hpqf : ∀ a b, q a → p b → p (f a b)) (px : p x) (q_s : ∀ a ∈ s, q a) : p (foldr f H x s) := begin revert s, refine multiset.induction (by simp [px]) _, intros a s hs hsa, rw foldr_cons, have hps : ∀ (x : α), x ∈ s → q x, from λ x hxs, hsa x (mem_cons_of_mem hxs), exact hpqf a (foldr f H x s) (hsa a (mem_cons_self a s)) (hs hps), end lemma foldr_induction (f : α → α → α) (H : left_commutative f) (x : α) (p : α → Prop) (s : multiset α) (p_f : ∀ a b, p a → p b → p (f a b)) (px : p x) (p_s : ∀ a ∈ s, p a) : p (foldr f H x s) := foldr_induction' f H x p p s p_f px p_s lemma foldl_induction' (f : β → α → β) (H : right_commutative f) (x : β) (q : α → Prop) (p : β → Prop) (s : multiset α) (hpqf : ∀ a b, q a → p b → p (f b a)) (px : p x) (q_s : ∀ a ∈ s, q a) : p (foldl f H x s) := begin rw foldl_swap, exact foldr_induction' (λ x y, f y x) (λ x y z, (H _ _ _).symm) x q p s hpqf px q_s, end lemma foldl_induction (f : α → α → α) (H : right_commutative f) (x : α) (p : α → Prop) (s : multiset α) (p_f : ∀ a b, p a → p b → p (f b a)) (px : p x) (p_s : ∀ a ∈ s, p a) : p (foldl f H x s) := foldl_induction' f H x p p s p_f px p_s /-- Product of a multiset given a commutative monoid structure on `α`. `prod {a, b, c} = a * b * c` -/ @[to_additive] def prod [comm_monoid α] : multiset α → α := foldr (*) (λ x y z, by simp [mul_left_comm]) 1 @[to_additive] theorem prod_eq_foldr [comm_monoid α] (s : multiset α) : prod s = foldr (*) (λ x y z, by simp [mul_left_comm]) 1 s := rfl @[to_additive] theorem prod_eq_foldl [comm_monoid α] (s : multiset α) : prod s = foldl (*) (λ x y z, by simp [mul_right_comm]) 1 s := (foldr_swap _ _ _ _).trans (by simp [mul_comm]) @[simp, to_additive] theorem coe_prod [comm_monoid α] (l : list α) : prod ↑l = l.prod := prod_eq_foldl _ attribute [norm_cast] coe_prod coe_sum @[simp, to_additive] theorem prod_zero [comm_monoid α] : @prod α _ 0 = 1 := rfl @[simp, to_additive] theorem prod_cons [comm_monoid α] (a : α) (s) : prod (a ::ₘ s) = a * prod s := foldr_cons _ _ _ _ _ @[to_additive] theorem prod_singleton [comm_monoid α] (a : α) : prod (a ::ₘ 0) = a := by simp @[simp, to_additive] theorem prod_add [comm_monoid α] (s t : multiset α) : prod (s + t) = prod s * prod t := quotient.induction_on₂ s t $ λ l₁ l₂, by simp instance sum.is_add_monoid_hom [add_comm_monoid α] : is_add_monoid_hom (sum : multiset α → α) := { map_add := sum_add, map_zero := sum_zero } lemma prod_smul {α : Type*} [comm_monoid α] (m : multiset α) : ∀n, (n •ℕ m).prod = m.prod ^ n | 0 := rfl | (n + 1) := by rw [add_nsmul, one_nsmul, pow_add, pow_one, prod_add, prod_smul n] @[simp] theorem prod_repeat [comm_monoid α] (a : α) (n : ℕ) : prod (multiset.repeat a n) = a ^ n := by simp [repeat, list.prod_repeat] @[simp] theorem sum_repeat [add_comm_monoid α] : ∀ (a : α) (n : ℕ), sum (multiset.repeat a n) = n •ℕ a := @prod_repeat (multiplicative α) _ attribute [to_additive] prod_repeat lemma prod_map_one [comm_monoid γ] {m : multiset α} : prod (m.map (λa, (1 : γ))) = (1 : γ) := by simp lemma sum_map_zero [add_comm_monoid γ] {m : multiset α} : sum (m.map (λa, (0 : γ))) = (0 : γ) := by simp attribute [to_additive] prod_map_one @[simp, to_additive] lemma prod_map_mul [comm_monoid γ] {m : multiset α} {f g : α → γ} : prod (m.map $ λa, f a * g a) = prod (m.map f) * prod (m.map g) := multiset.induction_on m (by simp) (assume a m ih, by simp [ih]; cc) lemma prod_map_prod_map [comm_monoid γ] (m : multiset α) (n : multiset β) {f : α → β → γ} : prod (m.map $ λa, prod $ n.map $ λb, f a b) = prod (n.map $ λb, prod $ m.map $ λa, f a b) := multiset.induction_on m (by simp) (assume a m ih, by simp [ih]) lemma sum_map_sum_map [add_comm_monoid γ] : ∀ (m : multiset α) (n : multiset β) {f : α → β → γ}, sum (m.map $ λa, sum $ n.map $ λb, f a b) = sum (n.map $ λb, sum $ m.map $ λa, f a b) := @prod_map_prod_map _ _ (multiplicative γ) _ attribute [to_additive] prod_map_prod_map lemma sum_map_mul_left [semiring β] {b : β} {s : multiset α} {f : α → β} : sum (s.map (λa, b * f a)) = b * sum (s.map f) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, mul_add]) lemma sum_map_mul_right [semiring β] {b : β} {s : multiset α} {f : α → β} : sum (s.map (λa, f a * b)) = sum (s.map f) * b := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, add_mul]) lemma prod_eq_zero {M₀ : Type*} [comm_monoid_with_zero M₀] {s : multiset M₀} (h : (0 : M₀) ∈ s) : multiset.prod s = 0 := begin rcases multiset.exists_cons_of_mem h with ⟨s', hs'⟩, simp [hs', multiset.prod_cons] end lemma prod_eq_zero_iff {M₀ : Type*} [comm_monoid_with_zero M₀] [no_zero_divisors M₀] [nontrivial M₀] {s : multiset M₀} : multiset.prod s = 0 ↔ (0 : M₀) ∈ s := by { rcases s with ⟨l⟩, simp } theorem prod_ne_zero {M₀ : Type*} [comm_monoid_with_zero M₀] [no_zero_divisors M₀] [nontrivial M₀] {m : multiset M₀} (h : (0 : M₀) ∉ m) : m.prod ≠ 0 := mt prod_eq_zero_iff.1 h @[to_additive] lemma prod_hom [comm_monoid α] [comm_monoid β] (s : multiset α) (f : α →* β) : (s.map f).prod = f s.prod := quotient.induction_on s $ λ l, by simp only [l.prod_hom f, quot_mk_to_coe, coe_map, coe_prod] @[to_additive] theorem prod_hom_rel [comm_monoid β] [comm_monoid γ] (s : multiset α) {r : β → γ → Prop} {f : α → β} {g : α → γ} (h₁ : r 1 1) (h₂ : ∀⦃a b c⦄, r b c → r (f a * b) (g a * c)) : r (s.map f).prod (s.map g).prod := quotient.induction_on s $ λ l, by simp only [l.prod_hom_rel h₁ h₂, quot_mk_to_coe, coe_map, coe_prod] lemma dvd_prod [comm_monoid α] {a : α} {s : multiset α} : a ∈ s → a ∣ s.prod := quotient.induction_on s (λ l a h, by simpa using list.dvd_prod h) a lemma prod_dvd_prod [comm_monoid α] {s t : multiset α} (h : s ≤ t) : s.prod ∣ t.prod := begin rcases multiset.le_iff_exists_add.1 h with ⟨z, rfl⟩, simp, end @[to_additive sum_nonneg] lemma one_le_prod_of_one_le [ordered_comm_monoid α] {m : multiset α} : (∀ x ∈ m, (1 : α) ≤ x) → 1 ≤ m.prod := quotient.induction_on m $ λ l hl, by simpa using list.one_le_prod_of_one_le hl @[to_additive] lemma single_le_prod [ordered_comm_monoid α] {m : multiset α} : (∀ x ∈ m, (1 : α) ≤ x) → ∀ x ∈ m, x ≤ m.prod := quotient.induction_on m $ λ l hl x hx, by simpa using list.single_le_prod hl x hx @[to_additive all_zero_of_le_zero_le_of_sum_eq_zero] lemma all_one_of_le_one_le_of_prod_eq_one [ordered_comm_monoid α] {m : multiset α} : (∀ x ∈ m, (1 : α) ≤ x) → m.prod = 1 → (∀ x ∈ m, x = (1 : α)) := begin apply quotient.induction_on m, simp only [quot_mk_to_coe, coe_prod, mem_coe], intros l hl₁ hl₂ x hx, apply all_one_of_le_one_le_of_prod_eq_one hl₁ hl₂ _ hx, end lemma sum_eq_zero_iff [canonically_ordered_add_monoid α] {m : multiset α} : m.sum = 0 ↔ ∀ x ∈ m, x = (0 : α) := quotient.induction_on m $ λ l, by simpa using list.sum_eq_zero_iff l @[to_additive] lemma prod_induction {M : Type*} [comm_monoid M] (p : M → Prop) (s : multiset M) (p_mul : ∀ a b, p a → p b → p (a * b)) (p_one : p 1) (p_s : ∀ a ∈ s, p a) : p s.prod := begin rw prod_eq_foldr, exact foldr_induction (*) (λ x y z, by simp [mul_left_comm]) 1 p s p_mul p_one p_s, end @[to_additive le_sum_of_subadditive_on_pred] lemma le_prod_of_submultiplicative_on_pred [comm_monoid α] [ordered_comm_monoid β] (f : α → β) (p : α → Prop) (h_one : f 1 = 1) (hp_one : p 1) (h_mul : ∀ a b, p a → p b → f (a * b) ≤ f a * f b) (hp_mul : ∀ a b, p a → p b → p (a * b)) (s : multiset α) (hps : ∀ a, a ∈ s → p a) : f s.prod ≤ (s.map f).prod := begin revert s, refine multiset.induction _ _, { simp [le_of_eq h_one], }, intros a s hs hpsa, have hps : ∀ x, x ∈ s → p x, from λ x hx, hpsa x (mem_cons_of_mem hx), have hp_prod : p s.prod, from prod_induction p s hp_mul hp_one hps, rw [prod_cons, map_cons, prod_cons], exact (h_mul a s.prod (hpsa a (mem_cons_self a s)) hp_prod).trans (mul_le_mul_left' (hs hps) _), end @[to_additive le_sum_of_subadditive] lemma le_prod_of_submultiplicative [comm_monoid α] [ordered_comm_monoid β] (f : α → β) (h_one : f 1 = 1) (h_mul : ∀ a b, f (a * b) ≤ f a * f b) (s : multiset α) : f s.prod ≤ (s.map f).prod := le_prod_of_submultiplicative_on_pred f (λ i, true) h_one trivial (λ x y _ _ , h_mul x y) (by simp) s (by simp) @[to_additive] lemma prod_induction_nonempty {M : Type*} [comm_monoid M] (p : M → Prop) (p_mul : ∀ a b, p a → p b → p (a * b)) {s : multiset M} (hs_nonempty : s ≠ ∅) (p_s : ∀ a ∈ s, p a) : p s.prod := begin revert s, refine multiset.induction _ _, { intro h, exfalso, simpa using h, }, intros a s hs hsa hpsa, rw prod_cons, by_cases hs_empty : s = ∅, { simp [hs_empty, hpsa a], }, have hps : ∀ (x : M), x ∈ s → p x, from λ x hxs, hpsa x (mem_cons_of_mem hxs), exact p_mul a s.prod (hpsa a (mem_cons_self a s)) (hs hs_empty hps), end @[to_additive le_sum_nonempty_of_subadditive_on_pred] lemma le_prod_nonempty_of_submultiplicative_on_pred [comm_monoid α] [ordered_comm_monoid β] (f : α → β) (p : α → Prop) (h_mul : ∀ a b, p a → p b → f (a * b) ≤ f a * f b) (hp_mul : ∀ a b, p a → p b → p (a * b)) (s : multiset α) (hs_nonempty : s ≠ ∅) (hs : ∀ a, a ∈ s → p a) : f s.prod ≤ (s.map f).prod := begin revert s, refine multiset.induction _ _, { intro h, exfalso, exact h rfl, }, rintros a s hs hsa_nonempty hsa_prop, rw [prod_cons, map_cons, prod_cons], by_cases hs_empty : s = ∅, { simp [hs_empty], }, have hsa_restrict : (∀ x, x ∈ s → p x), from λ x hx, hsa_prop x (mem_cons_of_mem hx), have hp_sup : p s.prod, from prod_induction_nonempty p hp_mul hs_empty hsa_restrict, have hp_a : p a, from hsa_prop a (mem_cons_self a s), exact (h_mul a _ hp_a hp_sup).trans (mul_le_mul_left' (hs hs_empty hsa_restrict) _), end @[to_additive le_sum_nonempty_of_subadditive] lemma le_prod_nonempty_of_submultiplicative [comm_monoid α] [ordered_comm_monoid β] (f : α → β) (h_mul : ∀ a b, f (a * b) ≤ f a * f b) (s : multiset α) (hs_nonempty : s ≠ ∅) : f s.prod ≤ (s.map f).prod := le_prod_nonempty_of_submultiplicative_on_pred f (λ i, true) (by simp [h_mul]) (by simp) s hs_nonempty (by simp) lemma abs_sum_le_sum_abs [linear_ordered_field α] {s : multiset α} : abs s.sum ≤ (s.map abs).sum := le_sum_of_subadditive _ abs_zero abs_add s theorem dvd_sum [comm_semiring α] {a : α} {s : multiset α} : (∀ x ∈ s, a ∣ x) → a ∣ s.sum := multiset.induction_on s (λ _, dvd_zero _) (λ x s ih h, by rw sum_cons; exact dvd_add (h _ (mem_cons_self _ _)) (ih (λ y hy, h _ (mem_cons.2 (or.inr hy))))) @[simp] theorem sum_map_singleton (s : multiset α) : (s.map (λ a, a ::ₘ 0)).sum = s := multiset.induction_on s (by simp) (by simp) /-! ### Join -/ /-- `join S`, where `S` is a multiset of multisets, is the lift of the list join operation, that is, the union of all the sets. join {{1, 2}, {1, 2}, {0, 1}} = {0, 1, 1, 1, 2, 2} -/ def join : multiset (multiset α) → multiset α := sum theorem coe_join : ∀ L : list (list α), join (L.map (@coe _ (multiset α) _) : multiset (multiset α)) = L.join | [] := rfl | (l :: L) := congr_arg (λ s : multiset α, ↑l + s) (coe_join L) @[simp] theorem join_zero : @join α 0 = 0 := rfl @[simp] theorem join_cons (s S) : @join α (s ::ₘ S) = s + join S := sum_cons _ _ @[simp] theorem join_add (S T) : @join α (S + T) = join S + join T := sum_add _ _ @[simp] theorem mem_join {a S} : a ∈ @join α S ↔ ∃ s ∈ S, a ∈ s := multiset.induction_on S (by simp) $ by simp [or_and_distrib_right, exists_or_distrib] {contextual := tt} @[simp] theorem card_join (S) : card (@join α S) = sum (map card S) := multiset.induction_on S (by simp) (by simp) /-! ### `multiset.bind` -/ /-- `bind s f` is the monad bind operation, defined as `join (map f s)`. It is the union of `f a` as `a` ranges over `s`. -/ def bind (s : multiset α) (f : α → multiset β) : multiset β := join (map f s) @[simp] theorem coe_bind (l : list α) (f : α → list β) : @bind α β l (λ a, f a) = l.bind f := by rw [list.bind, ← coe_join, list.map_map]; refl @[simp] theorem zero_bind (f : α → multiset β) : bind 0 f = 0 := rfl @[simp] theorem cons_bind (a s) (f : α → multiset β) : bind (a ::ₘ s) f = f a + bind s f := by simp [bind] @[simp] theorem add_bind (s t) (f : α → multiset β) : bind (s + t) f = bind s f + bind t f := by simp [bind] @[simp] theorem bind_zero (s : multiset α) : bind s (λa, 0 : α → multiset β) = 0 := by simp [bind, join] @[simp] theorem bind_add (s : multiset α) (f g : α → multiset β) : bind s (λa, f a + g a) = bind s f + bind s g := by simp [bind, join] @[simp] theorem bind_cons (s : multiset α) (f : α → β) (g : α → multiset β) : bind s (λa, f a ::ₘ g a) = map f s + bind s g := multiset.induction_on s (by simp) (by simp [add_comm, add_left_comm] {contextual := tt}) @[simp] theorem mem_bind {b s} {f : α → multiset β} : b ∈ bind s f ↔ ∃ a ∈ s, b ∈ f a := by simp [bind]; simp [-exists_and_distrib_right, exists_and_distrib_right.symm]; rw exists_swap; simp [and_assoc] @[simp] theorem card_bind (s) (f : α → multiset β) : card (bind s f) = sum (map (card ∘ f) s) := by simp [bind] lemma bind_congr {f g : α → multiset β} {m : multiset α} : (∀a∈m, f a = g a) → bind m f = bind m g := by simp [bind] {contextual := tt} lemma bind_hcongr {β' : Type*} {m : multiset α} {f : α → multiset β} {f' : α → multiset β'} (h : β = β') (hf : ∀a∈m, f a == f' a) : bind m f == bind m f' := begin subst h, simp at hf, simp [bind_congr hf] end lemma map_bind (m : multiset α) (n : α → multiset β) (f : β → γ) : map f (bind m n) = bind m (λa, map f (n a)) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_map (m : multiset α) (n : β → multiset γ) (f : α → β) : bind (map f m) n = bind m (λa, n (f a)) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_assoc {s : multiset α} {f : α → multiset β} {g : β → multiset γ} : (s.bind f).bind g = s.bind (λa, (f a).bind g) := multiset.induction_on s (by simp) (by simp {contextual := tt}) lemma bind_bind (m : multiset α) (n : multiset β) {f : α → β → multiset γ} : (bind m $ λa, bind n $ λb, f a b) = (bind n $ λb, bind m $ λa, f a b) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_map_comm (m : multiset α) (n : multiset β) {f : α → β → γ} : (bind m $ λa, n.map $ λb, f a b) = (bind n $ λb, m.map $ λa, f a b) := multiset.induction_on m (by simp) (by simp {contextual := tt}) @[simp, to_additive] lemma prod_bind [comm_monoid β] (s : multiset α) (t : α → multiset β) : prod (bind s t) = prod (s.map $ λa, prod (t a)) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, cons_bind]) /-! ### Product of two `multiset`s -/ /-- The multiplicity of `(a, b)` in `product s t` is the product of the multiplicity of `a` in `s` and `b` in `t`. -/ def product (s : multiset α) (t : multiset β) : multiset (α × β) := s.bind $ λ a, t.map $ prod.mk a @[simp] theorem coe_product (l₁ : list α) (l₂ : list β) : @product α β l₁ l₂ = l₁.product l₂ := by rw [product, list.product, ← coe_bind]; simp @[simp] theorem zero_product (t) : @product α β 0 t = 0 := rfl @[simp] theorem cons_product (a : α) (s : multiset α) (t : multiset β) : product (a ::ₘ s) t = map (prod.mk a) t + product s t := by simp [product] @[simp] theorem product_singleton (a : α) (b : β) : product (a ::ₘ 0) (b ::ₘ 0) = (a,b) ::ₘ 0 := rfl @[simp] theorem add_product (s t : multiset α) (u : multiset β) : product (s + t) u = product s u + product t u := by simp [product] @[simp] theorem product_add (s : multiset α) : ∀ t u : multiset β, product s (t + u) = product s t + product s u := multiset.induction_on s (λ t u, rfl) $ λ a s IH t u, by rw [cons_product, IH]; simp; cc @[simp] theorem mem_product {s t} : ∀ {p : α × β}, p ∈ @product α β s t ↔ p.1 ∈ s ∧ p.2 ∈ t | (a, b) := by simp [product, and.left_comm] @[simp] theorem card_product (s : multiset α) (t : multiset β) : card (product s t) = card s * card t := by simp [product, repeat, (∘), mul_comm] /-! ### Sigma multiset -/ section variable {σ : α → Type*} /-- `sigma s t` is the dependent version of `product`. It is the sum of `(a, b)` as `a` ranges over `s` and `b` ranges over `t a`. -/ protected def sigma (s : multiset α) (t : Π a, multiset (σ a)) : multiset (Σ a, σ a) := s.bind $ λ a, (t a).map $ sigma.mk a @[simp] theorem coe_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) : @multiset.sigma α σ l₁ (λ a, l₂ a) = l₁.sigma l₂ := by rw [multiset.sigma, list.sigma, ← coe_bind]; simp @[simp] theorem zero_sigma (t) : @multiset.sigma α σ 0 t = 0 := rfl @[simp] theorem cons_sigma (a : α) (s : multiset α) (t : Π a, multiset (σ a)) : (a ::ₘ s).sigma t = map (sigma.mk a) (t a) + s.sigma t := by simp [multiset.sigma] @[simp] theorem sigma_singleton (a : α) (b : α → β) : (a ::ₘ 0).sigma (λ a, b a ::ₘ 0) = ⟨a, b a⟩ ::ₘ 0 := rfl @[simp] theorem add_sigma (s t : multiset α) (u : Π a, multiset (σ a)) : (s + t).sigma u = s.sigma u + t.sigma u := by simp [multiset.sigma] @[simp] theorem sigma_add (s : multiset α) : ∀ t u : Π a, multiset (σ a), s.sigma (λ a, t a + u a) = s.sigma t + s.sigma u := multiset.induction_on s (λ t u, rfl) $ λ a s IH t u, by rw [cons_sigma, IH]; simp; cc @[simp] theorem mem_sigma {s t} : ∀ {p : Σ a, σ a}, p ∈ @multiset.sigma α σ s t ↔ p.1 ∈ s ∧ p.2 ∈ t p.1 | ⟨a, b⟩ := by simp [multiset.sigma, and_assoc, and.left_comm] @[simp] theorem card_sigma (s : multiset α) (t : Π a, multiset (σ a)) : card (s.sigma t) = sum (map (λ a, card (t a)) s) := by simp [multiset.sigma, (∘)] end /-! ### Map for partial functions -/ /-- Lift of the list `pmap` operation. Map a partial function `f` over a multiset `s` whose elements are all in the domain of `f`. -/ def pmap {p : α → Prop} (f : Π a, p a → β) (s : multiset α) : (∀ a ∈ s, p a) → multiset β := quot.rec_on s (λ l H, ↑(pmap f l H)) $ λ l₁ l₂ (pp : l₁ ~ l₂), funext $ λ (H₂ : ∀ a ∈ l₂, p a), have H₁ : ∀ a ∈ l₁, p a, from λ a h, H₂ a (pp.subset h), have ∀ {s₂ e H}, @eq.rec (multiset α) l₁ (λ s, (∀ a ∈ s, p a) → multiset β) (λ _, ↑(pmap f l₁ H₁)) s₂ e H = ↑(pmap f l₁ H₁), by intros s₂ e _; subst e, this.trans $ quot.sound $ pp.pmap f @[simp] theorem coe_pmap {p : α → Prop} (f : Π a, p a → β) (l : list α) (H : ∀ a ∈ l, p a) : pmap f l H = l.pmap f H := rfl @[simp] lemma pmap_zero {p : α → Prop} (f : Π a, p a → β) (h : ∀a∈(0:multiset α), p a) : pmap f 0 h = 0 := rfl @[simp] lemma pmap_cons {p : α → Prop} (f : Π a, p a → β) (a : α) (m : multiset α) : ∀(h : ∀b∈a ::ₘ m, p b), pmap f (a ::ₘ m) h = f a (h a (mem_cons_self a m)) ::ₘ pmap f m (λa ha, h a $ mem_cons_of_mem ha) := quotient.induction_on m $ assume l h, rfl /-- "Attach" a proof that `a ∈ s` to each element `a` in `s` to produce a multiset on `{x // x ∈ s}`. -/ def attach (s : multiset α) : multiset {x // x ∈ s} := pmap subtype.mk s (λ a, id) @[simp] theorem coe_attach (l : list α) : @eq (multiset {x // x ∈ l}) (@attach α l) l.attach := rfl theorem sizeof_lt_sizeof_of_mem [has_sizeof α] {x : α} {s : multiset α} (hx : x ∈ s) : sizeof x < sizeof s := by { induction s with l a b, exact list.sizeof_lt_sizeof_of_mem hx, refl } theorem pmap_eq_map (p : α → Prop) (f : α → β) (s : multiset α) : ∀ H, @pmap _ _ p (λ a _, f a) s H = map f s := quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map p f l H theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β} (s : multiset α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) : pmap f s H₁ = pmap g s H₂ := quot.induction_on s (λ l H₁ H₂, congr_arg coe $ pmap_congr l h) H₁ H₂ theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β) (s) : ∀ H, map g (pmap f s H) = pmap (λ a h, g (f a h)) s H := quot.induction_on s $ λ l H, congr_arg coe $ map_pmap g f l H theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β) (s) : ∀ H, pmap f s H = s.attach.map (λ x, f x.1 (H _ x.2)) := quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map_attach f l H theorem attach_map_val (s : multiset α) : s.attach.map subtype.val = s := quot.induction_on s $ λ l, congr_arg coe $ attach_map_val l @[simp] theorem mem_attach (s : multiset α) : ∀ x, x ∈ s.attach := quot.induction_on s $ λ l, mem_attach _ @[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β} {s H b} : b ∈ pmap f s H ↔ ∃ a (h : a ∈ s), f a (H a h) = b := quot.induction_on s (λ l H, mem_pmap) H @[simp] theorem card_pmap {p : α → Prop} (f : Π a, p a → β) (s H) : card (pmap f s H) = card s := quot.induction_on s (λ l H, length_pmap) H @[simp] theorem card_attach {m : multiset α} : card (attach m) = card m := card_pmap _ _ _ @[simp] lemma attach_zero : (0 : multiset α).attach = 0 := rfl lemma attach_cons (a : α) (m : multiset α) : (a ::ₘ m).attach = ⟨a, mem_cons_self a m⟩ ::ₘ (m.attach.map $ λp, ⟨p.1, mem_cons_of_mem p.2⟩) := quotient.induction_on m $ assume l, congr_arg coe $ congr_arg (list.cons _) $ by rw [list.map_pmap]; exact list.pmap_congr _ (assume a' h₁ h₂, subtype.eq rfl) section decidable_pi_exists variables {m : multiset α} protected def decidable_forall_multiset {p : α → Prop} [hp : ∀a, decidable (p a)] : decidable (∀a∈m, p a) := quotient.rec_on_subsingleton m (λl, decidable_of_iff (∀a∈l, p a) $ by simp) instance decidable_dforall_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] : decidable (∀a (h : a ∈ m), p a h) := decidable_of_decidable_of_iff (@multiset.decidable_forall_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _) (iff.intro (assume h a ha, h ⟨a, ha⟩ (mem_attach _ _)) (assume h ⟨a, ha⟩ _, h _ _)) /-- decidable equality for functions whose domain is bounded by multisets -/ instance decidable_eq_pi_multiset {β : α → Type*} [h : ∀a, decidable_eq (β a)] : decidable_eq (Πa∈m, β a) := assume f g, decidable_of_iff (∀a (h : a ∈ m), f a h = g a h) (by simp [function.funext_iff]) def decidable_exists_multiset {p : α → Prop} [decidable_pred p] : decidable (∃ x ∈ m, p x) := quotient.rec_on_subsingleton m list.decidable_exists_mem instance decidable_dexists_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] : decidable (∃a (h : a ∈ m), p a h) := decidable_of_decidable_of_iff (@multiset.decidable_exists_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _) (iff.intro (λ ⟨⟨a, ha₁⟩, _, ha₂⟩, ⟨a, ha₁, ha₂⟩) (λ ⟨a, ha₁, ha₂⟩, ⟨⟨a, ha₁⟩, mem_attach _ _, ha₂⟩)) end decidable_pi_exists /-! ### Subtraction -/ section variables [decidable_eq α] {s t u : multiset α} {a b : α} /-- `s - t` is the multiset such that `count a (s - t) = count a s - count a t` for all `a`. -/ protected def sub (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.diff l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ p₁.diff p₂ instance : has_sub (multiset α) := ⟨multiset.sub⟩ @[simp] theorem coe_sub (s t : list α) : (s - t : multiset α) = (s.diff t : list α) := rfl theorem sub_eq_fold_erase (s t : multiset α) : s - t = foldl erase erase_comm s t := quotient.induction_on₂ s t $ λ l₁ l₂, show ↑(l₁.diff l₂) = foldl erase erase_comm ↑l₁ ↑l₂, by { rw diff_eq_foldl l₁ l₂, symmetry, exact foldl_hom _ _ _ _ _ (λ x y, rfl) } @[simp] theorem sub_zero (s : multiset α) : s - 0 = s := quot.induction_on s $ λ l, rfl @[simp] theorem sub_cons (a : α) (s t : multiset α) : s - a ::ₘ t = s.erase a - t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ diff_cons _ _ _ theorem add_sub_of_le (h : s ≤ t) : s + (t - s) = t := begin revert t, refine multiset.induction_on s (by simp) (λ a s IH t h, _), have := cons_erase (mem_of_le h (mem_cons_self _ _)), rw [cons_add, sub_cons, IH, this], exact (cons_le_cons_iff a).1 (this.symm ▸ h) end theorem sub_add' : s - (t + u) = s - t - u := quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, congr_arg coe $ diff_append _ _ _ theorem sub_add_cancel (h : t ≤ s) : s - t + t = s := by rw [add_comm, add_sub_of_le h] @[simp] theorem add_sub_cancel_left (s : multiset α) : ∀ t, s + t - s = t := multiset.induction_on s (by simp) (λ a s IH t, by rw [cons_add, sub_cons, erase_cons_head, IH]) @[simp] theorem add_sub_cancel (s t : multiset α) : s + t - t = s := by rw [add_comm, add_sub_cancel_left] theorem sub_le_sub_right (h : s ≤ t) (u) : s - u ≤ t - u := by revert s t h; exact multiset.induction_on u (by simp {contextual := tt}) (λ a u IH s t h, by simp [IH, erase_le_erase a h]) theorem sub_le_sub_left (h : s ≤ t) : ∀ u, u - t ≤ u - s := le_induction_on h $ λ l₁ l₂ h, begin induction h with l₁ l₂ a s IH l₁ l₂ a s IH; intro u, { refl }, { rw [← cons_coe, sub_cons], exact le_trans (sub_le_sub_right (erase_le _ _) _) (IH u) }, { rw [← cons_coe, sub_cons, ← cons_coe, sub_cons], exact IH _ } end theorem sub_le_iff_le_add : s - t ≤ u ↔ s ≤ u + t := by revert s; exact multiset.induction_on t (by simp) (λ a t IH s, by simp [IH, erase_le_iff_le_cons]) theorem le_sub_add (s t : multiset α) : s ≤ s - t + t := sub_le_iff_le_add.1 (le_refl _) theorem sub_le_self (s t : multiset α) : s - t ≤ s := sub_le_iff_le_add.2 (le_add_right _ _) @[simp] theorem card_sub {s t : multiset α} (h : t ≤ s) : card (s - t) = card s - card t := (nat.sub_eq_of_eq_add $ by rw [add_comm, ← card_add, sub_add_cancel h]).symm /-! ### Union -/ /-- `s ∪ t` is the lattice join operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∪ t` is the maximum of the multiplicities in `s` and `t`. -/ def union (s t : multiset α) : multiset α := s - t + t instance : has_union (multiset α) := ⟨union⟩ theorem union_def (s t : multiset α) : s ∪ t = s - t + t := rfl theorem le_union_left (s t : multiset α) : s ≤ s ∪ t := le_sub_add _ _ theorem le_union_right (s t : multiset α) : t ≤ s ∪ t := le_add_left _ _ theorem eq_union_left : t ≤ s → s ∪ t = s := sub_add_cancel theorem union_le_union_right (h : s ≤ t) (u) : s ∪ u ≤ t ∪ u := add_le_add_right (sub_le_sub_right h _) u theorem union_le (h₁ : s ≤ u) (h₂ : t ≤ u) : s ∪ t ≤ u := by rw ← eq_union_left h₂; exact union_le_union_right h₁ t @[simp] theorem mem_union : a ∈ s ∪ t ↔ a ∈ s ∨ a ∈ t := ⟨λ h, (mem_add.1 h).imp_left (mem_of_le $ sub_le_self _ _), or.rec (mem_of_le $ le_union_left _ _) (mem_of_le $ le_union_right _ _)⟩ @[simp] theorem map_union [decidable_eq β] {f : α → β} (finj : function.injective f) {s t : multiset α} : map f (s ∪ t) = map f s ∪ map f t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe (by rw [list.map_append f, list.map_diff finj]) /-! ### Intersection -/ /-- `s ∩ t` is the lattice meet operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∩ t` is the minimum of the multiplicities in `s` and `t`. -/ def inter (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.bag_inter l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ p₁.bag_inter p₂ instance : has_inter (multiset α) := ⟨inter⟩ @[simp] theorem inter_zero (s : multiset α) : s ∩ 0 = 0 := quot.induction_on s $ λ l, congr_arg coe l.bag_inter_nil @[simp] theorem zero_inter (s : multiset α) : 0 ∩ s = 0 := quot.induction_on s $ λ l, congr_arg coe l.nil_bag_inter @[simp] theorem cons_inter_of_pos {a} (s : multiset α) {t} : a ∈ t → (a ::ₘ s) ∩ t = a ::ₘ s ∩ t.erase a := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ cons_bag_inter_of_pos _ h @[simp] theorem cons_inter_of_neg {a} (s : multiset α) {t} : a ∉ t → (a ::ₘ s) ∩ t = s ∩ t := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ cons_bag_inter_of_neg _ h theorem inter_le_left (s t : multiset α) : s ∩ t ≤ s := quotient.induction_on₂ s t $ λ l₁ l₂, (bag_inter_sublist_left _ _).subperm theorem inter_le_right (s : multiset α) : ∀ t, s ∩ t ≤ t := multiset.induction_on s (λ t, (zero_inter t).symm ▸ zero_le _) $ λ a s IH t, if h : a ∈ t then by simpa [h] using cons_le_cons a (IH (t.erase a)) else by simp [h, IH] theorem le_inter (h₁ : s ≤ t) (h₂ : s ≤ u) : s ≤ t ∩ u := begin revert s u, refine multiset.induction_on t _ (λ a t IH, _); intros, { simp [h₁] }, by_cases a ∈ u, { rw [cons_inter_of_pos _ h, ← erase_le_iff_le_cons], exact IH (erase_le_iff_le_cons.2 h₁) (erase_le_erase _ h₂) }, { rw cons_inter_of_neg _ h, exact IH ((le_cons_of_not_mem $ mt (mem_of_le h₂) h).1 h₁) h₂ } end @[simp] theorem mem_inter : a ∈ s ∩ t ↔ a ∈ s ∧ a ∈ t := ⟨λ h, ⟨mem_of_le (inter_le_left _ _) h, mem_of_le (inter_le_right _ _) h⟩, λ ⟨h₁, h₂⟩, by rw [← cons_erase h₁, cons_inter_of_pos _ h₂]; apply mem_cons_self⟩ instance : lattice (multiset α) := { sup := (∪), sup_le := @union_le _ _, le_sup_left := le_union_left, le_sup_right := le_union_right, inf := (∩), le_inf := @le_inter _ _, inf_le_left := inter_le_left, inf_le_right := inter_le_right, ..@multiset.partial_order α } @[simp] theorem sup_eq_union (s t : multiset α) : s ⊔ t = s ∪ t := rfl @[simp] theorem inf_eq_inter (s t : multiset α) : s ⊓ t = s ∩ t := rfl @[simp] theorem le_inter_iff : s ≤ t ∩ u ↔ s ≤ t ∧ s ≤ u := le_inf_iff @[simp] theorem union_le_iff : s ∪ t ≤ u ↔ s ≤ u ∧ t ≤ u := sup_le_iff instance : semilattice_inf_bot (multiset α) := { bot := 0, bot_le := zero_le, ..multiset.lattice } theorem union_comm (s t : multiset α) : s ∪ t = t ∪ s := sup_comm theorem inter_comm (s t : multiset α) : s ∩ t = t ∩ s := inf_comm theorem eq_union_right (h : s ≤ t) : s ∪ t = t := by rw [union_comm, eq_union_left h] theorem union_le_union_left (h : s ≤ t) (u) : u ∪ s ≤ u ∪ t := sup_le_sup_left h _ theorem union_le_add (s t : multiset α) : s ∪ t ≤ s + t := union_le (le_add_right _ _) (le_add_left _ _) theorem union_add_distrib (s t u : multiset α) : (s ∪ t) + u = (s + u) ∪ (t + u) := by simpa [(∪), union, eq_comm, add_assoc] using show s + u - (t + u) = s - t, by rw [add_comm t, sub_add', add_sub_cancel] theorem add_union_distrib (s t u : multiset α) : s + (t ∪ u) = (s + t) ∪ (s + u) := by rw [add_comm, union_add_distrib, add_comm s, add_comm s] theorem cons_union_distrib (a : α) (s t : multiset α) : a ::ₘ (s ∪ t) = (a ::ₘ s) ∪ (a ::ₘ t) := by simpa using add_union_distrib (a ::ₘ 0) s t theorem inter_add_distrib (s t u : multiset α) : (s ∩ t) + u = (s + u) ∩ (t + u) := begin by_contra h, cases lt_iff_cons_le.1 (lt_of_le_of_ne (le_inter (add_le_add_right (inter_le_left s t) u) (add_le_add_right (inter_le_right s t) u)) h) with a hl, rw ← cons_add at hl, exact not_le_of_lt (lt_cons_self (s ∩ t) a) (le_inter (le_of_add_le_add_right (le_trans hl (inter_le_left _ _))) (le_of_add_le_add_right (le_trans hl (inter_le_right _ _)))) end theorem add_inter_distrib (s t u : multiset α) : s + (t ∩ u) = (s + t) ∩ (s + u) := by rw [add_comm, inter_add_distrib, add_comm s, add_comm s] theorem cons_inter_distrib (a : α) (s t : multiset α) : a ::ₘ (s ∩ t) = (a ::ₘ s) ∩ (a ::ₘ t) := by simp theorem union_add_inter (s t : multiset α) : s ∪ t + s ∩ t = s + t := begin apply le_antisymm, { rw union_add_distrib, refine union_le (add_le_add_left (inter_le_right _ _) _) _, rw add_comm, exact add_le_add_right (inter_le_left _ _) _ }, { rw [add_comm, add_inter_distrib], refine le_inter (add_le_add_right (le_union_right _ _) _) _, rw add_comm, exact add_le_add_right (le_union_left _ _) _ } end theorem sub_add_inter (s t : multiset α) : s - t + s ∩ t = s := begin rw [inter_comm], revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _), by_cases a ∈ s, { rw [cons_inter_of_pos _ h, sub_cons, add_cons, IH, cons_erase h] }, { rw [cons_inter_of_neg _ h, sub_cons, erase_of_not_mem h, IH] } end theorem sub_inter (s t : multiset α) : s - (s ∩ t) = s - t := add_right_cancel $ by rw [sub_add_inter s t, sub_add_cancel (inter_le_left _ _)] end /-! ### `multiset.filter` -/ section variables (p : α → Prop) [decidable_pred p] /-- `filter p s` returns the elements in `s` (with the same multiplicities) which satisfy `p`, and removes the rest. -/ def filter (s : multiset α) : multiset α := quot.lift_on s (λ l, (filter p l : multiset α)) (λ l₁ l₂ h, quot.sound $ h.filter p) @[simp] theorem coe_filter (l : list α) : filter p (↑l) = l.filter p := rfl @[simp] theorem filter_zero : filter p 0 = 0 := rfl lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q] {s : multiset α} : (∀ x ∈ s, p x ↔ q x) → filter p s = filter q s := quot.induction_on s $ λ l h, congr_arg coe $ filter_congr h @[simp] theorem filter_add (s t : multiset α) : filter p (s + t) = filter p s + filter p t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ filter_append _ _ @[simp] theorem filter_le (s : multiset α) : filter p s ≤ s := quot.induction_on s $ λ l, (filter_sublist _).subperm @[simp] theorem filter_subset (s : multiset α) : filter p s ⊆ s := subset_of_le $ filter_le _ _ theorem filter_le_filter {s t} (h : s ≤ t) : filter p s ≤ filter p t := le_induction_on h $ λ l₁ l₂ h, (filter_sublist_filter p h).subperm variable {p} @[simp] theorem filter_cons_of_pos {a : α} (s) : p a → filter p (a ::ₘ s) = a ::ₘ filter p s := quot.induction_on s $ λ l h, congr_arg coe $ filter_cons_of_pos l h @[simp] theorem filter_cons_of_neg {a : α} (s) : ¬ p a → filter p (a ::ₘ s) = filter p s := quot.induction_on s $ λ l h, @congr_arg _ _ _ _ coe $ filter_cons_of_neg l h @[simp] theorem mem_filter {a : α} {s} : a ∈ filter p s ↔ a ∈ s ∧ p a := quot.induction_on s $ λ l, mem_filter theorem of_mem_filter {a : α} {s} (h : a ∈ filter p s) : p a := (mem_filter.1 h).2 theorem mem_of_mem_filter {a : α} {s} (h : a ∈ filter p s) : a ∈ s := (mem_filter.1 h).1 theorem mem_filter_of_mem {a : α} {l} (m : a ∈ l) (h : p a) : a ∈ filter p l := mem_filter.2 ⟨m, h⟩ theorem filter_eq_self {s} : filter p s = s ↔ ∀ a ∈ s, p a := quot.induction_on s $ λ l, iff.trans ⟨λ h, eq_of_sublist_of_length_eq (filter_sublist _) (@congr_arg _ _ _ _ card h), congr_arg coe⟩ filter_eq_self theorem filter_eq_nil {s} : filter p s = 0 ↔ ∀ a ∈ s, ¬p a := quot.induction_on s $ λ l, iff.trans ⟨λ h, eq_nil_of_length_eq_zero (@congr_arg _ _ _ _ card h), congr_arg coe⟩ filter_eq_nil theorem le_filter {s t} : s ≤ filter p t ↔ s ≤ t ∧ ∀ a ∈ s, p a := ⟨λ h, ⟨le_trans h (filter_le _ _), λ a m, of_mem_filter (mem_of_le h m)⟩, λ ⟨h, al⟩, filter_eq_self.2 al ▸ filter_le_filter p h⟩ variable (p) @[simp] theorem filter_sub [decidable_eq α] (s t : multiset α) : filter p (s - t) = filter p s - filter p t := begin revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _), rw [sub_cons, IH], by_cases p a, { rw [filter_cons_of_pos _ h, sub_cons], congr, by_cases m : a ∈ s, { rw [← cons_inj_right a, ← filter_cons_of_pos _ h, cons_erase (mem_filter_of_mem m h), cons_erase m] }, { rw [erase_of_not_mem m, erase_of_not_mem (mt mem_of_mem_filter m)] } }, { rw [filter_cons_of_neg _ h], by_cases m : a ∈ s, { rw [(by rw filter_cons_of_neg _ h : filter p (erase s a) = filter p (a ::ₘ erase s a)), cons_erase m] }, { rw [erase_of_not_mem m] } } end @[simp] theorem filter_union [decidable_eq α] (s t : multiset α) : filter p (s ∪ t) = filter p s ∪ filter p t := by simp [(∪), union] @[simp] theorem filter_inter [decidable_eq α] (s t : multiset α) : filter p (s ∩ t) = filter p s ∩ filter p t := le_antisymm (le_inter (filter_le_filter _ $ inter_le_left _ _) (filter_le_filter _ $ inter_le_right _ _)) $ le_filter.2 ⟨inf_le_inf (filter_le _ _) (filter_le _ _), λ a h, of_mem_filter (mem_of_le (inter_le_left _ _) h)⟩ @[simp] theorem filter_filter (q) [decidable_pred q] (s : multiset α) : filter p (filter q s) = filter (λ a, p a ∧ q a) s := quot.induction_on s $ λ l, congr_arg coe $ filter_filter p q l theorem filter_add_filter (q) [decidable_pred q] (s : multiset α) : filter p s + filter q s = filter (λ a, p a ∨ q a) s + filter (λ a, p a ∧ q a) s := multiset.induction_on s rfl $ λ a s IH, by by_cases p a; by_cases q a; simp * theorem filter_add_not (s : multiset α) : filter p s + filter (λ a, ¬ p a) s = s := by rw [filter_add_filter, filter_eq_self.2, filter_eq_nil.2]; simp [decidable.em] theorem map_filter (f : β → α) (s : multiset β) : filter p (map f s) = map f (filter (p ∘ f) s) := quot.induction_on s (λ l, by simp [map_filter]) /-! ### Simultaneously filter and map elements of a multiset -/ /-- `filter_map f s` is a combination filter/map operation on `s`. The function `f : α → option β` is applied to each element of `s`; if `f a` is `some b` then `b` is added to the result, otherwise `a` is removed from the resulting multiset. -/ def filter_map (f : α → option β) (s : multiset α) : multiset β := quot.lift_on s (λ l, (filter_map f l : multiset β)) (λ l₁ l₂ h, quot.sound $ h.filter_map f) @[simp] theorem coe_filter_map (f : α → option β) (l : list α) : filter_map f l = l.filter_map f := rfl @[simp] theorem filter_map_zero (f : α → option β) : filter_map f 0 = 0 := rfl @[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (s : multiset α) (h : f a = none) : filter_map f (a ::ₘ s) = filter_map f s := quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_none a l h @[simp] theorem filter_map_cons_some (f : α → option β) (a : α) (s : multiset α) {b : β} (h : f a = some b) : filter_map f (a ::ₘ s) = b ::ₘ filter_map f s := quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_some f a l h theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f := funext $ λ s, quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_map f) l theorem filter_map_eq_filter : filter_map (option.guard p) = filter p := funext $ λ s, quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_filter p) l theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (s : multiset α) : filter_map g (filter_map f s) = filter_map (λ x, (f x).bind g) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter_map f g l theorem map_filter_map (f : α → option β) (g : β → γ) (s : multiset α) : map g (filter_map f s) = filter_map (λ x, (f x).map g) s := quot.induction_on s $ λ l, congr_arg coe $ map_filter_map f g l theorem filter_map_map (f : α → β) (g : β → option γ) (s : multiset α) : filter_map g (map f s) = filter_map (g ∘ f) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_map f g l theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (s : multiset α) : filter p (filter_map f s) = filter_map (λ x, (f x).filter p) s := quot.induction_on s $ λ l, congr_arg coe $ filter_filter_map f p l theorem filter_map_filter (f : α → option β) (s : multiset α) : filter_map f (filter p s) = filter_map (λ x, if p x then f x else none) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter p f l @[simp] theorem filter_map_some (s : multiset α) : filter_map some s = s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_some l @[simp] theorem mem_filter_map (f : α → option β) (s : multiset α) {b : β} : b ∈ filter_map f s ↔ ∃ a, a ∈ s ∧ f a = some b := quot.induction_on s $ λ l, mem_filter_map f l theorem map_filter_map_of_inv (f : α → option β) (g : β → α) (H : ∀ x : α, (f x).map g = some x) (s : multiset α) : map g (filter_map f s) = s := quot.induction_on s $ λ l, congr_arg coe $ map_filter_map_of_inv f g H l theorem filter_map_le_filter_map (f : α → option β) {s t : multiset α} (h : s ≤ t) : filter_map f s ≤ filter_map f t := le_induction_on h $ λ l₁ l₂ h, (h.filter_map _).subperm /-! ### countp -/ /-- `countp p s` counts the number of elements of `s` (with multiplicity) that satisfy `p`. -/ def countp (s : multiset α) : ℕ := quot.lift_on s (countp p) (λ l₁ l₂, perm.countp_eq p) @[simp] theorem coe_countp (l : list α) : countp p l = l.countp p := rfl @[simp] theorem countp_zero : countp p 0 = 0 := rfl variable {p} @[simp] theorem countp_cons_of_pos {a : α} (s) : p a → countp p (a ::ₘ s) = countp p s + 1 := quot.induction_on s $ countp_cons_of_pos p @[simp] theorem countp_cons_of_neg {a : α} (s) : ¬ p a → countp p (a ::ₘ s) = countp p s := quot.induction_on s $ countp_cons_of_neg p variable (p) theorem countp_eq_card_filter (s) : countp p s = card (filter p s) := quot.induction_on s $ λ l, countp_eq_length_filter _ _ @[simp] theorem countp_add (s t) : countp p (s + t) = countp p s + countp p t := by simp [countp_eq_card_filter] instance countp.is_add_monoid_hom : is_add_monoid_hom (countp p : multiset α → ℕ) := { map_add := countp_add _, map_zero := countp_zero _ } @[simp] theorem countp_sub [decidable_eq α] {s t : multiset α} (h : t ≤ s) : countp p (s - t) = countp p s - countp p t := by simp [countp_eq_card_filter, h, filter_le_filter] theorem countp_le_of_le {s t} (h : s ≤ t) : countp p s ≤ countp p t := by simpa [countp_eq_card_filter] using card_le_of_le (filter_le_filter p h) @[simp] theorem countp_filter (q) [decidable_pred q] (s : multiset α) : countp p (filter q s) = countp (λ a, p a ∧ q a) s := by simp [countp_eq_card_filter] variable {p} theorem countp_pos {s} : 0 < countp p s ↔ ∃ a ∈ s, p a := by simp [countp_eq_card_filter, card_pos_iff_exists_mem] theorem countp_pos_of_mem {s a} (h : a ∈ s) (pa : p a) : 0 < countp p s := countp_pos.2 ⟨_, h, pa⟩ end /-! ### Multiplicity of an element -/ section variable [decidable_eq α] /-- `count a s` is the multiplicity of `a` in `s`. -/ def count (a : α) : multiset α → ℕ := countp (eq a) @[simp] theorem coe_count (a : α) (l : list α) : count a (↑l) = l.count a := coe_countp _ _ @[simp] theorem count_zero (a : α) : count a 0 = 0 := rfl @[simp] theorem count_cons_self (a : α) (s : multiset α) : count a (a ::ₘ s) = succ (count a s) := countp_cons_of_pos _ rfl @[simp, priority 990] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (s : multiset α) : count a (b ::ₘ s) = count a s := countp_cons_of_neg _ h theorem count_le_of_le (a : α) {s t} : s ≤ t → count a s ≤ count a t := countp_le_of_le _ theorem count_le_count_cons (a b : α) (s : multiset α) : count a s ≤ count a (b ::ₘ s) := count_le_of_le _ (le_cons_self _ _) theorem count_cons (a b : α) (s : multiset α) : count a (b ::ₘ s) = count a s + (if a = b then 1 else 0) := by by_cases h : a = b; simp [h] theorem count_singleton (a : α) : count a (a ::ₘ 0) = 1 := by simp @[simp] theorem count_add (a : α) : ∀ s t, count a (s + t) = count a s + count a t := countp_add _ instance count.is_add_monoid_hom (a : α) : is_add_monoid_hom (count a : multiset α → ℕ) := countp.is_add_monoid_hom _ @[simp] theorem count_smul (a : α) (n s) : count a (n •ℕ s) = n * count a s := by induction n; simp [*, succ_nsmul', succ_mul] theorem count_pos {a : α} {s : multiset α} : 0 < count a s ↔ a ∈ s := by simp [count, countp_pos] @[simp, priority 980] theorem count_eq_zero_of_not_mem {a : α} {s : multiset α} (h : a ∉ s) : count a s = 0 := by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h') @[simp] theorem count_eq_zero {a : α} {s : multiset α} : count a s = 0 ↔ a ∉ s := iff_not_comm.1 $ count_pos.symm.trans pos_iff_ne_zero theorem count_ne_zero {a : α} {s : multiset α} : count a s ≠ 0 ↔ a ∈ s := by simp [ne.def, count_eq_zero] @[simp] theorem count_repeat_self (a : α) (n : ℕ) : count a (repeat a n) = n := by simp [repeat] theorem count_repeat (a b : α) (n : ℕ) : count a (repeat b n) = if (a = b) then n else 0 := begin split_ifs with h₁, { rw [h₁, count_repeat_self] }, { rw [count_eq_zero], apply mt eq_of_mem_repeat h₁ }, end @[simp] theorem count_erase_self (a : α) (s : multiset α) : count a (erase s a) = pred (count a s) := begin by_cases a ∈ s, { rw [(by rw cons_erase h : count a s = count a (a ::ₘ erase s a)), count_cons_self]; refl }, { rw [erase_of_not_mem h, count_eq_zero.2 h]; refl } end @[simp, priority 980] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) (s : multiset α) : count a (erase s b) = count a s := begin by_cases b ∈ s, { rw [← count_cons_of_ne ab, cons_erase h] }, { rw [erase_of_not_mem h] } end @[simp] theorem count_sub (a : α) (s t : multiset α) : count a (s - t) = count a s - count a t := begin revert s, refine multiset.induction_on t (by simp) (λ b t IH s, _), rw [sub_cons, IH], by_cases ab : a = b, { subst b, rw [count_erase_self, count_cons_self, sub_succ, pred_sub] }, { rw [count_erase_of_ne ab, count_cons_of_ne ab] } end @[simp] theorem count_union (a : α) (s t : multiset α) : count a (s ∪ t) = max (count a s) (count a t) := by simp [(∪), union, sub_add_eq_max, -add_comm] @[simp] theorem count_inter (a : α) (s t : multiset α) : count a (s ∩ t) = min (count a s) (count a t) := begin apply @nat.add_left_cancel (count a (s - t)), rw [← count_add, sub_add_inter, count_sub, sub_add_min], end lemma count_sum {m : multiset β} {f : β → multiset α} {a : α} : count a (map f m).sum = sum (m.map $ λb, count a $ f b) := multiset.induction_on m (by simp) ( by simp) lemma count_bind {m : multiset β} {f : β → multiset α} {a : α} : count a (bind m f) = sum (m.map $ λb, count a $ f b) := count_sum theorem le_count_iff_repeat_le {a : α} {s : multiset α} {n : ℕ} : n ≤ count a s ↔ repeat a n ≤ s := quot.induction_on s $ λ l, le_count_iff_repeat_sublist.trans repeat_le_coe.symm @[simp] theorem count_filter_of_pos {p} [decidable_pred p] {a} {s : multiset α} (h : p a) : count a (filter p s) = count a s := quot.induction_on s $ λ l, count_filter h @[simp] theorem count_filter_of_neg {p} [decidable_pred p] {a} {s : multiset α} (h : ¬ p a) : count a (filter p s) = 0 := multiset.count_eq_zero_of_not_mem (λ t, h (of_mem_filter t)) theorem ext {s t : multiset α} : s = t ↔ ∀ a, count a s = count a t := quotient.induction_on₂ s t $ λ l₁ l₂, quotient.eq.trans perm_iff_count @[ext] theorem ext' {s t : multiset α} : (∀ a, count a s = count a t) → s = t := ext.2 @[simp] theorem coe_inter (s t : list α) : (s ∩ t : multiset α) = (s.bag_inter t : list α) := by ext; simp theorem le_iff_count {s t : multiset α} : s ≤ t ↔ ∀ a, count a s ≤ count a t := ⟨λ h a, count_le_of_le a h, λ al, by rw ← (ext.2 (λ a, by simp [max_eq_right (al a)]) : s ∪ t = t); apply le_union_left⟩ instance : distrib_lattice (multiset α) := { le_sup_inf := λ s t u, le_of_eq $ eq.symm $ ext.2 $ λ a, by simp only [max_min_distrib_left, multiset.count_inter, multiset.sup_eq_union, multiset.count_union, multiset.inf_eq_inter], ..multiset.lattice } instance : semilattice_sup_bot (multiset α) := { bot := 0, bot_le := zero_le, ..multiset.lattice } end @[simp] lemma mem_nsmul {a : α} {s : multiset α} {n : ℕ} (h0 : n ≠ 0) : a ∈ n •ℕ s ↔ a ∈ s := begin classical, cases n, { exfalso, apply h0 rfl }, rw [← not_iff_not, ← count_eq_zero, ← count_eq_zero], simp [h0], end /-! ### Lift a relation to `multiset`s -/ section rel /-- `rel r s t` -- lift the relation `r` between two elements to a relation between `s` and `t`, s.t. there is a one-to-one mapping betweem elements in `s` and `t` following `r`. -/ @[mk_iff] inductive rel (r : α → β → Prop) : multiset α → multiset β → Prop | zero : rel 0 0 | cons {a b as bs} : r a b → rel as bs → rel (a ::ₘ as) (b ::ₘ bs) variables {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop} private lemma rel_flip_aux {s t} (h : rel r s t) : rel (flip r) t s := rel.rec_on h rel.zero (assume _ _ _ _ h₀ h₁ ih, rel.cons h₀ ih) lemma rel_flip {s t} : rel (flip r) s t ↔ rel r t s := ⟨rel_flip_aux, rel_flip_aux⟩ lemma rel_eq_refl {s : multiset α} : rel (=) s s := multiset.induction_on s rel.zero (assume a s, rel.cons rfl) lemma rel_eq {s t : multiset α} : rel (=) s t ↔ s = t := begin split, { assume h, induction h; simp * }, { assume h, subst h, exact rel_eq_refl } end lemma rel.mono {p : α → β → Prop} {s t} (h : ∀a b, r a b → p a b) (hst : rel r s t) : rel p s t := begin induction hst, case rel.zero { exact rel.zero }, case rel.cons : a b s t hab hst ih { exact ih.cons (h a b hab) } end lemma rel.add {s t u v} (hst : rel r s t) (huv : rel r u v) : rel r (s + u) (t + v) := begin induction hst, case rel.zero { simpa using huv }, case rel.cons : a b s t hab hst ih { simpa using ih.cons hab } end lemma rel_flip_eq {s t : multiset α} : rel (λa b, b = a) s t ↔ s = t := show rel (flip (=)) s t ↔ s = t, by rw [rel_flip, rel_eq, eq_comm] @[simp] lemma rel_zero_left {b : multiset β} : rel r 0 b ↔ b = 0 := by rw [rel_iff]; simp @[simp] lemma rel_zero_right {a : multiset α} : rel r a 0 ↔ a = 0 := by rw [rel_iff]; simp lemma rel_cons_left {a as bs} : rel r (a ::ₘ as) bs ↔ (∃b bs', r a b ∧ rel r as bs' ∧ bs = b ::ₘ bs') := begin split, { generalize hm : a ::ₘ as = m, assume h, induction h generalizing as, case rel.zero { simp at hm, contradiction }, case rel.cons : a' b as' bs ha'b h ih { rcases cons_eq_cons.1 hm with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩, { subst eq₁, subst eq₂, exact ⟨b, bs, ha'b, h, rfl⟩ }, { rcases ih eq₂.symm with ⟨b', bs', h₁, h₂, eq⟩, exact ⟨b', b ::ₘ bs', h₁, eq₁.symm ▸ rel.cons ha'b h₂, eq.symm ▸ cons_swap _ _ _⟩ } } }, { exact assume ⟨b, bs', hab, h, eq⟩, eq.symm ▸ rel.cons hab h } end lemma rel_cons_right {as b bs} : rel r as (b ::ₘ bs) ↔ (∃a as', r a b ∧ rel r as' bs ∧ as = a ::ₘ as') := begin rw [← rel_flip, rel_cons_left], apply exists_congr, assume a, apply exists_congr, assume as', rw [rel_flip, flip] end lemma rel_add_left {as₀ as₁} : ∀{bs}, rel r (as₀ + as₁) bs ↔ (∃bs₀ bs₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ bs = bs₀ + bs₁) := multiset.induction_on as₀ (by simp) begin assume a s ih bs, simp only [ih, cons_add, rel_cons_left], split, { assume h, rcases h with ⟨b, bs', hab, h, rfl⟩, rcases h with ⟨bs₀, bs₁, h₀, h₁, rfl⟩, exact ⟨b ::ₘ bs₀, bs₁, ⟨b, bs₀, hab, h₀, rfl⟩, h₁, by simp⟩ }, { assume h, rcases h with ⟨bs₀, bs₁, h, h₁, rfl⟩, rcases h with ⟨b, bs, hab, h₀, rfl⟩, exact ⟨b, bs + bs₁, hab, ⟨bs, bs₁, h₀, h₁, rfl⟩, by simp⟩ } end lemma rel_add_right {as bs₀ bs₁} : rel r as (bs₀ + bs₁) ↔ (∃as₀ as₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ as = as₀ + as₁) := by rw [← rel_flip, rel_add_left]; simp [rel_flip] lemma rel_map_left {s : multiset γ} {f : γ → α} : ∀{t}, rel r (s.map f) t ↔ rel (λa b, r (f a) b) s t := multiset.induction_on s (by simp) (by simp [rel_cons_left] {contextual := tt}) lemma rel_map_right {s : multiset α} {t : multiset γ} {f : γ → β} : rel r s (t.map f) ↔ rel (λa b, r a (f b)) s t := by rw [← rel_flip, rel_map_left, ← rel_flip]; refl lemma rel_join {s t} (h : rel (rel r) s t) : rel r s.join t.join := begin induction h, case rel.zero { simp }, case rel.cons : a b s t hab hst ih { simpa using hab.add ih } end lemma rel_map {p : γ → δ → Prop} {s t} {f : α → γ} {g : β → δ} (h : (r ⇒ p) f g) (hst : rel r s t) : rel p (s.map f) (t.map g) := by rw [rel_map_left, rel_map_right]; exact hst.mono h lemma rel_bind {p : γ → δ → Prop} {s t} {f : α → multiset γ} {g : β → multiset δ} (h : (r ⇒ rel p) f g) (hst : rel r s t) : rel p (s.bind f) (t.bind g) := by apply rel_join; apply rel_map; assumption lemma card_eq_card_of_rel {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) : card s = card t := by induction h; simp [*] lemma exists_mem_of_rel_of_mem {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) : ∀ {a : α} (ha : a ∈ s), ∃ b ∈ t, r a b := begin induction h with x y s t hxy hst ih, { simp }, { assume a ha, cases mem_cons.1 ha with ha ha, { exact ⟨y, mem_cons_self _ _, ha.symm ▸ hxy⟩ }, { rcases ih ha with ⟨b, hbt, hab⟩, exact ⟨b, mem_cons.2 (or.inr hbt), hab⟩ } } end end rel section map theorem map_eq_map {f : α → β} (hf : function.injective f) {s t : multiset α} : s.map f = t.map f ↔ s = t := by rw [← rel_eq, ← rel_eq, rel_map_left, rel_map_right]; simp [hf.eq_iff] theorem map_injective {f : α → β} (hf : function.injective f) : function.injective (multiset.map f) := assume x y, (map_eq_map hf).1 end map section quot theorem map_mk_eq_map_mk_of_rel {r : α → α → Prop} {s t : multiset α} (hst : s.rel r t) : s.map (quot.mk r) = t.map (quot.mk r) := rel.rec_on hst rfl $ assume a b s t hab hst ih, by simp [ih, quot.sound hab] theorem exists_multiset_eq_map_quot_mk {r : α → α → Prop} (s : multiset (quot r)) : ∃t:multiset α, s = t.map (quot.mk r) := multiset.induction_on s ⟨0, rfl⟩ $ assume a s ⟨t, ht⟩, quot.induction_on a $ assume a, ht.symm ▸ ⟨a ::ₘ t, (map_cons _ _ _).symm⟩ theorem induction_on_multiset_quot {r : α → α → Prop} {p : multiset (quot r) → Prop} (s : multiset (quot r)) : (∀s:multiset α, p (s.map (quot.mk r))) → p s := match s, exists_multiset_eq_map_quot_mk s with _, ⟨t, rfl⟩ := assume h, h _ end end quot /-! ### Disjoint multisets -/ /-- `disjoint s t` means that `s` and `t` have no elements in common. -/ def disjoint (s t : multiset α) : Prop := ∀ ⦃a⦄, a ∈ s → a ∈ t → false @[simp] theorem coe_disjoint (l₁ l₂ : list α) : @disjoint α l₁ l₂ ↔ l₁.disjoint l₂ := iff.rfl theorem disjoint.symm {s t : multiset α} (d : disjoint s t) : disjoint t s | a i₂ i₁ := d i₁ i₂ theorem disjoint_comm {s t : multiset α} : disjoint s t ↔ disjoint t s := ⟨disjoint.symm, disjoint.symm⟩ theorem disjoint_left {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := iff.rfl theorem disjoint_right {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := disjoint_comm theorem disjoint_iff_ne {s t : multiset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by simp [disjoint_left, imp_not_comm] theorem disjoint_of_subset_left {s t u : multiset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t | x m₁ := d (h m₁) theorem disjoint_of_subset_right {s t u : multiset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t | x m m₁ := d m (h m₁) theorem disjoint_of_le_left {s t u : multiset α} (h : s ≤ u) : disjoint u t → disjoint s t := disjoint_of_subset_left (subset_of_le h) theorem disjoint_of_le_right {s t u : multiset α} (h : t ≤ u) : disjoint s u → disjoint s t := disjoint_of_subset_right (subset_of_le h) @[simp] theorem zero_disjoint (l : multiset α) : disjoint 0 l | a := (not_mem_nil a).elim @[simp, priority 1100] theorem singleton_disjoint {l : multiset α} {a : α} : disjoint (a ::ₘ 0) l ↔ a ∉ l := by simp [disjoint]; refl @[simp, priority 1100] theorem disjoint_singleton {l : multiset α} {a : α} : disjoint l (a ::ₘ 0) ↔ a ∉ l := by rw disjoint_comm; simp @[simp] theorem disjoint_add_left {s t u : multiset α} : disjoint (s + t) u ↔ disjoint s u ∧ disjoint t u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_add_right {s t u : multiset α} : disjoint s (t + u) ↔ disjoint s t ∧ disjoint s u := by rw [disjoint_comm, disjoint_add_left]; tauto @[simp] theorem disjoint_cons_left {a : α} {s t : multiset α} : disjoint (a ::ₘ s) t ↔ a ∉ t ∧ disjoint s t := (@disjoint_add_left _ (a ::ₘ 0) s t).trans $ by simp @[simp] theorem disjoint_cons_right {a : α} {s t : multiset α} : disjoint s (a ::ₘ t) ↔ a ∉ s ∧ disjoint s t := by rw [disjoint_comm, disjoint_cons_left]; tauto theorem inter_eq_zero_iff_disjoint [decidable_eq α] {s t : multiset α} : s ∩ t = 0 ↔ disjoint s t := by rw ← subset_zero; simp [subset_iff, disjoint] @[simp] theorem disjoint_union_left [decidable_eq α] {s t u : multiset α} : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_union_right [decidable_eq α] {s t u : multiset α} : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := by simp [disjoint, or_imp_distrib, forall_and_distrib] lemma disjoint_map_map {f : α → γ} {g : β → γ} {s : multiset α} {t : multiset β} : disjoint (s.map f) (t.map g) ↔ (∀a∈s, ∀b∈t, f a ≠ g b) := by { simp [disjoint, @eq_comm _ (f _) (g _)], refl } /-- `pairwise r m` states that there exists a list of the elements s.t. `r` holds pairwise on this list. -/ def pairwise (r : α → α → Prop) (m : multiset α) : Prop := ∃l:list α, m = l ∧ l.pairwise r lemma pairwise_coe_iff_pairwise {r : α → α → Prop} (hr : symmetric r) {l : list α} : multiset.pairwise r l ↔ l.pairwise r := iff.intro (assume ⟨l', eq, h⟩, ((quotient.exact eq).pairwise_iff hr).2 h) (assume h, ⟨l, rfl, h⟩) end multiset namespace multiset section choose variables (p : α → Prop) [decidable_pred p] (l : multiset α) /-- Given a proof `hp` that there exists a unique `a ∈ l` such that `p a`, `choose_x p l hp` returns that `a` together with proofs of `a ∈ l` and `p a`. -/ def choose_x : Π hp : (∃! a, a ∈ l ∧ p a), { a // a ∈ l ∧ p a } := quotient.rec_on l (λ l' ex_unique, list.choose_x p l' (exists_of_exists_unique ex_unique)) begin intros, funext hp, suffices all_equal : ∀ x y : { t // t ∈ b ∧ p t }, x = y, { apply all_equal }, { rintros ⟨x, px⟩ ⟨y, py⟩, rcases hp with ⟨z, ⟨z_mem_l, pz⟩, z_unique⟩, congr, calc x = z : z_unique x px ... = y : (z_unique y py).symm } end /-- Given a proof `hp` that there exists a unique `a ∈ l` such that `p a`, `choose p l hp` returns that `a`. -/ def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := (choose_x p l hp).property lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1 lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2 end choose variable (α) /-- The equivalence between lists and multisets of a subsingleton type. -/ def subsingleton_equiv [subsingleton α] : list α ≃ multiset α := { to_fun := coe, inv_fun := quot.lift id $ λ (a b : list α) (h : a ~ b), list.ext_le h.length_eq $ λ n h₁ h₂, subsingleton.elim _ _, left_inv := λ l, rfl, right_inv := λ m, quot.induction_on m $ λ l, rfl } variable {α} @[simp] lemma coe_subsingleton_equiv [subsingleton α] : (subsingleton_equiv α : list α → multiset α) = coe := rfl end multiset @[to_additive] theorem monoid_hom.map_multiset_prod [comm_monoid α] [comm_monoid β] (f : α →* β) (s : multiset α) : f s.prod = (s.map f).prod := (s.prod_hom f).symm
ee7130a2542aad009cfe6696518255d1ae1aa74b
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/stage0/src/Init/Lean/Elab/ResolveName.lean
e90bf21bee777a5521cc55287e3eee48f7031981
[ "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
5,178
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ prelude import Init.Lean.Hygiene import Init.Lean.Modifiers import Init.Lean.Elab.Alias namespace Lean namespace Elab inductive OpenDecl | simple (ns : Name) (except : List Name) | explicit (id : Name) (declName : Name) namespace OpenDecl instance : Inhabited OpenDecl := ⟨simple Name.anonymous []⟩ instance : HasToString OpenDecl := ⟨fun decl => match decl with | explicit id decl => toString id ++ " → " ++ toString decl | simple ns ex => toString ns ++ (if ex == [] then "" else " hiding " ++ toString ex)⟩ end OpenDecl def rootNamespace := `_root_ def removeRoot (n : Name) : Name := n.replacePrefix rootNamespace Name.anonymous /- Global name resolution -/ /- Check whether `ns ++ id` is a valid namepace name and/or there are aliases names `ns ++ id`. -/ private def resolveQualifiedName (env : Environment) (ns : Name) (id : Name) : List Name := let resolvedId := ns ++ id; let resolvedIds := getAliases env resolvedId; if env.contains resolvedId && (!id.isAtomic || !isProtected env resolvedId) then resolvedId :: resolvedIds else resolvedIds /- Check surrounding namespaces -/ private def resolveUsingNamespace (env : Environment) (id : Name) : Name → List Name | ns@(Name.str p _ _) => match resolveQualifiedName env ns id with | [] => resolveUsingNamespace p | resolvedIds => resolvedIds | _ => [] /- Check exact name -/ private def resolveExact (env : Environment) (id : Name) : Option Name := if id.isAtomic then none else let resolvedId := id.replacePrefix rootNamespace Name.anonymous; if env.contains resolvedId then some resolvedId else none /- Check open namespaces -/ private def resolveOpenDecls (env : Environment) (id : Name) : List OpenDecl → List Name → List Name | [], resolvedIds => resolvedIds | OpenDecl.simple ns exs :: openDecls, resolvedIds => if exs.elem id then resolveOpenDecls openDecls resolvedIds else let newResolvedIds := resolveQualifiedName env ns id; resolveOpenDecls openDecls (newResolvedIds ++ resolvedIds) | OpenDecl.explicit openedId resolvedId :: openDecls, resolvedIds => let resolvedIds := if id == openedId then resolvedId :: resolvedIds else resolvedIds; resolveOpenDecls openDecls resolvedIds private def resolveGlobalNameAux (env : Environment) (ns : Name) (openDecls : List OpenDecl) (scpView : MacroScopesView) : Name → List String → List (Name × List String) | id@(Name.str p s _), projs => -- NOTE: we assume that macro scopes always belong to the projected constant, not the projections let id := { name := id, .. scpView }.review; match resolveUsingNamespace env id ns with | resolvedIds@(_ :: _) => resolvedIds.eraseDups.map $ fun id => (id, projs) | [] => match resolveExact env id with | some newId => [(newId, projs)] | none => let resolvedIds := if env.contains id then [id] else []; let resolvedIds := resolveOpenDecls env id openDecls resolvedIds; let resolvedIds := getAliases env id ++ resolvedIds; match resolvedIds with | resolvedIds@(_ :: _) => resolvedIds.eraseDups.map $ fun id => (id, projs) | [] => resolveGlobalNameAux p (s::projs) | _, _ => [] def resolveGlobalName (env : Environment) (ns : Name) (openDecls : List OpenDecl) (id : Name) : List (Name × List String) := -- decode macro scopes from name before recursion let extractionResult := extractMacroScopes id; resolveGlobalNameAux env ns openDecls extractionResult extractionResult.name [] /- Namespace resolution -/ def resolveNamespaceUsingScope (env : Environment) (n : Name) : Name → Option Name | Name.anonymous => none | ns@(Name.str p _ _) => if isNamespace env (ns ++ n) then some (ns ++ n) else resolveNamespaceUsingScope p | _ => unreachable! def resolveNamespaceUsingOpenDecls (env : Environment) (n : Name) : List OpenDecl → Option Name | [] => none | OpenDecl.simple ns [] :: ds => if isNamespace env (ns ++ n) then some (ns ++ n) else resolveNamespaceUsingOpenDecls ds | _ :: ds => resolveNamespaceUsingOpenDecls ds /- Given a name `id` try to find namespace it refers to. The resolution procedure works as follows 1- If `id` is the extact name of an existing namespace, then return `id` 2- If `id` is in the scope of `namespace` commands the namespace `s_1. ... . s_n`, then return `s_1 . ... . s_i ++ n` if it is the name of an existing namespace. We search "backwards". 3- Finally, for each command `open N`, return `N ++ n` if it is the name of an existing namespace. We search "backwards" again. That is, we try the most recent `open` command first. We only consider simple `open` commands. -/ def resolveNamespace (env : Environment) (ns : Name) (openDecls : List OpenDecl) (id : Name) : Option Name := if isNamespace env id then some id else match resolveNamespaceUsingScope env id ns with | some n => some n | none => match resolveNamespaceUsingOpenDecls env id openDecls with | some n => some n | none => none end Elab end Lean
6c6c9929556199f26fc9edc10a0cf7a4cf0208f5
ca1ad81c8733787aba30f7a8d63f418508e12812
/clfrags/src/core/consequence_relation.lean
f1508a3404f40763d4e7ca301e645cdab500944e
[]
no_license
greati/hilbert-classical-fragments
5cdbe07851e979c8a03c621a5efd4d24bbfa333a
18a21ac6b2e890060eb4ae65752fc0245394d226
refs/heads/master
1,591,973,117,184
1,573,822,710,000
1,573,822,710,000
194,334,439
2
0
null
null
null
null
UTF-8
Lean
false
false
894
lean
import data.set open set namespace logic def reflexivity (R : set Prop → Prop → Prop) := ∀ α : Prop, R {α} α def monotonicity (R : set Prop → Prop → Prop) : Prop := ∀ Γ Δ : set Prop, ∀ α : Prop, Γ ⊆ Δ ∧ R Γ α → R Δ α def transitivity (R : set Prop → Prop → Prop) : Prop := ∀ Γ Δ : set Prop, ∀ α : Prop, R (Γ ∪ Δ) α ∧ (∀ β ∈ Δ, R Γ β) → R Γ α theorem transitivity_single (R : set Prop → Prop → Prop) : Prop := ∀ Γ : set Prop, ∀ α β : Prop, R (Γ ∪ {α}) β ∧ R Γ α → R Γ β variables {α β : Prop} variables {Γ Δ : set Prop} variable R : set Prop → Prop → Prop variable {reflCr : reflexivity R} variable {monCr : monotonicity R} variable {cutCr : transitivity R} example (x : Prop) : R {x} x := reflCr x end logic
813d4746d981843d26f6b9225f9fade5ac77fe33
94e33a31faa76775069b071adea97e86e218a8ee
/src/algebra/hom/freiman.lean
5de585bf795de68b457ba1e0247f758e6385c7e3
[ "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
17,321
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import algebra.big_operators.multiset import data.fun_like.basic /-! # Freiman homomorphisms In this file, we define Freiman homomorphisms. A `n`-Freiman homomorphism on `A` is a function `f : α → β` such that `f (x₁) * ... * f (xₙ) = f (y₁) * ... * f (yₙ)` for all `x₁, ..., xₙ, y₁, ..., yₙ ∈ A` such that `x₁ * ... * xₙ = y₁ * ... * yₙ`. In particular, any `mul_hom` is a Freiman homomorphism. They are of interest in additive combinatorics. ## Main declaration * `freiman_hom`: Freiman homomorphism. * `add_freiman_hom`: Additive Freiman homomorphism. ## Notation * `A →*[n] β`: Multiplicative `n`-Freiman homomorphism on `A` * `A →+[n] β`: Additive `n`-Freiman homomorphism on `A` ## Implementation notes In the context of combinatorics, we are interested in Freiman homomorphisms over sets which are not necessarily closed under addition/multiplication. This means we must parametrize them with a set in an `add_monoid`/`monoid` instead of the `add_monoid`/`monoid` itself. ## References [Yufei Zhao, *18.225: Graph Theory and Additive Combinatorics*](https://yufeizhao.com/gtac/) ## TODO `monoid_hom.to_freiman_hom` could be relaxed to `mul_hom.to_freiman_hom` by proving `(s.map f).prod = (t.map f).prod` directly by induction instead of going through `f s.prod`. Define `n`-Freiman isomorphisms. Affine maps induce Freiman homs. Concretely, provide the `add_freiman_hom_class (α →ₐ[𝕜] β) A β n` instance. -/ open multiset variables {F α β γ δ G : Type*} /-- An additive `n`-Freiman homomorphism is a map which preserves sums of `n` elements. -/ structure add_freiman_hom (A : set α) (β : Type*) [add_comm_monoid α] [add_comm_monoid β] (n : ℕ) := (to_fun : α → β) (map_sum_eq_map_sum' {s t : multiset α} (hsA : ∀ ⦃x⦄, x ∈ s → x ∈ A) (htA : ∀ ⦃x⦄, x ∈ t → x ∈ A) (hs : s.card = n) (ht : t.card = n) (h : s.sum = t.sum) : (s.map to_fun).sum = (t.map to_fun).sum) /-- A `n`-Freiman homomorphism on a set `A` is a map which preserves products of `n` elements. -/ @[to_additive add_freiman_hom] structure freiman_hom (A : set α) (β : Type*) [comm_monoid α] [comm_monoid β] (n : ℕ) := (to_fun : α → β) (map_prod_eq_map_prod' {s t : multiset α} (hsA : ∀ ⦃x⦄, x ∈ s → x ∈ A) (htA : ∀ ⦃x⦄, x ∈ t → x ∈ A) (hs : s.card = n) (ht : t.card = n) (h : s.prod = t.prod) : (s.map to_fun).prod = (t.map to_fun).prod) notation A ` →+[`:25 n:25 `] `:0 β:0 := add_freiman_hom A β n notation A ` →*[`:25 n:25 `] `:0 β:0 := freiman_hom A β n /-- `add_freiman_hom_class F s β n` states that `F` is a type of `n`-ary sums-preserving morphisms. You should extend this class when you extend `add_freiman_hom`. -/ class add_freiman_hom_class (F : Type*) (A : out_param $ set α) (β : out_param $ Type*) [add_comm_monoid α] [add_comm_monoid β] (n : ℕ) [fun_like F α (λ _, β)] := (map_sum_eq_map_sum' (f : F) {s t : multiset α} (hsA : ∀ ⦃x⦄, x ∈ s → x ∈ A) (htA : ∀ ⦃x⦄, x ∈ t → x ∈ A) (hs : s.card = n) (ht : t.card = n) (h : s.sum = t.sum) : (s.map f).sum = (t.map f).sum) /-- `freiman_hom_class F A β n` states that `F` is a type of `n`-ary products-preserving morphisms. You should extend this class when you extend `freiman_hom`. -/ @[to_additive add_freiman_hom_class "`add_freiman_hom_class F A β n` states that `F` is a type of `n`-ary sums-preserving morphisms. You should extend this class when you extend `add_freiman_hom`."] class freiman_hom_class (F : Type*) (A : out_param $ set α) (β : out_param $ Type*) [comm_monoid α] [comm_monoid β] (n : ℕ) [fun_like F α (λ _, β)] := (map_prod_eq_map_prod' (f : F) {s t : multiset α} (hsA : ∀ ⦃x⦄, x ∈ s → x ∈ A) (htA : ∀ ⦃x⦄, x ∈ t → x ∈ A) (hs : s.card = n) (ht : t.card = n) (h : s.prod = t.prod) : (s.map f).prod = (t.map f).prod) variables [fun_like F α (λ _, β)] section comm_monoid variables [comm_monoid α] [comm_monoid β] [comm_monoid γ] [comm_monoid δ] [comm_group G] {A : set α} {B : set β} {C : set γ} {n : ℕ} {a b c d : α} @[to_additive] lemma map_prod_eq_map_prod [freiman_hom_class F A β n] (f : F) {s t : multiset α} (hsA : ∀ ⦃x⦄, x ∈ s → x ∈ A) (htA : ∀ ⦃x⦄, x ∈ t → x ∈ A) (hs : s.card = n) (ht : t.card = n) (h : s.prod = t.prod) : (s.map f).prod = (t.map f).prod := freiman_hom_class.map_prod_eq_map_prod' f hsA htA hs ht h @[to_additive] lemma map_mul_map_eq_map_mul_map [freiman_hom_class F A β 2] (f : F) (ha : a ∈ A) (hb : b ∈ A) (hc : c ∈ A) (hd : d ∈ A) (h : a * b = c * d) : f a * f b = f c * f d := begin simp_rw ←prod_pair at ⊢ h, refine map_prod_eq_map_prod f _ _ (card_pair _ _) (card_pair _ _) h; simp [ha, hb, hc, hd], end namespace freiman_hom @[to_additive] instance fun_like : fun_like (A →*[n] β) α (λ _, β) := { coe := to_fun, coe_injective' := λ f g h, by cases f; cases g; congr' } @[to_additive] instance freiman_hom_class : freiman_hom_class (A →*[n] β) A β n := { map_prod_eq_map_prod' := map_prod_eq_map_prod' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ @[to_additive] instance : has_coe_to_fun (A →*[n] β) (λ _, α → β) := ⟨to_fun⟩ initialize_simps_projections freiman_hom (to_fun → apply) @[simp, to_additive] lemma to_fun_eq_coe (f : A →*[n] β) : f.to_fun = f := rfl @[ext, to_additive] lemma ext ⦃f g : A →*[n] β⦄ (h : ∀ x, f x = g x) : f = g := fun_like.ext f g h @[simp, to_additive] lemma coe_mk (f : α → β) (h : ∀ s t : multiset α, (∀ ⦃x⦄, x ∈ s → x ∈ A) → (∀ ⦃x⦄, x ∈ t → x ∈ A) → s.card = n → t.card = n → s.prod = t.prod → (s.map f).prod = (t.map f).prod) : ⇑(mk f h) = f := rfl @[simp, to_additive] lemma mk_coe (f : A →*[n] β) (h) : mk f h = f := ext $ λ _, rfl /-- The identity map from a commutative monoid to itself. -/ @[to_additive "The identity map from an additive commutative monoid to itself.", simps] protected def id (A : set α) (n : ℕ) : A →*[n] α := { to_fun := λ x, x, map_prod_eq_map_prod' := λ s t _ _ _ _ h, by rw [map_id', map_id', h] } /-- Composition of Freiman homomorphisms as a Freiman homomorphism. -/ @[to_additive "Composition of additive Freiman homomorphisms as an additive Freiman homomorphism."] protected def comp (f : B →*[n] γ) (g : A →*[n] β) (hAB : A.maps_to g B) : A →*[n] γ := { to_fun := f ∘ g, map_prod_eq_map_prod' := λ s t hsA htA hs ht h, begin rw [←map_map, map_prod_eq_map_prod f _ _ ((s.card_map _).trans hs) ((t.card_map _).trans ht) (map_prod_eq_map_prod g hsA htA hs ht h), map_map], { simpa using (λ a h, hAB (hsA h)) }, { simpa using (λ a h, hAB (htA h)) } end } @[simp, to_additive] lemma coe_comp (f : B →*[n] γ) (g : A →*[n] β) {hfg} : ⇑(f.comp g hfg) = f ∘ g := rfl @[to_additive] lemma comp_apply (f : B →*[n] γ) (g : A →*[n] β) {hfg} (x : α) : f.comp g hfg x = f (g x) := rfl @[to_additive] lemma comp_assoc (f : A →*[n] β) (g : B →*[n] γ) (h : C →*[n] δ) {hf hhg hgf} {hh : A.maps_to (g.comp f hgf) C} : (h.comp g hhg).comp f hf = h.comp (g.comp f hgf) hh := rfl @[to_additive] lemma cancel_right {g₁ g₂ : B →*[n] γ} {f : A →*[n] β} (hf : function.surjective f) {hg₁ hg₂} : g₁.comp f hg₁ = g₂.comp f hg₂ ↔ g₁ = g₂ := ⟨λ h, ext $ hf.forall.2 $ fun_like.ext_iff.1 h, λ h, h ▸ rfl⟩ @[to_additive] lemma cancel_right_on {g₁ g₂ : B →*[n] γ} {f : A →*[n] β} (hf : A.surj_on f B) {hf'} : A.eq_on (g₁.comp f hf') (g₂.comp f hf') ↔ B.eq_on g₁ g₂ := hf.cancel_right hf' @[to_additive] lemma cancel_left_on {g : B →*[n] γ} {f₁ f₂ : A →*[n] β} (hg : B.inj_on g) {hf₁ hf₂} : A.eq_on (g.comp f₁ hf₁) (g.comp f₂ hf₂) ↔ A.eq_on f₁ f₂ := hg.cancel_left hf₁ hf₂ @[simp, to_additive] lemma comp_id (f : A →*[n] β) {hf} : f.comp (freiman_hom.id A n) hf = f := ext $ λ x, rfl @[simp, to_additive] lemma id_comp (f : A →*[n] β) {hf} : (freiman_hom.id B n).comp f hf = f := ext $ λ x, rfl /-- `freiman_hom.const A n b` is the Freiman homomorphism sending everything to `b`. -/ @[to_additive "`add_freiman_hom.const n b` is the Freiman homomorphism sending everything to `b`."] def const (A : set α) (n : ℕ) (b : β) : A →*[n] β := { to_fun := λ _, b, map_prod_eq_map_prod' := λ s t _ _ hs ht _, by rw [multiset.map_const, multiset.map_const, prod_repeat, prod_repeat, hs, ht] } @[simp, to_additive] lemma const_apply (n : ℕ) (b : β) (x : α) : const A n b x = b := rfl @[simp, to_additive] lemma const_comp (n : ℕ) (c : γ) (f : A →*[n] β) {hf} : (const B n c).comp f hf = const A n c := rfl /-- `1` is the Freiman homomorphism sending everything to `1`. -/ @[to_additive "`0` is the Freiman homomorphism sending everything to `0`."] instance : has_one (A →*[n] β) := ⟨const A n 1⟩ @[simp, to_additive] lemma one_apply (x : α) : (1 : A →*[n] β) x = 1 := rfl @[simp, to_additive] lemma one_comp (f : A →*[n] β) {hf} : (1 : B →*[n] γ).comp f hf = 1 := rfl @[to_additive] instance : inhabited (A →*[n] β) := ⟨1⟩ /-- `f * g` is the Freiman homomorphism sends `x` to `f x * g x`. -/ @[to_additive "`f + g` is the Freiman homomorphism sending `x` to `f x + g x`."] instance : has_mul (A →*[n] β) := ⟨λ f g, { to_fun := λ x, f x * g x, map_prod_eq_map_prod' := λ s t hsA htA hs ht h, by rw [prod_map_mul, prod_map_mul, map_prod_eq_map_prod f hsA htA hs ht h, map_prod_eq_map_prod g hsA htA hs ht h] }⟩ @[simp, to_additive] lemma mul_apply (f g : A →*[n] β) (x : α) : (f * g) x = f x * g x := rfl @[to_additive] lemma mul_comp (g₁ g₂ : B →*[n] γ) (f : A →*[n] β) {hg hg₁ hg₂} : (g₁ * g₂).comp f hg = g₁.comp f hg₁ * g₂.comp f hg₂ := rfl /-- If `f` is a Freiman homomorphism to a commutative group, then `f⁻¹` is the Freiman homomorphism sending `x` to `(f x)⁻¹`. -/ @[to_additive "If `f` is a Freiman homomorphism to an additive commutative group, then `-f` is the Freiman homomorphism sending `x` to `-f x`."] instance : has_inv (A →*[n] G) := ⟨λ f, { to_fun := λ x, (f x)⁻¹, map_prod_eq_map_prod' := λ s t hsA htA hs ht h, by rw [prod_map_inv, prod_map_inv, map_prod_eq_map_prod f hsA htA hs ht h] }⟩ @[simp, to_additive] lemma inv_apply (f : A →*[n] G) (x : α) : f⁻¹ x = (f x)⁻¹ := rfl @[simp, to_additive] lemma inv_comp (f : B →*[n] G) (g : A →*[n] β) {hf hf'} : f⁻¹.comp g hf = (f.comp g hf')⁻¹ := ext $ λ x, rfl /-- If `f` and `g` are Freiman homomorphisms to a commutative group, then `f / g` is the Freiman homomorphism sending `x` to `f x / g x`. -/ @[to_additive "If `f` and `g` are additive Freiman homomorphisms to an additive commutative group, then `f - g` is the additive Freiman homomorphism sending `x` to `f x - g x`"] instance : has_div (A →*[n] G) := ⟨λ f g, { to_fun := λ x, f x / g x, map_prod_eq_map_prod' := λ s t hsA htA hs ht h, by rw [prod_map_div, prod_map_div, map_prod_eq_map_prod f hsA htA hs ht h, map_prod_eq_map_prod g hsA htA hs ht h] }⟩ @[simp, to_additive] lemma div_apply (f g : A →*[n] G) (x : α) : (f / g) x = f x / g x := rfl @[simp, to_additive] lemma div_comp (f₁ f₂ : B →*[n] G) (g : A →*[n] β) {hf hf₁ hf₂} : (f₁ / f₂).comp g hf = f₁.comp g hf₁ / f₂.comp g hf₂ := ext $ λ x, rfl /-! ### Instances -/ /-- `A →*[n] β` is a `comm_monoid`. -/ @[to_additive "`α →+[n] β` is an `add_comm_monoid`."] instance : comm_monoid (A →*[n] β) := { mul := (*), mul_assoc := λ a b c, by { ext, apply mul_assoc }, one := 1, one_mul := λ a, by { ext, apply one_mul }, mul_one := λ a, by { ext, apply mul_one }, mul_comm := λ a b, by { ext, apply mul_comm }, npow := λ m f, { to_fun := λ x, f x ^ m, map_prod_eq_map_prod' := λ s t hsA htA hs ht h, by rw [prod_map_pow, prod_map_pow, map_prod_eq_map_prod f hsA htA hs ht h] }, npow_zero' := λ f, by { ext x, exact pow_zero _ }, npow_succ' := λ n f, by { ext x, exact pow_succ _ _ } } /-- If `β` is a commutative group, then `A →*[n] β` is a commutative group too. -/ @[to_additive "If `β` is an additive commutative group, then `A →*[n] β` is an additive commutative group too."] instance {β} [comm_group β] : comm_group (A →*[n] β) := { inv := has_inv.inv, div := has_div.div, div_eq_mul_inv := by { intros, ext, apply div_eq_mul_inv }, mul_left_inv := by { intros, ext, apply mul_left_inv }, zpow := λ n f, { to_fun := λ x, (f x) ^ n, map_prod_eq_map_prod' := λ s t hsA htA hs ht h, by rw [prod_map_zpow, prod_map_zpow, map_prod_eq_map_prod f hsA htA hs ht h] }, zpow_zero' := λ f, by { ext x, exact zpow_zero _ }, zpow_succ' := λ n f, by { ext x, simp_rw [zpow_of_nat, pow_succ, mul_apply, coe_mk] }, zpow_neg' := λ n f, by { ext x, simp_rw [zpow_neg_succ_of_nat, zpow_coe_nat], refl }, ..freiman_hom.comm_monoid } end freiman_hom /-! ### Hom hierarchy -/ --TODO: change to `monoid_hom_class F A β → freiman_hom_class F A β n` once `map_multiset_prod` is -- generalized /-- A monoid homomorphism is naturally a `freiman_hom` on its entire domain. We can't leave the domain `A : set α` of the `freiman_hom` a free variable, since it wouldn't be inferrable. -/ @[to_additive " An additive monoid homomorphism is naturally an `add_freiman_hom` on its entire domain. We can't leave the domain `A : set α` of the `freiman_hom` a free variable, since it wouldn't be inferrable."] instance monoid_hom.freiman_hom_class : freiman_hom_class (α →* β) set.univ β n := { map_prod_eq_map_prod' := λ f s t _ _ _ _ h, by rw [←f.map_multiset_prod, h, f.map_multiset_prod] } /-- A `monoid_hom` is naturally a `freiman_hom`. -/ @[to_additive add_monoid_hom.to_add_freiman_hom "An `add_monoid_hom` is naturally an `add_freiman_hom`"] def monoid_hom.to_freiman_hom (A : set α) (n : ℕ) (f : α →* β) : A →*[n] β := { to_fun := f, map_prod_eq_map_prod' := λ s t hsA htA, map_prod_eq_map_prod f (λ _ _, set.mem_univ _) (λ _ _, set.mem_univ _) } @[simp, to_additive] lemma monoid_hom.to_freiman_hom_coe (f : α →* β) : (f.to_freiman_hom A n : α → β) = f := rfl @[to_additive] lemma monoid_hom.to_freiman_hom_injective : function.injective (monoid_hom.to_freiman_hom A n : (α →* β) → A →*[n] β) := λ f g h, monoid_hom.ext $ show _, from fun_like.ext_iff.mp h end comm_monoid section cancel_comm_monoid variables [comm_monoid α] [cancel_comm_monoid β] {A : set α} {m n : ℕ} @[to_additive] lemma map_prod_eq_map_prod_of_le [freiman_hom_class F A β n] (f : F) {s t : multiset α} (hsA : ∀ x ∈ s, x ∈ A) (htA : ∀ x ∈ t, x ∈ A) (hs : s.card = m) (ht : t.card = m) (hst : s.prod = t.prod) (h : m ≤ n) : (s.map f).prod = (t.map f).prod := begin obtain rfl | hm := m.eq_zero_or_pos, { rw card_eq_zero at hs ht, rw [hs, ht] }, rw [←hs, card_pos_iff_exists_mem] at hm, obtain ⟨a, ha⟩ := hm, suffices : ((s + repeat a (n - m)).map f).prod = ((t + repeat a (n - m)).map f).prod, { simp_rw [multiset.map_add, prod_add] at this, exact mul_right_cancel this }, replace ha := hsA _ ha, refine map_prod_eq_map_prod f (λ x hx, _) (λ x hx, _) _ _ _, rotate 2, assumption, -- Can't infer `A` and `n` from the context, so do it manually. { rw mem_add at hx, refine hx.elim (hsA _) (λ h, _), rwa eq_of_mem_repeat h }, { rw mem_add at hx, refine hx.elim (htA _) (λ h, _), rwa eq_of_mem_repeat h }, { rw [card_add, hs, card_repeat, add_tsub_cancel_of_le h] }, { rw [card_add, ht, card_repeat, add_tsub_cancel_of_le h] }, { rw [prod_add, prod_add, hst] } end /-- `α →*[n] β` is naturally included in `A →*[m] β` for any `m ≤ n`. -/ @[to_additive add_freiman_hom.to_add_freiman_hom "`α →+[n] β` is naturally included in `α →+[m] β` for any `m ≤ n`"] def freiman_hom.to_freiman_hom (h : m ≤ n) (f : A →*[n] β) : A →*[m] β := { to_fun := f, map_prod_eq_map_prod' := λ s t hsA htA hs ht hst, map_prod_eq_map_prod_of_le f hsA htA hs ht hst h } /-- A `n`-Freiman homomorphism is also a `m`-Freiman homomorphism for any `m ≤ n`. -/ @[to_additive add_freiman_hom.add_freiman_hom_class_of_le "An additive `n`-Freiman homomorphism is also an additive `m`-Freiman homomorphism for any `m ≤ n`."] def freiman_hom.freiman_hom_class_of_le [freiman_hom_class F A β n] (h : m ≤ n) : freiman_hom_class F A β m := { map_prod_eq_map_prod' := λ f s t hsA htA hs ht hst, map_prod_eq_map_prod_of_le f hsA htA hs ht hst h } @[simp, to_additive add_freiman_hom.to_add_freiman_hom_coe] lemma freiman_hom.to_freiman_hom_coe (h : m ≤ n) (f : A →*[n] β) : (f.to_freiman_hom h : α → β) = f := rfl @[to_additive] lemma freiman_hom.to_freiman_hom_injective (h : m ≤ n) : function.injective (freiman_hom.to_freiman_hom h : (A →*[n] β) → A →*[m] β) := λ f g hfg, freiman_hom.ext $ by convert fun_like.ext_iff.1 hfg end cancel_comm_monoid
b3b4e30fff2616a35b5c7e24e44552e760109059
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/order/bounded_lattice.lean
031650ae4b88e97fd2d4d283ab6f7f489e43cc28
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
29,416
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 data.option.basic 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 section prio set_option default_priority 100 -- see Note [default priority] /-- 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 ≤ ⊤) end prio 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 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 haveI this := partial_order.ext H, have tt := order_top.ext_top H, cases A; cases B; injection this; congr' end section prio set_option default_priority 100 -- see Note [default priority] /-- 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) end prio 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 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 haveI this := partial_order.ext H, have tt := order_bot.ext_bot H, cases A; cases B; injection this; congr' end section prio set_option default_priority 100 -- see Note [default priority] /-- A `semilattice_sup_top` is a semilattice with top and join. -/ class semilattice_sup_top (α : Type u) extends order_top α, semilattice_sup α end prio 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 section prio set_option default_priority 100 -- see Note [default priority] /-- A `semilattice_sup_bot` is a semilattice with bottom and join. -/ class semilattice_sup_bot (α : Type u) extends order_bot α, semilattice_sup α end prio 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 } private def bot_aux (s : set ℕ) [decidable_pred s] [h : nonempty s] : s := have ∃ x, x ∈ s, from nonempty.elim h (λ x, ⟨x.1, x.2⟩), ⟨nat.find this, nat.find_spec this⟩ instance nat.subtype.semilattice_sup_bot (s : set ℕ) [decidable_pred s] [h : nonempty s] : semilattice_sup_bot s := { bot := bot_aux s, bot_le := λ x, nat.find_min' _ x.2, ..subtype.linear_order s, ..lattice_of_decidable_linear_order } section prio set_option default_priority 100 -- see Note [default priority] /-- A `semilattice_inf_top` is a semilattice with top and meet. -/ class semilattice_inf_top (α : Type u) extends order_top α, semilattice_inf α end prio 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 section prio set_option default_priority 100 -- see Note [default priority] /-- A `semilattice_inf_bot` is a semilattice with bottom and meet. -/ class semilattice_inf_bot (α : Type u) extends order_bot α, semilattice_inf α end prio 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 -/ section prio set_option default_priority 100 -- see Note [default priority] /-- 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 α end prio @[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 haveI H1 : @bounded_lattice.to_lattice α A = @bounded_lattice.to_lattice α B := lattice.ext H, haveI H2 := order_bot.ext H, haveI H3 : @bounded_lattice.to_order_top α A = @bounded_lattice.to_order_top α B := order_top.ext H, have tt := order_bot.ext_bot H, cases A; cases B; injection H1; injection H2; injection H3; congr' end section prio set_option default_priority 100 -- see Note [default priority] /-- A bounded distributive lattice is exactly what it sounds like. -/ class bounded_distrib_lattice α extends distrib_lattice α, bounded_lattice α end prio 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 (le_refl _) this ... = ⊥ : h₂⟩ /- Prop instance -/ instance bounded_lattice_Prop : bounded_lattice Prop := { bounded_lattice . 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), top := true, le_top := assume a Ha, true.intro, bot := false, bot_le := @false.elim } 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 /- Function lattices -/ /- TODO: * build up the lattice hierarchy for `fun`-functor piecewise. semilattic_*, bounded_lattice, lattice ... * can this be generalized to the dependent function space? -/ instance pi.bounded_lattice {α : Type u} {β : Type v} [bounded_lattice β] : bounded_lattice (α → β) := by pi_instance 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 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 [(<)] 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] 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 lemma coe_lt_coe [partial_order α] {a b : α} : (a : with_bot α) < b ↔ a < b := some_lt_some lemma bot_lt_some [partial_order α] (a : α) : (⊥ : with_bot α) < some a := lt_of_le_of_ne bot_le (λ h, option.no_confusion h) lemma bot_lt_coe [partial_order α] (a : α) : (⊥ : with_bot α) < a := bot_lt_some a 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 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] 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] 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 dense_coe [partial_order α] [densely_ordered α] [no_top_order α] {a b : with_top α} (h : a < b) : ∃ x : α, a < ↑x ∧ ↑x < b := let ⟨y, hy⟩ := dense h, ⟨x, hx⟩ := (lt_iff_exists_coe _ _).1 hy.2 in ⟨x, hx.1 ▸ hy⟩ end with_top 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
562f0635c541530c3dcca222bf0d102517bd020f
367134ba5a65885e863bdc4507601606690974c1
/src/algebra/group_power/lemmas.lean
1463a418a6d1107eadfcef7035720c50b3518073
[ "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
31,604
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis -/ import algebra.group_power.basic import algebra.opposites import data.list.basic import data.int.cast import data.equiv.basic import data.equiv.mul_add import deprecated.group /-! # Lemmas about power operations on monoids and groups This file contains lemmas about `monoid.pow`, `group.pow`, `nsmul`, `gsmul` which require additional imports besides those available in `.basic`. -/ universes u v w x y z u₁ u₂ variables {M : Type u} {N : Type v} {G : Type w} {H : Type x} {A : Type y} {B : Type z} {R : Type u₁} {S : Type u₂} /-! ### (Additive) monoid -/ section monoid variables [monoid M] [monoid N] [add_monoid A] [add_monoid B] @[simp] theorem nsmul_one [has_one A] : ∀ n : ℕ, n •ℕ (1 : A) = n := add_monoid_hom.eq_nat_cast ⟨λ n, n •ℕ (1 : A), zero_nsmul _, λ _ _, add_nsmul _ _ _⟩ (one_nsmul _) @[simp, priority 500] theorem list.prod_repeat (a : M) (n : ℕ) : (list.repeat a n).prod = a ^ n := begin induction n with n ih, { refl }, { rw [list.repeat_succ, list.prod_cons, ih], refl, } end @[simp, priority 500] theorem list.sum_repeat : ∀ (a : A) (n : ℕ), (list.repeat a n).sum = n •ℕ a := @list.prod_repeat (multiplicative A) _ @[simp, norm_cast] lemma units.coe_pow (u : units M) (n : ℕ) : ((u ^ n : units M) : M) = u ^ n := (units.coe_hom M).map_pow u n lemma is_unit_of_pow_eq_one (x : M) (n : ℕ) (hx : x ^ n = 1) (hn : 0 < n) : is_unit x := begin cases n, { exact (nat.not_lt_zero _ hn).elim }, refine ⟨⟨x, x ^ n, _, _⟩, rfl⟩, { rwa [pow_succ] at hx }, { rwa [pow_succ'] at hx } end end monoid theorem nat.nsmul_eq_mul (m n : ℕ) : m •ℕ n = m * n := by induction m with m ih; [rw [zero_nsmul, zero_mul], rw [succ_nsmul', ih, nat.succ_mul]] section group variables [group G] [group H] [add_group A] [add_group B] open int local attribute [ematch] le_of_lt open nat theorem gsmul_one [has_one A] (n : ℤ) : n •ℤ (1 : A) = n := by cases n; simp lemma gpow_add_one (a : G) : ∀ n : ℤ, a ^ (n + 1) = a ^ n * a | (of_nat n) := by simp [← int.coe_nat_succ, pow_succ'] | -[1+0] := by simp [int.neg_succ_of_nat_eq] | -[1+(n+1)] := by rw [int.neg_succ_of_nat_eq, gpow_neg, neg_add, neg_add_cancel_right, gpow_neg, ← int.coe_nat_succ, gpow_coe_nat, gpow_coe_nat, pow_succ _ (n + 1), mul_inv_rev, inv_mul_cancel_right] theorem add_one_gsmul : ∀ (a : A) (i : ℤ), (i + 1) •ℤ a = i •ℤ a + a := @gpow_add_one (multiplicative A) _ lemma gpow_sub_one (a : G) (n : ℤ) : a ^ (n - 1) = a ^ n * a⁻¹ := calc a ^ (n - 1) = a ^ (n - 1) * a * a⁻¹ : (mul_inv_cancel_right _ _).symm ... = a^n * a⁻¹ : by rw [← gpow_add_one, sub_add_cancel] lemma gpow_add (a : G) (m n : ℤ) : a ^ (m + n) = a ^ m * a ^ n := begin induction n using int.induction_on with n ihn n ihn, case hz : { simp }, { simp only [← add_assoc, gpow_add_one, ihn, mul_assoc] }, { rw [gpow_sub_one, ← mul_assoc, ← ihn, ← gpow_sub_one, add_sub_assoc] } end lemma mul_self_gpow (b : G) (m : ℤ) : b*b^m = b^(m+1) := by { conv_lhs {congr, rw ← gpow_one b }, rw [← gpow_add, add_comm] } lemma mul_gpow_self (b : G) (m : ℤ) : b^m*b = b^(m+1) := by { conv_lhs {congr, skip, rw ← gpow_one b }, rw [← gpow_add, add_comm] } theorem add_gsmul : ∀ (a : A) (i j : ℤ), (i + j) •ℤ a = i •ℤ a + j •ℤ a := @gpow_add (multiplicative A) _ lemma gpow_sub (a : G) (m n : ℤ) : a ^ (m - n) = a ^ m * (a ^ n)⁻¹ := by rw [sub_eq_add_neg, gpow_add, gpow_neg] lemma sub_gsmul (m n : ℤ) (a : A) : (m - n) •ℤ a = m •ℤ a - n •ℤ a := by simpa only [sub_eq_add_neg] using @gpow_sub (multiplicative A) _ _ _ _ theorem gpow_one_add (a : G) (i : ℤ) : a ^ (1 + i) = a * a ^ i := by rw [gpow_add, gpow_one] theorem one_add_gsmul : ∀ (a : A) (i : ℤ), (1 + i) •ℤ a = a + i •ℤ a := @gpow_one_add (multiplicative A) _ theorem gpow_mul_comm (a : G) (i j : ℤ) : a ^ i * a ^ j = a ^ j * a ^ i := by rw [← gpow_add, ← gpow_add, add_comm] theorem gsmul_add_comm : ∀ (a : A) (i j), i •ℤ a + j •ℤ a = j •ℤ a + i •ℤ a := @gpow_mul_comm (multiplicative A) _ theorem gpow_mul (a : G) (m n : ℤ) : a ^ (m * n) = (a ^ m) ^ n := int.induction_on n (by simp) (λ n ihn, by simp [mul_add, gpow_add, ihn]) (λ n ihn, by simp only [mul_sub, gpow_sub, ihn, mul_one, gpow_one]) theorem gsmul_mul' : ∀ (a : A) (m n : ℤ), m * n •ℤ a = n •ℤ (m •ℤ a) := @gpow_mul (multiplicative A) _ theorem gpow_mul' (a : G) (m n : ℤ) : a ^ (m * n) = (a ^ n) ^ m := by rw [mul_comm, gpow_mul] theorem gsmul_mul (a : A) (m n : ℤ) : m * n •ℤ a = m •ℤ (n •ℤ a) := by rw [mul_comm, gsmul_mul'] theorem gpow_bit0 (a : G) (n : ℤ) : a ^ bit0 n = a ^ n * a ^ n := gpow_add _ _ _ theorem bit0_gsmul (a : A) (n : ℤ) : bit0 n •ℤ a = n •ℤ a + n •ℤ a := gpow_add _ _ _ theorem gpow_bit1 (a : G) (n : ℤ) : a ^ bit1 n = a ^ n * a ^ n * a := by rw [bit1, gpow_add, gpow_bit0, gpow_one] theorem bit1_gsmul : ∀ (a : A) (n : ℤ), bit1 n •ℤ a = n •ℤ a + n •ℤ a + a := @gpow_bit1 (multiplicative A) _ @[simp] theorem monoid_hom.map_gpow (f : G →* H) (a : G) (n : ℤ) : f (a ^ n) = f a ^ n := by cases n; [exact f.map_pow _ _, exact (f.map_inv _).trans (congr_arg _ $ f.map_pow _ _)] @[simp] theorem add_monoid_hom.map_gsmul (f : A →+ B) (a : A) (n : ℤ) : f (n •ℤ a) = n •ℤ f a := f.to_multiplicative.map_gpow a n @[simp, norm_cast] lemma units.coe_gpow (u : units G) (n : ℤ) : ((u ^ n : units G) : G) = u ^ n := (units.coe_hom G).map_gpow u n end group section ordered_add_comm_group variables [ordered_add_comm_group A] /-! Lemmas about `gsmul` under ordering, placed here (rather than in `algebra.group_power.basic` with their friends) because they require facts from `data.int.basic`-/ open int lemma gsmul_pos {a : A} (ha : 0 < a) {k : ℤ} (hk : (0:ℤ) < k) : 0 < k •ℤ a := begin lift k to ℕ using int.le_of_lt hk, apply nsmul_pos ha, exact coe_nat_pos.mp hk, end theorem gsmul_le_gsmul {a : A} {n m : ℤ} (ha : 0 ≤ a) (h : n ≤ m) : n •ℤ a ≤ m •ℤ a := calc n •ℤ a = n •ℤ a + 0 : (add_zero _).symm ... ≤ n •ℤ a + (m - n) •ℤ a : add_le_add_left (gsmul_nonneg ha (sub_nonneg.mpr h)) _ ... = m •ℤ a : by { rw [← add_gsmul], simp } theorem gsmul_lt_gsmul {a : A} {n m : ℤ} (ha : 0 < a) (h : n < m) : n •ℤ a < m •ℤ a := calc n •ℤ a = n •ℤ a + 0 : (add_zero _).symm ... < n •ℤ a + (m - n) •ℤ a : add_lt_add_left (gsmul_pos ha (sub_pos.mpr h)) _ ... = m •ℤ a : by { rw [← add_gsmul], simp } lemma abs_nsmul {α : Type*} [linear_ordered_add_comm_group α] (n : ℕ) (a : α) : abs (n •ℕ a) = n •ℕ abs a := begin cases le_total a 0 with hneg hpos, { rw [abs_of_nonpos hneg, ← abs_neg, ← neg_nsmul, abs_of_nonneg], exact nsmul_nonneg (neg_nonneg.mpr hneg) n }, { rw [abs_of_nonneg hpos, abs_of_nonneg], exact nsmul_nonneg hpos n } end lemma abs_gsmul {α : Type*} [linear_ordered_add_comm_group α] (n : ℤ) (a : α) : abs (n •ℤ a) = (abs n) •ℤ abs a := begin by_cases n0 : 0 ≤ n, { lift n to ℕ using n0, simp only [abs_nsmul, coe_nat_abs, gsmul_coe_nat] }, { lift (- n) to ℕ using int.le_of_lt (neg_pos.mpr (not_le.mp n0)) with m h, rw [← abs_neg (n •ℤ a), ← neg_gsmul, ← abs_neg n, ← h], convert abs_nsmul m _, simp only [coe_nat_abs, gsmul_coe_nat] }, end lemma abs_add_eq_add_abs_le {α : Type*} [linear_ordered_add_comm_group α] {a b : α} (hle : a ≤ b) : abs (a + b) = abs a + abs b ↔ (0 ≤ a ∧ 0 ≤ b ∨ a ≤ 0 ∧ b ≤ 0) := begin by_cases a0 : 0 ≤ a; by_cases b0 : 0 ≤ b, { simp [a0, b0, abs_of_nonneg, add_nonneg a0 b0] }, { exact (lt_irrefl (0 : α) (a0.trans_lt (hle.trans_lt (not_le.mp b0)))).elim }, any_goals { simp [(not_le.mp a0).le, (not_le.mp b0).le, abs_of_nonpos, add_nonpos, add_comm] }, obtain F := (not_le.mp a0), have : (abs (a + b) = -a + b ↔ b ≤ 0) ↔ (abs (a + b) = abs a + abs b ↔ 0 ≤ a ∧ 0 ≤ b ∨ a ≤ 0 ∧ b ≤ 0), { simp [a0, b0, abs_of_neg, abs_of_nonneg, F, F.le] }, refine this.mp ⟨λ h, _, λ h, by simp only [le_antisymm h b0, abs_of_neg F, add_zero]⟩, by_cases ba : a + b ≤ 0, { refine le_of_eq (eq_zero_of_neg_eq _), rwa [abs_of_nonpos ba, neg_add_rev, add_comm, add_right_inj] at h }, { refine (lt_irrefl (0 : α) _).elim, rw [abs_of_pos (not_le.mp ba), add_left_inj] at h, rwa eq_zero_of_neg_eq h.symm at F } end lemma abs_add_eq_add_abs_iff {α : Type*} [linear_ordered_add_comm_group α] (a b : α) : abs (a + b) = abs a + abs b ↔ (0 ≤ a ∧ 0 ≤ b ∨ a ≤ 0 ∧ b ≤ 0) := begin by_cases ab : a ≤ b, { exact abs_add_eq_add_abs_le ab }, { rw [add_comm a, add_comm (abs _), abs_add_eq_add_abs_le ((not_le.mp ab).le), and.comm, @and.comm (b ≤ 0 ) _] } end end ordered_add_comm_group section linear_ordered_add_comm_group variable [linear_ordered_add_comm_group A] theorem gsmul_le_gsmul_iff {a : A} {n m : ℤ} (ha : 0 < a) : n •ℤ a ≤ m •ℤ a ↔ n ≤ m := begin refine ⟨λ h, _, gsmul_le_gsmul $ le_of_lt ha⟩, by_contra H, exact lt_irrefl _ (lt_of_lt_of_le (gsmul_lt_gsmul ha (not_le.mp H)) h) end theorem gsmul_lt_gsmul_iff {a : A} {n m : ℤ} (ha : 0 < a) : n •ℤ a < m •ℤ a ↔ n < m := begin refine ⟨λ h, _, gsmul_lt_gsmul ha⟩, by_contra H, exact lt_irrefl _ (lt_of_le_of_lt (gsmul_le_gsmul (le_of_lt ha) $ not_lt.mp H) h) end theorem nsmul_le_nsmul_iff {a : A} {n m : ℕ} (ha : 0 < a) : n •ℕ a ≤ m •ℕ a ↔ n ≤ m := begin refine ⟨λ h, _, nsmul_le_nsmul $ le_of_lt ha⟩, by_contra H, exact lt_irrefl _ (lt_of_lt_of_le (nsmul_lt_nsmul ha (not_le.mp H)) h) end theorem nsmul_lt_nsmul_iff {a : A} {n m : ℕ} (ha : 0 < a) : n •ℕ a < m •ℕ a ↔ n < m := begin refine ⟨λ h, _, nsmul_lt_nsmul ha⟩, by_contra H, exact lt_irrefl _ (lt_of_le_of_lt (nsmul_le_nsmul (le_of_lt ha) $ not_lt.mp H) h) end end linear_ordered_add_comm_group @[simp] lemma with_bot.coe_nsmul [add_monoid A] (a : A) (n : ℕ) : ((nsmul n a : A) : with_bot A) = nsmul n a := add_monoid_hom.map_nsmul ⟨(coe : A → with_bot A), with_bot.coe_zero, with_bot.coe_add⟩ a n theorem nsmul_eq_mul' [semiring R] (a : R) (n : ℕ) : n •ℕ a = a * n := by induction n with n ih; [rw [zero_nsmul, nat.cast_zero, mul_zero], rw [succ_nsmul', ih, nat.cast_succ, mul_add, mul_one]] @[simp] theorem nsmul_eq_mul [semiring R] (n : ℕ) (a : R) : n •ℕ a = n * a := by rw [nsmul_eq_mul', (n.cast_commute a).eq] theorem mul_nsmul_left [semiring R] (a b : R) (n : ℕ) : n •ℕ (a * b) = a * (n •ℕ b) := by rw [nsmul_eq_mul', nsmul_eq_mul', mul_assoc] theorem mul_nsmul_assoc [semiring R] (a b : R) (n : ℕ) : n •ℕ (a * b) = n •ℕ a * b := by rw [nsmul_eq_mul, nsmul_eq_mul, mul_assoc] @[simp, norm_cast] theorem nat.cast_pow [semiring R] (n m : ℕ) : (↑(n ^ m) : R) = ↑n ^ m := by induction m with m ih; [exact nat.cast_one, rw [pow_succ', pow_succ', nat.cast_mul, ih]] @[simp, norm_cast] theorem int.coe_nat_pow (n m : ℕ) : ((n ^ m : ℕ) : ℤ) = n ^ m := by induction m with m ih; [exact int.coe_nat_one, rw [pow_succ', pow_succ', int.coe_nat_mul, ih]] theorem int.nat_abs_pow (n : ℤ) (k : ℕ) : int.nat_abs (n ^ k) = (int.nat_abs n) ^ k := by induction k with k ih; [refl, rw [pow_succ', int.nat_abs_mul, pow_succ', ih]] -- The next four lemmas allow us to replace multiplication by a numeral with a `gsmul` expression. -- They are used by the `noncomm_ring` tactic, to normalise expressions before passing to `abel`. lemma bit0_mul [ring R] {n r : R} : bit0 n * r = gsmul 2 (n * r) := by { dsimp [bit0], rw [add_mul, add_gsmul, one_gsmul], } lemma mul_bit0 [ring R] {n r : R} : r * bit0 n = gsmul 2 (r * n) := by { dsimp [bit0], rw [mul_add, add_gsmul, one_gsmul], } lemma bit1_mul [ring R] {n r : R} : bit1 n * r = gsmul 2 (n * r) + r := by { dsimp [bit1], rw [add_mul, bit0_mul, one_mul], } lemma mul_bit1 [ring R] {n r : R} : r * bit1 n = gsmul 2 (r * n) + r := by { dsimp [bit1], rw [mul_add, mul_bit0, mul_one], } @[simp] theorem gsmul_eq_mul [ring R] (a : R) : ∀ n, n •ℤ a = n * a | (n : ℕ) := nsmul_eq_mul _ _ | -[1+ n] := show -(_ •ℕ _)=-_*_, by rw [neg_mul_eq_neg_mul_symm, nsmul_eq_mul, nat.cast_succ] theorem gsmul_eq_mul' [ring R] (a : R) (n : ℤ) : n •ℤ a = a * n := by rw [gsmul_eq_mul, (n.cast_commute a).eq] theorem mul_gsmul_left [ring R] (a b : R) (n : ℤ) : n •ℤ (a * b) = a * (n •ℤ b) := by rw [gsmul_eq_mul', gsmul_eq_mul', mul_assoc] theorem mul_gsmul_assoc [ring R] (a b : R) (n : ℤ) : n •ℤ (a * b) = n •ℤ a * b := by rw [gsmul_eq_mul, gsmul_eq_mul, mul_assoc] @[simp] lemma gsmul_int_int (a b : ℤ) : a •ℤ b = a * b := by simp [gsmul_eq_mul] lemma gsmul_int_one (n : ℤ) : n •ℤ 1 = n := by simp @[simp, norm_cast] theorem int.cast_pow [ring R] (n : ℤ) (m : ℕ) : (↑(n ^ m) : R) = ↑n ^ m := by induction m with m ih; [exact int.cast_one, rw [pow_succ, pow_succ, int.cast_mul, ih]] lemma neg_one_pow_eq_pow_mod_two [ring R] {n : ℕ} : (-1 : R) ^ n = (-1) ^ (n % 2) := by rw [← nat.mod_add_div n 2, pow_add, pow_mul]; simp [pow_two] section ordered_semiring variable [ordered_semiring R] /-- Bernoulli's inequality. This version works for semirings but requires additional hypotheses `0 ≤ a * a` and `0 ≤ (1 + a) * (1 + a)`. -/ theorem one_add_mul_le_pow' {a : R} (Hsqr : 0 ≤ a * a) (Hsqr' : 0 ≤ (1 + a) * (1 + a)) (H : 0 ≤ 2 + a) : ∀ (n : ℕ), 1 + (n : R) * a ≤ (1 + a) ^ n | 0 := by simp | 1 := by simp | (n+2) := have 0 ≤ (n : R) * (a * a * (2 + a)) + a * a, from add_nonneg (mul_nonneg n.cast_nonneg (mul_nonneg Hsqr H)) Hsqr, calc 1 + (↑(n + 2) : R) * a ≤ 1 + ↑(n + 2) * a + (n * (a * a * (2 + a)) + a * a) : (le_add_iff_nonneg_right _).2 this ... = (1 + a) * (1 + a) * (1 + n * a) : by { simp [add_mul, mul_add, bit0, mul_assoc, (n.cast_commute (_ : R)).left_comm], ac_refl } ... ≤ (1 + a) * (1 + a) * (1 + a)^n : mul_le_mul_of_nonneg_left (one_add_mul_le_pow' n) Hsqr' ... = (1 + a)^(n + 2) : by simp only [pow_succ, mul_assoc] private lemma pow_lt_pow_of_lt_one_aux {a : R} (h : 0 < a) (ha : a < 1) (i : ℕ) : ∀ k : ℕ, a ^ (i + k + 1) < a ^ i | 0 := begin simp only [add_zero], rw ←one_mul (a^i), exact mul_lt_mul ha (le_refl _) (pow_pos h _) zero_le_one end | (k+1) := begin rw ←one_mul (a^i), apply mul_lt_mul ha _ _ zero_le_one, { apply le_of_lt, apply pow_lt_pow_of_lt_one_aux }, { show 0 < a ^ (i + (k + 1) + 0), apply pow_pos h } end private lemma pow_le_pow_of_le_one_aux {a : R} (h : 0 ≤ a) (ha : a ≤ 1) (i : ℕ) : ∀ k : ℕ, a ^ (i + k) ≤ a ^ i | 0 := by simp | (k+1) := by rw [←add_assoc, ←one_mul (a^i)]; exact mul_le_mul ha (pow_le_pow_of_le_one_aux _) (pow_nonneg h _) zero_le_one lemma pow_lt_pow_of_lt_one {a : R} (h : 0 < a) (ha : a < 1) {i j : ℕ} (hij : i < j) : a ^ j < a ^ i := let ⟨k, hk⟩ := nat.exists_eq_add_of_lt hij in by rw hk; exact pow_lt_pow_of_lt_one_aux h ha _ _ lemma pow_lt_pow_iff_of_lt_one {a : R} {n m : ℕ} (hpos : 0 < a) (h : a < 1) : a ^ m < a ^ n ↔ n < m := begin have : strict_mono (λ (n : order_dual ℕ), a ^ (id n : ℕ)) := λ m n, pow_lt_pow_of_lt_one hpos h, exact this.lt_iff_lt end lemma pow_le_pow_of_le_one {a : R} (h : 0 ≤ a) (ha : a ≤ 1) {i j : ℕ} (hij : i ≤ j) : a ^ j ≤ a ^ i := let ⟨k, hk⟩ := nat.exists_eq_add_of_le hij in by rw hk; exact pow_le_pow_of_le_one_aux h ha _ _ lemma pow_le_one {x : R} : ∀ (n : ℕ) (h0 : 0 ≤ x) (h1 : x ≤ 1), x ^ n ≤ 1 | 0 h0 h1 := le_refl (1 : R) | (n+1) h0 h1 := mul_le_one h1 (pow_nonneg h0 _) (pow_le_one n h0 h1) end ordered_semiring section linear_ordered_semiring variables [linear_ordered_semiring R] lemma sign_cases_of_C_mul_pow_nonneg {C r : R} (h : ∀ n : ℕ, 0 ≤ C * r ^ n) : C = 0 ∨ (0 < C ∧ 0 ≤ r) := begin have : 0 ≤ C, by simpa only [pow_zero, mul_one] using h 0, refine this.eq_or_lt.elim (λ h, or.inl h.symm) (λ hC, or.inr ⟨hC, _⟩), refine nonneg_of_mul_nonneg_left _ hC, simpa only [pow_one] using h 1 end end linear_ordered_semiring section linear_ordered_ring variables [linear_ordered_ring R] {a : R} {n : ℕ} @[simp] lemma abs_pow (a : R) (n : ℕ) : abs (a ^ n) = abs a ^ n := abs_hom.to_monoid_hom.map_pow a n @[simp] theorem pow_bit1_neg_iff : a ^ bit1 n < 0 ↔ a < 0 := ⟨λ h, not_le.1 $ λ h', not_le.2 h $ pow_nonneg h' _, λ h, mul_neg_of_neg_of_pos h (pow_bit0_pos h.ne _)⟩ @[simp] theorem pow_bit1_nonneg_iff : 0 ≤ a ^ bit1 n ↔ 0 ≤ a := le_iff_le_iff_lt_iff_lt.2 pow_bit1_neg_iff @[simp] theorem pow_bit1_nonpos_iff : a ^ bit1 n ≤ 0 ↔ a ≤ 0 := by simp only [le_iff_lt_or_eq, pow_bit1_neg_iff, pow_eq_zero_iff (bit1_pos (zero_le n))] @[simp] theorem pow_bit1_pos_iff : 0 < a ^ bit1 n ↔ 0 < a := lt_iff_lt_of_le_iff_le pow_bit1_nonpos_iff theorem pow_even_nonneg (a : R) (hn : even n) : 0 ≤ a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using pow_bit0_nonneg a k theorem pow_even_pos (ha : a ≠ 0) (hn : even n) : 0 < a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using pow_bit0_pos ha k theorem pow_odd_nonneg (ha : 0 ≤ a) (hn : odd n) : 0 ≤ a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using pow_bit1_nonneg_iff.mpr ha theorem pow_odd_pos (ha : 0 < a) (hn : odd n) : 0 < a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using pow_bit1_pos_iff.mpr ha theorem pow_odd_nonpos (ha : a ≤ 0) (hn : odd n) : a ^ n ≤ 0:= by cases hn with k hk; simpa only [hk, two_mul] using pow_bit1_nonpos_iff.mpr ha theorem pow_odd_neg (ha : a < 0) (hn : odd n) : a ^ n < 0:= by cases hn with k hk; simpa only [hk, two_mul] using pow_bit1_neg_iff.mpr ha lemma strict_mono_pow_bit1 (n : ℕ) : strict_mono (λ a : R, a ^ bit1 n) := begin intros a b hab, cases le_total a 0 with ha ha, { cases le_or_lt b 0 with hb hb, { rw [← neg_lt_neg_iff, ← neg_pow_bit1, ← neg_pow_bit1], exact pow_lt_pow_of_lt_left (neg_lt_neg hab) (neg_nonneg.2 hb) (bit1_pos (zero_le n)) }, { exact (pow_bit1_nonpos_iff.2 ha).trans_lt (pow_bit1_pos_iff.2 hb) } }, { exact pow_lt_pow_of_lt_left hab ha (bit1_pos (zero_le n)) } end /-- Bernoulli's inequality for `n : ℕ`, `-2 ≤ a`. -/ theorem one_add_mul_le_pow (H : -2 ≤ a) (n : ℕ) : 1 + (n : R) * a ≤ (1 + a) ^ n := one_add_mul_le_pow' (mul_self_nonneg _) (mul_self_nonneg _) (neg_le_iff_add_nonneg'.1 H) _ /-- Bernoulli's inequality reformulated to estimate `a^n`. -/ theorem one_add_mul_sub_le_pow (H : -1 ≤ a) (n : ℕ) : 1 + (n : R) * (a - 1) ≤ a ^ n := have -2 ≤ a - 1, by rwa [bit0, neg_add, ← sub_eq_add_neg, sub_le_sub_iff_right], by simpa only [add_sub_cancel'_right] using one_add_mul_le_pow this n end linear_ordered_ring /-- Bernoulli's inequality reformulated to estimate `(n : K)`. -/ theorem nat.cast_le_pow_sub_div_sub {K : Type*} [linear_ordered_field K] {a : K} (H : 1 < a) (n : ℕ) : (n : K) ≤ (a ^ n - 1) / (a - 1) := (le_div_iff (sub_pos.2 H)).2 $ le_sub_left_of_add_le $ one_add_mul_sub_le_pow ((neg_le_self $ @zero_le_one K _).trans H.le) _ /-- For any `a > 1` and a natural `n` we have `n ≤ a ^ n / (a - 1)`. See also `nat.cast_le_pow_sub_div_sub` for a stronger inequality with `a ^ n - 1` in the numerator. -/ theorem nat.cast_le_pow_div_sub {K : Type*} [linear_ordered_field K] {a : K} (H : 1 < a) (n : ℕ) : (n : K) ≤ a ^ n / (a - 1) := (n.cast_le_pow_sub_div_sub H).trans $ div_le_div_of_le (sub_nonneg.2 H.le) (sub_le_self _ zero_le_one) namespace int lemma units_pow_two (u : units ℤ) : u ^ 2 = 1 := (pow_two u).symm ▸ units_mul_self u lemma units_pow_eq_pow_mod_two (u : units ℤ) (n : ℕ) : u ^ n = u ^ (n % 2) := by conv {to_lhs, rw ← nat.mod_add_div n 2}; rw [pow_add, pow_mul, units_pow_two, one_pow, mul_one] @[simp] lemma nat_abs_pow_two (x : ℤ) : (x.nat_abs ^ 2 : ℤ) = x ^ 2 := by rw [pow_two, int.nat_abs_mul_self', pow_two] lemma abs_le_self_pow_two (a : ℤ) : (int.nat_abs a : ℤ) ≤ a ^ 2 := by { rw [← int.nat_abs_pow_two a, pow_two], norm_cast, apply nat.le_mul_self } lemma le_self_pow_two (b : ℤ) : b ≤ b ^ 2 := le_trans (le_nat_abs) (abs_le_self_pow_two _) end int variables (M G A) /-- Monoid homomorphisms from `multiplicative ℕ` are defined by the image of `multiplicative.of_add 1`. -/ def powers_hom [monoid M] : M ≃ (multiplicative ℕ →* M) := { to_fun := λ x, ⟨λ n, x ^ n.to_add, pow_zero x, λ m n, pow_add x m n⟩, inv_fun := λ f, f (multiplicative.of_add 1), left_inv := pow_one, right_inv := λ f, monoid_hom.ext $ λ n, by { simp [← f.map_pow, ← of_add_nsmul] } } /-- Monoid homomorphisms from `multiplicative ℤ` are defined by the image of `multiplicative.of_add 1`. -/ def gpowers_hom [group G] : G ≃ (multiplicative ℤ →* G) := { to_fun := λ x, ⟨λ n, x ^ n.to_add, gpow_zero x, λ m n, gpow_add x m n⟩, inv_fun := λ f, f (multiplicative.of_add 1), left_inv := gpow_one, right_inv := λ f, monoid_hom.ext $ λ n, by { simp [← f.map_gpow, ← of_add_gsmul ] } } /-- Additive homomorphisms from `ℕ` are defined by the image of `1`. -/ def multiples_hom [add_monoid A] : A ≃ (ℕ →+ A) := { to_fun := λ x, ⟨λ n, n •ℕ x, zero_nsmul x, λ m n, add_nsmul _ _ _⟩, inv_fun := λ f, f 1, left_inv := one_nsmul, right_inv := λ f, add_monoid_hom.ext_nat $ one_nsmul (f 1) } /-- Additive homomorphisms from `ℤ` are defined by the image of `1`. -/ def gmultiples_hom [add_group A] : A ≃ (ℤ →+ A) := { to_fun := λ x, ⟨λ n, n •ℤ x, zero_gsmul x, λ m n, add_gsmul _ _ _⟩, inv_fun := λ f, f 1, left_inv := one_gsmul, right_inv := λ f, add_monoid_hom.ext_int $ one_gsmul (f 1) } variables {M G A} @[simp] lemma powers_hom_apply [monoid M] (x : M) (n : multiplicative ℕ) : powers_hom M x n = x ^ n.to_add := rfl @[simp] lemma powers_hom_symm_apply [monoid M] (f : multiplicative ℕ →* M) : (powers_hom M).symm f = f (multiplicative.of_add 1) := rfl @[simp] lemma gpowers_hom_apply [group G] (x : G) (n : multiplicative ℤ) : gpowers_hom G x n = x ^ n.to_add := rfl @[simp] lemma gpowers_hom_symm_apply [group G] (f : multiplicative ℤ →* G) : (gpowers_hom G).symm f = f (multiplicative.of_add 1) := rfl @[simp] lemma multiples_hom_apply [add_monoid A] (x : A) (n : ℕ) : multiples_hom A x n = n •ℕ x := rfl @[simp] lemma multiples_hom_symm_apply [add_monoid A] (f : ℕ →+ A) : (multiples_hom A).symm f = f 1 := rfl @[simp] lemma gmultiples_hom_apply [add_group A] (x : A) (n : ℤ) : gmultiples_hom A x n = n •ℤ x := rfl @[simp] lemma gmultiples_hom_symm_apply [add_group A] (f : ℤ →+ A) : (gmultiples_hom A).symm f = f 1 := rfl lemma monoid_hom.apply_mnat [monoid M] (f : multiplicative ℕ →* M) (n : multiplicative ℕ) : f n = (f (multiplicative.of_add 1)) ^ n.to_add := by rw [← powers_hom_symm_apply, ← powers_hom_apply, equiv.apply_symm_apply] @[ext] lemma monoid_hom.ext_mnat [monoid M] ⦃f g : multiplicative ℕ →* M⦄ (h : f (multiplicative.of_add 1) = g (multiplicative.of_add 1)) : f = g := monoid_hom.ext $ λ n, by rw [f.apply_mnat, g.apply_mnat, h] lemma monoid_hom.apply_mint [group M] (f : multiplicative ℤ →* M) (n : multiplicative ℤ) : f n = (f (multiplicative.of_add 1)) ^ n.to_add := by rw [← gpowers_hom_symm_apply, ← gpowers_hom_apply, equiv.apply_symm_apply] @[ext] lemma monoid_hom.ext_mint [group M] ⦃f g : multiplicative ℤ →* M⦄ (h : f (multiplicative.of_add 1) = g (multiplicative.of_add 1)) : f = g := monoid_hom.ext $ λ n, by rw [f.apply_mint, g.apply_mint, h] lemma add_monoid_hom.apply_nat [add_monoid M] (f : ℕ →+ M) (n : ℕ) : f n = n •ℕ (f 1) := by rw [← multiples_hom_symm_apply, ← multiples_hom_apply, equiv.apply_symm_apply] /-! `add_monoid_hom.ext_nat` is defined in `data.nat.cast` -/ lemma add_monoid_hom.apply_int [add_group M] (f : ℤ →+ M) (n : ℤ) : f n = n •ℤ (f 1) := by rw [← gmultiples_hom_symm_apply, ← gmultiples_hom_apply, equiv.apply_symm_apply] /-! `add_monoid_hom.ext_int` is defined in `data.int.cast` -/ variables (M G A) /-- If `M` is commutative, `powers_hom` is a multiplicative equivalence. -/ def powers_mul_hom [comm_monoid M] : M ≃* (multiplicative ℕ →* M) := { map_mul' := λ a b, monoid_hom.ext $ by simp [mul_pow], ..powers_hom M} /-- If `M` is commutative, `gpowers_hom` is a multiplicative equivalence. -/ def gpowers_mul_hom [comm_group G] : G ≃* (multiplicative ℤ →* G) := { map_mul' := λ a b, monoid_hom.ext $ by simp [mul_gpow], ..gpowers_hom G} /-- If `M` is commutative, `multiples_hom` is an additive equivalence. -/ def multiples_add_hom [add_comm_monoid A] : A ≃+ (ℕ →+ A) := { map_add' := λ a b, add_monoid_hom.ext $ by simp [nsmul_add], ..multiples_hom A} /-- If `M` is commutative, `gmultiples_hom` is an additive equivalence. -/ def gmultiples_add_hom [add_comm_group A] : A ≃+ (ℤ →+ A) := { map_add' := λ a b, add_monoid_hom.ext $ by simp [gsmul_add], ..gmultiples_hom A} variables {M G A} @[simp] lemma powers_mul_hom_apply [comm_monoid M] (x : M) (n : multiplicative ℕ) : powers_mul_hom M x n = x ^ n.to_add := rfl @[simp] lemma powers_mul_hom_symm_apply [comm_monoid M] (f : multiplicative ℕ →* M) : (powers_mul_hom M).symm f = f (multiplicative.of_add 1) := rfl @[simp] lemma gpowers_mul_hom_apply [comm_group G] (x : G) (n : multiplicative ℤ) : gpowers_mul_hom G x n = x ^ n.to_add := rfl @[simp] lemma gpowers_mul_hom_symm_apply [comm_group G] (f : multiplicative ℤ →* G) : (gpowers_mul_hom G).symm f = f (multiplicative.of_add 1) := rfl @[simp] lemma multiples_add_hom_apply [add_comm_monoid A] (x : A) (n : ℕ) : multiples_add_hom A x n = n •ℕ x := rfl @[simp] lemma multiples_add_hom_symm_apply [add_comm_monoid A] (f : ℕ →+ A) : (multiples_add_hom A).symm f = f 1 := rfl @[simp] lemma gmultiples_add_hom_apply [add_comm_group A] (x : A) (n : ℤ) : gmultiples_add_hom A x n = n •ℤ x := rfl @[simp] lemma gmultiples_add_hom_symm_apply [add_comm_group A] (f : ℤ →+ A) : (gmultiples_add_hom A).symm f = f 1 := rfl /-! ### Commutativity (again) Facts about `semiconj_by` and `commute` that require `gpow` or `gsmul`, or the fact that integer multiplication equals semiring multiplication. -/ namespace semiconj_by section variables [semiring R] {a x y : R} @[simp] lemma cast_nat_mul_right (h : semiconj_by a x y) (n : ℕ) : semiconj_by a ((n : R) * x) (n * y) := semiconj_by.mul_right (nat.commute_cast _ _) h @[simp] lemma cast_nat_mul_left (h : semiconj_by a x y) (n : ℕ) : semiconj_by ((n : R) * a) x y := semiconj_by.mul_left (nat.cast_commute _ _) h @[simp] lemma cast_nat_mul_cast_nat_mul (h : semiconj_by a x y) (m n : ℕ) : semiconj_by ((m : R) * a) (n * x) (n * y) := (h.cast_nat_mul_left m).cast_nat_mul_right n end variables [monoid M] [group G] [ring R] @[simp] lemma units_gpow_right {a : M} {x y : units M} (h : semiconj_by a x y) : ∀ m : ℤ, semiconj_by a (↑(x^m)) (↑(y^m)) | (n : ℕ) := by simp only [gpow_coe_nat, units.coe_pow, h, pow_right] | -[1+n] := by simp only [gpow_neg_succ_of_nat, units.coe_pow, units_inv_right, h, pow_right] variables {a b x y x' y' : R} @[simp] lemma cast_int_mul_right (h : semiconj_by a x y) (m : ℤ) : semiconj_by a ((m : ℤ) * x) (m * y) := semiconj_by.mul_right (int.commute_cast _ _) h @[simp] lemma cast_int_mul_left (h : semiconj_by a x y) (m : ℤ) : semiconj_by ((m : R) * a) x y := semiconj_by.mul_left (int.cast_commute _ _) h @[simp] lemma cast_int_mul_cast_int_mul (h : semiconj_by a x y) (m n : ℤ) : semiconj_by ((m : R) * a) (n * x) (n * y) := (h.cast_int_mul_left m).cast_int_mul_right n end semiconj_by namespace commute section variables [semiring R] {a b : R} @[simp] theorem cast_nat_mul_right (h : commute a b) (n : ℕ) : commute a ((n : R) * b) := h.cast_nat_mul_right n @[simp] theorem cast_nat_mul_left (h : commute a b) (n : ℕ) : commute ((n : R) * a) b := h.cast_nat_mul_left n @[simp] theorem cast_nat_mul_cast_nat_mul (h : commute a b) (m n : ℕ) : commute ((m : R) * a) (n * b) := h.cast_nat_mul_cast_nat_mul m n @[simp] theorem self_cast_nat_mul (n : ℕ) : commute a (n * a) := (commute.refl a).cast_nat_mul_right n @[simp] theorem cast_nat_mul_self (n : ℕ) : commute ((n : R) * a) a := (commute.refl a).cast_nat_mul_left n @[simp] theorem self_cast_nat_mul_cast_nat_mul (m n : ℕ) : commute ((m : R) * a) (n * a) := (commute.refl a).cast_nat_mul_cast_nat_mul m n end variables [monoid M] [group G] [ring R] @[simp] lemma units_gpow_right {a : M} {u : units M} (h : commute a u) (m : ℤ) : commute a (↑(u^m)) := h.units_gpow_right m @[simp] lemma units_gpow_left {u : units M} {a : M} (h : commute ↑u a) (m : ℤ) : commute (↑(u^m)) a := (h.symm.units_gpow_right m).symm variables {a b : R} @[simp] lemma cast_int_mul_right (h : commute a b) (m : ℤ) : commute a (m * b) := h.cast_int_mul_right m @[simp] lemma cast_int_mul_left (h : commute a b) (m : ℤ) : commute ((m : R) * a) b := h.cast_int_mul_left m lemma cast_int_mul_cast_int_mul (h : commute a b) (m n : ℤ) : commute ((m : R) * a) (n * b) := h.cast_int_mul_cast_int_mul m n variables (a) (m n : ℤ) @[simp] theorem self_cast_int_mul : commute a (n * a) := (commute.refl a).cast_int_mul_right n @[simp] theorem cast_int_mul_self : commute ((n : R) * a) a := (commute.refl a).cast_int_mul_left n theorem self_cast_int_mul_cast_int_mul : commute ((m : R) * a) (n * a) := (commute.refl a).cast_int_mul_cast_int_mul m n end commute section multiplicative open multiplicative @[simp] lemma nat.to_add_pow (a : multiplicative ℕ) (b : ℕ) : to_add (a ^ b) = to_add a * b := begin induction b with b ih, { erw [pow_zero, to_add_one, mul_zero] }, { simp [*, pow_succ, add_comm, nat.mul_succ] } end @[simp] lemma nat.of_add_mul (a b : ℕ) : of_add (a * b) = of_add a ^ b := (nat.to_add_pow _ _).symm @[simp] lemma int.to_add_pow (a : multiplicative ℤ) (b : ℕ) : to_add (a ^ b) = to_add a * b := by induction b; simp [*, mul_add, pow_succ, add_comm] @[simp] lemma int.to_add_gpow (a : multiplicative ℤ) (b : ℤ) : to_add (a ^ b) = to_add a * b := int.induction_on b (by simp) (by simp [gpow_add, mul_add] {contextual := tt}) (by simp [gpow_add, mul_add, sub_eq_add_neg, -int.add_neg_one] {contextual := tt}) @[simp] lemma int.of_add_mul (a b : ℤ) : of_add (a * b) = of_add a ^ b := (int.to_add_gpow _ _).symm end multiplicative namespace units variables [monoid M] lemma conj_pow (u : units M) (x : M) (n : ℕ) : (↑u * x * ↑(u⁻¹))^n = u * x^n * ↑(u⁻¹) := (divp_eq_iff_mul_eq.2 ((u.mk_semiconj_by x).pow_right n).eq.symm).symm lemma conj_pow' (u : units M) (x : M) (n : ℕ) : (↑(u⁻¹) * x * u)^n = ↑(u⁻¹) * x^n * u:= (u⁻¹).conj_pow x n open opposite /-- Moving to the opposite monoid commutes with taking powers. -/ @[simp] lemma op_pow (x : M) (n : ℕ) : op (x ^ n) = (op x) ^ n := begin induction n with n h, { simp }, { rw [pow_succ', op_mul, h, pow_succ] } end @[simp] lemma unop_pow (x : Mᵒᵖ) (n : ℕ) : unop (x ^ n) = (unop x) ^ n := begin induction n with n h, { simp }, { rw [pow_succ', unop_mul, h, pow_succ] } end end units
3a2c3b2a90ab0265caa19122b34e4f8e92a4c791
367134ba5a65885e863bdc4507601606690974c1
/src/data/equiv/ring.lean
0c7ff5896bf9e38478d027c0509cd1881dabad70
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
13,427
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Callum Sutton, Yury Kudryashov -/ import data.equiv.mul_add import algebra.field import algebra.opposites /-! # (Semi)ring equivs In this file we define extension of `equiv` called `ring_equiv`, which is a datatype representing an isomorphism of `semiring`s, `ring`s, `division_ring`s, or `field`s. We also introduce the corresponding group of automorphisms `ring_aut`. ## Notations * ``infix ` ≃+* `:25 := ring_equiv`` The extended equiv have coercions to functions, and the coercion is the canonical notation when treating the isomorphism as maps. ## Implementation notes The fields for `ring_equiv` now avoid the unbundled `is_mul_hom` and `is_add_hom`, as these are deprecated. Definition of multiplication in the groups of automorphisms agrees with function composition, multiplication in `equiv.perm`, and multiplication in `category_theory.End`, not with `category_theory.comp`. ## Tags equiv, mul_equiv, add_equiv, ring_equiv, mul_aut, add_aut, ring_aut -/ variables {R : Type*} {S : Type*} {S' : Type*} set_option old_structure_cmd true /-- An equivalence between two (semi)rings that preserves the algebraic structure. -/ structure ring_equiv (R S : Type*) [has_mul R] [has_add R] [has_mul S] [has_add S] extends R ≃ S, R ≃* S, R ≃+ S infix ` ≃+* `:25 := ring_equiv /-- The "plain" equivalence of types underlying an equivalence of (semi)rings. -/ add_decl_doc ring_equiv.to_equiv /-- The equivalence of additive monoids underlying an equivalence of (semi)rings. -/ add_decl_doc ring_equiv.to_add_equiv /-- The equivalence of multiplicative monoids underlying an equivalence of (semi)rings. -/ add_decl_doc ring_equiv.to_mul_equiv namespace ring_equiv section basic variables [has_mul R] [has_add R] [has_mul S] [has_add S] [has_mul S'] [has_add S'] instance : has_coe_to_fun (R ≃+* S) := ⟨_, ring_equiv.to_fun⟩ @[simp] lemma to_fun_eq_coe (f : R ≃+* S) : f.to_fun = f := rfl /-- A ring isomorphism preserves multiplication. -/ @[simp] lemma map_mul (e : R ≃+* S) (x y : R) : e (x * y) = e x * e y := e.map_mul' x y /-- A ring isomorphism preserves addition. -/ @[simp] lemma map_add (e : R ≃+* S) (x y : R) : e (x + y) = e x + e y := e.map_add' x y /-- Two ring isomorphisms agree if they are defined by the same underlying function. -/ @[ext] lemma ext {f g : R ≃+* S} (h : ∀ x, f x = g x) : f = g := begin have h₁ : f.to_equiv = g.to_equiv := equiv.ext h, cases f, cases g, congr, { exact (funext h) }, { exact congr_arg equiv.inv_fun h₁ } end @[simp] theorem coe_mk (e e' h₁ h₂ h₃ h₄) : ⇑(⟨e, e', h₁, h₂, h₃, h₄⟩ : R ≃+* S) = e := rfl @[simp] theorem mk_coe (e : R ≃+* S) (e' h₁ h₂ h₃ h₄) : (⟨e, e', h₁, h₂, h₃, h₄⟩ : R ≃+* S) = e := ext $ λ _, rfl protected lemma congr_arg {f : R ≃+* S} : Π {x x' : R}, x = x' → f x = f x' | _ _ rfl := rfl protected lemma congr_fun {f g : R ≃+* S} (h : f = g) (x : R) : f x = g x := h ▸ rfl lemma ext_iff {f g : R ≃+* S} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, ext⟩ instance has_coe_to_mul_equiv : has_coe (R ≃+* S) (R ≃* S) := ⟨ring_equiv.to_mul_equiv⟩ instance has_coe_to_add_equiv : has_coe (R ≃+* S) (R ≃+ S) := ⟨ring_equiv.to_add_equiv⟩ lemma to_add_equiv_eq_coe (f : R ≃+* S) : f.to_add_equiv = ↑f := rfl lemma to_mul_equiv_eq_coe (f : R ≃+* S) : f.to_mul_equiv = ↑f := rfl @[simp, norm_cast] lemma coe_to_mul_equiv (f : R ≃+* S) : ⇑(f : R ≃* S) = f := rfl @[simp, norm_cast] lemma coe_to_add_equiv (f : R ≃+* S) : ⇑(f : R ≃+ S) = f := rfl /-- The `ring_equiv` between two semirings with a unique element. -/ def ring_equiv_of_unique_of_unique {M N} [unique M] [unique N] [has_add M] [has_mul M] [has_add N] [has_mul N] : M ≃+* N := { ..add_equiv.add_equiv_of_unique_of_unique, ..mul_equiv.mul_equiv_of_unique_of_unique} instance {M N} [unique M] [unique N] [has_add M] [has_mul M] [has_add N] [has_mul N] : unique (M ≃+* N) := { default := ring_equiv_of_unique_of_unique, uniq := λ _, ext $ λ x, subsingleton.elim _ _ } variable (R) /-- The identity map is a ring isomorphism. -/ @[refl] protected def refl : R ≃+* R := { .. mul_equiv.refl R, .. add_equiv.refl R } @[simp] lemma refl_apply (x : R) : ring_equiv.refl R x = x := rfl @[simp] lemma coe_add_equiv_refl : (ring_equiv.refl R : R ≃+ R) = add_equiv.refl R := rfl @[simp] lemma coe_mul_equiv_refl : (ring_equiv.refl R : R ≃* R) = mul_equiv.refl R := rfl instance : inhabited (R ≃+* R) := ⟨ring_equiv.refl R⟩ variables {R} /-- The inverse of a ring isomorphism is a ring isomorphism. -/ @[symm] protected def symm (e : R ≃+* S) : S ≃+* R := { .. e.to_mul_equiv.symm, .. e.to_add_equiv.symm } /-- See Note [custom simps projection] -/ def simps.inv_fun (e : R ≃+* S) : S → R := e.symm initialize_simps_projections ring_equiv (to_fun → apply, inv_fun → symm_apply) @[simp] lemma symm_symm (e : R ≃+* S) : e.symm.symm = e := ext $ λ x, rfl lemma symm_bijective : function.bijective (ring_equiv.symm : (R ≃+* S) → (S ≃+* R)) := equiv.bijective ⟨ring_equiv.symm, ring_equiv.symm, symm_symm, symm_symm⟩ @[simp] lemma mk_coe' (e : R ≃+* S) (f h₁ h₂ h₃ h₄) : (ring_equiv.mk f ⇑e h₁ h₂ h₃ h₄ : S ≃+* R) = e.symm := symm_bijective.injective $ ext $ λ x, rfl @[simp] lemma symm_mk (f : R → S) (g h₁ h₂ h₃ h₄) : (mk f g h₁ h₂ h₃ h₄).symm = { to_fun := g, inv_fun := f, ..(mk f g h₁ h₂ h₃ h₄).symm} := rfl /-- Transitivity of `ring_equiv`. -/ @[trans] protected def trans (e₁ : R ≃+* S) (e₂ : S ≃+* S') : R ≃+* S' := { .. (e₁.to_mul_equiv.trans e₂.to_mul_equiv), .. (e₁.to_add_equiv.trans e₂.to_add_equiv) } @[simp] lemma trans_apply {A B C : Type*} [semiring A] [semiring B] [semiring C] (e : A ≃+* B) (f : B ≃+* C) (a : A) : e.trans f a = f (e a) := rfl protected lemma bijective (e : R ≃+* S) : function.bijective e := e.to_equiv.bijective protected lemma injective (e : R ≃+* S) : function.injective e := e.to_equiv.injective protected lemma surjective (e : R ≃+* S) : function.surjective e := e.to_equiv.surjective @[simp] lemma apply_symm_apply (e : R ≃+* S) : ∀ x, e (e.symm x) = x := e.to_equiv.apply_symm_apply @[simp] lemma symm_apply_apply (e : R ≃+* S) : ∀ x, e.symm (e x) = x := e.to_equiv.symm_apply_apply lemma image_eq_preimage (e : R ≃+* S) (s : set R) : e '' s = e.symm ⁻¹' s := e.to_equiv.image_eq_preimage s end basic section comm_semiring open opposite variables (R) [comm_semiring R] /-- A commutative ring is isomorphic to its opposite. -/ def to_opposite : R ≃+* Rᵒᵖ := { map_add' := λ x y, rfl, map_mul' := λ x y, mul_comm (op y) (op x), ..equiv_to_opposite } @[simp] lemma to_opposite_apply (r : R) : to_opposite R r = op r := rfl @[simp] lemma to_opposite_symm_apply (r : Rᵒᵖ) : (to_opposite R).symm r = unop r := rfl end comm_semiring section semiring variables [semiring R] [semiring S] (f : R ≃+* S) (x y : R) /-- A ring isomorphism sends one to one. -/ @[simp] lemma map_one : f 1 = 1 := (f : R ≃* S).map_one /-- A ring isomorphism sends zero to zero. -/ @[simp] lemma map_zero : f 0 = 0 := (f : R ≃+ S).map_zero variable {x} @[simp] lemma map_eq_one_iff : f x = 1 ↔ x = 1 := (f : R ≃* S).map_eq_one_iff @[simp] lemma map_eq_zero_iff : f x = 0 ↔ x = 0 := (f : R ≃+ S).map_eq_zero_iff lemma map_ne_one_iff : f x ≠ 1 ↔ x ≠ 1 := (f : R ≃* S).map_ne_one_iff lemma map_ne_zero_iff : f x ≠ 0 ↔ x ≠ 0 := (f : R ≃+ S).map_ne_zero_iff /-- Produce a ring isomorphism from a bijective ring homomorphism. -/ noncomputable def of_bijective (f : R →+* S) (hf : function.bijective f) : R ≃+* S := { .. equiv.of_bijective f hf, .. f } end semiring section variables [ring R] [ring S] (f : R ≃+* S) (x y : R) @[simp] lemma map_neg : f (-x) = -f x := (f : R ≃+ S).map_neg x @[simp] lemma map_sub : f (x - y) = f x - f y := (f : R ≃+ S).map_sub x y @[simp] lemma map_neg_one : f (-1) = -1 := f.map_one ▸ f.map_neg 1 end section semiring_hom variables [semiring R] [semiring S] [semiring S'] /-- Reinterpret a ring equivalence as a ring homomorphism. -/ def to_ring_hom (e : R ≃+* S) : R →+* S := { .. e.to_mul_equiv.to_monoid_hom, .. e.to_add_equiv.to_add_monoid_hom } lemma to_ring_hom_injective : function.injective (to_ring_hom : (R ≃+* S) → R →+* S) := λ f g h, ring_equiv.ext (ring_hom.ext_iff.1 h) instance has_coe_to_ring_hom : has_coe (R ≃+* S) (R →+* S) := ⟨ring_equiv.to_ring_hom⟩ lemma to_ring_hom_eq_coe (f : R ≃+* S) : f.to_ring_hom = ↑f := rfl @[simp, norm_cast] lemma coe_to_ring_hom (f : R ≃+* S) : ⇑(f : R →+* S) = f := rfl lemma coe_ring_hom_inj_iff {R S : Type*} [semiring R] [semiring S] (f g : R ≃+* S) : f = g ↔ (f : R →+* S) = g := ⟨congr_arg _, λ h, ext $ ring_hom.ext_iff.mp h⟩ /-- Reinterpret a ring equivalence as a monoid homomorphism. -/ abbreviation to_monoid_hom (e : R ≃+* S) : R →* S := e.to_ring_hom.to_monoid_hom /-- Reinterpret a ring equivalence as an `add_monoid` homomorphism. -/ abbreviation to_add_monoid_hom (e : R ≃+* S) : R →+ S := e.to_ring_hom.to_add_monoid_hom @[simp] lemma to_ring_hom_refl : (ring_equiv.refl R).to_ring_hom = ring_hom.id R := rfl @[simp] lemma to_monoid_hom_refl : (ring_equiv.refl R).to_monoid_hom = monoid_hom.id R := rfl @[simp] lemma to_add_monoid_hom_refl : (ring_equiv.refl R).to_add_monoid_hom = add_monoid_hom.id R := rfl @[simp] lemma to_ring_hom_apply_symm_to_ring_hom_apply (e : R ≃+* S) : ∀ (y : S), e.to_ring_hom (e.symm.to_ring_hom y) = y := e.to_equiv.apply_symm_apply @[simp] lemma symm_to_ring_hom_apply_to_ring_hom_apply (e : R ≃+* S) : ∀ (x : R), e.symm.to_ring_hom (e.to_ring_hom x) = x := equiv.symm_apply_apply (e.to_equiv) @[simp] lemma to_ring_hom_trans (e₁ : R ≃+* S) (e₂ : S ≃+* S') : (e₁.trans e₂).to_ring_hom = e₂.to_ring_hom.comp e₁.to_ring_hom := rfl @[simp] lemma to_ring_hom_comp_symm_to_ring_hom (e : R ≃+* S) : e.to_ring_hom.comp e.symm.to_ring_hom = ring_hom.id _ := by { ext, simp } @[simp] lemma symm_to_ring_hom_comp_to_ring_hom (e : R ≃+* S) : e.symm.to_ring_hom.comp e.to_ring_hom = ring_hom.id _ := by { ext, simp } /-- Construct an equivalence of rings from homomorphisms in both directions, which are inverses. -/ def of_hom_inv (hom : R →+* S) (inv : S →+* R) (hom_inv_id : inv.comp hom = ring_hom.id R) (inv_hom_id : hom.comp inv = ring_hom.id S) : R ≃+* S := { inv_fun := inv, left_inv := λ x, ring_hom.congr_fun hom_inv_id x, right_inv := λ x, ring_hom.congr_fun inv_hom_id x, ..hom } @[simp] lemma of_hom_inv_apply (hom : R →+* S) (inv : S →+* R) (hom_inv_id inv_hom_id) (r : R) : (of_hom_inv hom inv hom_inv_id inv_hom_id) r = hom r := rfl @[simp] lemma of_hom_inv_symm_apply (hom : R →+* S) (inv : S →+* R) (hom_inv_id inv_hom_id) (s : S) : (of_hom_inv hom inv hom_inv_id inv_hom_id).symm s = inv s := rfl end semiring_hom end ring_equiv namespace mul_equiv /-- Gives a `ring_equiv` from a `mul_equiv` preserving addition.-/ def to_ring_equiv {R : Type*} {S : Type*} [has_add R] [has_add S] [has_mul R] [has_mul S] (h : R ≃* S) (H : ∀ x y : R, h (x + y) = h x + h y) : R ≃+* S := {..h.to_equiv, ..h, ..add_equiv.mk' h.to_equiv H } end mul_equiv namespace ring_equiv variables [has_add R] [has_add S] [has_mul R] [has_mul S] @[simp] theorem trans_symm (e : R ≃+* S) : e.trans e.symm = ring_equiv.refl R := ext e.3 @[simp] theorem symm_trans (e : R ≃+* S) : e.symm.trans e = ring_equiv.refl S := ext e.4 /-- If two rings are isomorphic, and the second is an integral domain, then so is the first. -/ protected lemma is_integral_domain {A : Type*} (B : Type*) [ring A] [ring B] (hB : is_integral_domain B) (e : A ≃+* B) : is_integral_domain A := { mul_comm := λ x y, have e.symm (e x * e y) = e.symm (e y * e x), by rw hB.mul_comm, by simpa, eq_zero_or_eq_zero_of_mul_eq_zero := λ x y hxy, have e x * e y = 0, by rw [← e.map_mul, hxy, e.map_zero], (hB.eq_zero_or_eq_zero_of_mul_eq_zero _ _ this).imp (λ hx, by simpa using congr_arg e.symm hx) (λ hy, by simpa using congr_arg e.symm hy), exists_pair_ne := ⟨e.symm 0, e.symm 1, by { haveI : nontrivial B := hB.to_nontrivial, exact e.symm.injective.ne zero_ne_one }⟩ } /-- If two rings are isomorphic, and the second is an integral domain, then so is the first. -/ protected def integral_domain {A : Type*} (B : Type*) [ring A] [integral_domain B] (e : A ≃+* B) : integral_domain A := { .. (‹_› : ring A), .. e.is_integral_domain B (integral_domain.to_is_integral_domain B) } end ring_equiv namespace equiv variables (K : Type*) [division_ring K] /-- In a division ring `K`, the unit group `units K` is equivalent to the subtype of nonzero elements. -/ -- TODO: this might already exist elsewhere for `group_with_zero` -- deduplicate or generalize def units_equiv_ne_zero : units K ≃ {a : K | a ≠ 0} := ⟨λ a, ⟨a.1, a.ne_zero⟩, λ a, units.mk0 _ a.2, λ ⟨_, _, _, _⟩, units.ext rfl, λ ⟨_, _⟩, rfl⟩ variable {K} @[simp] lemma coe_units_equiv_ne_zero (a : units K) : ((units_equiv_ne_zero K a) : K) = a := rfl end equiv
6e0bc05cafec8fc3c103f7188e462ce8182d2224
cb1829c15cd3d28210f93507f96dfb1f56ec0128
/theorem_proving/02-dependent_types_part2.lean
d3eb0d5ac98d707328261883598959b081b068d1
[]
no_license
williamdemeo/LEAN_wjd
69f9f76e35092b89e4479a320be2fa3c18aed6fe
13826c75c06ef435166a26a72e76fe984c15bad7
refs/heads/master
1,609,516,630,137
1,518,123,893,000
1,518,123,893,000
97,740,278
2
0
null
null
null
null
UTF-8
Lean
false
false
5,636
lean
#print "------------------------------------------------" #print "Section 2.8 Dependent Types" -- (page 16 in new ed) /- It is clear that `cons α` should have type α → list α → list α But what type should `cons` itself have? A first guess might be Type → α → list α → list α But on reflection, we see this does not make sense: the α in this expression does not refer to anything, whereas it should refer to the argument of type Type. In other words, assuming `α : Type` is the first argument to the function, the type of the next two elements are `α` and `list α`. These types *depend* on the first argument `α`. This is an instance of a `Pi` type, or dependent function type. If we are given `α : Type` and `β : α → Type`, then we think of β as a family of types indexed by α. That is, we have a type `β a` for each `a : α`. The type Π x : α, β x denotes the type of functions f such that, for each `a : α`, `f a` is an element of `β a`. Note that `Π x : α, β` makes sense for any expression `β : Type`. When the value of β happens to depend on x, then `Π x : α, β` denotes a *dependent* function type. When β doesn't depend on x, then `Π x : α, β` is the same as the type `α → β`. Indeed, in dependent type theory (and in Lean), the `Pi` construction is fundamental, and `α → β` is just notation for `Π x : α, β` when β doesn't depend on α. -/ namespace page25 #print "----- page17, new ed-------------------" universe u constant list : Type u → Type u -- N.B. we don't just want `list : Type → Type` constant cons : Π (α : Type u), α → list α → list α constant nil : Π (α : Type u), list α constant head : Π (α : Type u), list α → α constant tail : Π (α : Type u), list α → list α constant append : Π (α : Type u), list α → list α → list α #check list #check @cons #check @nil #check @head #check @tail #check @append end page25 namespace page18 --(new edition) universe u constant vec : Type u → ℕ → Type u namespace vec constant empty : Π (α : Type u), vec α 0 constant cons : Π (α : Type u) (n : ℕ), α → vec α n → vec α (n+1) constant append : Π (α : Type u) (n m : ℕ), vec α n → vec α m → vec α (n+m) end vec end page18 /- One more important and illustrative example of dependent types, the *Sigma types*, `Σ x : α, β x`, sometimes known as *dependent products*. `Σ x : α, β x` denotes the type of pairs `sigma.mk a b` where `a : α` and `b : β a`. -/ /- Pi types Π x : α, β x generalize the notion of a function type α → β by allowing β to depend on α. Sigma types `Σ x : α, β x` generalize the cartesian product `α × β` in the same way; in the expression sigma.mk a b, the type of the second element, `b : β a`, depends on the first element, `a : α`. -/ namespace page27 #print "----- page18, new ed-------------------" variable α : Type variable β : α → Type variable a : α variable b : β a #check sigma.mk a b -- (a, b) : Σ (a : α), β a #check (sigma.mk a b).1 -- (a, b).fst : α #check (sigma.mk a b).2 -- β (sigma.fst (sigma.mk a b)) #reduce (sigma.mk a b).1 #reduce (sigma.mk a b).2 end page27 /- `(sigma.mk a b).1` and `(sigma.mk a b).2` are short for `sigma.fst (sigma.mk a b)` and `sigma.snd (sigma.mk a b)`, and these reduce to a and b, respectively. (cf. 3rd to last line of output below) -/ /- Section 2.8 output list : Type u_1 → Type u_1 cons : Π {T : Type u_1}, T → list T → list T nil : Π {T : Type u_1}, list T head : Π {α : Type u_1} [_inst_1 : inhabited α], list α → α tail : Π {α : Type u_1}, list α → list α append : Π {α : Type u_1} [c : has_append α], α → α → α ⟨a, b⟩ : Σ (a : α), β a ⟨a, b⟩.fst : α ⟨a, b⟩.snd : (λ (a : α), β a) (⟨a, b⟩.fst) a b -/ #print "------------------------------------------------" #print "Section 2.9 Implicit Arguments" /- Lean allows us to specify that this argument should, by default, be left implicit. This is done by putting the arguments in curly braces. -/ namespace implicits universe u def ident {α : Type u} (x : α) := x variables α β : Type u variables (a : α) (b : β) #check ident #check ident a #check ident b /- This makes the first argument to ident implicit. Notationally, this hides the specification of the type, making it look as though ident simply takes an argument of any type. -/ /- Sometimes, however, we may find ourselves in a situation where we have declared an argument to a function to be implicit, but now want to provide the argument explicitly. -/ #check @id #check @id α #check @id β #check @id α a #check @id β b /- Notice that the first #check command now gives the type of the identifier, id, without inserting placeholders. Moreover, the output indicates that the first argument is implicit. -/ end implicits /- Section 2.9 output ident : ?M_1 → ?M_1 ident a : α ident b : β id : Π {α : Sort u_1}, α → α id : α → α id : β → β id a : α id b : β -/
d415cdcd1604ec7905d3f6f467ace19e93878e9a
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/special_functions/complex/arg.lean
59b2e80c434aefbbe207b5e8a2aeda67a425f3c5
[ "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
24,946
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Benjamin Davidson -/ import algebra.order.to_interval_mod import analysis.special_functions.trigonometric.angle import analysis.special_functions.trigonometric.inverse /-! # The argument of a complex number. We define `arg : ℂ → ℝ`, returing a real number in the range (-π, π], such that for `x ≠ 0`, `sin (arg x) = x.im / x.abs` and `cos (arg x) = x.re / x.abs`, while `arg 0` defaults to `0` -/ noncomputable theory namespace complex open_locale complex_conjugate real topological_space open filter set /-- `arg` returns values in the range (-π, π], such that for `x ≠ 0`, `sin (arg x) = x.im / x.abs` and `cos (arg x) = x.re / x.abs`, `arg 0` defaults to `0` -/ noncomputable def arg (x : ℂ) : ℝ := if 0 ≤ x.re then real.arcsin (x.im / x.abs) else if 0 ≤ x.im then real.arcsin ((-x).im / x.abs) + π else real.arcsin ((-x).im / x.abs) - π lemma sin_arg (x : ℂ) : real.sin (arg x) = x.im / x.abs := by unfold arg; split_ifs; simp [sub_eq_add_neg, arg, real.sin_arcsin (abs_le.1 (abs_im_div_abs_le_one x)).1 (abs_le.1 (abs_im_div_abs_le_one x)).2, real.sin_add, neg_div, real.arcsin_neg, real.sin_neg] lemma cos_arg {x : ℂ} (hx : x ≠ 0) : real.cos (arg x) = x.re / x.abs := begin have habs : 0 < abs x := abs.pos hx, have him : |im x / abs x| ≤ 1, { rw [_root_.abs_div, abs_abs], exact div_le_one_of_le x.abs_im_le_abs (abs.nonneg x) }, rw abs_le at him, rw arg, split_ifs with h₁ h₂ h₂, { rw [real.cos_arcsin], field_simp [real.sqrt_sq, habs.le, *] }, { rw [real.cos_add_pi, real.cos_arcsin], field_simp [real.sqrt_div (sq_nonneg _), real.sqrt_sq_eq_abs, _root_.abs_of_neg (not_le.1 h₁), *] }, { rw [real.cos_sub_pi, real.cos_arcsin], field_simp [real.sqrt_div (sq_nonneg _), real.sqrt_sq_eq_abs, _root_.abs_of_neg (not_le.1 h₁), *] } end @[simp] lemma abs_mul_exp_arg_mul_I (x : ℂ) : ↑(abs x) * exp (arg x * I) = x := begin rcases eq_or_ne x 0 with (rfl|hx), { simp }, { have : abs x ≠ 0 := abs.ne_zero hx, ext; field_simp [sin_arg, cos_arg hx, this, mul_comm (abs x)] } end @[simp] lemma abs_mul_cos_add_sin_mul_I (x : ℂ) : (abs x * (cos (arg x) + sin (arg x) * I) : ℂ) = x := by rw [← exp_mul_I, abs_mul_exp_arg_mul_I] lemma abs_eq_one_iff (z : ℂ) : abs z = 1 ↔ ∃ θ : ℝ, exp (θ * I) = z := begin refine ⟨λ hz, ⟨arg z, _⟩, _⟩, { calc exp (arg z * I) = abs z * exp (arg z * I) : by rw [hz, of_real_one, one_mul] ... = z : abs_mul_exp_arg_mul_I z }, { rintro ⟨θ, rfl⟩, exact complex.abs_exp_of_real_mul_I θ }, end @[simp] lemma range_exp_mul_I : range (λ x : ℝ, exp (x * I)) = metric.sphere 0 1 := by { ext x, simp only [mem_sphere_zero_iff_norm, norm_eq_abs, abs_eq_one_iff, mem_range] } lemma arg_mul_cos_add_sin_mul_I {r : ℝ} (hr : 0 < r) {θ : ℝ} (hθ : θ ∈ Ioc (-π) π) : arg (r * (cos θ + sin θ * I)) = θ := begin simp only [arg, map_mul, abs_cos_add_sin_mul_I, abs_of_nonneg hr.le, mul_one], simp only [of_real_mul_re, of_real_mul_im, neg_im, ← of_real_cos, ← of_real_sin, ← mk_eq_add_mul_I, neg_div, mul_div_cancel_left _ hr.ne', mul_nonneg_iff_right_nonneg_of_pos hr], by_cases h₁ : θ ∈ Icc (-(π / 2)) (π / 2), { rw if_pos, exacts [real.arcsin_sin' h₁, real.cos_nonneg_of_mem_Icc h₁] }, { rw [mem_Icc, not_and_distrib, not_le, not_le] at h₁, cases h₁, { replace hθ := hθ.1, have hcos : real.cos θ < 0, { rw [← neg_pos, ← real.cos_add_pi], refine real.cos_pos_of_mem_Ioo ⟨_, _⟩; linarith }, have hsin : real.sin θ < 0 := real.sin_neg_of_neg_of_neg_pi_lt (by linarith) hθ, rw [if_neg, if_neg, ← real.sin_add_pi, real.arcsin_sin, add_sub_cancel]; [linarith, linarith, exact hsin.not_le, exact hcos.not_le] }, { replace hθ := hθ.2, have hcos : real.cos θ < 0 := real.cos_neg_of_pi_div_two_lt_of_lt h₁ (by linarith), have hsin : 0 ≤ real.sin θ := real.sin_nonneg_of_mem_Icc ⟨by linarith, hθ⟩, rw [if_neg, if_pos, ← real.sin_sub_pi, real.arcsin_sin, sub_add_cancel]; [linarith, linarith, exact hsin, exact hcos.not_le] } } end lemma arg_cos_add_sin_mul_I {θ : ℝ} (hθ : θ ∈ Ioc (-π) π) : arg (cos θ + sin θ * I) = θ := by rw [← one_mul (_ + _), ← of_real_one, arg_mul_cos_add_sin_mul_I zero_lt_one hθ] @[simp] lemma arg_zero : arg 0 = 0 := by simp [arg, le_refl] lemma ext_abs_arg {x y : ℂ} (h₁ : x.abs = y.abs) (h₂ : x.arg = y.arg) : x = y := by rw [← abs_mul_exp_arg_mul_I x, ← abs_mul_exp_arg_mul_I y, h₁, h₂] lemma ext_abs_arg_iff {x y : ℂ} : x = y ↔ abs x = abs y ∧ arg x = arg y := ⟨λ h, h ▸ ⟨rfl, rfl⟩, and_imp.2 ext_abs_arg⟩ lemma arg_mem_Ioc (z : ℂ) : arg z ∈ Ioc (-π) π := begin have hπ : 0 < π := real.pi_pos, rcases eq_or_ne z 0 with (rfl|hz), simp [hπ, hπ.le], rcases exists_unique_add_zsmul_mem_Ioc real.two_pi_pos (arg z) (-π) with ⟨N, hN, -⟩, rw [two_mul, neg_add_cancel_left, ← two_mul, zsmul_eq_mul] at hN, rw [← abs_mul_cos_add_sin_mul_I z, ← cos_add_int_mul_two_pi _ N, ← sin_add_int_mul_two_pi _ N], simp only [← of_real_one, ← of_real_bit0, ← of_real_mul, ← of_real_add, ← of_real_int_cast], rwa [arg_mul_cos_add_sin_mul_I (abs.pos hz) hN] end @[simp] lemma range_arg : range arg = Ioc (-π) π := (range_subset_iff.2 arg_mem_Ioc).antisymm (λ x hx, ⟨_, arg_cos_add_sin_mul_I hx⟩) lemma arg_le_pi (x : ℂ) : arg x ≤ π := (arg_mem_Ioc x).2 lemma neg_pi_lt_arg (x : ℂ) : -π < arg x := (arg_mem_Ioc x).1 lemma abs_arg_le_pi (z : ℂ) : |arg z| ≤ π := abs_le.2 ⟨(neg_pi_lt_arg z).le, arg_le_pi z⟩ @[simp] lemma arg_nonneg_iff {z : ℂ} : 0 ≤ arg z ↔ 0 ≤ z.im := begin rcases eq_or_ne z 0 with (rfl|h₀), { simp }, calc 0 ≤ arg z ↔ 0 ≤ real.sin (arg z) : ⟨λ h, real.sin_nonneg_of_mem_Icc ⟨h, arg_le_pi z⟩, by { contrapose!, intro h, exact real.sin_neg_of_neg_of_neg_pi_lt h (neg_pi_lt_arg _) }⟩ ... ↔ _ : by rw [sin_arg, le_div_iff (abs.pos h₀), zero_mul] end @[simp] lemma arg_neg_iff {z : ℂ} : arg z < 0 ↔ z.im < 0 := lt_iff_lt_of_le_iff_le arg_nonneg_iff lemma arg_real_mul (x : ℂ) {r : ℝ} (hr : 0 < r) : arg (r * x) = arg x := begin rcases eq_or_ne x 0 with (rfl|hx), { rw mul_zero }, conv_lhs { rw [← abs_mul_cos_add_sin_mul_I x, ← mul_assoc, ← of_real_mul, arg_mul_cos_add_sin_mul_I (mul_pos hr (abs.pos hx)) x.arg_mem_Ioc] } end lemma arg_eq_arg_iff {x y : ℂ} (hx : x ≠ 0) (hy : y ≠ 0) : arg x = arg y ↔ (abs y / abs x : ℂ) * x = y := begin simp only [ext_abs_arg_iff, map_mul, map_div₀, abs_of_real, abs_abs, div_mul_cancel _ (abs.ne_zero hx), eq_self_iff_true, true_and], rw [← of_real_div, arg_real_mul], exact div_pos (abs.pos hy) (abs.pos hx) end @[simp] lemma arg_one : arg 1 = 0 := by simp [arg, zero_le_one] @[simp] lemma arg_neg_one : arg (-1) = π := by simp [arg, le_refl, not_le.2 (zero_lt_one' ℝ)] @[simp] lemma arg_I : arg I = π / 2 := by simp [arg, le_refl] @[simp] lemma arg_neg_I : arg (-I) = -(π / 2) := by simp [arg, le_refl] @[simp] lemma tan_arg (x : ℂ) : real.tan (arg x) = x.im / x.re := begin by_cases h : x = 0, { simp only [h, zero_div, complex.zero_im, complex.arg_zero, real.tan_zero, complex.zero_re] }, rw [real.tan_eq_sin_div_cos, sin_arg, cos_arg h, div_div_div_cancel_right _ (abs.ne_zero h)] end lemma arg_of_real_of_nonneg {x : ℝ} (hx : 0 ≤ x) : arg x = 0 := by simp [arg, hx] lemma arg_eq_zero_iff {z : ℂ} : arg z = 0 ↔ 0 ≤ z.re ∧ z.im = 0 := begin refine ⟨λ h, _, _⟩, { rw [←abs_mul_cos_add_sin_mul_I z, h], simp [abs.nonneg] }, { cases z with x y, rintro ⟨h, rfl : y = 0⟩, exact arg_of_real_of_nonneg h } end lemma arg_eq_pi_iff {z : ℂ} : arg z = π ↔ z.re < 0 ∧ z.im = 0 := begin by_cases h₀ : z = 0, { simp [h₀, lt_irrefl, real.pi_ne_zero.symm] }, split, { intro h, rw [← abs_mul_cos_add_sin_mul_I z, h], simp [h₀] }, { cases z with x y, rintro ⟨h : x < 0, rfl : y = 0⟩, rw [← arg_neg_one, ← arg_real_mul (-1) (neg_pos.2 h)], simp [← of_real_def] } end lemma arg_lt_pi_iff {z : ℂ} : arg z < π ↔ 0 ≤ z.re ∨ z.im ≠ 0 := by rw [(arg_le_pi z).lt_iff_ne, not_iff_comm, not_or_distrib, not_le, not_not, arg_eq_pi_iff] lemma arg_of_real_of_neg {x : ℝ} (hx : x < 0) : arg x = π := arg_eq_pi_iff.2 ⟨hx, rfl⟩ lemma arg_eq_pi_div_two_iff {z : ℂ} : arg z = π / 2 ↔ z.re = 0 ∧ 0 < z.im := begin by_cases h₀ : z = 0, { simp [h₀, lt_irrefl, real.pi_div_two_pos.ne] }, split, { intro h, rw [← abs_mul_cos_add_sin_mul_I z, h], simp [h₀] }, { cases z with x y, rintro ⟨rfl : x = 0, hy : 0 < y⟩, rw [← arg_I, ← arg_real_mul I hy, of_real_mul', I_re, I_im, mul_zero, mul_one] } end lemma arg_eq_neg_pi_div_two_iff {z : ℂ} : arg z = - (π / 2) ↔ z.re = 0 ∧ z.im < 0 := begin by_cases h₀ : z = 0, { simp [h₀, lt_irrefl, real.pi_ne_zero] }, split, { intro h, rw [← abs_mul_cos_add_sin_mul_I z, h], simp [h₀] }, { cases z with x y, rintro ⟨rfl : x = 0, hy : y < 0⟩, rw [← arg_neg_I, ← arg_real_mul (-I) (neg_pos.2 hy), mk_eq_add_mul_I], simp } end lemma arg_of_re_nonneg {x : ℂ} (hx : 0 ≤ x.re) : arg x = real.arcsin (x.im / x.abs) := if_pos hx lemma arg_of_re_neg_of_im_nonneg {x : ℂ} (hx_re : x.re < 0) (hx_im : 0 ≤ x.im) : arg x = real.arcsin ((-x).im / x.abs) + π := by simp only [arg, hx_re.not_le, hx_im, if_true, if_false] lemma arg_of_re_neg_of_im_neg {x : ℂ} (hx_re : x.re < 0) (hx_im : x.im < 0) : arg x = real.arcsin ((-x).im / x.abs) - π := by simp only [arg, hx_re.not_le, hx_im.not_le, if_false] lemma arg_of_im_nonneg_of_ne_zero {z : ℂ} (h₁ : 0 ≤ z.im) (h₂ : z ≠ 0) : arg z = real.arccos (z.re / abs z) := by rw [← cos_arg h₂, real.arccos_cos (arg_nonneg_iff.2 h₁) (arg_le_pi _)] lemma arg_of_im_pos {z : ℂ} (hz : 0 < z.im) : arg z = real.arccos (z.re / abs z) := arg_of_im_nonneg_of_ne_zero hz.le (λ h, hz.ne' $ h.symm ▸ rfl) lemma arg_of_im_neg {z : ℂ} (hz : z.im < 0) : arg z = -real.arccos (z.re / abs z) := begin have h₀ : z ≠ 0, from mt (congr_arg im) hz.ne, rw [← cos_arg h₀, ← real.cos_neg, real.arccos_cos, neg_neg], exacts [neg_nonneg.2 (arg_neg_iff.2 hz).le, neg_le.2 (neg_pi_lt_arg z).le] end lemma arg_conj (x : ℂ) : arg (conj x) = if arg x = π then π else -arg x := begin simp_rw [arg_eq_pi_iff, arg, neg_im, conj_im, conj_re, abs_conj, neg_div, neg_neg, real.arcsin_neg, apply_ite has_neg.neg, neg_add, neg_sub, neg_neg, ←sub_eq_add_neg, sub_neg_eq_add, add_comm π], rcases lt_trichotomy x.re 0 with (hr|hr|hr); rcases lt_trichotomy x.im 0 with (hi|hi|hi), { simp [hr, hr.not_le, hi.le, hi.ne, not_le.2 hi] }, { simp [hr, hr.not_le, hi] }, { simp [hr, hr.not_le, hi.ne.symm, hi.le, not_le.2 hi] }, { simp [hr] }, { simp [hr] }, { simp [hr] }, { simp [hr, hr.le, hi.ne] }, { simp [hr, hr.le, hr.le.not_lt] }, { simp [hr, hr.le, hr.le.not_lt] }, end lemma arg_inv (x : ℂ) : arg x⁻¹ = if arg x = π then π else -arg x := begin rw [←arg_conj, inv_def, mul_comm], by_cases hx : x = 0, { simp [hx] }, { exact arg_real_mul (conj x) (by simp [hx]) } end lemma arg_le_pi_div_two_iff {z : ℂ} : arg z ≤ π / 2 ↔ 0 ≤ re z ∨ im z < 0 := begin cases le_or_lt 0 (re z) with hre hre, { simp only [hre, arg_of_re_nonneg hre, real.arcsin_le_pi_div_two, true_or] }, simp only [hre.not_le, false_or], cases le_or_lt 0 (im z) with him him, { simp only [him.not_lt], rw [iff_false, not_le, arg_of_re_neg_of_im_nonneg hre him, ← sub_lt_iff_lt_add, half_sub, real.neg_pi_div_two_lt_arcsin, neg_im, neg_div, neg_lt_neg_iff, div_lt_one, ← _root_.abs_of_nonneg him, abs_im_lt_abs], exacts [hre.ne, abs.pos $ ne_of_apply_ne re hre.ne] }, { simp only [him], rw [iff_true, arg_of_re_neg_of_im_neg hre him], exact (sub_le_self _ real.pi_pos.le).trans (real.arcsin_le_pi_div_two _) } end lemma neg_pi_div_two_le_arg_iff {z : ℂ} : -(π / 2) ≤ arg z ↔ 0 ≤ re z ∨ 0 ≤ im z := begin cases le_or_lt 0 (re z) with hre hre, { simp only [hre, arg_of_re_nonneg hre, real.neg_pi_div_two_le_arcsin, true_or] }, simp only [hre.not_le, false_or], cases le_or_lt 0 (im z) with him him, { simp only [him], rw [iff_true, arg_of_re_neg_of_im_nonneg hre him], exact (real.neg_pi_div_two_le_arcsin _).trans (le_add_of_nonneg_right real.pi_pos.le) }, { simp only [him.not_le], rw [iff_false, not_le, arg_of_re_neg_of_im_neg hre him, sub_lt_iff_lt_add', ← sub_eq_add_neg, sub_half, real.arcsin_lt_pi_div_two, div_lt_one, neg_im, ← abs_of_neg him, abs_im_lt_abs], exacts [hre.ne, abs.pos $ ne_of_apply_ne re hre.ne] } end @[simp] lemma abs_arg_le_pi_div_two_iff {z : ℂ} : |arg z| ≤ π / 2 ↔ 0 ≤ re z := by rw [abs_le, arg_le_pi_div_two_iff, neg_pi_div_two_le_arg_iff, ← or_and_distrib_left, ← not_le, and_not_self, or_false] @[simp] lemma arg_conj_coe_angle (x : ℂ) : (arg (conj x) : real.angle) = -arg x := begin by_cases h : arg x = π; simp [arg_conj, h] end @[simp] lemma arg_inv_coe_angle (x : ℂ) : (arg x⁻¹ : real.angle) = -arg x := begin by_cases h : arg x = π; simp [arg_inv, h] end lemma arg_neg_eq_arg_sub_pi_of_im_pos {x : ℂ} (hi : 0 < x.im) : arg (-x) = arg x - π := begin rw [arg_of_im_pos hi, arg_of_im_neg (show (-x).im < 0, from left.neg_neg_iff.2 hi)], simp [neg_div, real.arccos_neg] end lemma arg_neg_eq_arg_add_pi_of_im_neg {x : ℂ} (hi : x.im < 0) : arg (-x) = arg x + π := begin rw [arg_of_im_neg hi, arg_of_im_pos (show 0 < (-x).im, from left.neg_pos_iff.2 hi)], simp [neg_div, real.arccos_neg, add_comm, ←sub_eq_add_neg] end lemma arg_neg_eq_arg_sub_pi_iff {x : ℂ} : arg (-x) = arg x - π ↔ (0 < x.im ∨ x.im = 0 ∧ x.re < 0) := begin rcases lt_trichotomy x.im 0 with (hi|hi|hi), { simp [hi, hi.ne, hi.not_lt, arg_neg_eq_arg_add_pi_of_im_neg, sub_eq_add_neg, ←add_eq_zero_iff_eq_neg, real.pi_ne_zero] }, { rw (ext rfl hi : x = x.re), rcases lt_trichotomy x.re 0 with (hr|hr|hr), { rw [arg_of_real_of_neg hr, ←of_real_neg, arg_of_real_of_nonneg (left.neg_pos_iff.2 hr).le], simp [hr] }, { simp [hr, hi, real.pi_ne_zero] }, { rw [arg_of_real_of_nonneg hr.le, ←of_real_neg, arg_of_real_of_neg (left.neg_neg_iff.2 hr)], simp [hr.not_lt, ←add_eq_zero_iff_eq_neg, real.pi_ne_zero] } }, { simp [hi, arg_neg_eq_arg_sub_pi_of_im_pos] } end lemma arg_neg_eq_arg_add_pi_iff {x : ℂ} : arg (-x) = arg x + π ↔ (x.im < 0 ∨ x.im = 0 ∧ 0 < x.re) := begin rcases lt_trichotomy x.im 0 with (hi|hi|hi), { simp [hi, arg_neg_eq_arg_add_pi_of_im_neg] }, { rw (ext rfl hi : x = x.re), rcases lt_trichotomy x.re 0 with (hr|hr|hr), { rw [arg_of_real_of_neg hr, ←of_real_neg, arg_of_real_of_nonneg (left.neg_pos_iff.2 hr).le], simp [hr.not_lt, ←two_mul, real.pi_ne_zero] }, { simp [hr, hi, real.pi_ne_zero.symm] }, { rw [arg_of_real_of_nonneg hr.le, ←of_real_neg, arg_of_real_of_neg (left.neg_neg_iff.2 hr)], simp [hr] } }, { simp [hi, hi.ne.symm, hi.not_lt, arg_neg_eq_arg_sub_pi_of_im_pos, sub_eq_add_neg, ←add_eq_zero_iff_neg_eq, real.pi_ne_zero] } end lemma arg_neg_coe_angle {x : ℂ} (hx : x ≠ 0) : (arg (-x) : real.angle) = arg x + π := begin rcases lt_trichotomy x.im 0 with (hi|hi|hi), { rw [arg_neg_eq_arg_add_pi_of_im_neg hi, real.angle.coe_add] }, { rw (ext rfl hi : x = x.re), rcases lt_trichotomy x.re 0 with (hr|hr|hr), { rw [arg_of_real_of_neg hr, ←of_real_neg, arg_of_real_of_nonneg (left.neg_pos_iff.2 hr).le, ←real.angle.coe_add, ←two_mul, real.angle.coe_two_pi, real.angle.coe_zero] }, { exact false.elim (hx (ext hr hi)) }, { rw [arg_of_real_of_nonneg hr.le, ←of_real_neg, arg_of_real_of_neg (left.neg_neg_iff.2 hr), real.angle.coe_zero, zero_add] } }, { rw [arg_neg_eq_arg_sub_pi_of_im_pos hi, real.angle.coe_sub, real.angle.sub_coe_pi_eq_add_coe_pi] } end lemma arg_mul_cos_add_sin_mul_I_eq_to_Ioc_mod {r : ℝ} (hr : 0 < r) (θ : ℝ) : arg (r * (cos θ + sin θ * I)) = to_Ioc_mod (-π) real.two_pi_pos θ := begin have hi : to_Ioc_mod (-π) real.two_pi_pos θ ∈ Ioc (-π) π, { convert to_Ioc_mod_mem_Ioc _ real.two_pi_pos _, ring }, convert arg_mul_cos_add_sin_mul_I hr hi using 3, simp [to_Ioc_mod, cos_add_int_mul_two_pi, sin_add_int_mul_two_pi] end lemma arg_cos_add_sin_mul_I_eq_to_Ioc_mod (θ : ℝ) : arg (cos θ + sin θ * I) = to_Ioc_mod (-π) real.two_pi_pos θ := by rw [←one_mul (_ + _), ←of_real_one, arg_mul_cos_add_sin_mul_I_eq_to_Ioc_mod zero_lt_one] lemma arg_mul_cos_add_sin_mul_I_sub {r : ℝ} (hr : 0 < r) (θ : ℝ) : arg (r * (cos θ + sin θ * I)) - θ = 2 * π * ⌊(π - θ) / (2 * π)⌋ := begin rw [arg_mul_cos_add_sin_mul_I_eq_to_Ioc_mod hr, to_Ioc_mod_sub_self, to_Ioc_div_eq_floor, zsmul_eq_mul], ring_nf end lemma arg_cos_add_sin_mul_I_sub (θ : ℝ) : arg (cos θ + sin θ * I) - θ = 2 * π * ⌊(π - θ) / (2 * π)⌋ := by rw [←one_mul (_ + _), ←of_real_one, arg_mul_cos_add_sin_mul_I_sub zero_lt_one] lemma arg_mul_cos_add_sin_mul_I_coe_angle {r : ℝ} (hr : 0 < r) (θ : real.angle) : (arg (r * (real.angle.cos θ + real.angle.sin θ * I)) : real.angle) = θ := begin induction θ using real.angle.induction_on, rw [real.angle.cos_coe, real.angle.sin_coe, real.angle.angle_eq_iff_two_pi_dvd_sub], use ⌊(π - θ) / (2 * π)⌋, exact_mod_cast arg_mul_cos_add_sin_mul_I_sub hr θ end lemma arg_cos_add_sin_mul_I_coe_angle (θ : real.angle) : (arg (real.angle.cos θ + real.angle.sin θ * I) : real.angle) = θ := by rw [←one_mul (_ + _), ←of_real_one, arg_mul_cos_add_sin_mul_I_coe_angle zero_lt_one] lemma arg_mul_coe_angle {x y : ℂ} (hx : x ≠ 0) (hy : y ≠ 0) : (arg (x * y) : real.angle) = arg x + arg y := begin convert arg_mul_cos_add_sin_mul_I_coe_angle (mul_pos (abs.pos hx) (abs.pos hy)) (arg x + arg y : real.angle) using 3, simp_rw [←real.angle.coe_add, real.angle.sin_coe, real.angle.cos_coe, of_real_cos, of_real_sin, cos_add_sin_I, of_real_add, add_mul, exp_add, of_real_mul], rw [mul_assoc, mul_comm (exp _), ←mul_assoc (abs y : ℂ), abs_mul_exp_arg_mul_I, mul_comm y, ←mul_assoc, abs_mul_exp_arg_mul_I] end lemma arg_div_coe_angle {x y : ℂ} (hx : x ≠ 0) (hy : y ≠ 0) : (arg (x / y) : real.angle) = arg x - arg y := by rw [div_eq_mul_inv, arg_mul_coe_angle hx (inv_ne_zero hy), arg_inv_coe_angle, sub_eq_add_neg] @[simp] lemma arg_coe_angle_to_real_eq_arg (z : ℂ) : (arg z : real.angle).to_real = arg z := begin rw real.angle.to_real_coe_eq_self_iff_mem_Ioc, exact arg_mem_Ioc _ end lemma arg_coe_angle_eq_iff_eq_to_real {z : ℂ} {θ : real.angle} : (arg z : real.angle) = θ ↔ arg z = θ.to_real := by rw [←real.angle.to_real_inj, arg_coe_angle_to_real_eq_arg] @[simp] lemma arg_coe_angle_eq_iff {x y : ℂ} : (arg x : real.angle) = arg y ↔ arg x = arg y := by simp_rw [←real.angle.to_real_inj, arg_coe_angle_to_real_eq_arg] section continuity variables {x z : ℂ} lemma arg_eq_nhds_of_re_pos (hx : 0 < x.re) : arg =ᶠ[𝓝 x] λ x, real.arcsin (x.im / x.abs) := ((continuous_re.tendsto _).eventually (lt_mem_nhds hx)).mono $ λ y hy, arg_of_re_nonneg hy.le lemma arg_eq_nhds_of_re_neg_of_im_pos (hx_re : x.re < 0) (hx_im : 0 < x.im) : arg =ᶠ[𝓝 x] λ x, real.arcsin ((-x).im / x.abs) + π := begin suffices h_forall_nhds : ∀ᶠ (y : ℂ) in (𝓝 x), y.re < 0 ∧ 0 < y.im, from h_forall_nhds.mono (λ y hy, arg_of_re_neg_of_im_nonneg hy.1 hy.2.le), refine is_open.eventually_mem _ (⟨hx_re, hx_im⟩ : x.re < 0 ∧ 0 < x.im), exact is_open.and (is_open_lt continuous_re continuous_zero) (is_open_lt continuous_zero continuous_im), end lemma arg_eq_nhds_of_re_neg_of_im_neg (hx_re : x.re < 0) (hx_im : x.im < 0) : arg =ᶠ[𝓝 x] λ x, real.arcsin ((-x).im / x.abs) - π := begin suffices h_forall_nhds : ∀ᶠ (y : ℂ) in (𝓝 x), y.re < 0 ∧ y.im < 0, from h_forall_nhds.mono (λ y hy, arg_of_re_neg_of_im_neg hy.1 hy.2), refine is_open.eventually_mem _ (⟨hx_re, hx_im⟩ : x.re < 0 ∧ x.im < 0), exact is_open.and (is_open_lt continuous_re continuous_zero) (is_open_lt continuous_im continuous_zero), end lemma arg_eq_nhds_of_im_pos (hz : 0 < im z) : arg =ᶠ[𝓝 z] λ x, real.arccos (x.re / abs x) := ((continuous_im.tendsto _).eventually (lt_mem_nhds hz)).mono $ λ x, arg_of_im_pos lemma arg_eq_nhds_of_im_neg (hz : im z < 0) : arg =ᶠ[𝓝 z] λ x, -real.arccos (x.re / abs x) := ((continuous_im.tendsto _).eventually (gt_mem_nhds hz)).mono $ λ x, arg_of_im_neg lemma continuous_at_arg (h : 0 < x.re ∨ x.im ≠ 0) : continuous_at arg x := begin have h₀ : abs x ≠ 0, { rw abs.ne_zero_iff, rintro rfl, simpa using h }, rw [← lt_or_lt_iff_ne] at h, rcases h with (hx_re|hx_im|hx_im), exacts [(real.continuous_at_arcsin.comp (continuous_im.continuous_at.div continuous_abs.continuous_at h₀)).congr (arg_eq_nhds_of_re_pos hx_re).symm, (real.continuous_arccos.continuous_at.comp (continuous_re.continuous_at.div continuous_abs.continuous_at h₀)).neg.congr (arg_eq_nhds_of_im_neg hx_im).symm, (real.continuous_arccos.continuous_at.comp (continuous_re.continuous_at.div continuous_abs.continuous_at h₀)).congr (arg_eq_nhds_of_im_pos hx_im).symm] end lemma tendsto_arg_nhds_within_im_neg_of_re_neg_of_im_zero {z : ℂ} (hre : z.re < 0) (him : z.im = 0) : tendsto arg (𝓝[{z : ℂ | z.im < 0}] z) (𝓝 (-π)) := begin suffices H : tendsto (λ x : ℂ, real.arcsin ((-x).im / x.abs) - π) (𝓝[{z : ℂ | z.im < 0}] z) (𝓝 (-π)), { refine H.congr' _, have : ∀ᶠ x : ℂ in 𝓝 z, x.re < 0, from continuous_re.tendsto z (gt_mem_nhds hre), filter_upwards [self_mem_nhds_within, mem_nhds_within_of_mem_nhds this] with _ him hre, rw [arg, if_neg hre.not_le, if_neg him.not_le], }, convert (real.continuous_at_arcsin.comp_continuous_within_at ((continuous_im.continuous_at.comp_continuous_within_at continuous_within_at_neg).div continuous_abs.continuous_within_at _)).sub tendsto_const_nhds, { simp [him] }, { lift z to ℝ using him, simpa using hre.ne } end lemma continuous_within_at_arg_of_re_neg_of_im_zero {z : ℂ} (hre : z.re < 0) (him : z.im = 0) : continuous_within_at arg {z : ℂ | 0 ≤ z.im} z := begin have : arg =ᶠ[𝓝[{z : ℂ | 0 ≤ z.im}] z] λ x, real.arcsin ((-x).im / x.abs) + π, { have : ∀ᶠ x : ℂ in 𝓝 z, x.re < 0, from continuous_re.tendsto z (gt_mem_nhds hre), filter_upwards [self_mem_nhds_within, mem_nhds_within_of_mem_nhds this] with _ him hre, rw [arg, if_neg hre.not_le, if_pos him] }, refine continuous_within_at.congr_of_eventually_eq _ this _, { refine (real.continuous_at_arcsin.comp_continuous_within_at ((continuous_im.continuous_at.comp_continuous_within_at continuous_within_at_neg).div continuous_abs.continuous_within_at _)).add tendsto_const_nhds, lift z to ℝ using him, simpa using hre.ne }, { rw [arg, if_neg hre.not_le, if_pos him.ge] } end lemma tendsto_arg_nhds_within_im_nonneg_of_re_neg_of_im_zero {z : ℂ} (hre : z.re < 0) (him : z.im = 0) : tendsto arg (𝓝[{z : ℂ | 0 ≤ z.im}] z) (𝓝 π) := by simpa only [arg_eq_pi_iff.2 ⟨hre, him⟩] using (continuous_within_at_arg_of_re_neg_of_im_zero hre him).tendsto lemma continuous_at_arg_coe_angle (h : x ≠ 0) : continuous_at (coe ∘ arg : ℂ → real.angle) x := begin by_cases hs : 0 < x.re ∨ x.im ≠ 0, { exact real.angle.continuous_coe.continuous_at.comp (continuous_at_arg hs) }, { rw [←function.comp.right_id (coe ∘ arg), (function.funext_iff.2 (λ _, (neg_neg _).symm) : (id : ℂ → ℂ) = has_neg.neg ∘ has_neg.neg), ←function.comp.assoc], refine continuous_at.comp _ continuous_neg.continuous_at, suffices : continuous_at (function.update ((coe ∘ arg) ∘ has_neg.neg : ℂ → real.angle) 0 π) (-x), by rwa continuous_at_update_of_ne (neg_ne_zero.2 h) at this, have ha : function.update ((coe ∘ arg) ∘ has_neg.neg : ℂ → real.angle) 0 π = λ z, (arg z : real.angle) + π, { rw function.update_eq_iff, exact ⟨by simp, λ z hz, arg_neg_coe_angle hz⟩ }, rw ha, push_neg at hs, refine (real.angle.continuous_coe.continuous_at.comp (continuous_at_arg (or.inl _))).add continuous_at_const, rw [neg_re, neg_pos], exact hs.1.lt_of_ne (λ h0, h (ext_iff.2 ⟨h0, hs.2⟩)) } end end continuity end complex
5571977a5f1680aa5f0385d362b67d518b4f8451
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/linear_algebra/multilinear.lean
f89b3f4956d3af181133c36c07afbbbef8117b0b
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
32,865
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import linear_algebra.basic import tactic.omega import data.fintype.card /-! # Multilinear maps We define multilinear maps as maps from `Π(i : ι), M₁ i` to `M₂` which are linear in each coordinate. Here, `M₁ i` and `M₂` are modules over a ring `R`, and `ι` is an arbitrary type (although some statements will require it to be a fintype). This space, denoted by `multilinear_map R M₁ M₂`, inherits a module structure by pointwise addition and multiplication. ## Main definitions * `multilinear_map R M₁ M₂` is the space of multilinear maps from `Π(i : ι), M₁ i` to `M₂`. * `f.map_smul` is the multiplicativity of the multilinear map `f` along each coordinate. * `f.map_add` is the additivity of the multilinear map `f` along each coordinate. * `f.map_smul_univ` expresses the multiplicativity of `f` over all coordinates at the same time, writing `f (λi, c i • m i)` as `univ.prod c • f m`. * `f.map_add_univ` expresses the additivity of `f` over all coordinates at the same time, writing `f (m + m')` as the sum over all subsets `s` of `ι` of `f (s.piecewise m m')`. * `f.map_sum` expresses `f (Σ_{j₁} g₁ j₁, ..., Σ_{jₙ} gₙ jₙ)` as the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all possible functions. We also register isomorphisms corresponding to currying or uncurrying variables, transforming a multilinear function `f` on `n+1` variables into a linear function taking values in multilinear functions in `n` variables, and into a multilinear function in `n` variables taking values in linear functions. These operations are called `f.curry_left` and `f.curry_right` respectively (with inverses `f.uncurry_left` and `f.uncurry_right`). These operations induce linear equivalences between spaces of multilinear functions in `n+1` variables and spaces of linear functions into multilinear functions in `n` variables (resp. multilinear functions in `n` variables taking values in linear functions), called respectively `multilinear_curry_left_equiv` and `multilinear_curry_right_equiv`. ## Implementation notes Expressing that a map is linear along the `i`-th coordinate when all other coordinates are fixed can be done in two (equivalent) different ways: * fixing a vector `m : Π(j : ι - i), M₁ j.val`, and then choosing separately the `i`-th coordinate * fixing a vector `m : Πj, M₁ j`, and then modifying its `i`-th coordinate The second way is more artificial as the value of `m` at `i` is not relevant, but it has the advantage of avoiding subtype inclusion issues. This is the definition we use, based on `function.update` that allows to change the value of `m` at `i`. -/ open function fin set universes u v v' v₁ v₂ v₃ w u' variables {R : Type u} {ι : Type u'} {n : ℕ} {M : fin n.succ → Type v} {M₁ : ι → Type v₁} {M₂ : Type v₂} {M₃ : Type v₃} {M' : Type v'} [decidable_eq ι] /-- Multilinear maps over the ring `R`, from `Πi, M₁ i` to `M₂` where `M₁ i` and `M₂` are modules over `R`. -/ structure multilinear_map (R : Type u) {ι : Type u'} (M₁ : ι → Type v) (M₂ : Type w) [decidable_eq ι] [ring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂] [∀i, module R (M₁ i)] [module R M₂] := (to_fun : (Πi, M₁ i) → M₂) (add : ∀(m : Πi, M₁ i) (i : ι) (x y : M₁ i), to_fun (update m i (x + y)) = to_fun (update m i x) + to_fun (update m i y)) (smul : ∀(m : Πi, M₁ i) (i : ι) (c : R) (x : M₁ i), to_fun (update m i (c • x)) = c • to_fun (update m i x)) namespace multilinear_map section ring variables [ring R] [∀i, add_comm_group (M i)] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂] [add_comm_group M₃] [add_comm_group M'] [∀i, module R (M i)] [∀i, module R (M₁ i)] [module R M₂] [module R M₃] [module R M'] (f f' : multilinear_map R M₁ M₂) instance : has_coe_to_fun (multilinear_map R M₁ M₂) := ⟨_, to_fun⟩ @[ext] theorem ext {f f' : multilinear_map R M₁ M₂} (H : ∀ x, f x = f' x) : f = f' := by cases f; cases f'; congr'; exact funext H @[simp] lemma map_add (m : Πi, M₁ i) (i : ι) (x y : M₁ i) : f (update m i (x + y)) = f (update m i x) + f (update m i y) := f.add m i x y @[simp] lemma map_smul (m : Πi, M₁ i) (i : ι) (c : R) (x : M₁ i) : f (update m i (c • x)) = c • f (update m i x) := f.smul m i c x @[simp] lemma map_sub (m : Πi, M₁ i) (i : ι) (x y : M₁ i) : f (update m i (x - y)) = f (update m i x) - f (update m i y) := by { simp only [map_add, add_left_inj, sub_eq_add_neg, (neg_one_smul R y).symm, map_smul], simp } lemma map_coord_zero {m : Πi, M₁ i} (i : ι) (h : m i = 0) : f m = 0 := begin have : (0 : R) • (0 : M₁ i) = 0, by simp, rw [← update_eq_self i m, h, ← this, f.map_smul, zero_smul] end @[simp] lemma map_zero [nonempty ι] : f 0 = 0 := begin obtain ⟨i, _⟩ : ∃i:ι, i ∈ set.univ := set.exists_mem_of_nonempty ι, exact map_coord_zero f i rfl end instance : has_add (multilinear_map R M₁ M₂) := ⟨λf f', ⟨λx, f x + f' x, λm i x y, by simp [add_left_comm, add_assoc], λm i c x, by simp [smul_add]⟩⟩ @[simp] lemma add_apply (m : Πi, M₁ i) : (f + f') m = f m + f' m := rfl instance : has_neg (multilinear_map R M₁ M₂) := ⟨λ f, ⟨λ m, - f m, λm i x y, by simp [add_comm], λm i c x, by simp⟩⟩ @[simp] lemma neg_apply (m : Πi, M₁ i) : (-f) m = - (f m) := rfl instance : has_zero (multilinear_map R M₁ M₂) := ⟨⟨λ _, 0, λm i x y, by simp, λm i c x, by simp⟩⟩ instance : inhabited (multilinear_map R M₁ M₂) := ⟨0⟩ @[simp] lemma zero_apply (m : Πi, M₁ i) : (0 : multilinear_map R M₁ M₂) m = 0 := rfl instance : add_comm_group (multilinear_map R M₁ M₂) := by refine {zero := 0, add := (+), neg := has_neg.neg, ..}; intros; ext; simp [add_comm, add_left_comm] @[simp] lemma sum_apply {α : Type*} (f : α → multilinear_map R M₁ M₂) (m : Πi, M₁ i) : ∀ {s : finset α}, (s.sum f) m = s.sum (λ a, f a m) := begin classical, apply finset.induction, { rw finset.sum_empty, simp }, { assume a s has H, rw finset.sum_insert has, simp [H, has] } end /-- If `f` is a multilinear map, then `f.to_linear_map m i` is the linear map obtained by fixing all coordinates but `i` equal to those of `m`, and varying the `i`-th coordinate. -/ def to_linear_map (m : Πi, M₁ i) (i : ι) : M₁ i →ₗ[R] M₂ := { to_fun := λx, f (update m i x), add := λx y, by simp, smul := λc x, by simp } /-- The cartesian product of two multilinear maps, as a multilinear map. -/ def prod (f : multilinear_map R M₁ M₂) (g : multilinear_map R M₁ M₃) : multilinear_map R M₁ (M₂ × M₃) := { to_fun := λ m, (f m, g m), add := λ m i x y, by simp, smul := λ m i c x, by simp } /-- Given a multilinear map `f` on `n` variables (parameterized by `fin n`) and a subset `s` of `k` of these variables, one gets a new multilinear map on `fin k` by varying these variables, and fixing the other ones equal to a given value `z`. It is denoted by `f.restr s hk z`, where `hk` is a proof that the cardinality of `s` is `k`. The implicit identification between `fin k` and `s` that we use is the canonical (increasing) bijection. -/ noncomputable def restr {k n : ℕ} (f : multilinear_map R (λ i : fin n, M') M₂) (s : finset (fin n)) (hk : s.card = k) (z : M') : multilinear_map R (λ i : fin k, M') M₂ := { to_fun := λ v, f (λ j, if h : j ∈ s then v ((s.mono_equiv_of_fin hk).symm ⟨j, h⟩) else z), add := λ v i x y, by { erw [dite_comp_equiv_update, dite_comp_equiv_update, dite_comp_equiv_update], simp }, smul := λ v i c x, by { erw [dite_comp_equiv_update, dite_comp_equiv_update], simp } } variable {R} /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the additivity of a multilinear map along the first variable. -/ lemma cons_add (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (x y : M 0) : f (cons (x+y) m) = f (cons x m) + f (cons y m) := by rw [← update_cons_zero x m (x+y), f.map_add, update_cons_zero, update_cons_zero] /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the multiplicativity of a multilinear map along the first variable. -/ lemma cons_smul (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (c : R) (x : M 0) : f (cons (c • x) m) = c • f (cons x m) := by rw [← update_cons_zero x m (c • x), f.map_smul, update_cons_zero] /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `snoc`, one can express directly the additivity of a multilinear map along the first variable. -/ lemma snoc_add (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.cast_succ) (x y : M (last n)) : f (snoc m (x+y)) = f (snoc m x) + f (snoc m y) := by rw [← update_snoc_last x m (x+y), f.map_add, update_snoc_last, update_snoc_last] /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the multiplicativity of a multilinear map along the first variable. -/ lemma snoc_smul (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.cast_succ) (c : R) (x : M (last n)) : f (snoc m (c • x)) = c • f (snoc m x) := by rw [← update_snoc_last x m (c • x), f.map_smul, update_snoc_last] /-- If `g` is multilinear and `f` is linear, then `g (f m₁, ..., f mₙ)` is again a multilinear function, that we call `g.comp_linear_map f`. -/ def comp_linear_map (g : multilinear_map R (λ (i : ι), M₂) M₃) (f : M' →ₗ[R] M₂) : multilinear_map R (λ (i : ι), M') M₃ := { to_fun := λ m, g (f ∘ m), add := λ m i x y, by simp [comp_update], smul := λ m i c x, by simp [comp_update] } /-- If one adds to a vector `m'` another vector `m`, but only for coordinates in a finset `t`, then the image under a multilinear map `f` is the sum of `f (s.piecewise m m')` along all subsets `s` of `t`. This is mainly an auxiliary statement to prove the result when `t = univ`, given in `map_add_univ`, although it can be useful in its own right as it does not require the index set `ι` to be finite.-/ lemma map_piecewise_add (m m' : Πi, M₁ i) (t : finset ι) : f (t.piecewise (m + m') m') = t.powerset.sum (λs, f (s.piecewise m m')) := begin revert m', refine finset.induction_on t (by simp) _, assume i t hit Hrec m', have A : (insert i t).piecewise (m + m') m' = update (t.piecewise (m + m') m') i (m i + m' i) := t.piecewise_insert _ _ _, have B : update (t.piecewise (m + m') m') i (m' i) = t.piecewise (m + m') m', { ext j, by_cases h : j = i, { rw h, simp [hit] }, { simp [h] } }, let m'' := update m' i (m i), have C : update (t.piecewise (m + m') m') i (m i) = t.piecewise (m + m'') m'', { ext j, by_cases h : j = i, { rw h, simp [m'', hit] }, { by_cases h' : j ∈ t; simp [h, hit, m'', h'] } }, rw [A, f.map_add, B, C, finset.sum_powerset_insert hit, Hrec, Hrec, add_comm], congr' 1, apply finset.sum_congr rfl (λs hs, _), have : (insert i s).piecewise m m' = s.piecewise m m'', { ext j, by_cases h : j = i, { rw h, simp [m'', finset.not_mem_of_mem_powerset_of_not_mem hs hit] }, { by_cases h' : j ∈ s; simp [h, m'', h'] } }, rw this end /-- Additivity of a multilinear map along all coordinates at the same time, writing `f (m + m')` as the sum of `f (s.piecewise m m')` over all sets `s`. -/ lemma map_add_univ [fintype ι] (m m' : Πi, M₁ i) : f (m + m') = (finset.univ : finset (finset ι)).sum (λs, f (s.piecewise m m')) := by simpa using f.map_piecewise_add m m' finset.univ section apply_sum variables {α : ι → Type*} [fintype ι] (g : Π i, α i → M₁ i) (A : Π i, finset (α i)) open_locale classical open fintype finset /-- If `f` is multilinear, then `f (Σ_{j₁ ∈ A₁} g₁ j₁, ..., Σ_{jₙ ∈ Aₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions with `r 1 ∈ A₁`, ..., `r n ∈ Aₙ`. This follows from multilinearity by expanding successively with respect to each coordinate. Here, we give an auxiliary statement tailored for an inductive proof. Use instead `map_sum_finset`. -/ lemma map_sum_finset_aux {n : ℕ} (h : finset.univ.sum (λ i, (A i).card) = n) : f (λ i, (A i).sum (g i)) = (pi_finset A).sum (λ r, f (λ i, g i (r i))) := begin unfreezeI, induction n using nat.strong_induction_on with n IH generalizing A, -- If one of the sets is empty, then all the sums are zero by_cases Ai_empty : ∃ i, A i = ∅, { rcases Ai_empty with ⟨i, hi⟩, have : (A i).sum (λ j, g i j) = 0, by convert sum_empty, rw f.map_coord_zero i this, have : pi_finset A = ∅, { apply finset.eq_empty_of_forall_not_mem (λ r hr, _), have : r i ∈ A i := mem_pi_finset.mp hr i, rwa hi at this }, convert sum_empty.symm }, push_neg at Ai_empty, -- Otherwise, if all sets are at most singletons, then they are exactly singletons and the result -- is again straightforward by_cases Ai_singleton : ∀ i, (A i).card ≤ 1, { have Ai_card : ∀ i, (A i).card = 1, { assume i, have : finset.card (A i) ≠ 0, by simp [finset.card_eq_zero, Ai_empty i], have : finset.card (A i) ≤ 1 := Ai_singleton i, omega }, have : ∀ (r : Π i, α i), r ∈ pi_finset A → f (λ i, g i (r i)) = f (λ i, (A i).sum (λ j, g i j)), { assume r hr, unfold_coes, congr, ext i, have : ∀ j ∈ A i, g i j = g i (r i), { assume j hj, congr, apply finset.card_le_one_iff.1 (Ai_singleton i) hj, exact mem_pi_finset.mp hr i }, simp only [finset.sum_congr rfl this, finset.mem_univ, finset.sum_const, Ai_card i, add_monoid.one_smul] }, simp only [sum_congr rfl this, Ai_card, card_pi_finset, prod_const_one, add_monoid.one_smul, sum_const] }, -- Remains the interesting case where one of the `A i`, say `A i₀`, has cardinality at least 2. -- We will split into two parts `B i₀` and `C i₀` of smaller cardinality, let `B i = C i = A i` -- for `i ≠ i₀`, apply the inductive assumption to `B` and `C`, and add up the corresponding -- parts to get the sum for `A`. push_neg at Ai_singleton, obtain ⟨i₀, hi₀⟩ : ∃ i, 1 < (A i).card := Ai_singleton, obtain ⟨j₁, j₂, hj₁, hj₂, j₁_ne_j₂⟩ : ∃ j₁ j₂, (j₁ ∈ A i₀) ∧ (j₂ ∈ A i₀) ∧ j₁ ≠ j₂ := finset.one_lt_card_iff.1 hi₀, let B := function.update A i₀ (A i₀ \ {j₂}), let C := function.update A i₀ {j₂}, have B_subset_A : ∀ i, B i ⊆ A i, { assume i, by_cases hi : i = i₀, { rw hi, simp only [B, sdiff_subset, update_same]}, { simp only [hi, B, update_noteq, ne.def, not_false_iff, finset.subset.refl] } }, have C_subset_A : ∀ i, C i ⊆ A i, { assume i, by_cases hi : i = i₀, { rw hi, simp only [C, hj₂, finset.singleton_subset_iff, update_same] }, { simp only [hi, C, update_noteq, ne.def, not_false_iff, finset.subset.refl] } }, -- split the sum at `i₀` as the sum over `B i₀` plus the sum over `C i₀`, to use additivity. have A_eq_BC : (λ i, (A i).sum (g i)) = function.update (λ i, (A i).sum (g i)) i₀ ((B i₀).sum (g i₀) + (C i₀).sum (g i₀)), { ext i, by_cases hi : i = i₀, { rw [hi], simp only [function.update_same], have : A i₀ = B i₀ ∪ C i₀, { simp only [B, C, function.update_same, finset.sdiff_union_self_eq_union], symmetry, simp only [hj₂, finset.singleton_subset_iff, union_eq_left_iff_subset] }, rw this, apply finset.sum_union, apply finset.disjoint_right.2 (λ j hj, _), have : j = j₂, by { dsimp [C] at hj, simpa using hj }, rw this, dsimp [B], simp only [mem_sdiff, eq_self_iff_true, not_true, not_false_iff, finset.mem_singleton, update_same, and_false] }, { simp [hi] } }, have Beq : function.update (λ i, (A i).sum (g i)) i₀ ((B i₀).sum (g i₀)) = (λ i, finset.sum (B i) (g i)), { ext i, by_cases hi : i = i₀, { rw hi, simp only [update_same] }, { simp only [hi, B, update_noteq, ne.def, not_false_iff] } }, have Ceq : function.update (λ i, (A i).sum (g i)) i₀ ((C i₀).sum (g i₀)) = (λ i, finset.sum (C i) (g i)), { ext i, by_cases hi : i = i₀, { rw hi, simp only [update_same] }, { simp only [hi, C, update_noteq, ne.def, not_false_iff] } }, -- Express the inductive assumption for `B` have Brec : f (λ i, finset.sum (B i) (g i)) = (pi_finset B).sum (λ r, f (λ i, g i (r i))), { have : finset.univ.sum (λ i, finset.card (B i)) < finset.univ.sum (λ i, finset.card (A i)), { refine finset.sum_lt_sum (λ i hi, finset.card_le_of_subset (B_subset_A i)) ⟨i₀, finset.mem_univ _, _⟩, have : {j₂} ⊆ A i₀, by simp [hj₂], simp only [B, finset.card_sdiff this, function.update_same, finset.card_singleton], exact nat.pred_lt (ne_of_gt (lt_trans zero_lt_one hi₀)) }, rw h at this, exact IH _ this B rfl }, -- Express the inductive assumption for `C` have Crec : f (λ i, finset.sum (C i) (g i)) = (pi_finset C).sum (λ r, f (λ i, g i (r i))), { have : finset.univ.sum (λ i, finset.card (C i)) < finset.univ.sum (λ i, finset.card (A i)) := finset.sum_lt_sum (λ i hi, finset.card_le_of_subset (C_subset_A i)) ⟨i₀, finset.mem_univ _, by simp [C, hi₀]⟩, rw h at this, exact IH _ this C rfl }, have D : disjoint (pi_finset B) (pi_finset C), { have : disjoint (B i₀) (C i₀), by simp [B, C], exact pi_finset_disjoint_of_disjoint B C this }, have pi_BC : pi_finset A = pi_finset B ∪ pi_finset C, { apply finset.subset.antisymm, { assume r hr, by_cases hri₀ : r i₀ = j₂, { apply finset.mem_union_right, apply mem_pi_finset.2 (λ i, _), by_cases hi : i = i₀, { have : r i₀ ∈ C i₀, by simp [C, hri₀], convert this }, { simp [C, hi, mem_pi_finset.1 hr i] } }, { apply finset.mem_union_left, apply mem_pi_finset.2 (λ i, _), by_cases hi : i = i₀, { have : r i₀ ∈ B i₀, by simp [B, hri₀, mem_pi_finset.1 hr i₀], convert this }, { simp [B, hi, mem_pi_finset.1 hr i] } } }, { exact finset.union_subset (pi_finset_subset _ _ (λ i, B_subset_A i)) (pi_finset_subset _ _ (λ i, C_subset_A i)) } }, rw A_eq_BC, simp only [multilinear_map.map_add, Beq, Ceq, Brec, Crec, pi_BC], rw ← finset.sum_union D, end /-- If `f` is multilinear, then `f (Σ_{j₁ ∈ A₁} g₁ j₁, ..., Σ_{jₙ ∈ Aₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions with `r 1 ∈ A₁`, ..., `r n ∈ Aₙ`. This follows from multilinearity by expanding successively with respect to each coordinate. -/ lemma map_sum_finset : f (λ i, (A i).sum (g i)) = (pi_finset A).sum (λ r, f (λ i, g i (r i))) := f.map_sum_finset_aux _ _ rfl /-- If `f` is multilinear, then `f (Σ_{j₁} g₁ j₁, ..., Σ_{jₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions `r`. This follows from multilinearity by expanding successively with respect to each coordinate. -/ lemma map_sum [∀ i, fintype (α i)] : f (λ i, finset.univ.sum (g i)) = finset.univ.sum (λ (r : Π i, α i), f (λ i, g i (r i))) := f.map_sum_finset g (λ i, finset.univ) end apply_sum end ring section comm_ring variables [comm_ring R] [∀i, add_comm_group (M₁ i)] [∀i, add_comm_group (M i)] [add_comm_group M₂] [∀i, module R (M i)] [∀i, module R (M₁ i)] [module R M₂] (f f' : multilinear_map R M₁ M₂) /-- If one multiplies by `c i` the coordinates in a finset `s`, then the image under a multilinear map is multiplied by `s.prod c`. This is mainly an auxiliary statement to prove the result when `s = univ`, given in `map_smul_univ`, although it can be useful in its own right as it does not require the index set `ι` to be finite. -/ lemma map_piecewise_smul (c : ι → R) (m : Πi, M₁ i) (s : finset ι) : f (s.piecewise (λi, c i • m i) m) = s.prod c • f m := begin refine s.induction_on (by simp) _, assume j s j_not_mem_s Hrec, have A : function.update (s.piecewise (λi, c i • m i) m) j (m j) = s.piecewise (λi, c i • m i) m, { ext i, by_cases h : i = j, { rw h, simp [j_not_mem_s] }, { simp [h] } }, rw [s.piecewise_insert, f.map_smul, A, Hrec], simp [j_not_mem_s, mul_smul] end /-- Multiplicativity of a multilinear map along all coordinates at the same time, writing `f (λi, c i • m i)` as `univ.prod c • f m`. -/ lemma map_smul_univ [fintype ι] (c : ι → R) (m : Πi, M₁ i) : f (λi, c i • m i) = finset.univ.prod c • f m := by simpa using map_piecewise_smul f c m finset.univ instance : has_scalar R (multilinear_map R M₁ M₂) := ⟨λ c f, ⟨λ m, c • f m, λm i x y, by simp [smul_add], λl i x d, by simp [smul_smul, mul_comm]⟩⟩ @[simp] lemma smul_apply (c : R) (m : Πi, M₁ i) : (c • f) m = c • f m := rfl /-- The space of multilinear maps is a module over `R`, for the pointwise addition and scalar multiplication. -/ instance : module R (multilinear_map R M₁ M₂) := module.of_core $ by refine { smul := (•), ..}; intros; ext; simp [smul_add, add_smul, smul_smul] variables (R ι) /-- The canonical multilinear map on `R^ι` when `ι` is finite, associating to `m` the product of all the `m i` (multiplied by a fixed reference element `z` in the target module) -/ protected def mk_pi_ring [fintype ι] (z : M₂) : multilinear_map R (λ(i : ι), R) M₂ := { to_fun := λm, finset.univ.prod m • z, add := λ m i x y, by simp [finset.prod_update_of_mem, add_mul, add_smul], smul := λ m i c x, by { rw [smul_eq_mul], simp [finset.prod_update_of_mem, smul_smul, mul_assoc] } } variables {R ι} @[simp] lemma mk_pi_ring_apply [fintype ι] (z : M₂) (m : ι → R) : (multilinear_map.mk_pi_ring R ι z : (ι → R) → M₂) m = finset.univ.prod m • z := rfl lemma mk_pi_ring_apply_one_eq_self [fintype ι] (f : multilinear_map R (λ(i : ι), R) M₂) : multilinear_map.mk_pi_ring R ι (f (λi, 1)) = f := begin ext m, have : m = (λi, m i • 1), by { ext j, simp }, conv_rhs { rw [this, f.map_smul_univ] }, refl end variables (R ι M₂) /-- When `ι` is finite, multilinear maps on `R^ι` with values in `M₂` are in bijection with `M₂`, as such a multilinear map is completely determined by its value on the constant vector made of ones. We register this bijection as a linear equivalence in `multilinear_map.pi_ring_equiv`. -/ protected def pi_ring_equiv [fintype ι] : M₂ ≃ₗ[R] (multilinear_map R (λ(i : ι), R) M₂) := { to_fun := λ z, multilinear_map.mk_pi_ring R ι z, inv_fun := λ f, f (λi, 1), add := λ z z', by { ext m, simp [smul_add] }, smul := λ c z, by { ext m, simp [smul_smul, mul_comm] }, left_inv := λ z, by simp, right_inv := λ f, f.mk_pi_ring_apply_one_eq_self } end comm_ring end multilinear_map namespace linear_map variables [ring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂] [add_comm_group M₃] [∀i, module R (M₁ i)] [module R M₂] [module R M₃] /-- Composing a multilinear map with a linear map gives again a multilinear map. -/ def comp_multilinear_map (g : M₂ →ₗ[R] M₃) (f : multilinear_map R M₁ M₂) : multilinear_map R M₁ M₃ := { to_fun := λ m, g (f m), add := λ m i x y, by simp, smul := λ m i c x, by simp } end linear_map section currying /-! ### Currying We associate to a multilinear map in `n+1` variables (i.e., based on `fin n.succ`) two curried functions, named `f.curry_left` (which is a linear map on `E 0` taking values in multilinear maps in `n` variables) and `f.curry_right` (wich is a multilinear map in `n` variables taking values in linear maps on `E 0`). In both constructions, the variable that is singled out is `0`, to take advantage of the operations `cons` and `tail` on `fin n`. The inverse operations are called `uncurry_left` and `uncurry_right`. We also register linear equiv versions of these correspondences, in `multilinear_curry_left_equiv` and `multilinear_curry_right_equiv`. -/ open multilinear_map variables {R M M₂} [comm_ring R] [∀i, add_comm_group (M i)] [add_comm_group M'] [add_comm_group M₂] [∀i, module R (M i)] [module R M'] [module R M₂] /-! #### Left currying -/ /-- Given a linear map `f` from `M 0` to multilinear maps on `n` variables, construct the corresponding multilinear map on `n+1` variables obtained by concatenating the variables, given by `m ↦ f (m 0) (tail m)`-/ def linear_map.uncurry_left (f : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) : multilinear_map R M M₂ := { to_fun := λm, f (m 0) (tail m), add := λm i x y, begin by_cases h : i = 0, { revert x y, rw h, assume x y, rw [update_same, update_same, update_same, f.map_add, add_apply, tail_update_zero, tail_update_zero, tail_update_zero] }, { rw [update_noteq (ne.symm h), update_noteq (ne.symm h), update_noteq (ne.symm h)], revert x y, rw ← succ_pred i h, assume x y, rw [tail_update_succ, map_add, tail_update_succ, tail_update_succ] } end, smul := λm i c x, begin by_cases h : i = 0, { revert x, rw h, assume x, rw [update_same, update_same, tail_update_zero, tail_update_zero, ← smul_apply, f.map_smul] }, { rw [update_noteq (ne.symm h), update_noteq (ne.symm h)], revert x, rw ← succ_pred i h, assume x, rw [tail_update_succ, tail_update_succ, map_smul] } end } @[simp] lemma linear_map.uncurry_left_apply (f : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) (m : Πi, M i) : f.uncurry_left m = f (m 0) (tail m) := rfl /-- Given a multilinear map `f` in `n+1` variables, split the first variable to obtain a linear map into multilinear maps in `n` variables, given by `x ↦ (m ↦ f (cons x m))`. -/ def multilinear_map.curry_left (f : multilinear_map R M M₂) : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂) := { to_fun := λx, { to_fun := λm, f (cons x m), add := λm i y y', by simp, smul := λm i y c, by simp }, add := λx y, by { ext m, exact cons_add f m x y }, smul := λc x, by { ext m, exact cons_smul f m c x } } @[simp] lemma multilinear_map.curry_left_apply (f : multilinear_map R M M₂) (x : M 0) (m : Π(i : fin n), M i.succ) : f.curry_left x m = f (cons x m) := rfl @[simp] lemma linear_map.curry_uncurry_left (f : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) : f.uncurry_left.curry_left = f := begin ext m x, simp only [tail_cons, linear_map.uncurry_left_apply, multilinear_map.curry_left_apply], rw cons_zero end @[simp] lemma multilinear_map.uncurry_curry_left (f : multilinear_map R M M₂) : f.curry_left.uncurry_left = f := by { ext m, simp } variables (R M M₂) /-- The space of multilinear maps on `Π(i : fin (n+1)), M i` is canonically isomorphic to the space of linear maps from `M 0` to the space of multilinear maps on `Π(i : fin n), M i.succ `, by separating the first variable. We register this isomorphism as a linear isomorphism in `multilinear_curry_left_equiv R M M₂`. The direct and inverse maps are given by `f.uncurry_left` and `f.curry_left`. Use these unless you need the full framework of linear equivs. -/ def multilinear_curry_left_equiv : (M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) ≃ₗ[R] (multilinear_map R M M₂) := { to_fun := linear_map.uncurry_left, add := λf₁ f₂, by { ext m, refl }, smul := λc f, by { ext m, refl }, inv_fun := multilinear_map.curry_left, left_inv := linear_map.curry_uncurry_left, right_inv := multilinear_map.uncurry_curry_left } variables {R M M₂} /-! #### Right currying -/ /-- Given a multilinear map `f` in `n` variables to the space of linear maps from `M (last n)` to `M₂`, construct the corresponding multilinear map on `n+1` variables obtained by concatenating the variables, given by `m ↦ f (init m) (m (last n))`-/ def multilinear_map.uncurry_right (f : (multilinear_map R (λ(i : fin n), M i.cast_succ) (M (last n) →ₗ[R] M₂))) : multilinear_map R M M₂ := { to_fun := λm, f (init m) (m (last n)), add := λm i x y, begin by_cases h : i.val < n, { have : last n ≠ i := ne.symm (ne_of_lt h), rw [update_noteq this, update_noteq this, update_noteq this], revert x y, rw [(cast_succ_cast_lt i h).symm], assume x y, rw [init_update_cast_succ, map_add, init_update_cast_succ, init_update_cast_succ, linear_map.add_apply] }, { revert x y, rw eq_last_of_not_lt h, assume x y, rw [init_update_last, init_update_last, init_update_last, update_same, update_same, update_same, linear_map.map_add] } end, smul := λm i c x, begin by_cases h : i.val < n, { have : last n ≠ i := ne.symm (ne_of_lt h), rw [update_noteq this, update_noteq this], revert x, rw [(cast_succ_cast_lt i h).symm], assume x, rw [init_update_cast_succ, init_update_cast_succ, map_smul, linear_map.smul_apply] }, { revert x, rw eq_last_of_not_lt h, assume x, rw [update_same, update_same, init_update_last, init_update_last, linear_map.map_smul] } end } @[simp] lemma multilinear_map.uncurry_right_apply (f : (multilinear_map R (λ(i : fin n), M i.cast_succ) ((M (last n)) →ₗ[R] M₂))) (m : Πi, M i) : f.uncurry_right m = f (init m) (m (last n)) := rfl /-- Given a multilinear map `f` in `n+1` variables, split the last variable to obtain a multilinear map in `n` variables taking values in linear maps from `M (last n)` to `M₂`, given by `m ↦ (x ↦ f (snoc m x))`. -/ def multilinear_map.curry_right (f : multilinear_map R M M₂) : multilinear_map R (λ(i : fin n), M (fin.cast_succ i)) ((M (last n)) →ₗ[R] M₂) := { to_fun := λm, { to_fun := λx, f (snoc m x), add := λx y, by rw f.snoc_add, smul := λc x, by rw f.snoc_smul }, add := λm i x y, begin ext z, change f (snoc (update m i (x + y)) z) = f (snoc (update m i x) z) + f (snoc (update m i y) z), rw [snoc_update, snoc_update, snoc_update, f.map_add] end, smul := λm i c x, begin ext z, change f (snoc (update m i (c • x)) z) = c • f (snoc (update m i x) z), rw [snoc_update, snoc_update, f.map_smul] end } @[simp] lemma multilinear_map.curry_right_apply (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.cast_succ) (x : M (last n)) : f.curry_right m x = f (snoc m x) := rfl @[simp] lemma multilinear_map.curry_uncurry_right (f : (multilinear_map R (λ(i : fin n), M i.cast_succ) ((M (last n)) →ₗ[R] M₂))) : f.uncurry_right.curry_right = f := begin ext m x, simp only [snoc_last, multilinear_map.curry_right_apply, multilinear_map.uncurry_right_apply], rw init_snoc end @[simp] lemma multilinear_map.uncurry_curry_right (f : multilinear_map R M M₂) : f.curry_right.uncurry_right = f := by { ext m, simp } variables (R M M₂) /-- The space of multilinear maps on `Π(i : fin (n+1)), M i` is canonically isomorphic to the space of linear maps from the space of multilinear maps on `Π(i : fin n), M i.cast_succ` to the space of linear maps on `M (last n)`, by separating the last variable. We register this isomorphism as a linear isomorphism in `multilinear_curry_right_equiv R M M₂`. The direct and inverse maps are given by `f.uncurry_right` and `f.curry_right`. Use these unless you need the full framework of linear equivs. -/ def multilinear_curry_right_equiv : (multilinear_map R (λ(i : fin n), M i.cast_succ) ((M (last n)) →ₗ[R] M₂)) ≃ₗ[R] (multilinear_map R M M₂) := { to_fun := multilinear_map.uncurry_right, add := λf₁ f₂, by { ext m, refl }, smul := λc f, by { ext m, rw [smul_apply], refl }, inv_fun := multilinear_map.curry_right, left_inv := multilinear_map.curry_uncurry_right, right_inv := multilinear_map.uncurry_curry_right } end currying
2d53ee181a6c8fda4b9a72e171dc94b6c1110258
367134ba5a65885e863bdc4507601606690974c1
/src/algebra/category/CommRing/limits.lean
b2548386764ebfc684580b8b2edf64e7554cf5ac
[ "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,551
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.ring.pi import algebra.category.CommRing.basic import algebra.category.Group.limits import ring_theory.subring /-! # The category of (commutative) rings has all limits Further, these limits are preserved by the forgetful functor --- that is, the underlying types are just the limits in the category of types. -/ open category_theory open category_theory.limits universe u noncomputable theory namespace SemiRing variables {J : Type u} [small_category J] instance semiring_obj (F : J ⥤ SemiRing) (j) : semiring ((F ⋙ forget SemiRing).obj j) := by { change semiring (F.obj j), apply_instance } /-- The flat sections of a functor into `SemiRing` form a subsemiring of all sections. -/ def sections_subsemiring (F : J ⥤ SemiRing) : subsemiring (Π j, F.obj j) := { carrier := (F ⋙ forget SemiRing).sections, ..(AddMon.sections_add_submonoid (F ⋙ forget₂ SemiRing AddCommMon ⋙ forget₂ AddCommMon AddMon)), ..(Mon.sections_submonoid (F ⋙ forget₂ SemiRing Mon)) } instance limit_semiring (F : J ⥤ SemiRing) : semiring (types.limit_cone (F ⋙ forget SemiRing.{u})).X := (sections_subsemiring F).to_semiring /-- `limit.π (F ⋙ forget SemiRing) j` as a `ring_hom`. -/ def limit_π_ring_hom (F : J ⥤ SemiRing.{u}) (j) : (types.limit_cone (F ⋙ forget SemiRing)).X →+* (F ⋙ forget SemiRing).obj j := { to_fun := (types.limit_cone (F ⋙ forget SemiRing)).π.app j, ..AddMon.limit_π_add_monoid_hom (F ⋙ forget₂ SemiRing AddCommMon.{u} ⋙ forget₂ AddCommMon AddMon) j, ..Mon.limit_π_monoid_hom (F ⋙ forget₂ SemiRing Mon) j, } namespace has_limits -- The next two definitions are used in the construction of `has_limits SemiRing`. -- After that, the limits should be constructed using the generic limits API, -- e.g. `limit F`, `limit.cone F`, and `limit.is_limit F`. /-- Construction of a limit cone in `SemiRing`. (Internal use only; use the limits API.) -/ def limit_cone (F : J ⥤ SemiRing) : cone F := { X := SemiRing.of (types.limit_cone (F ⋙ forget _)).X, π := { app := limit_π_ring_hom F, naturality' := λ j j' f, ring_hom.coe_inj ((types.limit_cone (F ⋙ forget _)).π.naturality f) } } /-- Witness that the limit cone in `SemiRing` is a limit cone. (Internal use only; use the limits API.) -/ def limit_cone_is_limit (F : J ⥤ SemiRing) : is_limit (limit_cone F) := begin refine is_limit.of_faithful (forget SemiRing) (types.limit_cone_is_limit _) (λ s, ⟨_, _, _, _, _⟩) (λ s, rfl); tidy end end has_limits open has_limits /-- The category of rings has all limits. -/ @[irreducible] instance has_limits : has_limits SemiRing := { has_limits_of_shape := λ J 𝒥, by exactI { has_limit := λ F, has_limit.mk { cone := limit_cone F, is_limit := limit_cone_is_limit F } } } /-- An auxiliary declaration to speed up typechecking. -/ def forget₂_AddCommMon_preserves_limits_aux (F : J ⥤ SemiRing) : is_limit ((forget₂ SemiRing AddCommMon).map_cone (limit_cone F)) := AddCommMon.limit_cone_is_limit (F ⋙ forget₂ SemiRing AddCommMon) /-- The forgetful functor from semirings to additive commutative monoids preserves all limits. -/ instance forget₂_AddCommMon_preserves_limits : preserves_limits (forget₂ SemiRing AddCommMon) := { preserves_limits_of_shape := λ J 𝒥, by exactI { preserves_limit := λ F, preserves_limit_of_preserves_limit_cone (limit_cone_is_limit F) (forget₂_AddCommMon_preserves_limits_aux F) } } /-- An auxiliary declaration to speed up typechecking. -/ def forget₂_Mon_preserves_limits_aux (F : J ⥤ SemiRing) : is_limit ((forget₂ SemiRing Mon).map_cone (limit_cone F)) := Mon.has_limits.limit_cone_is_limit (F ⋙ forget₂ SemiRing Mon) /-- The forgetful functor from semirings to monoids preserves all limits. -/ instance forget₂_Mon_preserves_limits : preserves_limits (forget₂ SemiRing Mon) := { preserves_limits_of_shape := λ J 𝒥, by exactI { preserves_limit := λ F, preserves_limit_of_preserves_limit_cone (limit_cone_is_limit F) (forget₂_Mon_preserves_limits_aux F) } } /-- The forgetful functor from semirings to types preserves all limits. -/ instance forget_preserves_limits : preserves_limits (forget SemiRing) := { preserves_limits_of_shape := λ J 𝒥, by exactI { preserves_limit := λ F, preserves_limit_of_preserves_limit_cone (limit_cone_is_limit F) (types.limit_cone_is_limit (F ⋙ forget _)) } } end SemiRing namespace CommSemiRing variables {J : Type u} [small_category J] instance comm_semiring_obj (F : J ⥤ CommSemiRing) (j) : comm_semiring ((F ⋙ forget CommSemiRing).obj j) := by { change comm_semiring (F.obj j), apply_instance } instance limit_comm_semiring (F : J ⥤ CommSemiRing) : comm_semiring (types.limit_cone (F ⋙ forget CommSemiRing.{u})).X := @subsemiring.to_comm_semiring (Π j, F.obj j) _ (SemiRing.sections_subsemiring (F ⋙ forget₂ CommSemiRing SemiRing.{u})) /-- We show that the forgetful functor `CommSemiRing ⥤ SemiRing` creates limits. All we need to do is notice that the limit point has a `comm_semiring` instance available, and then reuse the existing limit. -/ instance (F : J ⥤ CommSemiRing) : creates_limit F (forget₂ CommSemiRing SemiRing.{u}) := creates_limit_of_reflects_iso (λ c' t, { lifted_cone := { X := CommSemiRing.of (types.limit_cone (F ⋙ forget _)).X, π := { app := SemiRing.limit_π_ring_hom (F ⋙ forget₂ CommSemiRing SemiRing), naturality' := (SemiRing.has_limits.limit_cone (F ⋙ forget₂ _ _)).π.naturality, } }, valid_lift := is_limit.unique_up_to_iso (SemiRing.has_limits.limit_cone_is_limit _) t, makes_limit := is_limit.of_faithful (forget₂ CommSemiRing SemiRing.{u}) (SemiRing.has_limits.limit_cone_is_limit _) (λ s, _) (λ s, rfl) }) /-- A choice of limit cone for a functor into `CommSemiRing`. (Generally, you'll just want to use `limit F`.) -/ def limit_cone (F : J ⥤ CommSemiRing) : cone F := lift_limit (limit.is_limit (F ⋙ (forget₂ CommSemiRing SemiRing.{u}))) /-- The chosen cone is a limit cone. (Generally, you'll just want to use `limit.cone F`.) -/ def limit_cone_is_limit (F : J ⥤ CommSemiRing) : is_limit (limit_cone F) := lifted_limit_is_limit _ /-- The category of rings has all limits. -/ @[irreducible] instance has_limits : has_limits CommSemiRing.{u} := { has_limits_of_shape := λ J 𝒥, by exactI { has_limit := λ F, has_limit_of_created F (forget₂ CommSemiRing SemiRing.{u}) } } /-- The forgetful functor from rings to semirings preserves all limits. -/ instance forget₂_SemiRing_preserves_limits : preserves_limits (forget₂ CommSemiRing SemiRing) := { preserves_limits_of_shape := λ J 𝒥, { preserves_limit := λ F, by apply_instance } } /-- The forgetful functor from rings to types preserves all limits. (That is, the underlying types could have been computed instead as limits in the category of types.) -/ instance forget_preserves_limits : preserves_limits (forget CommSemiRing) := { preserves_limits_of_shape := λ J 𝒥, by exactI { preserves_limit := λ F, limits.comp_preserves_limit (forget₂ CommSemiRing SemiRing) (forget SemiRing) } } end CommSemiRing namespace Ring variables {J : Type u} [small_category J] instance ring_obj (F : J ⥤ Ring) (j) : ring ((F ⋙ forget Ring).obj j) := by { change ring (F.obj j), apply_instance } /-- The flat sections of a functor into `Ring` form a subring of all sections. -/ def sections_subring (F : J ⥤ Ring) : subring (Π j, F.obj j) := { carrier := (F ⋙ forget Ring).sections, .. AddGroup.sections_add_subgroup (F ⋙ forget₂ Ring AddCommGroup ⋙ forget₂ AddCommGroup AddGroup), .. SemiRing.sections_subsemiring (F ⋙ forget₂ Ring SemiRing) } instance limit_ring (F : J ⥤ Ring) : ring (types.limit_cone (F ⋙ forget Ring.{u})).X := (sections_subring F).to_ring /-- We show that the forgetful functor `CommRing ⥤ Ring` creates limits. All we need to do is notice that the limit point has a `ring` instance available, and then reuse the existing limit. -/ instance (F : J ⥤ Ring) : creates_limit F (forget₂ Ring SemiRing.{u}) := creates_limit_of_reflects_iso (λ c' t, { lifted_cone := { X := Ring.of (types.limit_cone (F ⋙ forget _)).X, π := { app := SemiRing.limit_π_ring_hom (F ⋙ forget₂ Ring SemiRing), naturality' := (SemiRing.has_limits.limit_cone (F ⋙ forget₂ _ _)).π.naturality, } }, valid_lift := is_limit.unique_up_to_iso (SemiRing.has_limits.limit_cone_is_limit _) t, makes_limit := is_limit.of_faithful (forget₂ Ring SemiRing.{u}) (SemiRing.has_limits.limit_cone_is_limit _) (λ s, _) (λ s, rfl) }) /-- A choice of limit cone for a functor into `Ring`. (Generally, you'll just want to use `limit F`.) -/ def limit_cone (F : J ⥤ Ring) : cone F := lift_limit (limit.is_limit (F ⋙ (forget₂ Ring SemiRing.{u}))) /-- The chosen cone is a limit cone. (Generally, you'll just want to use `limit.cone F`.) -/ def limit_cone_is_limit (F : J ⥤ Ring) : is_limit (limit_cone F) := lifted_limit_is_limit _ /-- The category of rings has all limits. -/ @[irreducible] instance has_limits : has_limits Ring := { has_limits_of_shape := λ J 𝒥, by exactI { has_limit := λ F, has_limit_of_created F (forget₂ Ring SemiRing) } } /-- The forgetful functor from rings to semirings preserves all limits. -/ instance forget₂_SemiRing_preserves_limits : preserves_limits (forget₂ Ring SemiRing) := { preserves_limits_of_shape := λ J 𝒥, { preserves_limit := λ F, by apply_instance } } /-- An auxiliary declaration to speed up typechecking. -/ def forget₂_AddCommGroup_preserves_limits_aux (F : J ⥤ Ring) : is_limit ((forget₂ Ring AddCommGroup).map_cone (limit_cone F)) := AddCommGroup.limit_cone_is_limit (F ⋙ forget₂ Ring AddCommGroup) /-- The forgetful functor from rings to additive commutative groups preserves all limits. -/ instance forget₂_AddCommGroup_preserves_limits : preserves_limits (forget₂ Ring AddCommGroup) := { preserves_limits_of_shape := λ J 𝒥, by exactI { preserves_limit := λ F, preserves_limit_of_preserves_limit_cone (limit_cone_is_limit F) (forget₂_AddCommGroup_preserves_limits_aux F) } } /-- The forgetful functor from rings to types preserves all limits. (That is, the underlying types could have been computed instead as limits in the category of types.) -/ instance forget_preserves_limits : preserves_limits (forget Ring) := { preserves_limits_of_shape := λ J 𝒥, by exactI { preserves_limit := λ F, limits.comp_preserves_limit (forget₂ Ring SemiRing) (forget SemiRing) } } end Ring namespace CommRing variables {J : Type u} [small_category J] instance comm_ring_obj (F : J ⥤ CommRing) (j) : comm_ring ((F ⋙ forget CommRing).obj j) := by { change comm_ring (F.obj j), apply_instance } instance limit_comm_ring (F : J ⥤ CommRing) : comm_ring (types.limit_cone (F ⋙ forget CommRing.{u})).X := @subring.to_comm_ring (Π j, F.obj j) _ (Ring.sections_subring (F ⋙ forget₂ CommRing Ring.{u})) /-- We show that the forgetful functor `CommRing ⥤ Ring` creates limits. All we need to do is notice that the limit point has a `comm_ring` instance available, and then reuse the existing limit. -/ instance (F : J ⥤ CommRing) : creates_limit F (forget₂ CommRing Ring.{u}) := /- A terse solution here would be ``` creates_limit_of_fully_faithful_of_iso (CommRing.of (limit (F ⋙ forget _))) (iso.refl _) ``` but it seems this would introduce additional identity morphisms in `limit.π`. -/ creates_limit_of_reflects_iso (λ c' t, { lifted_cone := { X := CommRing.of (types.limit_cone (F ⋙ forget _)).X, π := { app := SemiRing.limit_π_ring_hom (F ⋙ forget₂ CommRing Ring.{u} ⋙ forget₂ Ring SemiRing), naturality' := (SemiRing.has_limits.limit_cone (F ⋙ forget₂ _ _ ⋙ forget₂ _ _)).π.naturality } }, valid_lift := is_limit.unique_up_to_iso (Ring.limit_cone_is_limit _) t, makes_limit := is_limit.of_faithful (forget₂ CommRing Ring.{u}) (Ring.limit_cone_is_limit _) (λ s, _) (λ s, rfl) }) /-- A choice of limit cone for a functor into `CommRing`. (Generally, you'll just want to use `limit F`.) -/ def limit_cone (F : J ⥤ CommRing) : cone F := lift_limit (limit.is_limit (F ⋙ (forget₂ CommRing Ring.{u}))) /-- The chosen cone is a limit cone. (Generally, you'll just want to use `limit.cone F`.) -/ def limit_cone_is_limit (F : J ⥤ CommRing) : is_limit (limit_cone F) := lifted_limit_is_limit _ /-- The category of commutative rings has all limits. -/ @[irreducible] instance has_limits : has_limits CommRing.{u} := { has_limits_of_shape := λ J 𝒥, by exactI { has_limit := λ F, has_limit_of_created F (forget₂ CommRing Ring.{u}) } } /-- The forgetful functor from commutative rings to rings preserves all limits. (That is, the underlying rings could have been computed instead as limits in the category of rings.) -/ instance forget₂_Ring_preserves_limits : preserves_limits (forget₂ CommRing Ring) := { preserves_limits_of_shape := λ J 𝒥, { preserves_limit := λ F, by apply_instance } } /-- An auxiliary declaration to speed up typechecking. -/ def forget₂_CommSemiRing_preserves_limits_aux (F : J ⥤ CommRing) : is_limit ((forget₂ CommRing CommSemiRing).map_cone (limit_cone F)) := CommSemiRing.limit_cone_is_limit (F ⋙ forget₂ CommRing CommSemiRing) /-- The forgetful functor from commutative rings to commutative semirings preserves all limits. (That is, the underlying commutative semirings could have been computed instead as limits in the category of commutative semirings.) -/ instance forget₂_CommSemiRing_preserves_limits : preserves_limits (forget₂ CommRing CommSemiRing) := { preserves_limits_of_shape := λ J 𝒥, by exactI { preserves_limit := λ F, preserves_limit_of_preserves_limit_cone (limit_cone_is_limit F) (forget₂_CommSemiRing_preserves_limits_aux F) } } /-- The forgetful functor from commutative rings to types preserves all limits. (That is, the underlying types could have been computed instead as limits in the category of types.) -/ instance forget_preserves_limits : preserves_limits (forget CommRing) := { preserves_limits_of_shape := λ J 𝒥, by exactI { preserves_limit := λ F, limits.comp_preserves_limit (forget₂ CommRing Ring) (forget Ring) } } end CommRing
0bc2455fed7317b84746a6d155652bc343a731ab
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/nat/cast/basic.lean
1f06d0878e807d5c9351db06a8e5462a7cacde79
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
9,455
lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import algebra.char_zero.defs import algebra.group_with_zero.commute import algebra.hom.ring import algebra.order.group.abs import algebra.ring.commute import data.nat.order.basic import algebra.group.opposite /-! # Cast of natural numbers (additional theorems) > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file proves additional properties about the *canonical* homomorphism from the natural numbers into an additive monoid with a one (`nat.cast`). ## Main declarations * `cast_add_monoid_hom`: `cast` bundled as an `add_monoid_hom`. * `cast_ring_hom`: `cast` bundled as a `ring_hom`. -/ variables {α β : Type*} namespace nat /-- `coe : ℕ → α` as an `add_monoid_hom`. -/ def cast_add_monoid_hom (α : Type*) [add_monoid_with_one α] : ℕ →+ α := { to_fun := coe, map_add' := cast_add, map_zero' := cast_zero } @[simp] lemma coe_cast_add_monoid_hom [add_monoid_with_one α] : (cast_add_monoid_hom α : ℕ → α) = coe := rfl @[simp, norm_cast] theorem cast_mul [non_assoc_semiring α] (m n : ℕ) : ((m * n : ℕ) : α) = m * n := by induction n; simp [mul_succ, mul_add, *] /-- `coe : ℕ → α` as a `ring_hom` -/ def cast_ring_hom (α : Type*) [non_assoc_semiring α] : ℕ →+* α := { to_fun := coe, map_one' := cast_one, map_mul' := cast_mul, .. cast_add_monoid_hom α } @[simp] lemma coe_cast_ring_hom [non_assoc_semiring α] : (cast_ring_hom α : ℕ → α) = coe := rfl lemma cast_commute [non_assoc_semiring α] (n : ℕ) (x : α) : commute ↑n x := nat.rec_on n (by rw [cast_zero]; exact commute.zero_left x) $ λ n ihn, by rw [cast_succ]; exact ihn.add_left (commute.one_left x) lemma cast_comm [non_assoc_semiring α] (n : ℕ) (x : α) : (n : α) * x = x * n := (cast_commute n x).eq lemma commute_cast [non_assoc_semiring α] (x : α) (n : ℕ) : commute x n := (n.cast_commute x).symm section ordered_semiring variables [ordered_semiring α] @[mono] theorem mono_cast : monotone (coe : ℕ → α) := monotone_nat_of_le_succ $ λ n, by rw [nat.cast_succ]; exact le_add_of_nonneg_right zero_le_one @[simp] theorem cast_nonneg (n : ℕ) : 0 ≤ (n : α) := @nat.cast_zero α _ ▸ mono_cast (nat.zero_le n) section nontrivial variable [nontrivial α] lemma cast_add_one_pos (n : ℕ) : 0 < (n : α) + 1 := zero_lt_one.trans_le $ le_add_of_nonneg_left n.cast_nonneg @[simp] lemma cast_pos {n : ℕ} : (0 : α) < n ↔ 0 < n := by cases n; simp [cast_add_one_pos] end nontrivial variables [char_zero α] {m n : ℕ} lemma strict_mono_cast : strict_mono (coe : ℕ → α) := mono_cast.strict_mono_of_injective cast_injective /-- `coe : ℕ → α` as an `order_embedding` -/ @[simps { fully_applied := ff }] def cast_order_embedding : ℕ ↪o α := order_embedding.of_strict_mono coe nat.strict_mono_cast @[simp, norm_cast] lemma cast_le : (m : α) ≤ n ↔ m ≤ n := strict_mono_cast.le_iff_le @[simp, norm_cast, mono] lemma cast_lt : (m : α) < n ↔ m < n := strict_mono_cast.lt_iff_lt @[simp, norm_cast] lemma one_lt_cast : 1 < (n : α) ↔ 1 < n := by rw [←cast_one, cast_lt] @[simp, norm_cast] lemma one_le_cast : 1 ≤ (n : α) ↔ 1 ≤ n := by rw [←cast_one, cast_le] @[simp, norm_cast] lemma cast_lt_one : (n : α) < 1 ↔ n = 0 := by rw [←cast_one, cast_lt, lt_succ_iff, ←bot_eq_zero, le_bot_iff] @[simp, norm_cast] lemma cast_le_one : (n : α) ≤ 1 ↔ n ≤ 1 := by rw [←cast_one, cast_le] end ordered_semiring /-- A version of `nat.cast_sub` that works for `ℝ≥0` and `ℚ≥0`. Note that this proof doesn't work for `ℕ∞` and `ℝ≥0∞`, so we use type-specific lemmas for these types. -/ @[simp, norm_cast] lemma cast_tsub [canonically_ordered_comm_semiring α] [has_sub α] [has_ordered_sub α] [contravariant_class α α (+) (≤)] (m n : ℕ) : ↑(m - n) = (m - n : α) := begin cases le_total m n with h h, { rw [tsub_eq_zero_of_le h, cast_zero, tsub_eq_zero_of_le], exact mono_cast h }, { rcases le_iff_exists_add'.mp h with ⟨m, rfl⟩, rw [add_tsub_cancel_right, cast_add, add_tsub_cancel_right] } end @[simp, norm_cast] theorem cast_min [linear_ordered_semiring α] {a b : ℕ} : (↑(min a b) : α) = min a b := (@mono_cast α _).map_min @[simp, norm_cast] theorem cast_max [linear_ordered_semiring α] {a b : ℕ} : (↑(max a b) : α) = max a b := (@mono_cast α _).map_max @[simp, norm_cast] theorem abs_cast [linear_ordered_ring α] (a : ℕ) : |(a : α)| = a := abs_of_nonneg (cast_nonneg a) lemma coe_nat_dvd [semiring α] {m n : ℕ} (h : m ∣ n) : (m : α) ∣ (n : α) := map_dvd (nat.cast_ring_hom α) h alias coe_nat_dvd ← _root_.has_dvd.dvd.nat_cast end nat section add_monoid_hom_class variables {A B F : Type*} [add_monoid_with_one B] lemma ext_nat' [add_monoid A] [add_monoid_hom_class F ℕ A] (f g : F) (h : f 1 = g 1) : f = g := fun_like.ext f g $ begin apply nat.rec, { simp only [nat.nat_zero_eq_zero, map_zero] }, simp [nat.succ_eq_add_one, h] {contextual := tt} end @[ext] lemma add_monoid_hom.ext_nat [add_monoid A] : ∀ {f g : ℕ →+ A}, ∀ h : f 1 = g 1, f = g := ext_nat' variable [add_monoid_with_one A] -- these versions are primed so that the `ring_hom_class` versions aren't lemma eq_nat_cast' [add_monoid_hom_class F ℕ A] (f : F) (h1 : f 1 = 1) : ∀ n : ℕ, f n = n | 0 := by simp | (n+1) := by rw [map_add, h1, eq_nat_cast' n, nat.cast_add_one] lemma map_nat_cast' {A} [add_monoid_with_one A] [add_monoid_hom_class F A B] (f : F) (h : f 1 = 1) : ∀ (n : ℕ), f n = n | 0 := by simp | (n+1) := by rw [nat.cast_add, map_add, nat.cast_add, map_nat_cast', nat.cast_one, h, nat.cast_one] end add_monoid_hom_class section monoid_with_zero_hom_class variables {A F : Type*} [mul_zero_one_class A] /-- If two `monoid_with_zero_hom`s agree on the positive naturals they are equal. -/ theorem ext_nat'' [monoid_with_zero_hom_class F ℕ A] (f g : F) (h_pos : ∀ {n : ℕ}, 0 < n → f n = g n) : f = g := begin apply fun_like.ext, rintro (_|n), { simp }, exact h_pos n.succ_pos end @[ext] theorem monoid_with_zero_hom.ext_nat : ∀ {f g : ℕ →*₀ A}, (∀ {n : ℕ}, 0 < n → f n = g n) → f = g := ext_nat'' end monoid_with_zero_hom_class section ring_hom_class variables {R S F : Type*} [non_assoc_semiring R] [non_assoc_semiring S] @[simp] lemma eq_nat_cast [ring_hom_class F ℕ R] (f : F) : ∀ n, f n = n := eq_nat_cast' f $ map_one f @[simp] lemma map_nat_cast [ring_hom_class F R S] (f : F) : ∀ n : ℕ, f (n : R) = n := map_nat_cast' f $ map_one f lemma ext_nat [ring_hom_class F ℕ R] (f g : F) : f = g := ext_nat' f g $ by simp only [map_one] lemma ne_zero.nat_of_injective {n : ℕ} [h : ne_zero (n : R)] [ring_hom_class F R S] {f : F} (hf : function.injective f) : ne_zero (n : S) := ⟨λ h, (ne_zero.nat_cast_ne n R) $ hf $ by simpa only [map_nat_cast, map_zero]⟩ lemma ne_zero.nat_of_ne_zero {R S} [semiring R] [semiring S] {F} [ring_hom_class F R S] (f : F) {n : ℕ} [hn : ne_zero (n : S)] : ne_zero (n : R) := by { apply ne_zero.of_map f, simp only [map_nat_cast, hn] } end ring_hom_class namespace ring_hom /-- This is primed to match `eq_int_cast'`. -/ lemma eq_nat_cast' {R} [non_assoc_semiring R] (f : ℕ →+* R) : f = nat.cast_ring_hom R := ring_hom.ext $ eq_nat_cast f end ring_hom @[simp, norm_cast] theorem nat.cast_id (n : ℕ) : ↑n = n := rfl @[simp] lemma nat.cast_ring_hom_nat : nat.cast_ring_hom ℕ = ring_hom.id ℕ := rfl -- I don't think `ring_hom_class` is good here, because of the `subsingleton` TC slowness instance nat.unique_ring_hom {R : Type*} [non_assoc_semiring R] : unique (ℕ →+* R) := { default := nat.cast_ring_hom R, uniq := ring_hom.eq_nat_cast' } namespace pi variables {π : α → Type*} [Π a, has_nat_cast (π a)] instance : has_nat_cast (Π a, π a) := by refine_struct { .. }; tactic.pi_instance_derive_field lemma nat_apply (n : ℕ) (a : α) : (n : Π a, π a) a = n := rfl @[simp] lemma coe_nat (n : ℕ) : (n : Π a, π a) = λ _, n := rfl end pi lemma sum.elim_nat_cast_nat_cast {α β γ : Type*} [has_nat_cast γ] (n : ℕ) : sum.elim (n : α → γ) (n : β → γ) = n := @sum.elim_lam_const_lam_const α β γ n namespace pi variables {π : α → Type*} [Π a, add_monoid_with_one (π a)] instance : add_monoid_with_one (Π a, π a) := by refine_struct { .. }; tactic.pi_instance_derive_field end pi /-! ### Order dual -/ open order_dual instance [h : has_nat_cast α] : has_nat_cast αᵒᵈ := h instance [h : add_monoid_with_one α] : add_monoid_with_one αᵒᵈ := h instance [h : add_comm_monoid_with_one α] : add_comm_monoid_with_one αᵒᵈ := h @[simp] lemma to_dual_nat_cast [has_nat_cast α] (n : ℕ) : to_dual (n : α) = n := rfl @[simp] lemma of_dual_nat_cast [has_nat_cast α] (n : ℕ) : (of_dual n : α) = n := rfl /-! ### Lexicographic order -/ instance [h : has_nat_cast α] : has_nat_cast (lex α) := h instance [h : add_monoid_with_one α] : add_monoid_with_one (lex α) := h instance [h : add_comm_monoid_with_one α] : add_comm_monoid_with_one (lex α) := h @[simp] lemma to_lex_nat_cast [has_nat_cast α] (n : ℕ) : to_lex (n : α) = n := rfl @[simp] lemma of_lex_nat_cast [has_nat_cast α] (n : ℕ) : (of_lex n : α) = n := rfl
e5ef847d5231419f268b8b0199255e626c979083
471bedbd023d35c9d078c2f936dd577ace7f5813
/library/init/meta/mk_has_reflect_instance.lean
62bda6ae71a4ee405e4346bc9af35eda9481445b
[ "Apache-2.0" ]
permissive
lambdaxymox/lean
e06f0fa503666df827edd9867d7f49ca017aae64
fc13c8c72a15dab71a2c2b31410c2cadc3526bd7
refs/heads/master
1,666,785,407,985
1,666,153,673,000
1,666,153,673,000
310,165,986
0
0
Apache-2.0
1,604,542,096,000
1,604,542,095,000
null
UTF-8
Lean
false
false
3,775
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich Helper tactic for constructing a has_reflect instance. -/ prelude import init.meta.rec_util namespace tactic open expr environment list /- Retrieve the name of the type we are building a has_reflect instance for. -/ private meta def get_has_reflect_type_name : tactic name := do { (app (const n ls) t) ← target, when (n ≠ `has_reflect) failed, (const I ls) ← return (get_app_fn t), return I } <|> fail "mk_has_reflect_instance tactic failed, target type is expected to be of the form (has_reflect ...)" /- Try to synthesize constructor argument using type class resolution -/ private meta def mk_has_reflect_instance_for (a : expr) : tactic expr := do t ← infer_type a, do { m ← mk_mapp `reflected [none, some a], inst ← mk_instance m <|> do { f ← pp t, fail (to_fmt "mk_has_reflect_instance failed, failed to generate instance for" ++ format.nest 2 (format.line ++ f)) }, mk_app `reflect [a, inst] } /- Synthesize (recursive) instances of `reflected` for all fields -/ private meta def mk_reflect : name → name → list name → nat → tactic (list expr) | I_name F_name [] num_rec := return [] | I_name F_name (fname::fnames) num_rec := do field ← get_local fname, rec ← is_type_app_of field I_name, quote ← if rec then mk_brec_on_rec_value F_name num_rec else mk_has_reflect_instance_for field, quotes ← mk_reflect I_name F_name fnames (if rec then num_rec + 1 else num_rec), return (quote :: quotes) /- Solve the subgoal for constructor `F_name` -/ private meta def has_reflect_case (I_name F_name : name) (field_names : list name) : tactic unit := do field_quotes ← mk_reflect I_name F_name field_names 0, -- fn should be of the form `F_name ps fs`, where ps are the inductive parameter arguments, -- and `fs.length = field_names.length` `(reflected _ %%fn) ← target, -- `reflected _ (F_name ps)` should be synthesizable directly, using instances from the context let fn := field_names.foldl (λ fn _, expr.app_fn fn) fn, quote ← mk_mapp `reflected [none, some fn] >>= mk_instance, -- now extend to an instance of `reflected _ (F_name ps fs)` quote ← field_quotes.mfoldl (λ quote fquote, to_expr ``(reflected.subst %%quote %%fquote)) quote, exact quote private meta def for_each_has_reflect_goal : name → name → list (list name) → tactic unit | I_name F_name [] := done <|> fail "mk_has_reflect_instance failed, unexpected number of cases" | I_name F_name (ns::nss) := do solve1 (has_reflect_case I_name F_name ns), for_each_has_reflect_goal I_name F_name nss /-- Solves a goal of the form `has_reflect α` where α is an inductive type. Needs to synthesize a `reflected` instance for each inductive parameter type of α and for each constructor parameter of α. -/ meta def mk_has_reflect_instance : tactic unit := do I_name ← get_has_reflect_type_name, env ← get_env, v_name : name ← return `_v, F_name : name ← return `_F, guard (env.inductive_num_indices I_name = 0) <|> fail "mk_has_reflect_instance failed, indexed families are currently not supported", -- Use brec_on if type is recursive. -- We store the functional in the variable F. if is_recursive env I_name then intro `_v >>= (λ x, induction x [v_name, F_name] (some $ I_name <.> "brec_on") >> return ()) else intro v_name >> return (), arg_names : list (list name) ← mk_constructors_arg_names I_name `_p, get_local v_name >>= λ v, cases v (join arg_names), for_each_has_reflect_goal I_name F_name arg_names end tactic
c338beac8be39384192ada43dd9b2d066c41cb1c
42610cc2e5db9c90269470365e6056df0122eaa0
/library/data/finset/extra_finset.lean
9ff832eb8ba2b9b0c2a4a19f5807bcf67b214b20
[ "Apache-2.0" ]
permissive
tomsib2001/lean
2ab59bfaebd24a62109f800dcf4a7139ebd73858
eb639a7d53fb40175bea5c8da86b51d14bb91f76
refs/heads/master
1,586,128,387,740
1,468,968,950,000
1,468,968,950,000
61,027,234
0
0
null
1,465,813,585,000
1,465,813,585,000
null
UTF-8
Lean
false
false
10,571
lean
import data.fintype.basic data.nat data.list.perm data.finset algebra.binary algebra.ordered_ring open nat quot subtype binary function eq.ops finset section set_operations lemma subset_inter {T : Type} [Hdeceq : decidable_eq T] {A B C : finset T} (sAB :A ⊆ B) (sAC : A ⊆ C) : A ⊆ B ∩ C := begin apply subset_of_forall, intro x HxA, apply mem_inter, apply (mem_of_subset_of_mem sAB), exact HxA, apply (mem_of_subset_of_mem sAC), exact HxA, end lemma finset_inter_subset_left {T : Type} [Hdeceq : decidable_eq T] {A B : finset T} : A ∩ B ⊆ A := begin apply subset_of_forall, intros x HxAintB, apply (finset.mem_of_mem_inter_left HxAintB), end lemma finset_inter_subset_right {T : Type} [Hdeceq : decidable_eq T] {A B : finset T} : A ∩ B ⊆ B := begin apply subset_of_forall, intros x HxAintB, apply (finset.mem_of_mem_inter_right HxAintB), end lemma subset_compl {T : Type} [HfT : fintype T] [Hdeceq : decidable_eq T] {A B : finset T} (sAB : A ⊆ B) : finset.compl B ⊆ finset.compl A := subset_of_forall (take x HxB, begin apply mem_compl, have HnB: x ∉ B, from (not_mem_of_mem_compl HxB), intro HxA, apply HnB, apply mem_of_subset_of_mem sAB HxA, end) lemma missing_compl_compl {T : Type} [HfT : fintype T] [Hdeceq : decidable_eq T] (A : finset T) : finset.compl (finset.compl A) = A := begin apply eq_of_subset_of_subset, apply subset_of_forall, intro x HxnnA, have nnxA : x ∉ finset.compl A, from not_mem_of_mem_compl HxnnA, rewrite (not_iff_not_of_iff (mem_compl_iff A x)) at nnxA, exact (not_not_elim nnxA), apply subset_of_forall, intro x HxA, apply mem_compl, rewrite (not_iff_not_of_iff (mem_compl_iff A x)), apply not_not_intro, exact HxA end lemma eq_is_eq_compl {T : Type} [HfT : fintype T] [Hdeceq : decidable_eq T] {A B : finset T} : (A = B) ↔ (- A = - B) := begin apply iff.intro, intro HAB, rewrite HAB, intro HcAcB, rewrite -missing_compl_compl, rewrite HcAcB, apply missing_compl_compl end lemma image_id {T : Type} [HfT : fintype T] [Hdeceq : decidable_eq T] {A : finset T} : id ' A = A := ext (take a, iff.intro (suppose Ha : a ∈ id ' A, begin rewrite mem_image_iff at Ha, cases Ha with x Hx, cases Hx with HxA Hxa, rewrite ↑id at Hxa, exact (eq.subst Hxa HxA) end) (suppose a ∈ A, begin rewrite mem_image_iff, apply (exists.intro a), exact and.intro this rfl end)) -- less sure that the next two are really necessary lemma image_singleton {A B : Type} [hA: decidable_eq A] [hB: decidable_eq B] (f : A → B) (a : A) : image f (insert a empty) = insert (f a) empty := begin rewrite image_insert end lemma singleton_subset_iff {A : Type} [hA: decidable_eq A] (a : A) (S : finset A) : '{a} ⊆ S ↔ a ∈ S := iff.intro (take H, mem_of_subset_of_mem H (mem_singleton a)) (take HaS, begin apply subset_of_forall, intro x Hx, rewrite mem_singleton_iff at Hx, rewrite Hx, exact HaS end) lemma insert_empty {A : Type} [hAdec : decidable_eq A] (a : A) (b : A) : finset.insert a finset.empty = insert b empty → a = b := assume Heq_set, have Hab : mem a (insert b empty), from (eq.subst Heq_set (mem_insert a empty)), or.elim (eq.subst (mem_insert_eq a b empty) Hab) (take H, H) begin intro Habs, exact false.elim (not_mem_empty a Habs) end lemma subset_sep_iff {A : Type} [fintype A] [decidable_eq A] (p1 p2 : A → Prop) [decidable_pred (λ x, p1 x)] [decidable_pred (λ x, p2 x)] : {x ∈ univ | p1 x} ⊆ {x ∈ univ | p2 x} ↔ ∀ (x : A), p1 x → p2 x := begin apply iff.intro, intro Hp1p2, intro x Hp1x, have Hsepp1x : x ∈ sep p1 univ, from mem_sep_of_mem (mem_univ _) Hp1x, have Hp2x : x ∈ sep p2 univ, from mem_of_subset_of_mem Hp1p2 Hsepp1x, exact (of_mem_sep Hp2x), intro Hp1p2, have H : ∀ (x : A), x ∈ {x ∈ univ | p1 x} → x ∈ { x ∈ univ | p2 x}, from take x Hx, begin apply mem_sep_of_mem (mem_univ _), apply Hp1p2 x (of_mem_sep Hx) end, apply subset_of_forall H end end set_operations section finset_of_fintype definition fintype_of_finset [instance] {T : Type} [HfT : fintype T] : fintype (finset T) := fintype.mk sorry sorry sorry end finset_of_fintype section minmax variables [T : Type] [HfT : fintype T] [Hdeceq : decidable_eq T] include Hdeceq HfT definition minSet [reducible] (P : finset T → Prop) (A : finset T) := ∀ (B : finset T), B ⊆ A → (P B ↔ B = A) definition decidable_minset [instance] (P : finset T → Prop) [HdecP : ∀ B, decidable (P B)] (A : finset T) : decidable (minSet P A) := _ lemma minsetp (P : finset T → Prop) (A : finset T) (HminSet : minSet P A) : P A := iff.elim_right (HminSet A (subset.refl A)) (!rfl) lemma minsetinf (P : finset T → Prop) (A B : finset T) (HminSet : minSet P A) (HPB : P B) (Hsubset : subset B A) : B = A := iff.elim_left (HminSet B Hsubset) HPB lemma in_empty_empty (A : finset T) : subset A ∅ → A = ∅ := λ H, iff.elim_left (subset_empty_iff A) H lemma minSet_empty (P : finset T → Prop) (Hempty : P ∅) : minSet P ∅ := take B HBinEmpty, have HBempty : B = ∅, from in_empty_empty B HBinEmpty, iff.intro (assume HPB, HBempty) (assume Heq : B = ∅, eq.substr Heq Hempty) lemma helper_lemma (P : finset T → Prop) : (exists U, subset U ∅ ∧ P U) → exists U, minSet P U ∧ subset U ∅ := assume (H : (exists U, subset U ∅ ∧ P U)), obtain (U : finset T) (HU : subset U ∅ ∧ P U), from H, have Hempty : U = ∅, from iff.elim_left (subset_empty_iff U) (and.left HU), have HPU : P U, from (and.right HU), exists.intro U (and.intro (eq.substr Hempty (minSet_empty P (eq.subst Hempty HPU))) (and.left HU)) definition smallest (P : nat → Prop) (HdecP : forall (n : nat), decidable (P n)) (n : nat) : P n → exists (m : nat), m ≤ n ∧ P m ∧ ∀ k, P k → m ≤ k := have Hgeneral : ∀ i, i ≤ n → P i → exists (m : nat), m ≤ i ∧ P m ∧ ∀ k, P k → m ≤ k, from nat.rec_on n begin intro i li0 HPi, apply (exists.intro 0), rewrite (eq_zero_of_le_zero li0) at *, apply and.intro, apply nat.le_refl, apply (and.intro HPi), intro k Hk, apply zero_le end begin intro a HR, have Hcases : (exists j, j ≤ a ∧ P j) ∨ ¬ (exists j, j ≤ a ∧ P j), from (decidable.em (exists j, j ≤ a ∧ P j)), cases Hcases with yes no, cases yes with j Hj, cases Hj with lja Pj, intro i Hi HPi, cases (le_or_eq_succ_of_le_succ Hi) with lia iSa, apply (HR i lia HPi), cases (le_or_gt i j) with lij ltji, apply (HR i (nat.le_trans lij lja) HPi), cases (HR j lja Pj) with m Hm, apply (exists.intro m), apply and.intro, apply (nat.le_of_lt (lt_of_le_of_lt (and.left Hm) ltji)), exact (and.right Hm), intro i liSa HPi, cases (le_or_eq_succ_of_le_succ liSa) with lia iSa, exfalso, apply no, apply exists.intro i (and.intro lia HPi), apply exists.intro i, apply and.intro, apply nat.le_refl, apply and.intro, exact HPi, intro k Pk, cases nat.lt_or_ge k i with ltki geki, exfalso, apply no, apply exists.intro k, apply and.intro, apply le_of_lt_succ, apply lt_of_lt_of_le ltki liSa, exact Pk, exact geki end, Hgeneral n !le.refl lemma minSet_exists (P : finset T → Prop) (HdecP : forall (A : finset T), decidable (P A)) (C : finset T) (HPC : P C) : exists A, minSet P A ∧ subset A C := let Pnat := λ (n :nat), exists (B : finset T), card B = n ∧ P B ∧ B ⊆ C in have HPnatC : Pnat (card C), from exists.intro C (and.intro rfl (and.intro HPC (subset.refl C))), have Hsmallest : exists (m : nat), m ≤ (card C) ∧ Pnat m ∧ ∀ k, Pnat k → m ≤ k, from @smallest T _ _ Pnat (λ n, decidable_exists_finite) (card C) HPnatC, obtain m Hm, from Hsmallest, begin cases Hm with Hmcard Hm2, cases Hm2 with HPnatm Hminm, cases HPnatm with B HB, apply (exists.intro B), apply and.intro, intro K, intro HsKB, apply iff.intro, intro HPK, apply eq_of_card_eq_of_subset, have HcardKB : card K ≤ card B, from card_le_card_of_subset HsKB , have cardBK : card B ≤ card K, from begin rewrite (and.left HB), apply ((Hminm (card K))), apply (exists.intro K), apply and.intro, apply rfl, apply and.intro, exact HPK, apply (subset.trans HsKB (and.right (and.right HB))), end, apply (eq_of_le_of_ge HcardKB cardBK), exact HsKB, intro Heq, rewrite Heq, exact (and.left(and.right HB)), exact and.right (and.right HB) end definition maxSet (P : finset T → Prop) (A : finset T) := minSet (λ B, P (compl B)) (compl A) definition decidable_maxset [instance] (P : finset T → Prop) [HdecP : ∀ B, decidable (P B)] (A : finset T) : decidable (maxSet P A) := decidable_minset _ _ lemma maxsetp {P : finset T → Prop} {A : finset T} : maxSet P A → P A := assume H : minSet (λ B, P (finset.compl B)) (finset.compl A), have H1 : (λ B, P (-B)) (-A), from minsetp (λ B, P (finset.compl B)) (finset.compl A) H, eq.subst (missing_compl_compl A) H1 -- can't find the two lemmas which would make this easy lemma maxsetsup (P : finset T → Prop) (A B : finset T) : maxSet P A → P B → A ⊆ B → B = A := assume (Hmax : maxSet P A) HPB HsAB, have Hsub : - B ⊆ - A, from subset_compl HsAB, have H : _, from minsetinf (λ B, P (- B)) (- A) (- B) Hmax (eq.substr (missing_compl_compl B) HPB) Hsub, begin rewrite -(missing_compl_compl), rewrite H, apply missing_compl_compl end lemma maxSet_exists (P : finset T → Prop) [HdecP : forall A, decidable (P A)](C : finset T) (HPC : P C) : exists A, maxSet P A ∧ subset C A := have H : _, from minSet_exists (λ B, P (compl B)) _ (compl C) (eq.substr (missing_compl_compl C) HPC), obtain A HA, from H, exists.intro (compl A) (and.intro (eq.substr (missing_compl_compl A) (and.left HA)) begin rewrite -missing_compl_compl, apply subset_compl, exact and.right HA end) lemma maxSet_iff {P : finset T → Prop} {A : finset T} : maxSet P A ↔ (∀ B, A ⊆ B → (P B ↔ B = A)) := begin rewrite [↑maxSet,↑minSet], apply iff.intro, intro H1, intro B HB, have scBcA : - B ⊆ - A, from subset_compl HB, have H : P B ↔ - B = - A, from eq.subst !missing_compl_compl (H1 (-B) (scBcA)), rewrite [H,-eq_is_eq_compl], intro H2, intro B HBcA, have sAcB : A ⊆ - B, from eq.subst !missing_compl_compl (subset_compl HBcA), have HcBA : (P (-B) ↔ - B = A), from (H2 (-B) sAcB), rewrite [HcBA,eq_is_eq_compl,missing_compl_compl] end end minmax
7c590947e91acc59f274add79062dd9a70451cf1
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/category_theory/limits/filtered_colimit_commutes_finite_limit.lean
c0694db6dd574f051b6a541fa8dc619c0fb4e124
[ "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
13,459
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.colimit_limit import category_theory.limits.shapes.finite_limits /-! # Filtered colimits commute with finite limits. We show that for a functor `F : J × K ⥤ Type v`, when `J` is finite and `K` is filtered, the universal morphism `colimit_limit_to_limit_colimit F` comparing the colimit (over `K`) of the limits (over `J`) with the limit of the colimits is an isomorphism. (In fact, to prove that it is injective only requires that `J` has finitely many objects.) ## References * Borceux, Handbook of categorical algebra 1, Theorem 2.13.4 * [Stacks: Filtered colimits](https://stacks.math.columbia.edu/tag/002W) -/ universes v u open category_theory open category_theory.category open category_theory.limits.types.filtered_colimit namespace category_theory.limits variables {J K : Type v} [small_category J] [small_category K] variables (F : J × K ⥤ Type v) open category_theory.prod variables [is_filtered K] section /-! Injectivity doesn't need that we have finitely many morphisms in `J`, only that there are finitely many objects. -/ variables [fintype J] /-- This follows this proof from * Borceux, Handbook of categorical algebra 1, Theorem 2.13.4 -/ lemma colimit_limit_to_limit_colimit_injective : function.injective (colimit_limit_to_limit_colimit F) := begin classical, -- Suppose we have two terms `x y` in the colimit (over `K`) of the limits (over `J`), -- and that these have the same image under `colimit_limit_to_limit_colimit F`. intros x y h, -- These elements of the colimit have representatives somewhere: obtain ⟨kx, x, rfl⟩ := types.jointly_surjective' x, obtain ⟨ky, y, rfl⟩ := types.jointly_surjective' y, dsimp at x y, -- Since the images of `x` and `y` are equal in a limit, they are equal componentwise -- (indexed by `j : J`), replace h := λ j, congr_arg (limit.π ((curry.obj F) ⋙ colim) j) h, -- and they are equations in a filtered colimit, -- so for each `j` we have some place `k j` to the right of both `kx` and `ky` simp [colimit_eq_iff] at h, let k := λ j, (h j).some, let f : Π j, kx ⟶ k j := λ j, (h j).some_spec.some, let g : Π j, ky ⟶ k j := λ j, (h j).some_spec.some_spec.some, -- where the images of the components of the representatives become equal: have w : Π j, F.map ((𝟙 j, f j) : (j, kx) ⟶ (j, k j)) (limit.π ((curry.obj (swap K J ⋙ F)).obj kx) j x) = F.map ((𝟙 j, g j) : (j, ky) ⟶ (j, k j)) (limit.π ((curry.obj (swap K J ⋙ F)).obj ky) j y) := λ j, (h j).some_spec.some_spec.some_spec, -- We now use that `K` is filtered, picking some point to the right of all these -- morphisms `f j` and `g j`. let O : finset K := (finset.univ).image k ∪ {kx, ky}, have kxO : kx ∈ O := finset.mem_union.mpr (or.inr (by simp)), have kyO : ky ∈ O := finset.mem_union.mpr (or.inr (by simp)), have kjO : ∀ j, k j ∈ O := λ j, finset.mem_union.mpr (or.inl (by simp)), let H : finset (Σ' (X Y : K) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y) := (finset.univ).image (λ j : J, ⟨kx, k j, kxO, finset.mem_union.mpr (or.inl (by simp)), f j⟩) ∪ (finset.univ).image (λ j : J, ⟨ky, k j, kyO, finset.mem_union.mpr (or.inl (by simp)), g j⟩), obtain ⟨S, T, W⟩ := is_filtered.sup_exists O H, have fH : ∀ j, (⟨kx, k j, kxO, kjO j, f j⟩ : (Σ' (X Y : K) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y)) ∈ H := λ j, (finset.mem_union.mpr (or.inl begin simp only [true_and, finset.mem_univ, eq_self_iff_true, exists_prop_of_true, finset.mem_image, heq_iff_eq], refine ⟨j, rfl, _⟩, simp only [heq_iff_eq], exact ⟨rfl, rfl, rfl⟩, end)), have gH : ∀ j, (⟨ky, k j, kyO, kjO j, g j⟩ : (Σ' (X Y : K) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y)) ∈ H := λ j, (finset.mem_union.mpr (or.inr begin simp only [true_and, finset.mem_univ, eq_self_iff_true, exists_prop_of_true, finset.mem_image, heq_iff_eq], refine ⟨j, rfl, _⟩, simp only [heq_iff_eq], exact ⟨rfl, rfl, rfl⟩, end)), -- Our goal is now an equation between equivalence classes of representatives of a colimit, -- and so it suffices to show those representative become equal somewhere, in particular at `S`. apply types.colimit_sound' (T kxO) (T kyO), -- We can check if two elements of a limit (in `Type`) are equal by comparing them componentwise. ext, -- Now it's just a calculation using `W` and `w`. simp only [functor.comp_map, limits.types.map_π_apply, curry.obj_map_app, swap_map], rw ←W _ _ (fH j), rw ←W _ _ (gH j), simp [w], end end variables [fin_category J] /-- This follows this proof from * Borceux, Handbook of categorical algebra 1, Theorem 2.13.4 although with different names. -/ lemma colimit_limit_to_limit_colimit_surjective : function.surjective (colimit_limit_to_limit_colimit F) := begin classical, -- We begin with some element `x` in the limit (over J) over the colimits (over K), intro x, -- This consists of some coherent family of elements in the various colimits, -- and so our first task is to pick representatives of these elements. have z := λ j, types.jointly_surjective' (limit.π (curry.obj F ⋙ limits.colim) j x), -- `k : J ⟶ K` records where the representative of the element in the `j`-th element of `x` lives let k : J → K := λ j, (z j).some, -- `y j : F.obj (j, k j)` is the representative let y : Π j, F.obj (j, k j) := λ j, (z j).some_spec.some, -- and we record that these representatives, when mapped back into the relevant colimits, -- are actually the components of `x`. have e : ∀ j, colimit.ι ((curry.obj F).obj j) (k j) (y j) = limit.π (curry.obj F ⋙ limits.colim) j x := λ j, (z j).some_spec.some_spec, clear_value k y, -- A little tidying up of things we no longer need. clear z, -- As a first step, we use that `K` is filtered to pick some point `k' : K` above all the `k j` let k' : K := is_filtered.sup (finset.univ.image k) ∅, -- and name the morphisms as `g j : k j ⟶ k'`. have g : Π j, k j ⟶ k' := λ j, is_filtered.to_sup (finset.univ.image k) ∅ (by simp), clear_value k', -- Recalling that the components of `x`, which are indexed by `j : J`, are "coherent", -- in other words preserved by morphisms in the `J` direction, -- we see that for any morphism `f : j ⟶ j'` in `J`, -- the images of `y j` and `y j'`, when mapped to `F.obj (j', k')` respectively by -- `(f, g j)` and `(𝟙 j', g j')`, both represent the same element in the colimit. have w : ∀ {j j' : J} (f : j ⟶ j'), colimit.ι ((curry.obj F).obj j') k' (F.map ((𝟙 j', g j') : (j', k j') ⟶ (j', k')) (y j')) = colimit.ι ((curry.obj F).obj j') k' (F.map ((f, g j) : (j, k j) ⟶ (j', k')) (y j)), { intros j j' f, have t : (f, g j) = (((f, 𝟙 (k j)) : (j, k j) ⟶ (j', k j)) ≫ (𝟙 j', g j) : (j, k j) ⟶ (j', k')), { simp only [id_comp, comp_id, prod_comp], }, erw [types.colimit_w_apply, t, functor_to_types.map_comp_apply, types.colimit_w_apply, e, ←types.limit_w_apply f, ←e], simp, }, -- Because `K` is filtered, we can restate this as saying that -- for each such `f`, there is some place to the right of `k'` -- where these images of `y j` and `y j'` become equal. simp_rw colimit_eq_iff at w, -- We take a moment to restate `w` more conveniently. let kf : Π {j j'} (f : j ⟶ j'), K := λ _ _ f, (w f).some, let gf : Π {j j'} (f : j ⟶ j'), k' ⟶ kf f := λ _ _ f, (w f).some_spec.some, let hf : Π {j j'} (f : j ⟶ j'), k' ⟶ kf f := λ _ _ f, (w f).some_spec.some_spec.some, have wf : Π {j j'} (f : j ⟶ j'), F.map ((𝟙 j', g j' ≫ gf f) : (j', k j') ⟶ (j', kf f)) (y j') = F.map ((f, g j ≫ hf f) : (j, k j) ⟶ (j', kf f)) (y j) := λ j j' f, begin have q : ((curry.obj F).obj j').map (gf f) (F.map _ (y j')) = ((curry.obj F).obj j').map (hf f) (F.map _ (y j)) := (w f).some_spec.some_spec.some_spec, dsimp at q, simp_rw ←functor_to_types.map_comp_apply at q, convert q; simp only [comp_id], end, clear_value kf gf hf, -- and clean up some things that are no longer needed. clear w, -- We're now ready to use the fact that `K` is filtered a second time, -- picking some place to the right of all of -- the morphisms `gf f : k' ⟶ kh f` and `hf f : k' ⟶ kf f`. -- At this point we're relying on there being only finitely morphisms in `J`. let O := finset.univ.bind (λ j, finset.univ.bind (λ j', finset.univ.image (@kf j j'))) ∪ {k'}, have kfO : ∀ {j j'} (f : j ⟶ j'), kf f ∈ O := λ j j' f, finset.mem_union.mpr (or.inl ( begin rw [finset.mem_bind], refine ⟨j, finset.mem_univ j, _⟩, rw [finset.mem_bind], refine ⟨j', finset.mem_univ j', _⟩, rw [finset.mem_image], refine ⟨f, finset.mem_univ _, _⟩, refl, end)), have k'O : k' ∈ O := finset.mem_union.mpr (or.inr (finset.mem_singleton.mpr rfl)), let H : finset (Σ' (X Y : K) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y) := finset.univ.bind (λ j : J, finset.univ.bind (λ j' : J, finset.univ.bind (λ f : j ⟶ j', {⟨k', kf f, k'O, kfO f, gf f⟩, ⟨k', kf f, k'O, kfO f, hf f⟩}))), obtain ⟨k'', i', s'⟩ := is_filtered.sup_exists O H, -- We then restate this slightly more conveniently, as a family of morphism `i f : kf f ⟶ k''`, -- satisfying `gf f ≫ i f = hf f' ≫ i f'`. let i : Π {j j'} (f : j ⟶ j'), kf f ⟶ k'' := λ j j' f, i' (kfO f), have s : ∀ {j₁ j₂ j₃ j₄} (f : j₁ ⟶ j₂) (f' : j₃ ⟶ j₄), gf f ≫ i f = hf f' ≫ i f' := begin intros, rw [s', s'], swap 2, exact k'O, swap 2, { rw [finset.mem_bind], refine ⟨j₁, finset.mem_univ _, _⟩, rw [finset.mem_bind], refine ⟨j₂, finset.mem_univ _, _⟩, rw [finset.mem_bind], refine ⟨f, finset.mem_univ _, _⟩, simp only [true_or, eq_self_iff_true, and_self, finset.mem_insert, heq_iff_eq], }, { rw [finset.mem_bind], refine ⟨j₃, finset.mem_univ _, _⟩, rw [finset.mem_bind], refine ⟨j₄, finset.mem_univ _, _⟩, rw [finset.mem_bind], refine ⟨f', finset.mem_univ _, _⟩, simp only [eq_self_iff_true, or_true, and_self, finset.mem_insert, finset.mem_singleton, heq_iff_eq], } end, clear_value i, clear s' i' H kfO k'O O, -- We're finally ready to construct the pre-image, and verify it really maps to `x`. fsplit, { -- We construct the pre-image (which, recall is meant to be a point -- in the colimit (over `K`) of the limits (over `J`)) via a representative at `k''`. apply colimit.ι (curry.obj (swap K J ⋙ F) ⋙ limits.lim) k'' _, dsimp, -- This representative is meant to be an element of a limit, -- so we need to construct a family of elements in `F.obj (j, k'')` for varying `j`, -- then show that are coherent with respect to morphisms in the `j` direction. ext, swap, { -- We construct the elements as the images of the `y j`. exact λ j, F.map (⟨𝟙 j, g j ≫ gf (𝟙 j) ≫ i (𝟙 j)⟩ : (j, k j) ⟶ (j, k'')) (y j), }, { -- After which it's just a calculation, using `s` and `wf`, to see they are coherent. dsimp, simp only [←functor_to_types.map_comp_apply, prod_comp, id_comp, comp_id], calc F.map ((f, g j ≫ gf (𝟙 j) ≫ i (𝟙 j)) : (j, k j) ⟶ (j', k'')) (y j) = F.map ((f, g j ≫ hf f ≫ i f) : (j, k j) ⟶ (j', k'')) (y j) : by rw s (𝟙 j) f ... = F.map ((𝟙 j', i f) : (j', kf f) ⟶ (j', k'')) (F.map ((f, g j ≫ hf f) : (j, k j) ⟶ (j', kf f)) (y j)) : by rw [←functor_to_types.map_comp_apply, prod_comp, comp_id, assoc] ... = F.map ((𝟙 j', i f) : (j', kf f) ⟶ (j', k'')) (F.map ((𝟙 j', g j' ≫ gf f) : (j', k j') ⟶ (j', kf f)) (y j')) : by rw ←wf f ... = F.map ((𝟙 j', g j' ≫ gf f ≫ i f) : (j', k j') ⟶ (j', k'')) (y j') : by rw [←functor_to_types.map_comp_apply, prod_comp, id_comp, assoc] ... = F.map ((𝟙 j', g j' ≫ gf (𝟙 j') ≫ i (𝟙 j')) : (j', k j') ⟶ (j', k'')) (y j') : by rw [s f (𝟙 j'), ←s (𝟙 j') (𝟙 j')], }, }, -- Finally we check that this maps to `x`. { -- We can do this componentwise: apply types.limit_ext, intro j, -- and as each component is an equation in a colimit, we can verify it by -- pointing out the morphism which carries one representative to the other: simp only [←e, colimit_eq_iff, curry.obj_obj_map, limits.types.limit.π_mk, bifunctor.map_id_comp, id.def, types_comp_apply, limits.ι_colimit_limit_to_limit_colimit_π_apply], refine ⟨k'', 𝟙 k'', g j ≫ gf (𝟙 j) ≫ i (𝟙 j), _⟩, simp only [bifunctor.map_id_comp, types_comp_apply, bifunctor.map_id, types_id_apply], }, end noncomputable instance colimit_limit_to_limit_colimit_is_iso : is_iso (colimit_limit_to_limit_colimit F) := (is_iso_equiv_bijective _).symm ⟨colimit_limit_to_limit_colimit_injective F, colimit_limit_to_limit_colimit_surjective F⟩ end category_theory.limits
3e84b7df032fabce1a6eda0732bbeaa2e19d2707
8e2026ac8a0660b5a490dfb895599fb445bb77a0
/library/tools/smt2/builder.lean
08efc2f95aa6f9d60f00639007121d11c0cc6dae
[ "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
1,047
lean
import .syntax @[reducible] def smt2.builder (α : Type) := state (list smt2.cmd) α meta def smt2.builder.to_format {α : Type} (build : smt2.builder α) : format := format.join $ list.map to_fmt $ (build []).snd meta instance (α : Type) : has_to_format (smt2.builder α) := ⟨ smt2.builder.to_format ⟩ namespace smt2 namespace builder def add_command (c : cmd) : builder unit := do cs ← state.read, state.write (c :: cs) def echo (msg : string) : builder unit := add_command (cmd.echo msg) def check_sat : builder unit := add_command cmd.check_sat def pop (n : nat) : builder unit := add_command $ cmd.pop n def push (n : nat) : builder unit := add_command $ cmd.push n def scope {α} (level : nat) (action : builder α) : builder α := do push level, res ← action, pop level, return res def reset : builder unit := add_command cmd.reset def exit' : builder unit := add_command cmd.exit_cmd def declare_const (sym : string) (s : sort) : builder unit := add_command $ cmd.declare_const sym s end builder end smt2
4f8e1e4f32a6e3b88177c747763557dbc90c01f1
1437b3495ef9020d5413178aa33c0a625f15f15f
/group_theory/coset.lean
5d67023339fe1134bb35e2dde4e59026c2636882
[ "Apache-2.0" ]
permissive
jean002/mathlib
c66bbb2d9fdc9c03ae07f869acac7ddbfce67a30
dc6c38a765799c99c4d9c8d5207d9e6c9e0e2cfd
refs/heads/master
1,587,027,806,375
1,547,306,358,000
1,547,306,358,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,403
lean
/- Copyright (c) 2018 Mitchell Rowett. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mitchell Rowett, Scott Morrison -/ import group_theory.subgroup data.equiv.basic data.quot open set function variable {α : Type*} @[to_additive left_add_coset] def left_coset [has_mul α] (a : α) (s : set α) : set α := (λ x, a * x) '' s attribute [to_additive left_add_coset.equations._eqn_1] left_coset.equations._eqn_1 @[to_additive right_add_coset] def right_coset [has_mul α] (s : set α) (a : α) : set α := (λ x, x * a) '' s attribute [to_additive right_add_coset.equations._eqn_1] right_coset.equations._eqn_1 local infix ` *l `:70 := left_coset local infix ` +l `:70 := left_add_coset local infix ` *r `:70 := right_coset local infix ` +r `:70 := right_add_coset section coset_mul variable [has_mul α] @[to_additive mem_left_add_coset] lemma mem_left_coset {s : set α} {x : α} (a : α) (hxS : x ∈ s) : a * x ∈ a *l s := mem_image_of_mem (λ b : α, a * b) hxS @[to_additive mem_right_add_coset] lemma mem_right_coset {s : set α} {x : α} (a : α) (hxS : x ∈ s) : x * a ∈ s *r a := mem_image_of_mem (λ b : α, b * a) hxS @[to_additive left_add_coset_equiv] def left_coset_equiv (s : set α) (a b : α) := a *l s = b *l s @[to_additive left_add_coset_equiv_rel] lemma left_coset_equiv_rel (s : set α) : equivalence (left_coset_equiv s) := mk_equivalence (left_coset_equiv s) (λ a, rfl) (λ a b, eq.symm) (λ a b c, eq.trans) end coset_mul section coset_semigroup variable [semigroup α] @[simp] lemma left_coset_assoc (s : set α) (a b : α) : a *l (b *l s) = (a * b) *l s := by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc] attribute [to_additive left_add_coset_assoc] left_coset_assoc @[simp] lemma right_coset_assoc (s : set α) (a b : α) : s *r a *r b = s *r (a * b) := by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc] attribute [to_additive right_add_coset_assoc] right_coset_assoc @[to_additive left_add_coset_right_add_coset] lemma left_coset_right_coset (s : set α) (a b : α) : a *l s *r b = a *l (s *r b) := by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc] end coset_semigroup section coset_monoid variables [monoid α] (s : set α) @[simp] lemma one_left_coset : 1 *l s = s := set.ext $ by simp [left_coset] attribute [to_additive zero_left_add_coset] one_left_coset @[simp] lemma right_coset_one : s *r 1 = s := set.ext $ by simp [right_coset] attribute [to_additive right_add_coset_zero] right_coset_one end coset_monoid section coset_submonoid open is_submonoid variables [monoid α] (s : set α) [is_submonoid s] @[to_additive mem_own_left_add_coset] lemma mem_own_left_coset (a : α) : a ∈ a *l s := suffices a * 1 ∈ a *l s, by simpa, mem_left_coset a (one_mem s) @[to_additive mem_own_right_add_coset] lemma mem_own_right_coset (a : α) : a ∈ s *r a := suffices 1 * a ∈ s *r a, by simpa, mem_right_coset a (one_mem s) @[to_additive mem_left_add_coset_left_add_coset] lemma mem_left_coset_left_coset {a : α} (ha : a *l s = s) : a ∈ s := by rw [←ha]; exact mem_own_left_coset s a @[to_additive mem_right_add_coset_right_add_coset] lemma mem_right_coset_right_coset {a : α} (ha : s *r a = s) : a ∈ s := by rw [←ha]; exact mem_own_right_coset s a end coset_submonoid section coset_group variables [group α] {s : set α} {x : α} @[to_additive mem_left_add_coset_iff] lemma mem_left_coset_iff (a : α) : x ∈ a *l s ↔ a⁻¹ * x ∈ s := iff.intro (assume ⟨b, hb, eq⟩, by simp [eq.symm, hb]) (assume h, ⟨a⁻¹ * x, h, by simp⟩) @[to_additive mem_right_add_coset_iff] lemma mem_right_coset_iff (a : α) : x ∈ s *r a ↔ x * a⁻¹ ∈ s := iff.intro (assume ⟨b, hb, eq⟩, by simp [eq.symm, hb]) (assume h, ⟨x * a⁻¹, h, by simp⟩) end coset_group section coset_subgroup open is_submonoid open is_subgroup variables [group α] (s : set α) [is_subgroup s] @[to_additive left_add_coset_mem_left_add_coset] lemma left_coset_mem_left_coset {a : α} (ha : a ∈ s) : a *l s = s := set.ext $ by simp [mem_left_coset_iff, mul_mem_cancel_right s (inv_mem ha)] @[to_additive right_add_coset_mem_right_add_coset] lemma right_coset_mem_right_coset {a : α} (ha : a ∈ s) : s *r a = s := set.ext $ assume b, by simp [mem_right_coset_iff, mul_mem_cancel_left s (inv_mem ha)] @[to_additive normal_of_eq_add_cosets] theorem normal_of_eq_cosets [normal_subgroup s] (g : α) : g *l s = s *r g := set.ext $ assume a, by simp [mem_left_coset_iff, mem_right_coset_iff]; rw [mem_norm_comm_iff] @[to_additive eq_add_cosets_of_normal] theorem eq_cosets_of_normal (h : ∀ g, g *l s = s *r g) : normal_subgroup s := ⟨assume a ha g, show g * a * g⁻¹ ∈ s, by rw [← mem_right_coset_iff, ← h]; exact mem_left_coset g ha⟩ @[to_additive normal_iff_eq_add_cosets] theorem normal_iff_eq_cosets : normal_subgroup s ↔ ∀ g, g *l s = s *r g := ⟨@normal_of_eq_cosets _ _ s _, eq_cosets_of_normal s⟩ end coset_subgroup namespace quotient_group def left_rel [group α] (s : set α) [is_subgroup s] : setoid α := ⟨λ x y, x⁻¹ * y ∈ s, assume x, by simp [is_submonoid.one_mem], assume x y hxy, have (x⁻¹ * y)⁻¹ ∈ s, from is_subgroup.inv_mem hxy, by simpa using this, assume x y z hxy hyz, have x⁻¹ * y * (y⁻¹ * z) ∈ s, from is_submonoid.mul_mem hxy hyz, by simpa [mul_assoc] using this⟩ attribute [to_additive quotient_add_group.left_rel._proof_1] left_rel._proof_1 attribute [to_additive quotient_add_group.left_rel] left_rel attribute [to_additive quotient_add_group.left_rel.equations._eqn_1] left_rel.equations._eqn_1 /-- `quotient s` is the quotient type representing the left cosets of `s`. If `s` is a normal subgroup, `quotient s` is a group -/ def quotient [group α] (s : set α) [is_subgroup s] : Type* := quotient (left_rel s) attribute [to_additive quotient_add_group.quotient] quotient attribute [to_additive quotient_add_group.quotient.equations._eqn_1] quotient.equations._eqn_1 variables [group α] {s : set α} [is_subgroup s] @[to_additive quotient_add_group.mk] def mk (a : α) : quotient s := quotient.mk' a attribute [to_additive quotient_add_group.mk.equations._eqn_1] mk.equations._eqn_1 @[elab_as_eliminator, to_additive quotient_add_group.induction_on] lemma induction_on {C : quotient s → Prop} (x : quotient s) (H : ∀ z, C (quotient_group.mk z)) : C x := quotient.induction_on' x H attribute [elab_as_eliminator] quotient_add_group.induction_on @[to_additive quotient_add_group.has_coe] instance : has_coe α (quotient s) := ⟨mk⟩ attribute [to_additive quotient_add_group.has_coe.equations._eqn_1] has_coe.equations._eqn_1 @[elab_as_eliminator, to_additive quotient_add_group.induction_on'] lemma induction_on' {C : quotient s → Prop} (x : quotient s) (H : ∀ z : α, C z) : C x := quotient.induction_on' x H attribute [elab_as_eliminator] quotient_add_group.induction_on' @[to_additive quotient_add_group.inhabited] instance [group α] (s : set α) [is_subgroup s] : inhabited (quotient s) := ⟨((1 : α) : quotient s)⟩ attribute [to_additive quotient_add_group.inhabited.equations._eqn_1] inhabited.equations._eqn_1 @[to_additive quotient_add_group.eq] protected lemma eq {a b : α} : (a : quotient s) = b ↔ a⁻¹ * b ∈ s := quotient.eq' @[to_additive quotient_add_group.eq_class_eq_left_coset] lemma eq_class_eq_left_coset [group α] (s : set α) [is_subgroup s] (g : α) : {x : α | (x : quotient s) = g} = left_coset g s := set.ext $ λ z, by rw [mem_left_coset_iff, set.mem_set_of_eq, eq_comm, quotient_group.eq] end quotient_group namespace is_subgroup open quotient_group variables [group α] {s : set α} def left_coset_equiv_subgroup (g : α) : left_coset g s ≃ s := ⟨λ x, ⟨g⁻¹ * x.1, (mem_left_coset_iff _).1 x.2⟩, λ x, ⟨g * x.1, x.1, x.2, rfl⟩, λ ⟨x, hx⟩, subtype.eq $ by simp, λ ⟨g, hg⟩, subtype.eq $ by simp⟩ attribute [to_additive is_add_subgroup.left_add_coset_equiv_subgroup._match_2] left_coset_equiv_subgroup._match_2 attribute [to_additive is_add_subgroup.left_add_coset_equiv_subgroup._match_1] left_coset_equiv_subgroup._match_1 attribute [to_additive is_add_subgroup.left_add_coset_equiv_subgroup._proof_4] left_coset_equiv_subgroup._proof_4 attribute [to_additive is_add_subgroup.left_add_coset_equiv_subgroup._proof_3] left_coset_equiv_subgroup._proof_3 attribute [to_additive is_add_subgroup.left_add_coset_equiv_subgroup._proof_2] left_coset_equiv_subgroup._proof_2 attribute [to_additive is_add_subgroup.left_add_coset_equiv_subgroup._proof_1] left_coset_equiv_subgroup._proof_1 attribute [to_additive is_add_subgroup.left_add_coset_equiv_subgroup] left_coset_equiv_subgroup attribute [to_additive is_add_subgroup.left_add_coset_equiv_subgroup.equations._eqn_1] left_coset_equiv_subgroup.equations._eqn_1 attribute [to_additive is_add_subgroup.left_add_coset_equiv_subgroup._match_1.equations._eqn_1] left_coset_equiv_subgroup._match_1.equations._eqn_1 attribute [to_additive is_add_subgroup.left_add_coset_equiv_subgroup._match_2.equations._eqn_1] left_coset_equiv_subgroup._match_2.equations._eqn_1 noncomputable def group_equiv_quotient_times_subgroup (hs : is_subgroup s) : α ≃ (quotient s × s) := calc α ≃ Σ L : quotient s, {x : α // (x : quotient s)= L} : equiv.equiv_fib quotient_group.mk ... ≃ Σ L : quotient s, left_coset (quotient.out' L) s : equiv.sigma_congr_right (λ L, begin rw ← eq_class_eq_left_coset, show {x // quotient.mk' x = L} ≃ {x : α // quotient.mk' x = quotient.mk' _}, simp [-quotient.eq'] end) ... ≃ Σ L : quotient s, s : equiv.sigma_congr_right (λ L, left_coset_equiv_subgroup _) ... ≃ (quotient s × s) : equiv.sigma_equiv_prod _ _ attribute [to_additive is_add_subgroup.add_group_equiv_quotient_times_subgroup._proof_2] group_equiv_quotient_times_subgroup._proof_2 attribute [to_additive is_add_subgroup.add_group_equiv_quotient_times_subgroup._proof_1] group_equiv_quotient_times_subgroup._proof_1 attribute [to_additive is_add_subgroup.add_group_equiv_quotient_times_subgroup] group_equiv_quotient_times_subgroup attribute [to_additive is_add_subgroup.add_group_equiv_quotient_times_subgroup.equations._eqn_1] group_equiv_quotient_times_subgroup.equations._eqn_1 end is_subgroup
50863c361293db81c3896673eec2ba5cb958f03b
491068d2ad28831e7dade8d6dff871c3e49d9431
/hott/algebra/order.hlean
1f4dd97ea4c15554c8f30d3fa4afb0462f170af6
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,373
hlean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad Various types of orders. We develop weak orders "≤" and strict orders "<" separately. We also consider structures with both, where the two are related by x < y ↔ (x ≤ y × x ≠ y) (order_pair) x ≤ y ↔ (x < y ⊎ x = y) (strong_order_pair) These might not hold constructively in some applications, but we can define additional structures with both < and ≤ as needed. Ported from the standard library -/ --import logic.eq logic.connectives open core prod namespace algebra variable {A : Type} /- overloaded symbols -/ structure has_le.{l} [class] (A : Type.{l}) : Type.{l+1} := (le : A → A → Type.{l}) structure has_lt [class] (A : Type) := (lt : A → A → Type₀) infixl <= := has_le.le infixl ≤ := has_le.le infixl < := has_lt.lt definition has_le.ge [reducible] {A : Type} [s : has_le A] (a b : A) := b ≤ a notation a ≥ b := has_le.ge a b notation a >= b := has_le.ge a b definition has_lt.gt [reducible] {A : Type} [s : has_lt A] (a b : A) := b < a notation a > b := has_lt.gt a b /- weak orders -/ structure weak_order [class] (A : Type) extends has_le A := (le_refl : Πa, le a a) (le_trans : Πa b c, le a b → le b c → le a c) (le_antisymm : Πa b, le a b → le b a → a = b) section variable [s : weak_order A] include s definition le.refl (a : A) : a ≤ a := !weak_order.le_refl definition le.trans [trans] {a b c : A} : a ≤ b → b ≤ c → a ≤ c := !weak_order.le_trans definition ge.trans [trans] {a b c : A} (H1 : a ≥ b) (H2: b ≥ c) : a ≥ c := le.trans H2 H1 definition le.antisymm {a b : A} : a ≤ b → b ≤ a → a = b := !weak_order.le_antisymm end structure linear_weak_order [class] (A : Type) extends weak_order A : Type := (le_total : Πa b, le a b ⊎ le b a) definition le.total [s : linear_weak_order A] (a b : A) : a ≤ b ⊎ b ≤ a := !linear_weak_order.le_total /- strict orders -/ structure strict_order [class] (A : Type) extends has_lt A := (lt_irrefl : Πa, ¬ lt a a) (lt_trans : Πa b c, lt a b → lt b c → lt a c) section variable [s : strict_order A] include s definition lt.irrefl (a : A) : ¬ a < a := !strict_order.lt_irrefl definition lt.trans [trans] {a b c : A} : a < b → b < c → a < c := !strict_order.lt_trans definition gt.trans [trans] {a b c : A} (H1 : a > b) (H2: b > c) : a > c := lt.trans H2 H1 definition ne_of_lt {a b : A} (lt_ab : a < b) : a ≠ b := assume eq_ab : a = b, show empty, from lt.irrefl b (eq_ab ▸ lt_ab) definition ne_of_gt {a b : A} (gt_ab : a > b) : a ≠ b := ne.symm (ne_of_lt gt_ab) definition lt.asymm {a b : A} (H : a < b) : ¬ b < a := assume H1 : b < a, lt.irrefl _ (lt.trans H H1) end /- well-founded orders -/ -- TODO: do these duplicate what Leo has done? if so, eliminate structure wf_strict_order [class] (A : Type) extends strict_order A := (wf_rec : ΠP : A → Type, (Πx, (Πy, lt y x → P y) → P x) → Πx, P x) definition wf.rec_on {A : Type} [s : wf_strict_order A] {P : A → Type} (x : A) (H : Πx, (Πy, wf_strict_order.lt y x → P y) → P x) : P x := wf_strict_order.wf_rec P H x definition wf.ind_on := @wf.rec_on /- structures with a weak and a strict order -/ structure order_pair [class] (A : Type) extends weak_order A, has_lt A := (lt_iff_le_and_ne : Πa b, lt a b ↔ (le a b × a ≠ b)) section variable [s : order_pair A] variables {a b c : A} include s definition lt_iff_le_and_ne : a < b ↔ (a ≤ b × a ≠ b) := !order_pair.lt_iff_le_and_ne definition le_of_lt (H : a < b) : a ≤ b := pr1 (iff.mp lt_iff_le_and_ne H) definition lt_of_le_of_ne (H1 : a ≤ b) (H2 : a ≠ b) : a < b := iff.mp (iff.symm lt_iff_le_and_ne) (pair H1 H2) private definition lt_irrefl (s' : order_pair A) (a : A) : ¬ a < a := assume H : a < a, have H1 : a ≠ a, from pr2 (iff.mp !lt_iff_le_and_ne H), H1 rfl private definition lt_trans (s' : order_pair A) (a b c: A) (lt_ab : a < b) (lt_bc : b < c) : a < c := have le_ab : a ≤ b, from le_of_lt lt_ab, have le_bc : b ≤ c, from le_of_lt lt_bc, have le_ac : a ≤ c, from le.trans le_ab le_bc, have ne_ac : a ≠ c, from assume eq_ac : a = c, have le_ba : b ≤ a, from eq_ac⁻¹ ▸ le_bc, have eq_ab : a = b, from le.antisymm le_ab le_ba, have ne_ab : a ≠ b, from pr2 (iff.mp lt_iff_le_and_ne lt_ab), ne_ab eq_ab, show a < c, from lt_of_le_of_ne le_ac ne_ac definition order_pair.to_strict_order [instance] [coercion] [reducible] : strict_order A := ⦃ strict_order, s, lt_irrefl := lt_irrefl s, lt_trans := lt_trans s ⦄ definition lt_of_lt_of_le [trans] : a < b → b ≤ c → a < c := assume lt_ab : a < b, assume le_bc : b ≤ c, have le_ac : a ≤ c, from le.trans (le_of_lt lt_ab) le_bc, have ne_ac : a ≠ c, from assume eq_ac : a = c, have le_ba : b ≤ a, from eq_ac⁻¹ ▸ le_bc, have eq_ab : a = b, from le.antisymm (le_of_lt lt_ab) le_ba, show empty, from ne_of_lt lt_ab eq_ab, show a < c, from lt_of_le_of_ne le_ac ne_ac definition lt_of_le_of_lt [trans] : a ≤ b → b < c → a < c := assume le_ab : a ≤ b, assume lt_bc : b < c, have le_ac : a ≤ c, from le.trans le_ab (le_of_lt lt_bc), have ne_ac : a ≠ c, from assume eq_ac : a = c, have le_cb : c ≤ b, from eq_ac ▸ le_ab, have eq_bc : b = c, from le.antisymm (le_of_lt lt_bc) le_cb, show empty, from ne_of_lt lt_bc eq_bc, show a < c, from lt_of_le_of_ne le_ac ne_ac definition gt_of_gt_of_ge [trans] (H1 : a > b) (H2 : b ≥ c) : a > c := lt_of_le_of_lt H2 H1 definition gt_of_ge_of_gt [trans] (H1 : a ≥ b) (H2 : b > c) : a > c := lt_of_lt_of_le H2 H1 definition not_le_of_lt (H : a < b) : ¬ b ≤ a := assume H1 : b ≤ a, lt.irrefl _ (lt_of_lt_of_le H H1) definition not_lt_of_le (H : a ≤ b) : ¬ b < a := assume H1 : b < a, lt.irrefl _ (lt_of_le_of_lt H H1) end structure strong_order_pair [class] (A : Type) extends order_pair A := (le_iff_lt_or_eq : Πa b, le a b ↔ lt a b ⊎ a = b) definition le_iff_lt_or_eq [s : strong_order_pair A] {a b : A} : a ≤ b ↔ a < b ⊎ a = b := !strong_order_pair.le_iff_lt_or_eq definition lt_or_eq_of_le [s : strong_order_pair A] {a b : A} (le_ab : a ≤ b) : a < b ⊎ a = b := iff.mp le_iff_lt_or_eq le_ab -- We can also construct a strong order pair by defining a strict order, and then defining -- x ≤ y ↔ x < y ⊎ x = y structure strict_order_with_le [class] (A : Type) extends strict_order A, has_le A := (le_iff_lt_or_eq : Πa b, le a b ↔ lt a b ⊎ a = b) private definition le_refl (s : strict_order_with_le A) (a : A) : a ≤ a := iff.mp (iff.symm !strict_order_with_le.le_iff_lt_or_eq) (sum.inr rfl) private definition le_trans (s : strict_order_with_le A) (a b c : A) (le_ab : a ≤ b) (le_bc : b ≤ c) : a ≤ c := sum.rec_on (iff.mp !strict_order_with_le.le_iff_lt_or_eq le_ab) (assume lt_ab : a < b, sum.rec_on (iff.mp !strict_order_with_le.le_iff_lt_or_eq le_bc) (assume lt_bc : b < c, iff.elim_right !strict_order_with_le.le_iff_lt_or_eq (sum.inl (lt.trans lt_ab lt_bc))) (assume eq_bc : b = c, eq_bc ▸ le_ab)) (assume eq_ab : a = b, eq_ab⁻¹ ▸ le_bc) private definition le_antisymm (s : strict_order_with_le A) (a b : A) (le_ab : a ≤ b) (le_ba : b ≤ a) : a = b := sum.rec_on (iff.mp !strict_order_with_le.le_iff_lt_or_eq le_ab) (assume lt_ab : a < b, sum.rec_on (iff.mp !strict_order_with_le.le_iff_lt_or_eq le_ba) (assume lt_ba : b < a, absurd (lt.trans lt_ab lt_ba) (lt.irrefl a)) (assume eq_ba : b = a, eq_ba⁻¹)) (assume eq_ab : a = b, eq_ab) private definition lt_iff_le_ne (s : strict_order_with_le A) (a b : A) : a < b ↔ a ≤ b × a ≠ b := iff.intro (assume lt_ab : a < b, have le_ab : a ≤ b, from iff.elim_right !strict_order_with_le.le_iff_lt_or_eq (sum.inl lt_ab), show a ≤ b × a ≠ b, from pair le_ab (ne_of_lt lt_ab)) (assume H : a ≤ b × a ≠ b, have H1 : a < b ⊎ a = b, from iff.mp !strict_order_with_le.le_iff_lt_or_eq (pr1 H), show a < b, from sum_resolve_left H1 (pr2 H)) definition strict_order_with_le.to_order_pair [instance] [coercion] [reducible] [s : strict_order_with_le A] : strong_order_pair A := ⦃ strong_order_pair, s, le_refl := le_refl s, le_trans := le_trans s, le_antisymm := le_antisymm s, lt_iff_le_and_ne := lt_iff_le_ne s ⦄ /- linear orders -/ structure linear_order_pair [class] (A : Type) extends order_pair A, linear_weak_order A structure linear_strong_order_pair [class] (A : Type) extends strong_order_pair A, linear_weak_order A section variable [s : linear_strong_order_pair A] variables (a b c : A) include s definition lt.trichotomy : a < b ⊎ a = b ⊎ b < a := sum.rec_on (le.total a b) (assume H : a ≤ b, sum.rec_on (iff.mp !le_iff_lt_or_eq H) (assume H1, sum.inl H1) (assume H1, sum.inr (sum.inl H1))) (assume H : b ≤ a, sum.rec_on (iff.mp !le_iff_lt_or_eq H) (assume H1, sum.inr (sum.inr H1)) (assume H1, sum.inr (sum.inl (H1⁻¹)))) definition lt.by_cases {a b : A} {P : Type} (H1 : a < b → P) (H2 : a = b → P) (H3 : b < a → P) : P := sum.rec_on !lt.trichotomy (assume H, H1 H) (assume H, sum.rec_on H (assume H', H2 H') (assume H', H3 H')) definition linear_strong_order_pair.to_linear_order_pair [instance] [coercion] [reducible] : linear_order_pair A := ⦃ linear_order_pair, s ⦄ definition le_of_not_lt {a b : A} (H : ¬ a < b) : b ≤ a := lt.by_cases (assume H', absurd H' H) (assume H', H' ▸ !le.refl) (assume H', le_of_lt H') definition lt_of_not_le {a b : A} (H : ¬ a ≤ b) : b < a := lt.by_cases (assume H', absurd (le_of_lt H') H) (assume H', absurd (H' ▸ !le.refl) H) (assume H', H') definition lt_or_ge : a < b ⊎ a ≥ b := lt.by_cases (assume H1 : a < b, sum.inl H1) (assume H1 : a = b, sum.inr (H1 ▸ le.refl a)) (assume H1 : a > b, sum.inr (le_of_lt H1)) definition le_or_gt : a ≤ b ⊎ a > b := !sum.swap (lt_or_ge b a) definition lt_or_gt_of_ne {a b : A} (H : a ≠ b) : a < b ⊎ a > b := lt.by_cases (assume H1, sum.inl H1) (assume H1, absurd H1 H) (assume H1, sum.inr H1) end structure decidable_linear_order [class] (A : Type) extends linear_strong_order_pair A := (decidable_lt : decidable_rel lt) section variable [s : decidable_linear_order A] variables {a b c d : A} include s open decidable definition decidable_lt [instance] : decidable (a < b) := @decidable_linear_order.decidable_lt _ _ _ _ definition decidable_le [instance] : decidable (a ≤ b) := by_cases (assume H : a < b, inl (le_of_lt H)) (assume H : ¬ a < b, have H1 : b ≤ a, from le_of_not_lt H, by_cases (assume H2 : b < a, inr (not_le_of_lt H2)) (assume H2 : ¬ b < a, inl (le_of_not_lt H2))) definition decidable_eq [instance] : decidable (a = b) := by_cases (assume H : a ≤ b, by_cases (assume H1 : b ≤ a, inl (le.antisymm H H1)) (assume H1 : ¬ b ≤ a, inr (assume H2 : a = b, H1 (H2 ▸ le.refl a)))) (assume H : ¬ a ≤ b, (inr (assume H1 : a = b, H (H1 ▸ !le.refl)))) -- testing equality first may result in more definitional equalities definition lt.cases {B : Type} (a b : A) (t_lt t_eq t_gt : B) : B := if a = b then t_eq else (if a < b then t_lt else t_gt) definition lt.cases_of_eq {B : Type} {a b : A} {t_lt t_eq t_gt : B} (H : a = b) : lt.cases a b t_lt t_eq t_gt = t_eq := if_pos H definition lt.cases_of_lt {B : Type} {a b : A} {t_lt t_eq t_gt : B} (H : a < b) : lt.cases a b t_lt t_eq t_gt = t_lt := if_neg (ne_of_lt H) ⬝ if_pos H definition lt.cases_of_gt {B : Type} {a b : A} {t_lt t_eq t_gt : B} (H : a > b) : lt.cases a b t_lt t_eq t_gt = t_gt := if_neg (ne.symm (ne_of_lt H)) ⬝ if_neg (lt.asymm H) end end algebra /- For reference, these are all the transitivity rules defined in this file: calc_trans le.trans calc_trans lt.trans calc_trans lt_of_lt_of_le calc_trans lt_of_le_of_lt calc_trans ge.trans calc_trans gt.trans calc_trans gt_of_gt_of_ge calc_trans gt_of_ge_of_gt -/
3775af828ae8b5fe1a84518c45042d84884ce5e3
cad9160f67da6c3eecba9bb47aa1acdf5862cd58
/src/sets.lean
8e5cddbd47b855353a1eeef6ae0c0bed2cbf6658
[]
no_license
paraseba/topology-janich
902a9ecf06aa225215a4cf144bf0d6e0043b6135
270f3d2de019c093c86ac967b4ec9a4a2f25a5d3
refs/heads/master
1,671,576,401,688
1,599,706,090,000
1,599,706,090,000
291,599,865
0
0
null
null
null
null
UTF-8
Lean
false
false
1,413
lean
import tactic.basic import data.set.basic namespace set variables {α : Type*} {β : Type*} lemma union_of_sub (s: set α) (f : α → set α) (hf : ∀ x ∈ s, x ∈ f x ∧ f x ⊆ s) : s = ⋃₀ (f '' s) := begin ext, split, simp at *, { intros xs, exact ⟨ x, xs, (hf x xs).1 ⟩ }, { simp, intros x' xs' xfx', exact (hf x' xs').2 xfx', } end lemma preimage_nonempty_of_inter_range {s : set β} (f : α → β) : (s ∩ range f).nonempty → (f⁻¹' s).nonempty := begin intros hi, cases hi with b hb, have : b ∈ range f := mem_of_mem_inter_right hb, cases mem_range.mp this with a ha, have : f a ∈ s := mem_of_eq_of_mem ha (mem_of_mem_inter_left hb), exact ⟨ a, mem_preimage.mpr this⟩, end lemma nonempty_inter_iff_nonempty {s t : set α} : (s ∩ t).nonempty → s.nonempty ∧ t.nonempty := begin intros h, cases h with a ha, have h1: a ∈ s := mem_of_mem_inter_left ha, have h2: a ∈ t := mem_of_mem_inter_right ha, exact ⟨ ⟨ a, h1 ⟩ , ⟨ a, h2 ⟩ ⟩ , end lemma inter_of_subtype (s t: set α) : t ∩ s = subtype.val '' {a : ↥s | ↑a ∈ t} := begin ext, simp at *, split, { intros h, exact ⟨ h.2, h.1 ⟩ , }, { rintros ⟨yins, yint ⟩, exact ⟨ yint, yins ⟩, } end end set
365ccf882060f9e4e0f1a19f95d66138b3cff807
367134ba5a65885e863bdc4507601606690974c1
/src/data/nat/gcd.lean
f9a09e4ae3283ffbfbe113af7820e348e79568e2
[ "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
16,760
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura -/ import data.nat.basic /-! # Definitions and properties of `gcd`, `lcm`, and `coprime` -/ namespace nat /-! ### `gcd` -/ theorem gcd_dvd (m n : ℕ) : (gcd m n ∣ m) ∧ (gcd m n ∣ n) := gcd.induction m n (λn, by rw gcd_zero_left; exact ⟨dvd_zero n, dvd_refl n⟩) (λm n npos, by rw ←gcd_rec; exact λ ⟨IH₁, IH₂⟩, ⟨IH₂, (dvd_mod_iff IH₂).1 IH₁⟩) theorem gcd_dvd_left (m n : ℕ) : gcd m n ∣ m := (gcd_dvd m n).left theorem gcd_dvd_right (m n : ℕ) : gcd m n ∣ n := (gcd_dvd m n).right theorem gcd_le_left {m} (n) (h : 0 < m) : gcd m n ≤ m := le_of_dvd h $ gcd_dvd_left m n theorem gcd_le_right (m) {n} (h : 0 < n) : gcd m n ≤ n := le_of_dvd h $ gcd_dvd_right m n theorem dvd_gcd {m n k : ℕ} : k ∣ m → k ∣ n → k ∣ gcd m n := gcd.induction m n (λn _ kn, by rw gcd_zero_left; exact kn) (λn m mpos IH H1 H2, by rw gcd_rec; exact IH ((dvd_mod_iff H1).2 H2) H1) theorem dvd_gcd_iff {m n k : ℕ} : k ∣ gcd m n ↔ k ∣ m ∧ k ∣ n := iff.intro (λ h, ⟨dvd_trans h (gcd_dvd m n).left, dvd_trans h (gcd_dvd m n).right⟩) (λ h, dvd_gcd h.left h.right) theorem gcd_comm (m n : ℕ) : gcd m n = gcd n m := dvd_antisymm (dvd_gcd (gcd_dvd_right m n) (gcd_dvd_left m n)) (dvd_gcd (gcd_dvd_right n m) (gcd_dvd_left n m)) theorem gcd_eq_left_iff_dvd {m n : ℕ} : m ∣ n ↔ gcd m n = m := ⟨λ h, by rw [gcd_rec, mod_eq_zero_of_dvd h, gcd_zero_left], λ h, h ▸ gcd_dvd_right m n⟩ theorem gcd_eq_right_iff_dvd {m n : ℕ} : m ∣ n ↔ gcd n m = m := by rw gcd_comm; apply gcd_eq_left_iff_dvd theorem gcd_assoc (m n k : ℕ) : gcd (gcd m n) k = gcd m (gcd n k) := dvd_antisymm (dvd_gcd (dvd.trans (gcd_dvd_left (gcd m n) k) (gcd_dvd_left m n)) (dvd_gcd (dvd.trans (gcd_dvd_left (gcd m n) k) (gcd_dvd_right m n)) (gcd_dvd_right (gcd m n) k))) (dvd_gcd (dvd_gcd (gcd_dvd_left m (gcd n k)) (dvd.trans (gcd_dvd_right m (gcd n k)) (gcd_dvd_left n k))) (dvd.trans (gcd_dvd_right m (gcd n k)) (gcd_dvd_right n k))) @[simp] theorem gcd_one_right (n : ℕ) : gcd n 1 = 1 := eq.trans (gcd_comm n 1) $ gcd_one_left n theorem gcd_mul_left (m n k : ℕ) : gcd (m * n) (m * k) = m * gcd n k := gcd.induction n k (λk, by repeat {rw mul_zero <|> rw gcd_zero_left}) (λk n H IH, by rwa [←mul_mod_mul_left, ←gcd_rec, ←gcd_rec] at IH) theorem gcd_mul_right (m n k : ℕ) : gcd (m * n) (k * n) = gcd m k * n := by rw [mul_comm m n, mul_comm k n, mul_comm (gcd m k) n, gcd_mul_left] theorem gcd_pos_of_pos_left {m : ℕ} (n : ℕ) (mpos : 0 < m) : 0 < gcd m n := pos_of_dvd_of_pos (gcd_dvd_left m n) mpos theorem gcd_pos_of_pos_right (m : ℕ) {n : ℕ} (npos : 0 < n) : 0 < gcd m n := pos_of_dvd_of_pos (gcd_dvd_right m n) npos theorem eq_zero_of_gcd_eq_zero_left {m n : ℕ} (H : gcd m n = 0) : m = 0 := or.elim (eq_zero_or_pos m) id (assume H1 : 0 < m, absurd (eq.symm H) (ne_of_lt (gcd_pos_of_pos_left _ H1))) theorem eq_zero_of_gcd_eq_zero_right {m n : ℕ} (H : gcd m n = 0) : n = 0 := by rw gcd_comm at H; exact eq_zero_of_gcd_eq_zero_left H theorem gcd_div {m n k : ℕ} (H1 : k ∣ m) (H2 : k ∣ n) : gcd (m / k) (n / k) = gcd m n / k := or.elim (eq_zero_or_pos k) (λk0, by rw [k0, nat.div_zero, nat.div_zero, nat.div_zero, gcd_zero_right]) (λH3, nat.eq_of_mul_eq_mul_right H3 $ by rw [ nat.div_mul_cancel (dvd_gcd H1 H2), ←gcd_mul_right, nat.div_mul_cancel H1, nat.div_mul_cancel H2]) theorem gcd_dvd_gcd_of_dvd_left {m k : ℕ} (n : ℕ) (H : m ∣ k) : gcd m n ∣ gcd k n := dvd_gcd (dvd.trans (gcd_dvd_left m n) H) (gcd_dvd_right m n) theorem gcd_dvd_gcd_of_dvd_right {m k : ℕ} (n : ℕ) (H : m ∣ k) : gcd n m ∣ gcd n k := dvd_gcd (gcd_dvd_left n m) (dvd.trans (gcd_dvd_right n m) H) theorem gcd_dvd_gcd_mul_left (m n k : ℕ) : gcd m n ∣ gcd (k * m) n := gcd_dvd_gcd_of_dvd_left _ (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right (m n k : ℕ) : gcd m n ∣ gcd (m * k) n := gcd_dvd_gcd_of_dvd_left _ (dvd_mul_right _ _) theorem gcd_dvd_gcd_mul_left_right (m n k : ℕ) : gcd m n ∣ gcd m (k * n) := gcd_dvd_gcd_of_dvd_right _ (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right_right (m n k : ℕ) : gcd m n ∣ gcd m (n * k) := gcd_dvd_gcd_of_dvd_right _ (dvd_mul_right _ _) theorem gcd_eq_left {m n : ℕ} (H : m ∣ n) : gcd m n = m := dvd_antisymm (gcd_dvd_left _ _) (dvd_gcd (dvd_refl _) H) theorem gcd_eq_right {m n : ℕ} (H : n ∣ m) : gcd m n = n := by rw [gcd_comm, gcd_eq_left H] @[simp] lemma gcd_mul_left_left (m n : ℕ) : gcd (m * n) n = n := dvd_antisymm (gcd_dvd_right _ _) (dvd_gcd (dvd_mul_left _ _) (dvd_refl _)) @[simp] lemma gcd_mul_left_right (m n : ℕ) : gcd n (m * n) = n := by rw [gcd_comm, gcd_mul_left_left] @[simp] lemma gcd_mul_right_left (m n : ℕ) : gcd (n * m) n = n := by rw [mul_comm, gcd_mul_left_left] @[simp] lemma gcd_mul_right_right (m n : ℕ) : gcd n (n * m) = n := by rw [gcd_comm, gcd_mul_right_left] @[simp] lemma gcd_gcd_self_right_left (m n : ℕ) : gcd m (gcd m n) = gcd m n := dvd_antisymm (gcd_dvd_right _ _) (dvd_gcd (gcd_dvd_left _ _) (dvd_refl _)) @[simp] lemma gcd_gcd_self_right_right (m n : ℕ) : gcd m (gcd n m) = gcd n m := by rw [gcd_comm n m, gcd_gcd_self_right_left] @[simp] lemma gcd_gcd_self_left_right (m n : ℕ) : gcd (gcd n m) m = gcd n m := by rw [gcd_comm, gcd_gcd_self_right_right] @[simp] lemma gcd_gcd_self_left_left (m n : ℕ) : gcd (gcd m n) m = gcd m n := by rw [gcd_comm m n, gcd_gcd_self_left_right] lemma gcd_add_mul_self (m n k : ℕ) : gcd m (n + k * m) = gcd m n := by simp [gcd_rec m (n + k * m), gcd_rec m n] theorem gcd_eq_zero_iff {i j : ℕ} : gcd i j = 0 ↔ i = 0 ∧ j = 0 := begin split, { intro h, exact ⟨eq_zero_of_gcd_eq_zero_left h, eq_zero_of_gcd_eq_zero_right h⟩, }, { intro h, rw [h.1, h.2], exact nat.gcd_zero_right _ } end /-! ### `lcm` -/ theorem lcm_comm (m n : ℕ) : lcm m n = lcm n m := by delta lcm; rw [mul_comm, gcd_comm] @[simp] theorem lcm_zero_left (m : ℕ) : lcm 0 m = 0 := by delta lcm; rw [zero_mul, nat.zero_div] @[simp] theorem lcm_zero_right (m : ℕ) : lcm m 0 = 0 := lcm_comm 0 m ▸ lcm_zero_left m @[simp] theorem lcm_one_left (m : ℕ) : lcm 1 m = m := by delta lcm; rw [one_mul, gcd_one_left, nat.div_one] @[simp] theorem lcm_one_right (m : ℕ) : lcm m 1 = m := lcm_comm 1 m ▸ lcm_one_left m @[simp] theorem lcm_self (m : ℕ) : lcm m m = m := or.elim (eq_zero_or_pos m) (λh, by rw [h, lcm_zero_left]) (λh, by delta lcm; rw [gcd_self, nat.mul_div_cancel _ h]) theorem dvd_lcm_left (m n : ℕ) : m ∣ lcm m n := dvd.intro (n / gcd m n) (nat.mul_div_assoc _ $ gcd_dvd_right m n).symm theorem dvd_lcm_right (m n : ℕ) : n ∣ lcm m n := lcm_comm n m ▸ dvd_lcm_left n m theorem gcd_mul_lcm (m n : ℕ) : gcd m n * lcm m n = m * n := by delta lcm; rw [nat.mul_div_cancel' (dvd.trans (gcd_dvd_left m n) (dvd_mul_right m n))] theorem lcm_dvd {m n k : ℕ} (H1 : m ∣ k) (H2 : n ∣ k) : lcm m n ∣ k := or.elim (eq_zero_or_pos k) (λh, by rw h; exact dvd_zero _) (λkpos, dvd_of_mul_dvd_mul_left (gcd_pos_of_pos_left n (pos_of_dvd_of_pos H1 kpos)) $ by rw [gcd_mul_lcm, ←gcd_mul_right, mul_comm n k]; exact dvd_gcd (mul_dvd_mul_left _ H2) (mul_dvd_mul_right H1 _)) theorem lcm_assoc (m n k : ℕ) : lcm (lcm m n) k = lcm m (lcm n k) := dvd_antisymm (lcm_dvd (lcm_dvd (dvd_lcm_left m (lcm n k)) (dvd.trans (dvd_lcm_left n k) (dvd_lcm_right m (lcm n k)))) (dvd.trans (dvd_lcm_right n k) (dvd_lcm_right m (lcm n k)))) (lcm_dvd (dvd.trans (dvd_lcm_left m n) (dvd_lcm_left (lcm m n) k)) (lcm_dvd (dvd.trans (dvd_lcm_right m n) (dvd_lcm_left (lcm m n) k)) (dvd_lcm_right (lcm m n) k))) theorem lcm_ne_zero {m n : ℕ} (hm : m ≠ 0) (hn : n ≠ 0) : lcm m n ≠ 0 := by { intro h, simpa [h, hm, hn] using gcd_mul_lcm m n, } /-! ### `coprime` See also `nat.coprime_of_dvd` and `nat.coprime_of_dvd'` to prove `nat.coprime m n`. -/ instance (m n : ℕ) : decidable (coprime m n) := by unfold coprime; apply_instance theorem coprime.gcd_eq_one {m n : ℕ} : coprime m n → gcd m n = 1 := id theorem coprime.symm {m n : ℕ} : coprime n m → coprime m n := (gcd_comm m n).trans theorem coprime.dvd_of_dvd_mul_right {m n k : ℕ} (H1 : coprime k n) (H2 : k ∣ m * n) : k ∣ m := let t := dvd_gcd (dvd_mul_left k m) H2 in by rwa [gcd_mul_left, H1.gcd_eq_one, mul_one] at t theorem coprime.dvd_of_dvd_mul_left {m n k : ℕ} (H1 : coprime k m) (H2 : k ∣ m * n) : k ∣ n := by rw mul_comm at H2; exact H1.dvd_of_dvd_mul_right H2 theorem coprime.gcd_mul_left_cancel {k : ℕ} (m : ℕ) {n : ℕ} (H : coprime k n) : gcd (k * m) n = gcd m n := have H1 : coprime (gcd (k * m) n) k, by rw [coprime, gcd_assoc, H.symm.gcd_eq_one, gcd_one_right], dvd_antisymm (dvd_gcd (H1.dvd_of_dvd_mul_left (gcd_dvd_left _ _)) (gcd_dvd_right _ _)) (gcd_dvd_gcd_mul_left _ _ _) theorem coprime.gcd_mul_right_cancel (m : ℕ) {k n : ℕ} (H : coprime k n) : gcd (m * k) n = gcd m n := by rw [mul_comm m k, H.gcd_mul_left_cancel m] theorem coprime.gcd_mul_left_cancel_right {k m : ℕ} (n : ℕ) (H : coprime k m) : gcd m (k * n) = gcd m n := by rw [gcd_comm m n, gcd_comm m (k * n), H.gcd_mul_left_cancel n] theorem coprime.gcd_mul_right_cancel_right {k m : ℕ} (n : ℕ) (H : coprime k m) : gcd m (n * k) = gcd m n := by rw [mul_comm n k, H.gcd_mul_left_cancel_right n] theorem coprime_div_gcd_div_gcd {m n : ℕ} (H : 0 < gcd m n) : coprime (m / gcd m n) (n / gcd m n) := by delta coprime; rw [gcd_div (gcd_dvd_left m n) (gcd_dvd_right m n), nat.div_self H] theorem not_coprime_of_dvd_of_dvd {m n d : ℕ} (dgt1 : 1 < d) (Hm : d ∣ m) (Hn : d ∣ n) : ¬ coprime m n := λ (co : gcd m n = 1), not_lt_of_ge (le_of_dvd zero_lt_one $ by rw ←co; exact dvd_gcd Hm Hn) dgt1 theorem exists_coprime {m n : ℕ} (H : 0 < gcd m n) : ∃ m' n', coprime m' n' ∧ m = m' * gcd m n ∧ n = n' * gcd m n := ⟨_, _, coprime_div_gcd_div_gcd H, (nat.div_mul_cancel (gcd_dvd_left m n)).symm, (nat.div_mul_cancel (gcd_dvd_right m n)).symm⟩ theorem exists_coprime' {m n : ℕ} (H : 0 < gcd m n) : ∃ g m' n', 0 < g ∧ coprime m' n' ∧ m = m' * g ∧ n = n' * g := let ⟨m', n', h⟩ := exists_coprime H in ⟨_, m', n', H, h⟩ theorem coprime.mul {m n k : ℕ} (H1 : coprime m k) (H2 : coprime n k) : coprime (m * n) k := (H1.gcd_mul_left_cancel n).trans H2 theorem coprime.mul_right {k m n : ℕ} (H1 : coprime k m) (H2 : coprime k n) : coprime k (m * n) := (H1.symm.mul H2.symm).symm theorem coprime.coprime_dvd_left {m k n : ℕ} (H1 : m ∣ k) (H2 : coprime k n) : coprime m n := eq_one_of_dvd_one (by delta coprime at H2; rw ← H2; exact gcd_dvd_gcd_of_dvd_left _ H1) theorem coprime.coprime_dvd_right {m k n : ℕ} (H1 : n ∣ m) (H2 : coprime k m) : coprime k n := (H2.symm.coprime_dvd_left H1).symm theorem coprime.coprime_mul_left {k m n : ℕ} (H : coprime (k * m) n) : coprime m n := H.coprime_dvd_left (dvd_mul_left _ _) theorem coprime.coprime_mul_right {k m n : ℕ} (H : coprime (m * k) n) : coprime m n := H.coprime_dvd_left (dvd_mul_right _ _) theorem coprime.coprime_mul_left_right {k m n : ℕ} (H : coprime m (k * n)) : coprime m n := H.coprime_dvd_right (dvd_mul_left _ _) theorem coprime.coprime_mul_right_right {k m n : ℕ} (H : coprime m (n * k)) : coprime m n := H.coprime_dvd_right (dvd_mul_right _ _) theorem coprime.coprime_div_left {m n a : ℕ} (cmn : coprime m n) (dvd : a ∣ m) : coprime (m / a) n := begin by_cases a_split : (a = 0), { subst a_split, rw zero_dvd_iff at dvd, simpa [dvd] using cmn, }, { rcases dvd with ⟨k, rfl⟩, rw nat.mul_div_cancel_left _ (nat.pos_of_ne_zero a_split), exact coprime.coprime_mul_left cmn, }, end theorem coprime.coprime_div_right {m n a : ℕ} (cmn : coprime m n) (dvd : a ∣ n) : coprime m (n / a) := (coprime.coprime_div_left cmn.symm dvd).symm lemma coprime_mul_iff_left {k m n : ℕ} : coprime (m * n) k ↔ coprime m k ∧ coprime n k := ⟨λ h, ⟨coprime.coprime_mul_right h, coprime.coprime_mul_left h⟩, λ ⟨h, _⟩, by rwa [coprime, coprime.gcd_mul_left_cancel n h]⟩ lemma coprime_mul_iff_right {k m n : ℕ} : coprime k (m * n) ↔ coprime k m ∧ coprime k n := by { repeat { rw [coprime, nat.gcd_comm k] }, exact coprime_mul_iff_left } lemma coprime.gcd_left (k : ℕ) {m n : ℕ} (hmn : coprime m n) : coprime (gcd k m) n := hmn.coprime_dvd_left $ gcd_dvd_right k m lemma coprime.gcd_right (k : ℕ) {m n : ℕ} (hmn : coprime m n) : coprime m (gcd k n) := hmn.coprime_dvd_right $ gcd_dvd_right k n lemma coprime.gcd_both (k l : ℕ) {m n : ℕ} (hmn : coprime m n) : coprime (gcd k m) (gcd l n) := (hmn.gcd_left k).gcd_right l lemma coprime.mul_dvd_of_dvd_of_dvd {a n m : ℕ} (hmn : coprime m n) (hm : m ∣ a) (hn : n ∣ a) : m * n ∣ a := let ⟨k, hk⟩ := hm in hk.symm ▸ mul_dvd_mul_left _ (hmn.symm.dvd_of_dvd_mul_left (hk ▸ hn)) theorem coprime_one_left : ∀ n, coprime 1 n := gcd_one_left theorem coprime_one_right : ∀ n, coprime n 1 := gcd_one_right theorem coprime.pow_left {m k : ℕ} (n : ℕ) (H1 : coprime m k) : coprime (m ^ n) k := nat.rec_on n (coprime_one_left _) (λn IH, H1.mul IH) theorem coprime.pow_right {m k : ℕ} (n : ℕ) (H1 : coprime k m) : coprime k (m ^ n) := (H1.symm.pow_left n).symm theorem coprime.pow {k l : ℕ} (m n : ℕ) (H1 : coprime k l) : coprime (k ^ m) (l ^ n) := (H1.pow_left _).pow_right _ theorem coprime.eq_one_of_dvd {k m : ℕ} (H : coprime k m) (d : k ∣ m) : k = 1 := by rw [← H.gcd_eq_one, gcd_eq_left d] @[simp] theorem coprime_zero_left (n : ℕ) : coprime 0 n ↔ n = 1 := by simp [coprime] @[simp] theorem coprime_zero_right (n : ℕ) : coprime n 0 ↔ n = 1 := by simp [coprime] @[simp] theorem coprime_one_left_iff (n : ℕ) : coprime 1 n ↔ true := by simp [coprime] @[simp] theorem coprime_one_right_iff (n : ℕ) : coprime n 1 ↔ true := by simp [coprime] @[simp] theorem coprime_self (n : ℕ) : coprime n n ↔ n = 1 := by simp [coprime] /-- Represent a divisor of `m * n` as a product of a divisor of `m` and a divisor of `n`. -/ def prod_dvd_and_dvd_of_dvd_prod {m n k : ℕ} (H : k ∣ m * n) : { d : {m' // m' ∣ m} × {n' // n' ∣ n} // k = d.1 * d.2 } := begin cases h0 : (gcd k m), case nat.zero { have : k = 0 := eq_zero_of_gcd_eq_zero_left h0, subst this, have : m = 0 := eq_zero_of_gcd_eq_zero_right h0, subst this, exact ⟨⟨⟨0, dvd_refl 0⟩, ⟨n, dvd_refl n⟩⟩, (zero_mul n).symm⟩ }, case nat.succ : tmp { have hpos : 0 < gcd k m := h0.symm ▸ nat.zero_lt_succ _; clear h0 tmp, have hd : gcd k m * (k / gcd k m) = k := (nat.mul_div_cancel' (gcd_dvd_left k m)), refine ⟨⟨⟨gcd k m, gcd_dvd_right k m⟩, ⟨k / gcd k m, _⟩⟩, hd.symm⟩, apply dvd_of_mul_dvd_mul_left hpos, rw [hd, ← gcd_mul_right], exact dvd_gcd (dvd_mul_right _ _) H } end theorem gcd_mul_dvd_mul_gcd (k m n : ℕ) : gcd k (m * n) ∣ gcd k m * gcd k n := begin rcases (prod_dvd_and_dvd_of_dvd_prod $ gcd_dvd_right k (m * n)) with ⟨⟨⟨m', hm'⟩, ⟨n', hn'⟩⟩, h⟩, replace h : gcd k (m * n) = m' * n' := h, rw h, have hm'n' : m' * n' ∣ k := h ▸ gcd_dvd_left _ _, apply mul_dvd_mul, { have hm'k : m' ∣ k := dvd_trans (dvd_mul_right m' n') hm'n', exact dvd_gcd hm'k hm' }, { have hn'k : n' ∣ k := dvd_trans (dvd_mul_left n' m') hm'n', exact dvd_gcd hn'k hn' } end theorem coprime.gcd_mul (k : ℕ) {m n : ℕ} (h : coprime m n) : gcd k (m * n) = gcd k m * gcd k n := dvd_antisymm (gcd_mul_dvd_mul_gcd k m n) ((h.gcd_both k k).mul_dvd_of_dvd_of_dvd (gcd_dvd_gcd_mul_right_right _ _ _) (gcd_dvd_gcd_mul_left_right _ _ _)) theorem pow_dvd_pow_iff {a b n : ℕ} (n0 : 0 < n) : a ^ n ∣ b ^ n ↔ a ∣ b := begin refine ⟨λ h, _, λ h, pow_dvd_pow_of_dvd h _⟩, cases eq_zero_or_pos (gcd a b) with g0 g0, { simp [eq_zero_of_gcd_eq_zero_right g0] }, rcases exists_coprime' g0 with ⟨g, a', b', g0', co, rfl, rfl⟩, rw [mul_pow, mul_pow] at h, replace h := dvd_of_mul_dvd_mul_right (pow_pos g0' _) h, have := pow_dvd_pow a' n0, rw [pow_one, (co.pow n n).eq_one_of_dvd h] at this, simp [eq_one_of_dvd_one this] end lemma gcd_mul_gcd_of_coprime_of_mul_eq_mul {a b c d : ℕ} (cop : c.coprime d) (h : a * b = c * d) : a.gcd c * b.gcd c = c := begin apply dvd_antisymm, { apply nat.coprime.dvd_of_dvd_mul_right (nat.coprime.mul (cop.gcd_left _) (cop.gcd_left _)), rw ← h, apply mul_dvd_mul (gcd_dvd _ _).1 (gcd_dvd _ _).1 }, { rw [gcd_comm a _, gcd_comm b _], transitivity c.gcd (a * b), rw [h, gcd_mul_right_right d c], apply gcd_mul_dvd_mul_gcd } end end nat
7515608b80404dad909e87048f8d4c8c2b6cc92d
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/limits/constructions/over/products.lean
75544c3ad3c875d373ccc705a13bd497cdcb7ab1
[ "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
6,150
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Reid Barton, Bhavik Mehta -/ import category_theory.over import category_theory.limits.shapes.pullbacks import category_theory.limits.shapes.wide_pullbacks import category_theory.limits.shapes.finite_products /-! # Products in the over category Shows that products in the over category can be derived from wide pullbacks in the base category. The main result is `over_product_of_wide_pullback`, which says that if `C` has `J`-indexed wide pullbacks, then `over B` has `J`-indexed products. -/ universes v u -- morphism levels before object levels. See note [category_theory universes]. open category_theory category_theory.limits variables {J : Type v} variables {C : Type u} [category.{v} C] variable {X : C} namespace category_theory.over namespace construct_products /-- (Implementation) Given a product diagram in `C/B`, construct the corresponding wide pullback diagram in `C`. -/ @[reducible] def wide_pullback_diagram_of_diagram_over (B : C) {J : Type v} (F : discrete J ⥤ over B) : wide_pullback_shape J ⥤ C := wide_pullback_shape.wide_cospan B (λ j, (F.obj j).left) (λ j, (F.obj j).hom) /-- (Impl) A preliminary definition to avoid timeouts. -/ @[simps] def cones_equiv_inverse_obj (B : C) {J : Type v} (F : discrete J ⥤ over B) (c : cone F) : cone (wide_pullback_diagram_of_diagram_over B F) := { X := c.X.left, π := { app := λ X, option.cases_on X c.X.hom (λ (j : J), (c.π.app j).left), -- `tidy` can do this using `case_bash`, but let's try to be a good `-T50000` citizen: naturality' := λ X Y f, begin dsimp, cases X; cases Y; cases f, { rw [category.id_comp, category.comp_id], }, { rw [over.w, category.id_comp], }, { rw [category.id_comp, category.comp_id], }, end } } /-- (Impl) A preliminary definition to avoid timeouts. -/ @[simps] def cones_equiv_inverse (B : C) {J : Type v} (F : discrete J ⥤ over B) : cone F ⥤ cone (wide_pullback_diagram_of_diagram_over B F) := { obj := cones_equiv_inverse_obj B F, map := λ c₁ c₂ f, { hom := f.hom.left, w' := λ j, begin cases j, { simp }, { dsimp, rw ← f.w j, refl } end } } /-- (Impl) A preliminary definition to avoid timeouts. -/ @[simps] def cones_equiv_functor (B : C) {J : Type v} (F : discrete J ⥤ over B) : cone (wide_pullback_diagram_of_diagram_over B F) ⥤ cone F := { obj := λ c, { X := over.mk (c.π.app none), π := { app := λ j, over.hom_mk (c.π.app (some j)) (by apply c.w (wide_pullback_shape.hom.term j)) } }, map := λ c₁ c₂ f, { hom := over.hom_mk f.hom } } local attribute [tidy] tactic.case_bash /-- (Impl) A preliminary definition to avoid timeouts. -/ @[simp] def cones_equiv_unit_iso (B : C) (F : discrete J ⥤ over B) : 𝟭 (cone (wide_pullback_diagram_of_diagram_over B F)) ≅ cones_equiv_functor B F ⋙ cones_equiv_inverse B F := nat_iso.of_components (λ _, cones.ext {hom := 𝟙 _, inv := 𝟙 _} (by tidy)) (by tidy) /-- (Impl) A preliminary definition to avoid timeouts. -/ @[simp] def cones_equiv_counit_iso (B : C) (F : discrete J ⥤ over B) : cones_equiv_inverse B F ⋙ cones_equiv_functor B F ≅ 𝟭 (cone F) := nat_iso.of_components (λ _, cones.ext {hom := over.hom_mk (𝟙 _), inv := over.hom_mk (𝟙 _)} (by tidy)) (by tidy) -- TODO: Can we add `. obviously` to the second arguments of `nat_iso.of_components` and -- `cones.ext`? /-- (Impl) Establish an equivalence between the category of cones for `F` and for the "grown" `F`. -/ @[simps] def cones_equiv (B : C) (F : discrete J ⥤ over B) : cone (wide_pullback_diagram_of_diagram_over B F) ≌ cone F := { functor := cones_equiv_functor B F, inverse := cones_equiv_inverse B F, unit_iso := cones_equiv_unit_iso B F, counit_iso := cones_equiv_counit_iso B F, } /-- Use the above equivalence to prove we have a limit. -/ lemma has_over_limit_discrete_of_wide_pullback_limit {B : C} (F : discrete J ⥤ over B) [has_limit (wide_pullback_diagram_of_diagram_over B F)] : has_limit F := has_limit.mk { cone := _, is_limit := is_limit.of_right_adjoint (cones_equiv B F).functor (limit.is_limit (wide_pullback_diagram_of_diagram_over B F)) } /-- Given a wide pullback in `C`, construct a product in `C/B`. -/ lemma over_product_of_wide_pullback [has_limits_of_shape (wide_pullback_shape J) C] {B : C} : has_limits_of_shape (discrete J) (over B) := { has_limit := λ F, has_over_limit_discrete_of_wide_pullback_limit F } /-- Given a pullback in `C`, construct a binary product in `C/B`. -/ lemma over_binary_product_of_pullback [has_pullbacks C] {B : C} : has_binary_products (over B) := over_product_of_wide_pullback /-- Given all wide pullbacks in `C`, construct products in `C/B`. -/ lemma over_products_of_wide_pullbacks [has_wide_pullbacks C] {B : C} : has_products (over B) := λ J, over_product_of_wide_pullback /-- Given all finite wide pullbacks in `C`, construct finite products in `C/B`. -/ lemma over_finite_products_of_finite_wide_pullbacks [has_finite_wide_pullbacks C] {B : C} : has_finite_products (over B) := ⟨λ J 𝒥₁ 𝒥₂, by exactI over_product_of_wide_pullback⟩ end construct_products /-- Construct terminal object in the over category. This isn't an instance as it's not typically the way we want to define terminal objects. (For instance, this gives a terminal object which is different from the generic one given by `over_product_of_wide_pullback` above.) -/ lemma over_has_terminal (B : C) : has_terminal (over B) := { has_limit := λ F, has_limit.mk { cone := { X := over.mk (𝟙 _), π := { app := λ p, pempty.elim p } }, is_limit := { lift := λ s, over.hom_mk _, fac' := λ _ j, j.elim, uniq' := λ s m _, begin ext, rw over.hom_mk_left, have := m.w, dsimp at this, rwa [category.comp_id, category.comp_id] at this end } } } end category_theory.over
873873c9dcd630e3533c1c2677cbda7a27aa418d
e514e8b939af519a1d5e9b30a850769d058df4e9
/examples/knot_isotopy.lean
1ef6f20882d6e2ad56c279a8e5648c40860a2765
[]
no_license
semorrison/lean-rewrite-search
dca317c5a52e170fb6ffc87c5ab767afb5e3e51a
e804b8f2753366b8957be839908230ee73f9e89f
refs/heads/master
1,624,051,754,485
1,614,160,817,000
1,614,160,817,000
162,660,605
0
1
null
null
null
null
UTF-8
Lean
false
false
6,383
lean
import tactic.rewrite_search inductive slice | pos : ℕ → slice | neg : ℕ → slice | cup : ℕ → slice | cap : ℕ → slice open slice inductive diagram | nil | cons : slice → diagram → diagram infixr ` ~~ `:80 := diagram.cons notation `t[` l:(foldr `, ` (h t, diagram.cons h t) diagram.nil `]`) := l namespace isotopy variable (d : diagram) axiom commute_pos_pos (n m) (h : n ≥ m + 2) : (pos n) ~~ (pos m) ~~ d = (pos m) ~~ (pos n) ~~ d axiom commute_pos_neg (n m) (h : n ≥ m + 2) : (pos n) ~~ (neg m) ~~ d = (neg m) ~~ (pos n) ~~ d axiom commute_neg_pos (n m) (h : n ≥ m + 2) : (neg n) ~~ (pos m) ~~ d = (pos m) ~~ (neg n) ~~ d axiom commute_neg_neg (n m) (h : n ≥ m + 2) : (neg n) ~~ (neg m) ~~ d = (neg m) ~~ (neg n) ~~ d axiom commute_cup_pos (n m) (h : n ≥ m + 2) : (cup n) ~~ (pos m) ~~ d = (pos m) ~~ (cup n) ~~ d axiom commute_cup_neg (n m) (h : n ≥ m + 2) : (cup n) ~~ (neg m) ~~ d = (neg m) ~~ (cup n) ~~ d axiom commute_cap_pos (n m) (h : n ≥ m + 2) : (cap n) ~~ (pos m) ~~ d = (pos m) ~~ (cap n) ~~ d axiom commute_cap_neg (n m) (h : n ≥ m + 2) : (cap n) ~~ (neg m) ~~ d = (neg m) ~~ (cap n) ~~ d axiom commute_pos_cup (n m) (h : n ≥ m) : (pos n) ~~ (cup m) ~~ d = (cup m) ~~ (pos (n+2)) ~~ d axiom commute_pos_cap (n m) (h : n ≥ m + 2) : (pos n) ~~ (cap m) ~~ d = (cap m) ~~ (pos (n-2)) ~~ d axiom commute_neg_cup (n m) (h : n ≥ m) : (neg n) ~~ (cup m) ~~ d = (cup m) ~~ (neg (n+2)) ~~ d axiom commute_neg_cap (n m) (h : n ≥ m + 2) : (neg n) ~~ (cap m) ~~ d = (cap m) ~~ (neg (n-2)) ~~ d axiom commute_cup_cup (n m) (h : n ≥ m) : (cup n) ~~ (cup m) ~~ d = (cup m) ~~ (cup (n+2)) ~~ d axiom commute_cup_cap (n m) (h : n ≥ m + 2) : (cup n) ~~ (cap m) ~~ d = (cap m) ~~ (cup (n-2)) ~~ d axiom commute_cap_cup (n m) (h : n ≥ m) : (cap n) ~~ (cup m) ~~ d = (cup m) ~~ (cap (n+2)) ~~ d axiom commute_cap_cap (n m) (h : n ≥ m + 2) : (cap n) ~~ (cap m) ~~ d = (cap m) ~~ (cap (n-2)) ~~ d axiom zigzag_left (n : ℕ) : (cup n) ~~ (cap (n+1)) ~~ d = d axiom zigzag_right (n : ℕ) : (cup (n+1)) ~~ (cap n) ~~ d = d axiom R2_east (n : ℕ) : (neg n) ~~ (pos n) ~~ d = d axiom R2_west (n : ℕ) : (pos n) ~~ (neg n) ~~ d = d axiom R2_north (n : ℕ) : (cup (n+1)) ~~ (pos n) ~~ (neg (n+2)) ~~ cap(n+1) ~~ d = (cap n) ~~ (cup n) ~~ d axiom R2_south (n : ℕ) : (cup (n+1)) ~~ (neg n) ~~ (pos (n+2)) ~~ cap(n+1) ~~ d = (cap n) ~~ (cup n) ~~ d axiom R1_pos_east (n : ℕ) : (cup (n+1)) ~~ (pos n) ~~ (cap (n+1)) ~~ d = d axiom R1_neg_east (n : ℕ) : (cup (n+1)) ~~ (neg n) ~~ (cap (n+1)) ~~ d = d axiom R1_pos_west (n : ℕ) : (cup n) ~~ (pos (n+1)) ~~ (cap n) ~~ d = d axiom R1_neg_west (n : ℕ) : (cup n) ~~ (neg (n+1)) ~~ (cap n) ~~ d = d axiom R1_pos_north (n : ℕ) : (pos n) ~~ (cap n) ~~ d = (cap n) ~~ d axiom R1_neg_north (n : ℕ) : (neg n) ~~ (cap n) ~~ d = (cap n) ~~ d axiom R1_pos_south (n : ℕ) : (cup n) ~~ (pos n) ~~ d = (cup n) ~~ d axiom R1_neg_south (n : ℕ) : (cup n) ~~ (neg n) ~~ d = (cup n) ~~ d axiom R3_pos_pos_pos (n : ℕ) : (pos n) ~~ (pos (n+1)) ~~ (pos n) ~~ d = (pos (n+1)) ~~ (pos n) ~~ (pos (n+1)) ~~ d axiom R3_pos_pos_neg (n : ℕ) : (pos n) ~~ (pos (n+1)) ~~ (neg n) ~~ d = (neg (n+1)) ~~ (pos n) ~~ (pos (n+1)) ~~ d axiom R3_pos_neg_neg (n : ℕ) : (pos n) ~~ (neg (n+1)) ~~ (neg n) ~~ d = (neg (n+1)) ~~ (neg n) ~~ (pos (n+1)) ~~ d axiom R3_neg_pos_pos (n : ℕ) : (neg n) ~~ (pos (n+1)) ~~ (pos n) ~~ d = (pos (n+1)) ~~ (pos n) ~~ (neg (n+1)) ~~ d axiom R3_neg_neg_pos (n : ℕ) : (neg n) ~~ (neg (n+1)) ~~ (pos n) ~~ d = (pos (n+1)) ~~ (neg n) ~~ (neg (n+1)) ~~ d axiom R3_neg_neg_neg (n : ℕ) : (neg n) ~~ (neg (n+1)) ~~ (neg n) ~~ d = (neg (n+1)) ~~ (neg n) ~~ (neg (n+1)) ~~ d axiom cap_over (n : ℕ) : (pos n) ~~ (cap (n+1)) ~~ d = (neg (n+1)) ~~ (cap n) ~~ d axiom cap_under (n : ℕ) : (neg n) ~~ (cap (n+1)) ~~ d = (pos (n+1)) ~~ (cap n) ~~ d axiom cup_over (n : ℕ) : (cup (n+1)) ~~ (neg n) ~~ d = (cup n) ~~ (pos (n+1)) ~~ d axiom cup_under (n : ℕ) : (cup (n+1)) ~~ (pos n) ~~ d = (cup n) ~~ (neg (n+1)) ~~ d -- axiom rotate_pos_clockwise (n : ℕ) : (cup n) ~~ (pos (n+1)) ~~ (cap (n+2)) ~~ d = (neg n) ~~ d -- axiom rotate_neg_clockwise (n : ℕ) : (cup n) ~~ (neg (n+1)) ~~ (cap (n+2)) ~~ d = (pos n) ~~ d -- axiom rotate_pos_widdershins (n : ℕ) : (cup (n+2)) ~~ (pos (n+1)) ~~ (cap n) ~~ d = (neg n) ~~ d -- axiom rotate_neg_widdershins (n : ℕ) : (cup (n+2)) ~~ (neg (n+1)) ~~ (cap n) ~~ d = (pos n) ~~ d attribute [search] commute_pos_pos commute_pos_neg commute_neg_pos commute_neg_neg attribute [search] commute_cup_pos commute_cup_neg commute_cap_pos commute_cap_neg attribute [search] commute_pos_cup commute_pos_cap commute_neg_cup commute_neg_cap attribute [search] commute_cup_cup commute_cup_cap commute_cap_cup commute_cap_cap attribute [search] zigzag_left zigzag_right attribute [search] cap_over cap_under cup_over cup_under attribute [search] R1_pos_east R1_neg_east R1_pos_west R1_neg_west R1_pos_north R1_neg_north R1_pos_south R1_neg_south attribute [search] R2_east R2_west R2_north R2_south attribute [search] R3_pos_pos_pos R3_pos_pos_neg R3_pos_neg_neg R3_neg_pos_pos R3_neg_neg_pos R3_neg_neg_neg -- attribute [search] rotate_pos_clockwise rotate_neg_clockwise rotate_pos_widdershins rotate_neg_widdershins end isotopy open isotopy open tactic meta def isotopy := `[rewrite_search_using [`search] { discharger := `[norm_num], simplifier := norm_num.derive, explain := tt }] meta def isotopy' := `[rewrite_search_using [`search] { discharger := `[norm_num], simplifier := norm_num.derive, trace := tt, no visualiser, explain := tt }] lemma commute_1 : t[pos 0, neg 2, pos 4] = t[pos 4, neg 2, pos 0] := by isotopy lemma commute_2 : t[cup 0, pos 2] = t[pos 0, cup 0] := by isotopy lemma commute_3 : t[cup 2, cap 0] = t[cup 0, cap 2] := by isotopy lemma bulge : t[cup 1, cap 0, cup 0, cap 1] = t[] := by isotopy lemma R2_north : t[cup 1, pos 0, neg 2, cap 1] = t[cap 0, cup 0] := by isotopy lemma twists : t[cup 0, cup 2, pos 0, pos 2, cap 1, cap 0] = t[cup 0, cap 0] := by isotopy -- begin -- rw commute_cup_pos, -- rw R1_pos_south, -- rw R1_pos_south, -- rw zigzag_right, -- norm_num -- end lemma rotate : t[cup 0, pos 1, cap 2] = t[neg 0] := by isotopy -- lemma recognise_trefoil : t[cup 0, cup 1, pos 0, pos 0, pos 0, cap 1, cap 0] = t[cup 0, cup 2, neg 1, pos 0, pos 2, cap 1, cap 0] := by isotopy
732dda19ba4099a0aa5a18b14528c13e06b454d4
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/init/meta/rb_map.lean
b364c9e39184fcc420c4ada5ba313bbb38413bf3
[ "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
4,194
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, Jeremy Avigad -/ prelude import init.ordering init.meta.name init.meta.format meta_constant {u₁ u₂} rb_map : Type u₁ → Type u₂ → Type (max u₁ u₂ 1) namespace rb_map meta_constant mk_core {key : Type} (data : Type) : (key → key → ordering) → rb_map key data meta_constant size {key : Type} {data : Type} : rb_map key data → nat meta_constant insert {key : Type} {data : Type} : rb_map key data → key → data → rb_map key data meta_constant erase {key : Type} {data : Type} : rb_map key data → key → rb_map key data meta_constant contains {key : Type} {data : Type} : rb_map key data → key → bool meta_constant find {key : Type} {data : Type} : rb_map key data → key → option data meta_constant min {key : Type} {data : Type} : rb_map key data → option data meta_constant max {key : Type} {data : Type} : rb_map key data → option data meta_constant fold {key : Type} {data : Type} {A :Type} : rb_map key data → A → (key → data → A → A) → A attribute [inline] meta_definition mk (key : Type) [has_ordering key] (data : Type) : rb_map key data := mk_core data has_ordering.cmp open list meta_definition of_list {key : Type} {data : Type} [has_ordering key] : list (key × data) → rb_map key data | [] := mk key data | ((k, v)::ls) := insert (of_list ls) k v end rb_map attribute [reducible] meta_definition nat_map (data : Type) := rb_map nat data namespace nat_map export rb_map (hiding mk) attribute [inline] meta_definition mk (data : Type) : nat_map data := rb_map.mk nat data end nat_map attribute [reducible] meta_definition name_map (data : Type) := rb_map name data namespace name_map export rb_map (hiding mk) attribute [inline] meta_definition mk (data : Type) : name_map data := rb_map.mk name data end name_map open rb_map prod section open format variables {key : Type} {data : Type} [has_to_format key] [has_to_format data] private meta_definition format_key_data (k : key) (d : data) (first : bool) : format := (if first = tt then to_fmt "" else to_fmt "," ++ line) ++ to_fmt k ++ space ++ to_fmt "←" ++ space ++ to_fmt d attribute [instance] meta_definition rb_map_has_to_format : has_to_format (rb_map key data) := has_to_format.mk (λ m, group (to_fmt "⟨" ++ nest 1 (pr₁ (fold m (to_fmt "", tt) (λ k d p, (pr₁ p ++ format_key_data k d (pr₂ p), ff)))) ++ to_fmt "⟩")) end section variables {key : Type} {data : Type} [has_to_string key] [has_to_string data] private meta_definition key_data_to_string (k : key) (d : data) (first : bool) : string := (if first = tt then "" else ", ") ++ to_string k ++ " ← " ++ to_string d attribute [instance] meta_definition rb_map_has_to_string : has_to_string (rb_map key data) := has_to_string.mk (λ m, "⟨" ++ (pr₁ (fold m ("", tt) (λ k d p, (pr₁ p ++ key_data_to_string k d (pr₂ p), ff)))) ++ "⟩") end /- a variant of rb_maps that stores a list of elements for each key. "find" returns the list of elements in the opposite order that they were inserted. -/ meta_definition rb_lmap (key : Type) (data : Type) : Type := rb_map key (list data) namespace rb_lmap protected meta_definition mk (key : Type) [has_ordering key] (data : Type) : rb_lmap key data := rb_map.mk key (list data) meta_definition insert {key : Type} {data : Type} (rbl : rb_lmap key data) (k : key) (d : data) : rb_lmap key data := match (rb_map.find rbl k) with | none := rb_map.insert rbl k [d] | (some l) := rb_map.insert (rb_map.erase rbl k) k (d :: l) end meta_definition erase {key : Type} {data : Type} (rbl : rb_lmap key data) (k : key) : rb_lmap key data := rb_map.erase rbl k meta_definition contains {key : Type} {data : Type} (rbl : rb_lmap key data) (k : key) : bool := rb_map.contains rbl k meta_definition find {key : Type} {data : Type} (rbl : rb_lmap key data) (k : key) : list data := match (rb_map.find rbl k) with | none := [] | (some l) := l end end rb_lmap
311de36c44e623f2c4d474d06f5988617883dda8
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/hott/init/trunc.hlean
4767025f287d30a061ea66b4a80323ac145a4dd6
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,178
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Floris van Doorn Definition of is_trunc (n-truncatedness) Ported from Coq HoTT. -/ --TODO: can we replace some definitions with a hprop as codomain by theorems? prelude import .logic .equiv .types .pathover open eq nat sigma unit namespace is_trunc /- Truncation levels -/ inductive trunc_index : Type₀ := | minus_two : trunc_index | succ : trunc_index → trunc_index /- notation for trunc_index is -2, -1, 0, 1, ... from 0 and up this comes from a coercion from num to trunc_index (via nat) -/ postfix ` .+1`:(max+1) := trunc_index.succ postfix ` .+2`:(max+1) := λn, (n .+1 .+1) notation `-2` := trunc_index.minus_two notation `-1` := -2.+1 -- ISSUE: -1 gets printed as -2.+1 export [coercions] nat notation `ℕ₋₂` := trunc_index namespace trunc_index definition add (n m : trunc_index) : trunc_index := trunc_index.rec_on m n (λ k l, l .+1) definition leq (n m : trunc_index) : Type₀ := trunc_index.rec_on n (λm, unit) (λ n p m, trunc_index.rec_on m (λ p, empty) (λ m q p, p m) p) m infix <= := trunc_index.leq infix ≤ := trunc_index.leq end trunc_index infix `+2+`:65 := trunc_index.add namespace trunc_index definition succ_le_succ {n m : trunc_index} (H : n ≤ m) : n.+1 ≤ m.+1 := H definition le_of_succ_le_succ {n m : trunc_index} (H : n.+1 ≤ m.+1) : n ≤ m := H definition minus_two_le (n : trunc_index) : -2 ≤ n := star definition le.refl (n : trunc_index) : n ≤ n := by induction n with n IH; exact star; exact IH definition empty_of_succ_le_minus_two {n : trunc_index} (H : n .+1 ≤ -2) : empty := H end trunc_index definition trunc_index.of_nat [coercion] [reducible] (n : nat) : trunc_index := (nat.rec_on n -2 (λ n k, k.+1)).+2 definition sub_two [reducible] (n : nat) : trunc_index := nat.rec_on n -2 (λ n k, k.+1) postfix ` .-2`:(max+1) := sub_two /- truncated types -/ /- Just as in Coq HoTT we define an internal version of contractibility and is_trunc, but we only use `is_trunc` and `is_contr` -/ structure contr_internal (A : Type) := (center : A) (center_eq : Π(a : A), center = a) definition is_trunc_internal (n : trunc_index) : Type → Type := trunc_index.rec_on n (λA, contr_internal A) (λn trunc_n A, (Π(x y : A), trunc_n (x = y))) end is_trunc open is_trunc structure is_trunc [class] (n : trunc_index) (A : Type) := (to_internal : is_trunc_internal n A) open nat num is_trunc.trunc_index namespace is_trunc abbreviation is_contr := is_trunc -2 abbreviation is_hprop := is_trunc -1 abbreviation is_hset := is_trunc 0 variables {A B : Type} definition is_trunc_succ_intro (A : Type) (n : trunc_index) [H : ∀x y : A, is_trunc n (x = y)] : is_trunc n.+1 A := is_trunc.mk (λ x y, !is_trunc.to_internal) definition is_trunc_eq [instance] [priority 1200] (n : trunc_index) [H : is_trunc (n.+1) A] (x y : A) : is_trunc n (x = y) := is_trunc.mk (is_trunc.to_internal (n.+1) A x y) /- contractibility -/ definition is_contr.mk (center : A) (center_eq : Π(a : A), center = a) : is_contr A := is_trunc.mk (contr_internal.mk center center_eq) definition center (A : Type) [H : is_contr A] : A := contr_internal.center (is_trunc.to_internal -2 A) definition center_eq [H : is_contr A] (a : A) : !center = a := contr_internal.center_eq (is_trunc.to_internal -2 A) a definition eq_of_is_contr [H : is_contr A] (x y : A) : x = y := (center_eq x)⁻¹ ⬝ (center_eq y) definition hprop_eq_of_is_contr {A : Type} [H : is_contr A] {x y : A} (p q : x = y) : p = q := have K : ∀ (r : x = y), eq_of_is_contr x y = r, from (λ r, eq.rec_on r !con.left_inv), (K p)⁻¹ ⬝ K q theorem is_contr_eq {A : Type} [H : is_contr A] (x y : A) : is_contr (x = y) := is_contr.mk !eq_of_is_contr (λ p, !hprop_eq_of_is_contr) local attribute is_contr_eq [instance] /- truncation is upward close -/ -- n-types are also (n+1)-types theorem is_trunc_succ [instance] [priority 900] (A : Type) (n : trunc_index) [H : is_trunc n A] : is_trunc (n.+1) A := trunc_index.rec_on n (λ A (H : is_contr A), !is_trunc_succ_intro) (λ n IH A (H : is_trunc (n.+1) A), @is_trunc_succ_intro _ _ (λ x y, IH _ _)) A H --in the proof the type of H is given explicitly to make it available for class inference theorem is_trunc_of_leq.{l} (A : Type.{l}) {n m : trunc_index} (Hnm : n ≤ m) [Hn : is_trunc n A] : is_trunc m A := have base : ∀k A, k ≤ -2 → is_trunc k A → (is_trunc -2 A), from λ k A, trunc_index.cases_on k (λh1 h2, h2) (λk h1 h2, empty.elim (trunc_index.empty_of_succ_le_minus_two h1)), have step : Π (m : trunc_index) (IHm : Π (n : trunc_index) (A : Type), n ≤ m → is_trunc n A → is_trunc m A) (n : trunc_index) (A : Type) (Hnm : n ≤ m .+1) (Hn : is_trunc n A), is_trunc m .+1 A, from λm IHm n, trunc_index.rec_on n (λA Hnm Hn, @is_trunc_succ A m (IHm -2 A star Hn)) (λn IHn A Hnm (Hn : is_trunc n.+1 A), @is_trunc_succ_intro A m (λx y, IHm n (x = y) (trunc_index.le_of_succ_le_succ Hnm) _)), trunc_index.rec_on m base step n A Hnm Hn definition is_trunc_of_imp_is_trunc {n : trunc_index} (H : A → is_trunc (n.+1) A) : is_trunc (n.+1) A := @is_trunc_succ_intro _ _ (λx y, @is_trunc_eq _ _ (H x) x y) definition is_trunc_of_imp_is_trunc_of_leq {n : trunc_index} (Hn : -1 ≤ n) (H : A → is_trunc n A) : is_trunc n A := trunc_index.rec_on n (λHn H, empty.rec _ Hn) (λn IH Hn, is_trunc_of_imp_is_trunc) Hn H -- these must be definitions, because we need them to compute sometimes definition is_trunc_of_is_contr (A : Type) (n : trunc_index) [H : is_contr A] : is_trunc n A := trunc_index.rec_on n H _ definition is_trunc_succ_of_is_hprop (A : Type) (n : trunc_index) [H : is_hprop A] : is_trunc (n.+1) A := is_trunc_of_leq A (show -1 ≤ n.+1, from star) definition is_trunc_succ_succ_of_is_hset (A : Type) (n : trunc_index) [H : is_hset A] : is_trunc (n.+2) A := is_trunc_of_leq A (show 0 ≤ n.+2, from star) /- hprops -/ definition is_hprop.elim [H : is_hprop A] (x y : A) : x = y := !center definition is_contr_of_inhabited_hprop {A : Type} [H : is_hprop A] (x : A) : is_contr A := is_contr.mk x (λy, !is_hprop.elim) theorem is_hprop_of_imp_is_contr {A : Type} (H : A → is_contr A) : is_hprop A := @is_trunc_succ_intro A -2 (λx y, have H2 [visible] : is_contr A, from H x, !is_contr_eq) theorem is_hprop.mk {A : Type} (H : ∀x y : A, x = y) : is_hprop A := is_hprop_of_imp_is_contr (λ x, is_contr.mk x (H x)) theorem is_hprop_elim_self {A : Type} {H : is_hprop A} (x : A) : is_hprop.elim x x = idp := !is_hprop.elim /- hsets -/ theorem is_hset.mk (A : Type) (H : ∀(x y : A) (p q : x = y), p = q) : is_hset A := @is_trunc_succ_intro _ _ (λ x y, is_hprop.mk (H x y)) definition is_hset.elim [H : is_hset A] ⦃x y : A⦄ (p q : x = y) : p = q := !is_hprop.elim /- instances -/ definition is_contr_sigma_eq [instance] [priority 800] {A : Type} (a : A) : is_contr (Σ(x : A), a = x) := is_contr.mk (sigma.mk a idp) (λp, sigma.rec_on p (λ b q, eq.rec_on q idp)) definition is_contr_sigma_eq' [instance] [priority 800] {A : Type} (a : A) : is_contr (Σ(x : A), x = a) := is_contr.mk (sigma.mk a idp) (λp, sigma.rec_on p (λ b q, eq.rec_on q idp)) definition is_contr_unit : is_contr unit := is_contr.mk star (λp, unit.rec_on p idp) definition is_hprop_empty : is_hprop empty := is_hprop.mk (λx, !empty.elim x) local attribute is_contr_unit is_hprop_empty [instance] definition is_trunc_unit [instance] (n : trunc_index) : is_trunc n unit := !is_trunc_of_is_contr definition is_trunc_empty [instance] (n : trunc_index) : is_trunc (n.+1) empty := !is_trunc_succ_of_is_hprop /- interaction with equivalences -/ section open is_equiv equiv --should we remove the following two theorems as they are special cases of --"is_trunc_is_equiv_closed" definition is_contr_is_equiv_closed (f : A → B) [Hf : is_equiv f] [HA: is_contr A] : (is_contr B) := is_contr.mk (f (center A)) (λp, eq_of_eq_inv !center_eq) definition is_contr_equiv_closed (H : A ≃ B) [HA: is_contr A] : is_contr B := is_contr_is_equiv_closed (to_fun H) definition equiv_of_is_contr_of_is_contr [HA : is_contr A] [HB : is_contr B] : A ≃ B := equiv.mk (λa, center B) (is_equiv.adjointify (λa, center B) (λb, center A) center_eq center_eq) theorem is_trunc_is_equiv_closed (n : trunc_index) (f : A → B) [H : is_equiv f] [HA : is_trunc n A] : is_trunc n B := trunc_index.rec_on n (λA (HA : is_contr A) B f (H : is_equiv f), is_contr_is_equiv_closed f) (λn IH A (HA : is_trunc n.+1 A) B f (H : is_equiv f), @is_trunc_succ_intro _ _ (λ x y : B, IH (f⁻¹ x = f⁻¹ y) _ (x = y) (ap f⁻¹)⁻¹ !is_equiv_inv)) A HA B f H definition is_trunc_is_equiv_closed_rev (n : trunc_index) (f : A → B) [H : is_equiv f] [HA : is_trunc n B] : is_trunc n A := is_trunc_is_equiv_closed n f⁻¹ definition is_trunc_equiv_closed (n : trunc_index) (f : A ≃ B) [HA : is_trunc n A] : is_trunc n B := is_trunc_is_equiv_closed n (to_fun f) definition is_trunc_equiv_closed_rev (n : trunc_index) (f : A ≃ B) [HA : is_trunc n B] : is_trunc n A := is_trunc_is_equiv_closed n (to_inv f) definition is_equiv_of_is_hprop [constructor] [HA : is_hprop A] [HB : is_hprop B] (f : A → B) (g : B → A) : is_equiv f := is_equiv.mk f g (λb, !is_hprop.elim) (λa, !is_hprop.elim) (λa, !is_hset.elim) definition equiv_of_is_hprop [constructor] [HA : is_hprop A] [HB : is_hprop B] (f : A → B) (g : B → A) : A ≃ B := equiv.mk f (is_equiv_of_is_hprop f g) definition equiv_of_iff_of_is_hprop [unfold 5] [HA : is_hprop A] [HB : is_hprop B] (H : A ↔ B) : A ≃ B := equiv_of_is_hprop (iff.elim_left H) (iff.elim_right H) /- truncatedness of lift -/ definition is_trunc_lift [instance] [priority 1450] (A : Type) (n : trunc_index) [H : is_trunc n A] : is_trunc n (lift A) := is_trunc_equiv_closed _ !equiv_lift end /- interaction with the Unit type -/ open equiv -- A contractible type is equivalent to [Unit]. *) variable (A) definition equiv_unit_of_is_contr [H : is_contr A] : A ≃ unit := equiv.MK (λ (x : A), ⋆) (λ (u : unit), center A) (λ (u : unit), unit.rec_on u idp) (λ (x : A), center_eq x) /- interaction with pathovers -/ variable {A} variables {C : A → Type} {a a₂ : A} (p : a = a₂) (c : C a) (c₂ : C a₂) definition is_hprop.elimo [H : is_hprop (C a)] : c =[p] c₂ := pathover_of_eq_tr !is_hprop.elim definition is_trunc_pathover [instance] (n : trunc_index) [H : is_trunc (n.+1) (C a)] : is_trunc n (c =[p] c₂) := is_trunc_equiv_closed_rev n !pathover_equiv_eq_tr variables {p c c₂} theorem is_hset.elimo (q q' : c =[p] c₂) [H : is_hset (C a)] : q = q' := !is_hprop.elim -- TODO: port "Truncated morphisms" /- truncated universe -/ -- TODO: move to root namespace? structure trunctype (n : trunc_index) := (carrier : Type) (struct : is_trunc n carrier) attribute trunctype.carrier [coercion] attribute trunctype.struct [instance] [priority 1400] notation n `-Type` := trunctype n abbreviation hprop := -1-Type abbreviation hset := 0-Type protected abbreviation hprop.mk := @trunctype.mk -1 protected abbreviation hset.mk := @trunctype.mk (-1.+1) protected abbreviation trunctype.mk' [parsing_only] (n : trunc_index) (A : Type) [H : is_trunc n A] : n-Type := trunctype.mk A H definition tlift.{u v} [constructor] {n : trunc_index} (A : trunctype.{u} n) : trunctype.{max u v} n := trunctype.mk (lift A) (is_trunc_lift _ _) end is_trunc
7974e29f07b607719bcf40b8fdee3c4eec8f60f8
94e33a31faa76775069b071adea97e86e218a8ee
/src/measure_theory/probability_mass_function/basic.lean
b5c04e85c793ad0d82544f0b7d1ad16434ac22f9
[ "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
9,236
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, Devon Tuma -/ import topology.instances.ennreal import measure_theory.measure.measure_space /-! # Probability mass functions This file is about probability mass functions or discrete probability measures: a function `α → ℝ≥0` such that the values have (infinite) sum `1`. Construction of monadic `pure` and `bind` is found in `probability_mass_function/monad.lean`, other constructions of `pmf`s are found in `probability_mass_function/constructions.lean`. Given `p : pmf α`, `pmf.to_outer_measure` constructs an `outer_measure` on `α`, by assigning each set the sum of the probabilities of each of its elements. Under this outer measure, every set is Carathéodory-measurable, so we can further extend this to a `measure` on `α`, see `pmf.to_measure`. `pmf.to_measure.is_probability_measure` shows this associated measure is a probability measure. ## Tags probability mass function, discrete probability measure -/ noncomputable theory variables {α β γ : Type*} open_locale classical big_operators nnreal ennreal /-- A probability mass function, or discrete probability measures is a function `α → ℝ≥0` such that the values have (infinite) sum `1`. -/ def {u} pmf (α : Type u) : Type u := { f : α → ℝ≥0 // has_sum f 1 } namespace pmf instance : has_coe_to_fun (pmf α) (λ p, α → ℝ≥0) := ⟨λ p a, p.1 a⟩ @[ext] protected lemma ext : ∀ {p q : pmf α}, (∀ a, p a = q a) → p = q | ⟨f, hf⟩ ⟨g, hg⟩ eq := subtype.eq $ funext eq lemma has_sum_coe_one (p : pmf α) : has_sum p 1 := p.2 lemma summable_coe (p : pmf α) : summable p := (p.has_sum_coe_one).summable @[simp] lemma tsum_coe (p : pmf α) : ∑' a, p a = 1 := p.has_sum_coe_one.tsum_eq /-- The support of a `pmf` is the set where it is nonzero. -/ def support (p : pmf α) : set α := function.support p @[simp] lemma mem_support_iff (p : pmf α) (a : α) : a ∈ p.support ↔ p a ≠ 0 := iff.rfl lemma apply_eq_zero_iff (p : pmf α) (a : α) : p a = 0 ↔ a ∉ p.support := by rw [mem_support_iff, not_not] lemma coe_le_one (p : pmf α) (a : α) : p a ≤ 1 := has_sum_le (by { intro b, split_ifs; simp only [h, zero_le'] }) (has_sum_ite_eq a (p a)) (has_sum_coe_one p) section outer_measure open measure_theory measure_theory.outer_measure /-- Construct an `outer_measure` from a `pmf`, by assigning measure to each set `s : set α` equal to the sum of `p x` for for each `x ∈ α` -/ def to_outer_measure (p : pmf α) : outer_measure α := outer_measure.sum (λ (x : α), p x • dirac x) variables (p : pmf α) (s t : set α) lemma to_outer_measure_apply : p.to_outer_measure s = ∑' x, s.indicator (coe ∘ p) x := tsum_congr (λ x, smul_dirac_apply (p x) x s) lemma to_outer_measure_apply' : p.to_outer_measure s = ↑(∑' (x : α), s.indicator p x) := by simp only [ennreal.coe_tsum (nnreal.indicator_summable (summable_coe p) s), ennreal.coe_indicator, to_outer_measure_apply] @[simp] lemma to_outer_measure_apply_finset (s : finset α) : p.to_outer_measure s = ∑ x in s, ↑(p x) := begin refine (to_outer_measure_apply p s).trans ((@tsum_eq_sum _ _ _ _ _ _ s _).trans _), { exact λ x hx, set.indicator_of_not_mem hx _ }, { exact finset.sum_congr rfl (λ x hx, set.indicator_of_mem hx _) } end lemma to_outer_measure_apply_eq_zero_iff : p.to_outer_measure s = 0 ↔ disjoint p.support s := begin rw [to_outer_measure_apply', ennreal.coe_eq_zero, tsum_eq_zero_iff (nnreal.indicator_summable (summable_coe p) s)], exact function.funext_iff.symm.trans set.indicator_eq_zero', end lemma to_outer_measure_apply_eq_one_iff : p.to_outer_measure s = 1 ↔ p.support ⊆ s := begin rw [to_outer_measure_apply', ennreal.coe_eq_one], refine ⟨λ h a ha, _, λ h, _⟩, { have hsp : ∀ x, s.indicator p x ≤ p x := λ _, set.indicator_apply_le (λ _, le_rfl), have := λ hpa, ne_of_lt (nnreal.tsum_lt_tsum hsp hpa p.summable_coe) (h.trans p.tsum_coe.symm), exact not_not.1 (λ has, ha $ set.indicator_apply_eq_self.1 (le_antisymm (set.indicator_apply_le $ λ _, le_rfl) $ le_of_not_lt $ this) has) }, { suffices : ∀ x, x ∉ s → p x = 0, from trans (tsum_congr $ λ a, (set.indicator_apply s p a).trans (ite_eq_left_iff.2 $ symm ∘ (this a))) p.tsum_coe, exact λ a ha, (p.apply_eq_zero_iff a).2 $ set.not_mem_subset h ha } end @[simp] lemma to_outer_measure_apply_inter_support : p.to_outer_measure (s ∩ p.support) = p.to_outer_measure s := by simp only [to_outer_measure_apply', ennreal.coe_eq_coe, pmf.support, set.indicator_inter_support] /-- Slightly stronger than `outer_measure.mono` having an intersection with `p.support` -/ lemma to_outer_measure_mono {s t : set α} (h : s ∩ p.support ⊆ t) : p.to_outer_measure s ≤ p.to_outer_measure t := le_trans (le_of_eq (to_outer_measure_apply_inter_support p s).symm) (p.to_outer_measure.mono h) lemma to_outer_measure_apply_eq_of_inter_support_eq {s t : set α} (h : s ∩ p.support = t ∩ p.support) : p.to_outer_measure s = p.to_outer_measure t := le_antisymm (p.to_outer_measure_mono (h.symm ▸ (set.inter_subset_left t p.support))) (p.to_outer_measure_mono (h ▸ (set.inter_subset_left s p.support))) @[simp] lemma to_outer_measure_apply_fintype [fintype α] : p.to_outer_measure s = ↑(∑ x, (s.indicator p x)) := (p.to_outer_measure_apply' s).trans (ennreal.coe_eq_coe.2 $ tsum_eq_sum (λ x h, absurd (finset.mem_univ x) h)) @[simp] lemma to_outer_measure_caratheodory (p : pmf α) : (to_outer_measure p).caratheodory = ⊤ := begin refine (eq_top_iff.2 $ le_trans (le_Inf $ λ x hx, _) (le_sum_caratheodory _)), obtain ⟨y, hy⟩ := hx, exact ((le_of_eq (dirac_caratheodory y).symm).trans (le_smul_caratheodory _ _)).trans (le_of_eq hy), end end outer_measure section measure open measure_theory /-- Since every set is Carathéodory-measurable under `pmf.to_outer_measure`, we can further extend this `outer_measure` to a `measure` on `α` -/ def to_measure [measurable_space α] (p : pmf α) : measure α := p.to_outer_measure.to_measure ((to_outer_measure_caratheodory p).symm ▸ le_top) variables [measurable_space α] (p : pmf α) (s t : set α) lemma to_outer_measure_apply_le_to_measure_apply : p.to_outer_measure s ≤ p.to_measure s := le_to_measure_apply p.to_outer_measure _ s lemma to_measure_apply_eq_to_outer_measure_apply (hs : measurable_set s) : p.to_measure s = p.to_outer_measure s := to_measure_apply p.to_outer_measure _ hs lemma to_measure_apply (hs : measurable_set s) : p.to_measure s = ∑' x, s.indicator (coe ∘ p) x := (p.to_measure_apply_eq_to_outer_measure_apply s hs).trans (p.to_outer_measure_apply s) lemma to_measure_apply' (hs : measurable_set s) : p.to_measure s = ↑(∑' x, s.indicator p x) := (p.to_measure_apply_eq_to_outer_measure_apply s hs).trans (p.to_outer_measure_apply' s) lemma to_measure_apply_eq_one_iff (hs : measurable_set s) : p.to_measure s = 1 ↔ p.support ⊆ s := (p.to_measure_apply_eq_to_outer_measure_apply s hs : p.to_measure s = p.to_outer_measure s).symm ▸ (p.to_outer_measure_apply_eq_one_iff s) @[simp] lemma to_measure_apply_inter_support (hs : measurable_set s) (hp : measurable_set p.support) : p.to_measure (s ∩ p.support) = p.to_measure s := by simp [p.to_measure_apply_eq_to_outer_measure_apply s hs, p.to_measure_apply_eq_to_outer_measure_apply _ (hs.inter hp)] lemma to_measure_mono {s t : set α} (hs : measurable_set s) (ht : measurable_set t) (h : s ∩ p.support ⊆ t) : p.to_measure s ≤ p.to_measure t := by simpa only [p.to_measure_apply_eq_to_outer_measure_apply, hs, ht] using to_outer_measure_mono p h lemma to_measure_apply_eq_of_inter_support_eq {s t : set α} (hs : measurable_set s) (ht : measurable_set t) (h : s ∩ p.support = t ∩ p.support) : p.to_measure s = p.to_measure t := by simpa only [p.to_measure_apply_eq_to_outer_measure_apply, hs, ht] using to_outer_measure_apply_eq_of_inter_support_eq p h section measurable_singleton_class variables [measurable_singleton_class α] @[simp] lemma to_measure_apply_finset (s : finset α) : p.to_measure s = ∑ x in s, (p x : ℝ≥0∞) := (p.to_measure_apply_eq_to_outer_measure_apply s s.measurable_set).trans (p.to_outer_measure_apply_finset s) lemma to_measure_apply_of_finite (hs : s.finite) : p.to_measure s = ↑(∑' x, s.indicator p x) := (p.to_measure_apply_eq_to_outer_measure_apply s hs.measurable_set).trans (p.to_outer_measure_apply' s) @[simp] lemma to_measure_apply_fintype [fintype α] : p.to_measure s = ↑(∑ x, s.indicator p x) := (p.to_measure_apply_eq_to_outer_measure_apply s s.to_finite.measurable_set).trans (p.to_outer_measure_apply_fintype s) end measurable_singleton_class /-- The measure associated to a `pmf` by `to_measure` is a probability measure -/ instance to_measure.is_probability_measure (p : pmf α) : is_probability_measure (p.to_measure) := ⟨by simpa only [measurable_set.univ, to_measure_apply_eq_to_outer_measure_apply, set.indicator_univ, to_outer_measure_apply', ennreal.coe_eq_one] using tsum_coe p⟩ end measure end pmf
50d91d7013dc23f539040c39f2a700cf1bbd2bd2
94637389e03c919023691dcd05bd4411b1034aa5
/src/zzz_junk/has_one/has_one.lean
1d68ed5e0733d38459549aa9253420f337fe9fb0
[]
no_license
kevinsullivan/complogic-s21
7c4eef2105abad899e46502270d9829d913e8afc
99039501b770248c8ceb39890be5dfe129dc1082
refs/heads/master
1,682,985,669,944
1,621,126,241,000
1,621,126,241,000
335,706,272
0
38
null
1,618,325,669,000
1,612,374,118,000
Lean
UTF-8
Lean
false
false
481
lean
import ..has_mul.has_mul namespace hidden universe u /- @[class] structure has_one (α : Type u) extends hidden.has_mul α := --(mul : α → α → α) --inherited from has_mul (one: α) -- preview of what's coming (one_mul : ∀ (a : α ), mul one a = a) (mul_one : ∀ (a : α ), mul a one = a ) -- ^^^^^^^^^^^^^^ proposition -- proofs -/ @[class] structure has_one (α : Type u) := --(mul : α → α → α) --inherited from has_mul (one: α) end hidden
99b7d9897e1ae8ade6501457d78a7283d4007132
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/geometry/manifold/charted_space.lean
7b26dd9a9f438849113db419d1663a18edf188d7
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
44,742
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 topology.local_homeomorph /-! # Charted spaces A smooth manifold is a topological space `M` locally modelled on a euclidean space (or a euclidean half-space for manifolds with boundaries, or an infinite dimensional vector space for more general notions of manifolds), i.e., the manifold is covered by open subsets on which there are local homeomorphisms (the charts) going to a model space `H`, and the changes of charts should be smooth maps. In this file, we introduce a general framework describing these notions, where the model space is an arbitrary topological space. We avoid the word *manifold*, which should be reserved for the situation where the model space is a (subset of a) vector space, and use the terminology *charted space* instead. If the changes of charts satisfy some additional property (for instance if they are smooth), then `M` inherits additional structure (it makes sense to talk about smooth manifolds). There are therefore two different ingredients in a charted space: * the set of charts, which is data * the fact that changes of charts belong to some group (in fact groupoid), which is additional Prop. We separate these two parts in the definition: the charted space structure is just the set of charts, and then the different smoothness requirements (smooth manifold, orientable manifold, contact manifold, and so on) are additional properties of these charts. These properties are formalized through the notion of structure groupoid, i.e., a set of local homeomorphisms stable under composition and inverse, to which the change of coordinates should belong. ## Main definitions * `structure_groupoid H` : a subset of local homeomorphisms of `H` stable under composition, inverse and restriction (ex: local diffeos). * `continuous_groupoid H` : the groupoid of all local homeomorphisms of `H` * `charted_space H M` : charted space structure on `M` modelled on `H`, given by an atlas of local homeomorphisms from `M` to `H` whose sources cover `M`. This is a type class. * `has_groupoid M G` : when `G` is a structure groupoid on `H` and `M` is a charted space modelled on `H`, require that all coordinate changes belong to `G`. This is a type class. * `atlas H M` : when `M` is a charted space modelled on `H`, the atlas of this charted space structure, i.e., the set of charts. * `G.maximal_atlas M` : when `M` is a charted space modelled on `H` and admitting `G` as a structure groupoid, one can consider all the local homeomorphisms from `M` to `H` such that changing coordinate from any chart to them belongs to `G`. This is a larger atlas, called the maximal atlas (for the groupoid `G`). * `structomorph G M M'` : the type of diffeomorphisms between the charted spaces `M` and `M'` for the groupoid `G`. We avoid the word diffeomorphism, keeping it for the smooth category. As a basic example, we give the instance `instance charted_space_model_space (H : Type*) [topological_space H] : charted_space H H` saying that a topological space is a charted space over itself, with the identity as unique chart. This charted space structure is compatible with any groupoid. Additional useful definitions: * `pregroupoid H` : a subset of local mas of `H` stable under composition and restriction, but not inverse (ex: smooth maps) * `groupoid_of_pregroupoid` : construct a groupoid from a pregroupoid, by requiring that a map and its inverse both belong to the pregroupoid (ex: construct diffeos from smooth maps) * `chart_at H x` is a preferred chart at `x : M` when `M` has a charted space structure modelled on `H`. * `G.compatible he he'` states that, for any two charts `e` and `e'` in the atlas, the composition of `e.symm` and `e'` belongs to the groupoid `G` when `M` admits `G` as a structure groupoid. * `G.compatible_of_mem_maximal_atlas he he'` states that, for any two charts `e` and `e'` in the maximal atlas associated to the groupoid `G`, the composition of `e.symm` and `e'` belongs to the `G` if `M` admits `G` as a structure groupoid. * `charted_space_core.to_charted_space`: consider a space without a topology, but endowed with a set of charts (which are local equivs) for which the change of coordinates are local homeos. Then one can construct a topology on the space for which the charts become local homeos, defining a genuine charted space structure. ## Implementation notes The atlas in a charted space is *not* a maximal atlas in general: the notion of maximality depends on the groupoid one considers, and changing groupoids changes the maximal atlas. With the current formalization, it makes sense first to choose the atlas, and then to ask whether this precise atlas defines a smooth manifold, an orientable manifold, and so on. A consequence is that structomorphisms between `M` and `M'` do *not* induce a bijection between the atlases of `M` and `M'`: the definition is only that, read in charts, the structomorphism locally belongs to the groupoid under consideration. (This is equivalent to inducing a bijection between elements of the maximal atlas). A consequence is that the invariance under structomorphisms of properties defined in terms of the atlas is not obvious in general, and could require some work in theory (amounting to the fact that these properties only depend on the maximal atlas, for instance). In practice, this does not create any real difficulty. We use the letter `H` for the model space thinking of the case of manifolds with boundary, where the model space is a half space. Manifolds are sometimes defined as topological spaces with an atlas of local diffeomorphisms, and sometimes as spaces with an atlas from which a topology is deduced. We use the former approach: otherwise, there would be an instance from manifolds to topological spaces, which means that any instance search for topological spaces would try to find manifold structures involving a yet unknown model space, leading to problems. However, we also introduce the latter approach, through a structure `charted_space_core` making it possible to construct a topology out of a set of local equivs with compatibility conditions (but we do not register it as an instance). In the definition of a charted space, the model space is written as an explicit parameter as there can be several model spaces for a given topological space. For instance, a complex manifold (modelled over `ℂ^n`) will also be seen sometimes as a real manifold modelled over `ℝ^(2n)`. ## Notations In the locale `manifold`, we denote the composition of local homeomorphisms with `≫ₕ`, and the composition of local equivs with `≫`. -/ noncomputable theory open_locale classical topological_space open filter universes u variables {H : Type u} {H' : Type*} {M : Type*} {M' : Type*} {M'' : Type*} /- Notational shortcut for the composition of local homeomorphisms and local equivs, i.e., `local_homeomorph.trans` and `local_equiv.trans`. Note that, as is usual for equivs, the composition is from left to right, hence the direction of the arrow. -/ localized "infixr ` ≫ₕ `:100 := local_homeomorph.trans" in manifold localized "infixr ` ≫ `:100 := local_equiv.trans" in manifold /- `simp` looks for subsingleton instances at every call. This turns out to be very inefficient, especially in `simp`-heavy parts of the library such as the manifold code. Disable two such instances to speed up things. NB: this is just a hack. TODO: fix `simp` properly. -/ localized "attribute [-instance] unique.subsingleton pi.subsingleton" in manifold open set local_homeomorph /-! ### Structure groupoids-/ section groupoid /-! One could add to the definition of a structure groupoid the fact that the restriction of an element of the groupoid to any open set still belongs to the groupoid. (This is in Kobayashi-Nomizu.) I am not sure I want this, for instance on `H × E` where `E` is a vector space, and the groupoid is made of functions respecting the fibers and linear in the fibers (so that a charted space over this groupoid is naturally a vector bundle) I prefer that the members of the groupoid are always defined on sets of the form `s × E`. There is a typeclass `closed_under_restriction` for groupoids which have the restriction property. The only nontrivial requirement is locality: if a local homeomorphism belongs to the groupoid around each point in its domain of definition, then it belongs to the groupoid. Without this requirement, the composition of structomorphisms does not have to be a structomorphism. Note that this implies that a local homeomorphism with empty source belongs to any structure groupoid, as it trivially satisfies this condition. There is also a technical point, related to the fact that a local homeomorphism is by definition a global map which is a homeomorphism when restricted to its source subset (and its values outside of the source are not relevant). Therefore, we also require that being a member of the groupoid only depends on the values on the source. We use primes in the structure names as we will reformulate them below (without primes) using a `has_mem` instance, writing `e ∈ G` instead of `e ∈ G.members`. -/ /-- A structure groupoid is a set of local homeomorphisms of a topological space stable under composition and inverse. They appear in the definition of the smoothness class of a manifold. -/ structure structure_groupoid (H : Type u) [topological_space H] := (members : set (local_homeomorph H H)) (trans' : ∀e e' : local_homeomorph H H, e ∈ members → e' ∈ members → e ≫ₕ e' ∈ members) (symm' : ∀e : local_homeomorph H H, e ∈ members → e.symm ∈ members) (id_mem' : local_homeomorph.refl H ∈ members) (locality' : ∀e : local_homeomorph H H, (∀x ∈ e.source, ∃s, is_open s ∧ x ∈ s ∧ e.restr s ∈ members) → e ∈ members) (eq_on_source' : ∀ e e' : local_homeomorph H H, e ∈ members → e' ≈ e → e' ∈ members) variable [topological_space H] instance : has_mem (local_homeomorph H H) (structure_groupoid H) := ⟨λ(e : local_homeomorph H H) (G : structure_groupoid H), e ∈ G.members⟩ lemma structure_groupoid.trans (G : structure_groupoid H) {e e' : local_homeomorph H H} (he : e ∈ G) (he' : e' ∈ G) : e ≫ₕ e' ∈ G := G.trans' e e' he he' lemma structure_groupoid.symm (G : structure_groupoid H) {e : local_homeomorph H H} (he : e ∈ G) : e.symm ∈ G := G.symm' e he lemma structure_groupoid.id_mem (G : structure_groupoid H) : local_homeomorph.refl H ∈ G := G.id_mem' lemma structure_groupoid.locality (G : structure_groupoid H) {e : local_homeomorph H H} (h : ∀x ∈ e.source, ∃s, is_open s ∧ x ∈ s ∧ e.restr s ∈ G) : e ∈ G := G.locality' e h lemma structure_groupoid.eq_on_source (G : structure_groupoid H) {e e' : local_homeomorph H H} (he : e ∈ G) (h : e' ≈ e) : e' ∈ G := G.eq_on_source' e e' he h /-- Partial order on the set of groupoids, given by inclusion of the members of the groupoid -/ instance structure_groupoid.partial_order : partial_order (structure_groupoid H) := partial_order.lift structure_groupoid.members (λa b h, by { cases a, cases b, dsimp at h, induction h, refl }) lemma structure_groupoid.le_iff {G₁ G₂ : structure_groupoid H} : G₁ ≤ G₂ ↔ ∀ e, e ∈ G₁ → e ∈ G₂ := iff.rfl /-- The trivial groupoid, containing only the identity (and maps with empty source, as this is necessary from the definition) -/ def id_groupoid (H : Type u) [topological_space H] : structure_groupoid H := { members := {local_homeomorph.refl H} ∪ {e : local_homeomorph H H | e.source = ∅}, trans' := λe e' he he', begin cases he; simp at he he', { simpa only [he, refl_trans]}, { have : (e ≫ₕ e').source ⊆ e.source := sep_subset _ _, rw he at this, have : (e ≫ₕ e') ∈ {e : local_homeomorph H H | e.source = ∅} := disjoint_iff.1 this, exact (mem_union _ _ _).2 (or.inr this) }, end, symm' := λe he, begin cases (mem_union _ _ _).1 he with E E, { finish }, { right, simpa only [e.to_local_equiv.image_source_eq_target.symm] with mfld_simps using E}, end, id_mem' := mem_union_left _ rfl, locality' := λe he, begin cases e.source.eq_empty_or_nonempty with h h, { right, exact h }, { left, rcases h with ⟨x, hx⟩, rcases he x hx with ⟨s, open_s, xs, hs⟩, have x's : x ∈ (e.restr s).source, { rw [restr_source, open_s.interior_eq], exact ⟨hx, xs⟩ }, cases hs, { replace hs : local_homeomorph.restr e s = local_homeomorph.refl H, by simpa only using hs, have : (e.restr s).source = univ, by { rw hs, simp }, change (e.to_local_equiv).source ∩ interior s = univ at this, have : univ ⊆ interior s, by { rw ← this, exact inter_subset_right _ _ }, have : s = univ, by rwa [open_s.interior_eq, univ_subset_iff] at this, simpa only [this, restr_univ] using hs }, { exfalso, rw mem_set_of_eq at hs, rwa hs at x's } }, end, eq_on_source' := λe e' he he'e, begin cases he, { left, have : e = e', { refine eq_of_eq_on_source_univ (setoid.symm he'e) _ _; rw set.mem_singleton_iff.1 he ; refl }, rwa ← this }, { right, change (e.to_local_equiv).source = ∅ at he, rwa [set.mem_set_of_eq, he'e.source_eq] } end } /-- Every structure groupoid contains the identity groupoid -/ instance : order_bot (structure_groupoid H) := { bot := id_groupoid H, bot_le := begin assume u f hf, change f ∈ {local_homeomorph.refl H} ∪ {e : local_homeomorph H H | e.source = ∅} at hf, simp only [singleton_union, mem_set_of_eq, mem_insert_iff] at hf, cases hf, { rw hf, apply u.id_mem }, { apply u.locality, assume x hx, rw [hf, mem_empty_eq] at hx, exact hx.elim } end, ..structure_groupoid.partial_order } instance (H : Type u) [topological_space H] : inhabited (structure_groupoid H) := ⟨id_groupoid H⟩ /-- To construct a groupoid, one may consider classes of local homeos such that both the function and its inverse have some property. If this property is stable under composition, one gets a groupoid. `pregroupoid` bundles the properties needed for this construction, with the groupoid of smooth functions with smooth inverses as an application. -/ structure pregroupoid (H : Type*) [topological_space H] := (property : (H → H) → (set H) → Prop) (comp : ∀{f g u v}, property f u → property g v → is_open u → is_open v → is_open (u ∩ f ⁻¹' v) → property (g ∘ f) (u ∩ f ⁻¹' v)) (id_mem : property id univ) (locality : ∀{f u}, is_open u → (∀x∈u, ∃v, is_open v ∧ x ∈ v ∧ property f (u ∩ v)) → property f u) (congr : ∀{f g : H → H} {u}, is_open u → (∀x∈u, g x = f x) → property f u → property g u) /-- Construct a groupoid of local homeos for which the map and its inverse have some property, from a pregroupoid asserting that this property is stable under composition. -/ def pregroupoid.groupoid (PG : pregroupoid H) : structure_groupoid H := { members := {e : local_homeomorph H H | PG.property e e.source ∧ PG.property e.symm e.target}, trans' := λe e' he he', begin split, { apply PG.comp he.1 he'.1 e.open_source e'.open_source, apply e.continuous_to_fun.preimage_open_of_open e.open_source e'.open_source }, { apply PG.comp he'.2 he.2 e'.open_target e.open_target, apply e'.continuous_inv_fun.preimage_open_of_open e'.open_target e.open_target } end, symm' := λe he, ⟨he.2, he.1⟩, id_mem' := ⟨PG.id_mem, PG.id_mem⟩, locality' := λe he, begin split, { apply PG.locality e.open_source (λx xu, _), rcases he x xu with ⟨s, s_open, xs, hs⟩, refine ⟨s, s_open, xs, _⟩, convert hs.1 using 1, dsimp [local_homeomorph.restr], rw s_open.interior_eq }, { apply PG.locality e.open_target (λx xu, _), rcases he (e.symm x) (e.map_target xu) with ⟨s, s_open, xs, hs⟩, refine ⟨e.target ∩ e.symm ⁻¹' s, _, ⟨xu, xs⟩, _⟩, { exact continuous_on.preimage_open_of_open e.continuous_inv_fun e.open_target s_open }, { rw [← inter_assoc, inter_self], convert hs.2 using 1, dsimp [local_homeomorph.restr], rw s_open.interior_eq } }, end, eq_on_source' := λe e' he ee', begin split, { apply PG.congr e'.open_source ee'.2, simp only [ee'.1, he.1] }, { have A := ee'.symm', apply PG.congr e'.symm.open_source A.2, convert he.2, rw A.1, refl } end } lemma mem_groupoid_of_pregroupoid {PG : pregroupoid H} {e : local_homeomorph H H} : e ∈ PG.groupoid ↔ PG.property e e.source ∧ PG.property e.symm e.target := iff.rfl lemma groupoid_of_pregroupoid_le (PG₁ PG₂ : pregroupoid H) (h : ∀f s, PG₁.property f s → PG₂.property f s) : PG₁.groupoid ≤ PG₂.groupoid := begin refine structure_groupoid.le_iff.2 (λ e he, _), rw mem_groupoid_of_pregroupoid at he ⊢, exact ⟨h _ _ he.1, h _ _ he.2⟩ end lemma mem_pregroupoid_of_eq_on_source (PG : pregroupoid H) {e e' : local_homeomorph H H} (he' : e ≈ e') (he : PG.property e e.source) : PG.property e' e'.source := begin rw ← he'.1, exact PG.congr e.open_source he'.eq_on.symm he, end /-- The pregroupoid of all local maps on a topological space `H` -/ @[reducible] def continuous_pregroupoid (H : Type*) [topological_space H] : pregroupoid H := { property := λf s, true, comp := λf g u v hf hg hu hv huv, trivial, id_mem := trivial, locality := λf u u_open h, trivial, congr := λf g u u_open hcongr hf, trivial } instance (H : Type*) [topological_space H] : inhabited (pregroupoid H) := ⟨continuous_pregroupoid H⟩ /-- The groupoid of all local homeomorphisms on a topological space `H` -/ def continuous_groupoid (H : Type*) [topological_space H] : structure_groupoid H := pregroupoid.groupoid (continuous_pregroupoid H) /-- Every structure groupoid is contained in the groupoid of all local homeomorphisms -/ instance : order_top (structure_groupoid H) := { top := continuous_groupoid H, le_top := λ u f hf, by { split; exact dec_trivial }, ..structure_groupoid.partial_order } /-- A groupoid is closed under restriction if it contains all restrictions of its element local homeomorphisms to open subsets of the source. -/ class closed_under_restriction (G : structure_groupoid H) : Prop := (closed_under_restriction : ∀ {e : local_homeomorph H H}, e ∈ G → ∀ (s : set H), is_open s → e.restr s ∈ G) lemma closed_under_restriction' {G : structure_groupoid H} [closed_under_restriction G] {e : local_homeomorph H H} (he : e ∈ G) {s : set H} (hs : is_open s) : e.restr s ∈ G := closed_under_restriction.closed_under_restriction he s hs /-- The trivial restriction-closed groupoid, containing only local homeomorphisms equivalent to the restriction of the identity to the various open subsets. -/ def id_restr_groupoid : structure_groupoid H := { members := {e | ∃ {s : set H} (h : is_open s), e ≈ local_homeomorph.of_set s h}, trans' := begin rintros e e' ⟨s, hs, hse⟩ ⟨s', hs', hse'⟩, refine ⟨s ∩ s', is_open_inter hs hs', _⟩, have := local_homeomorph.eq_on_source.trans' hse hse', rwa local_homeomorph.of_set_trans_of_set at this, end, symm' := begin rintros e ⟨s, hs, hse⟩, refine ⟨s, hs, _⟩, rw [← of_set_symm], exact local_homeomorph.eq_on_source.symm' hse, end, id_mem' := ⟨univ, is_open_univ, by simp only with mfld_simps⟩, locality' := begin intros e h, refine ⟨e.source, e.open_source, by simp only with mfld_simps, _⟩, intros x hx, rcases h x hx with ⟨s, hs, hxs, s', hs', hes'⟩, have hes : x ∈ (e.restr s).source, { rw e.restr_source, refine ⟨hx, _⟩, rw hs.interior_eq, exact hxs }, simpa only with mfld_simps using local_homeomorph.eq_on_source.eq_on hes' hes, end, eq_on_source' := begin rintros e e' ⟨s, hs, hse⟩ hee', exact ⟨s, hs, setoid.trans hee' hse⟩, end } lemma id_restr_groupoid_mem {s : set H} (hs : is_open s) : of_set s hs ∈ @id_restr_groupoid H _ := ⟨s, hs, by refl⟩ /-- The trivial restriction-closed groupoid is indeed `closed_under_restriction`. -/ instance closed_under_restriction_id_restr_groupoid : closed_under_restriction (@id_restr_groupoid H _) := ⟨ begin rintros e ⟨s', hs', he⟩ s hs, use [s' ∩ s, is_open_inter hs' hs], refine setoid.trans (local_homeomorph.eq_on_source.restr he s) _, exact ⟨by simp only [hs.interior_eq] with mfld_simps, by simp only with mfld_simps⟩, end ⟩ /-- A groupoid is closed under restriction if and only if it contains the trivial restriction-closed groupoid. -/ lemma closed_under_restriction_iff_id_le (G : structure_groupoid H) : closed_under_restriction G ↔ id_restr_groupoid ≤ G := begin split, { introsI _i, apply structure_groupoid.le_iff.mpr, rintros e ⟨s, hs, hes⟩, refine G.eq_on_source _ hes, convert closed_under_restriction' G.id_mem hs, change s = _ ∩ _, rw hs.interior_eq, simp only with mfld_simps }, { intros h, split, intros e he s hs, rw ← of_set_trans (e : local_homeomorph H H) hs, refine G.trans _ he, apply structure_groupoid.le_iff.mp h, exact id_restr_groupoid_mem hs }, end /-- The groupoid of all local homeomorphisms on a topological space `H` is closed under restriction. -/ instance : closed_under_restriction (continuous_groupoid H) := (closed_under_restriction_iff_id_le _).mpr (by convert le_top) end groupoid /-! ### Charted spaces -/ /-- A charted space is a topological space endowed with an atlas, i.e., a set of local homeomorphisms taking value in a model space `H`, called charts, such that the domains of the charts cover the whole space. We express the covering property by chosing for each `x` a member `chart_at H x` of the atlas containing `x` in its source: in the smooth case, this is convenient to construct the tangent bundle in an efficient way. The model space is written as an explicit parameter as there can be several model spaces for a given topological space. For instance, a complex manifold (modelled over `ℂ^n`) will also be seen sometimes as a real manifold over `ℝ^(2n)`. -/ class charted_space (H : Type*) [topological_space H] (M : Type*) [topological_space M] := (atlas [] : set (local_homeomorph M H)) (chart_at [] : M → local_homeomorph M H) (mem_chart_source [] : ∀x, x ∈ (chart_at x).source) (chart_mem_atlas [] : ∀x, chart_at x ∈ atlas) export charted_space attribute [simp, mfld_simps] mem_chart_source chart_mem_atlas section charted_space /-- Any space is a charted_space modelled over itself, by just using the identity chart -/ instance charted_space_self (H : Type*) [topological_space H] : charted_space H H := { atlas := {local_homeomorph.refl H}, chart_at := λx, local_homeomorph.refl H, mem_chart_source := λx, mem_univ x, chart_mem_atlas := λx, mem_singleton _ } /-- In the trivial charted_space structure of a space modelled over itself through the identity, the atlas members are just the identity -/ @[simp, mfld_simps] lemma charted_space_self_atlas {H : Type*} [topological_space H] {e : local_homeomorph H H} : e ∈ atlas H H ↔ e = local_homeomorph.refl H := by simp [atlas, charted_space.atlas] /-- In the model space, chart_at is always the identity -/ @[simp, mfld_simps] lemma chart_at_self_eq {H : Type*} [topological_space H] {x : H} : chart_at H x = local_homeomorph.refl H := by simpa using chart_mem_atlas H x section variables (H) [topological_space H] [topological_space M] [charted_space H M] lemma mem_chart_target (x : M) : chart_at H x x ∈ (chart_at H x).target := (chart_at H x).map_source (mem_chart_source _ _) /-- If a topological space admits an atlas with locally compact charts, then the space itself is locally compact. -/ lemma charted_space.locally_compact [locally_compact_space H] : locally_compact_space M := begin have : ∀ (x : M), (𝓝 x).has_basis (λ s, s ∈ 𝓝 (chart_at H x x) ∧ is_compact s ∧ s ⊆ (chart_at H x).target) (λ s, (chart_at H x).symm '' s), { intro x, rw [← (chart_at H x).symm_map_nhds_eq (mem_chart_source H x)], exact ((compact_basis_nhds (chart_at H x x)).has_basis_self_subset (mem_nhds_sets (chart_at H x).open_target (mem_chart_target H x))).map _ }, refine locally_compact_space_of_has_basis this _, rintro x s ⟨h₁, h₂, h₃⟩, exact h₂.image_of_continuous_on ((chart_at H x).continuous_on_symm.mono h₃) end end /-- Same thing as `H × H'`. We introduce it for technical reasons: a charted space `M` with model `H` is a set of local charts from `M` to `H` covering the space. Every space is registered as a charted space over itself, using the only chart `id`, in `manifold_model_space`. You can also define a product of charted space `M` and `M'` (with model space `H × H'`) by taking the products of the charts. Now, on `H × H'`, there are two charted space structures with model space `H × H'` itself, the one coming from `manifold_model_space`, and the one coming from the product of the two `manifold_model_space` on each component. They are equal, but not defeq (because the product of `id` and `id` is not defeq to `id`), which is bad as we know. This expedient of renaming `H × H'` solves this problem. -/ def model_prod (H : Type*) (H' : Type*) := H × H' section local attribute [reducible] model_prod instance model_prod_inhabited {α β : Type*} [inhabited α] [inhabited β] : inhabited (model_prod α β) := ⟨(default α, default β)⟩ instance (H : Type*) [topological_space H] (H' : Type*) [topological_space H'] : topological_space (model_prod H H') := by apply_instance /- Next lemma shows up often when dealing with derivatives, register it as simp. -/ @[simp, mfld_simps] lemma model_prod_range_prod_id {H : Type*} {H' : Type*} {α : Type*} (f : H → α) : range (λ (p : model_prod H H'), (f p.1, p.2)) = set.prod (range f) univ := by rw prod_range_univ_eq end /-- The product of two charted spaces is naturally a charted space, with the canonical construction of the atlas of product maps. -/ instance prod_charted_space (H : Type*) [topological_space H] (M : Type*) [topological_space M] [charted_space H M] (H' : Type*) [topological_space H'] (M' : Type*) [topological_space M'] [charted_space H' M'] : charted_space (model_prod H H') (M × M') := { atlas := {f : (local_homeomorph (M×M') (model_prod H H')) | ∃ g ∈ charted_space.atlas H M, ∃ h ∈ (charted_space.atlas H' M'), f = local_homeomorph.prod g h}, chart_at := λ x: (M × M'), (charted_space.chart_at H x.1).prod (charted_space.chart_at H' x.2), mem_chart_source := begin intro x, simp only with mfld_simps, end, chart_mem_atlas := begin intro x, use (charted_space.chart_at H x.1), split, { apply chart_mem_atlas _, }, { use (charted_space.chart_at H' x.2), simp only [chart_mem_atlas, and_self, true_and] } end } section prod_charted_space variables [topological_space H] [topological_space M] [charted_space H M] [topological_space H'] [topological_space M'] [charted_space H' M'] {x : M×M'} @[simp, mfld_simps] lemma prod_charted_space_chart_at : (chart_at (model_prod H H') x) = (chart_at H x.fst).prod (chart_at H' x.snd) := rfl end prod_charted_space end charted_space /-! ### Constructing a topology from an atlas -/ /-- Sometimes, one may want to construct a charted space structure on a space which does not yet have a topological structure, where the topology would come from the charts. For this, one needs charts that are only local equivs, and continuity properties for their composition. This is formalised in `charted_space_core`. -/ @[nolint has_inhabited_instance] structure charted_space_core (H : Type*) [topological_space H] (M : Type*) := (atlas : set (local_equiv M H)) (chart_at : M → local_equiv M H) (mem_chart_source : ∀x, x ∈ (chart_at x).source) (chart_mem_atlas : ∀x, chart_at x ∈ atlas) (open_source : ∀e e' : local_equiv M H, e ∈ atlas → e' ∈ atlas → is_open (e.symm.trans e').source) (continuous_to_fun : ∀e e' : local_equiv M H, e ∈ atlas → e' ∈ atlas → continuous_on (e.symm.trans e') (e.symm.trans e').source) namespace charted_space_core variables [topological_space H] (c : charted_space_core H M) {e : local_equiv M H} /-- Topology generated by a set of charts on a Type. -/ protected def to_topological_space : topological_space M := topological_space.generate_from $ ⋃ (e : local_equiv M H) (he : e ∈ c.atlas) (s : set H) (s_open : is_open s), {e ⁻¹' s ∩ e.source} lemma open_source' (he : e ∈ c.atlas) : @is_open M c.to_topological_space e.source := begin apply topological_space.generate_open.basic, simp only [exists_prop, mem_Union, mem_singleton_iff], refine ⟨e, he, univ, is_open_univ, _⟩, simp only [set.univ_inter, set.preimage_univ] end lemma open_target (he : e ∈ c.atlas) : is_open e.target := begin have E : e.target ∩ e.symm ⁻¹' e.source = e.target := subset.antisymm (inter_subset_left _ _) (λx hx, ⟨hx, local_equiv.target_subset_preimage_source _ hx⟩), simpa [local_equiv.trans_source, E] using c.open_source e e he he end /-- An element of the atlas in a charted space without topology becomes a local homeomorphism for the topology constructed from this atlas. The `local_homeomorph` version is given in this definition. -/ protected def local_homeomorph (e : local_equiv M H) (he : e ∈ c.atlas) : @local_homeomorph M H c.to_topological_space _ := { open_source := by convert c.open_source' he, open_target := by convert c.open_target he, continuous_to_fun := begin letI : topological_space M := c.to_topological_space, rw continuous_on_open_iff (c.open_source' he), assume s s_open, rw inter_comm, apply topological_space.generate_open.basic, simp only [exists_prop, mem_Union, mem_singleton_iff], exact ⟨e, he, ⟨s, s_open, rfl⟩⟩ end, continuous_inv_fun := begin letI : topological_space M := c.to_topological_space, apply continuous_on_open_of_generate_from (c.open_target he), assume t ht, simp only [exists_prop, mem_Union, mem_singleton_iff] at ht, rcases ht with ⟨e', e'_atlas, s, s_open, ts⟩, rw ts, let f := e.symm.trans e', have : is_open (f ⁻¹' s ∩ f.source), by simpa [inter_comm] using (continuous_on_open_iff (c.open_source e e' he e'_atlas)).1 (c.continuous_to_fun e e' he e'_atlas) s s_open, have A : e' ∘ e.symm ⁻¹' s ∩ (e.target ∩ e.symm ⁻¹' e'.source) = e.target ∩ (e' ∘ e.symm ⁻¹' s ∩ e.symm ⁻¹' e'.source), by { rw [← inter_assoc, ← inter_assoc], congr' 1, exact inter_comm _ _ }, simpa [local_equiv.trans_source, preimage_inter, preimage_comp.symm, A] using this end, ..e } /-- Given a charted space without topology, endow it with a genuine charted space structure with respect to the topology constructed from the atlas. -/ def to_charted_space : @charted_space H _ M c.to_topological_space := { atlas := ⋃ (e : local_equiv M H) (he : e ∈ c.atlas), {c.local_homeomorph e he}, chart_at := λx, c.local_homeomorph (c.chart_at x) (c.chart_mem_atlas x), mem_chart_source := λx, c.mem_chart_source x, chart_mem_atlas := λx, begin simp only [mem_Union, mem_singleton_iff], exact ⟨c.chart_at x, c.chart_mem_atlas x, rfl⟩, end } end charted_space_core /-! ### Charted space with a given structure groupoid -/ section has_groupoid variables [topological_space H] [topological_space M] [charted_space H M] section set_option old_structure_cmd true /-- A charted space has an atlas in a groupoid `G` if the change of coordinates belong to the groupoid -/ class has_groupoid {H : Type*} [topological_space H] (M : Type*) [topological_space M] [charted_space H M] (G : structure_groupoid H) : Prop := (compatible [] : ∀{e e' : local_homeomorph M H}, e ∈ atlas H M → e' ∈ atlas H M → e.symm ≫ₕ e' ∈ G) end /-- Reformulate in the `structure_groupoid` namespace the compatibility condition of charts in a charted space admitting a structure groupoid, to make it more easily accessible with dot notation. -/ lemma structure_groupoid.compatible {H : Type*} [topological_space H] (G : structure_groupoid H) {M : Type*} [topological_space M] [charted_space H M] [has_groupoid M G] {e e' : local_homeomorph M H} (he : e ∈ atlas H M) (he' : e' ∈ atlas H M) : e.symm ≫ₕ e' ∈ G := has_groupoid.compatible G he he' lemma has_groupoid_of_le {G₁ G₂ : structure_groupoid H} (h : has_groupoid M G₁) (hle : G₁ ≤ G₂) : has_groupoid M G₂ := ⟨ λ e e' he he', hle ((h.compatible : _) he he') ⟩ lemma has_groupoid_of_pregroupoid (PG : pregroupoid H) (h : ∀{e e' : local_homeomorph M H}, e ∈ atlas H M → e' ∈ atlas H M → PG.property (e.symm ≫ₕ e') (e.symm ≫ₕ e').source) : has_groupoid M (PG.groupoid) := ⟨assume e e' he he', mem_groupoid_of_pregroupoid.mpr ⟨h he he', h he' he⟩⟩ /-- The trivial charted space structure on the model space is compatible with any groupoid -/ instance has_groupoid_model_space (H : Type*) [topological_space H] (G : structure_groupoid H) : has_groupoid H G := { compatible := λe e' he he', begin replace he : e ∈ atlas H H := he, replace he' : e' ∈ atlas H H := he', rw charted_space_self_atlas at he he', simp [he, he', structure_groupoid.id_mem] end } /-- Any charted space structure is compatible with the groupoid of all local homeomorphisms -/ instance has_groupoid_continuous_groupoid : has_groupoid M (continuous_groupoid H) := ⟨begin assume e e' he he', rw [continuous_groupoid, mem_groupoid_of_pregroupoid], simp only [and_self] end⟩ section maximal_atlas variables (M) (G : structure_groupoid H) /-- Given a charted space admitting a structure groupoid, the maximal atlas associated to this structure groupoid is the set of all local charts that are compatible with the atlas, i.e., such that changing coordinates with an atlas member gives an element of the groupoid. -/ def structure_groupoid.maximal_atlas : set (local_homeomorph M H) := {e | ∀ e' ∈ atlas H M, e.symm ≫ₕ e' ∈ G ∧ e'.symm ≫ₕ e ∈ G} variable {M} /-- The elements of the atlas belong to the maximal atlas for any structure groupoid -/ lemma structure_groupoid.mem_maximal_atlas_of_mem_atlas [has_groupoid M G] {e : local_homeomorph M H} (he : e ∈ atlas H M) : e ∈ G.maximal_atlas M := λ e' he', ⟨G.compatible he he', G.compatible he' he⟩ lemma structure_groupoid.chart_mem_maximal_atlas [has_groupoid M G] (x : M) : chart_at H x ∈ G.maximal_atlas M := G.mem_maximal_atlas_of_mem_atlas (chart_mem_atlas H x) variable {G} lemma mem_maximal_atlas_iff {e : local_homeomorph M H} : e ∈ G.maximal_atlas M ↔ ∀ e' ∈ atlas H M, e.symm ≫ₕ e' ∈ G ∧ e'.symm ≫ₕ e ∈ G := iff.rfl /-- Changing coordinates between two elements of the maximal atlas gives rise to an element of the structure groupoid. -/ lemma structure_groupoid.compatible_of_mem_maximal_atlas {e e' : local_homeomorph M H} (he : e ∈ G.maximal_atlas M) (he' : e' ∈ G.maximal_atlas M) : e.symm ≫ₕ e' ∈ G := begin apply G.locality (λ x hx, _), set f := chart_at H (e.symm x) with hf, let s := e.target ∩ (e.symm ⁻¹' f.source), have hs : is_open s, { apply e.symm.continuous_to_fun.preimage_open_of_open; apply open_source }, have xs : x ∈ s, by { dsimp at hx, simp [s, hx] }, refine ⟨s, hs, xs, _⟩, have A : e.symm ≫ₕ f ∈ G := (mem_maximal_atlas_iff.1 he f (chart_mem_atlas _ _)).1, have B : f.symm ≫ₕ e' ∈ G := (mem_maximal_atlas_iff.1 he' f (chart_mem_atlas _ _)).2, have C : (e.symm ≫ₕ f) ≫ₕ (f.symm ≫ₕ e') ∈ G := G.trans A B, have D : (e.symm ≫ₕ f) ≫ₕ (f.symm ≫ₕ e') ≈ (e.symm ≫ₕ e').restr s := calc (e.symm ≫ₕ f) ≫ₕ (f.symm ≫ₕ e') = e.symm ≫ₕ (f ≫ₕ f.symm) ≫ₕ e' : by simp [trans_assoc] ... ≈ e.symm ≫ₕ (of_set f.source f.open_source) ≫ₕ e' : by simp [eq_on_source.trans', trans_self_symm] ... ≈ (e.symm ≫ₕ (of_set f.source f.open_source)) ≫ₕ e' : by simp [trans_assoc] ... ≈ (e.symm.restr s) ≫ₕ e' : by simp [s, trans_of_set'] ... ≈ (e.symm ≫ₕ e').restr s : by simp [restr_trans], exact G.eq_on_source C (setoid.symm D), end variable (G) /-- In the model space, the identity is in any maximal atlas. -/ lemma structure_groupoid.id_mem_maximal_atlas : local_homeomorph.refl H ∈ G.maximal_atlas H := G.mem_maximal_atlas_of_mem_atlas (by simp) end maximal_atlas section singleton variables {α : Type*} [topological_space α] variables (e : local_homeomorph α H) /-- If a single local homeomorphism `e` from a space `α` into `H` has source covering the whole space `α`, then that local homeomorphism induces an `H`-charted space structure on `α`. (This condition is equivalent to `e` being an open embedding of `α` into `H`; see `local_homeomorph.to_open_embedding` and `open_embedding.to_local_homeomorph`.) -/ def singleton_charted_space (h : e.source = set.univ) : charted_space H α := { atlas := {e}, chart_at := λ _, e, mem_chart_source := λ _, by simp only [h] with mfld_simps, chart_mem_atlas := λ _, by tauto } lemma singleton_charted_space_one_chart (h : e.source = set.univ) (e' : local_homeomorph α H) (h' : e' ∈ (singleton_charted_space e h).atlas) : e' = e := h' /-- Given a local homeomorphism `e` from a space `α` into `H`, if its source covers the whole space `α`, then the induced charted space structure on `α` is `has_groupoid G` for any structure groupoid `G` which is closed under restrictions. -/ lemma singleton_has_groupoid (h : e.source = set.univ) (G : structure_groupoid H) [closed_under_restriction G] : @has_groupoid _ _ _ _ (singleton_charted_space e h) G := { compatible := begin intros e' e'' he' he'', rw singleton_charted_space_one_chart e h e' he', rw singleton_charted_space_one_chart e h e'' he'', refine G.eq_on_source _ e.trans_symm_self, have hle : id_restr_groupoid ≤ G := (closed_under_restriction_iff_id_le G).mp (by assumption), exact structure_groupoid.le_iff.mp hle _ (id_restr_groupoid_mem _), end } end singleton namespace topological_space.opens open topological_space variables (G : structure_groupoid H) [has_groupoid M G] variables (s : opens M) /-- An open subset of a charted space is naturally a charted space. -/ instance : charted_space H s := { atlas := ⋃ (x : s), {@local_homeomorph.subtype_restr _ _ _ _ (chart_at H x.1) s ⟨x⟩}, chart_at := λ x, @local_homeomorph.subtype_restr _ _ _ _ (chart_at H x.1) s ⟨x⟩, mem_chart_source := λ x, by { simp only with mfld_simps, exact (mem_chart_source H x.1) }, chart_mem_atlas := λ x, by { simp only [mem_Union, mem_singleton_iff], use x } } /-- If a groupoid `G` is `closed_under_restriction`, then an open subset of a space which is `has_groupoid G` is naturally `has_groupoid G`. -/ instance [closed_under_restriction G] : has_groupoid s G := { compatible := begin rintros e e' ⟨_, ⟨x, hc⟩, he⟩ ⟨_, ⟨x', hc'⟩, he'⟩, haveI : nonempty s := ⟨x⟩, simp only [hc.symm, mem_singleton_iff, subtype.val_eq_coe] at he, simp only [hc'.symm, mem_singleton_iff, subtype.val_eq_coe] at he', rw [he, he'], convert G.eq_on_source _ (subtype_restr_symm_trans_subtype_restr s (chart_at H x) (chart_at H x')), apply closed_under_restriction', { exact G.compatible (chart_mem_atlas H x) (chart_mem_atlas H x') }, { exact preimage_open_of_open_symm (chart_at H x) s.2 }, end } end topological_space.opens /-! ### Structomorphisms -/ /-- A `G`-diffeomorphism between two charted spaces is a homeomorphism which, when read in the charts, belongs to `G`. We avoid the word diffeomorph as it is too related to the smooth category, and use structomorph instead. -/ @[nolint has_inhabited_instance] structure structomorph (G : structure_groupoid H) (M : Type*) (M' : Type*) [topological_space M] [topological_space M'] [charted_space H M] [charted_space H M'] extends homeomorph M M' := (mem_groupoid : ∀c : local_homeomorph M H, ∀c' : local_homeomorph M' H, c ∈ atlas H M → c' ∈ atlas H M' → c.symm ≫ₕ to_homeomorph.to_local_homeomorph ≫ₕ c' ∈ G) variables [topological_space M'] [topological_space M''] {G : structure_groupoid H} [charted_space H M'] [charted_space H M''] /-- The identity is a diffeomorphism of any charted space, for any groupoid. -/ def structomorph.refl (M : Type*) [topological_space M] [charted_space H M] [has_groupoid M G] : structomorph G M M := { mem_groupoid := λc c' hc hc', begin change (local_homeomorph.symm c) ≫ₕ (local_homeomorph.refl M) ≫ₕ c' ∈ G, rw local_homeomorph.refl_trans, exact has_groupoid.compatible G hc hc' end, ..homeomorph.refl M } /-- The inverse of a structomorphism is a structomorphism -/ def structomorph.symm (e : structomorph G M M') : structomorph G M' M := { mem_groupoid := begin assume c c' hc hc', have : (c'.symm ≫ₕ e.to_homeomorph.to_local_homeomorph ≫ₕ c).symm ∈ G := G.symm (e.mem_groupoid c' c hc' hc), rwa [trans_symm_eq_symm_trans_symm, trans_symm_eq_symm_trans_symm, symm_symm, trans_assoc] at this, end, ..e.to_homeomorph.symm} /-- The composition of structomorphisms is a structomorphism -/ def structomorph.trans (e : structomorph G M M') (e' : structomorph G M' M'') : structomorph G M M'' := { mem_groupoid := begin /- Let c and c' be two charts in M and M''. We want to show that e' ∘ e is smooth in these charts, around any point x. For this, let y = e (c⁻¹ x), and consider a chart g around y. Then g ∘ e ∘ c⁻¹ and c' ∘ e' ∘ g⁻¹ are both smooth as e and e' are structomorphisms, so their composition is smooth, and it coincides with c' ∘ e' ∘ e ∘ c⁻¹ around x. -/ assume c c' hc hc', refine G.locality (λx hx, _), let f₁ := e.to_homeomorph.to_local_homeomorph, let f₂ := e'.to_homeomorph.to_local_homeomorph, let f := (e.to_homeomorph.trans e'.to_homeomorph).to_local_homeomorph, have feq : f = f₁ ≫ₕ f₂ := homeomorph.trans_to_local_homeomorph _ _, -- define the atlas g around y let y := (c.symm ≫ₕ f₁) x, let g := chart_at H y, have hg₁ := chart_mem_atlas H y, have hg₂ := mem_chart_source H y, let s := (c.symm ≫ₕ f₁).source ∩ (c.symm ≫ₕ f₁) ⁻¹' g.source, have open_s : is_open s, by apply (c.symm ≫ₕ f₁).continuous_to_fun.preimage_open_of_open; apply open_source, have : x ∈ s, { split, { simp only [trans_source, preimage_univ, inter_univ, homeomorph.to_local_homeomorph_source], rw trans_source at hx, exact hx.1 }, { exact hg₂ } }, refine ⟨s, open_s, this, _⟩, let F₁ := (c.symm ≫ₕ f₁ ≫ₕ g) ≫ₕ (g.symm ≫ₕ f₂ ≫ₕ c'), have A : F₁ ∈ G := G.trans (e.mem_groupoid c g hc hg₁) (e'.mem_groupoid g c' hg₁ hc'), let F₂ := (c.symm ≫ₕ f ≫ₕ c').restr s, have : F₁ ≈ F₂ := calc F₁ ≈ c.symm ≫ₕ f₁ ≫ₕ (g ≫ₕ g.symm) ≫ₕ f₂ ≫ₕ c' : by simp [F₁, trans_assoc] ... ≈ c.symm ≫ₕ f₁ ≫ₕ (of_set g.source g.open_source) ≫ₕ f₂ ≫ₕ c' : by simp [eq_on_source.trans', trans_self_symm g] ... ≈ ((c.symm ≫ₕ f₁) ≫ₕ (of_set g.source g.open_source)) ≫ₕ (f₂ ≫ₕ c') : by simp [trans_assoc] ... ≈ ((c.symm ≫ₕ f₁).restr s) ≫ₕ (f₂ ≫ₕ c') : by simp [s, trans_of_set'] ... ≈ ((c.symm ≫ₕ f₁) ≫ₕ (f₂ ≫ₕ c')).restr s : by simp [restr_trans] ... ≈ (c.symm ≫ₕ (f₁ ≫ₕ f₂) ≫ₕ c').restr s : by simp [eq_on_source.restr, trans_assoc] ... ≈ F₂ : by simp [F₂, feq], have : F₂ ∈ G := G.eq_on_source A (setoid.symm this), exact this end, ..homeomorph.trans e.to_homeomorph e'.to_homeomorph } end has_groupoid
1807347e1486a895d70b1058c005d1c7d6071ad3
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/algebra/homology/chain_complex.lean
c5cdffa80c36c38ca78be59f99ace7679d57f5ca
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,130
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import data.int.basic import category_theory.graded_object import category_theory.differential_object /-! # Chain complexes We define a chain complex in `V` as a differential `ℤ`-graded object in `V`. This is fancy language for the obvious definition, and it seems we can use it straightforwardly: ``` example (C : chain_complex V) : C.X 5 ⟶ C.X 6 := C.d 5 ``` -/ universes v u open category_theory open category_theory.limits variables (V : Type u) [category.{v} V] variables [has_zero_morphisms V] section /-- A `homological_complex V b` for `b : β` is a (co)chain complex graded by `β`, with differential in grading `b`. (We use the somewhat cumbersome `homological_complex` to avoid the name conflict with `ℂ`.) -/ abbreviation homological_complex {β : Type} [add_comm_group β] (b : β) : Type (max v u) := differential_object (graded_object_with_shift b V) /-- A chain complex in `V` is "just" a differential `ℤ`-graded object in `V`, with differential graded `-1`. -/ abbreviation chain_complex : Type (max v u) := homological_complex V (-1 : ℤ) /-- A cochain complex in `V` is "just" a differential `ℤ`-graded object in `V`, with differential graded `+1`. -/ abbreviation cochain_complex : Type (max v u) := homological_complex V (1 : ℤ) -- The chain groups of a chain complex `C` are accessed as `C.X i`, -- and the differentials as `C.d i : C.X i ⟶ C.X (i-1)`. example (C : chain_complex V) : C.X 5 ⟶ C.X 4 := C.d 5 end namespace homological_complex variables {V} variables {β : Type} [add_comm_group β] {b : β} @[simp, reassoc] lemma d_squared (C : homological_complex V b) (i : β) : C.d i ≫ C.d (i+b) = 0 := congr_fun (C.d_squared) i /-- A convenience lemma for morphisms of cochain complexes, picking out one component of the commutation relation. -/ -- I haven't been able to get this to work with projection notation: `f.comm_at i` @[simp, reassoc] lemma comm_at {C D : homological_complex V b} (f : C ⟶ D) (i : β) : C.d i ≫ f.f (i+b) = f.f i ≫ D.d i := congr_fun f.comm i @[simp, reassoc] lemma comm {C D : homological_complex V b} (f : C ⟶ D) : C.d ≫ f.f⟦1⟧' = f.f ≫ D.d := differential_object.hom.comm _ @[reassoc] lemma eq_to_hom_d (C : homological_complex V b) {i j : β} (h : i = j) : eq_to_hom (congr_arg C.X h) ≫ C.d j = C.d i ≫ eq_to_hom (congr_arg C.X (congr_arg (λ a, a + b) h) : _) := begin induction h, simp, end @[reassoc] lemma eq_to_hom_f {C D : homological_complex V b} (f : C ⟶ D) {n m : β} (h : n = m) : eq_to_hom (congr_arg C.X h) ≫ f.f m = f.f n ≫ eq_to_hom (congr_arg D.X h) := begin induction h, simp end variables (V) /-- The forgetful functor from cochain complexes to graded objects, forgetting the differential. -/ abbreviation forget : (homological_complex V b) ⥤ (graded_object β V) := differential_object.forget _ section local attribute [instance] has_zero_object.has_zero instance : inhabited (homological_complex (discrete punit) b) := ⟨0⟩ end end homological_complex open homological_complex -- The components of a cochain map `f : C ⟶ D` are accessed as `f.f i`. example {C D : cochain_complex V} (f : C ⟶ D) : C.X 5 ⟶ D.X 5 := f.f 5 example {C D : cochain_complex V} (f : C ⟶ D) : C.d ≫ f.f⟦1⟧' = f.f ≫ D.d := by simp example {C D : cochain_complex V} (f : C ⟶ D) : C.d 5 ≫ f.f 6 = f.f 5 ≫ D.d 5 := comm_at f 5 -- TODO when V is enriched in W, what do we need to ensure -- `chain_complex V` is also enriched in W? -- TODO `chain_complex V` is a module category for `V` when `V` is monoidal -- TODO When V is enriched in AddCommGroup, and has coproducts, -- we can collapse a double complex to obtain a complex. -- If the double complex is supported in a quadrant, we only need finite coproducts. -- TODO when V is monoidal, enriched in `AddCommGroup`, -- and has coproducts then -- `chain_complex V` is monoidal too. -- If the complexes are bounded below we only need finite coproducts.
fc54a75c9f0fb261eae3222cc6a69810c53e75f1
618003631150032a5676f229d13a079ac875ff77
/src/tactic/finish.lean
05b643506752d33220a519e44d5c997f0ccfc1c8
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
23,096
lean
/- Copyright (c) 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Jesse Michael Han -/ import tactic.hint /-! # The `finish` family of tactics These tactics do straightforward things: they call the simplifier, split conjunctive assumptions, eliminate existential quantifiers on the left, and look for contradictions. They rely on ematching and congruence closure to try to finish off a goal at the end. The procedures *do* split on disjunctions and recreate the smt state for each terminal call, so they are only meant to be used on small, straightforward problems. ## Main definitions We provide the following tactics: * `finish` -- solves the goal or fails * `clarify` -- makes as much progress as possible while not leaving more than one goal * `safe` -- splits freely, finishes off whatever subgoals it can, and leaves the rest All accept an optional list of simplifier rules, typically definitions that should be expanded. (The equations and identities should not refer to the local context.) ## Implementation notes The variants `ifinish`, `iclarify`, and `isafe` try to restrict to intuitionistic logic. But the `done` tactic leaks classical logic: ```lean example {P : Prop} : ¬¬P → P := by using_smt (do smt_tactic.intros, smt_tactic.close) ``` They also do not work well with the current heuristic instantiation method used by `ematch`. So they are left here mainly for reference. -/ declare_trace auto.done declare_trace auto.finish namespace tactic namespace interactive meta def revert_all := tactic.revert_all end interactive end tactic open tactic expr namespace auto /-! ### Utilities -/ meta def whnf_reducible (e : expr) : tactic expr := whnf e reducible -- stolen from interactive.lean meta def add_simps : simp_lemmas → list name → tactic simp_lemmas | s [] := return s | s (n::ns) := do s' ← s.add_simp n, add_simps s' ns /-- Configuration information for the auto tactics. * `(use_simp := tt)`: call the simplifier * `(classical := tt)`: use classical logic * `(max_ematch_rounds := 20)`: for the "done" tactic -/ @[derive decidable_eq, derive inhabited] structure auto_config : Type := (use_simp := tt) (classical := tt) (max_ematch_rounds := 20) /-! ### Preprocess goal. We want to move everything to the left of the sequent arrow. For intuitionistic logic, we replace the goal `p` with `∀ f, (p → f) → f` and introduce. -/ theorem by_contradiction_trick (p : Prop) (h : ∀ f : Prop, (p → f) → f) : p := h p id meta def preprocess_goal (cfg : auto_config) : tactic unit := do repeat (intro1 >> skip), tgt ← target >>= whnf_reducible, if (¬ (is_false tgt)) then if cfg.classical then (mk_mapp ``classical.by_contradiction [some tgt]) >>= apply >> intro1 >> skip else (mk_mapp ``decidable.by_contradiction [some tgt, none] >>= apply >> intro1 >> skip) <|> applyc ``by_contradiction_trick >> intro1 >> intro1 >> skip else skip /-! ### Normalize hypotheses Bring conjunctions to the outside (for splitting), bring universal quantifiers to the outside (for ematching). The classical normalizer eliminates `a → b` in favor of `¬ a ∨ b`. For efficiency, we push negations inwards from the top down. (For example, consider simplifying `¬ ¬ (p ∨ q)`.) -/ section universe u variable {α : Type u} variables (p q : Prop) variable (s : α → Prop) local attribute [instance, priority 10] classical.prop_decidable theorem not_not_eq : (¬ ¬ p) = p := propext not_not theorem not_and_eq : (¬ (p ∧ q)) = (¬ p ∨ ¬ q) := propext not_and_distrib theorem not_or_eq : (¬ (p ∨ q)) = (¬ p ∧ ¬ q) := propext not_or_distrib theorem not_forall_eq : (¬ ∀ x, s x) = (∃ x, ¬ s x) := propext not_forall theorem not_exists_eq : (¬ ∃ x, s x) = (∀ x, ¬ s x) := propext not_exists theorem not_implies_eq : (¬ (p → q)) = (p ∧ ¬ q) := propext not_imp theorem classical.implies_iff_not_or : (p → q) ↔ (¬ p ∨ q) := imp_iff_not_or end def common_normalize_lemma_names : list name := [``bex_def, ``forall_and_distrib, ``exists_imp_distrib, ``or.assoc, ``or.comm, ``or.left_comm, ``and.assoc, ``and.comm, ``and.left_comm] def classical_normalize_lemma_names : list name := common_normalize_lemma_names ++ [``classical.implies_iff_not_or] /-- optionally returns an equivalent expression and proof of equivalence -/ private meta def transform_negation_step (cfg : auto_config) (e : expr) : tactic (option (expr × expr)) := do e ← whnf_reducible e, match e with | `(¬ %%ne) := (do ne ← whnf_reducible ne, match ne with | `(¬ %%a) := if ¬ cfg.classical then return none else do pr ← mk_app ``not_not_eq [a], return (some (a, pr)) | `(%%a ∧ %%b) := do pr ← mk_app ``not_and_eq [a, b], return (some (`(¬ %%a ∨ ¬ %%b), pr)) | `(%%a ∨ %%b) := do pr ← mk_app ``not_or_eq [a, b], return (some (`(¬ %%a ∧ ¬ %%b), pr)) | `(Exists %%p) := do pr ← mk_app ``not_exists_eq [p], `(%%_ = %%e') ← infer_type pr, return (some (e', pr)) | (pi n bi d p) := if ¬ cfg.classical then return none else if p.has_var then do pr ← mk_app ``not_forall_eq [lam n bi d (expr.abstract_local p n)], `(%%_ = %%e') ← infer_type pr, return (some (e', pr)) else do pr ← mk_app ``not_implies_eq [d, p], `(%%_ = %%e') ← infer_type pr, return (some (e', pr)) | _ := return none end) | _ := return none end /-- given an expr `e`, returns a new expression and a proof of equality -/ private meta def transform_negation (cfg : auto_config) : expr → tactic (option (expr × expr)) := λ e, do opr ← transform_negation_step cfg e, match opr with | (some (e', pr)) := do opr' ← transform_negation e', match opr' with | none := return (some (e', pr)) | (some (e'', pr')) := do pr'' ← mk_eq_trans pr pr', return (some (e'', pr'')) end | none := return none end meta def normalize_negations (cfg : auto_config) (h : expr) : tactic unit := do t ← infer_type h, (_, e, pr) ← simplify_top_down () (λ _, λ e, do oepr ← transform_negation cfg e, match oepr with | (some (e', pr)) := return ((), e', pr) | none := do pr ← mk_eq_refl e, return ((), e, pr) end) t, replace_hyp h e pr, skip meta def normalize_hyp (cfg : auto_config) (simps : simp_lemmas) (h : expr) : tactic unit := (do h ← simp_hyp simps [] h, try (normalize_negations cfg h)) <|> try (normalize_negations cfg h) meta def normalize_hyps (cfg : auto_config) : tactic unit := do simps ← if cfg.classical then add_simps simp_lemmas.mk classical_normalize_lemma_names else add_simps simp_lemmas.mk common_normalize_lemma_names, local_context >>= monad.mapm' (normalize_hyp cfg simps) /-! ### Eliminate existential quantifiers -/ /-- eliminate an existential quantifier if there is one -/ meta def eelim : tactic unit := do ctx ← local_context, first $ ctx.map $ λ h, do t ← infer_type h >>= whnf_reducible, guard (is_app_of t ``Exists), tgt ← target, to_expr ``(@exists.elim _ _ %%tgt %%h) >>= apply, intros, clear h /-- eliminate all existential quantifiers, fails if there aren't any -/ meta def eelims : tactic unit := eelim >> repeat eelim /-! ### Substitute if there is a hypothesis `x = t` or `t = x` -/ /-- carries out a subst if there is one, fails otherwise -/ meta def do_subst : tactic unit := do ctx ← local_context, first $ ctx.map $ λ h, do t ← infer_type h >>= whnf_reducible, match t with | `(%%a = %%b) := subst h | _ := failed end meta def do_substs : tactic unit := do_subst >> repeat do_subst /-! ### Split all conjunctions -/ /-- Assumes `pr` is a proof of `t`. Adds the consequences of `t` to the context and returns `tt` if anything nontrivial has been added. -/ meta def add_conjuncts : expr → expr → tactic bool := λ pr t, let assert_consequences := λ e t, mcond (add_conjuncts e t) skip (note_anon t e >> skip) in do t' ← whnf_reducible t, match t' with | `(%%a ∧ %%b) := do e₁ ← mk_app ``and.left [pr], assert_consequences e₁ a, e₂ ← mk_app ``and.right [pr], assert_consequences e₂ b, return tt | `(true) := do return tt | _ := return ff end /-- return `tt` if any progress is made -/ meta def split_hyp (h : expr) : tactic bool := do t ← infer_type h, mcond (add_conjuncts h t) (clear h >> return tt) (return ff) /-- return `tt` if any progress is made -/ meta def split_hyps_aux : list expr → tactic bool | [] := return ff | (h :: hs) := do b₁ ← split_hyp h, b₂ ← split_hyps_aux hs, return (b₁ || b₂) /-- fail if no progress is made -/ meta def split_hyps : tactic unit := local_context >>= split_hyps_aux >>= guardb /-! ### Eagerly apply all the preprocessing rules -/ /-- Eagerly apply all the preprocessing rules -/ meta def preprocess_hyps (cfg : auto_config) : tactic unit := do repeat (intro1 >> skip), preprocess_goal cfg, normalize_hyps cfg, repeat (do_substs <|> split_hyps <|> eelim /-<|> self_simplify_hyps-/) /-! ### Terminal tactic -/ /-- The terminal tactic, used to try to finish off goals: - Call the contradiction tactic. - Open an SMT state, and use ematching and congruence closure, with all the universal statements in the context. TODO(Jeremy): allow users to specify attribute for ematching lemmas? -/ meta def mk_hinst_lemmas : list expr → smt_tactic hinst_lemmas | [] := -- return hinst_lemmas.mk do get_hinst_lemmas_for_attr `ematch | (h :: hs) := do his ← mk_hinst_lemmas hs, t ← infer_type h, match t with | (pi _ _ _ _) := do t' ← infer_type t, if t' = `(Prop) then (do new_lemma ← hinst_lemma.mk h, return (hinst_lemmas.add his new_lemma)) <|> return his else return his | _ := return his end private meta def report_invalid_em_lemma {α : Type} (n : name) : smt_tactic α := fail format!"invalid ematch lemma '{n}'" private meta def add_hinst_lemma_from_name (md : transparency) (lhs_lemma : bool) (n : name) (hs : hinst_lemmas) (ref : pexpr) : smt_tactic hinst_lemmas := do p ← resolve_name n, match p with | expr.const n _ := (do h ← hinst_lemma.mk_from_decl_core md n lhs_lemma, tactic.save_const_type_info n ref, return $ hs.add h) <|> (do hs₁ ← smt_tactic.mk_ematch_eqn_lemmas_for_core md n, tactic.save_const_type_info n ref, return $ hs.merge hs₁) <|> report_invalid_em_lemma n | _ := (do e ← to_expr p, h ← hinst_lemma.mk_core md e lhs_lemma, try (tactic.save_type_info e ref), return $ hs.add h) <|> report_invalid_em_lemma n end private meta def add_hinst_lemma_from_pexpr (md : transparency) (lhs_lemma : bool) (hs : hinst_lemmas) : pexpr → smt_tactic hinst_lemmas | p@(expr.const c []) := add_hinst_lemma_from_name md lhs_lemma c hs p | p@(expr.local_const c _ _ _) := add_hinst_lemma_from_name md lhs_lemma c hs p | p := do new_e ← to_expr p, h ← hinst_lemma.mk_core md new_e lhs_lemma, return $ hs.add h private meta def add_hinst_lemmas_from_pexprs (md : transparency) (lhs_lemma : bool) (ps : list pexpr) (hs : hinst_lemmas) : smt_tactic hinst_lemmas := list.mfoldl (add_hinst_lemma_from_pexpr md lhs_lemma) hs ps /-- `done` first attempts to close the goal using `contradiction`. If this fails, it creates an SMT state and will repeatedly use `ematch` (using `ematch` lemmas in the environment, universally quantified assumptions, and the supplied lemmas `ps`) and congruence closure. -/ meta def done (ps : list pexpr) (cfg : auto_config := {}) : tactic unit := do trace_state_if_enabled `auto.done "entering done", contradiction <|> (solve1 $ (do revert_all, using_smt (do smt_tactic.intros, ctx ← local_context, hs ← mk_hinst_lemmas ctx, hs' ← add_hinst_lemmas_from_pexprs reducible ff ps hs, smt_tactic.iterate_at_most cfg.max_ematch_rounds (smt_tactic.ematch_using hs' >> smt_tactic.try smt_tactic.close)))) /-! ### Tactics that perform case splits -/ @[derive decidable_eq, derive inhabited] inductive case_option | force -- fail unless all goals are solved | at_most_one -- leave at most one goal | accept -- leave as many goals as necessary private meta def case_cont (s : case_option) (cont : case_option → tactic unit) : tactic unit := do match s with | case_option.force := cont case_option.force >> cont case_option.force | case_option.at_most_one := -- if the first one succeeds, commit to it, and try the second (mcond (cont case_option.force >> return tt) (cont case_option.at_most_one) skip) <|> -- otherwise, try the second (swap >> cont case_option.force >> cont case_option.at_most_one) | case_option.accept := focus' [cont case_option.accept, cont case_option.accept] end -- three possible outcomes: -- finds something to case, the continuations succeed ==> returns tt -- finds something to case, the continutations fail ==> fails -- doesn't find anything to case ==> returns ff meta def case_hyp (h : expr) (s : case_option) (cont : case_option → tactic unit) : tactic bool := do t ← infer_type h, match t with | `(%%a ∨ %%b) := cases h >> case_cont s cont >> return tt | _ := return ff end meta def case_some_hyp_aux (s : case_option) (cont : case_option → tactic unit) : list expr → tactic bool | [] := return ff | (h::hs) := mcond (case_hyp h s cont) (return tt) (case_some_hyp_aux hs) meta def case_some_hyp (s : case_option) (cont : case_option → tactic unit) : tactic bool := local_context >>= case_some_hyp_aux s cont /-! ### The main tactics -/ /-- `safe_core s ps cfg opt` negates the goal, normalizes hypotheses (by splitting conjunctions, eliminating existentials, pushing negations inwards, and calling `simp` with the supplied lemmas `s`), and then tries `contradiction`. If this fails, it will create an SMT state and repeatedly use `ematch` (using `ematch` lemmas in the environment, universally quantified assumptions, and the supplied lemmas `ps`) and congruence closure. `safe_core` is complete for propositional logic. Depending on the form of `opt` it will: - (if `opt` is `case_option.force`) fail if it does not close the goal, - (if `opt` is `case_option.at_most_one`) fail if it produces more than one goal, and - (if `opt` is `case_option.accept`) ignore the number of goals it produces. -/ meta def safe_core (s : simp_lemmas × list name) (ps : list pexpr) (cfg : auto_config) : case_option → tactic unit := λ co, focus1 $ do trace_state_if_enabled `auto.finish "entering safe_core", if cfg.use_simp then do trace_if_enabled `auto.finish "simplifying hypotheses", simp_all s.1 s.2 { fail_if_unchanged := ff }, trace_state_if_enabled `auto.finish "result:" else skip, tactic.done <|> do trace_if_enabled `auto.finish "preprocessing hypotheses", preprocess_hyps cfg, trace_state_if_enabled `auto.finish "result:", done ps cfg <|> (mcond (case_some_hyp co safe_core) skip (match co with | case_option.force := done ps cfg | case_option.at_most_one := try (done ps cfg) | case_option.accept := try (done ps cfg) end)) /-- `clarify` is `safe_core`, but with the `(opt : case_option)` parameter fixed at `case_option.at_most_one`. -/ meta def clarify (s : simp_lemmas × list name) (ps : list pexpr) (cfg : auto_config := {}) : tactic unit := safe_core s ps cfg case_option.at_most_one /-- `safe` is `safe_core`, but with the `(opt : case_option)` parameter fixed at `case_option.accept`. -/ meta def safe (s : simp_lemmas × list name) (ps : list pexpr) (cfg : auto_config := {}) : tactic unit := safe_core s ps cfg case_option.accept /-- `finish` is `safe_core`, but with the `(opt : case_option)` parameter fixed at `case_option.force`. -/ meta def finish (s : simp_lemmas × list name) (ps : list pexpr) (cfg : auto_config := {}) : tactic unit := safe_core s ps cfg case_option.force /-- `iclarify` is like `clarify`, but in some places restricts to intuitionistic logic. Classical logic still leaks, so this tactic is deprecated. -/ meta def iclarify (s : simp_lemmas × list name) (ps : list pexpr) (cfg : auto_config := {}) : tactic unit := clarify s ps {classical := ff, ..cfg} /-- `isafe` is like `safe`, but in some places restricts to intuitionistic logic. Classical logic still leaks, so this tactic is deprecated. -/ meta def isafe (s : simp_lemmas × list name) (ps : list pexpr) (cfg : auto_config := {}) : tactic unit := safe s ps {classical := ff, ..cfg} /-- `ifinish` is like `finish`, but in some places restricts to intuitionistic logic. Classical logic still leaks, so this tactic is deprecated. -/ meta def ifinish (s : simp_lemmas × list name) (ps : list pexpr) (cfg : auto_config := {}) : tactic unit := finish s ps {classical := ff, ..cfg} end auto /-! ### interactive versions -/ open auto namespace tactic namespace interactive open lean lean.parser interactive interactive.types local postfix `?`:9001 := optional local postfix *:9001 := many /-- `clarify [h1,...,hn] using [e1,...,en]` negates the goal, normalizes hypotheses (by splitting conjunctions, eliminating existentials, pushing negations inwards, and calling `simp` with the supplied lemmas `h1,...,hn`), and then tries `contradiction`. If this fails, it will create an SMT state and repeatedly use `ematch` (using `ematch` lemmas in the environment, universally quantified assumptions, and the supplied lemmas `e1,...,en`) and congruence closure. `clarify` is complete for propositional logic. Either of the supplied simp lemmas or the supplied ematch lemmas are optional. `clarify` will fail if it produces more than one goal. -/ meta def clarify (hs : parse simp_arg_list) (ps : parse (tk "using" *> pexpr_list_or_texpr)?) (cfg : auto_config := {}) : tactic unit := do s ← mk_simp_set ff [] hs, auto.clarify s (ps.get_or_else []) cfg /-- `safe [h1,...,hn] using [e1,...,en]` negates the goal, normalizes hypotheses (by splitting conjunctions, eliminating existentials, pushing negations inwards, and calling `simp` with the supplied lemmas `h1,...,hn`), and then tries `contradiction`. If this fails, it will create an SMT state and repeatedly use `ematch` (using `ematch` lemmas in the environment, universally quantified assumptions, and the supplied lemmas `e1,...,en`) and congruence closure. `safe` is complete for propositional logic. Either of the supplied simp lemmas or the supplied ematch lemmas are optional. `safe` ignores the number of goals it produces, and should never fail. -/ meta def safe (hs : parse simp_arg_list) (ps : parse (tk "using" *> pexpr_list_or_texpr)?) (cfg : auto_config := {}) : tactic unit := do s ← mk_simp_set ff [] hs, auto.safe s (ps.get_or_else []) cfg /-- `finish [h1,...,hn] using [e1,...,en]` negates the goal, normalizes hypotheses (by splitting conjunctions, eliminating existentials, pushing negations inwards, and calling `simp` with the supplied lemmas `h1,...,hn`), and then tries `contradiction`. If this fails, it will create an SMT state and repeatedly use `ematch` (using `ematch` lemmas in the environment, universally quantified assumptions, and the supplied lemmas `e1,...,en`) and congruence closure. `finish` is complete for propositional logic. Either of the supplied simp lemmas or the supplied ematch lemmas are optional. `finish` will fail if it does not close the goal. -/ meta def finish (hs : parse simp_arg_list) (ps : parse (tk "using" *> pexpr_list_or_texpr)?) (cfg : auto_config := {}) : tactic unit := do s ← mk_simp_set ff [] hs, auto.finish s (ps.get_or_else []) cfg add_hint_tactic "finish" /-- These tactics do straightforward things: they call the simplifier, split conjunctive assumptions, eliminate existential quantifiers on the left, and look for contradictions. They rely on ematching and congruence closure to try to finish off a goal at the end. The procedures *do* split on disjunctions and recreate the smt state for each terminal call, so they are only meant to be used on small, straightforward problems. * `finish`: solves the goal or fails * `clarify`: makes as much progress as possible while not leaving more than one goal * `safe`: splits freely, finishes off whatever subgoals it can, and leaves the rest All accept an optional list of simplifier rules, typically definitions that should be expanded. (The equations and identities should not refer to the local context.) All also accept an optional list of `ematch` lemmas, which must be preceded by `using`. -/ add_tactic_doc { name := "finish / clarify / safe", category := doc_category.tactic, decl_names := [`tactic.interactive.finish, `tactic.interactive.clarify, `tactic.interactive.safe], tags := ["logic", "finishing"] } /-- `iclarify` is like `clarify`, but only uses intuitionistic logic. -/ meta def iclarify (hs : parse simp_arg_list) (ps : parse (tk "using" *> pexpr_list_or_texpr)?) (cfg : auto_config := {}) : tactic unit := do s ← mk_simp_set ff [] hs, auto.iclarify s (ps.get_or_else []) cfg /-- `isafe` is like `safe`, but only uses intuitionistic logic. -/ meta def isafe (hs : parse simp_arg_list) (ps : parse (tk "using" *> pexpr_list_or_texpr)?) (cfg : auto_config := {}) : tactic unit := do s ← mk_simp_set ff [] hs, auto.isafe s (ps.get_or_else []) cfg /-- `ifinish` is like `finish`, but only uses intuitionistic logic. -/ meta def ifinish (hs : parse simp_arg_list) (ps : parse (tk "using" *> pexpr_list_or_texpr)?) (cfg : auto_config := {}) : tactic unit := do s ← mk_simp_set ff [] hs, auto.ifinish s (ps.get_or_else []) cfg end interactive end tactic
33a5595dcb598e5829a55e86d77b3f1b07fc9ced
a4673261e60b025e2c8c825dfa4ab9108246c32e
/tests/lean/run/backtrackable_estate.lean
653dbc3e06fb656dc74dfaead2e9a0100b7d4cf8
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
685
lean
import Init.System.IO structure MyState := (bs : Nat := 0) -- backtrackable state (ps : Nat := 0) -- non backtrackable state instance : Repr MyState := ⟨fun s => repr (s.bs, s.ps)⟩ instance : EStateM.Backtrackable Nat MyState := { save := fun s => s.bs, restore := fun s d => { s with bs := d } } abbrev M := EStateM String MyState def bInc : M Unit := -- increment backtrackble counter modify $ fun s => { s with bs := s.bs + 1 } def pInc : M Unit := -- increment nonbacktrackable counter modify $ fun s => { s with ps := s.ps + 1 } def tst : M MyState := do bInc; pInc; ((bInc *> throw "failed") <|> pInc); pInc; get #eval tst.run' {} -- (some (1, 3))
24ae2c119a7fba3926cecbd191373b3a2573042b
4da0c8e61fcd6ec3f3be47ee14a038850c03d0c3
/src/s5/default.lean
64da6bf266c28144a1ed63bd616b106e4e1cc601
[ "Apache-2.0" ]
permissive
bbentzen/mpl
fcbea60204bc8fd64667e0f76a5cebf4b67fb6ca
bb5066ec51fa11a4b66f440c4f6c9a3d8fb2e0de
refs/heads/master
1,625,175,849,308
1,624,207,634,000
1,624,207,634,000
142,774,375
9
0
null
null
null
null
UTF-8
Lean
false
false
161
lean
/- Copyright (c) 2018 Bruno Bentzen. All rights reserved. Released under the Apache License 2.0 (see "License"); Author: Bruno Bentzen -/ import ..default
3446c1c286164e591ab6eedc960967a6681a781f
ef4d3feecef33d1c1b4bd3a023b85e6a58f9e708
/theorem-proving-in-lean/ch3/Exercises.lean
aa0a476bcaa5d15d07ac628397fb41feccf9b6ee
[]
no_license
MikeMKH/kata
1b7da1b8d2cc115c912f2b06b583a8e675a449e1
305b054a37517dbe4d09545d41f024937f536c20
refs/heads/master
1,585,594,368,426
1,542,835,119,000
1,542,835,119,000
16,891,298
0
0
null
1,542,835,120,000
1,392,575,890,000
Racket
UTF-8
Lean
false
false
2,673
lean
open classical variables p q r s : Prop -- commutativity of ∧ and ∨ example : p ∧ q ↔ q ∧ p := iff.intro (assume hpq : p ∧ q, show q ∧ p, from and.intro (and.right hpq) (and.left hpq)) (assume hqp : q ∧ p, show p ∧ q, from and.intro (and.right hqp) (and.left hqp)) example : p ∨ q ↔ q ∨ p := iff.intro (assume hpq: p ∨ q, or.elim hpq (assume hp : p, or.inr hp) (assume hq : q, or.inl hq)) (assume hpq : q ∨ p, or.elim hpq (assume hq : q, or.inr hq) (assume hq : p, or.inl hq)) -- associativity of ∧ and ∨ example : (p ∧ q) ∧ r ↔ p ∧ (q ∧ r) := iff.intro (assume h : (p ∧ q) ∧ r, have hpq : p ∧ q, from and.left h, have hr : r, from and.right h, show p ∧ (q ∧ r), from and.intro (and.left hpq) (and.intro (and.right hpq) hr)) (assume h : p ∧ (q ∧ r), have hp : p, from and.left h, have hqr : q ∧ r, from and.right h, show (p ∧ q) ∧ r, from and.intro (and.intro hp (and.left hqr)) (and.right hqr)) example : (p ∨ q) ∨ r ↔ p ∨ (q ∨ r) := iff.intro (assume h : (p ∨ q) ∨ r, or.elim h (assume hpq, or.elim hpq or.inl (assume hq, or.intro_right p (or.intro_left r hq))) (assume hr, or.intro_right p (or.intro_right q hr)) ) (assume h : p ∨ (q ∨ r), or.elim h (assume hp, or.inl (or.intro_left q hp)) (assume hqr, or.elim hqr (assume hq, or.intro_left r (or.intro_right p hq)) or.inr) ) -- -- distributivity -- example : p ∧ (q ∨ r) ↔ (p ∧ q) ∨ (p ∧ r) := sorry -- example : p ∨ (q ∧ r) ↔ (p ∨ q) ∧ (p ∨ r) := sorry -- -- other properties -- example : (p → (q → r)) ↔ (p ∧ q → r) := sorry -- example : ((p ∨ q) → r) ↔ (p → r) ∧ (q → r) := sorry -- example : ¬(p ∨ q) ↔ ¬p ∧ ¬q := sorry -- example : ¬p ∨ ¬q → ¬(p ∧ q) := sorry -- example : ¬(p ∧ ¬p) := sorry -- example : p ∧ ¬q → ¬(p → q) := sorry -- example : ¬p → (p → q) := sorry -- example : (¬p ∨ q) → (p → q) := sorry -- example : p ∨ false ↔ p := sorry -- example : p ∧ false ↔ false := sorry -- example : ¬(p ↔ ¬p) := sorry -- example : (p → q) → (¬q → ¬p) := sorry -- -- these require classical reasoning -- example : (p → r ∨ s) → ((p → r) ∨ (p → s)) := sorry -- example : ¬(p ∧ q) → ¬p ∨ ¬q := sorry -- example : ¬(p → q) → p ∧ ¬q := sorry -- example : (p → q) → (¬p ∨ q) := sorry -- example : (¬q → ¬p) → (p → q) := sorry -- example : p ∨ ¬p := sorry -- example : (((p → q) → p) → p) := sorry
a757c169d00c40c8036e3acb80dba5abfbea82ee
2c096fdfecf64e46ea7bc6ce5521f142b5926864
/src/Lean/Meta/Tactic/Assert.lean
953fb1cc502f454075a1bdcc3bfb53bb7b3cc369
[ "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
5,740
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Tactic.FVarSubst import Lean.Meta.Tactic.Intro namespace Lean.Meta /-- Convert the given goal `Ctx |- target` into `Ctx |- type -> target`. It assumes `val` has type `type` -/ def _root_.Lean.MVarId.assert (mvarId : MVarId) (name : Name) (type : Expr) (val : Expr) : MetaM MVarId := mvarId.withContext do mvarId.checkNotAssigned `assert let tag ← mvarId.getTag let target ← mvarId.getType let newType := Lean.mkForall name BinderInfo.default type target let newMVar ← mkFreshExprSyntheticOpaqueMVar newType tag mvarId.assign (mkApp newMVar val) return newMVar.mvarId! @[deprecated MVarId.assert] def assert (mvarId : MVarId) (name : Name) (type : Expr) (val : Expr) : MetaM MVarId := mvarId.assert name type val /-- Convert the given goal `Ctx |- target` into `Ctx |- let name : type := val; target`. It assumes `val` has type `type` -/ def _root_.Lean.MVarId.define (mvarId : MVarId) (name : Name) (type : Expr) (val : Expr) : MetaM MVarId := do mvarId.withContext do mvarId.checkNotAssigned `define let tag ← mvarId.getTag let target ← mvarId.getType let newType := Lean.mkLet name type val target let newMVar ← mkFreshExprSyntheticOpaqueMVar newType tag mvarId.assign newMVar return newMVar.mvarId! @[deprecated MVarId.define] def define (mvarId : MVarId) (name : Name) (type : Expr) (val : Expr) : MetaM MVarId := do mvarId.define name type val /-- Convert the given goal `Ctx |- target` into `Ctx |- (hName : type) -> hName = val -> target`. It assumes `val` has type `type` -/ def _root_.Lean.MVarId.assertExt (mvarId : MVarId) (name : Name) (type : Expr) (val : Expr) (hName : Name := `h) : MetaM MVarId := do mvarId.withContext do mvarId.checkNotAssigned `assert let tag ← mvarId.getTag let target ← mvarId.getType let u ← getLevel type let hType := mkApp3 (mkConst `Eq [u]) type (mkBVar 0) val let newType := Lean.mkForall name BinderInfo.default type $ Lean.mkForall hName BinderInfo.default hType target let newMVar ← mkFreshExprSyntheticOpaqueMVar newType tag let rflPrf ← mkEqRefl val mvarId.assign (mkApp2 newMVar val rflPrf) return newMVar.mvarId! @[deprecated MVarId.assertExt] def assertExt (mvarId : MVarId) (name : Name) (type : Expr) (val : Expr) (hName : Name := `h) : MetaM MVarId := do mvarId.assertExt name type val hName structure AssertAfterResult where fvarId : FVarId mvarId : MVarId subst : FVarSubst /-- Convert the given goal `Ctx |- target` into a goal containing `(userName : type)` after the local declaration with if `fvarId`. It assumes `val` has type `type`, and that `type` is well-formed after `fvarId`. Note that `val` does not need to be well-formed after `fvarId`. That is, it may contain variables that are defined after `fvarId`. -/ def _root_.Lean.MVarId.assertAfter (mvarId : MVarId) (fvarId : FVarId) (userName : Name) (type : Expr) (val : Expr) : MetaM AssertAfterResult := do mvarId.withContext do mvarId.checkNotAssigned `assertAfter let tag ← mvarId.getTag let target ← mvarId.getType let localDecl ← fvarId.getDecl let lctx ← getLCtx let localInsts ← getLocalInstances let fvarIds := lctx.foldl (init := #[]) (start := localDecl.index+1) fun fvarIds decl => fvarIds.push decl.fvarId let xs := fvarIds.map mkFVar let targetNew ← mkForallFVars xs target (usedLetOnly := false) let targetNew := Lean.mkForall userName BinderInfo.default type targetNew let lctxNew := fvarIds.foldl (init := lctx) fun lctxNew fvarId => lctxNew.erase fvarId let localInstsNew := localInsts.filter fun inst => !fvarIds.contains inst.fvar.fvarId! let mvarNew ← mkFreshExprMVarAt lctxNew localInstsNew targetNew MetavarKind.syntheticOpaque tag let args := (fvarIds.filter fun fvarId => !(lctx.get! fvarId).isLet).map mkFVar let args := #[val] ++ args mvarId.assign (mkAppN mvarNew args) let (fvarIdNew, mvarIdNew) ← mvarNew.mvarId!.intro1P let (fvarIdsNew, mvarIdNew) ← mvarIdNew.introNP fvarIds.size let subst := fvarIds.size.fold (init := {}) fun i subst => subst.insert fvarIds[i]! (mkFVar fvarIdsNew[i]!) return { fvarId := fvarIdNew, mvarId := mvarIdNew, subst := subst } @[deprecated MVarId.assertAfter] def assertAfter (mvarId : MVarId) (fvarId : FVarId) (userName : Name) (type : Expr) (val : Expr) : MetaM AssertAfterResult := do mvarId.assertAfter fvarId userName type val structure Hypothesis where userName : Name type : Expr value : Expr /-- Convert the given goal `Ctx |- target` into `Ctx, (hs[0].userName : hs[0].type) ... |-target`. It assumes `hs[i].val` has type `hs[i].type`. -/ def _root_.Lean.MVarId.assertHypotheses (mvarId : MVarId) (hs : Array Hypothesis) : MetaM (Array FVarId × MVarId) := do if hs.isEmpty then return (#[], mvarId) else mvarId.withContext do mvarId.checkNotAssigned `assertHypotheses let tag ← mvarId.getTag let target ← mvarId.getType let targetNew := hs.foldr (init := target) fun h targetNew => mkForall h.userName BinderInfo.default h.type targetNew let mvarNew ← mkFreshExprSyntheticOpaqueMVar targetNew tag let val := hs.foldl (init := mvarNew) fun val h => mkApp val h.value mvarId.assign val mvarNew.mvarId!.introNP hs.size @[deprecated MVarId.assertHypotheses] def assertHypotheses (mvarId : MVarId) (hs : Array Hypothesis) : MetaM (Array FVarId × MVarId) := do mvarId.assertHypotheses hs end Lean.Meta
f06598d19f6b3259bf9fcf098563d566bab45c4b
87fd6b43d22688237c02b87c30d2a524f53bab24
/src/game/sets/sets_level07.lean
953af33c58beca6e6782ac19d6c3596bf7c6a6b3
[ "Apache-2.0" ]
permissive
grthomson/real-number-game
66142fedf0987db90f66daed52f9c8b42b70f909
8ddc15fdddc241c246653f7bb341df36e4e880a8
refs/heads/master
1,668,059,330,605
1,592,873,454,000
1,592,873,454,000
262,025,764
0
0
null
1,588,849,107,000
1,588,849,106,000
null
UTF-8
Lean
false
false
724
lean
import tactic --hide import game.sets.sets_level06 -- hide variable X : Type --hide open_locale classical -- hide namespace xena -- hide /- # Chapter 1 : Sets ## Level 7 : The empty set -/ /- The way to handle the empty set is the following: ``` lemma mem_empty_iff (a : X) : a ∈ (∅ : set X) ↔ false ``` -/ /- Axiom : mem_empty_iff : a ∈ (∅ : set X) ↔ false -/ /- Hint : Hint Remember that `exfalso` changes any goal to `false`. This can be convenient if your hypotheses can prove `false`. -/ /- Lemma The empty set is a subset of any set $A$. -/ theorem empty_set_subset (A : set X) : ∅ ⊆ A := begin rw subset_iff, intros x hx, exfalso, rw mem_empty_iff at hx, exact hx, end end xena
294513597b9e21bc38446c7f13ef90b60e4eb6ac
82e44445c70db0f03e30d7be725775f122d72f3e
/src/algebra/big_operators/basic.lean
f2c3a73e09fff3a33f4a4f5c4fbce87281520fd0
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
59,921
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import data.finset.fold import data.equiv.mul_add import tactic.abel /-! # Big operators In this file we define products and sums indexed by finite sets (specifically, `finset`). ## Notation We introduce the following notation, localized in `big_operators`. To enable the notation, use `open_locale big_operators`. Let `s` be a `finset α`, and `f : α → β` a function. * `∏ x in s, f x` is notation for `finset.prod s f` (assuming `β` is a `comm_monoid`) * `∑ x in s, f x` is notation for `finset.sum s f` (assuming `β` is an `add_comm_monoid`) * `∏ x, f x` is notation for `finset.prod finset.univ f` (assuming `α` is a `fintype` and `β` is a `comm_monoid`) * `∑ x, f x` is notation for `finset.sum finset.univ f` (assuming `α` is a `fintype` and `β` is an `add_comm_monoid`) ## Implementation Notes The first arguments in all definitions and lemmas is the codomain of the function of the big operator. This is necessary for the heuristic in `@[to_additive]`. See the documentation of `to_additive.attr` for more information. -/ universes u v w variables {β : Type u} {α : Type v} {γ : Type w} namespace finset /-- `∏ x in s, f x` is the product of `f x` as `x` ranges over the elements of the finite set `s`. -/ @[to_additive "`∑ x in s, f` is the sum of `f x` as `x` ranges over the elements of the finite set `s`."] protected def prod [comm_monoid β] (s : finset α) (f : α → β) : β := (s.1.map f).prod @[simp, to_additive] lemma prod_mk [comm_monoid β] (s : multiset α) (hs : s.nodup) (f : α → β) : (⟨s, hs⟩ : finset α).prod f = (s.map f).prod := rfl end finset /-- There is no established mathematical convention for the operator precedence of big operators like `∏` and `∑`. We will have to make a choice. Online discussions, such as https://math.stackexchange.com/q/185538/30839 seem to suggest that `∏` and `∑` should have the same precedence, and that this should be somewhere between `*` and `+`. The latter have precedence levels `70` and `65` respectively, and we therefore choose the level `67`. In practice, this means that parentheses should be placed as follows: ```lean ∑ k in K, (a k + b k) = ∑ k in K, a k + ∑ k in K, b k → ∏ k in K, a k * b k = (∏ k in K, a k) * (∏ k in K, b k) ``` (Example taken from page 490 of Knuth's *Concrete Mathematics*.) -/ library_note "operator precedence of big operators" localized "notation `∑` binders `, ` r:(scoped:67 f, finset.sum finset.univ f) := r" in big_operators localized "notation `∏` binders `, ` r:(scoped:67 f, finset.prod finset.univ f) := r" in big_operators localized "notation `∑` binders ` in ` s `, ` r:(scoped:67 f, finset.sum s f) := r" in big_operators localized "notation `∏` binders ` in ` s `, ` r:(scoped:67 f, finset.prod s f) := r" in big_operators open_locale big_operators namespace finset variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} @[to_additive] lemma prod_eq_multiset_prod [comm_monoid β] (s : finset α) (f : α → β) : ∏ x in s, f x = (s.1.map f).prod := rfl @[to_additive] theorem prod_eq_fold [comm_monoid β] (s : finset α) (f : α → β) : ∏ x in s, f x = s.fold (*) 1 f := rfl @[simp] lemma sum_multiset_singleton (s : finset α) : s.sum (λ x, x ::ₘ 0) = s.val := by simp [sum_eq_multiset_sum] end finset @[to_additive] lemma monoid_hom.map_prod [comm_monoid β] [comm_monoid γ] (g : β →* γ) (f : α → β) (s : finset α) : g (∏ x in s, f x) = ∏ x in s, g (f x) := by simp only [finset.prod_eq_multiset_prod, g.map_multiset_prod, multiset.map_map] @[to_additive] lemma mul_equiv.map_prod [comm_monoid β] [comm_monoid γ] (g : β ≃* γ) (f : α → β) (s : finset α) : g (∏ x in s, f x) = ∏ x in s, g (f x) := g.to_monoid_hom.map_prod f s lemma ring_hom.map_list_prod [semiring β] [semiring γ] (f : β →+* γ) (l : list β) : f l.prod = (l.map f).prod := f.to_monoid_hom.map_list_prod l lemma ring_hom.map_list_sum [non_assoc_semiring β] [non_assoc_semiring γ] (f : β →+* γ) (l : list β) : f l.sum = (l.map f).sum := f.to_add_monoid_hom.map_list_sum l lemma ring_hom.map_multiset_prod [comm_semiring β] [comm_semiring γ] (f : β →+* γ) (s : multiset β) : f s.prod = (s.map f).prod := f.to_monoid_hom.map_multiset_prod s lemma ring_hom.map_multiset_sum [non_assoc_semiring β] [non_assoc_semiring γ] (f : β →+* γ) (s : multiset β) : f s.sum = (s.map f).sum := f.to_add_monoid_hom.map_multiset_sum s lemma ring_hom.map_prod [comm_semiring β] [comm_semiring γ] (g : β →+* γ) (f : α → β) (s : finset α) : g (∏ x in s, f x) = ∏ x in s, g (f x) := g.to_monoid_hom.map_prod f s lemma ring_hom.map_sum [non_assoc_semiring β] [non_assoc_semiring γ] (g : β →+* γ) (f : α → β) (s : finset α) : g (∑ x in s, f x) = ∑ x in s, g (f x) := g.to_add_monoid_hom.map_sum f s @[to_additive] lemma monoid_hom.coe_prod [mul_one_class β] [comm_monoid γ] (f : α → β →* γ) (s : finset α) : ⇑(∏ x in s, f x) = ∏ x in s, f x := (monoid_hom.coe_fn β γ).map_prod _ _ -- See also `finset.prod_apply`, with the same conclusion -- but with the weaker hypothesis `f : α → β → γ`. @[simp, to_additive] lemma monoid_hom.finset_prod_apply [mul_one_class β] [comm_monoid γ] (f : α → β →* γ) (s : finset α) (b : β) : (∏ x in s, f x) b = ∏ x in s, f x b := (monoid_hom.eval b).map_prod _ _ variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} namespace finset section comm_monoid variables [comm_monoid β] @[simp, to_additive] lemma prod_empty {f : α → β} : (∏ x in (∅:finset α), f x) = 1 := rfl @[simp, to_additive] lemma prod_insert [decidable_eq α] : a ∉ s → (∏ x in (insert a s), f x) = f a * ∏ x in s, f x := fold_insert /-- The product of `f` over `insert a s` is the same as the product over `s`, as long as `a` is in `s` or `f a = 1`. -/ @[simp, to_additive "The sum of `f` over `insert a s` is the same as the sum over `s`, as long as `a` is in `s` or `f a = 0`."] lemma prod_insert_of_eq_one_if_not_mem [decidable_eq α] (h : a ∉ s → f a = 1) : ∏ x in insert a s, f x = ∏ x in s, f x := begin by_cases hm : a ∈ s, { simp_rw insert_eq_of_mem hm }, { rw [prod_insert hm, h hm, one_mul] }, end /-- The product of `f` over `insert a s` is the same as the product over `s`, as long as `f a = 1`. -/ @[simp, to_additive "The sum of `f` over `insert a s` is the same as the sum over `s`, as long as `f a = 0`."] lemma prod_insert_one [decidable_eq α] (h : f a = 1) : ∏ x in insert a s, f x = ∏ x in s, f x := prod_insert_of_eq_one_if_not_mem (λ _, h) @[simp, to_additive] lemma prod_singleton : (∏ x in (singleton a), f x) = f a := eq.trans fold_singleton $ mul_one _ @[to_additive] lemma prod_pair [decidable_eq α] {a b : α} (h : a ≠ b) : (∏ x in ({a, b} : finset α), f x) = f a * f b := by rw [prod_insert (not_mem_singleton.2 h), prod_singleton] @[simp, priority 1100, to_additive] lemma prod_const_one : (∏ x in s, (1 : β)) = 1 := by simp only [finset.prod, multiset.map_const, multiset.prod_repeat, one_pow] @[simp, to_additive] lemma prod_image [decidable_eq α] {s : finset γ} {g : γ → α} : (∀ x ∈ s, ∀ y ∈ s, g x = g y → x = y) → (∏ x in (s.image g), f x) = ∏ x in s, f (g x) := fold_image @[simp, to_additive] lemma prod_map (s : finset α) (e : α ↪ γ) (f : γ → β) : (∏ x in (s.map e), f x) = ∏ x in s, f (e x) := by rw [finset.prod, finset.map_val, multiset.map_map]; refl @[congr, to_additive] lemma prod_congr (h : s₁ = s₂) : (∀ x ∈ s₂, f x = g x) → s₁.prod f = s₂.prod g := by rw [h]; exact fold_congr attribute [congr] finset.sum_congr @[to_additive] lemma prod_union_inter [decidable_eq α] : (∏ x in (s₁ ∪ s₂), f x) * (∏ x in (s₁ ∩ s₂), f x) = (∏ x in s₁, f x) * (∏ x in s₂, f x) := fold_union_inter @[to_additive] lemma prod_union [decidable_eq α] (h : disjoint s₁ s₂) : (∏ x in (s₁ ∪ s₂), f x) = (∏ x in s₁, f x) * (∏ x in s₂, f x) := by rw [←prod_union_inter, (disjoint_iff_inter_eq_empty.mp h)]; exact (mul_one _).symm end comm_monoid end finset section open finset variables [fintype α] [decidable_eq α] [comm_monoid β] @[to_additive] lemma is_compl.prod_mul_prod {s t : finset α} (h : is_compl s t) (f : α → β) : (∏ i in s, f i) * (∏ i in t, f i) = ∏ i, f i := (finset.prod_union h.disjoint).symm.trans $ by rw [← finset.sup_eq_union, h.sup_eq_top]; refl end namespace finset section comm_monoid variables [comm_monoid β] @[to_additive] lemma prod_mul_prod_compl [fintype α] [decidable_eq α] (s : finset α) (f : α → β) : (∏ i in s, f i) * (∏ i in sᶜ, f i) = ∏ i, f i := is_compl_compl.prod_mul_prod f @[to_additive] lemma prod_compl_mul_prod [fintype α] [decidable_eq α] (s : finset α) (f : α → β) : (∏ i in sᶜ, f i) * (∏ i in s, f i) = ∏ i, f i := is_compl_compl.symm.prod_mul_prod f @[to_additive] lemma prod_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) : (∏ x in (s₂ \ s₁), f x) * (∏ x in s₁, f x) = (∏ x in s₂, f x) := by rw [←prod_union sdiff_disjoint, sdiff_union_of_subset h] @[simp, to_additive] lemma prod_sum_elim [decidable_eq (α ⊕ γ)] (s : finset α) (t : finset γ) (f : α → β) (g : γ → β) : ∏ x in s.map function.embedding.inl ∪ t.map function.embedding.inr, sum.elim f g x = (∏ x in s, f x) * (∏ x in t, g x) := begin rw [prod_union, prod_map, prod_map], { simp only [sum.elim_inl, function.embedding.inl_apply, function.embedding.inr_apply, sum.elim_inr] }, { simp only [disjoint_left, finset.mem_map, finset.mem_map], rintros _ ⟨i, hi, rfl⟩ ⟨j, hj, H⟩, cases H } end @[to_additive] lemma prod_bUnion [decidable_eq α] {s : finset γ} {t : γ → finset α} : (∀ x ∈ s, ∀ y ∈ s, x ≠ y → disjoint (t x) (t y)) → (∏ x in (s.bUnion t), f x) = ∏ x in s, ∏ i in t x, f i := by haveI := classical.dec_eq γ; exact finset.induction_on s (λ _, by simp only [bUnion_empty, prod_empty]) (assume x s hxs ih hd, have hd' : ∀ x ∈ s, ∀ y ∈ s, x ≠ y → disjoint (t x) (t y), from assume _ hx _ hy, hd _ (mem_insert_of_mem hx) _ (mem_insert_of_mem hy), have ∀ y ∈ s, x ≠ y, from assume _ hy h, by rw [←h] at hy; contradiction, have ∀ y ∈ s, disjoint (t x) (t y), from assume _ hy, hd _ (mem_insert_self _ _) _ (mem_insert_of_mem hy) (this _ hy), have disjoint (t x) (finset.bUnion s t), from (disjoint_bUnion_right _ _ _).mpr this, by simp only [bUnion_insert, prod_insert hxs, prod_union this, ih hd']) @[to_additive] lemma prod_product {s : finset γ} {t : finset α} {f : γ×α → β} : (∏ x in s.product t, f x) = ∏ x in s, ∏ y in t, f (x, y) := begin haveI := classical.dec_eq α, haveI := classical.dec_eq γ, rw [product_eq_bUnion, prod_bUnion], { congr, funext, exact prod_image (λ _ _ _ _ H, (prod.mk.inj H).2) }, simp only [disjoint_iff_ne, mem_image], rintros _ _ _ _ h ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ _, apply h, cc end /-- An uncurried version of `finset.prod_product`. -/ @[to_additive "An uncurried version of `finset.sum_product`"] lemma prod_product' {s : finset γ} {t : finset α} {f : γ → α → β} : (∏ x in s.product t, f x.1 x.2) = ∏ x in s, ∏ y in t, f x y := prod_product /-- Product over a sigma type equals the product of fiberwise products. For rewriting in the reverse direction, use `finset.prod_sigma'`. -/ @[to_additive "Sum over a sigma type equals the sum of fiberwise sums. For rewriting in the reverse direction, use `finset.sum_sigma'`"] lemma prod_sigma {σ : α → Type*} (s : finset α) (t : Π a, finset (σ a)) (f : sigma σ → β) : (∏ x in s.sigma t, f x) = ∏ a in s, ∏ s in (t a), f ⟨a, s⟩ := by classical; calc (∏ x in s.sigma t, f x) = ∏ x in s.bUnion (λ a, (t a).map (function.embedding.sigma_mk a)), f x : by rw sigma_eq_bUnion ... = ∏ a in s, ∏ x in (t a).map (function.embedding.sigma_mk a), f x : prod_bUnion $ assume a₁ ha a₂ ha₂ h x hx, by { simp only [inf_eq_inter, mem_inter, mem_map, function.embedding.sigma_mk_apply] at hx, rcases hx with ⟨⟨y, hy, rfl⟩, ⟨z, hz, hz'⟩⟩, cc } ... = ∏ a in s, ∏ s in t a, f ⟨a, s⟩ : prod_congr rfl $ λ _ _, prod_map _ _ _ @[to_additive] lemma prod_sigma' {σ : α → Type*} (s : finset α) (t : Π a, finset (σ a)) (f : Π a, σ a → β) : (∏ a in s, ∏ s in (t a), f a s) = ∏ x in s.sigma t, f x.1 x.2 := eq.symm $ prod_sigma s t (λ x, f x.1 x.2) @[to_additive] lemma prod_fiberwise_of_maps_to [decidable_eq γ] {s : finset α} {t : finset γ} {g : α → γ} (h : ∀ x ∈ s, g x ∈ t) (f : α → β) : (∏ y in t, ∏ x in s.filter (λ x, g x = y), f x) = ∏ x in s, f x := begin letI := classical.dec_eq α, rw [← bUnion_filter_eq_of_maps_to h] {occs := occurrences.pos [2]}, refine (prod_bUnion $ λ x' hx y' hy hne, _).symm, rw [disjoint_filter], rintros x hx rfl, exact hne end @[to_additive] lemma prod_image' [decidable_eq α] {s : finset γ} {g : γ → α} (h : γ → β) (eq : ∀ c ∈ s, f (g c) = ∏ x in s.filter (λ c', g c' = g c), h x) : (∏ x in s.image g, f x) = ∏ x in s, h x := calc (∏ x in s.image g, f x) = ∏ x in s.image g, ∏ x in s.filter (λ c', g c' = x), h x : prod_congr rfl $ λ x hx, let ⟨c, hcs, hc⟩ := mem_image.1 hx in hc ▸ (eq c hcs) ... = ∏ x in s, h x : prod_fiberwise_of_maps_to (λ x, mem_image_of_mem g) _ @[to_additive] lemma prod_mul_distrib : ∏ x in s, (f x * g x) = (∏ x in s, f x) * (∏ x in s, g x) := eq.trans (by rw one_mul; refl) fold_op_distrib @[to_additive] lemma prod_comm {s : finset γ} {t : finset α} {f : γ → α → β} : (∏ x in s, ∏ y in t, f x y) = (∏ y in t, ∏ x in s, f x y) := begin classical, apply finset.induction_on s, { simp only [prod_empty, prod_const_one] }, { intros _ _ H ih, simp only [prod_insert H, prod_mul_distrib, ih] } end @[to_additive] lemma prod_hom_rel [comm_monoid γ] {r : β → γ → Prop} {f : α → β} {g : α → γ} {s : finset α} (h₁ : r 1 1) (h₂ : ∀ a b c, r b c → r (f a * b) (g a * c)) : r (∏ x in s, f x) (∏ x in s, g x) := by { delta finset.prod, apply multiset.prod_hom_rel; assumption } @[to_additive] lemma prod_subset (h : s₁ ⊆ s₂) (hf : ∀ x ∈ s₂, x ∉ s₁ → f x = 1) : (∏ x in s₁, f x) = ∏ x in s₂, f x := by haveI := classical.dec_eq α; exact have ∏ x in s₂ \ s₁, f x = ∏ x in s₂ \ s₁, 1, from prod_congr rfl $ by simpa only [mem_sdiff, and_imp], by rw [←prod_sdiff h]; simp only [this, prod_const_one, one_mul] @[to_additive] lemma prod_filter_of_ne {p : α → Prop} [decidable_pred p] (hp : ∀ x ∈ s, f x ≠ 1 → p x) : (∏ x in (s.filter p), f x) = (∏ x in s, f x) := prod_subset (filter_subset _ _) $ λ x, by { classical, rw [not_imp_comm, mem_filter], exact λ h₁ h₂, ⟨h₁, hp _ h₁ h₂⟩ } -- If we use `[decidable_eq β]` here, some rewrites fail because they find a wrong `decidable` -- instance first; `{∀ x, decidable (f x ≠ 1)}` doesn't work with `rw ← prod_filter_ne_one` @[to_additive] lemma prod_filter_ne_one [∀ x, decidable (f x ≠ 1)] : (∏ x in (s.filter $ λ x, f x ≠ 1), f x) = (∏ x in s, f x) := prod_filter_of_ne $ λ _ _, id @[to_additive] lemma prod_filter (p : α → Prop) [decidable_pred p] (f : α → β) : (∏ a in s.filter p, f a) = (∏ a in s, if p a then f a else 1) := calc (∏ a in s.filter p, f a) = ∏ a in s.filter p, if p a then f a else 1 : prod_congr rfl (assume a h, by rw [if_pos (mem_filter.1 h).2]) ... = ∏ a in s, if p a then f a else 1 : begin refine prod_subset (filter_subset _ s) (assume x hs h, _), rw [mem_filter, not_and] at h, exact if_neg (h hs) end @[to_additive] lemma prod_eq_single_of_mem {s : finset α} {f : α → β} (a : α) (h : a ∈ s) (h₀ : ∀ b ∈ s, b ≠ a → f b = 1) : (∏ x in s, f x) = f a := begin haveI := classical.dec_eq α, calc (∏ x in s, f x) = ∏ x in {a}, f x : begin refine (prod_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { simpa only [mem_singleton] } end ... = f a : prod_singleton end @[to_additive] lemma prod_eq_single {s : finset α} {f : α → β} (a : α) (h₀ : ∀ b ∈ s, b ≠ a → f b = 1) (h₁ : a ∉ s → f a = 1) : (∏ x in s, f x) = f a := by haveI := classical.dec_eq α; from classical.by_cases (assume : a ∈ s, prod_eq_single_of_mem a this h₀) (assume : a ∉ s, (prod_congr rfl $ λ b hb, h₀ b hb $ by rintro rfl; cc).trans $ prod_const_one.trans (h₁ this).symm) @[to_additive] lemma prod_eq_mul_of_mem {s : finset α} {f : α → β} (a b : α) (ha : a ∈ s) (hb : b ∈ s) (hn : a ≠ b) (h₀ : ∀ c ∈ s, c ≠ a ∧ c ≠ b → f c = 1) : (∏ x in s, f x) = (f a) * (f b) := begin haveI := classical.dec_eq α; let s' := ({a, b} : finset α), have hu : s' ⊆ s, { refine insert_subset.mpr _, apply and.intro ha, apply singleton_subset_iff.mpr hb }, have hf : ∀ c ∈ s, c ∉ s' → f c = 1, { intros c hc hcs, apply h₀ c hc, apply not_or_distrib.mp, intro hab, apply hcs, apply mem_insert.mpr, rw mem_singleton, exact hab }, rw ←prod_subset hu hf, exact finset.prod_pair hn end @[to_additive] lemma prod_eq_mul {s : finset α} {f : α → β} (a b : α) (hn : a ≠ b) (h₀ : ∀ c ∈ s, c ≠ a ∧ c ≠ b → f c = 1) (ha : a ∉ s → f a = 1) (hb : b ∉ s → f b = 1) : (∏ x in s, f x) = (f a) * (f b) := begin haveI := classical.dec_eq α; by_cases h₁ : a ∈ s; by_cases h₂ : b ∈ s, { exact prod_eq_mul_of_mem a b h₁ h₂ hn h₀ }, { rw [hb h₂, mul_one], apply prod_eq_single_of_mem a h₁, exact λ c hc hca, h₀ c hc ⟨hca, ne_of_mem_of_not_mem hc h₂⟩ }, { rw [ha h₁, one_mul], apply prod_eq_single_of_mem b h₂, exact λ c hc hcb, h₀ c hc ⟨ne_of_mem_of_not_mem hc h₁, hcb⟩ }, { rw [ha h₁, hb h₂, mul_one], exact trans (prod_congr rfl (λ c hc, h₀ c hc ⟨ne_of_mem_of_not_mem hc h₁, ne_of_mem_of_not_mem hc h₂⟩)) prod_const_one } end @[to_additive] lemma prod_attach {f : α → β} : (∏ x in s.attach, f x) = (∏ x in s, f x) := by haveI := classical.dec_eq α; exact calc (∏ x in s.attach, f x.val) = (∏ x in (s.attach).image subtype.val, f x) : by rw [prod_image]; exact assume x _ y _, subtype.eq ... = _ : by rw [attach_image_val] /-- A product over `s.subtype p` equals one over `s.filter p`. -/ @[simp, to_additive "A sum over `s.subtype p` equals one over `s.filter p`."] lemma prod_subtype_eq_prod_filter (f : α → β) {p : α → Prop} [decidable_pred p] : ∏ x in s.subtype p, f x = ∏ x in s.filter p, f x := begin conv_lhs { erw ←prod_map (s.subtype p) (function.embedding.subtype _) f }, exact prod_congr (subtype_map _) (λ x hx, rfl) end /-- If all elements of a `finset` satisfy the predicate `p`, a product over `s.subtype p` equals that product over `s`. -/ @[to_additive "If all elements of a `finset` satisfy the predicate `p`, a sum over `s.subtype p` equals that sum over `s`."] lemma prod_subtype_of_mem (f : α → β) {p : α → Prop} [decidable_pred p] (h : ∀ x ∈ s, p x) : ∏ x in s.subtype p, f x = ∏ x in s, f x := by simp_rw [prod_subtype_eq_prod_filter, filter_true_of_mem h] /-- A product of a function over a `finset` in a subtype equals a product in the main type of a function that agrees with the first function on that `finset`. -/ @[to_additive "A sum of a function over a `finset` in a subtype equals a sum in the main type of a function that agrees with the first function on that `finset`."] lemma prod_subtype_map_embedding {p : α → Prop} {s : finset {x // p x}} {f : {x // p x} → β} {g : α → β} (h : ∀ x : {x // p x}, x ∈ s → g x = f x) : ∏ x in s.map (function.embedding.subtype _), g x = ∏ x in s, f x := begin rw finset.prod_map, exact finset.prod_congr rfl h end @[to_additive] lemma prod_finset_coe (f : α → β) (s : finset α) : ∏ (i : (s : set α)), f i = ∏ i in s, f i := prod_attach @[to_additive] lemma prod_subtype {p : α → Prop} {F : fintype (subtype p)} (s : finset α) (h : ∀ x, x ∈ s ↔ p x) (f : α → β) : ∏ a in s, f a = ∏ a : subtype p, f a := have (∈ s) = p, from set.ext h, by { substI p, rw [←prod_finset_coe], congr } @[to_additive] lemma prod_eq_one {f : α → β} {s : finset α} (h : ∀ x ∈ s, f x = 1) : (∏ x in s, f x) = 1 := calc (∏ x in s, f x) = ∏ x in s, 1 : finset.prod_congr rfl h ... = 1 : finset.prod_const_one @[to_additive] lemma prod_apply_dite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f : Π (x : α), p x → γ) (g : Π (x : α), ¬p x → γ) (h : γ → β) : (∏ x in s, h (if hx : p x then f x hx else g x hx)) = (∏ x in (s.filter p).attach, h (f x.1 (mem_filter.mp x.2).2)) * (∏ x in (s.filter (λ x, ¬ p x)).attach, h (g x.1 (mem_filter.mp x.2).2)) := by letI := classical.dec_eq α; exact calc ∏ x in s, h (if hx : p x then f x hx else g x hx) = ∏ x in s.filter p ∪ s.filter (λ x, ¬ p x), h (if hx : p x then f x hx else g x hx) : by rw [filter_union_filter_neg_eq] ... = (∏ x in s.filter p, h (if hx : p x then f x hx else g x hx)) * (∏ x in s.filter (λ x, ¬ p x), h (if hx : p x then f x hx else g x hx)) : prod_union (by simp [disjoint_right] {contextual := tt}) ... = (∏ x in (s.filter p).attach, h (if hx : p x.1 then f x.1 hx else g x.1 hx)) * (∏ x in (s.filter (λ x, ¬ p x)).attach, h (if hx : p x.1 then f x.1 hx else g x.1 hx)) : congr_arg2 _ prod_attach.symm prod_attach.symm ... = (∏ x in (s.filter p).attach, h (f x.1 (mem_filter.mp x.2).2)) * (∏ x in (s.filter (λ x, ¬ p x)).attach, h (g x.1 (mem_filter.mp x.2).2)) : congr_arg2 _ (prod_congr rfl (λ x hx, congr_arg h (dif_pos (mem_filter.mp x.2).2))) (prod_congr rfl (λ x hx, congr_arg h (dif_neg (mem_filter.mp x.2).2))) @[to_additive] lemma prod_apply_ite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f g : α → γ) (h : γ → β) : (∏ x in s, h (if p x then f x else g x)) = (∏ x in s.filter p, h (f x)) * (∏ x in s.filter (λ x, ¬ p x), h (g x)) := trans (prod_apply_dite _ _ _) (congr_arg2 _ (@prod_attach _ _ _ _ (h ∘ f)) (@prod_attach _ _ _ _ (h ∘ g))) @[to_additive] lemma prod_dite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f : Π (x : α), p x → β) (g : Π (x : α), ¬p x → β) : (∏ x in s, if hx : p x then f x hx else g x hx) = (∏ x in (s.filter p).attach, f x.1 (mem_filter.mp x.2).2) * (∏ x in (s.filter (λ x, ¬ p x)).attach, g x.1 (mem_filter.mp x.2).2) := by simp [prod_apply_dite _ _ (λ x, x)] @[to_additive] lemma prod_ite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f g : α → β) : (∏ x in s, if p x then f x else g x) = (∏ x in s.filter p, f x) * (∏ x in s.filter (λ x, ¬ p x), g x) := by simp [prod_apply_ite _ _ (λ x, x)] @[to_additive] lemma prod_ite_of_false {p : α → Prop} {hp : decidable_pred p} (f g : α → β) (h : ∀ x ∈ s, ¬p x) : (∏ x in s, if p x then f x else g x) = (∏ x in s, g x) := by { rw prod_ite, simp [filter_false_of_mem h, filter_true_of_mem h] } @[to_additive] lemma prod_ite_of_true {p : α → Prop} {hp : decidable_pred p} (f g : α → β) (h : ∀ x ∈ s, p x) : (∏ x in s, if p x then f x else g x) = (∏ x in s, f x) := by { simp_rw ←(ite_not (p _)), apply prod_ite_of_false, simpa } @[to_additive] lemma prod_apply_ite_of_false {p : α → Prop} {hp : decidable_pred p} (f g : α → γ) (k : γ → β) (h : ∀ x ∈ s, ¬p x) : (∏ x in s, k (if p x then f x else g x)) = (∏ x in s, k (g x)) := by { simp_rw apply_ite k, exact prod_ite_of_false _ _ h } @[to_additive] lemma prod_apply_ite_of_true {p : α → Prop} {hp : decidable_pred p} (f g : α → γ) (k : γ → β) (h : ∀ x ∈ s, p x) : (∏ x in s, k (if p x then f x else g x)) = (∏ x in s, k (f x)) := by { simp_rw apply_ite k, exact prod_ite_of_true _ _ h } @[to_additive] lemma prod_extend_by_one [decidable_eq α] (s : finset α) (f : α → β) : ∏ i in s, (if i ∈ s then f i else 1) = ∏ i in s, f i := prod_congr rfl $ λ i hi, if_pos hi @[simp, to_additive] lemma prod_dite_eq [decidable_eq α] (s : finset α) (a : α) (b : Π x : α, a = x → β) : (∏ x in s, (if h : a = x then b x h else 1)) = ite (a ∈ s) (b a rfl) 1 := begin split_ifs with h, { rw [finset.prod_eq_single a, dif_pos rfl], { intros, rw dif_neg, cc }, { cc } }, { rw finset.prod_eq_one, intros, rw dif_neg, intro, cc } end @[simp, to_additive] lemma prod_dite_eq' [decidable_eq α] (s : finset α) (a : α) (b : Π x : α, x = a → β) : (∏ x in s, (if h : x = a then b x h else 1)) = ite (a ∈ s) (b a rfl) 1 := begin split_ifs with h, { rw [finset.prod_eq_single a, dif_pos rfl], { intros, rw dif_neg, cc }, { cc } }, { rw finset.prod_eq_one, intros, rw dif_neg, intro, cc } end @[simp, to_additive] lemma prod_ite_eq [decidable_eq α] (s : finset α) (a : α) (b : α → β) : (∏ x in s, (ite (a = x) (b x) 1)) = ite (a ∈ s) (b a) 1 := prod_dite_eq s a (λ x _, b x) /-- When a product is taken over a conditional whose condition is an equality test on the index and whose alternative is 1, then the product's value is either the term at that index or `1`. The difference with `prod_ite_eq` is that the arguments to `eq` are swapped. -/ @[simp, to_additive] lemma prod_ite_eq' [decidable_eq α] (s : finset α) (a : α) (b : α → β) : (∏ x in s, (ite (x = a) (b x) 1)) = ite (a ∈ s) (b a) 1 := prod_dite_eq' s a (λ x _, b x) @[to_additive] lemma prod_ite_index (p : Prop) [decidable p] (s t : finset α) (f : α → β) : (∏ x in if p then s else t, f x) = if p then ∏ x in s, f x else ∏ x in t, f x := apply_ite (λ s, ∏ x in s, f x) _ _ _ @[simp, to_additive] lemma prod_dite_irrel (p : Prop) [decidable p] (s : finset α) (f : p → α → β) (g : ¬p → α → β): (∏ x in s, if h : p then f h x else g h x) = if h : p then ∏ x in s, f h x else ∏ x in s, g h x := by { split_ifs with h; refl } @[simp] lemma sum_pi_single' {ι M : Type*} [decidable_eq ι] [add_comm_monoid M] (i : ι) (x : M) (s : finset ι) : ∑ j in s, pi.single i x j = if i ∈ s then x else 0 := sum_dite_eq' _ _ _ @[simp] lemma sum_pi_single {ι : Type*} {M : ι → Type*} [decidable_eq ι] [Π i, add_comm_monoid (M i)] (i : ι) (f : Π i, M i) (s : finset ι) : ∑ j in s, pi.single j (f j) i = if i ∈ s then f i else 0 := sum_dite_eq _ _ _ /-- Reorder a product. The difference with `prod_bij'` is that the bijection is specified as a surjective injection, rather than by an inverse function. -/ @[to_additive " Reorder a sum. The difference with `sum_bij'` is that the bijection is specified as a surjective injection, rather than by an inverse function. "] lemma prod_bij {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Π a ∈ s, γ) (hi : ∀ a ha, i a ha ∈ t) (h : ∀ a ha, f a = g (i a ha)) (i_inj : ∀ a₁ a₂ ha₁ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂) (i_surj : ∀ b ∈ t, ∃ a ha, b = i a ha) : (∏ x in s, f x) = (∏ x in t, g x) := congr_arg multiset.prod (multiset.map_eq_map_of_bij_of_nodup f g s.2 t.2 i hi h i_inj i_surj) /-- Reorder a product. The difference with `prod_bij` is that the bijection is specified with an inverse, rather than as a surjective injection. -/ @[to_additive " Reorder a sum. The difference with `sum_bij` is that the bijection is specified with an inverse, rather than as a surjective injection. "] lemma prod_bij' {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Π a ∈ s, γ) (hi : ∀ a ha, i a ha ∈ t) (h : ∀ a ha, f a = g (i a ha)) (j : Π a ∈ t, α) (hj : ∀ a ha, j a ha ∈ s) (left_inv : ∀ a ha, j (i a ha) (hi a ha) = a) (right_inv : ∀ a ha, i (j a ha) (hj a ha) = a) : (∏ x in s, f x) = (∏ x in t, g x) := begin refine prod_bij i hi h _ _, {intros a1 a2 h1 h2 eq, rw [←left_inv a1 h1, ←left_inv a2 h2], cc,}, {intros b hb, use j b hb, use hj b hb, exact (right_inv b hb).symm,}, end @[to_additive] lemma prod_bij_ne_one {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Π a ∈ s, f a ≠ 1 → γ) (hi : ∀ a h₁ h₂, i a h₁ h₂ ∈ t) (i_inj : ∀ a₁ a₂ h₁₁ h₁₂ h₂₁ h₂₂, i a₁ h₁₁ h₁₂ = i a₂ h₂₁ h₂₂ → a₁ = a₂) (i_surj : ∀ b ∈ t, g b ≠ 1 → ∃ a h₁ h₂, b = i a h₁ h₂) (h : ∀ a h₁ h₂, f a = g (i a h₁ h₂)) : (∏ x in s, f x) = (∏ x in t, g x) := by classical; exact calc (∏ x in s, f x) = ∏ x in (s.filter $ λ x, f x ≠ 1), f x : prod_filter_ne_one.symm ... = ∏ x in (t.filter $ λ x, g x ≠ 1), g x : prod_bij (assume a ha, i a (mem_filter.mp ha).1 (mem_filter.mp ha).2) (assume a ha, (mem_filter.mp ha).elim $ λ h₁ h₂, mem_filter.mpr ⟨hi a h₁ h₂, λ hg, h₂ (hg ▸ h a h₁ h₂)⟩) (assume a ha, (mem_filter.mp ha).elim $ h a) (assume a₁ a₂ ha₁ ha₂, (mem_filter.mp ha₁).elim $ λ ha₁₁ ha₁₂, (mem_filter.mp ha₂).elim $ λ ha₂₁ ha₂₂, i_inj a₁ a₂ _ _ _ _) (assume b hb, (mem_filter.mp hb).elim $ λ h₁ h₂, let ⟨a, ha₁, ha₂, eq⟩ := i_surj b h₁ h₂ in ⟨a, mem_filter.mpr ⟨ha₁, ha₂⟩, eq⟩) ... = (∏ x in t, g x) : prod_filter_ne_one @[to_additive] lemma nonempty_of_prod_ne_one (h : (∏ x in s, f x) ≠ 1) : s.nonempty := s.eq_empty_or_nonempty.elim (λ H, false.elim $ h $ H.symm ▸ prod_empty) id @[to_additive] lemma exists_ne_one_of_prod_ne_one (h : (∏ x in s, f x) ≠ 1) : ∃ a ∈ s, f a ≠ 1 := begin classical, rw ← prod_filter_ne_one at h, rcases nonempty_of_prod_ne_one h with ⟨x, hx⟩, exact ⟨x, (mem_filter.1 hx).1, (mem_filter.1 hx).2⟩ end @[to_additive] lemma prod_subset_one_on_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) (hg : ∀ x ∈ (s₂ \ s₁), g x = 1) (hfg : ∀ x ∈ s₁, f x = g x) : ∏ i in s₁, f i = ∏ i in s₂, g i := begin rw [← prod_sdiff h, prod_eq_one hg, one_mul], exact prod_congr rfl hfg end @[to_additive] lemma prod_range_succ_comm (f : ℕ → β) (n : ℕ) : ∏ x in range (n + 1), f x = f n * ∏ x in range n, f x := by rw [range_succ, prod_insert not_mem_range_self] @[to_additive] lemma prod_range_succ (f : ℕ → β) (n : ℕ) : ∏ x in range (n + 1), f x = (∏ x in range n, f x) * f n := by simp only [mul_comm, prod_range_succ_comm] @[to_additive] lemma prod_range_succ' (f : ℕ → β) : ∀ n : ℕ, (∏ k in range (n + 1), f k) = (∏ k in range n, f (k+1)) * f 0 | 0 := prod_range_succ _ _ | (n + 1) := by rw [prod_range_succ _ n, mul_right_comm, ← prod_range_succ', prod_range_succ] @[to_additive] lemma eventually_constant_prod {u : ℕ → β} {N : ℕ} (hu : ∀ n ≥ N, u n = 1) {n : ℕ} (hn : N ≤ n) : ∏ k in range (n + 1), u k = ∏ k in range (N + 1), u k := begin obtain ⟨m, rfl : n = N + m⟩ := le_iff_exists_add.mp hn, clear hn, induction m with m hm, { simp }, erw [prod_range_succ, hm], simp [hu] end @[to_additive] lemma prod_range_add (f : ℕ → β) (n m : ℕ) : ∏ x in range (n + m), f x = (∏ x in range n, f x) * (∏ x in range m, f (n + x)) := begin induction m with m hm, { simp }, { rw [nat.add_succ, prod_range_succ, hm, prod_range_succ, mul_assoc], }, end @[to_additive] lemma prod_range_zero (f : ℕ → β) : ∏ k in range 0, f k = 1 := by rw [range_zero, prod_empty] @[to_additive sum_range_one] lemma prod_range_one (f : ℕ → β) : ∏ k in range 1, f k = f 0 := by { rw [range_one], apply @prod_singleton β ℕ 0 f } open multiset lemma prod_multiset_map_count [decidable_eq α] (s : multiset α) {M : Type*} [comm_monoid M] (f : α → M) : (s.map f).prod = ∏ m in s.to_finset, (f m) ^ (s.count m) := begin apply s.induction_on, { simp only [prod_const_one, count_zero, prod_zero, pow_zero, map_zero] }, intros a s ih, simp only [prod_cons, map_cons, to_finset_cons, ih], by_cases has : a ∈ s.to_finset, { rw [insert_eq_of_mem has, ← insert_erase has, prod_insert (not_mem_erase _ _), prod_insert (not_mem_erase _ _), ← mul_assoc, count_cons_self, pow_succ], congr' 1, refine prod_congr rfl (λ x hx, _), rw [count_cons_of_ne (ne_of_mem_erase hx)] }, rw [prod_insert has, count_cons_self, count_eq_zero_of_not_mem (mt mem_to_finset.2 has), pow_one], congr' 1, refine prod_congr rfl (λ x hx, _), rw count_cons_of_ne, rintro rfl, exact has hx end lemma sum_multiset_map_count [decidable_eq α] (s : multiset α) {M : Type*} [add_comm_monoid M] (f : α → M) : (s.map f).sum = ∑ m in s.to_finset, s.count m • f m := @prod_multiset_map_count _ _ _ (multiplicative M) _ f attribute [to_additive] prod_multiset_map_count @[to_additive] lemma prod_multiset_count [decidable_eq α] [comm_monoid α] (s : multiset α) : s.prod = ∏ m in s.to_finset, m ^ (s.count m) := by { convert prod_multiset_map_count s id, rw map_id } /-- To prove a property of a product, it suffices to prove that the property is multiplicative and holds on factors. -/ @[to_additive "To prove a property of a sum, it suffices to prove that the property is additive and holds on summands."] lemma prod_induction {M : Type*} [comm_monoid M] (f : α → M) (p : M → Prop) (p_mul : ∀ a b, p a → p b → p (a * b)) (p_one : p 1) (p_s : ∀ x ∈ s, p $ f x) : p $ ∏ x in s, f x := multiset.prod_induction _ _ p_mul p_one (multiset.forall_mem_map_iff.mpr p_s) /-- To prove a property of a product, it suffices to prove that the property is multiplicative and holds on factors. -/ @[to_additive "To prove a property of a sum, it suffices to prove that the property is additive and holds on summands."] lemma prod_induction_nonempty {M : Type*} [comm_monoid M] (f : α → M) (p : M → Prop) (p_mul : ∀ a b, p a → p b → p (a * b)) (hs_nonempty : s.nonempty) (p_s : ∀ x ∈ s, p $ f x) : p $ ∏ x in s, f x := multiset.prod_induction_nonempty p p_mul (by simp [nonempty_iff_ne_empty.mp hs_nonempty]) (multiset.forall_mem_map_iff.mpr p_s) /-- For any product along `{0, ..., n-1}` of a commutative-monoid-valued function, we can verify that it's equal to a different function just by checking ratios of adjacent terms. This is a multiplicative discrete analogue of the fundamental theorem of calculus. -/ lemma prod_range_induction {M : Type*} [comm_monoid M] (f s : ℕ → M) (h0 : s 0 = 1) (h : ∀ n, s (n + 1) = s n * f n) (n : ℕ) : ∏ k in finset.range n, f k = s n := begin induction n with k hk, { simp only [h0, finset.prod_range_zero] }, { simp only [hk, finset.prod_range_succ, h, mul_comm] } end /-- For any sum along `{0, ..., n-1}` of a commutative-monoid-valued function, we can verify that it's equal to a different function just by checking differences of adjacent terms. This is a discrete analogue of the fundamental theorem of calculus. -/ lemma sum_range_induction {M : Type*} [add_comm_monoid M] (f s : ℕ → M) (h0 : s 0 = 0) (h : ∀ n, s (n + 1) = s n + f n) (n : ℕ) : ∑ k in finset.range n, f k = s n := @prod_range_induction (multiplicative M) _ f s h0 h n /-- A telescoping sum along `{0, ..., n-1}` of an additive commutative group valued function reduces to the difference of the last and first terms.-/ lemma sum_range_sub {G : Type*} [add_comm_group G] (f : ℕ → G) (n : ℕ) : ∑ i in range n, (f (i+1) - f i) = f n - f 0 := by { apply sum_range_induction; abel, simp } lemma sum_range_sub' {G : Type*} [add_comm_group G] (f : ℕ → G) (n : ℕ) : ∑ i in range n, (f i - f (i+1)) = f 0 - f n := by { apply sum_range_induction; abel, simp } /-- A telescoping product along `{0, ..., n-1}` of a commutative group valued function reduces to the ratio of the last and first factors.-/ @[to_additive] lemma prod_range_div {M : Type*} [comm_group M] (f : ℕ → M) (n : ℕ) : ∏ i in range n, (f (i+1) * (f i)⁻¹) = f n * (f 0)⁻¹ := by simpa only [← div_eq_mul_inv] using @sum_range_sub (additive M) _ f n @[to_additive] lemma prod_range_div' {M : Type*} [comm_group M] (f : ℕ → M) (n : ℕ) : ∏ i in range n, (f i * (f (i+1))⁻¹) = (f 0) * (f n)⁻¹ := by simpa only [← div_eq_mul_inv] using @sum_range_sub' (additive M) _ f n /-- A telescoping sum along `{0, ..., n-1}` of an `ℕ`-valued function reduces to the difference of the last and first terms when the function we are summing is monotone. -/ lemma sum_range_sub_of_monotone {f : ℕ → ℕ} (h : monotone f) (n : ℕ) : ∑ i in range n, (f (i+1) - f i) = f n - f 0 := begin refine sum_range_induction _ _ (nat.sub_self _) (λ n, _) _, have h₁ : f n ≤ f (n+1) := h (nat.le_succ _), have h₂ : f 0 ≤ f n := h (nat.zero_le _), rw [←nat.sub_add_comm h₂, nat.add_sub_cancel' h₁], end @[simp] lemma prod_const (b : β) : (∏ x in s, b) = b ^ s.card := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (λ a s has ih, by rw [prod_insert has, card_insert_of_not_mem has, pow_succ, ih]) lemma pow_eq_prod_const (b : β) : ∀ n, b ^ n = ∏ k in range n, b | 0 := by simp | (n+1) := by simp lemma prod_pow (s : finset α) (n : ℕ) (f : α → β) : ∏ x in s, f x ^ n = (∏ x in s, f x) ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [mul_pow] {contextual := tt}) @[to_additive] lemma prod_flip {n : ℕ} (f : ℕ → β) : ∏ r in range (n + 1), f (n - r) = ∏ k in range (n + 1), f k := begin induction n with n ih, { rw [prod_range_one, prod_range_one] }, { rw [prod_range_succ', prod_range_succ _ (nat.succ n)], simp [← ih] } end @[to_additive] lemma prod_involution {s : finset α} {f : α → β} : ∀ (g : Π a ∈ s, α) (h : ∀ a ha, f a * f (g a ha) = 1) (g_ne : ∀ a ha, f a ≠ 1 → g a ha ≠ a) (g_mem : ∀ a ha, g a ha ∈ s) (g_inv : ∀ a ha, g (g a ha) (g_mem a ha) = a), (∏ x in s, f x) = 1 := by haveI := classical.dec_eq α; haveI := classical.dec_eq β; exact finset.strong_induction_on s (λ s ih g h g_ne g_mem g_inv, s.eq_empty_or_nonempty.elim (λ hs, hs.symm ▸ rfl) (λ ⟨x, hx⟩, have hmem : ∀ y ∈ (s.erase x).erase (g x hx), y ∈ s, from λ y hy, (mem_of_mem_erase (mem_of_mem_erase hy)), have g_inj : ∀ {x hx y hy}, g x hx = g y hy → x = y, from λ x hx y hy h, by rw [← g_inv x hx, ← g_inv y hy]; simp [h], have ih': ∏ y in erase (erase s x) (g x hx), f y = (1 : β) := ih ((s.erase x).erase (g x hx)) ⟨subset.trans (erase_subset _ _) (erase_subset _ _), λ h, not_mem_erase (g x hx) (s.erase x) (h (g_mem x hx))⟩ (λ y hy, g y (hmem y hy)) (λ y hy, h y (hmem y hy)) (λ y hy, g_ne y (hmem y hy)) (λ y hy, mem_erase.2 ⟨λ (h : g y _ = g x hx), by simpa [g_inj h] using hy, mem_erase.2 ⟨λ (h : g y _ = x), have y = g x hx, from g_inv y (hmem y hy) ▸ by simp [h], by simpa [this] using hy, g_mem y (hmem y hy)⟩⟩) (λ y hy, g_inv y (hmem y hy)), if hx1 : f x = 1 then ih' ▸ eq.symm (prod_subset hmem (λ y hy hy₁, have y = x ∨ y = g x hx, by simp [hy] at hy₁; tauto, this.elim (λ hy, hy.symm ▸ hx1) (λ hy, h x hx ▸ hy ▸ hx1.symm ▸ (one_mul _).symm))) else by rw [← insert_erase hx, prod_insert (not_mem_erase _ _), ← insert_erase (mem_erase.2 ⟨g_ne x hx hx1, g_mem x hx⟩), prod_insert (not_mem_erase _ _), ih', mul_one, h x hx])) /-- The product of the composition of functions `f` and `g`, is the product over `b ∈ s.image g` of `f b` to the power of the cardinality of the fibre of `b` -/ lemma prod_comp [decidable_eq γ] {s : finset α} (f : γ → β) (g : α → γ) : ∏ a in s, f (g a) = ∏ b in s.image g, f b ^ (s.filter (λ a, g a = b)).card := calc ∏ a in s, f (g a) = ∏ x in (s.image g).sigma (λ b : γ, s.filter (λ a, g a = b)), f (g x.2) : prod_bij (λ a ha, ⟨g a, a⟩) (by simp; tauto) (λ _ _, rfl) (by simp) (by finish) ... = ∏ b in s.image g, ∏ a in s.filter (λ a, g a = b), f (g a) : prod_sigma _ _ _ ... = ∏ b in s.image g, ∏ a in s.filter (λ a, g a = b), f b : prod_congr rfl (λ b hb, prod_congr rfl (by simp {contextual := tt})) ... = ∏ b in s.image g, f b ^ (s.filter (λ a, g a = b)).card : prod_congr rfl (λ _ _, prod_const _) @[to_additive] lemma prod_piecewise [decidable_eq α] (s t : finset α) (f g : α → β) : (∏ x in s, (t.piecewise f g) x) = (∏ x in s ∩ t, f x) * (∏ x in s \ t, g x) := by { rw [piecewise, prod_ite, filter_mem_eq_inter, ← sdiff_eq_filter], } @[to_additive] lemma prod_inter_mul_prod_diff [decidable_eq α] (s t : finset α) (f : α → β) : (∏ x in s ∩ t, f x) * (∏ x in s \ t, f x) = (∏ x in s, f x) := by { convert (s.prod_piecewise t f f).symm, simp [finset.piecewise] } @[to_additive] lemma prod_eq_mul_prod_diff_singleton [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) : ∏ x in s, f x = f i * ∏ x in s \ {i}, f x := by { convert (s.prod_inter_mul_prod_diff {i} f).symm, simp [h] } @[to_additive] lemma prod_eq_prod_diff_singleton_mul [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) : ∏ x in s, f x = (∏ x in s \ {i}, f x) * f i := by { rw [prod_eq_mul_prod_diff_singleton h, mul_comm] } @[to_additive] lemma _root_.fintype.prod_eq_mul_prod_compl [decidable_eq α] [fintype α] (a : α) (f : α → β) : ∏ i, f i = (f a) * ∏ i in {a}ᶜ, f i := prod_eq_mul_prod_diff_singleton (mem_univ a) f @[to_additive] lemma _root_.fintype.prod_eq_prod_compl_mul [decidable_eq α] [fintype α] (a : α) (f : α → β) : ∏ i, f i = (∏ i in {a}ᶜ, f i) * f a := prod_eq_prod_diff_singleton_mul (mem_univ a) f /-- A product can be partitioned into a product of products, each equivalent under a setoid. -/ @[to_additive "A sum can be partitioned into a sum of sums, each equivalent under a setoid."] lemma prod_partition (R : setoid α) [decidable_rel R.r] : (∏ x in s, f x) = ∏ xbar in s.image quotient.mk, ∏ y in s.filter (λ y, ⟦y⟧ = xbar), f y := begin refine (finset.prod_image' f (λ x hx, _)).symm, refl, end /-- If we can partition a product into subsets that cancel out, then the whole product cancels. -/ @[to_additive "If we can partition a sum into subsets that cancel out, then the whole sum cancels."] lemma prod_cancels_of_partition_cancels (R : setoid α) [decidable_rel R.r] (h : ∀ x ∈ s, (∏ a in s.filter (λ y, y ≈ x), f a) = 1) : (∏ x in s, f x) = 1 := begin rw [prod_partition R, ←finset.prod_eq_one], intros xbar xbar_in_s, obtain ⟨x, x_in_s, xbar_eq_x⟩ := mem_image.mp xbar_in_s, rw [←xbar_eq_x, filter_congr (λ y _, @quotient.eq _ R y x)], apply h x x_in_s, end @[to_additive] lemma prod_update_of_not_mem [decidable_eq α] {s : finset α} {i : α} (h : i ∉ s) (f : α → β) (b : β) : (∏ x in s, function.update f i b x) = (∏ x in s, f x) := begin apply prod_congr rfl (λ j hj, _), have : j ≠ i, by { assume eq, rw eq at hj, exact h hj }, simp [this] end lemma prod_update_of_mem [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) (b : β) : (∏ x in s, function.update f i b x) = b * (∏ x in s \ (singleton i), f x) := by { rw [update_eq_piecewise, prod_piecewise], simp [h] } /-- If a product of a `finset` of size at most 1 has a given value, so do the terms in that product. -/ @[to_additive eq_of_card_le_one_of_sum_eq "If a sum of a `finset` of size at most 1 has a given value, so do the terms in that sum."] lemma eq_of_card_le_one_of_prod_eq {s : finset α} (hc : s.card ≤ 1) {f : α → β} {b : β} (h : ∏ x in s, f x = b) : ∀ x ∈ s, f x = b := begin intros x hx, by_cases hc0 : s.card = 0, { exact false.elim (card_ne_zero_of_mem hx hc0) }, { have h1 : s.card = 1 := le_antisymm hc (nat.one_le_of_lt (nat.pos_of_ne_zero hc0)), rw card_eq_one at h1, cases h1 with x2 hx2, rw [hx2, mem_singleton] at hx, simp_rw hx2 at h, rw hx, rw prod_singleton at h, exact h } end /-- Taking a product over `s : finset α` is the same as multiplying the value on a single element `f a` by the product of `s.erase a`. -/ @[to_additive "Taking a sum over `s : finset α` is the same as adding the value on a single element `f a` to the the sum over `s.erase a`."] lemma mul_prod_erase [decidable_eq α] (s : finset α) (f : α → β) {a : α} (h : a ∈ s) : f a * (∏ x in s.erase a, f x) = ∏ x in s, f x := by rw [← prod_insert (not_mem_erase a s), insert_erase h] /-- A variant of `finset.mul_prod_erase` with the multiplication swapped. -/ @[to_additive "A variant of `finset.add_sum_erase` with the addition swapped."] lemma prod_erase_mul [decidable_eq α] (s : finset α) (f : α → β) {a : α} (h : a ∈ s) : (∏ x in s.erase a, f x) * f a = ∏ x in s, f x := by rw [mul_comm, mul_prod_erase s f h] /-- If a function applied at a point is 1, a product is unchanged by removing that point, if present, from a `finset`. -/ @[to_additive "If a function applied at a point is 0, a sum is unchanged by removing that point, if present, from a `finset`."] lemma prod_erase [decidable_eq α] (s : finset α) {f : α → β} {a : α} (h : f a = 1) : ∏ x in s.erase a, f x = ∏ x in s, f x := begin rw ←sdiff_singleton_eq_erase, refine prod_subset (sdiff_subset _ _) (λ x hx hnx, _), rw sdiff_singleton_eq_erase at hnx, rwa eq_of_mem_of_not_mem_erase hx hnx end /-- If a product is 1 and the function is 1 except possibly at one point, it is 1 everywhere on the `finset`. -/ @[to_additive "If a sum is 0 and the function is 0 except possibly at one point, it is 0 everywhere on the `finset`."] lemma eq_one_of_prod_eq_one {s : finset α} {f : α → β} {a : α} (hp : ∏ x in s, f x = 1) (h1 : ∀ x ∈ s, x ≠ a → f x = 1) : ∀ x ∈ s, f x = 1 := begin intros x hx, classical, by_cases h : x = a, { rw h, rw h at hx, rw [←prod_subset (singleton_subset_iff.2 hx) (λ t ht ha, h1 t ht (not_mem_singleton.1 ha)), prod_singleton] at hp, exact hp }, { exact h1 x hx h } end lemma prod_pow_boole [decidable_eq α] (s : finset α) (f : α → β) (a : α) : (∏ x in s, (f x)^(ite (a = x) 1 0)) = ite (a ∈ s) (f a) 1 := by simp end comm_monoid /-- If `f = g = h` everywhere but at `i`, where `f i = g i + h i`, then the product of `f` over `s` is the sum of the products of `g` and `h`. -/ lemma prod_add_prod_eq [comm_semiring β] {s : finset α} {i : α} {f g h : α → β} (hi : i ∈ s) (h1 : g i + h i = f i) (h2 : ∀ j ∈ s, j ≠ i → g j = f j) (h3 : ∀ j ∈ s, j ≠ i → h j = f j) : ∏ i in s, g i + ∏ i in s, h i = ∏ i in s, f i := by { classical, simp_rw [prod_eq_mul_prod_diff_singleton hi, ← h1, right_distrib], congr' 2; apply prod_congr rfl; simpa } lemma sum_update_of_mem [add_comm_monoid β] [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) (b : β) : (∑ x in s, function.update f i b x) = b + (∑ x in s \ (singleton i), f x) := by { rw [update_eq_piecewise, sum_piecewise], simp [h] } attribute [to_additive] prod_update_of_mem lemma sum_nsmul [add_comm_monoid β] (s : finset α) (n : ℕ) (f : α → β) : (∑ x in s, n • (f x)) = n • ((∑ x in s, f x)) := @prod_pow (multiplicative β) _ _ _ _ _ attribute [to_additive sum_nsmul] prod_pow @[simp] lemma sum_const [add_comm_monoid β] (b : β) : (∑ x in s, b) = s.card • b := @prod_const (multiplicative β) _ _ _ _ attribute [to_additive] prod_const lemma card_eq_sum_ones (s : finset α) : s.card = ∑ _ in s, 1 := by simp lemma sum_const_nat {m : ℕ} {f : α → ℕ} (h₁ : ∀ x ∈ s, f x = m) : (∑ x in s, f x) = card s * m := begin rw [← nat.nsmul_eq_mul, ← sum_const], apply sum_congr rfl h₁ end @[simp] lemma sum_boole {s : finset α} {p : α → Prop} [non_assoc_semiring β] {hp : decidable_pred p} : (∑ x in s, if p x then (1 : β) else (0 : β)) = (s.filter p).card := by simp [sum_ite] lemma sum_comp [add_comm_monoid β] [decidable_eq γ] {s : finset α} (f : γ → β) (g : α → γ) : ∑ a in s, f (g a) = ∑ b in s.image g, (s.filter (λ a, g a = b)).card • (f b) := @prod_comp (multiplicative β) _ _ _ _ _ _ _ attribute [to_additive "The sum of the composition of functions `f` and `g`, is the sum over `b ∈ s.image g` of `f b` times of the cardinality of the fibre of `b`"] prod_comp lemma eq_sum_range_sub [add_comm_group β] (f : ℕ → β) (n : ℕ) : f n = f 0 + ∑ i in range n, (f (i+1) - f i) := by { rw finset.sum_range_sub, abel } lemma eq_sum_range_sub' [add_comm_group β] (f : ℕ → β) (n : ℕ) : f n = ∑ i in range (n + 1), if i = 0 then f 0 else f i - f (i - 1) := begin conv_lhs { rw [finset.eq_sum_range_sub f] }, simp [finset.sum_range_succ', add_comm] end section opposite open opposite /-- Moving to the opposite additive commutative monoid commutes with summing. -/ @[simp] lemma op_sum [add_comm_monoid β] {s : finset α} (f : α → β) : op (∑ x in s, f x) = ∑ x in s, op (f x) := (op_add_equiv : β ≃+ βᵒᵖ).map_sum _ _ @[simp] lemma unop_sum [add_comm_monoid β] {s : finset α} (f : α → βᵒᵖ) : unop (∑ x in s, f x) = ∑ x in s, unop (f x) := (op_add_equiv : β ≃+ βᵒᵖ).symm.map_sum _ _ end opposite section comm_group variables [comm_group β] @[simp, to_additive] lemma prod_inv_distrib : (∏ x in s, (f x)⁻¹) = (∏ x in s, f x)⁻¹ := (monoid_hom.map_prod (comm_group.inv_monoid_hom : β →* β) f s).symm end comm_group @[simp] theorem card_sigma {σ : α → Type*} (s : finset α) (t : Π a, finset (σ a)) : card (s.sigma t) = ∑ a in s, card (t a) := multiset.card_sigma _ _ lemma card_bUnion [decidable_eq β] {s : finset α} {t : α → finset β} (h : ∀ x ∈ s, ∀ y ∈ s, x ≠ y → disjoint (t x) (t y)) : (s.bUnion t).card = ∑ u in s, card (t u) := calc (s.bUnion t).card = ∑ i in s.bUnion t, 1 : by simp ... = ∑ a in s, ∑ i in t a, 1 : finset.sum_bUnion h ... = ∑ u in s, card (t u) : by simp lemma card_bUnion_le [decidable_eq β] {s : finset α} {t : α → finset β} : (s.bUnion t).card ≤ ∑ a in s, (t a).card := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (λ a s has ih, calc ((insert a s).bUnion t).card ≤ (t a).card + (s.bUnion t).card : by rw bUnion_insert; exact finset.card_union_le _ _ ... ≤ ∑ a in insert a s, card (t a) : by rw sum_insert has; exact add_le_add_left ih _) theorem card_eq_sum_card_fiberwise [decidable_eq β] {f : α → β} {s : finset α} {t : finset β} (H : ∀ x ∈ s, f x ∈ t) : s.card = ∑ a in t, (s.filter (λ x, f x = a)).card := by simp only [card_eq_sum_ones, sum_fiberwise_of_maps_to H] theorem card_eq_sum_card_image [decidable_eq β] (f : α → β) (s : finset α) : s.card = ∑ a in s.image f, (s.filter (λ x, f x = a)).card := card_eq_sum_card_fiberwise (λ _, mem_image_of_mem _) lemma gsmul_sum (α β : Type) [add_comm_group β] {f : α → β} {s : finset α} (z : ℤ) : gsmul z (∑ a in s, f a) = ∑ a in s, gsmul z (f a) := add_monoid_hom.map_sum (gsmul_add_group_hom z : β →+ β) f s @[simp] lemma sum_sub_distrib [add_comm_group β] : ∑ x in s, (f x - g x) = (∑ x in s, f x) - (∑ x in s, g x) := by simpa only [sub_eq_add_neg] using sum_add_distrib.trans (congr_arg _ sum_neg_distrib) section prod_eq_zero variables [comm_monoid_with_zero β] lemma prod_eq_zero (ha : a ∈ s) (h : f a = 0) : (∏ x in s, f x) = 0 := by { haveI := classical.dec_eq α, rw [←prod_erase_mul _ _ ha, h, mul_zero] } lemma prod_boole {s : finset α} {p : α → Prop} [decidable_pred p] : ∏ i in s, ite (p i) (1 : β) (0 : β) = ite (∀ i ∈ s, p i) 1 0 := begin split_ifs, { apply prod_eq_one, intros i hi, rw if_pos (h i hi) }, { push_neg at h, rcases h with ⟨i, hi, hq⟩, apply prod_eq_zero hi, rw [if_neg hq] }, end variables [nontrivial β] [no_zero_divisors β] lemma prod_eq_zero_iff : (∏ x in s, f x) = 0 ↔ (∃ a ∈ s, f a = 0) := begin classical, apply finset.induction_on s, exact ⟨not.elim one_ne_zero, λ ⟨_, H, _⟩, H.elim⟩, assume a s ha ih, rw [prod_insert ha, mul_eq_zero, bex_def, exists_mem_insert, ih, ← bex_def] end theorem prod_ne_zero_iff : (∏ x in s, f x) ≠ 0 ↔ (∀ a ∈ s, f a ≠ 0) := by { rw [ne, prod_eq_zero_iff], push_neg } end prod_eq_zero section comm_group_with_zero variables [comm_group_with_zero β] @[simp] lemma prod_inv_distrib' : (∏ x in s, (f x)⁻¹) = (∏ x in s, f x)⁻¹ := begin classical, by_cases h : ∃ x ∈ s, f x = 0, { simpa [prod_eq_zero_iff.mpr h, prod_eq_zero_iff] using h }, { push_neg at h, have h' := prod_ne_zero_iff.mpr h, have hf : ∀ x ∈ s, (f x)⁻¹ * f x = 1 := λ x hx, inv_mul_cancel (h x hx), apply mul_right_cancel' h', simp [h, h', ← finset.prod_mul_distrib, prod_congr rfl hf] } end end comm_group_with_zero end finset namespace fintype open finset /-- `fintype.prod_bijective` is a variant of `finset.prod_bij` that accepts `function.bijective`. See `function.bijective.prod_comp` for a version without `h`. -/ @[to_additive "`fintype.sum_equiv` is a variant of `finset.sum_bij` that accepts `function.bijective`. See `function.bijective.sum_comp` for a version without `h`. "] lemma prod_bijective {α β M : Type*} [fintype α] [fintype β] [comm_monoid M] (e : α → β) (he : function.bijective e) (f : α → M) (g : β → M) (h : ∀ x, f x = g (e x)) : ∏ x : α, f x = ∏ x : β, g x := prod_bij (λ x _, e x) (λ x _, mem_univ (e x)) (λ x _, h x) (λ x x' _ _ h, he.injective h) (λ y _, (he.surjective y).imp $ λ a h, ⟨mem_univ _, h.symm⟩) /-- `fintype.prod_equiv` is a specialization of `finset.prod_bij` that automatically fills in most arguments. See `equiv.prod_comp` for a version without `h`. -/ @[to_additive "`fintype.sum_equiv` is a specialization of `finset.sum_bij` that automatically fills in most arguments. See `equiv.sum_comp` for a version without `h`. "] lemma prod_equiv {α β M : Type*} [fintype α] [fintype β] [comm_monoid M] (e : α ≃ β) (f : α → M) (g : β → M) (h : ∀ x, f x = g (e x)) : ∏ x : α, f x = ∏ x : β, g x := prod_bijective e e.bijective f g h @[to_additive] lemma prod_finset_coe [comm_monoid β] : ∏ (i : (s : set α)), f i = ∏ i in s, f i := (finset.prod_subtype s (λ _, iff.rfl) f).symm end fintype namespace list @[to_additive] lemma prod_to_finset {M : Type*} [decidable_eq α] [comm_monoid M] (f : α → M) : ∀ {l : list α} (hl : l.nodup), l.to_finset.prod f = (l.map f).prod | [] _ := by simp | (a :: l) hl := let ⟨not_mem, hl⟩ := list.nodup_cons.mp hl in by simp [finset.prod_insert (mt list.mem_to_finset.mp not_mem), prod_to_finset hl] end list namespace multiset lemma abs_sum_le_sum_abs [linear_ordered_add_comm_group α] {s : multiset α} : abs s.sum ≤ (s.map abs).sum := le_sum_of_subadditive _ abs_zero abs_add s variables [decidable_eq α] @[simp] lemma to_finset_sum_count_eq (s : multiset α) : (∑ a in s.to_finset, s.count a) = s.card := multiset.induction_on s rfl (assume a s ih, calc (∑ x in to_finset (a ::ₘ s), count x (a ::ₘ s)) = ∑ x in to_finset (a ::ₘ s), ((if x = a then 1 else 0) + count x s) : finset.sum_congr rfl $ λ _ _, by split_ifs; [simp only [h, count_cons_self, nat.one_add], simp only [count_cons_of_ne h, zero_add]] ... = card (a ::ₘ s) : begin by_cases a ∈ s.to_finset, { have : ∑ x in s.to_finset, ite (x = a) 1 0 = ∑ x in {a}, ite (x = a) 1 0, { rw [finset.sum_ite_eq', if_pos h, finset.sum_singleton, if_pos rfl], }, rw [to_finset_cons, finset.insert_eq_of_mem h, finset.sum_add_distrib, ih, this, finset.sum_singleton, if_pos rfl, add_comm, card_cons] }, { have ha : a ∉ s, by rwa mem_to_finset at h, have : ∑ x in to_finset s, ite (x = a) 1 0 = ∑ x in to_finset s, 0, from finset.sum_congr rfl (λ x hx, if_neg $ by rintro rfl; cc), rw [to_finset_cons, finset.sum_insert h, if_pos rfl, finset.sum_add_distrib, this, finset.sum_const_zero, ih, count_eq_zero_of_not_mem ha, zero_add, add_comm, card_cons] } end) lemma count_sum' {s : finset β} {a : α} {f : β → multiset α} : count a (∑ x in s, f x) = ∑ x in s, count a (f x) := by { dunfold finset.sum, rw count_sum } @[simp] lemma to_finset_sum_count_nsmul_eq (s : multiset α) : (∑ a in s.to_finset, s.count a • (a ::ₘ 0)) = s := begin apply ext', intro b, rw count_sum', have h : count b s = count b (count b s • (b ::ₘ 0)), { rw [singleton_coe, count_nsmul, ← singleton_coe, count_singleton, mul_one] }, rw h, clear h, apply finset.sum_eq_single b, { intros c h hcb, rw count_nsmul, convert mul_zero (count c s), apply count_eq_zero.mpr, exact finset.not_mem_singleton.mpr (ne.symm hcb) }, { intro hb, rw [count_eq_zero_of_not_mem (mt mem_to_finset.2 hb), count_nsmul, zero_mul]} end theorem exists_smul_of_dvd_count (s : multiset α) {k : ℕ} (h : ∀ (a : α), k ∣ multiset.count a s) : ∃ (u : multiset α), s = k • u := begin use ∑ a in s.to_finset, (s.count a / k) • (a ::ₘ 0), have h₂ : ∑ (x : α) in s.to_finset, k • (count x s / k) • (x ::ₘ 0) = ∑ (x : α) in s.to_finset, count x s • (x ::ₘ 0), { refine congr_arg s.to_finset.sum _, apply funext, intro x, rw [← mul_nsmul, nat.mul_div_cancel' (h x)] }, rw [← finset.sum_nsmul, h₂, to_finset_sum_count_nsmul_eq] end end multiset @[simp, norm_cast] lemma nat.cast_sum [add_comm_monoid β] [has_one β] (s : finset α) (f : α → ℕ) : ↑(∑ x in s, f x : ℕ) = (∑ x in s, (f x : β)) := (nat.cast_add_monoid_hom β).map_sum f s @[simp, norm_cast] lemma int.cast_sum [add_comm_group β] [has_one β] (s : finset α) (f : α → ℤ) : ↑(∑ x in s, f x : ℤ) = (∑ x in s, (f x : β)) := (int.cast_add_hom β).map_sum f s @[simp, norm_cast] lemma nat.cast_prod {R : Type*} [comm_semiring R] (f : α → ℕ) (s : finset α) : (↑∏ i in s, f i : R) = ∏ i in s, f i := (nat.cast_ring_hom R).map_prod _ _ @[simp, norm_cast] lemma int.cast_prod {R : Type*} [comm_ring R] (f : α → ℤ) (s : finset α) : (↑∏ i in s, f i : R) = ∏ i in s, f i := (int.cast_ring_hom R).map_prod _ _ @[simp, norm_cast] lemma units.coe_prod {M : Type*} [comm_monoid M] (f : α → units M) (s : finset α) : (↑∏ i in s, f i : M) = ∏ i in s, f i := (units.coe_hom M).map_prod _ _ lemma nat_abs_sum_le {ι : Type*} (s : finset ι) (f : ι → ℤ) : (∑ i in s, f i).nat_abs ≤ ∑ i in s, (f i).nat_abs := begin classical, apply finset.induction_on s, { simp only [finset.sum_empty, int.nat_abs_zero] }, { intros i s his IH, simp only [his, finset.sum_insert, not_false_iff], exact (int.nat_abs_add_le _ _).trans (add_le_add le_rfl IH) } end
b7ad59c4e83710c701fdbd408d21dcb35eb7ed64
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/number_theory/class_number/admissible_card_pow_degree.lean
6ab5cf95274aee85d3c18621339daf8cfe3792ad
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,861
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import data.polynomial.degree.card_pow_degree import field_theory.finite.basic import number_theory.class_number.admissible_absolute_value /-! # Admissible absolute values on polynomials This file defines an admissible absolute value `polynomial.card_pow_degree_is_admissible` which we use to show the class number of the ring of integers of a function field is finite. ## Main results * `polynomial.card_pow_degree_is_admissible` shows `card_pow_degree`, mapping `p : polynomial 𝔽_q` to `q ^ degree p`, is admissible -/ namespace polynomial open absolute_value real variables {Fq : Type*} [field Fq] [fintype Fq] /-- If `A` is a family of enough low-degree polynomials over a finite field, there is a pair of equal elements in `A`. -/ lemma exists_eq_polynomial {d : ℕ} {m : ℕ} (hm : fintype.card Fq ^ d ≤ m) (b : polynomial Fq) (hb : nat_degree b ≤ d) (A : fin m.succ → polynomial Fq) (hA : ∀ i, degree (A i) < degree b) : ∃ i₀ i₁, i₀ ≠ i₁ ∧ A i₁ = A i₀ := begin -- Since there are > q^d elements of A, and only q^d choices for the highest `d` coefficients, -- there must be two elements of A with the same coefficients at -- `0`, ... `degree b - 1` ≤ `d - 1`. -- In other words, the following map is not injective: set f : fin m.succ → (fin d → Fq) := λ i j, (A i).coeff j, have : fintype.card (fin d → Fq) < fintype.card (fin m.succ), { simpa using lt_of_le_of_lt hm (nat.lt_succ_self m) }, -- Therefore, the differences have all coefficients higher than `deg b - d` equal. obtain ⟨i₀, i₁, i_ne, i_eq⟩ := fintype.exists_ne_map_eq_of_card_lt f this, use [i₀, i₁, i_ne], ext j, -- The coefficients higher than `deg b` are the same because they are equal to 0. by_cases hbj : degree b ≤ j, { rw [coeff_eq_zero_of_degree_lt (lt_of_lt_of_le (hA _) hbj), coeff_eq_zero_of_degree_lt (lt_of_lt_of_le (hA _) hbj)] }, -- So we only need to look for the coefficients between `0` and `deg b`. rw not_le at hbj, apply congr_fun i_eq.symm ⟨j, _⟩, exact lt_of_lt_of_le (coe_lt_degree.mp hbj) hb end /-- If `A` is a family of enough low-degree polynomials over a finite field, there is a pair of elements in `A` (with different indices but not necessarily distinct), such that their difference has small degree. -/ lemma exists_approx_polynomial_aux {d : ℕ} {m : ℕ} (hm : fintype.card Fq ^ d ≤ m) (b : polynomial Fq) (A : fin m.succ → polynomial Fq) (hA : ∀ i, degree (A i) < degree b) : ∃ i₀ i₁, i₀ ≠ i₁ ∧ degree (A i₁ - A i₀) < ↑(nat_degree b - d) := begin have hb : b ≠ 0, { rintro rfl, specialize hA 0, rw degree_zero at hA, exact not_lt_of_le bot_le hA }, -- Since there are > q^d elements of A, and only q^d choices for the highest `d` coefficients, -- there must be two elements of A with the same coefficients at -- `degree b - 1`, ... `degree b - d`. -- In other words, the following map is not injective: set f : fin m.succ → (fin d → Fq) := λ i j, (A i).coeff (nat_degree b - j.succ), have : fintype.card (fin d → Fq) < fintype.card (fin m.succ), { simpa using lt_of_le_of_lt hm (nat.lt_succ_self m) }, -- Therefore, the differences have all coefficients higher than `deg b - d` equal. obtain ⟨i₀, i₁, i_ne, i_eq⟩ := fintype.exists_ne_map_eq_of_card_lt f this, use [i₀, i₁, i_ne], refine (degree_lt_iff_coeff_zero _ _).mpr (λ j hj, _), -- The coefficients higher than `deg b` are the same because they are equal to 0. by_cases hbj : degree b ≤ j, { refine coeff_eq_zero_of_degree_lt (lt_of_lt_of_le _ hbj), exact lt_of_le_of_lt (degree_sub_le _ _) (max_lt (hA _) (hA _)) }, -- So we only need to look for the coefficients between `deg b - d` and `deg b`. rw [coeff_sub, sub_eq_zero], rw [not_le, degree_eq_nat_degree hb, with_bot.coe_lt_coe] at hbj, have hj : nat_degree b - j.succ < d, { by_cases hd : nat_degree b < d, { exact lt_of_le_of_lt sub_le_self' hd }, { rw not_lt at hd, have := lt_of_le_of_lt hj (nat.lt_succ_self j), rwa [sub_lt_iff_sub_lt hd hbj] at this } }, have : j = b.nat_degree - (nat_degree b - j.succ).succ, { rw [← nat.succ_sub hbj, nat.succ_sub_succ, nat.sub_sub_self hbj.le] }, convert congr_fun i_eq.symm ⟨nat_degree b - j.succ, hj⟩ end /-- If `A` is a family of enough low-degree polynomials over a finite field, there is a pair of elements in `A` (with different indices but not necessarily distinct), such that the difference of their remainders is close together. -/ lemma exists_approx_polynomial {b : polynomial Fq} (hb : b ≠ 0) {ε : ℝ} (hε : 0 < ε) (A : fin (fintype.card Fq ^ ⌈- log ε / log (fintype.card Fq)⌉₊).succ → polynomial Fq) : ∃ i₀ i₁, i₀ ≠ i₁ ∧ (card_pow_degree (A i₁ % b - A i₀ % b) : ℝ) < card_pow_degree b • ε := begin have hbε : 0 < card_pow_degree b • ε, { rw [algebra.smul_def, ring_hom.eq_int_cast], exact mul_pos (int.cast_pos.mpr (absolute_value.pos _ hb)) hε }, have one_lt_q : 1 < fintype.card Fq := fintype.one_lt_card, have one_lt_q' : (1 : ℝ) < fintype.card Fq, { assumption_mod_cast }, have q_pos : 0 < fintype.card Fq, { linarith }, have q_pos' : (0 : ℝ) < fintype.card Fq, { assumption_mod_cast }, -- If `b` is already small enough, then the remainders are equal and we are done. by_cases le_b : b.nat_degree ≤ ⌈- log ε / log (fintype.card Fq)⌉₊, { obtain ⟨i₀, i₁, i_ne, mod_eq⟩ := exists_eq_polynomial le_rfl b le_b (λ i, A i % b) (λ i, euclidean_domain.mod_lt (A i) hb), refine ⟨i₀, i₁, i_ne, _⟩, simp only at mod_eq, rwa [mod_eq, sub_self, absolute_value.map_zero, int.cast_zero] }, -- Otherwise, it suffices to choose two elements whose difference is of small enough degree. rw not_le at le_b, obtain ⟨i₀, i₁, i_ne, deg_lt⟩ := exists_approx_polynomial_aux le_rfl b (λ i, A i % b) (λ i, euclidean_domain.mod_lt (A i) hb), simp only at deg_lt, use [i₀, i₁, i_ne], -- Again, if the remainders are equal we are done. by_cases h : A i₁ % b = A i₀ % b, { rwa [h, sub_self, absolute_value.map_zero, int.cast_zero] }, have h' : A i₁ % b - A i₀ % b ≠ 0 := mt sub_eq_zero.mp h, -- If the remainders are not equal, we'll show their difference is of small degree. -- In particular, we'll show the degree is less than the following: suffices : (nat_degree (A i₁ % b - A i₀ % b) : ℝ) < b.nat_degree + log ε / log (fintype.card Fq), { rwa [← real.log_lt_log_iff (int.cast_pos.mpr (card_pow_degree.pos h')) hbε, card_pow_degree_nonzero _ h', card_pow_degree_nonzero _ hb, algebra.smul_def, ring_hom.eq_int_cast, int.cast_pow, int.cast_coe_nat, int.cast_pow, int.cast_coe_nat, log_mul (pow_ne_zero _ q_pos'.ne') hε.ne', ← rpow_nat_cast, ← rpow_nat_cast, log_rpow q_pos', log_rpow q_pos', ← lt_div_iff (log_pos one_lt_q'), add_div, mul_div_cancel _ (log_pos one_lt_q').ne'] }, -- And that result follows from manipulating the result from `exists_approx_polynomial_aux` -- to turn the `-⌈-stuff⌉₊` into `+ stuff`. refine lt_of_lt_of_le (nat.cast_lt.mpr (with_bot.coe_lt_coe.mp _)) _, swap, { convert deg_lt, rw degree_eq_nat_degree h' }, rw [← sub_neg_eq_add, neg_div], refine le_trans _ (sub_le_sub_left (nat.le_ceil _) (b.nat_degree : ℝ)), rw ← neg_div, exact le_of_eq (nat.cast_sub le_b.le) end /-- If `x` is close to `y` and `y` is close to `z`, then `x` and `z` are at least as close. -/ lemma card_pow_degree_anti_archimedean {x y z : polynomial Fq} {a : ℤ} (hxy : card_pow_degree (x - y) < a) (hyz : card_pow_degree (y - z) < a) : card_pow_degree (x - z) < a := begin have ha : 0 < a := lt_of_le_of_lt (absolute_value.nonneg _ _) hxy, by_cases hxy' : x = y, { rwa hxy' }, by_cases hyz' : y = z, { rwa ← hyz' }, by_cases hxz' : x = z, { rwa [hxz', sub_self, absolute_value.map_zero] }, rw [← ne.def, ← sub_ne_zero] at hxy' hyz' hxz', refine lt_of_le_of_lt _ (max_lt hxy hyz), rw [card_pow_degree_nonzero _ hxz', card_pow_degree_nonzero _ hxy', card_pow_degree_nonzero _ hyz'], have : (1 : ℤ) ≤ fintype.card Fq, { exact_mod_cast (@fintype.one_lt_card Fq _ _).le }, simp only [int.cast_pow, int.cast_coe_nat, le_max_iff], refine or.imp (pow_le_pow this) (pow_le_pow this) _, rw [nat_degree_le_iff_degree_le, nat_degree_le_iff_degree_le, ← le_max_iff, ← degree_eq_nat_degree hxy', ← degree_eq_nat_degree hyz'], convert degree_add_le (x - y) (y - z) using 2, exact (sub_add_sub_cancel _ _ _).symm end /-- A slightly stronger version of `exists_partition` on which we perform induction on `n`: for all `ε > 0`, we can partition the remainders of any family of polynomials `A` into equivalence classes, where the equivalence(!) relation is "closer than `ε`". -/ lemma exists_partition_polynomial_aux (n : ℕ) {ε : ℝ} (hε : 0 < ε) {b : polynomial Fq} (hb : b ≠ 0) (A : fin n → polynomial Fq) : ∃ (t : fin n → fin (fintype.card Fq ^ ⌈- log ε / log (fintype.card Fq)⌉₊)), ∀ (i₀ i₁ : fin n), t i₀ = t i₁ ↔ (card_pow_degree (A i₁ % b - A i₀ % b) : ℝ) < card_pow_degree b • ε := begin have hbε : 0 < card_pow_degree b • ε, { rw [algebra.smul_def, ring_hom.eq_int_cast], exact mul_pos (int.cast_pos.mpr (absolute_value.pos _ hb)) hε }, -- We go by induction on the size `A`. induction n with n ih, { refine ⟨fin_zero_elim, fin_zero_elim⟩ }, -- Show `anti_archimedean` also holds for real distances. have anti_archim' : ∀ {i j k} {ε : ℝ}, (card_pow_degree (A i % b - A j % b) : ℝ) < ε → (card_pow_degree (A j % b - A k % b) : ℝ) < ε → (card_pow_degree (A i % b - A k % b) : ℝ) < ε, { intros i j k ε, simp_rw [← int.lt_ceil], exact card_pow_degree_anti_archimedean }, obtain ⟨t', ht'⟩ := ih (fin.tail A), -- We got rid of `A 0`, so determine the index `j` of the partition we'll re-add it to. suffices : ∃ j, ∀ i, t' i = j ↔ (card_pow_degree (A 0 % b - A i.succ % b) : ℝ) < card_pow_degree b • ε, { obtain ⟨j, hj⟩ := this, refine ⟨fin.cons j t', λ i₀ i₁, _⟩, refine fin.cases _ (λ i₀, _) i₀; refine fin.cases _ (λ i₁, _) i₁, { simpa using hbε }, { rw [fin.cons_succ, fin.cons_zero, eq_comm, absolute_value.map_sub], exact hj i₁ }, { rw [fin.cons_succ, fin.cons_zero], exact hj i₀ }, { rw [fin.cons_succ, fin.cons_succ], exact ht' i₀ i₁ } }, -- `exists_approx_polynomial` guarantees that we can insert `A 0` into some partition `j`, -- but not that `j` is uniquely defined (which is needed to keep the induction going). obtain ⟨j, hj⟩ : ∃ j, ∀ (i : fin n), t' i = j → (card_pow_degree (A 0 % b - A i.succ % b) : ℝ) < card_pow_degree b • ε, { by_contra this, push_neg at this, obtain ⟨j₀, j₁, j_ne, approx⟩ := exists_approx_polynomial hb hε (fin.cons (A 0) (λ j, A (fin.succ (classical.some (this j))))), revert j_ne approx, refine fin.cases _ (λ j₀, _) j₀; refine fin.cases (λ j_ne approx, _) (λ j₁ j_ne approx, _) j₁, { exact absurd rfl j_ne }, { rw [fin.cons_succ, fin.cons_zero, ← not_le, absolute_value.map_sub] at approx, have := (classical.some_spec (this j₁)).2, contradiction }, { rw [fin.cons_succ, fin.cons_zero, ← not_le] at approx, have := (classical.some_spec (this j₀)).2, contradiction }, { rw [fin.cons_succ, fin.cons_succ] at approx, rw [ne.def, fin.succ_inj] at j_ne, have : j₀ = j₁ := (classical.some_spec (this j₀)).1.symm.trans (((ht' (classical.some (this j₀)) (classical.some (this j₁))).mpr approx).trans (classical.some_spec (this j₁)).1), contradiction } }, -- However, if one of those partitions `j` is inhabited by some `i`, then this `j` works. by_cases exists_nonempty_j : ∃ j, (∃ i, t' i = j) ∧ ∀ i, t' i = j → (card_pow_degree (A 0 % b - A i.succ % b) : ℝ) < card_pow_degree b • ε, { obtain ⟨j, ⟨i, hi⟩, hj⟩ := exists_nonempty_j, refine ⟨j, λ i', ⟨hj i', λ hi', trans ((ht' _ _).mpr _) hi⟩⟩, apply anti_archim' _ hi', rw absolute_value.map_sub, exact hj _ hi }, -- And otherwise, we can just take any `j`, since those are empty. refine ⟨j, λ i, ⟨hj i, λ hi, _⟩⟩, have := exists_nonempty_j ⟨t' i, ⟨i, rfl⟩, λ i' hi', anti_archim' hi ((ht' _ _).mp hi')⟩, contradiction end /-- For all `ε > 0`, we can partition the remainders of any family of polynomials `A` into classes, where all remainders in a class are close together. -/ lemma exists_partition_polynomial (n : ℕ) {ε : ℝ} (hε : 0 < ε) {b : polynomial Fq} (hb : b ≠ 0) (A : fin n → polynomial Fq) : ∃ (t : fin n → fin (fintype.card Fq ^ ⌈- log ε / log (fintype.card Fq)⌉₊)), ∀ (i₀ i₁ : fin n), t i₀ = t i₁ → (card_pow_degree (A i₁ % b - A i₀ % b) : ℝ) < card_pow_degree b • ε := begin obtain ⟨t, ht⟩ := exists_partition_polynomial_aux n hε hb A, exact ⟨t, λ i₀ i₁ hi, (ht i₀ i₁).mp hi⟩ end /-- `λ p, fintype.card Fq ^ degree p` is an admissible absolute value. We set `q ^ degree 0 = 0`. -/ noncomputable def card_pow_degree_is_admissible : is_admissible (card_pow_degree : absolute_value (polynomial Fq) ℤ) := { card := λ ε, fintype.card Fq ^ ⌈- log ε / log (fintype.card Fq)⌉₊, exists_partition' := λ n ε hε b hb, exists_partition_polynomial n hε hb, .. @card_pow_degree_is_euclidean Fq _ _ } end polynomial
2e29ce8d56f3a32fca2562c3b1732dd425f09b9e
e030b0259b777fedcdf73dd966f3f1556d392178
/library/init/meta/vm.lean
908ab08085b2cd3a9787394577f084e217765e83
[ "Apache-2.0" ]
permissive
fgdorais/lean
17b46a095b70b21fa0790ce74876658dc5faca06
c3b7c54d7cca7aaa25328f0a5660b6b75fe26055
refs/heads/master
1,611,523,590,686
1,484,412,902,000
1,484,412,902,000
38,489,734
0
0
null
1,435,923,380,000
1,435,923,379,000
null
UTF-8
Lean
false
false
6,400
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 -/ prelude import init.meta.tactic init.data.option.basic meta constant vm_obj : Type inductive vm_obj_kind | simple | constructor | closure | native_closure | mpz | name | level | expr | declaration | environment | tactic_state | format | options | other namespace vm_obj meta constant kind : vm_obj → vm_obj_kind /- For simple and constructor vm_obj's, it returns the constructor tag/index. Return 0 otherwise. -/ meta constant cidx : vm_obj → nat /- For closure vm_obj's, it returns the internal function index. -/ meta constant fn_idx : vm_obj → nat /- For constructor vm_obj's, it returns the data stored in the object. For closure vm_obj's, it returns the local arguments captured by the closure. -/ meta constant fields : vm_obj → list vm_obj /- For simple and mpz vm_obj's -/ meta constant to_nat : vm_obj → nat /- For name vm_obj's, it returns the name wrapped by the vm_obj. -/ meta constant to_name : vm_obj → name /- For level vm_obj's, it returns the universe level wrapped by the vm_obj. -/ meta constant to_level : vm_obj → level /- For expr vm_obj's, it returns the expression wrapped by the vm_obj. -/ meta constant to_expr : vm_obj → expr /- For declaration vm_obj's, it returns the declaration wrapped by the vm_obj. -/ meta constant to_declaration : vm_obj → declaration /- For environment vm_obj's, it returns the environment wrapped by the vm_obj. -/ meta constant to_environment : vm_obj → environment /- For tactic_state vm_obj's, it returns the tactic_state object wrapped by the vm_obj. -/ meta constant to_tactic_state : vm_obj → tactic_state /- For format vm_obj's, it returns the format object wrapped by the vm_obj. -/ meta constant to_format : vm_obj → format end vm_obj meta constant vm_decl : Type inductive vm_decl_kind | bytecode | builtin | cfun /- Information for local variables and arguments on the VM stack. Remark: type is only available if it is a closed term at compilation time. -/ meta structure vm_local_info := (id : name) (type : option expr) namespace vm_decl meta constant kind : vm_decl → vm_decl_kind meta constant to_name : vm_decl → name /- Internal function index associated with the given VM declaration. -/ meta constant idx : vm_decl → nat /- Number of arguments needed to execute the given VM declaration. -/ meta constant arity : vm_decl → nat /- Return (line, column) if available -/ meta constant pos : vm_decl → option (nat × nat) /- Return .olean file where the given VM declaration was imported from. -/ meta constant olean : vm_decl → option string /- Return names .olean file where the given VM declaration was imported from. -/ meta constant args_info : vm_decl → list vm_local_info end vm_decl meta constant vm_core : Type → Type meta constant vm_core.map {α β : Type} : (α → β) → vm_core α → vm_core β meta constant vm_core.ret {α : Type} : α → vm_core α meta constant vm_core.bind {α β : Type} : vm_core α → (α → vm_core β) → vm_core β meta instance : monad vm_core := {map := @vm_core.map, ret := @vm_core.ret, bind := @vm_core.bind} @[reducible] meta def vm (α : Type) : Type := option_t.{1 1} vm_core α namespace vm meta constant get_env : vm environment meta constant get_decl : name → vm vm_decl meta constant get_options : vm options meta constant stack_size : vm nat /- Return the vm_obj stored at the given position on the execution stack. It fails if position >= vm.stack_size -/ meta constant stack_obj : nat → vm vm_obj /- Return (name, type) for the object at the given position on the execution stack. It fails if position >= vm.stack_size. The name is anonymous if vm_obj is a transient value created by the compiler. Type information is only recorded if the type is a closed term at compilation time. -/ meta constant stack_obj_info : nat → vm (name × option expr) /- Pretty print the vm_obj at the given position on the execution stack. -/ meta constant pp_stack_obj : nat → vm format /- Pretty print the given expression. -/ meta constant pp_expr : expr → vm format /- Number of frames on the call stack. -/ meta constant call_stack_size : vm nat /- Return the function name at the given stack frame. Action fails if position >= vm.call_stack_size. -/ meta constant call_stack_fn : nat → vm name /- Return the range [start, end) for the given stack frame. Action fails if position >= vm.call_stack_size. The values start and end correspond to positions at the execution stack. We have that 0 <= start < end <= vm.stack_size -/ meta constant call_stack_var_range : nat → vm (nat × nat) /- Return the name of the function on top of the call stack. -/ meta constant curr_fn : vm name /- Return the base stack pointer for the frame on top of the call stack. -/ meta constant bp : vm nat /- Return the program counter. -/ meta constant pc : vm nat /- Convert the given vm_obj into a string -/ meta constant obj_to_string : vm_obj → vm string meta constant put_str : string → vm unit meta constant get_line : vm string /- Return tt if end of the input stream has been reached. For example, this can happen if the user presses Ctrl-D -/ meta constant eof : vm bool /- Return the list of declarations tagged with the given attribute. -/ meta constant get_attribute : name → vm (list name) meta def trace {α : Type} [has_to_format α] (a : α) : vm unit := do fmt ← return $ to_fmt a, return $ _root_.trace_fmt fmt (λ u, ()) end vm meta structure vm_monitor (s : Type) := (init : s) (step : s → vm s) /- Registers a new virtual machine monitor. The argument must be the name of a definition of type `vm_monitor S`. The command will override the last monitor. If option 'debugger' is true, then the VM will initialize the vm_monitor state using the 'init' field, and will invoke the function 'step' before each instruction is invoked. -/ meta constant vm_monitor.register : name → command
cf690231cc4cba140897319e07dc81d184acb0a9
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/linear_algebra/exterior_algebra/grading.lean
0f5089ccbee077f215e433e70b727affb84eced1
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
3,646
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import linear_algebra.exterior_algebra.basic import ring_theory.graded_algebra.basic /-! # Results about the grading structure of the exterior algebra > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Many of these results are copied with minimal modification from the tensor algebra. The main result is `exterior_algebra.graded_algebra`, which says that the exterior algebra is a ℕ-graded algebra. -/ namespace exterior_algebra variables {R M : Type*} [comm_ring R] [add_comm_group M] [module R M] variables (R M) open_locale direct_sum /-- A version of `exterior_algebra.ι` that maps directly into the graded structure. This is primarily an auxiliary construction used to provide `exterior_algebra.graded_algebra`. -/ def graded_algebra.ι : M →ₗ[R] ⨁ i : ℕ, ↥((ι R : M →ₗ[_] _).range ^ i) := direct_sum.lof R ℕ (λ i, ↥((ι R : M →ₗ[_] _).range ^ i)) 1 ∘ₗ (ι R).cod_restrict _ (λ m, by simpa only [pow_one] using linear_map.mem_range_self _ m) lemma graded_algebra.ι_apply (m : M) : graded_algebra.ι R M m = direct_sum.of (λ i, ↥((ι R : M →ₗ[_] _).range ^ i)) 1 (⟨ι R m, by simpa only [pow_one] using linear_map.mem_range_self _ m⟩) := rfl lemma graded_algebra.ι_sq_zero (m : M) : graded_algebra.ι R M m * graded_algebra.ι R M m = 0 := begin rw [graded_algebra.ι_apply, direct_sum.of_mul_of], refine dfinsupp.single_eq_zero.mpr (subtype.ext $ ι_sq_zero _), end /-- `exterior_algebra.graded_algebra.ι` lifted to exterior algebra. This is primarily an auxiliary construction used to provide `exterior_algebra.graded_algebra`. -/ def graded_algebra.lift_ι : exterior_algebra R M →ₐ[R] ⨁ (i : ℕ), ↥((ι R).range ^ i : submodule R (exterior_algebra R M)) := lift R ⟨by apply graded_algebra.ι R M, graded_algebra.ι_sq_zero R M⟩ variables (R M) lemma graded_algebra.lift_ι_eq (i : ℕ) (x : ((ι R : M →ₗ[R] exterior_algebra R M).range ^ i : submodule R (exterior_algebra R M))) : graded_algebra.lift_ι R M x = direct_sum.of (λ i, ↥((ι R).range ^ i : submodule R (exterior_algebra R M))) i x := begin cases x with x hx, dsimp only [subtype.coe_mk, direct_sum.lof_eq_of], refine submodule.pow_induction_on_left' _ (λ r, _) (λ x y i hx hy ihx ihy, _) (λ m hm i x hx ih, _) hx, { rw [alg_hom.commutes, direct_sum.algebra_map_apply], refl }, { rw [alg_hom.map_add, ihx, ihy, ←map_add], refl }, { obtain ⟨_, rfl⟩ := hm, rw [alg_hom.map_mul, ih, graded_algebra.lift_ι, lift_ι_apply, graded_algebra.ι_apply R M, direct_sum.of_mul_of], exact direct_sum.of_eq_of_graded_monoid_eq (sigma.subtype_ext (add_comm _ _) rfl) }, end /-- The exterior algebra is graded by the powers of the submodule `(exterior_algebra.ι R).range`. -/ instance graded_algebra : graded_algebra ((^) (ι R : M →ₗ[R] exterior_algebra R M).range : ℕ → submodule R _) := graded_algebra.of_alg_hom _ -- while not necessary, the `by apply` makes this elaborate faster (by apply graded_algebra.lift_ι R M) -- the proof from here onward is identical to the `tensor_algebra` case (begin ext m, dsimp only [linear_map.comp_apply, alg_hom.to_linear_map_apply, alg_hom.comp_apply, alg_hom.id_apply, graded_algebra.lift_ι], rw [lift_ι_apply, graded_algebra.ι_apply R M, direct_sum.coe_alg_hom_of, subtype.coe_mk], end) (by apply graded_algebra.lift_ι_eq R M) end exterior_algebra
c680373f1934dcba413e56ecadb15bb772774488
367134ba5a65885e863bdc4507601606690974c1
/src/data/multiset/pi.lean
49747b7d9ea08fcccb9b40753493712a3068434b
[ "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
4,893
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl -/ import data.multiset.nodup /-! # The cartesian product of multisets -/ namespace multiset section pi variables {α : Type*} open function /-- Given `δ : α → Type*`, `pi.empty δ` is the trivial dependent function out of the empty multiset. -/ def pi.empty (δ : α → Type*) : (Πa∈(0:multiset α), δ a) . variables [decidable_eq α] {δ : α → Type*} /-- Given `δ : α → Type*`, a multiset `m` and a term `a`, as well as a term `b : δ a` and a function `f` such that `f a' : δ a'` for all `a'` in `m`, `pi.cons m a b f` is a function `g` such that `g a'' : δ a''` for all `a''` in `a ::ₘ m`. -/ def pi.cons (m : multiset α) (a : α) (b : δ a) (f : Πa∈m, δ a) : Πa'∈a ::ₘ m, δ a' := λa' ha', if h : a' = a then eq.rec b h.symm else f a' $ (mem_cons.1 ha').resolve_left h lemma pi.cons_same {m : multiset α} {a : α} {b : δ a} {f : Πa∈m, δ a} (h : a ∈ a ::ₘ m) : pi.cons m a b f a h = b := dif_pos rfl lemma pi.cons_ne {m : multiset α} {a a' : α} {b : δ a} {f : Πa∈m, δ a} (h' : a' ∈ a ::ₘ m) (h : a' ≠ a) : pi.cons m a b f a' h' = f a' ((mem_cons.1 h').resolve_left h) := dif_neg h lemma pi.cons_swap {a a' : α} {b : δ a} {b' : δ a'} {m : multiset α} {f : Πa∈m, δ a} (h : a ≠ a') : pi.cons (a' ::ₘ m) a b (pi.cons m a' b' f) == pi.cons (a ::ₘ m) a' b' (pi.cons m a b f) := begin apply hfunext, { refl }, intros a'' _ h, subst h, apply hfunext, { rw [cons_swap] }, intros ha₁ ha₂ h, by_cases h₁ : a'' = a; by_cases h₂ : a'' = a'; simp [*, pi.cons_same, pi.cons_ne] at *, { subst h₁, rw [pi.cons_same, pi.cons_same] }, { subst h₂, rw [pi.cons_same, pi.cons_same] } end /-- `pi m t` constructs the Cartesian product over `t` indexed by `m`. -/ def pi (m : multiset α) (t : Πa, multiset (δ a)) : multiset (Πa∈m, δ a) := m.rec_on {pi.empty δ} (λa m (p : multiset (Πa∈m, δ a)), (t a).bind $ λb, p.map $ pi.cons m a b) begin intros a a' m n, by_cases eq : a = a', { subst eq }, { simp [map_bind, bind_bind (t a') (t a)], apply bind_hcongr, { rw [cons_swap a a'] }, intros b hb, apply bind_hcongr, { rw [cons_swap a a'] }, intros b' hb', apply map_hcongr, { rw [cons_swap a a'] }, intros f hf, exact pi.cons_swap eq } end @[simp] lemma pi_zero (t : Πa, multiset (δ a)) : pi 0 t = pi.empty δ ::ₘ 0 := rfl @[simp] lemma pi_cons (m : multiset α) (t : Πa, multiset (δ a)) (a : α) : pi (a ::ₘ m) t = ((t a).bind $ λb, (pi m t).map $ pi.cons m a b) := rec_on_cons a m lemma pi_cons_injective {a : α} {b : δ a} {s : multiset α} (hs : a ∉ s) : function.injective (pi.cons s a b) := assume f₁ f₂ eq, funext $ assume a', funext $ assume h', have ne : a ≠ a', from assume h, hs $ h.symm ▸ h', have a' ∈ a ::ₘ s, from mem_cons_of_mem h', calc f₁ a' h' = pi.cons s a b f₁ a' this : by rw [pi.cons_ne this ne.symm] ... = pi.cons s a b f₂ a' this : by rw [eq] ... = f₂ a' h' : by rw [pi.cons_ne this ne.symm] lemma card_pi (m : multiset α) (t : Πa, multiset (δ a)) : card (pi m t) = prod (m.map $ λa, card (t a)) := multiset.induction_on m (by simp) (by simp [mul_comm] {contextual := tt}) lemma nodup_pi {s : multiset α} {t : Πa, multiset (δ a)} : nodup s → (∀a∈s, nodup (t a)) → nodup (pi s t) := multiset.induction_on s (assume _ _, nodup_singleton _) begin assume a s ih hs ht, have has : a ∉ s, by simp at hs; exact hs.1, have hs : nodup s, by simp at hs; exact hs.2, simp, split, { assume b hb, from nodup_map (pi_cons_injective has) (ih hs $ assume a' h', ht a' $ mem_cons_of_mem h') }, { apply pairwise_of_nodup _ (ht a $ mem_cons_self _ _), from assume b₁ hb₁ b₂ hb₂ neb, disjoint_map_map.2 (assume f hf g hg eq, have pi.cons s a b₁ f a (mem_cons_self _ _) = pi.cons s a b₂ g a (mem_cons_self _ _), by rw [eq], neb $ show b₁ = b₂, by rwa [pi.cons_same, pi.cons_same] at this) } end lemma mem_pi (m : multiset α) (t : Πa, multiset (δ a)) : ∀f:Πa∈m, δ a, (f ∈ pi m t) ↔ (∀a (h : a ∈ m), f a h ∈ t a) := begin refine multiset.induction_on m (λ f, _) (λ a m ih f, _), { simpa using show f = pi.empty δ, by funext a ha; exact ha.elim }, simp only [mem_bind, exists_prop, mem_cons, pi_cons, mem_map], split, { rintro ⟨b, hb, f', hf', rfl⟩ a' ha', rw [ih] at hf', by_cases a' = a, { subst h, rwa [pi.cons_same] }, { rw [pi.cons_ne _ h], apply hf' } }, { intro hf, refine ⟨_, hf a (mem_cons_self a _), λa ha, f a (mem_cons_of_mem ha), (ih _).2 (λ a' h', hf _ _), _⟩, funext a' h', by_cases a' = a, { subst h, rw [pi.cons_same] }, { rw [pi.cons_ne _ h] } } end end pi end multiset
6a96938665ffda836432d9354d871f95869e4a29
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/measure_theory/measure/outer_measure.lean
6a3327d60630dec81d74341747aade2282f55ade
[ "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
61,599
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 analysis.specific_limits import measure_theory.pi_system import data.matrix.notation import topology.algebra.infinite_sum /-! # Outer Measures An outer measure is a function `μ : set α → ℝ≥0∞`, from the powerset of a type to the extended nonnegative real numbers that satisfies the following conditions: 1. `μ ∅ = 0`; 2. `μ` is monotone; 3. `μ` is countably subadditive. This means that the outer measure of a countable union is at most the sum of the outer measure on the individual sets. Note that we do not need `α` to be measurable to define an outer measure. The outer measures on a type `α` form a complete lattice. Given an arbitrary function `m : set α → ℝ≥0∞` that sends `∅` to `0` we can define an outer measure on `α` that on `s` is defined to be the infimum of `∑ᵢ, m (sᵢ)` for all collections of sets `sᵢ` that cover `s`. This is the unique maximal outer measure that is at most the given function. We also define this for functions `m` defined on a subset of `set α`, by treating the function as having value `∞` outside its domain. Given an outer measure `m`, the Carathéodory-measurable sets are the sets `s` such that for all sets `t` we have `m t = m (t ∩ s) + m (t \ s)`. This forms a measurable space. ## Main definitions and statements * `outer_measure.bounded_by` is the greatest outer measure that is at most the given function. If you know that the given functions sends `∅` to `0`, then `outer_measure.of_function` is a special case. * `caratheodory` is the Carathéodory-measurable space of an outer measure. * `Inf_eq_of_function_Inf_gen` is a characterization of the infimum of outer measures. * `induced_outer_measure` is the measure induced by a function on a subset of `set α` ## References * <https://en.wikipedia.org/wiki/Outer_measure> * <https://en.wikipedia.org/wiki/Carath%C3%A9odory%27s_criterion> ## Tags outer measure, Carathéodory-measurable, Carathéodory's criterion -/ noncomputable theory open set finset function filter encodable open_locale classical big_operators nnreal topological_space ennreal namespace measure_theory /-- An outer measure is a countably subadditive monotone function that sends `∅` to `0`. -/ structure outer_measure (α : Type*) := (measure_of : set α → ℝ≥0∞) (empty : measure_of ∅ = 0) (mono : ∀{s₁ s₂}, s₁ ⊆ s₂ → measure_of s₁ ≤ measure_of s₂) (Union_nat : ∀(s:ℕ → set α), measure_of (⋃i, s i) ≤ ∑'i, measure_of (s i)) namespace outer_measure section basic variables {α : Type*} {β : Type*} {ms : set (outer_measure α)} {m : outer_measure α} instance : has_coe_to_fun (outer_measure α) := ⟨_, λ m, m.measure_of⟩ @[simp] lemma measure_of_eq_coe (m : outer_measure α) : m.measure_of = m := rfl @[simp] theorem empty' (m : outer_measure α) : m ∅ = 0 := m.empty theorem mono' (m : outer_measure α) {s₁ s₂} (h : s₁ ⊆ s₂) : m s₁ ≤ m s₂ := m.mono h protected theorem Union (m : outer_measure α) {β} [encodable β] (s : β → set α) : m (⋃i, s i) ≤ ∑'i, m (s i) := rel_supr_tsum m m.empty (≤) m.Union_nat s lemma Union_null (m : outer_measure α) {β} [encodable β] {s : β → set α} (h : ∀ i, m (s i) = 0) : m (⋃i, s i) = 0 := by simpa [h] using m.Union s protected lemma Union_finset (m : outer_measure α) (s : β → set α) (t : finset β) : m (⋃i ∈ t, s i) ≤ ∑ i in t, m (s i) := rel_supr_sum m m.empty (≤) m.Union_nat s t protected lemma union (m : outer_measure α) (s₁ s₂ : set α) : m (s₁ ∪ s₂) ≤ m s₁ + m s₂ := rel_sup_add m m.empty (≤) m.Union_nat s₁ s₂ /-- If `s : ι → set α` is a sequence of sets, `S = ⋃ n, s n`, and `m (S \ s n)` tends to zero along some nontrivial filter (usually `at_top` on `α = ℕ`), then `m S = ⨆ n, m (s n)`. -/ lemma Union_of_tendsto_zero {ι} (m : outer_measure α) {s : ι → set α} (l : filter ι) [ne_bot l] (h0 : tendsto (λ k, m ((⋃ n, s n) \ s k)) l (𝓝 0)) : m (⋃ n, s n) = ⨆ n, m (s n) := begin set S := ⋃ n, s n, set M := ⨆ n, m (s n), have hsS : ∀ {k}, s k ⊆ S, from λ k, subset_Union _ _, refine le_antisymm _ (supr_le $ λ n, m.mono hsS), have A : ∀ k, m S ≤ M + m (S \ s k), from λ k, calc m S = m (s k ∪ S \ s k) : by rw [union_diff_self, union_eq_self_of_subset_left hsS] ... ≤ m (s k) + m (S \ s k) : m.union _ _ ... ≤ M + m (S \ s k) : add_le_add_right (le_supr _ k) _, have B : tendsto (λ k, M + m (S \ s k)) l (𝓝 (M + 0)), from tendsto_const_nhds.add h0, rw add_zero at B, exact ge_of_tendsto' B A end /-- If `s : ℕ → set α` is a monotone sequence of sets such that `∑' k, m (s (k + 1) \ s k) ≠ ∞`, then `m (⋃ n, s n) = ⨆ n, m (s n)`. -/ lemma Union_nat_of_monotone_of_tsum_ne_top (m : outer_measure α) {s : ℕ → set α} (h_mono : ∀ n, s n ⊆ s (n + 1)) (h0 : ∑' k, m (s (k + 1) \ s k) ≠ ∞) : m (⋃ n, s n) = ⨆ n, m (s n) := begin refine m.Union_of_tendsto_zero at_top _, refine tendsto_nhds_bot_mono' (ennreal.tendsto_sum_nat_add _ h0) (λ n, _), refine (m.mono _).trans (m.Union _), /- Current goal: `(⋃ k, s k) \ s n ⊆ ⋃ k, s (k + n + 1) \ s (k + n)` -/ have h' : monotone s := @monotone_nat_of_le_succ (set α) _ _ h_mono, simp only [diff_subset_iff, Union_subset_iff], intros i x hx, rcases nat.find_x ⟨i, hx⟩ with ⟨j, hj, hlt⟩, clear hx i, cases le_or_lt j n with hjn hnj, { exact or.inl (h' hjn hj) }, have : j - (n + 1) + n + 1 = j, by rw [add_assoc, nat.sub_add_cancel hnj], refine or.inr (mem_Union.2 ⟨j - (n + 1), _, hlt _ _⟩), { rwa this }, { rw [← nat.succ_le_iff, nat.succ_eq_add_one, this] } end lemma le_inter_add_diff {m : outer_measure α} {t : set α} (s : set α) : m t ≤ m (t ∩ s) + m (t \ s) := by { convert m.union _ _, rw inter_union_diff t s } lemma diff_null (m : outer_measure α) (s : set α) {t : set α} (ht : m t = 0) : m (s \ t) = m s := begin refine le_antisymm (m.mono $ diff_subset _ _) _, calc m s ≤ m (s ∩ t) + m (s \ t) : le_inter_add_diff _ ... ≤ m t + m (s \ t) : add_le_add_right (m.mono $ inter_subset_right _ _) _ ... = m (s \ t) : by rw [ht, zero_add] end lemma union_null (m : outer_measure α) {s₁ s₂ : set α} (h₁ : m s₁ = 0) (h₂ : m s₂ = 0) : m (s₁ ∪ s₂) = 0 := by simpa [h₁, h₂] using m.union s₁ s₂ lemma coe_fn_injective : injective (λ (μ : outer_measure α) (s : set α), μ s) := λ μ₁ μ₂ h, by { cases μ₁, cases μ₂, congr, exact h } @[ext] lemma ext {μ₁ μ₂ : outer_measure α} (h : ∀ s, μ₁ s = μ₂ s) : μ₁ = μ₂ := coe_fn_injective $ funext h /-- A version of `measure_theory.outer_measure.ext` that assumes `μ₁ s = μ₂ s` on all *nonempty* sets `s`, and gets `μ₁ ∅ = μ₂ ∅` from `measure_theory.outer_measure.empty'`. -/ lemma ext_nonempty {μ₁ μ₂ : outer_measure α} (h : ∀ s : set α, s.nonempty → μ₁ s = μ₂ s) : μ₁ = μ₂ := ext $ λ s, s.eq_empty_or_nonempty.elim (λ he, by rw [he, empty', empty']) (h s) instance : has_zero (outer_measure α) := ⟨{ measure_of := λ_, 0, empty := rfl, mono := assume _ _ _, le_refl 0, Union_nat := assume s, zero_le _ }⟩ @[simp] theorem coe_zero : ⇑(0 : outer_measure α) = 0 := rfl instance : inhabited (outer_measure α) := ⟨0⟩ instance : has_add (outer_measure α) := ⟨λm₁ m₂, { measure_of := λs, m₁ s + m₂ s, empty := show m₁ ∅ + m₂ ∅ = 0, by simp [outer_measure.empty], mono := assume s₁ s₂ h, add_le_add (m₁.mono h) (m₂.mono h), Union_nat := assume s, calc m₁ (⋃i, s i) + m₂ (⋃i, s i) ≤ (∑'i, m₁ (s i)) + (∑'i, m₂ (s i)) : add_le_add (m₁.Union_nat s) (m₂.Union_nat s) ... = _ : ennreal.tsum_add.symm}⟩ @[simp] theorem coe_add (m₁ m₂ : outer_measure α) : ⇑(m₁ + m₂) = m₁ + m₂ := rfl theorem add_apply (m₁ m₂ : outer_measure α) (s : set α) : (m₁ + m₂) s = m₁ s + m₂ s := rfl instance add_comm_monoid : add_comm_monoid (outer_measure α) := { zero := 0, add := (+), .. injective.add_comm_monoid (show outer_measure α → set α → ℝ≥0∞, from coe_fn) coe_fn_injective rfl (λ _ _, rfl) } instance : has_scalar ℝ≥0∞ (outer_measure α) := ⟨λ c m, { measure_of := λ s, c * m s, empty := by simp, mono := λ s t h, ennreal.mul_left_mono $ m.mono h, Union_nat := λ s, by { rw [ennreal.tsum_mul_left], exact ennreal.mul_left_mono (m.Union _) } }⟩ @[simp] lemma coe_smul (c : ℝ≥0∞) (m : outer_measure α) : ⇑(c • m) = c • m := rfl lemma smul_apply (c : ℝ≥0∞) (m : outer_measure α) (s : set α) : (c • m) s = c * m s := rfl instance : module ℝ≥0∞ (outer_measure α) := { smul := (•), .. injective.module ℝ≥0∞ ⟨show outer_measure α → set α → ℝ≥0∞, from coe_fn, coe_zero, coe_add⟩ coe_fn_injective coe_smul } instance : has_bot (outer_measure α) := ⟨0⟩ instance outer_measure.order_bot : order_bot (outer_measure α) := { le := λm₁ m₂, ∀s, m₁ s ≤ m₂ s, bot := 0, le_refl := assume a s, le_refl _, le_trans := assume a b c hab hbc s, le_trans (hab s) (hbc s), le_antisymm := assume a b hab hba, ext $ assume s, le_antisymm (hab s) (hba s), bot_le := assume a s, zero_le _ } section supremum instance : has_Sup (outer_measure α) := ⟨λms, { measure_of := λs, ⨆ m ∈ ms, (m : outer_measure α) s, empty := nonpos_iff_eq_zero.1 $ bsupr_le $ λ m h, le_of_eq m.empty, mono := assume s₁ s₂ hs, bsupr_le_bsupr $ assume m hm, m.mono hs, Union_nat := assume f, bsupr_le $ assume m hm, calc m (⋃i, f i) ≤ ∑' (i : ℕ), m (f i) : m.Union_nat _ ... ≤ ∑'i, (⨆ m ∈ ms, (m : outer_measure α) (f i)) : ennreal.tsum_le_tsum $ assume i, le_bsupr m hm }⟩ instance : complete_lattice (outer_measure α) := { .. outer_measure.order_bot, .. complete_lattice_of_Sup (outer_measure α) (λ ms, ⟨λ m hm s, le_bsupr m hm, λ m hm s, bsupr_le (λ m' hm', hm hm' s)⟩) } @[simp] theorem Sup_apply (ms : set (outer_measure α)) (s : set α) : (Sup ms) s = ⨆ m ∈ ms, (m : outer_measure α) s := rfl @[simp] theorem supr_apply {ι} (f : ι → outer_measure α) (s : set α) : (⨆ i : ι, f i) s = ⨆ i, f i s := by rw [supr, Sup_apply, supr_range, supr] @[norm_cast] theorem coe_supr {ι} (f : ι → outer_measure α) : ⇑(⨆ i, f i) = ⨆ i, f i := funext $ λ s, by rw [supr_apply, _root_.supr_apply] @[simp] theorem sup_apply (m₁ m₂ : outer_measure α) (s : set α) : (m₁ ⊔ m₂) s = m₁ s ⊔ m₂ s := by have := supr_apply (λ b, cond b m₁ m₂) s; rwa [supr_bool_eq, supr_bool_eq] at this theorem smul_supr {ι} (f : ι → outer_measure α) (c : ℝ≥0∞) : c • (⨆ i, f i) = ⨆ i, c • f i := ext $ λ s, by simp only [smul_apply, supr_apply, ennreal.mul_supr] end supremum @[mono] lemma mono'' {m₁ m₂ : outer_measure α} {s₁ s₂ : set α} (hm : m₁ ≤ m₂) (hs : s₁ ⊆ s₂) : m₁ s₁ ≤ m₂ s₂ := (hm s₁).trans (m₂.mono hs) /-- The pushforward of `m` along `f`. The outer measure on `s` is defined to be `m (f ⁻¹' s)`. -/ def map {β} (f : α → β) : outer_measure α →ₗ[ℝ≥0∞] outer_measure β := { to_fun := λ m, { measure_of := λs, m (f ⁻¹' s), empty := m.empty, mono := λ s t h, m.mono (preimage_mono h), Union_nat := λ s, by rw [preimage_Union]; exact m.Union_nat (λ i, f ⁻¹' s i) }, map_add' := λ m₁ m₂, coe_fn_injective rfl, map_smul' := λ c m, coe_fn_injective rfl } @[simp] theorem map_apply {β} (f : α → β) (m : outer_measure α) (s : set β) : map f m s = m (f ⁻¹' s) := rfl @[simp] theorem map_id (m : outer_measure α) : map id m = m := ext $ λ s, rfl @[simp] theorem map_map {β γ} (f : α → β) (g : β → γ) (m : outer_measure α) : map g (map f m) = map (g ∘ f) m := ext $ λ s, rfl @[mono] theorem map_mono {β} (f : α → β) : monotone (map f) := λ m m' h s, h _ @[simp] theorem map_sup {β} (f : α → β) (m m' : outer_measure α) : map f (m ⊔ m') = map f m ⊔ map f m' := ext $ λ s, by simp only [map_apply, sup_apply] @[simp] theorem map_supr {β ι} (f : α → β) (m : ι → outer_measure α) : map f (⨆ i, m i) = ⨆ i, map f (m i) := ext $ λ s, by simp only [map_apply, supr_apply] instance : functor outer_measure := {map := λ α β f, map f} instance : is_lawful_functor outer_measure := { id_map := λ α, map_id, comp_map := λ α β γ f g m, (map_map f g m).symm } /-- The dirac outer measure. -/ def dirac (a : α) : outer_measure α := { measure_of := λs, indicator s (λ _, 1) a, empty := by simp, mono := λ s t h, indicator_le_indicator_of_subset h (λ _, zero_le _) a, Union_nat := λ s, if hs : a ∈ ⋃ n, s n then let ⟨i, hi⟩ := mem_Union.1 hs in calc indicator (⋃ n, s n) (λ _, (1 : ℝ≥0∞)) a = 1 : indicator_of_mem hs _ ... = indicator (s i) (λ _, 1) a : (indicator_of_mem hi _).symm ... ≤ ∑' n, indicator (s n) (λ _, 1) a : ennreal.le_tsum _ else by simp only [indicator_of_not_mem hs, zero_le]} @[simp] theorem dirac_apply (a : α) (s : set α) : dirac a s = indicator s (λ _, 1) a := rfl /-- The sum of an (arbitrary) collection of outer measures. -/ def sum {ι} (f : ι → outer_measure α) : outer_measure α := { measure_of := λs, ∑' i, f i s, empty := by simp, mono := λ s t h, ennreal.tsum_le_tsum (λ i, (f i).mono' h), Union_nat := λ s, by rw ennreal.tsum_comm; exact ennreal.tsum_le_tsum (λ i, (f i).Union_nat _) } @[simp] theorem sum_apply {ι} (f : ι → outer_measure α) (s : set α) : sum f s = ∑' i, f i s := rfl theorem smul_dirac_apply (a : ℝ≥0∞) (b : α) (s : set α) : (a • dirac b) s = indicator s (λ _, a) b := by simp only [smul_apply, dirac_apply, ← indicator_mul_right _ (λ _, a), mul_one] /-- Pullback of an `outer_measure`: `comap f μ s = μ (f '' s)`. -/ def comap {β} (f : α → β) : outer_measure β →ₗ[ℝ≥0∞] outer_measure α := { to_fun := λ m, { measure_of := λ s, m (f '' s), empty := by simp, mono := λ s t h, m.mono $ image_subset f h, Union_nat := λ s, by { rw [image_Union], apply m.Union_nat } }, map_add' := λ m₁ m₂, rfl, map_smul' := λ c m, rfl } @[simp] lemma comap_apply {β} (f : α → β) (m : outer_measure β) (s : set α) : comap f m s = m (f '' s) := rfl @[mono] lemma comap_mono {β} (f : α → β) : monotone (comap f) := λ m m' h s, h _ @[simp] theorem comap_supr {β ι} (f : α → β) (m : ι → outer_measure β) : comap f (⨆ i, m i) = ⨆ i, comap f (m i) := ext $ λ s, by simp only [comap_apply, supr_apply] /-- Restrict an `outer_measure` to a set. -/ def restrict (s : set α) : outer_measure α →ₗ[ℝ≥0∞] outer_measure α := (map coe).comp (comap (coe : s → α)) @[simp] lemma restrict_apply (s t : set α) (m : outer_measure α) : restrict s m t = m (t ∩ s) := by simp [restrict] @[mono] lemma restrict_mono {s t : set α} (h : s ⊆ t) {m m' : outer_measure α} (hm : m ≤ m') : restrict s m ≤ restrict t m' := λ u, by { simp only [restrict_apply], exact (hm _).trans (m'.mono $ inter_subset_inter_right _ h) } @[simp] lemma restrict_univ (m : outer_measure α) : restrict univ m = m := ext $ λ s, by simp @[simp] lemma restrict_empty (m : outer_measure α) : restrict ∅ m = 0 := ext $ λ s, by simp @[simp] lemma restrict_supr {ι} (s : set α) (m : ι → outer_measure α) : restrict s (⨆ i, m i) = ⨆ i, restrict s (m i) := by simp [restrict] lemma map_comap {β} (f : α → β) (m : outer_measure β) : map f (comap f m) = restrict (range f) m := ext $ λ s, congr_arg m $ by simp only [image_preimage_eq_inter_range, subtype.range_coe] lemma map_comap_le {β} (f : α → β) (m : outer_measure β) : map f (comap f m) ≤ m := λ s, m.mono $ image_preimage_subset _ _ lemma restrict_le_self (m : outer_measure α) (s : set α) : restrict s m ≤ m := map_comap_le _ _ @[simp] lemma map_le_restrict_range {β} {ma : outer_measure α} {mb : outer_measure β} {f : α → β} : map f ma ≤ restrict (range f) mb ↔ map f ma ≤ mb := ⟨λ h, h.trans (restrict_le_self _ _), λ h s, by simpa using h (s ∩ range f)⟩ lemma map_comap_of_surjective {β} {f : α → β} (hf : surjective f) (m : outer_measure β) : map f (comap f m) = m := ext $ λ s, by rw [map_apply, comap_apply, hf.image_preimage] lemma le_comap_map {β} (f : α → β) (m : outer_measure α) : m ≤ comap f (map f m) := λ s, m.mono $ subset_preimage_image _ _ lemma comap_map {β} {f : α → β} (hf : injective f) (m : outer_measure α) : comap f (map f m) = m := ext $ λ s, by rw [comap_apply, map_apply, hf.preimage_image] @[simp] theorem top_apply {s : set α} (h : s.nonempty) : (⊤ : outer_measure α) s = ∞ := let ⟨a, as⟩ := h in top_unique $ le_trans (by simp [smul_dirac_apply, as]) (le_bsupr (∞ • dirac a) trivial) theorem top_apply' (s : set α) : (⊤ : outer_measure α) s = ⨅ (h : s = ∅), 0 := s.eq_empty_or_nonempty.elim (λ h, by simp [h]) (λ h, by simp [h, h.ne_empty]) @[simp] theorem comap_top (f : α → β) : comap f ⊤ = ⊤ := ext_nonempty $ λ s hs, by rw [comap_apply, top_apply hs, top_apply (hs.image _)] theorem map_top (f : α → β) : map f ⊤ = restrict (range f) ⊤ := ext $ λ s, by rw [map_apply, restrict_apply, ← image_preimage_eq_inter_range, top_apply', top_apply', set.image_eq_empty] theorem map_top_of_surjective (f : α → β) (hf : surjective f) : map f ⊤ = ⊤ := by rw [map_top, hf.range_eq, restrict_univ] end basic section of_function set_option eqn_compiler.zeta true variables {α : Type*} (m : set α → ℝ≥0∞) (m_empty : m ∅ = 0) include m_empty /-- Given any function `m` assigning measures to sets satisying `m ∅ = 0`, there is a unique maximal outer measure `μ` satisfying `μ s ≤ m s` for all `s : set α`. -/ protected def of_function : outer_measure α := let μ := λs, ⨅{f : ℕ → set α} (h : s ⊆ ⋃i, f i), ∑'i, m (f i) in { measure_of := μ, empty := le_antisymm (infi_le_of_le (λ_, ∅) $ infi_le_of_le (empty_subset _) $ by simp [m_empty]) (zero_le _), mono := assume s₁ s₂ hs, infi_le_infi $ assume f, infi_le_infi2 $ assume hb, ⟨subset.trans hs hb, le_refl _⟩, Union_nat := assume s, ennreal.le_of_forall_pos_le_add $ begin assume ε hε (hb : ∑'i, μ (s i) < ∞), rcases ennreal.exists_pos_sum_of_encodable (ennreal.coe_lt_coe.2 hε) ℕ with ⟨ε', hε', hl⟩, refine le_trans _ (add_le_add_left (le_of_lt hl) _), rw ← ennreal.tsum_add, choose f hf using show ∀i, ∃f:ℕ → set α, s i ⊆ (⋃i, f i) ∧ ∑'i, m (f i) < μ (s i) + ε' i, { intro, have : μ (s i) < μ (s i) + ε' i := ennreal.lt_add_right (lt_of_le_of_lt (by apply ennreal.le_tsum) hb) (by simpa using hε' i), simpa [μ, infi_lt_iff] }, refine le_trans _ (ennreal.tsum_le_tsum $ λ i, le_of_lt (hf i).2), rw [← ennreal.tsum_prod, ← equiv.nat_prod_nat_equiv_nat.symm.tsum_eq], swap, {apply_instance}, refine infi_le_of_le _ (infi_le _ _), exact Union_subset (λ i, subset.trans (hf i).1 $ Union_subset $ λ j, subset.trans (by simp) $ subset_Union _ $ equiv.nat_prod_nat_equiv_nat (i, j)), end } lemma of_function_apply (s : set α) : outer_measure.of_function m m_empty s = (⨅ (t : ℕ → set α) (h : s ⊆ Union t), ∑' n, m (t n)) := rfl variables {m m_empty} theorem of_function_le (s : set α) : outer_measure.of_function m m_empty s ≤ m s := let f : ℕ → set α := λi, nat.cases_on i s (λ _, ∅) in infi_le_of_le f $ infi_le_of_le (subset_Union f 0) $ le_of_eq $ tsum_eq_single 0 $ by rintro (_|i); simp [f, m_empty] theorem of_function_eq (s : set α) (m_mono : ∀ ⦃t : set α⦄, s ⊆ t → m s ≤ m t) (m_subadd : ∀ (s : ℕ → set α), m (⋃i, s i) ≤ ∑'i, m (s i)) : outer_measure.of_function m m_empty s = m s := le_antisymm (of_function_le s) $ le_infi $ λ f, le_infi $ λ hf, le_trans (m_mono hf) (m_subadd f) theorem le_of_function {μ : outer_measure α} : μ ≤ outer_measure.of_function m m_empty ↔ ∀ s, μ s ≤ m s := ⟨λ H s, le_trans (H s) (of_function_le s), λ H s, le_infi $ λ f, le_infi $ λ hs, le_trans (μ.mono hs) $ le_trans (μ.Union f) $ ennreal.tsum_le_tsum $ λ i, H _⟩ lemma is_greatest_of_function : is_greatest {μ : outer_measure α | ∀ s, μ s ≤ m s} (outer_measure.of_function m m_empty) := ⟨λ s, of_function_le _, λ μ, le_of_function.2⟩ lemma of_function_eq_Sup : outer_measure.of_function m m_empty = Sup {μ | ∀ s, μ s ≤ m s} := (@is_greatest_of_function α m m_empty).is_lub.Sup_eq.symm /-- If `m u = ∞` for any set `u` that has nonempty intersection both with `s` and `t`, then `μ (s ∪ t) = μ s + μ t`, where `μ = measure_theory.outer_measure.of_function m m_empty`. E.g., if `α` is an (e)metric space and `m u = ∞` on any set of diameter `≥ r`, then this lemma implies that `μ (s ∪ t) = μ s + μ t` on any two sets such that `r ≤ edist x y` for all `x ∈ s` and `y ∈ t`. -/ lemma of_function_union_of_top_of_nonempty_inter {s t : set α} (h : ∀ u, (s ∩ u).nonempty → (t ∩ u).nonempty → m u = ∞) : outer_measure.of_function m m_empty (s ∪ t) = outer_measure.of_function m m_empty s + outer_measure.of_function m m_empty t := begin refine le_antisymm (outer_measure.union _ _ _) (le_infi $ λ f, le_infi $ λ hf, _), set μ := outer_measure.of_function m m_empty, rcases em (∃ i, (s ∩ f i).nonempty ∧ (t ∩ f i).nonempty) with ⟨i, hs, ht⟩|he, { calc μ s + μ t ≤ ∞ : le_top ... = m (f i) : (h (f i) hs ht).symm ... ≤ ∑' i, m (f i) : ennreal.le_tsum i }, set I := λ s, {i : ℕ | (s ∩ f i).nonempty}, have hd : disjoint (I s) (I t), from λ i hi, he ⟨i, hi⟩, have hI : ∀ u ⊆ s ∪ t, μ u ≤ ∑' i : I u, μ (f i), from λ u hu, calc μ u ≤ μ (⋃ i : I u, f i) : μ.mono (λ x hx, let ⟨i, hi⟩ := mem_Union.1 (hf (hu hx)) in mem_Union.2 ⟨⟨i, ⟨x, hx, hi⟩⟩, hi⟩) ... ≤ ∑' i : I u, μ (f i) : μ.Union _, calc μ s + μ t ≤ (∑' i : I s, μ (f i)) + (∑' i : I t, μ (f i)) : add_le_add (hI _ $ subset_union_left _ _) (hI _ $ subset_union_right _ _) ... = ∑' i : I s ∪ I t, μ (f i) : (@tsum_union_disjoint _ _ _ _ _ (λ i, μ (f i)) _ _ _ hd ennreal.summable ennreal.summable).symm ... ≤ ∑' i, μ (f i) : tsum_le_tsum_of_inj coe subtype.coe_injective (λ _ _, zero_le _) (λ _, le_rfl) ennreal.summable ennreal.summable ... ≤ ∑' i, m (f i) : ennreal.tsum_le_tsum (λ i, of_function_le _) end lemma comap_of_function {β} (f : β → α) (h : monotone m ∨ surjective f) : comap f (outer_measure.of_function m m_empty) = outer_measure.of_function (λ s, m (f '' s)) (by rwa set.image_empty) := begin refine le_antisymm (le_of_function.2 $ λ s, _) (λ s, _), { rw comap_apply, apply of_function_le }, { rw [comap_apply, of_function_apply, of_function_apply], refine infi_le_infi2 (λ t, ⟨λ k, f ⁻¹' (t k), _⟩), refine infi_le_infi2 (λ ht, _), rw [set.image_subset_iff, preimage_Union] at ht, refine ⟨ht, ennreal.tsum_le_tsum $ λ n, _⟩, cases h, exacts [h (image_preimage_subset _ _), (congr_arg m (h.image_preimage (t n))).le] } end lemma map_of_function_le {β} (f : α → β) : map f (outer_measure.of_function m m_empty) ≤ outer_measure.of_function (λ s, m (f ⁻¹' s)) m_empty := le_of_function.2 $ λ s, by { rw map_apply, apply of_function_le } lemma map_of_function {β} {f : α → β} (hf : injective f) : map f (outer_measure.of_function m m_empty) = outer_measure.of_function (λ s, m (f ⁻¹' s)) m_empty := begin refine (map_of_function_le _).antisymm (λ s, _), simp only [of_function_apply, map_apply, le_infi_iff], intros t ht, refine infi_le_of_le (λ n, (range f)ᶜ ∪ f '' (t n)) (infi_le_of_le _ _), { rw [← union_Union, ← inter_subset, ← image_preimage_eq_inter_range, ← image_Union], exact image_subset _ ht }, { refine ennreal.tsum_le_tsum (λ n, le_of_eq _), simp [hf.preimage_image] } end lemma restrict_of_function (s : set α) (hm : monotone m) : restrict s (outer_measure.of_function m m_empty) = outer_measure.of_function (λ t, m (t ∩ s)) (by rwa set.empty_inter) := by simp only [restrict, linear_map.comp_apply, comap_of_function _ (or.inl hm), map_of_function subtype.coe_injective, subtype.image_preimage_coe] lemma smul_of_function {c : ℝ≥0∞} (hc : c ≠ ∞) : c • outer_measure.of_function m m_empty = outer_measure.of_function (c • m) (by simp [m_empty]) := begin ext1 s, haveI : nonempty {t : ℕ → set α // s ⊆ ⋃ i, t i} := ⟨⟨λ _, s, subset_Union (λ _, s) 0⟩⟩, simp only [smul_apply, of_function_apply, ennreal.tsum_mul_left, pi.smul_apply, smul_eq_mul, infi_subtype', ennreal.infi_mul_left (λ h, (hc h).elim)], end end of_function section bounded_by variables {α : Type*} (m : set α → ℝ≥0∞) /-- Given any function `m` assigning measures to sets, there is a unique maximal outer measure `μ` satisfying `μ s ≤ m s` for all `s : set α`. This is the same as `outer_measure.of_function`, except that it doesn't require `m ∅ = 0`. -/ def bounded_by : outer_measure α := outer_measure.of_function (λ s, ⨆ (h : s.nonempty), m s) (by simp [empty_not_nonempty]) variables {m} theorem bounded_by_le (s : set α) : bounded_by m s ≤ m s := (of_function_le _).trans supr_const_le theorem bounded_by_eq_of_function (m_empty : m ∅ = 0) (s : set α) : bounded_by m s = outer_measure.of_function m m_empty s := begin have : (λ s : set α, ⨆ (h : s.nonempty), m s) = m, { ext1 t, cases t.eq_empty_or_nonempty with h h; simp [h, empty_not_nonempty, m_empty] }, simp [bounded_by, this] end theorem bounded_by_apply (s : set α) : bounded_by m s = ⨅ (t : ℕ → set α) (h : s ⊆ Union t), ∑' n, ⨆ (h : (t n).nonempty), m (t n) := by simp [bounded_by, of_function_apply] theorem bounded_by_eq (s : set α) (m_empty : m ∅ = 0) (m_mono : ∀ ⦃t : set α⦄, s ⊆ t → m s ≤ m t) (m_subadd : ∀ (s : ℕ → set α), m (⋃i, s i) ≤ ∑'i, m (s i)) : bounded_by m s = m s := by rw [bounded_by_eq_of_function m_empty, of_function_eq s m_mono m_subadd] theorem le_bounded_by {μ : outer_measure α} : μ ≤ bounded_by m ↔ ∀ s, μ s ≤ m s := begin rw [bounded_by, le_of_function, forall_congr], intro s, cases s.eq_empty_or_nonempty with h h; simp [h, empty_not_nonempty] end theorem le_bounded_by' {μ : outer_measure α} : μ ≤ bounded_by m ↔ ∀ s : set α, s.nonempty → μ s ≤ m s := by { rw [le_bounded_by, forall_congr], intro s, cases s.eq_empty_or_nonempty with h h; simp [h] } lemma smul_bounded_by {c : ℝ≥0∞} (hc : c ≠ ∞) : c • bounded_by m = bounded_by (c • m) := begin simp only [bounded_by, smul_of_function hc], congr' 1 with s : 1, rcases s.eq_empty_or_nonempty with rfl|hs; simp * end lemma comap_bounded_by {β} (f : β → α) (h : monotone (λ s : {s : set α // s.nonempty}, m s) ∨ surjective f) : comap f (bounded_by m) = bounded_by (λ s, m (f '' s)) := begin refine (comap_of_function _ _).trans _, { refine h.imp (λ H s t hst, supr_le $ λ hs, _) id, have ht : t.nonempty := hs.mono hst, exact (@H ⟨s, hs⟩ ⟨t, ht⟩ hst).trans (le_supr (λ h : t.nonempty, m t) ht) }, { dunfold bounded_by, congr' with s : 1, rw nonempty_image_iff } end /-- If `m u = ∞` for any set `u` that has nonempty intersection both with `s` and `t`, then `μ (s ∪ t) = μ s + μ t`, where `μ = measure_theory.outer_measure.bounded_by m`. E.g., if `α` is an (e)metric space and `m u = ∞` on any set of diameter `≥ r`, then this lemma implies that `μ (s ∪ t) = μ s + μ t` on any two sets such that `r ≤ edist x y` for all `x ∈ s` and `y ∈ t`. -/ lemma bounded_by_union_of_top_of_nonempty_inter {s t : set α} (h : ∀ u, (s ∩ u).nonempty → (t ∩ u).nonempty → m u = ∞) : bounded_by m (s ∪ t) = bounded_by m s + bounded_by m t := of_function_union_of_top_of_nonempty_inter $ λ u hs ht, top_unique $ (h u hs ht).ge.trans $ le_supr (λ h, m u) (hs.mono $ inter_subset_right s u) end bounded_by section caratheodory_measurable universe u parameters {α : Type u} (m : outer_measure α) include m local attribute [simp] set.inter_comm set.inter_left_comm set.inter_assoc variables {s s₁ s₂ : set α} /-- A set `s` is Carathéodory-measurable for an outer measure `m` if for all sets `t` we have `m t = m (t ∩ s) + m (t \ s)`. -/ def is_caratheodory (s : set α) : Prop := ∀t, m t = m (t ∩ s) + m (t \ s) lemma is_caratheodory_iff_le' {s : set α} : is_caratheodory s ↔ ∀t, m (t ∩ s) + m (t \ s) ≤ m t := forall_congr $ λ t, le_antisymm_iff.trans $ and_iff_right $ le_inter_add_diff _ @[simp] lemma is_caratheodory_empty : is_caratheodory ∅ := by simp [is_caratheodory, m.empty, diff_empty] lemma is_caratheodory_compl : is_caratheodory s₁ → is_caratheodory s₁ᶜ := by simp [is_caratheodory, diff_eq, add_comm] @[simp] lemma is_caratheodory_compl_iff : is_caratheodory sᶜ ↔ is_caratheodory s := ⟨λ h, by simpa using is_caratheodory_compl m h, is_caratheodory_compl⟩ lemma is_caratheodory_union (h₁ : is_caratheodory s₁) (h₂ : is_caratheodory s₂) : is_caratheodory (s₁ ∪ s₂) := λ t, begin rw [h₁ t, h₂ (t ∩ s₁), h₂ (t \ s₁), h₁ (t ∩ (s₁ ∪ s₂)), inter_diff_assoc _ _ s₁, set.inter_assoc _ _ s₁, inter_eq_self_of_subset_right (set.subset_union_left _ _), union_diff_left, h₂ (t ∩ s₁)], simp [diff_eq, add_assoc] end lemma measure_inter_union (h : s₁ ∩ s₂ ⊆ ∅) (h₁ : is_caratheodory s₁) {t : set α} : m (t ∩ (s₁ ∪ s₂)) = m (t ∩ s₁) + m (t ∩ s₂) := by rw [h₁, set.inter_assoc, set.union_inter_cancel_left, inter_diff_assoc, union_diff_cancel_left h] lemma is_caratheodory_Union_lt {s : ℕ → set α} : ∀{n:ℕ}, (∀i<n, is_caratheodory (s i)) → is_caratheodory (⋃i<n, s i) | 0 h := by simp [nat.not_lt_zero] | (n + 1) h := by rw bUnion_lt_succ; exact is_caratheodory_union m (h n (le_refl (n + 1))) (is_caratheodory_Union_lt $ assume i hi, h i $ lt_of_lt_of_le hi $ nat.le_succ _) lemma is_caratheodory_inter (h₁ : is_caratheodory s₁) (h₂ : is_caratheodory s₂) : is_caratheodory (s₁ ∩ s₂) := by { rw [← is_caratheodory_compl_iff, compl_inter], exact is_caratheodory_union _ (is_caratheodory_compl _ h₁) (is_caratheodory_compl _ h₂) } lemma is_caratheodory_sum {s : ℕ → set α} (h : ∀i, is_caratheodory (s i)) (hd : pairwise (disjoint on s)) {t : set α} : ∀ {n}, ∑ i in finset.range n, m (t ∩ s i) = m (t ∩ ⋃i<n, s i) | 0 := by simp [nat.not_lt_zero, m.empty] | (nat.succ n) := begin simp [bUnion_lt_succ, range_succ], rw [measure_inter_union m _ (h n), is_caratheodory_sum], intro a, simpa [range_succ] using λ (h₁ : a ∈ s n) i (hi : i < n) h₂, hd _ _ (ne_of_gt hi) ⟨h₁, h₂⟩ end lemma is_caratheodory_Union_nat {s : ℕ → set α} (h : ∀i, is_caratheodory (s i)) (hd : pairwise (disjoint on s)) : is_caratheodory (⋃i, s i) := is_caratheodory_iff_le'.2 $ λ t, begin have hp : m (t ∩ ⋃i, s i) ≤ (⨆n, m (t ∩ ⋃i<n, s i)), { convert m.Union (λ i, t ∩ s i), { rw inter_Union }, { simp [ennreal.tsum_eq_supr_nat, is_caratheodory_sum m h hd] } }, refine le_trans (add_le_add_right hp _) _, rw ennreal.supr_add, refine supr_le (λ n, le_trans (add_le_add_left _ _) (ge_of_eq (is_caratheodory_Union_lt m (λ i _, h i) _))), refine m.mono (diff_subset_diff_right _), exact bUnion_subset (λ i _, subset_Union _ i), end lemma f_Union {s : ℕ → set α} (h : ∀i, is_caratheodory (s i)) (hd : pairwise (disjoint on s)) : m (⋃i, s i) = ∑'i, m (s i) := begin refine le_antisymm (m.Union_nat s) _, rw ennreal.tsum_eq_supr_nat, refine supr_le (λ n, _), have := @is_caratheodory_sum _ m _ h hd univ n, simp at this, simp [this], exact m.mono (bUnion_subset (λ i _, subset_Union _ i)), end /-- The Carathéodory-measurable sets for an outer measure `m` form a Dynkin system. -/ def caratheodory_dynkin : measurable_space.dynkin_system α := { has := is_caratheodory, has_empty := is_caratheodory_empty, has_compl := assume s, is_caratheodory_compl, has_Union_nat := assume f hf hn, is_caratheodory_Union_nat hn hf } /-- Given an outer measure `μ`, the Carathéodory-measurable space is defined such that `s` is measurable if `∀t, μ t = μ (t ∩ s) + μ (t \ s)`. -/ protected def caratheodory : measurable_space α := caratheodory_dynkin.to_measurable_space $ assume s₁ s₂, is_caratheodory_inter lemma is_caratheodory_iff {s : set α} : caratheodory.measurable_set' s ↔ ∀t, m t = m (t ∩ s) + m (t \ s) := iff.rfl lemma is_caratheodory_iff_le {s : set α} : caratheodory.measurable_set' s ↔ ∀t, m (t ∩ s) + m (t \ s) ≤ m t := is_caratheodory_iff_le' protected lemma Union_eq_of_caratheodory {s : ℕ → set α} (h : ∀i, caratheodory.measurable_set' (s i)) (hd : pairwise (disjoint on s)) : m (⋃i, s i) = ∑'i, m (s i) := f_Union h hd end caratheodory_measurable variables {α : Type*} lemma of_function_caratheodory {m : set α → ℝ≥0∞} {s : set α} {h₀ : m ∅ = 0} (hs : ∀t, m (t ∩ s) + m (t \ s) ≤ m t) : (outer_measure.of_function m h₀).caratheodory.measurable_set' s := begin apply (is_caratheodory_iff_le _).mpr, refine λ t, le_infi (λ f, le_infi $ λ hf, _), refine le_trans (add_le_add (infi_le_of_le (λi, f i ∩ s) $ infi_le _ _) (infi_le_of_le (λi, f i \ s) $ infi_le _ _)) _, { rw ← Union_inter, exact inter_subset_inter_left _ hf }, { rw ← Union_diff, exact diff_subset_diff_left hf }, { rw ← ennreal.tsum_add, exact ennreal.tsum_le_tsum (λ i, hs _) } end lemma bounded_by_caratheodory {m : set α → ℝ≥0∞} {s : set α} (hs : ∀t, m (t ∩ s) + m (t \ s) ≤ m t) : (bounded_by m).caratheodory.measurable_set' s := begin apply of_function_caratheodory, intro t, cases t.eq_empty_or_nonempty with h h, { simp [h, empty_not_nonempty] }, { convert le_trans _ (hs t), { simp [h] }, exact add_le_add supr_const_le supr_const_le } end @[simp] theorem zero_caratheodory : (0 : outer_measure α).caratheodory = ⊤ := top_unique $ λ s _ t, (add_zero _).symm theorem top_caratheodory : (⊤ : outer_measure α).caratheodory = ⊤ := top_unique $ assume s hs, (is_caratheodory_iff_le _).2 $ assume t, t.eq_empty_or_nonempty.elim (λ ht, by simp [ht]) (λ ht, by simp only [ht, top_apply, le_top]) theorem le_add_caratheodory (m₁ m₂ : outer_measure α) : m₁.caratheodory ⊓ m₂.caratheodory ≤ (m₁ + m₂ : outer_measure α).caratheodory := λ s ⟨hs₁, hs₂⟩ t, by simp [hs₁ t, hs₂ t, add_left_comm, add_assoc] theorem le_sum_caratheodory {ι} (m : ι → outer_measure α) : (⨅ i, (m i).caratheodory) ≤ (sum m).caratheodory := λ s h t, by simp [λ i, measurable_space.measurable_set_infi.1 h i t, ennreal.tsum_add] theorem le_smul_caratheodory (a : ℝ≥0∞) (m : outer_measure α) : m.caratheodory ≤ (a • m).caratheodory := λ s h t, by simp [h t, mul_add] @[simp] theorem dirac_caratheodory (a : α) : (dirac a).caratheodory = ⊤ := top_unique $ λ s _ t, begin by_cases ht : a ∈ t, swap, by simp [ht], by_cases hs : a ∈ s; simp* end section Inf_gen /-- Given a set of outer measures, we define a new function that on a set `s` is defined to be the infimum of `μ(s)` for the outer measures `μ` in the collection. We ensure that this function is defined to be `0` on `∅`, even if the collection of outer measures is empty. The outer measure generated by this function is the infimum of the given outer measures. -/ def Inf_gen (m : set (outer_measure α)) (s : set α) : ℝ≥0∞ := ⨅ (μ : outer_measure α) (h : μ ∈ m), μ s lemma Inf_gen_def (m : set (outer_measure α)) (t : set α) : Inf_gen m t = (⨅ (μ : outer_measure α) (h : μ ∈ m), μ t) := rfl lemma Inf_eq_bounded_by_Inf_gen (m : set (outer_measure α)) : Inf m = outer_measure.bounded_by (Inf_gen m) := begin refine le_antisymm _ _, { refine (le_bounded_by.2 $ λ s, _), refine le_binfi _, intros μ hμ, refine (show Inf m ≤ μ, from Inf_le hμ) s }, { refine le_Inf _, intros μ hμ t, refine le_trans (bounded_by_le t) (binfi_le μ hμ) } end lemma supr_Inf_gen_nonempty {m : set (outer_measure α)} (h : m.nonempty) (t : set α) : (⨆ (h : t.nonempty), Inf_gen m t) = (⨅ (μ : outer_measure α) (h : μ ∈ m), μ t) := begin rcases t.eq_empty_or_nonempty with rfl|ht, { rcases h with ⟨μ, hμ⟩, rw [eq_false_intro empty_not_nonempty, supr_false, eq_comm], simp_rw [empty'], apply bot_unique, refine infi_le_of_le μ (infi_le _ hμ) }, { simp [ht, Inf_gen_def] } end /-- The value of the Infimum of a nonempty set of outer measures on a set is not simply the minimum value of a measure on that set: it is the infimum sum of measures of countable set of sets that covers that set, where a different measure can be used for each set in the cover. -/ lemma Inf_apply {m : set (outer_measure α)} {s : set α} (h : m.nonempty) : Inf m s = ⨅ (t : ℕ → set α) (h2 : s ⊆ Union t), ∑' n, ⨅ (μ : outer_measure α) (h3 : μ ∈ m), μ (t n) := by simp_rw [Inf_eq_bounded_by_Inf_gen, bounded_by_apply, supr_Inf_gen_nonempty h] /-- The value of the Infimum of a set of outer measures on a nonempty set is not simply the minimum value of a measure on that set: it is the infimum sum of measures of countable set of sets that covers that set, where a different measure can be used for each set in the cover. -/ lemma Inf_apply' {m : set (outer_measure α)} {s : set α} (h : s.nonempty) : Inf m s = ⨅ (t : ℕ → set α) (h2 : s ⊆ Union t), ∑' n, ⨅ (μ : outer_measure α) (h3 : μ ∈ m), μ (t n) := m.eq_empty_or_nonempty.elim (λ hm, by simp [hm, h]) Inf_apply /-- The value of the Infimum of a nonempty family of outer measures on a set is not simply the minimum value of a measure on that set: it is the infimum sum of measures of countable set of sets that covers that set, where a different measure can be used for each set in the cover. -/ lemma infi_apply {ι} [nonempty ι] (m : ι → outer_measure α) (s : set α) : (⨅ i, m i) s = ⨅ (t : ℕ → set α) (h2 : s ⊆ Union t), ∑' n, ⨅ i, m i (t n) := by { rw [infi, Inf_apply (range_nonempty m)], simp only [infi_range] } /-- The value of the Infimum of a family of outer measures on a nonempty set is not simply the minimum value of a measure on that set: it is the infimum sum of measures of countable set of sets that covers that set, where a different measure can be used for each set in the cover. -/ lemma infi_apply' {ι} (m : ι → outer_measure α) {s : set α} (hs : s.nonempty) : (⨅ i, m i) s = ⨅ (t : ℕ → set α) (h2 : s ⊆ Union t), ∑' n, ⨅ i, m i (t n) := by { rw [infi, Inf_apply' hs], simp only [infi_range] } /-- The value of the Infimum of a nonempty family of outer measures on a set is not simply the minimum value of a measure on that set: it is the infimum sum of measures of countable set of sets that covers that set, where a different measure can be used for each set in the cover. -/ lemma binfi_apply {ι} {I : set ι} (hI : I.nonempty) (m : ι → outer_measure α) (s : set α) : (⨅ i ∈ I, m i) s = ⨅ (t : ℕ → set α) (h2 : s ⊆ Union t), ∑' n, ⨅ i ∈ I, m i (t n) := by { haveI := hI.to_subtype, simp only [← infi_subtype'', infi_apply] } /-- The value of the Infimum of a nonempty family of outer measures on a set is not simply the minimum value of a measure on that set: it is the infimum sum of measures of countable set of sets that covers that set, where a different measure can be used for each set in the cover. -/ lemma binfi_apply' {ι} (I : set ι) (m : ι → outer_measure α) {s : set α} (hs : s.nonempty) : (⨅ i ∈ I, m i) s = ⨅ (t : ℕ → set α) (h2 : s ⊆ Union t), ∑' n, ⨅ i ∈ I, m i (t n) := by { simp only [← infi_subtype'', infi_apply' _ hs] } lemma map_infi_le {ι β} (f : α → β) (m : ι → outer_measure α) : map f (⨅ i, m i) ≤ ⨅ i, map f (m i) := (map_mono f).map_infi_le lemma comap_infi {ι β} (f : α → β) (m : ι → outer_measure β) : comap f (⨅ i, m i) = ⨅ i, comap f (m i) := begin refine ext_nonempty (λ s hs, _), refine ((comap_mono f).map_infi_le s).antisymm _, simp only [comap_apply, infi_apply' _ hs, infi_apply' _ (hs.image _), le_infi_iff, set.image_subset_iff, preimage_Union], refine λ t ht, infi_le_of_le _ (infi_le_of_le ht $ ennreal.tsum_le_tsum $ λ k, _), exact infi_le_infi (λ i, (m i).mono (image_preimage_subset _ _)) end lemma map_infi {ι β} {f : α → β} (hf : injective f) (m : ι → outer_measure α) : map f (⨅ i, m i) = restrict (range f) (⨅ i, map f (m i)) := begin refine eq.trans _ (map_comap _ _), simp only [comap_infi, comap_map hf] end lemma map_infi_comap {ι β} [nonempty ι] {f : α → β} (m : ι → outer_measure β) : map f (⨅ i, comap f (m i)) = ⨅ i, map f (comap f (m i)) := begin refine (map_infi_le _ _).antisymm (λ s, _), simp only [map_apply, comap_apply, infi_apply, le_infi_iff], refine λ t ht, infi_le_of_le (λ n, f '' (t n) ∪ (range f)ᶜ) (infi_le_of_le _ _), { rw [← Union_union, set.union_comm, ← inter_subset, ← image_Union, ← image_preimage_eq_inter_range], exact image_subset _ ht }, { refine ennreal.tsum_le_tsum (λ n, infi_le_infi (λ i, (m i).mono _)), simp } end lemma map_binfi_comap {ι β} {I : set ι} (hI : I.nonempty) {f : α → β} (m : ι → outer_measure β) : map f (⨅ i ∈ I, comap f (m i)) = ⨅ i ∈ I, map f (comap f (m i)) := by { haveI := hI.to_subtype, rw [← infi_subtype'', ← infi_subtype''], exact map_infi_comap _ } lemma restrict_infi_restrict {ι} (s : set α) (m : ι → outer_measure α) : restrict s (⨅ i, restrict s (m i)) = restrict s (⨅ i, m i) := calc restrict s (⨅ i, restrict s (m i)) = restrict (range (coe : s → α)) (⨅ i, restrict s (m i)) : by rw [subtype.range_coe] ... = map (coe : s → α) (⨅ i, comap coe (m i)) : (map_infi subtype.coe_injective _).symm ... = restrict s (⨅ i, m i) : congr_arg (map coe) (comap_infi _ _).symm lemma restrict_infi {ι} [nonempty ι] (s : set α) (m : ι → outer_measure α) : restrict s (⨅ i, m i) = ⨅ i, restrict s (m i) := (congr_arg (map coe) (comap_infi _ _)).trans (map_infi_comap _) lemma restrict_binfi {ι} {I : set ι} (hI : I.nonempty) (s : set α) (m : ι → outer_measure α) : restrict s (⨅ i ∈ I, m i) = ⨅ i ∈ I, restrict s (m i) := by { haveI := hI.to_subtype, rw [← infi_subtype'', ← infi_subtype''], exact restrict_infi _ _ } /-- This proves that Inf and restrict commute for outer measures, so long as the set of outer measures is nonempty. -/ lemma restrict_Inf_eq_Inf_restrict (m : set (outer_measure α)) {s : set α} (hm : m.nonempty) : restrict s (Inf m) = Inf ((restrict s) '' m) := by simp only [Inf_eq_infi, restrict_binfi, hm, infi_image] end Inf_gen end outer_measure open outer_measure /-! ### Induced Outer Measure We can extend a function defined on a subset of `set α` to an outer measure. The underlying function is called `extend`, and the measure it induces is called `induced_outer_measure`. Some lemmas below are proven twice, once in the general case, and one where the function `m` is only defined on measurable sets (i.e. when `P = measurable_set`). In the latter cases, we can remove some hypotheses in the statement. The general version has the same name, but with a prime at the end. -/ section extend variables {α : Type*} {P : α → Prop} variables (m : Π (s : α), P s → ℝ≥0∞) /-- We can trivially extend a function defined on a subclass of objects (with codomain `ℝ≥0∞`) to all objects by defining it to be `∞` on the objects not in the class. -/ def extend (s : α) : ℝ≥0∞ := ⨅ h : P s, m s h lemma extend_eq {s : α} (h : P s) : extend m s = m s h := by simp [extend, h] lemma extend_eq_top {s : α} (h : ¬P s) : extend m s = ∞ := by simp [extend, h] lemma le_extend {s : α} (h : P s) : m s h ≤ extend m s := by { simp only [extend, le_infi_iff], intro, refl' } -- TODO: why this is a bad `congr` lemma? lemma extend_congr {β : Type*} {Pb : β → Prop} {mb : Π s : β, Pb s → ℝ≥0∞} {sa : α} {sb : β} (hP : P sa ↔ Pb sb) (hm : ∀ (ha : P sa) (hb : Pb sb), m sa ha = mb sb hb) : extend m sa = extend mb sb := infi_congr_Prop hP (λ h, hm _ _) end extend section extend_set variables {α : Type*} {P : set α → Prop} variables {m : Π (s : set α), P s → ℝ≥0∞} variables (P0 : P ∅) (m0 : m ∅ P0 = 0) variables (PU : ∀{{f : ℕ → set α}} (hm : ∀i, P (f i)), P (⋃i, f i)) variables (mU : ∀ {{f : ℕ → set α}} (hm : ∀i, P (f i)), pairwise (disjoint on f) → m (⋃i, f i) (PU hm) = ∑'i, m (f i) (hm i)) variables (msU : ∀ {{f : ℕ → set α}} (hm : ∀i, P (f i)), m (⋃i, f i) (PU hm) ≤ ∑'i, m (f i) (hm i)) variables (m_mono : ∀⦃s₁ s₂ : set α⦄ (hs₁ : P s₁) (hs₂ : P s₂), s₁ ⊆ s₂ → m s₁ hs₁ ≤ m s₂ hs₂) lemma extend_empty : extend m ∅ = 0 := (extend_eq _ P0).trans m0 lemma extend_Union_nat {f : ℕ → set α} (hm : ∀i, P (f i)) (mU : m (⋃i, f i) (PU hm) = ∑'i, m (f i) (hm i)) : extend m (⋃i, f i) = ∑'i, extend m (f i) := (extend_eq _ _).trans $ mU.trans $ by { congr' with i, rw extend_eq } section subadditive include PU msU lemma extend_Union_le_tsum_nat' (s : ℕ → set α) : extend m (⋃i, s i) ≤ ∑'i, extend m (s i) := begin by_cases h : ∀i, P (s i), { rw [extend_eq _ (PU h), congr_arg tsum _], { apply msU h }, funext i, apply extend_eq _ (h i) }, { cases not_forall.1 h with i hi, exact le_trans (le_infi $ λ h, hi.elim h) (ennreal.le_tsum i) } end end subadditive section mono include m_mono lemma extend_mono' ⦃s₁ s₂ : set α⦄ (h₁ : P s₁) (hs : s₁ ⊆ s₂) : extend m s₁ ≤ extend m s₂ := by { refine le_infi _, intro h₂, rw [extend_eq m h₁], exact m_mono h₁ h₂ hs } end mono section unions include P0 m0 PU mU lemma extend_Union {β} [encodable β] {f : β → set α} (hd : pairwise (disjoint on f)) (hm : ∀i, P (f i)) : extend m (⋃i, f i) = ∑'i, extend m (f i) := begin rw [← encodable.Union_decode₂, ← tsum_Union_decode₂], { exact extend_Union_nat PU (λ n, encodable.Union_decode₂_cases P0 hm) (mU _ (encodable.Union_decode₂_disjoint_on hd)) }, { exact extend_empty P0 m0 } end lemma extend_union {s₁ s₂ : set α} (hd : disjoint s₁ s₂) (h₁ : P s₁) (h₂ : P s₂) : extend m (s₁ ∪ s₂) = extend m s₁ + extend m s₂ := begin rw [union_eq_Union, extend_Union P0 m0 PU mU (pairwise_disjoint_on_bool.2 hd) (bool.forall_bool.2 ⟨h₂, h₁⟩), tsum_fintype], simp end end unions variable (m) /-- Given an arbitrary function on a subset of sets, we can define the outer measure corresponding to it (this is the unique maximal outer measure that is at most `m` on the domain of `m`). -/ def induced_outer_measure : outer_measure α := outer_measure.of_function (extend m) (extend_empty P0 m0) variables {m P0 m0} lemma le_induced_outer_measure {μ : outer_measure α} : μ ≤ induced_outer_measure m P0 m0 ↔ ∀ s (hs : P s), μ s ≤ m s hs := le_of_function.trans $ forall_congr $ λ s, le_infi_iff /-- If `P u` is `false` for any set `u` that has nonempty intersection both with `s` and `t`, then `μ (s ∪ t) = μ s + μ t`, where `μ = induced_outer_measure m P0 m0`. E.g., if `α` is an (e)metric space and `P u = diam u < r`, then this lemma implies that `μ (s ∪ t) = μ s + μ t` on any two sets such that `r ≤ edist x y` for all `x ∈ s` and `y ∈ t`. -/ lemma induced_outer_measure_union_of_false_of_nonempty_inter {s t : set α} (h : ∀ u, (s ∩ u).nonempty → (t ∩ u).nonempty → ¬P u) : induced_outer_measure m P0 m0 (s ∪ t) = induced_outer_measure m P0 m0 s + induced_outer_measure m P0 m0 t := of_function_union_of_top_of_nonempty_inter $ λ u hsu htu, infi_of_empty' $ h u hsu htu include msU m_mono lemma induced_outer_measure_eq_extend' {s : set α} (hs : P s) : induced_outer_measure m P0 m0 s = extend m s := of_function_eq s (λ t, extend_mono' m_mono hs) (extend_Union_le_tsum_nat' PU msU) lemma induced_outer_measure_eq' {s : set α} (hs : P s) : induced_outer_measure m P0 m0 s = m s hs := (induced_outer_measure_eq_extend' PU msU m_mono hs).trans $ extend_eq _ _ lemma induced_outer_measure_eq_infi (s : set α) : induced_outer_measure m P0 m0 s = ⨅ (t : set α) (ht : P t) (h : s ⊆ t), m t ht := begin apply le_antisymm, { simp only [le_infi_iff], intros t ht, simp only [le_infi_iff], intro hs, refine le_trans (mono' _ hs) _, exact le_of_eq (induced_outer_measure_eq' _ msU m_mono _) }, { refine le_infi _, intro f, refine le_infi _, intro hf, refine le_trans _ (extend_Union_le_tsum_nat' _ msU _), refine le_infi _, intro h2f, refine infi_le_of_le _ (infi_le_of_le h2f $ infi_le _ hf) } end lemma induced_outer_measure_preimage (f : α ≃ α) (Pm : ∀ (s : set α), P (f ⁻¹' s) ↔ P s) (mm : ∀ (s : set α) (hs : P s), m (f ⁻¹' s) ((Pm _).mpr hs) = m s hs) {A : set α} : induced_outer_measure m P0 m0 (f ⁻¹' A) = induced_outer_measure m P0 m0 A := begin simp only [induced_outer_measure_eq_infi _ msU m_mono], symmetry, refine infi_congr (preimage f) f.injective.preimage_surjective _, intro s, refine infi_congr_Prop (Pm s) _, intro hs, refine infi_congr_Prop f.surjective.preimage_subset_preimage_iff _, intro h2s, exact mm s hs end lemma induced_outer_measure_exists_set {s : set α} (hs : induced_outer_measure m P0 m0 s < ∞) {ε : ℝ≥0} (hε : 0 < ε) : ∃ (t : set α) (ht : P t), s ⊆ t ∧ induced_outer_measure m P0 m0 t ≤ induced_outer_measure m P0 m0 s + ε := begin have := ennreal.lt_add_right hs (ennreal.zero_lt_coe_iff.2 hε), conv at this {to_lhs, rw induced_outer_measure_eq_infi _ msU m_mono }, simp only [infi_lt_iff] at this, rcases this with ⟨t, h1t, h2t, h3t⟩, exact ⟨t, h1t, h2t, le_trans (le_of_eq $ induced_outer_measure_eq' _ msU m_mono h1t) (le_of_lt h3t)⟩ end /-- To test whether `s` is Carathéodory-measurable we only need to check the sets `t` for which `P t` holds. See `of_function_caratheodory` for another way to show the Carathéodory-measurability of `s`. -/ lemma induced_outer_measure_caratheodory (s : set α) : (induced_outer_measure m P0 m0).caratheodory.measurable_set' s ↔ ∀ (t : set α), P t → induced_outer_measure m P0 m0 (t ∩ s) + induced_outer_measure m P0 m0 (t \ s) ≤ induced_outer_measure m P0 m0 t := begin rw is_caratheodory_iff_le, split, { intros h t ht, exact h t }, { intros h u, conv_rhs { rw induced_outer_measure_eq_infi _ msU m_mono }, refine le_infi _, intro t, refine le_infi _, intro ht, refine le_infi _, intro h2t, refine le_trans _ (le_trans (h t ht) $ le_of_eq $ induced_outer_measure_eq' _ msU m_mono ht), refine add_le_add (mono' _ $ set.inter_subset_inter_left _ h2t) (mono' _ $ diff_subset_diff_left h2t) } end end extend_set /-! If `P` is `measurable_set` for some measurable space, then we can remove some hypotheses of the above lemmas. -/ section measurable_space variables {α : Type*} [measurable_space α] variables {m : Π (s : set α), measurable_set s → ℝ≥0∞} variables (m0 : m ∅ measurable_set.empty = 0) variable (mU : ∀ {{f : ℕ → set α}} (hm : ∀i, measurable_set (f i)), pairwise (disjoint on f) → m (⋃i, f i) (measurable_set.Union hm) = ∑'i, m (f i) (hm i)) include m0 mU lemma extend_mono {s₁ s₂ : set α} (h₁ : measurable_set s₁) (hs : s₁ ⊆ s₂) : extend m s₁ ≤ extend m s₂ := begin refine le_infi _, intro h₂, have := extend_union measurable_set.empty m0 measurable_set.Union mU disjoint_diff h₁ (h₂.diff h₁), rw union_diff_cancel hs at this, rw ← extend_eq m, exact le_iff_exists_add.2 ⟨_, this⟩, end lemma extend_Union_le_tsum_nat : ∀ (s : ℕ → set α), extend m (⋃i, s i) ≤ ∑'i, extend m (s i) := begin refine extend_Union_le_tsum_nat' measurable_set.Union _, intros f h, simp [Union_disjointed.symm] {single_pass := tt}, rw [mU (measurable_set.disjointed h) (disjoint_disjointed _)], refine ennreal.tsum_le_tsum (λ i, _), rw [← extend_eq m, ← extend_eq m], exact extend_mono m0 mU (measurable_set.disjointed h _) (disjointed_le f _), end lemma induced_outer_measure_eq_extend {s : set α} (hs : measurable_set s) : induced_outer_measure m measurable_set.empty m0 s = extend m s := of_function_eq s (λ t, extend_mono m0 mU hs) (extend_Union_le_tsum_nat m0 mU) lemma induced_outer_measure_eq {s : set α} (hs : measurable_set s) : induced_outer_measure m measurable_set.empty m0 s = m s hs := (induced_outer_measure_eq_extend m0 mU hs).trans $ extend_eq _ _ end measurable_space namespace outer_measure variables {α : Type*} [measurable_space α] (m : outer_measure α) /-- Given an outer measure `m` we can forget its value on non-measurable sets, and then consider `m.trim`, the unique maximal outer measure less than that function. -/ def trim : outer_measure α := induced_outer_measure (λ s _, m s) measurable_set.empty m.empty theorem le_trim : m ≤ m.trim := le_of_function.mpr $ λ s, le_infi $ λ _, le_refl _ theorem trim_eq {s : set α} (hs : measurable_set s) : m.trim s = m s := induced_outer_measure_eq' measurable_set.Union (λ f hf, m.Union_nat f) (λ _ _ _ _ h, m.mono h) hs theorem trim_congr {m₁ m₂ : outer_measure α} (H : ∀ {s : set α}, measurable_set s → m₁ s = m₂ s) : m₁.trim = m₂.trim := by { unfold trim, congr, funext s hs, exact H hs } @[mono] theorem trim_mono : monotone (trim : outer_measure α → outer_measure α) := λ m₁ m₂ H s, binfi_le_binfi $ λ f hs, ennreal.tsum_le_tsum $ λ b, infi_le_infi $ λ hf, H _ theorem le_trim_iff {m₁ m₂ : outer_measure α} : m₁ ≤ m₂.trim ↔ ∀ s, measurable_set s → m₁ s ≤ m₂ s := le_of_function.trans $ forall_congr $ λ s, le_infi_iff theorem trim_le_trim_iff {m₁ m₂ : outer_measure α} : m₁.trim ≤ m₂.trim ↔ ∀ s, measurable_set s → m₁ s ≤ m₂ s := le_trim_iff.trans $ forall_congr $ λ s, forall_congr $ λ hs, by rw [trim_eq _ hs] theorem trim_eq_trim_iff {m₁ m₂ : outer_measure α} : m₁.trim = m₂.trim ↔ ∀ s, measurable_set s → m₁ s = m₂ s := by simp only [le_antisymm_iff, trim_le_trim_iff, forall_and_distrib] theorem trim_eq_infi (s : set α) : m.trim s = ⨅ t (st : s ⊆ t) (ht : measurable_set t), m t := by { simp only [infi_comm] {single_pass := tt}, exact induced_outer_measure_eq_infi measurable_set.Union (λ f _, m.Union_nat f) (λ _ _ _ _ h, m.mono h) s } theorem trim_eq_infi' (s : set α) : m.trim s = ⨅ t : {t // s ⊆ t ∧ measurable_set t}, m t := by simp [infi_subtype, infi_and, trim_eq_infi] theorem trim_trim (m : outer_measure α) : m.trim.trim = m.trim := trim_eq_trim_iff.2 $ λ s, m.trim_eq @[simp] theorem trim_zero : (0 : outer_measure α).trim = 0 := ext $ λ s, le_antisymm (le_trans ((trim 0).mono (subset_univ s)) $ le_of_eq $ trim_eq _ measurable_set.univ) (zero_le _) theorem trim_sum_ge {ι} (m : ι → outer_measure α) : sum (λ i, (m i).trim) ≤ (sum m).trim := λ s, by simp [trim_eq_infi]; exact λ t st ht, ennreal.tsum_le_tsum (λ i, infi_le_of_le t $ infi_le_of_le st $ infi_le _ ht) lemma exists_measurable_superset_eq_trim (m : outer_measure α) (s : set α) : ∃ t, s ⊆ t ∧ measurable_set t ∧ m t = m.trim s := begin simp only [trim_eq_infi], set ms := ⨅ (t : set α) (st : s ⊆ t) (ht : measurable_set t), m t, by_cases hs : ms = ∞, { simp only [hs], simp only [infi_eq_top] at hs, exact ⟨univ, subset_univ s, measurable_set.univ, hs _ (subset_univ s) measurable_set.univ⟩ }, { have : ∀ r > ms, ∃ t, s ⊆ t ∧ measurable_set t ∧ m t < r, { intros r hs, simpa [infi_lt_iff] using hs }, have : ∀ n : ℕ, ∃ t, s ⊆ t ∧ measurable_set t ∧ m t < ms + n⁻¹, { assume n, refine this _ (ennreal.lt_add_right (lt_top_iff_ne_top.2 hs) _), exact (ennreal.inv_pos.2 $ ennreal.nat_ne_top _) }, choose t hsub hm hm', refine ⟨⋂ n, t n, subset_Inter hsub, measurable_set.Inter hm, _⟩, have : tendsto (λ n : ℕ, ms + n⁻¹) at_top (𝓝 (ms + 0)), from tendsto_const_nhds.add ennreal.tendsto_inv_nat_nhds_zero, rw add_zero at this, refine le_antisymm (ge_of_tendsto' this $ λ n, _) _, { exact le_trans (m.mono' $ Inter_subset t n) (hm' n).le }, { refine infi_le_of_le (⋂ n, t n) _, refine infi_le_of_le (subset_Inter hsub) _, refine infi_le _ (measurable_set.Inter hm) } } end lemma exists_measurable_superset_of_trim_eq_zero {m : outer_measure α} {s : set α} (h : m.trim s = 0) : ∃t, s ⊆ t ∧ measurable_set t ∧ m t = 0 := begin rcases exists_measurable_superset_eq_trim m s with ⟨t, hst, ht, hm⟩, exact ⟨t, hst, ht, h ▸ hm⟩ end /-- If `μ i` is a countable family of outer measures, then for every set `s` there exists a measurable set `t ⊇ s` such that `μ i t = (μ i).trim s` for all `i`. -/ lemma exists_measurable_superset_forall_eq_trim {ι} [encodable ι] (μ : ι → outer_measure α) (s : set α) : ∃ t, s ⊆ t ∧ measurable_set t ∧ ∀ i, μ i t = (μ i).trim s := begin choose t hst ht hμt using λ i, (μ i).exists_measurable_superset_eq_trim s, replace hst := subset_Inter hst, replace ht := measurable_set.Inter ht, refine ⟨⋂ i, t i, hst, ht, λ i, le_antisymm _ _⟩, exacts [hμt i ▸ (μ i).mono (Inter_subset _ _), (mono' _ hst).trans_eq ((μ i).trim_eq ht)] end /-- If `m₁ s = op (m₂ s) (m₃ s)` for all `s`, then the same is true for `m₁.trim`, `m₂.trim`, and `m₃ s`. -/ theorem trim_binop {m₁ m₂ m₃ : outer_measure α} {op : ℝ≥0∞ → ℝ≥0∞ → ℝ≥0∞} (h : ∀ s, m₁ s = op (m₂ s) (m₃ s)) (s : set α) : m₁.trim s = op (m₂.trim s) (m₃.trim s) := begin rcases exists_measurable_superset_forall_eq_trim (![m₁, m₂, m₃]) s with ⟨t, hst, ht, htm⟩, simp only [fin.forall_fin_succ, matrix.cons_val_zero, matrix.cons_val_succ] at htm, rw [← htm.1, ← htm.2.1, ← htm.2.2.1, h] end /-- If `m₁ s = op (m₂ s)` for all `s`, then the same is true for `m₁.trim` and `m₂.trim`. -/ theorem trim_op {m₁ m₂ : outer_measure α} {op : ℝ≥0∞ → ℝ≥0∞} (h : ∀ s, m₁ s = op (m₂ s)) (s : set α) : m₁.trim s = op (m₂.trim s) := @trim_binop α _ m₁ m₂ 0 (λ a b, op a) h s /-- `trim` is additive. -/ theorem trim_add (m₁ m₂ : outer_measure α) : (m₁ + m₂).trim = m₁.trim + m₂.trim := ext $ trim_binop (add_apply m₁ m₂) /-- `trim` respects scalar multiplication. -/ theorem trim_smul (c : ℝ≥0∞) (m : outer_measure α) : (c • m).trim = c • m.trim := ext $ trim_op (smul_apply c m) /-- `trim` sends the supremum of two outer measures to the supremum of the trimmed measures. -/ theorem trim_sup (m₁ m₂ : outer_measure α) : (m₁ ⊔ m₂).trim = m₁.trim ⊔ m₂.trim := ext $ λ s, (trim_binop (sup_apply m₁ m₂) s).trans (sup_apply _ _ _).symm /-- `trim` sends the supremum of a countable family of outer measures to the supremum of the trimmed measures. -/ lemma trim_supr {ι} [encodable ι] (μ : ι → outer_measure α) : trim (⨆ i, μ i) = ⨆ i, trim (μ i) := begin ext1 s, rcases exists_measurable_superset_forall_eq_trim (λ o, option.elim o (supr μ) μ) s with ⟨t, hst, ht, hμt⟩, simp only [option.forall, option.elim] at hμt, simp only [supr_apply, ← hμt.1, ← hμt.2] end /-- The trimmed property of a measure μ states that `μ.to_outer_measure.trim = μ.to_outer_measure`. This theorem shows that a restricted trimmed outer measure is a trimmed outer measure. -/ lemma restrict_trim {μ : outer_measure α} {s : set α} (hs : measurable_set s) : (restrict s μ).trim = restrict s μ.trim := begin refine le_antisymm (λ t, _) (le_trim_iff.2 $ λ t ht, _), { rw restrict_apply, rcases μ.exists_measurable_superset_eq_trim (t ∩ s) with ⟨t', htt', ht', hμt'⟩, rw [← hμt'], rw inter_subset at htt', refine (mono' _ htt').trans _, rw [trim_eq _ (hs.compl.union ht'), restrict_apply, union_inter_distrib_right, compl_inter_self, set.empty_union], exact μ.mono' (inter_subset_left _ _) }, { rw [restrict_apply, trim_eq _ (ht.inter hs), restrict_apply], exact le_rfl } end end outer_measure end measure_theory
2af22d2cb498477d91f83722e4a83e4e141242a2
94e33a31faa76775069b071adea97e86e218a8ee
/src/category_theory/adjunction/evaluation.lean
1bcf4ca7e93ef024c0c56e0146829e7f296674c3
[ "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
4,848
lean
/- Copyright (c) 2021 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import category_theory.limits.shapes.products import category_theory.functor.epi_mono /-! # Adjunctions involving evaluation We show that evaluation of functors have adjoints, given the existence of (co)products. -/ namespace category_theory open category_theory.limits universes v₁ v₂ u₁ u₂ variables {C : Type u₁} [category.{v₁} C] (D : Type u₂) [category.{v₂} D] noncomputable theory section variables [∀ (a b : C), has_coproducts_of_shape (a ⟶ b) D] /-- The left adjoint of evaluation. -/ @[simps] def evaluation_left_adjoint (c : C) : D ⥤ C ⥤ D := { obj := λ d, { obj := λ t, ∐ (λ i : c ⟶ t, d), map := λ u v f, sigma.desc $ λ g, sigma.ι (λ _, d) $ g ≫ f, map_id' := begin intros, ext ⟨j⟩, simp only [cofan.mk_ι_app, colimit.ι_desc, category.comp_id], congr' 1, rw category.comp_id, end, map_comp' := begin intros, ext, simp only [cofan.mk_ι_app, colimit.ι_desc_assoc, colimit.ι_desc], congr' 1, rw category.assoc, end }, map := λ d₁ d₂ f, { app := λ e, sigma.desc $ λ h, f ≫ sigma.ι (λ _, d₂) h, naturality' := by { intros, ext, dsimp, simp } }, map_id' := by { intros, ext x ⟨j⟩, dsimp, simp }, map_comp' := by { intros, ext, dsimp, simp } } /-- The adjunction showing that evaluation is a right adjoint. -/ @[simps unit_app counit_app_app] def evaluation_adjunction_right (c : C) : evaluation_left_adjoint D c ⊣ (evaluation _ _).obj c := adjunction.mk_of_hom_equiv { hom_equiv := λ d F, { to_fun := λ f, sigma.ι (λ _, d) (𝟙 _) ≫ f.app c, inv_fun := λ f, { app := λ e, sigma.desc $ λ h, f ≫ F.map h, naturality' := by { intros, ext, dsimp, simp } }, left_inv := begin intros f, ext x ⟨g⟩, dsimp, simp only [colimit.ι_desc, limits.cofan.mk_ι_app, category.assoc, ← f.naturality, evaluation_left_adjoint_obj_map, colimit.ι_desc_assoc, cofan.mk_ι_app], congr' 2, rw category.id_comp end, right_inv := λ f, by { dsimp, simp } }, hom_equiv_naturality_left_symm' := by { intros, ext, dsimp, simp }, hom_equiv_naturality_right' := by { intros, dsimp, simp } } instance evaluation_is_right_adjoint (c : C) : is_right_adjoint ((evaluation _ D).obj c) := ⟨_, evaluation_adjunction_right _ _⟩ lemma nat_trans.mono_iff_app_mono {F G : C ⥤ D} (η : F ⟶ G) : mono η ↔ (∀ c, mono (η.app c)) := begin split, { introsI h c, exact (infer_instance : mono (((evaluation _ _).obj c).map η)) }, { introsI _, apply nat_trans.mono_app_of_mono } end end section variables [∀ (a b : C), has_products_of_shape (a ⟶ b) D] /-- The right adjoint of evaluation. -/ @[simps] def evaluation_right_adjoint (c : C) : D ⥤ C ⥤ D := { obj := λ d, { obj := λ t, ∏ (λ i : t ⟶ c, d), map := λ u v f, pi.lift $ λ g, pi.π _ $ f ≫ g, map_id' := begin intros, ext ⟨j⟩, dsimp, simp only [limit.lift_π, category.id_comp, fan.mk_π_app], congr, simp, end, map_comp' := begin intros, ext ⟨j⟩, dsimp, simp only [limit.lift_π, fan.mk_π_app, category.assoc], congr' 1, simp, end }, map := λ d₁ d₂ f, { app := λ t, pi.lift $ λ g, pi.π _ g ≫ f, naturality' := by { intros, ext, dsimp, simp } }, map_id' := by { intros, ext x ⟨j⟩, dsimp, simp }, map_comp' := by { intros, ext, dsimp, simp } } /-- The adjunction showing that evaluation is a left adjoint. -/ @[simps unit_app_app counit_app] def evaluation_adjunction_left (c : C) : (evaluation _ _).obj c ⊣ evaluation_right_adjoint D c := adjunction.mk_of_hom_equiv { hom_equiv := λ F d, { to_fun := λ f, { app := λ t, pi.lift $ λ g, F.map g ≫ f, naturality' := by { intros, ext, dsimp, simp } }, inv_fun := λ f, f.app _ ≫ pi.π _ (𝟙 _), left_inv := λ f, by { dsimp, simp }, right_inv := begin intros f, ext x ⟨g⟩, dsimp, simp only [limit.lift_π, evaluation_right_adjoint_obj_map, nat_trans.naturality_assoc, fan.mk_π_app], congr, rw category.comp_id end }, hom_equiv_naturality_left_symm' := by { intros, dsimp, simp }, hom_equiv_naturality_right' := by { intros, ext, dsimp, simp } } instance evaluation_is_left_adjoint (c : C) : is_left_adjoint ((evaluation _ D).obj c) := ⟨_, evaluation_adjunction_left _ _⟩ lemma nat_trans.epi_iff_app_epi {F G : C ⥤ D} (η : F ⟶ G) : epi η ↔ (∀ c, epi (η.app c)) := begin split, { introsI h c, exact (infer_instance : epi (((evaluation _ _).obj c).map η)) }, { introsI, apply nat_trans.epi_app_of_epi } end end end category_theory
3d9096aa1972705e16661428f7a90164f453f38c
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/counterexamples/canonically_ordered_comm_semiring_two_mul.lean
034e6148f77d636ea3a6836e163d7d5b368616b6
[ "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
9,496
lean
/- Copyright (c) 2021 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import data.zmod.basic import ring_theory.subsemiring import algebra.ordered_monoid /-! A `canonically_ordered_comm_semiring` with two different elements `a` and `b` such that `a ≠ b` and `2 * a = 2 * b`. Thus, multiplication by a fixed non-zero element of a canonically ordered semiring need not be injective. In particular, multiplying by a strictly positive element need not be strictly monotone. Recall that a `canonically_ordered_comm_semiring` is a commutative semiring with a partial ordering that is "canonical" in the sense that the inequality `a ≤ b` holds if and only if there is a `c` such that `a + c = b`. There are several compatibility conditions among addition/multiplication and the order relation. The point of the counterexample is to show that monotonicity of multiplication cannot be strengthened to **strict** monotonicity. Reference: https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/canonically_ordered.20pathology -/ namespace from_Bhavik /-- Bhavik Mehta's example. There are only the initial definitions, but no proofs. The Type `K` is a canonically ordered commutative semiring with the property that `2 * (1/2) ≤ 2 * 1`, even though it is not true that `1/2 ≤ 1`, since `1/2` and `1` are not comparable. -/ @[derive [comm_semiring]] def K : Type := subsemiring.closure ({1.5} : set ℚ) instance : has_coe K ℚ := ⟨λ x, x.1⟩ instance inhabited_K : inhabited K := ⟨0⟩ instance : preorder K := { le := λ x y, x = y ∨ (x : ℚ) + 1 ≤ (y : ℚ), le_refl := λ x, or.inl rfl, le_trans := λ x y z xy yz, begin rcases xy with (rfl | _), { apply yz }, rcases yz with (rfl | _), { right, apply xy }, right, exact xy.trans (le_trans ((le_add_iff_nonneg_right _).mpr zero_le_one) yz) end } end from_Bhavik lemma mem_zmod_2 (a : zmod 2) : a = 0 ∨ a = 1 := begin rcases a with ⟨_ | _ | _ | _ | a_val, _ | ⟨_, _ | ⟨_, ⟨⟩⟩⟩⟩, { exact or.inl rfl }, { exact or.inr rfl }, end lemma add_self_zmod_2 (a : zmod 2) : a + a = 0 := begin rcases mem_zmod_2 a with rfl | rfl; refl, end namespace Nxzmod_2 variables {a b : ℕ × zmod 2} /-- The preorder relation on `ℕ × ℤ/2ℤ` where we only compare the first coordinate, except that we leave incomparable each pair of elements with the same first component. For instance, `∀ α, β ∈ ℤ/2ℤ`, the inequality `(1,α) ≤ (2,β)` holds, whereas, `∀ n ∈ ℤ`, the elements `(n,0)` and `(n,1)` are incomparable. -/ instance preN2 : partial_order (ℕ × zmod 2) := { le := λ x y, x = y ∨ x.1 < y.1, le_refl := λ a, or.inl rfl, le_trans := λ x y z xy yz, begin rcases xy with (rfl | _), { exact yz }, { rcases yz with (rfl | _), { exact or.inr xy}, { exact or.inr (xy.trans yz) } } end, le_antisymm := begin intros a b ab ba, cases ab with ab ab, { exact ab }, { cases ba with ba ba, { exact ba.symm }, { exact (nat.lt_asymm ab ba).elim } } end } instance csrN2 : comm_semiring (ℕ × zmod 2) := by apply_instance instance csrN2_1 : add_cancel_comm_monoid (ℕ × zmod 2) := { add_left_cancel := λ a b c h, (add_right_inj a).mp h, ..Nxzmod_2.csrN2 } /-- A strict inequality forces the first components to be different. -/ @[simp] lemma lt_def : a < b ↔ a.1 < b.1 := begin refine ⟨λ h, _, λ h, _⟩, { rcases h with ⟨(rfl | a1), h1⟩, { exact ((not_or_distrib.mp h1).1).elim rfl }, { exact a1 } }, refine ⟨or.inr h, not_or_distrib.mpr ⟨λ k, _, not_lt.mpr h.le⟩⟩, rw k at h, exact nat.lt_asymm h h end lemma add_left_cancel : ∀ (a b c : ℕ × zmod 2), a + b = a + c → b = c := λ a b c h, (add_right_inj a).mp h lemma add_le_add_left : ∀ (a b : ℕ × zmod 2), a ≤ b → ∀ (c : ℕ × zmod 2), c + a ≤ c + b := begin rintros a b (rfl | ab) c, { refl }, { exact or.inr (by simpa) } end lemma le_of_add_le_add_left : ∀ (a b c : ℕ × zmod 2), a + b ≤ a + c → b ≤ c := begin rintros a b c (bc | bc), { exact le_of_eq ((add_right_inj a).mp bc) }, { exact or.inr (by simpa using bc) } end lemma zero_le_one : (0 : ℕ × zmod 2) ≤ 1 := dec_trivial lemma mul_lt_mul_of_pos_left : ∀ (a b c : ℕ × zmod 2), a < b → 0 < c → c * a < c * b := λ a b c ab c0, lt_def.mpr ((mul_lt_mul_left (lt_def.mp c0)).mpr (lt_def.mp ab)) lemma mul_lt_mul_of_pos_right : ∀ (a b c : ℕ × zmod 2), a < b → 0 < c → a * c < b * c := λ a b c ab c0, lt_def.mpr ((mul_lt_mul_right (lt_def.mp c0)).mpr (lt_def.mp ab)) instance ocsN2 : ordered_comm_semiring (ℕ × zmod 2) := { add_le_add_left := add_le_add_left, le_of_add_le_add_left := le_of_add_le_add_left, zero_le_one := zero_le_one, mul_lt_mul_of_pos_left := mul_lt_mul_of_pos_left, mul_lt_mul_of_pos_right := mul_lt_mul_of_pos_right, ..Nxzmod_2.csrN2_1, ..(infer_instance : partial_order (ℕ × zmod 2)), ..(infer_instance : comm_semiring (ℕ × zmod 2)) } end Nxzmod_2 namespace ex_L open Nxzmod_2 subtype /-- Initially, `L` was defined as the subsemiring closure of `(1,0)`. -/ def L : Type := { l : (ℕ × zmod 2) // l ≠ (0, 1) } instance zero : has_zero L := ⟨⟨(0, 0), dec_trivial⟩⟩ instance one : has_one L := ⟨⟨(1, 1), dec_trivial⟩⟩ instance inhabited : inhabited L := ⟨1⟩ lemma add_L {a b : ℕ × zmod 2} (ha : a ≠ (0, 1)) (hb : b ≠ (0, 1)) : a + b ≠ (0, 1) := begin rcases a with ⟨a, a2⟩, rcases b with ⟨b, b2⟩, cases b, { rcases mem_zmod_2 b2 with rfl | rfl, { simp [ha] }, { simpa only } }, { simp [(a + b).succ_ne_zero] } end lemma mul_L {a b : ℕ × zmod 2} (ha : a ≠ (0, 1)) (hb : b ≠ (0, 1)) : a * b ≠ (0, 1) := begin rcases a with ⟨a, a2⟩, rcases b with ⟨b, b2⟩, cases b, { rcases mem_zmod_2 b2 with rfl | rfl; rcases mem_zmod_2 a2 with rfl | rfl; -- while this looks like a non-terminal `simp`, it (almost) isn't: there is only one goal where -- it does not finish the proof and on that goal it asks to prove `false` simp, exact hb rfl }, cases a, { rcases mem_zmod_2 b2 with rfl | rfl; rcases mem_zmod_2 a2 with rfl | rfl; -- while this looks like a non-terminal `simp`, it (almost) isn't: there is only one goal where -- it does not finish the proof and on that goal it asks to prove `false` simp, exact ha rfl }, { simp [mul_ne_zero _ _, nat.succ_ne_zero _] } end instance has_add_L : has_add L := { add := λ ⟨a, ha⟩ ⟨b, hb⟩, ⟨a + b, add_L ha hb⟩ } instance : has_mul L := { mul := λ ⟨a, ha⟩ ⟨b, hb⟩, ⟨a * b, mul_L ha hb⟩ } instance : ordered_comm_semiring L := begin refine function.injective.ordered_comm_semiring _ subtype.coe_injective rfl rfl _ _; { refine λ x y, _, cases x, cases y, refl } end lemma bot_le : ∀ (a : L), 0 ≤ a := begin rintros ⟨⟨an, a2⟩, ha⟩, cases an, { rcases mem_zmod_2 a2 with (rfl | rfl), { refl, }, { exact (ha rfl).elim } }, { refine or.inr _, exact nat.succ_pos _ } end instance order_bot : order_bot L := { bot := 0, bot_le := bot_le, ..(infer_instance : partial_order L) } lemma le_iff_exists_add : ∀ (a b : L), a ≤ b ↔ ∃ (c : L), b = a + c := begin rintros ⟨⟨an, a2⟩, ha⟩ ⟨⟨bn, b2⟩, hb⟩, rw subtype.mk_le_mk, refine ⟨λ h, _, λ h, _⟩, { rcases h with ⟨rfl, rfl⟩ | h, { exact ⟨(0 : L), (add_zero _).symm⟩ }, { refine ⟨⟨⟨bn - an, b2 + a2⟩, _⟩, _⟩, { rw [ne.def, prod.mk.inj_iff, not_and_distrib], exact or.inl (ne_of_gt (nat.sub_pos_of_lt h)) }, { congr, { exact (nat.add_sub_cancel' h.le).symm }, { change b2 = a2 + (b2 + a2), rw [add_comm b2, ← add_assoc, add_self_zmod_2, zero_add] } } } }, { rcases h with ⟨⟨⟨c, c2⟩, hc⟩, abc⟩, injection abc with abc, rw [prod.mk_add_mk, prod.mk.inj_iff] at abc, rcases abc with ⟨rfl, rfl⟩, cases c, { refine or.inl _, rw [ne.def, prod.mk.inj_iff, eq_self_iff_true, true_and] at hc, rcases mem_zmod_2 c2 with rfl | rfl, { rw [add_zero, add_zero] }, { exact (hc rfl).elim } }, { refine or.inr _, exact (lt_add_iff_pos_right _).mpr c.succ_pos } } end lemma eq_zero_or_eq_zero_of_mul_eq_zero : ∀ (a b : L), a * b = 0 → a = 0 ∨ b = 0 := begin rintros ⟨⟨a, a2⟩, ha⟩ ⟨⟨b, b2⟩, hb⟩ ab1, injection ab1 with ab, injection ab with abn ab2, rw mul_eq_zero at abn, rcases abn with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, { refine or.inl _, rcases mem_zmod_2 a2 with rfl | rfl, { refl }, { exact (ha rfl).elim } }, { refine or.inr _, rcases mem_zmod_2 b2 with rfl | rfl, { refl }, { exact (hb rfl).elim } } end instance can : canonically_ordered_comm_semiring L := { le_iff_exists_add := le_iff_exists_add, eq_zero_or_eq_zero_of_mul_eq_zero := eq_zero_or_eq_zero_of_mul_eq_zero, ..(infer_instance : order_bot L), ..(infer_instance : ordered_comm_semiring L) } /-- The elements `(1,0)` and `(1,1)` of `L` are different, but their doubles coincide. -/ example : ∃ a b : L, a ≠ b ∧ 2 * a = 2 * b := begin refine ⟨⟨(1,0), by simp⟩, 1, λ (h : (⟨(1, 0), _⟩ : L) = ⟨⟨1, 1⟩, _⟩), _, rfl⟩, obtain (F : (0 : zmod 2) = 1) := congr_arg (λ j : L, j.1.2) h, cases F, end end ex_L
1b91ef4bbedb891cd0d7f69698a220653d645f22
eecbdfcd97327701a240f05d64290a19a45d198a
/lib_devel/simplifier.lean
278f082f3fe3fca4c61af1ac55e79f44997aa2fe
[]
no_license
johoelzl/hanoifabs
d5ca27df51f9bccfb0152f03b480e9e1228a4b14
4235c6bc5d664897bbf5dde04e2237e4b20c9170
refs/heads/master
1,584,514,375,379
1,528,258,129,000
1,528,258,129,000
134,419,383
0
1
null
null
null
null
UTF-8
Lean
false
false
4,267
lean
/- Simplifier -/ #check tactic.simplify #check tactic.interactive.simp /- The simplifier is currently the most powerful tactic in Lean (besides definitional equality). Many problems can be solved by rewriting. But for this it is important to understand the simplifier and how to organize its rewrite rules. Basic idea: * the simplifier has an database of simp rules `l = r` (can be extended using `@[simp]`) * when invoked it tries to rewrite with as much of these simp rules as possible * bottom-up: i.e. when run on `f a` it first tries to rewrite `f = f'` then `a = a'` and only `f' a'`, if `f' a'` is rewritten, then the simplifier walks again over this term. * uses congruence rules `@[congr]` to avoid some problems with dependent types * permutation check allows to add commutativity rules * there is also `dsimp` which only unfold definitional equal rules: doesn't have type dependence problems * β-reduction: (λa, f a) x = f x * ζ-reduction: let t = x in C[x] = C[t] * ι-reduction: prod.fst (a, b) = a * contextual := tt: p → q: uses p when proving the assumptions of a conditional rw rule a = b → q: adds a = b as rewrite rule * how does the simplifier know which rule to apply? - it looks at the head symbol H of the term - collects all simp rules with head symbol H - matches each simp rule with the current term, i.e. here the transperency setting comes into play - rewrites using the first matching rule: conditional assumptions are proved using the discharger * problem: non terminating rewriting: a = b = a = b = a = .... f(a) = f(f a) = f (f (f a)) = .... * problem: head symbol needs to be a constant: ∀f, is_group_hom f → f (a + b) = f a + f b doesn't work as a simp rule * the interface: simp [r₁, r₂, …] simp * at * simp [*, r₁, r₂, …] simp [-r], simp only [r₁, r₂, …] If you add a constant `c` instead of a rule `r : l = r`, then the defining equations are added * rule preprocessing: ¬ a ⟹ a ↔ false a ≠ b ⟹ (a = b) ↔ false Type Dependence Problem: `f : Πn:ℕ, vector n ℕ` `p (f a)` ~> here `f` and `p` can be rewritten arbitrarily, but if we rewrite `a` we also need to change `p` (and its type)! (Note: `rw` sometimes works in this case as by default it rewrites *all* occurences of `a`, so also the one in `p`). -/ example {α : Type*} {a b c : α} (f : α → α) (hac : a = c) (hfa : f a = b) : f a = b := begin simp [hac, hfa], -- doesn't work as first `f a = f c` by `hac` end /- How to setup simp rules -/ /- Example: (non-commutative) groups Think about *normalizing* behaviour: does the theory have a normal form? For example for groups: (-a + -b) + -c and remove all zeros: 0 + a = a a + 0 = a replace - by plus: a - b = a + -b normalize under -: - 0 = 0 - (a + b) = -a + -b - (a - b) = -a + b - (- a) = a normalize +: a + (b + c) = (a + b) + c cancel: a + -a = 0 -a + a = 0 a + (-a + b) = b -a + (a + b) = b This breaks down for commutative groups, there we need a special tactic to find two inverse terms, reorders and cancels them. -/ /- Example: Morphisms f (x + y) = f x + f y f 0 = 0 -/ /- Normal forms: The right-hand side is not always shorter, but should be smaller in terms of some relation. a * (b + c) = a * b + c * b Is a possible rule (`+` < `*` is generally prefered) but results also in an explosion of the term, should be activated by the user case by case. -/ /- Logic by rewriting true ∧ a = a a ∧ ∃x, f x = ∃x, a ∧ f x (∃x, f x) → p = ∀x, f x → p -/ /- simp rules: Write rules generic: bad: x ^ (n + 1) = x ^ n * x good: x ^ 1 = x x ^ (n + m) = x ^ n * x ^ m General rule: `l = r` * have as much variables in `l` as possible * reduce them in `r` * `l` should be already in rewritten form * also: all variables in `r`, and in your assumptions need to occur already in `l` (with the exception of type class instances) take care of decidability: [decidable p] [decidable (λx, ¬ p x)] -- sometimes necessary -/
ae7773d0f09c7b7763dbb5047a929156bc1a6007
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/data/list/defs.lean
a6284d0fec801fd3811f130798e0c557a1879fb1
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
34,744
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro -/ import data.option.defs import logic.basic import tactic.cache /-! ## Definitions on lists This file contains various definitions on lists. It does not contain proofs about these definitions, those are contained in other files in `data/list` -/ namespace list open function nat native (rb_map mk_rb_map rb_map.of_list) universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} instance [decidable_eq α] : has_sdiff (list α) := ⟨ list.diff ⟩ /-- Split a list at an index. split_at 2 [a, b, c] = ([a, b], [c]) -/ def split_at : ℕ → list α → list α × list α | 0 a := ([], a) | (succ n) [] := ([], []) | (succ n) (x :: xs) := let (l, r) := split_at n xs in (x :: l, r) /-- An auxiliary function for `split_on_p`. -/ def split_on_p_aux {α : Type u} (P : α → Prop) [decidable_pred P] : list α → (list α → list α) → list (list α) | [] f := [f []] | (h :: t) f := if P h then f [] :: split_on_p_aux t id else split_on_p_aux t (λ l, f (h :: l)) /-- Split a list at every element satisfying a predicate. -/ def split_on_p {α : Type u} (P : α → Prop) [decidable_pred P] (l : list α) : list (list α) := split_on_p_aux P l id /-- Split a list at every occurrence of an element. [1,1,2,3,2,4,4].split_on 2 = [[1,1],[3],[4,4]] -/ def split_on {α : Type u} [decidable_eq α] (a : α) (as : list α) : list (list α) := as.split_on_p (=a) /-- Concatenate an element at the end of a list. concat [a, b] c = [a, b, c] -/ @[simp] def concat : list α → α → list α | [] a := [a] | (b::l) a := b :: concat l a /-- `head' xs` returns the first element of `xs` if `xs` is non-empty; it returns `none` otherwise -/ @[simp] def head' : list α → option α | [] := none | (a :: l) := some a /-- Convert a list into an array (whose length is the length of `l`). -/ def to_array (l : list α) : array l.length α := {data := λ v, l.nth_le v.1 v.2} /-- "inhabited" `nth` function: returns `default` instead of `none` in the case that the index is out of bounds. -/ @[simp] def inth [h : inhabited α] (l : list α) (n : nat) : α := (nth l n).iget /-- Apply a function to the nth tail of `l`. Returns the input without using `f` if the index is larger than the length of the list. modify_nth_tail f 2 [a, b, c] = [a, b] ++ f [c] -/ @[simp] def modify_nth_tail (f : list α → list α) : ℕ → list α → list α | 0 l := f l | (n+1) [] := [] | (n+1) (a::l) := a :: modify_nth_tail n l /-- Apply `f` to the head of the list, if it exists. -/ @[simp] def modify_head (f : α → α) : list α → list α | [] := [] | (a::l) := f a :: l /-- Apply `f` to the nth element of the list, if it exists. -/ def modify_nth (f : α → α) : ℕ → list α → list α := modify_nth_tail (modify_head f) /-- Apply `f` to the last element of `l`, if it exists. -/ @[simp] def modify_last (f : α → α) : list α → list α | [] := [] | [x] := [f x] | (x :: xs) := x :: modify_last xs /-- `insert_nth n a l` inserts `a` into the list `l` after the first `n` elements of `l` `insert_nth 2 1 [1, 2, 3, 4] = [1, 2, 1, 3, 4]`-/ def insert_nth (n : ℕ) (a : α) : list α → list α := modify_nth_tail (list.cons a) n section take' variable [inhabited α] /-- Take `n` elements from a list `l`. If `l` has less than `n` elements, append `n - length l` elements `default α`. -/ def take' : ∀ n, list α → list α | 0 l := [] | (n+1) l := l.head :: take' n l.tail end take' /-- Get the longest initial segment of the list whose members all satisfy `p`. take_while (λ x, x < 3) [0, 2, 5, 1] = [0, 2] -/ def take_while (p : α → Prop) [decidable_pred p] : list α → list α | [] := [] | (a::l) := if p a then a :: take_while l else [] /-- Fold a function `f` over the list from the left, returning the list of partial results. scanl (+) 0 [1, 2, 3] = [0, 1, 3, 6] -/ def scanl (f : α → β → α) : α → list β → list α | a [] := [a] | a (b::l) := a :: scanl (f a b) l /-- Auxiliary definition used to define `scanr`. If `scanr_aux f b l = (b', l')` then `scanr f b l = b' :: l'` -/ def scanr_aux (f : α → β → β) (b : β) : list α → β × list β | [] := (b, []) | (a::l) := let (b', l') := scanr_aux l in (f a b', b' :: l') /-- Fold a function `f` over the list from the right, returning the list of partial results. scanr (+) 0 [1, 2, 3] = [6, 5, 3, 0] -/ def scanr (f : α → β → β) (b : β) (l : list α) : list β := let (b', l') := scanr_aux f b l in b' :: l' /-- Product of a list. prod [a, b, c] = ((1 * a) * b) * c -/ def prod [has_mul α] [has_one α] : list α → α := foldl (*) 1 /-- Sum of a list. sum [a, b, c] = ((0 + a) + b) + c -/ -- Later this will be tagged with `to_additive`, but this can't be done yet because of import -- dependencies. def sum [has_add α] [has_zero α] : list α → α := foldl (+) 0 /-- The alternating sum of a list. -/ def alternating_sum {G : Type*} [has_zero G] [has_add G] [has_neg G] : list G → G | [] := 0 | (g :: []) := g | (g :: h :: t) := g + -h + alternating_sum t /-- The alternating product of a list. -/ def alternating_prod {G : Type*} [has_one G] [has_mul G] [has_inv G] : list G → G | [] := 1 | (g :: []) := g | (g :: h :: t) := g * h⁻¹ * alternating_prod t /-- Given a function `f : α → β ⊕ γ`, `partition_map f l` maps the list by `f` whilst partitioning the result it into a pair of lists, `list β × list γ`, partitioning the `sum.inl _` into the left list, and the `sum.inr _` into the right list. `partition_map (id : ℕ ⊕ ℕ → ℕ ⊕ ℕ) [inl 0, inr 1, inl 2] = ([0,2], [1])` -/ def partition_map (f : α → β ⊕ γ) : list α → list β × list γ | [] := ([],[]) | (x::xs) := match f x with | (sum.inr r) := prod.map id (cons r) $ partition_map xs | (sum.inl l) := prod.map (cons l) id $ partition_map xs end /-- `find p l` is the first element of `l` satisfying `p`, or `none` if no such element exists. -/ def find (p : α → Prop) [decidable_pred p] : list α → option α | [] := none | (a::l) := if p a then some a else find l /-- `mfind tac l` returns the first element of `l` on which `tac` succeeds, and fails otherwise. -/ def mfind {α} {m : Type u → Type v} [monad m] [alternative m] (tac : α → m punit) : list α → m α := list.mfirst $ λ a, tac a $> a /-- `mbfind' p l` returns the first element `a` of `l` for which `p a` returns true. `mbfind'` short-circuits, so `p` is not necessarily run on every `a` in `l`. This is a monadic version of `list.find`. -/ def mbfind' {m : Type u → Type v} [monad m] {α : Type u} (p : α → m (ulift bool)) : list α → m (option α) | [] := pure none | (x :: xs) := do ⟨px⟩ ← p x, if px then pure (some x) else mbfind' xs section variables {m : Type → Type v} [monad m] /-- A variant of `mbfind'` with more restrictive universe levels. -/ def mbfind {α} (p : α → m bool) (xs : list α) : m (option α) := xs.mbfind' (functor.map ulift.up ∘ p) /-- `many p as` returns true iff `p` returns true for any element of `l`. `many` short-circuits, so if `p` returns true for any element of `l`, later elements are not checked. This is a monadic version of `list.any`. -/ -- Implementing this via `mbfind` would give us less universe polymorphism. def many {α : Type u} (p : α → m bool) : list α → m bool | [] := pure false | (x :: xs) := do px ← p x, if px then pure tt else many xs /-- `mall p as` returns true iff `p` returns true for all elements of `l`. `mall` short-circuits, so if `p` returns false for any element of `l`, later elements are not checked. This is a monadic version of `list.all`. -/ def mall {α : Type u} (p : α → m bool) (as : list α) : m bool := bnot <$> many (λ a, bnot <$> p a) as /-- `mbor xs` runs the actions in `xs`, returning true if any of them returns true. `mbor` short-circuits, so if an action returns true, later actions are not run. This is a monadic version of `list.bor`. -/ def mbor : list (m bool) → m bool := many id /-- `mband xs` runs the actions in `xs`, returning true if all of them return true. `mband` short-circuits, so if an action returns false, later actions are not run. This is a monadic version of `list.band`. -/ def mband : list (m bool) → m bool := mall id end /-- Auxiliary definition for `foldl_with_index`. -/ def foldl_with_index_aux (f : ℕ → α → β → α) : ℕ → α → list β → α | _ a [] := a | i a (b :: l) := foldl_with_index_aux (i + 1) (f i a b) l /-- Fold a list from left to right as with `foldl`, but the combining function also receives each element's index. -/ def foldl_with_index (f : ℕ → α → β → α) (a : α) (l : list β) : α := foldl_with_index_aux f 0 a l /-- Auxiliary definition for `foldr_with_index`. -/ def foldr_with_index_aux (f : ℕ → α → β → β) : ℕ → β → list α → β | _ b [] := b | i b (a :: l) := f i a (foldr_with_index_aux (i + 1) b l) /-- Fold a list from right to left as with `foldr`, but the combining function also receives each element's index. -/ def foldr_with_index (f : ℕ → α → β → β) (b : β) (l : list α) : β := foldr_with_index_aux f 0 b l /-- `find_indexes p l` is the list of indexes of elements of `l` that satisfy `p`. -/ def find_indexes (p : α → Prop) [decidable_pred p] (l : list α) : list nat := foldr_with_index (λ i a is, if p a then i :: is else is) [] l /-- Returns the elements of `l` that satisfy `p` together with their indexes in `l`. The returned list is ordered by index. -/ def indexes_values (p : α → Prop) [decidable_pred p] (l : list α) : list (ℕ × α) := foldr_with_index (λ i a l, if p a then (i , a) :: l else l) [] l /-- `indexes_of a l` is the list of all indexes of `a` in `l`. For example: ``` indexes_of a [a, b, a, a] = [0, 2, 3] ``` -/ def indexes_of [decidable_eq α] (a : α) : list α → list nat := find_indexes (eq a) section mfold_with_index variables {m : Type v → Type w} [monad m] /-- Monadic variant of `foldl_with_index`. -/ def mfoldl_with_index {α β} (f : ℕ → β → α → m β) (b : β) (as : list α) : m β := as.foldl_with_index (λ i ma b, do a ← ma, f i a b) (pure b) /-- Monadic variant of `foldr_with_index`. -/ def mfoldr_with_index {α β} (f : ℕ → α → β → m β) (b : β) (as : list α) : m β := as.foldr_with_index (λ i a mb, do b ← mb, f i a b) (pure b) end mfold_with_index section mmap_with_index variables {m : Type v → Type w} [applicative m] /-- Auxiliary definition for `mmap_with_index`. -/ def mmap_with_index_aux {α β} (f : ℕ → α → m β) : ℕ → list α → m (list β) | _ [] := pure [] | i (a :: as) := list.cons <$> f i a <*> mmap_with_index_aux (i + 1) as /-- Applicative variant of `map_with_index`. -/ def mmap_with_index {α β} (f : ℕ → α → m β) (as : list α) : m (list β) := mmap_with_index_aux f 0 as /-- Auxiliary definition for `mmap_with_index'`. -/ def mmap_with_index'_aux {α} (f : ℕ → α → m punit) : ℕ → list α → m punit | _ [] := pure ⟨⟩ | i (a :: as) := f i a *> mmap_with_index'_aux (i + 1) as /-- A variant of `mmap_with_index` specialised to applicative actions which return `unit`. -/ def mmap_with_index' {α} (f : ℕ → α → m punit) (as : list α) : m punit := mmap_with_index'_aux f 0 as end mmap_with_index /-- `lookmap` is a combination of `lookup` and `filter_map`. `lookmap f l` will apply `f : α → option α` to each element of the list, replacing `a → b` at the first value `a` in the list such that `f a = some b`. -/ def lookmap (f : α → option α) : list α → list α | [] := [] | (a::l) := match f a with | some b := b :: l | none := a :: lookmap l end /-- `countp p l` is the number of elements of `l` that satisfy `p`. -/ def countp (p : α → Prop) [decidable_pred p] : list α → nat | [] := 0 | (x::xs) := if p x then succ (countp xs) else countp xs /-- `count a l` is the number of occurrences of `a` in `l`. -/ def count [decidable_eq α] (a : α) : list α → nat := countp (eq a) /-- `is_prefix l₁ l₂`, or `l₁ <+: l₂`, means that `l₁` is a prefix of `l₂`, that is, `l₂` has the form `l₁ ++ t` for some `t`. -/ def is_prefix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, l₁ ++ t = l₂ /-- `is_suffix l₁ l₂`, or `l₁ <:+ l₂`, means that `l₁` is a suffix of `l₂`, that is, `l₂` has the form `t ++ l₁` for some `t`. -/ def is_suffix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, t ++ l₁ = l₂ /-- `is_infix l₁ l₂`, or `l₁ <:+: l₂`, means that `l₁` is a contiguous substring of `l₂`, that is, `l₂` has the form `s ++ l₁ ++ t` for some `s, t`. -/ def is_infix (l₁ : list α) (l₂ : list α) : Prop := ∃ s t, s ++ l₁ ++ t = l₂ infix ` <+: `:50 := is_prefix infix ` <:+ `:50 := is_suffix infix ` <:+: `:50 := is_infix /-- `inits l` is the list of initial segments of `l`. inits [1, 2, 3] = [[], [1], [1, 2], [1, 2, 3]] -/ @[simp] def inits : list α → list (list α) | [] := [[]] | (a::l) := [] :: map (λt, a::t) (inits l) /-- `tails l` is the list of terminal segments of `l`. tails [1, 2, 3] = [[1, 2, 3], [2, 3], [3], []] -/ @[simp] def tails : list α → list (list α) | [] := [[]] | (a::l) := (a::l) :: tails l def sublists'_aux : list α → (list α → list β) → list (list β) → list (list β) | [] f r := f [] :: r | (a::l) f r := sublists'_aux l f (sublists'_aux l (f ∘ cons a) r) /-- `sublists' l` is the list of all (non-contiguous) sublists of `l`. It differs from `sublists` only in the order of appearance of the sublists; `sublists'` uses the first element of the list as the MSB, `sublists` uses the first element of the list as the LSB. sublists' [1, 2, 3] = [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]] -/ def sublists' (l : list α) : list (list α) := sublists'_aux l id [] def sublists_aux : list α → (list α → list β → list β) → list β | [] f := [] | (a::l) f := f [a] (sublists_aux l (λys r, f ys (f (a :: ys) r))) /-- `sublists l` is the list of all (non-contiguous) sublists of `l`; cf. `sublists'` for a different ordering. sublists [1, 2, 3] = [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]] -/ def sublists (l : list α) : list (list α) := [] :: sublists_aux l cons def sublists_aux₁ : list α → (list α → list β) → list β | [] f := [] | (a::l) f := f [a] ++ sublists_aux₁ l (λys, f ys ++ f (a :: ys)) section forall₂ variables {r : α → β → Prop} {p : γ → δ → Prop} /-- `forall₂ R l₁ l₂` means that `l₁` and `l₂` have the same length, and whenever `a` is the nth element of `l₁`, and `b` is the nth element of `l₂`, then `R a b` is satisfied. -/ inductive forall₂ (R : α → β → Prop) : list α → list β → Prop | nil : forall₂ [] [] | cons {a b l₁ l₂} : R a b → forall₂ l₁ l₂ → forall₂ (a::l₁) (b::l₂) attribute [simp] forall₂.nil end forall₂ /-- Auxiliary definition used to define `transpose`. `transpose_aux l L` takes each element of `l` and appends it to the start of each element of `L`. `transpose_aux [a, b, c] [l₁, l₂, l₃] = [a::l₁, b::l₂, c::l₃]` -/ def transpose_aux : list α → list (list α) → list (list α) | [] ls := ls | (a::i) [] := [a] :: transpose_aux i [] | (a::i) (l::ls) := (a::l) :: transpose_aux i ls /-- transpose of a list of lists, treated as a matrix. transpose [[1, 2], [3, 4], [5, 6]] = [[1, 3, 5], [2, 4, 6]] -/ def transpose : list (list α) → list (list α) | [] := [] | (l::ls) := transpose_aux l (transpose ls) /-- List of all sections through a list of lists. A section of `[L₁, L₂, ..., Lₙ]` is a list whose first element comes from `L₁`, whose second element comes from `L₂`, and so on. -/ def sections : list (list α) → list (list α) | [] := [[]] | (l::L) := bind (sections L) $ λ s, map (λ a, a::s) l section permutations def permutations_aux2 (t : α) (ts : list α) (r : list β) : list α → (list α → β) → list α × list β | [] f := (ts, r) | (y::ys) f := let (us, zs) := permutations_aux2 ys (λx : list α, f (y::x)) in (y :: us, f (t :: y :: us) :: zs) private def meas : (Σ'_:list α, list α) → ℕ × ℕ | ⟨l, i⟩ := (length l + length i, length l) local infix ` ≺ `:50 := inv_image (prod.lex (<) (<)) meas @[elab_as_eliminator] def permutations_aux.rec {C : list α → list α → Sort v} (H0 : ∀ is, C [] is) (H1 : ∀ t ts is, C ts (t::is) → C is [] → C (t::ts) is) : ∀ l₁ l₂, C l₁ l₂ | [] is := H0 is | (t::ts) is := have h1 : ⟨ts, t :: is⟩ ≺ ⟨t :: ts, is⟩, from show prod.lex _ _ (succ (length ts + length is), length ts) (succ (length ts) + length is, length (t :: ts)), by rw nat.succ_add; exact prod.lex.right _ (lt_succ_self _), have h2 : ⟨is, []⟩ ≺ ⟨t :: ts, is⟩, from prod.lex.left _ _ (nat.lt_add_of_pos_left (succ_pos _)), H1 t ts is (permutations_aux.rec ts (t::is)) (permutations_aux.rec is []) using_well_founded { dec_tac := tactic.assumption, rel_tac := λ _ _, `[exact ⟨(≺), @inv_image.wf _ _ _ meas (prod.lex_wf lt_wf lt_wf)⟩] } def permutations_aux : list α → list α → list (list α) := @@permutations_aux.rec (λ _ _, list (list α)) (λ is, []) (λ t ts is IH1 IH2, foldr (λy r, (permutations_aux2 t ts r y id).2) IH1 (is :: IH2)) /-- List of all permutations of `l`. permutations [1, 2, 3] = [[1, 2, 3], [2, 1, 3], [3, 2, 1], [2, 3, 1], [3, 1, 2], [1, 3, 2]] -/ def permutations (l : list α) : list (list α) := l :: permutations_aux l [] end permutations /-- `erasep p l` removes the first element of `l` satisfying the predicate `p`. -/ def erasep (p : α → Prop) [decidable_pred p] : list α → list α | [] := [] | (a::l) := if p a then l else a :: erasep l /-- `extractp p l` returns a pair of an element `a` of `l` satisfying the predicate `p`, and `l`, with `a` removed. If there is no such element `a` it returns `(none, l)`. -/ def extractp (p : α → Prop) [decidable_pred p] : list α → option α × list α | [] := (none, []) | (a::l) := if p a then (some a, l) else let (a', l') := extractp l in (a', a :: l') /-- `revzip l` returns a list of pairs of the elements of `l` paired with the elements of `l` in reverse order. `revzip [1,2,3,4,5] = [(1, 5), (2, 4), (3, 3), (4, 2), (5, 1)]` -/ def revzip (l : list α) : list (α × α) := zip l l.reverse /-- `product l₁ l₂` is the list of pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂`. product [1, 2] [5, 6] = [(1, 5), (1, 6), (2, 5), (2, 6)] -/ def product (l₁ : list α) (l₂ : list β) : list (α × β) := l₁.bind $ λ a, l₂.map $ prod.mk a /-- `sigma l₁ l₂` is the list of dependent pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂ a`. sigma [1, 2] (λ_, [(5 : ℕ), 6]) = [(1, 5), (1, 6), (2, 5), (2, 6)] -/ protected def sigma {σ : α → Type*} (l₁ : list α) (l₂ : Π a, list (σ a)) : list (Σ a, σ a) := l₁.bind $ λ a, (l₂ a).map $ sigma.mk a /-- Auxliary definition used to define `of_fn`. `of_fn_aux f m h l` returns the first `m` elements of `of_fn f` appended to `l` -/ def of_fn_aux {n} (f : fin n → α) : ∀ m, m ≤ n → list α → list α | 0 h l := l | (succ m) h l := of_fn_aux m (le_of_lt h) (f ⟨m, h⟩ :: l) /-- `of_fn f` with `f : fin n → α` returns the list whose ith element is `f i` `of_fun f = [f 0, f 1, ... , f(n - 1)]` -/ def of_fn {n} (f : fin n → α) : list α := of_fn_aux f n (le_refl _) [] /-- `of_fn_nth_val f i` returns `some (f i)` if `i < n` and `none` otherwise. -/ def of_fn_nth_val {n} (f : fin n → α) (i : ℕ) : option α := if h : i < n then some (f ⟨i, h⟩) else none /-- `disjoint l₁ l₂` means that `l₁` and `l₂` have no elements in common. -/ def disjoint (l₁ l₂ : list α) : Prop := ∀ ⦃a⦄, a ∈ l₁ → a ∈ l₂ → false section pairwise variables (R : α → α → Prop) /-- `pairwise R l` means that all the elements with earlier indexes are `R`-related to all the elements with later indexes. pairwise R [1, 2, 3] ↔ R 1 2 ∧ R 1 3 ∧ R 2 3 For example if `R = (≠)` then it asserts `l` has no duplicates, and if `R = (<)` then it asserts that `l` is (strictly) sorted. -/ inductive pairwise : list α → Prop | nil : pairwise [] | cons : ∀ {a : α} {l : list α}, (∀ a' ∈ l, R a a') → pairwise l → pairwise (a::l) variables {R} @[simp] theorem pairwise_cons {a : α} {l : list α} : pairwise R (a::l) ↔ (∀ a' ∈ l, R a a') ∧ pairwise R l := ⟨λ p, by cases p with a l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩ attribute [simp] pairwise.nil instance decidable_pairwise [decidable_rel R] (l : list α) : decidable (pairwise R l) := by induction l with hd tl ih; [exact is_true pairwise.nil, exactI decidable_of_iff' _ pairwise_cons] end pairwise /-- `pw_filter R l` is a maximal sublist of `l` which is `pairwise R`. `pw_filter (≠)` is the erase duplicates function (cf. `erase_dup`), and `pw_filter (<)` finds a maximal increasing subsequence in `l`. For example, pw_filter (<) [0, 1, 5, 2, 6, 3, 4] = [0, 1, 2, 3, 4] -/ def pw_filter (R : α → α → Prop) [decidable_rel R] : list α → list α | [] := [] | (x :: xs) := let IH := pw_filter xs in if ∀ y ∈ IH, R x y then x :: IH else IH section chain variable (R : α → α → Prop) /-- `chain R a l` means that `R` holds between adjacent elements of `a::l`. chain R a [b, c, d] ↔ R a b ∧ R b c ∧ R c d -/ inductive chain : α → list α → Prop | nil {a : α} : chain a [] | cons : ∀ {a b : α} {l : list α}, R a b → chain b l → chain a (b::l) /-- `chain' R l` means that `R` holds between adjacent elements of `l`. chain' R [a, b, c, d] ↔ R a b ∧ R b c ∧ R c d -/ def chain' : list α → Prop | [] := true | (a :: l) := chain R a l variable {R} @[simp] theorem chain_cons {a b : α} {l : list α} : chain R a (b::l) ↔ R a b ∧ chain R b l := ⟨λ p, by cases p with _ a b l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩ attribute [simp] chain.nil instance decidable_chain [decidable_rel R] (a : α) (l : list α) : decidable (chain R a l) := by induction l generalizing a; simp only [chain.nil, chain_cons]; resetI; apply_instance instance decidable_chain' [decidable_rel R] (l : list α) : decidable (chain' R l) := by cases l; dunfold chain'; apply_instance end chain /-- `nodup l` means that `l` has no duplicates, that is, any element appears at most once in the list. It is defined as `pairwise (≠)`. -/ def nodup : list α → Prop := pairwise (≠) instance nodup_decidable [decidable_eq α] : ∀ l : list α, decidable (nodup l) := list.decidable_pairwise /-- `erase_dup l` removes duplicates from `l` (taking only the first occurrence). Defined as `pw_filter (≠)`. erase_dup [1, 0, 2, 2, 1] = [0, 2, 1] -/ def erase_dup [decidable_eq α] : list α → list α := pw_filter (≠) /-- `range' s n` is the list of numbers `[s, s+1, ..., s+n-1]`. It is intended mainly for proving properties of `range` and `iota`. -/ @[simp] def range' : ℕ → ℕ → list ℕ | s 0 := [] | s (n+1) := s :: range' (s+1) n /-- Drop `none`s from a list, and replace each remaining `some a` with `a`. -/ def reduce_option {α} : list (option α) → list α := list.filter_map id /-- `ilast' x xs` returns the last element of `xs` if `xs` is non-empty; it returns `x` otherwise -/ @[simp] def ilast' {α} : α → list α → α | a [] := a | a (b::l) := ilast' b l /-- `last' xs` returns the last element of `xs` if `xs` is non-empty; it returns `none` otherwise -/ @[simp] def last' {α} : list α → option α | [] := none | [a] := some a | (b::l) := last' l /-- `rotate l n` rotates the elements of `l` to the left by `n` rotate [0, 1, 2, 3, 4, 5] 2 = [2, 3, 4, 5, 0, 1] -/ def rotate (l : list α) (n : ℕ) : list α := let (l₁, l₂) := list.split_at (n % l.length) l in l₂ ++ l₁ /-- rotate' is the same as `rotate`, but slower. Used for proofs about `rotate`-/ def rotate' : list α → ℕ → list α | [] n := [] | l 0 := l | (a::l) (n+1) := rotate' (l ++ [a]) n section choose variables (p : α → Prop) [decidable_pred p] (l : list α) /-- Given a decidable predicate `p` and a proof of existence of `a ∈ l` such that `p a`, choose the first element with this property. This version returns both `a` and proofs of `a ∈ l` and `p a`. -/ def choose_x : Π l : list α, Π hp : (∃ a, a ∈ l ∧ p a), { a // a ∈ l ∧ p a } | [] hp := false.elim (exists.elim hp (assume a h, not_mem_nil a h.left)) | (l :: ls) hp := if pl : p l then ⟨l, ⟨or.inl rfl, pl⟩⟩ else let ⟨a, ⟨a_mem_ls, pa⟩⟩ := choose_x ls (hp.imp (λ b ⟨o, h₂⟩, ⟨o.resolve_left (λ e, pl $ e ▸ h₂), h₂⟩)) in ⟨a, ⟨or.inr a_mem_ls, pa⟩⟩ /-- Given a decidable predicate `p` and a proof of existence of `a ∈ l` such that `p a`, choose the first element with this property. This version returns `a : α`, and properties are given by `choose_mem` and `choose_property`. -/ def choose (hp : ∃ a, a ∈ l ∧ p a) : α := choose_x p l hp end choose /-- Filters and maps elements of a list -/ def mmap_filter {m : Type → Type v} [monad m] {α β} (f : α → m (option β)) : list α → m (list β) | [] := return [] | (h :: t) := do b ← f h, t' ← t.mmap_filter, return $ match b with none := t' | (some x) := x::t' end /-- `mmap_upper_triangle f l` calls `f` on all elements in the upper triangular part of `l × l`. That is, for each `e ∈ l`, it will run `f e e` and then `f e e'` for each `e'` that appears after `e` in `l`. Example: suppose `l = [1, 2, 3]`. `mmap_upper_triangle f l` will produce the list `[f 1 1, f 1 2, f 1 3, f 2 2, f 2 3, f 3 3]`. -/ def mmap_upper_triangle {m} [monad m] {α β : Type u} (f : α → α → m β) : list α → m (list β) | [] := return [] | (h::t) := do v ← f h h, l ← t.mmap (f h), t ← t.mmap_upper_triangle, return $ (v::l) ++ t /-- `mmap'_diag f l` calls `f` on all elements in the upper triangular part of `l × l`. That is, for each `e ∈ l`, it will run `f e e` and then `f e e'` for each `e'` that appears after `e` in `l`. Example: suppose `l = [1, 2, 3]`. `mmap'_diag f l` will evaluate, in this order, `f 1 1`, `f 1 2`, `f 1 3`, `f 2 2`, `f 2 3`, `f 3 3`. -/ def mmap'_diag {m} [monad m] {α} (f : α → α → m unit) : list α → m unit | [] := return () | (h::t) := f h h >> t.mmap' (f h) >> t.mmap'_diag protected def traverse {F : Type u → Type v} [applicative F] {α β : Type*} (f : α → F β) : list α → F (list β) | [] := pure [] | (x :: xs) := list.cons <$> f x <*> traverse xs /-- `get_rest l l₁` returns `some l₂` if `l = l₁ ++ l₂`. If `l₁` is not a prefix of `l`, returns `none` -/ def get_rest [decidable_eq α] : list α → list α → option (list α) | l [] := some l | [] _ := none | (x::l) (y::l₁) := if x = y then get_rest l l₁ else none /-- `list.slice n m xs` removes a slice of length `m` at index `n` in list `xs`. -/ def slice {α} : ℕ → ℕ → list α → list α | 0 n xs := xs.drop n | (succ n) m [] := [] | (succ n) m (x :: xs) := x :: slice n m xs /-- Left-biased version of `list.map₂`. `map₂_left' f as bs` applies `f` to each pair of elements `aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, `f` is applied to `none` for the remaining `aᵢ`. Returns the results of the `f` applications and the remaining `bs`. ``` map₂_left' prod.mk [1, 2] ['a'] = ([(1, some 'a'), (2, none)], []) map₂_left' prod.mk [1] ['a', 'b'] = ([(1, some 'a')], ['b']) ``` -/ @[simp] def map₂_left' (f : α → option β → γ) : list α → list β → (list γ × list β) | [] bs := ([], bs) | (a :: as) [] := ((a :: as).map (λ a, f a none), []) | (a :: as) (b :: bs) := let rec := map₂_left' as bs in (f a (some b) :: rec.fst, rec.snd) /-- Right-biased version of `list.map₂`. `map₂_right' f as bs` applies `f` to each pair of elements `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, `f` is applied to `none` for the remaining `bᵢ`. Returns the results of the `f` applications and the remaining `as`. ``` map₂_right' prod.mk [1] ['a', 'b'] = ([(some 1, 'a'), (none, 'b')], []) map₂_right' prod.mk [1, 2] ['a'] = ([(some 1, 'a')], [2]) ``` -/ def map₂_right' (f : option α → β → γ) (as : list α) (bs : list β) : (list γ × list α) := map₂_left' (flip f) bs as /-- Left-biased version of `list.zip`. `zip_left' as bs` returns the list of pairs `(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, the remaining `aᵢ` are paired with `none`. Also returns the remaining `bs`. ``` zip_left' [1, 2] ['a'] = ([(1, some 'a'), (2, none)], []) zip_left' [1] ['a', 'b'] = ([(1, some 'a')], ['b']) zip_left' = map₂_left' prod.mk ``` -/ def zip_left' : list α → list β → list (α × option β) × list β := map₂_left' prod.mk /-- Right-biased version of `list.zip`. `zip_right' as bs` returns the list of pairs `(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, the remaining `bᵢ` are paired with `none`. Also returns the remaining `as`. ``` zip_right' [1] ['a', 'b'] = ([(some 1, 'a'), (none, 'b')], []) zip_right' [1, 2] ['a'] = ([(some 1, 'a')], [2]) zip_right' = map₂_right' prod.mk ``` -/ def zip_right' : list α → list β → list (option α × β) × list α := map₂_right' prod.mk /-- Left-biased version of `list.map₂`. `map₂_left f as bs` applies `f` to each pair `aᵢ ∈ as` and `bᵢ ‌∈ bs`. If `bs` is shorter than `as`, `f` is applied to `none` for the remaining `aᵢ`. ``` map₂_left prod.mk [1, 2] ['a'] = [(1, some 'a'), (2, none)] map₂_left prod.mk [1] ['a', 'b'] = [(1, some 'a')] map₂_left f as bs = (map₂_left' f as bs).fst ``` -/ @[simp] def map₂_left (f : α → option β → γ) : list α → list β → list γ | [] _ := [] | (a :: as) [] := (a :: as).map (λ a, f a none) | (a :: as) (b :: bs) := f a (some b) :: map₂_left as bs /-- Right-biased version of `list.map₂`. `map₂_right f as bs` applies `f` to each pair `aᵢ ∈ as` and `bᵢ ‌∈ bs`. If `as` is shorter than `bs`, `f` is applied to `none` for the remaining `bᵢ`. ``` map₂_right prod.mk [1, 2] ['a'] = [(some 1, 'a')] map₂_right prod.mk [1] ['a', 'b'] = [(some 1, 'a'), (none, 'b')] map₂_right f as bs = (map₂_right' f as bs).fst ``` -/ def map₂_right (f : option α → β → γ) (as : list α) (bs : list β) : list γ := map₂_left (flip f) bs as /-- Left-biased version of `list.zip`. `zip_left as bs` returns the list of pairs `(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, the remaining `aᵢ` are paired with `none`. ``` zip_left [1, 2] ['a'] = [(1, some 'a'), (2, none)] zip_left [1] ['a', 'b'] = [(1, some 'a')] zip_left = map₂_left prod.mk ``` -/ def zip_left : list α → list β → list (α × option β) := map₂_left prod.mk /-- Right-biased version of `list.zip`. `zip_right as bs` returns the list of pairs `(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, the remaining `bᵢ` are paired with `none`. ``` zip_right [1, 2] ['a'] = [(some 1, 'a')] zip_right [1] ['a', 'b'] = [(some 1, 'a'), (none, 'b')] zip_right = map₂_right prod.mk ``` -/ def zip_right : list α → list β → list (option α × β) := map₂_right prod.mk /-- If all elements of `xs` are `some xᵢ`, `all_some xs` returns the `xᵢ`. Otherwise it returns `none`. ``` all_some [some 1, some 2] = some [1, 2] all_some [some 1, none ] = none ``` -/ def all_some : list (option α) → option (list α) | [] := some [] | (some a :: as) := cons a <$> all_some as | (none :: as) := none /-- `fill_nones xs ys` replaces the `none`s in `xs` with elements of `ys`. If there are not enough `ys` to replace all the `none`s, the remaining `none`s are dropped from `xs`. ``` fill_nones [none, some 1, none, none] [2, 3] = [2, 1, 3] ``` -/ def fill_nones {α} : list (option α) → list α → list α | [] _ := [] | (some a :: as) as' := a :: fill_nones as as' | (none :: as) [] := as.reduce_option | (none :: as) (a :: as') := a :: fill_nones as as' /-- `take_list as ns` extracts successive sublists from `as`. For `ns = n₁ ... nₘ`, it first takes the `n₁` initial elements from `as`, then the next `n₂` ones, etc. It returns the sublists of `as` -- one for each `nᵢ` -- and the remaining elements of `as`. If `as` does not have at least as many elements as the sum of the `nᵢ`, the corresponding sublists will have less than `nᵢ` elements. ``` take_list ['a', 'b', 'c', 'd', 'e'] [2, 1, 1] = ([['a', 'b'], ['c'], ['d']], ['e']) take_list ['a', 'b'] [3, 1] = ([['a', 'b'], []], []) ``` -/ def take_list {α} : list α → list ℕ → list (list α) × list α | xs [] := ([], xs) | xs (n :: ns) := let ⟨xs₁, xs₂⟩ := xs.split_at n in let ⟨xss, rest⟩ := take_list xs₂ ns in (xs₁ :: xss, rest) /-- `to_rbmap as` is the map that associates each index `i` of `as` with the corresponding element of `as`. ``` to_rbmap ['a', 'b', 'c'] = rbmap_of [(0, 'a'), (1, 'b'), (2, 'c')] ``` -/ def to_rbmap : list α → rbmap ℕ α := foldl_with_index (λ i mapp a, mapp.insert i a) (mk_rbmap ℕ α) /-- `to_rb_map as` is the map that associates each index `i` of `as` with the corresponding element of `as`. ``` to_rb_map ['a', 'b', 'c'] = rb_map.of_list [(0, 'a'), (1, 'b'), (2, 'c')] ``` -/ meta def to_rb_map {α : Type} : list α → rb_map ℕ α := foldl_with_index (λ i mapp a, mapp.insert i a) mk_rb_map /-- `xs.to_chunks n` splits the list into sublists of size at most `n`, such that `(xs.to_chunks n).join = xs`. TODO: make non-meta; currently doesn't terminate, e.g. ``` #eval [0].to_chunks 0 ``` -/ meta def to_chunks {α} (n : ℕ) : list α → list (list α) | [] := [] | xs := xs.take n :: (xs.drop n).to_chunks /-- Asynchronous version of `list.map`. -/ meta def map_async_chunked {α β} (f : α → β) (xs : list α) (chunk_size := 1024) : list β := ((xs.to_chunks chunk_size).map (λ xs, task.delay (λ _, list.map f xs))).bind task.get end list
e7971677e4a35b3ede1c0b9e2f30e085648b5edc
2731214ea32f2a1a985300e281fb3117640a16c3
/portmanteau_integrals.lean
767b6ef763109d22af39d86e151a20b18b98ac6f
[ "Apache-2.0" ]
permissive
kkytola/lean_portmanteau
5d6a156db959974ebc4f5bed9118a7a2438a33fa
ac55eb4e24be43032cbc082e2b68d8fb8bd63f22
refs/heads/main
1,686,107,117,334
1,625,177,052,000
1,625,177,052,000
381,514,032
1
0
null
null
null
null
UTF-8
Lean
false
false
14,695
lean
/- Copyright (c) 2021 Kalle Kytölä. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kalle Kytölä -/ import tactic import measure_theory.measurable_space import measure_theory.integration import measure_theory.bochner_integration import measure_theory.borel_space import topology.metric_space.basic import topology.instances.real import topology.instances.ennreal import order.liminf_limsup import portmanteau_limsup_lemmas import portmanteau_definitions import portmanteau_proba_lemmas import analysis.seminorm noncomputable theory open set open classical open measure_theory open measurable_space open metric_space open borel_space open filter open order open_locale topological_space ennreal big_operators namespace portmanteau section portmanteau_integrals variables {α : Type} [topological_space α] abbreviation R_integrate (f : α → ℝ) (μ : borel_proba α) := @integral α ℝ (borel(α)) _ _ _ _ _ _ μ f abbreviation R_abs_nn : ℝ → nnreal := λ x , nnnorm x abbreviation R_abs_enn : ℝ → ennreal := λ x , ennreal.of_nnreal_hom (nnnorm x) --ennreal.of_real(abs(x)) lemma R_abs_enn_le_of_abs_le {x c : ℝ} (h : abs(x) ≤ c) : R_abs_enn(x) ≤ ennreal.of_real(c) := begin have c_nn : 0 ≤ c := le_trans (abs_nonneg x) h, have eq := real.coe_to_nnreal c c_nn , set c' := c.to_nnreal with hc' , have h₁ : R_abs_nn(x) ≤ c' := (real.le_to_nnreal_iff_coe_le c_nn).mpr h , exact (with_top.le_coe rfl).mpr h₁ , end -- TODO: Should state for finite measures? lemma integrable_of_bdd_realval {β : Type*} {mβ : measurable_space β} (μ : measure β) [μ_fin : probability_measure μ] (f : β → ℝ) (f_bdd : bdd_Rval f) (f_mble : @ae_measurable β ℝ mβ _ f μ) : integrable f μ := begin cases f_bdd with c hc , set f' := R_abs_enn ∘ f with hf' , suffices : lintegral μ f' < ⊤ , { rw hf' at this , exact ⟨ f_mble , this ⟩ , } , have bdd' : f' ≤ (λ b , ennreal.of_real(c)) , { rw hf' , intros b , dsimp , specialize hc b , exact R_abs_enn_le_of_abs_le hc , } , have integr_bdd := lintegral_mono bdd' , set c' := ennreal.of_real(c) with hc' , have const_integr : lintegral μ (λ b , c') = c' * (μ(univ)) , { rw ← set_lintegral_const univ c' , simp , } , have total : c' * (μ(univ)) < ⊤ , { rw (proba_muniv μ) , simp , } , rw ← const_integr at total , exact lt_of_le_of_lt integr_bdd total , end -- TODO: Should state for finite measures? lemma bdd_integral_of_bdd_ennval {β : Type*} {mβ : measurable_space β} (μ : measure β) [μ_fin : probability_measure μ] (f : β → ennreal) (f_bdd : bdd_ennval f) : lintegral μ f < ⊤ := begin cases f_bdd with c hc , have f_le_c : f ≤ λ x , c := hc , have integr_f_le := @lintegral_mono β mβ μ _ _ f_le_c , simp [proba_muniv] at integr_f_le , exact lt_of_le_of_lt integr_f_le (@ennreal.coe_lt_top c) , end lemma const_bdd_Rval {β : Type*} {c : ℝ} : bdd_Rval (λ (x : β) , c) := begin use abs(c) , intros x , refl , end lemma const_bdd_ennval {β : Type*} {c : nnreal} : bdd_ennval (λ (x : β) , c) := begin use c , intros x , simp only [ennreal.coe_le_coe] , end -- TODO: Should state for finite measures? lemma const_integrable {β : Type*} {mβ : measurable_space β} (μ : measure β) (μ_fin : probability_measure μ) (c : ℝ) : integrable (λ (x : β) , c) μ := begin apply integrable_const_iff.mpr , right , exact proba_finite μ univ , end lemma integral_cst {β : Type*} {mβ : measurable_space β} (μ : measure β) (μ_fin : probability_measure μ) (c : ℝ) : integral μ (λ (x : β) , c) = c := begin suffices : integral μ (λ (x : β) , c) = (μ(univ)).to_real * c, { simp [proba_muniv μ] , } , apply integral_const c , end lemma lintegral_cst {β : Type*} {mβ : measurable_space β} (μ : measure β) [μ_proba : probability_measure μ] (c : ennreal) : lintegral μ (λ (x : β) , c) = c := begin suffices : lintegral μ (λ (x : β) , c) = c * (μ(univ)) , { simp [proba_muniv μ] , } , apply lintegral_const c , end lemma integral_add_cst {β : Type*} {mβ : measurable_space β} {c : ℝ} (μ : measure β) [μ_fin : probability_measure μ] (f : β → ℝ) (f_intble: integrable f μ) : integral μ ( f + (λ (x : β) , c)) = integral μ f + c := begin have key := @integral_add β ℝ mβ _ _ _ _ _ _ f (λ (x : β) , c) μ f_intble (const_integrable μ μ_fin c) , rw integral_cst μ μ_fin c at key , exact key , end lemma lintegral_cst_sub {β : Type*} {mβ : measurable_space β} {c : ennreal} (μ : measure β) [μ_fin : probability_measure μ] (c_ne_top : c ≠ ⊤) (f : β → ennreal) (f_mble: measurable f) (f_le_c : f ≤ λ b , c) : lintegral μ ( (λ (x : β) , c) - f) = c - lintegral μ f := begin nth_rewrite 0 ←(lintegral_cst μ c) , have f_intble := bdd_integral_of_bdd_ennval μ f (bdd_ennval_of_le_cst f_le_c c_ne_top) , rw ← @lintegral_sub β mβ μ (λ (b : β) , c) f (measurable_const) f_mble f_intble (eventually_of_forall f_le_c) , refl , end lemma nnreal_integral_of_integrable_nonneg {β : Type*} {mβ : measurable_space β} (μ : measure β) (f : β → ℝ) (f_nn : 0 ≤ f) (f_intble : integrable f μ) : ennreal.of_real (integral μ f) = lintegral μ (ennreal.of_real ∘ f) := begin set g := λ (b : β) , (f(b)).to_nnreal with hg , have key := @lintegral_coe_eq_integral β mβ μ g (integrable.max_zero f_intble) , rw hg at key , set ψ : (β → nnreal) → (β → ℝ) := coe with hψ , have eq₀ : f = ψ(g) , { funext b , exact left_eq_sup.mpr (f_nn b) , } , have eq₂ : ∫ (a : β), ↑((λ (b : β), (f b).to_nnreal) a) ∂μ = integral μ (ψ(g)) := by refl , rw [eq₂ , ←eq₀] at key , rw ← key , refl , end lemma nnreal_integral_of_integrable_nonneg' {β : Type*} {mβ : measurable_space β} (μ : measure β) (f : β → ℝ) (f_nn : 0 ≤ f) (f_intble : integrable f μ) : integral μ f = (lintegral μ (ennreal.of_real ∘ f)).to_real := begin have key := nnreal_integral_of_integrable_nonneg μ f f_nn f_intble , have fin : lintegral μ (ennreal.of_real ∘ f) ≠ ⊤ , { rw ←key , exact ennreal.of_real_ne_top , } , have nn : 0 ≤ integral μ f := integral_nonneg f_nn , have eq := ennreal.to_real_of_real nn , rw key at eq , exact eq.symm , end example (s : ℕ → ℝ) (l : ℝ) (hlim : tendsto s at_top (𝓝 l)) (c : ℝ) : tendsto (λ (n : ℕ) , s(n) + c) at_top (𝓝 (l+c)) := begin exact tendsto.add_const c hlim , end lemma nonneg_of_add_abs_le (a c : ℝ) (h : abs(a) ≤ c) : 0 ≤ c + a := begin have key : c-abs(a) ≤ c+a := by linarith [neg_le.mp (neg_le_abs_self a)] , exact le_trans (sub_nonneg.mpr h) key , end private lemma portmanteau_continuous_equivalent_formulation' {μseq : ℕ → borel_proba α} {μ : borel_proba α} : portmanteau_continuous_ennval (λ n , (μseq(n) : @measure_theory.measure α (borel(α)))) μ → portmanteau_continuous_Rval (λ n , (μseq(n) : @measure_theory.measure α (borel(α)))) μ := begin intros cc_ennrealval , intros g g_cont g_bdd , have g_bdd' := g_bdd , cases g_bdd' with c hc , set h := (g + (λ x, c)) with hh , set f := λ (x : α) , ennreal.of_real (h(x)) with hf , have h_nn : 0 ≤ h , { intros x , rw hh , have samediff := nonneg_of_add_abs_le (g(x)) c (hc x) , rwa add_comm at samediff , } , have f_eq_h : f = ennreal.of_real ∘ h := by refl , have h_bdd : bdd_Rval h := bdd_Rval_add g_bdd const_bdd_Rval , have h_cont : continuous h := continuous.add g_cont (@continuous_const α ℝ _ _ c ) , have f_bdd : bdd_ennval f := bdd_ennval_of_bdd_Rval h_bdd , have f_cont : continuous f := cont_enn_of_cont_R h h_cont , specialize cc_ennrealval f f_cont f_bdd , have g_mble := continuous.borel_measurable g_cont , have h_mble := continuous.borel_measurable h_cont , have g_ae_mble := @measurable.ae_measurable α ℝ (borel(α)) _ g μ g_mble , have h_ae_mble := @measurable.ae_measurable α ℝ (borel(α)) _ h μ h_mble , have g_ae_mble_seq := λ n , @measurable.ae_measurable α ℝ (borel(α)) _ g (μseq(n)) g_mble , have h_ae_mble_seq := λ n , @measurable.ae_measurable α ℝ (borel(α)) _ h (μseq(n)) h_mble , have g_intble := @integrable_of_bdd_realval _ _ μ.val μ.prop g g_bdd g_ae_mble , have h_intble := @integrable_of_bdd_realval _ _ μ.val μ.prop h h_bdd h_ae_mble , have g_intble_seq := λ n , @integrable_of_bdd_realval _ _ (μseq(n)).val (μseq(n)).prop g g_bdd (g_ae_mble_seq n) , have h_intble_seq := λ n , @integrable_of_bdd_realval _ _ (μseq(n)).val (μseq(n)).prop h h_bdd (h_ae_mble_seq n) , suffices : lim_R (λ n , (@integral α ℝ (borel(α)) _ _ _ _ _ _ (μseq(n)) h)) (@integral α ℝ (borel(α)) _ _ _ _ _ _ μ h) , { have add_cst : (@integral α ℝ (borel(α)) _ _ _ _ _ _ μ h) = (@integral α ℝ (borel(α)) _ _ _ _ _ _ μ g) + c , { rw hh , apply @integral_add_cst _ _ _ μ.val μ.prop g g_intble , } , have add_cst_seq : (λ n , (@integral α ℝ (borel(α)) _ _ _ _ _ _ (μseq n) h)) = (λ n , (@integral α ℝ (borel(α)) _ _ _ _ _ _ (μseq n) g) + c) , { funext n , rw hh , apply @integral_add_cst _ _ _ (μseq(n)).val (μseq(n)).prop g (g_intble_seq n) , } , rw [add_cst , add_cst_seq] at this , have shift_lim := tendsto.add_const (-c) this , simp at shift_lim , exact shift_lim , } , have eq := nnreal_integral_of_integrable_nonneg' μ.val h h_nn h_intble , have eq_seq := λ n , nnreal_integral_of_integrable_nonneg' (μseq(n)).val h h_nn (h_intble_seq n) , have eq' : @integral α ℝ (borel(α)) _ _ _ _ _ _ μ h = (@lintegral α (borel(α)) μ f).to_real := eq , have eq_seq' : (λ n , @integral α ℝ (borel(α)) _ _ _ _ _ _ (μseq(n)).val h) = ennreal.to_real ∘ (λ n , (@lintegral α (borel(α)) (μseq(n)) f)) , { funext n , exact eq_seq n , } , have fin : @lintegral α (borel(α)) μ f ≠ ⊤ := ne_of_lt (@bdd_integral_of_bdd_ennval α (borel(α)) μ μ.prop f f_bdd) , have key := lim_R_of_lim_enn _ _ cc_ennrealval fin , rw ←eq' at key , rw ←eq_seq' at key , exact key , end private lemma portmanteau_continuous_equivalent_formulation'' {μseq : ℕ → (borel_proba α)} {μ : borel_proba α} : portmanteau_continuous_Rval (λ n , (μseq(n) : @measure_theory.measure α (borel(α)))) μ → portmanteau_continuous_ennval (λ n , (μseq(n) : @measure_theory.measure α (borel(α)))) μ := begin intros cc_Rval , intros f f_cont f_bdd , have f_fin_val : ∀ (x : α) , f(x) ≠ ⊤ := finval_of_bdd_ennval f_bdd , set g := λ (x : α) , ennreal.to_real (f(x)) with hg , have f_eq_g : f = ennreal.of_real ∘ g , { funext x , exact (ennreal.of_real_to_real (f_fin_val x)).symm , } , have g_nn : 0 ≤ g , { intros x , simp only [pi.zero_apply, ennreal.to_real_nonneg] , } , have g_bdd : bdd_Rval g , { cases f_bdd with c hc , use c , intros x , rw hg , specialize hc x , have abs_eq : (abs (f(x)).to_real) = g(x) := by simp only [ennreal.to_real_nonneg, abs_eq_self] , rw hg at abs_eq , dsimp at * , rw abs_eq , exact ennreal.to_real_le_coe_of_le_coe hc , } , have g_cont : continuous g := cont_R_of_cont_bdd_enn f f_cont f_bdd , have g_mble := continuous.borel_measurable g_cont , have g_ae_mble := @measurable.ae_measurable α ℝ (borel(α)) _ g μ g_mble , have g_ae_mble_seq := λ n , @measurable.ae_measurable α ℝ (borel(α)) _ g (μseq(n)) g_mble , have g_intble := @integrable_of_bdd_realval _ _ μ.val μ.prop g g_bdd g_ae_mble , have g_intble_seq := λ n , @integrable_of_bdd_realval _ _ (μseq(n)).val (μseq(n)).prop g g_bdd (g_ae_mble_seq n) , have eq := nnreal_integral_of_integrable_nonneg μ.val g g_nn g_intble , have eq_seq := λ n , nnreal_integral_of_integrable_nonneg (μseq(n)).val g g_nn (g_intble_seq n) , rw ← f_eq_g at * , have eq' : ennreal.of_real (@integral α ℝ (borel(α)) _ _ _ _ _ _ μ g) = @lintegral α (borel(α)) μ f := eq , have eq_seq' : (λ n , ennreal.of_real (@integral α ℝ (borel(α)) _ _ _ _ _ _ (μseq n) g)) = (λ n , @lintegral α (borel(α)) (μseq n) f) , -- := by simp [eq_seq] , { funext n , exact eq_seq n , } , rw ←eq' , rw ←eq_seq' , specialize cc_Rval g g_cont g_bdd , exact lim_enn_of_lim_R cc_Rval , end /-- The usual definition of weak convergence of probability measures is given in terms of sequences of probability measures: it is the requirement that the integrals of all continuous bounded functions against members of the sequence converge. This characterization is shown in `weak_conv_seq_iff`. -/ theorem weak_conv_seq_iff {α : Type*} [topological_space α] {μseq : ℕ → borel_proba α} {μ : borel_proba α} : tendsto μseq at_top (𝓝 μ) ↔ ( ∀ (f : α → ℝ) , continuous f → bdd_Rval f → tendsto (λ n, (@integral α ℝ (borel(α)) _ _ _ _ _ _ (μseq(n)) f)) at_top (𝓝 (@integral α ℝ (borel(α)) _ _ _ _ _ _ μ f)) ) := begin split , { intros weak_conv , have key := weak_conv_seq_iff'.mp weak_conv , have key' : portmanteau_continuous_ennval (λ n , (μseq(n) : @measure_theory.measure α (borel(α)))) μ , { intros f f_cont f_bdd , exact key ⟨ f , ⟨ f_cont , f_bdd ⟩ ⟩ , } , exact portmanteau_continuous_equivalent_formulation' key' , } , { intros h , have key := portmanteau_continuous_equivalent_formulation'' h , apply weak_conv_seq_iff'.mpr , intros f , exact key f.val f.prop.1 f.prop.2 , } , end theorem weak_conv_seq_iff_portmanteau_continuous_Rval {α : Type*} [topological_space α] {μseq : ℕ → borel_proba α} {μ : borel_proba α} : tendsto μseq at_top (𝓝 μ) ↔ portmanteau_continuous_Rval (λ n , (μseq(n) : @measure_theory.measure α (borel(α)))) μ := weak_conv_seq_iff theorem weak_conv_seq_iff_portmanteau_continuous_ennval {α : Type*} [topological_space α] {μseq : ℕ → borel_proba α} {μ : borel_proba α} : tendsto μseq at_top (𝓝 μ) ↔ portmanteau_continuous_ennval (λ n , (μseq(n) : @measure_theory.measure α (borel(α)))) μ := begin split , { intros h , exact portmanteau_continuous_equivalent_formulation'' (weak_conv_seq_iff_portmanteau_continuous_Rval.mp h) , } , { intros h , exact weak_conv_seq_iff_portmanteau_continuous_Rval.mpr (portmanteau_continuous_equivalent_formulation' h) , } , end end portmanteau_integrals end portmanteau
4315dfd570ae36b74b3b6133e623ec77b7465049
efce24474b28579aba3272fdb77177dc2b11d7aa
/src/homotopy_theory/topological_spaces/cylinder.lean
1833aad90bd8ceacd18ed3f866cd996d0a32833d
[ "Apache-2.0" ]
permissive
rwbarton/lean-homotopy-theory
cff499f24268d60e1c546e7c86c33f58c62888ed
39e1b4ea1ed1b0eca2f68bc64162dde6a6396dee
refs/heads/lean-3.4.2
1,622,711,883,224
1,598,550,958,000
1,598,550,958,000
136,023,667
12
6
Apache-2.0
1,573,187,573,000
1,528,116,262,000
Lean
UTF-8
Lean
false
false
2,524
lean
import topology.instances.real import category_theory.adjunction import tactic.norm_num import homotopy_theory.formal.cylinder.definitions import .category import .exponentiable noncomputable theory open category_theory open homotopy_theory.cylinder namespace homotopy_theory.topological_spaces -- TODO: Universes. We may eventually want to do homotopy theory in -- Top.{u} for arbitrary u. The type ℝ and its associated structures -- live only in Type 0, and transferring all that structure across -- `ulift` sounds tedious. Maybe it'd be better to think of Top.{u} as -- tensored over Top.{0} and use this structure to define IX = X × I -- rather than trying to transfer the object I to Top.{u} (and using -- the product in Top.{u} to define IX). -- -- For now, we stick to Top.{0}. local notation `Top` := Top.{0} -- The standard unit interval [0,1]. def I01 : Top := Top.mk_ob { t : ℝ // 0 ≤ t ∧ t ≤ 1 } instance : has_zero I01 := ⟨⟨0, by norm_num, by norm_num⟩⟩ instance : has_one I01 := ⟨⟨1, by norm_num, by norm_num⟩⟩ -- This is *really* slow. Why? -- instance : t2_space I01 := by dsimp [I01, Top.mk_ob]; apply_instance instance : t2_space I01 := by apply subtype.t2_space; apply_instance instance : compact_space I01 := ⟨compact_iff_compact_univ.mp compact_Icc⟩ -- The endpoint of [0,1] corresponding to an abstract endpoint. def I01_of_endpoint : endpoint → I01 | 0 := 0 | 1 := 1 -- The "time-reversal" function on [0,1]. def I01.v : I01 ⟶ I01 := Top.mk_hom (λ t, ⟨1 - t.val, sub_nonneg_of_le t.property.right, sub_le_self 1 t.property.left⟩) (by continuity!) instance : has_cylinder_with_involution Top := { I := -×I01, i := λ ε, Top.prod_pt_trans (I01_of_endpoint ε), p := Top.pr₁_trans, pi := assume ε, rfl, v := Top.product_by_trans I01.v, vi := assume ε, begin ext X p, { refl }, cases ε; apply subtype.eq, { change (1 : ℝ) - 0 = 1, norm_num }, { change (1 : ℝ) - 1 = 0, norm_num } end, vv := begin ext X p, { refl }, { rcases p with ⟨x, t, h⟩, change subtype.mk (1 - (1 - t)) _ = subtype.mk t _, simp [sub_sub_self] } end, pv := rfl } instance : cylinder_has_interchange.{0} Top := { T := { app := λ X, Top.mk_hom (λ q, ((q.1.1, q.2), q.1.2)) (by continuity!) }, Ti := by intros ε X; ext p; refl, TIi := by intros ε X; ext p; cases p; refl } instance I.is_left_adjoint : is_left_adjoint (I : Top ↝ Top) := by unfold I; apply_instance end homotopy_theory.topological_spaces
db7974b620da5f8741a80f015ebfb6322737f674
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/finset/nat_antidiagonal.lean
b74d438a74abadeeec10d540af3f0f0e6c9036ae
[ "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,456
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import data.finset.card import data.multiset.nat_antidiagonal /-! # Antidiagonals in ℕ × ℕ as finsets This file defines the antidiagonals of ℕ × ℕ as finsets: the `n`-th antidiagonal is the finset of pairs `(i, j)` such that `i + j = n`. This is useful for polynomial multiplication and more generally for sums going from `0` to `n`. ## Notes This refines files `data.list.nat_antidiagonal` and `data.multiset.nat_antidiagonal`. -/ namespace finset namespace nat /-- The antidiagonal of a natural number `n` is the finset of pairs `(i, j)` such that `i + j = n`. -/ def antidiagonal (n : ℕ) : finset (ℕ × ℕ) := ⟨multiset.nat.antidiagonal n, multiset.nat.nodup_antidiagonal n⟩ /-- A pair (i, j) is contained in the antidiagonal of `n` if and only if `i + j = n`. -/ @[simp] lemma mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} : x ∈ antidiagonal n ↔ x.1 + x.2 = n := by rw [antidiagonal, mem_def, multiset.nat.mem_antidiagonal] /-- The cardinality of the antidiagonal of `n` is `n + 1`. -/ @[simp] lemma card_antidiagonal (n : ℕ) : (antidiagonal n).card = n+1 := by simp [antidiagonal] /-- The antidiagonal of `0` is the list `[(0, 0)]` -/ @[simp] lemma antidiagonal_zero : antidiagonal 0 = {(0, 0)} := rfl lemma antidiagonal_succ {n : ℕ} : antidiagonal (n + 1) = insert (0, n + 1) ((antidiagonal n).map (function.embedding.prod_map ⟨nat.succ, nat.succ_injective⟩ (function.embedding.refl _))) := begin apply eq_of_veq, rw [insert_val_of_not_mem, map_val], {apply multiset.nat.antidiagonal_succ}, { intro con, rcases mem_map.1 con with ⟨⟨a,b⟩, ⟨h1, h2⟩⟩, simp only [prod.mk.inj_iff, function.embedding.coe_prod_map, prod.map_mk] at h2, apply nat.succ_ne_zero a h2.1, } end lemma map_swap_antidiagonal {n : ℕ} : (antidiagonal n).map ⟨prod.swap, prod.swap_right_inverse.injective⟩ = antidiagonal n := begin ext, simp only [exists_prop, mem_map, mem_antidiagonal, prod.exists], rw add_comm, split, { rintro ⟨b, c, ⟨rfl, rfl⟩⟩, simp }, { rintro rfl, use [a.snd, a.fst], simp } end /-- A point in the antidiagonal is determined by its first co-ordinate. -/ lemma antidiagonal_congr {n : ℕ} {p q : ℕ × ℕ} (hp : p ∈ antidiagonal n) (hq : q ∈ antidiagonal n) : p = q ↔ p.fst = q.fst := begin refine ⟨congr_arg prod.fst, (λ h, prod.ext h ((add_right_inj q.fst).mp _))⟩, rw mem_antidiagonal at hp hq, rw [hq, ← h, hp], end lemma antidiagonal.fst_le {n : ℕ} {kl : ℕ × ℕ} (hlk : kl ∈ antidiagonal n) : kl.1 ≤ n := begin rw le_iff_exists_add, use kl.2, rwa [mem_antidiagonal, eq_comm] at hlk end lemma antidiagonal.snd_le {n : ℕ} {kl : ℕ × ℕ} (hlk : kl ∈ antidiagonal n) : kl.2 ≤ n := begin rw le_iff_exists_add, use kl.1, rwa [mem_antidiagonal, eq_comm, add_comm] at hlk end lemma filter_fst_eq_antidiagonal (n m : ℕ) : filter (λ x : ℕ × ℕ, x.fst = m) (antidiagonal n) = if m ≤ n then {(m, n - m)} else ∅ := begin ext ⟨x, y⟩, simp only [mem_filter, nat.mem_antidiagonal], split_ifs with h h, { simp [and_comm, eq_tsub_iff_add_eq_of_le h, add_comm] {contextual := tt} }, { rw not_le at h, simp only [not_mem_empty, iff_false, not_and], exact λ hn, ne_of_lt (lt_of_le_of_lt (le_self_add.trans hn.le) h) } end lemma filter_snd_eq_antidiagonal (n m : ℕ) : filter (λ x : ℕ × ℕ, x.snd = m) (antidiagonal n) = if m ≤ n then {(n - m, m)} else ∅ := begin have : (λ (x : ℕ × ℕ), x.snd = m) ∘ prod.swap = (λ (x : ℕ × ℕ), x.fst = m), { ext, simp }, rw ←map_swap_antidiagonal, simp [map_filter, this, filter_fst_eq_antidiagonal, apply_ite (finset.map _)] end section equiv_prod /-- The disjoint union of antidiagonals `Σ (n : ℕ), antidiagonal n` is equivalent to the product `ℕ × ℕ`. This is such an equivalence, obtained by mapping `(n, (k, l))` to `(k, l)`. -/ @[simps] def sigma_antidiagonal_equiv_prod : (Σ (n : ℕ), antidiagonal n) ≃ ℕ × ℕ := { to_fun := λ x, x.2, inv_fun := λ x, ⟨x.1 + x.2, x, mem_antidiagonal.mpr rfl⟩, left_inv := begin rintros ⟨n, ⟨k, l⟩, h⟩, rw mem_antidiagonal at h, exact sigma.subtype_ext h rfl, end, right_inv := λ x, rfl } end equiv_prod end nat end finset
8d85afb87c79ac485382291fb089c6ebca45ffd8
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/logic/unnamed_148.lean
5da766114341cb9a911d201cb10720dd4c716410
[]
no_license
jamescheuk91/mathematics_in_lean
09f1f87d2b0dce53464ff0cbe592c568ff59cf5e
4452499264e2975bca2f42565c0925506ba5dda3
refs/heads/master
1,679,716,410,967
1,613,957,947,000
1,613,957,947,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
369
lean
import data.real.basic -- BEGIN lemma my_lemma : ∀ {x y ε : ℝ}, 0 < ε → ε ≤ 1 → abs x < ε → abs y < ε → abs (x * y) < ε := begin intros x y ε epos ele1 xlt ylt, calc abs (x * y) = abs x * abs y : sorry ... ≤ abs x * ε : sorry ... < 1 * ε : sorry ... = ε : sorry end -- END
120a70cf0959c70770d4efd1d862b49dd5faa751
618003631150032a5676f229d13a079ac875ff77
/src/tactic/pi_instances.lean
e721cf8d72ec9a5723d59f602b5d5633e9a03cee
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
2,018
lean
/- Copyright (c) 2018 Simon Hudon All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon -/ import order.basic /-! # `pi_instance` Automation for creating instances of mathematical structures for pi types -/ namespace tactic open tactic.interactive /-- Attempt to clear a goal obtained by refining a `pi_instance` goal. -/ meta def pi_instance_derive_field : tactic unit := do b ← target >>= is_prop, field ← get_current_field, if b then do vs ← introv [] <|> pure [], hs ← intros <|> pure [], reset_instance_cache, xn ← get_unused_name, try (() <$ ext1 [rcases_patt.one xn] <|> () <$ intro xn), xv ← option.iget <$> try_core (get_local xn), applyc field, hs.mmap (λ h, try $ () <$ (to_expr ``(congr_fun %%h %%xv) >>= apply) <|> () <$ apply (h xv) <|> () <$ (to_expr ``(set.mem_image_of_mem _ %%h) >>= apply) <|> () <$ solve_by_elim), return () else focus1 $ do expl_arity ← mk_const field >>= get_expl_arity, xs ← (list.iota expl_arity).mmap $ λ _, intro1, x ← intro1, applyc field, xs.mmap' (λ h, try $ () <$ (apply (h x) <|> apply h) <|> refine ``(set.image ($ %%x) %%h)) <|> fail "args", return () /-- `pi_instance` constructs an instance of `my_class (Π i : I, f i)` where we know `Π i, my_class (f i)`. If an order relation is required, it defaults to `pi.partial_order`. Any field of the instance that `pi_instance` cannot construct is left untouched and generated as a new goal. -/ meta def pi_instance : tactic unit := refine_struct ``( { ..pi.partial_order, .. } ); propagate_tags (try $ pi_instance_derive_field >> done) run_cmd add_interactive [`pi_instance] add_tactic_doc { name := "pi_instance", category := doc_category.tactic, decl_names := [`tactic.interactive.pi_instance], tags := ["type class"] } end tactic
8a540e131c544b067de95e1dbe0a67a1808366c0
ec5e5a9dbe7f60fa5784d15211d8bf24ada0825c
/src/Parser.lean
d0f644101aa5c971de62f2900c0e48623a367047
[]
no_license
pnwamk/lean-llvm
fcd9a828e52e80eb197f7d9032b3846f2e09ef74
ebc3bca9a57a6aef29529d46394f560398fb5c9c
refs/heads/master
1,668,418,078,706
1,593,548,643,000
1,593,548,643,000
258,617,753
0
0
null
1,587,760,298,000
1,587,760,298,000
null
UTF-8
Lean
false
false
3,992
lean
import Init.Control.Alternative import Init.Control.Applicative import Init.Control.Monad import Init.Data.Char namespace Nat. def fromDigitsAux : List Nat → Nat → Nat | [], n => n | d::ds, n => fromDigitsAux ds (n*10 + d). def fromDigits (ds:List Nat) := fromDigitsAux ds 0. end Nat. structure parse (α:Type) := (runParse : ∀(z:Type), (List String → String → z) /- global failure continuation -/ → (List String → String → z) /- local failure continuation -/ → (α → List String → String → z) /- success continuation -/ → List String → String → z). namespace parse. instance monad : Monad parse := { bind := λa b mx mf => parse.mk (λz kerr kfail k => mx.runParse z kerr kfail (λx => (mf x).runParse z kerr kfail k)) , pure := λa x => parse.mk (λz kerr kfail k => k x) }. instance alternative : Alternative parse := { failure := λa => parse.mk (λz kerr kfail k => kfail) , orelse := λa ma mb => parse.mk (λz kerr kfail k stk str => ma.runParse z kerr (λ_ _ => mb.runParse z kerr kfail k stk str) k stk str) }. def run {α} (m:parse α) : String → Sum (List String × String) α := m.runParse _ (λstk str => Sum.inl (stk,str)) (λstk str => Sum.inl (stk,str)) (λx stk str => if str.isEmpty then Sum.inr x else Sum.inl (stk,str)) []. def describe {α} (msg:String) (m:parse α) : parse α := parse.mk (λz kerr kfail k stk str => m.runParse z kerr kfail (λx _ str' => k x stk str') (msg::stk) str). def text (x:String) : parse String := parse.mk (λz kerr kfail k stk str => if String.isPrefixOf x str then k x stk (String.drop str (x.length)) else kfail (("expected string: " ++ x) :: stk) str). def char (p:Char → Bool) : parse Char := parse.mk (λz kerr kfail k stk str => let c := str.toSubstring.front; if ¬str.isEmpty ∧ p c then k c stk (String.drop str 1) else kfail stk str). def chars (p:Char → Bool) : parse String := parse.mk (λz kerr kfail k stk str => let str' := String.takeWhile str p; k str' stk (String.drop str (String.length str'))). def digit : parse Nat := describe "digit" $ do c <- char Char.isDigit; pure (c.val.toNat - ('0'.val.toNat)) def commit {α} (m:parse α) : parse α := parse.mk (λz kerr _kfail k => m.runParse z kerr kerr k). def delimit {α} (m:parse α) : parse α := parse.mk (λz kerr kfail k => m.runParse z kfail kfail k) def opt {α} (default:α) (m:parse α) : parse α := parse.mk (λz kerr _kfail k stk str => m.runParse z kerr (λ_ _ => k default stk str) k stk str). def opt' {α} (m:parse α) : parse (Option α) := opt none (some <$> m). def choosePrefix {α} : List (String × parse α) → parse α := delimit ∘ List.foldr (λb m => (do _ <- text b.1; commit b.2) <|> m) failure. partial def manyAux {α} (m:parse α) (z:Type) (someZ : z) : (List α → List String → String → z) → List String → String → z | k, stk, str => let kend := λ(_:List String) (_:String) => k [] stk str; m.runParse z kend kend (λx => manyAux (λxs => k (x::xs))) stk str. def many {α} (m:parse α) : parse (List α) := parse.mk (λz kerr _kfail => manyAux m z (kerr [] "")). def manyOne {α} (m:parse α) : parse (α × List α) := do x <- m; xs <- many m; pure (x,xs). def manyOne' {α} (m:parse α) : parse (List α) := do x <- m; xs <- many m; pure (x::xs). def sepBy {α β} (m:parse α) (sep:parse β) : parse (List α) := (List.cons <$> m <*> many (do _ <- sep; m)). def nat : parse Nat := parse.describe "nat" (Nat.fromDigits <$> manyOne' digit). def textThen {α} (strLit:String) (m:parse α) : parse α := do _ <- text strLit; m def eof : parse Unit := parse.mk (λz kerr kfail k stk str => if str.isEmpty then k () stk str else kfail ("Expected EOF"::stk) str). end parse.
8d44a1011924f3fb51999027721d6298e0063cbd
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/data/fin.lean
e31b36b66fea9c8eaadc756f85d0686bc041c786
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
66,516
lean
/- Copyright (c) 2017 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis, Keeley Hoek -/ import data.nat.cast import data.int.basic import tactic.localized import tactic.apply_fun import order.rel_iso /-! # The finite type with `n` elements `fin n` is the type whose elements are natural numbers smaller than `n`. This file expands on the development in the core library. ## Main definitions ### Induction principles * `fin_zero_elim` : Elimination principle for the empty set `fin 0`, generalizes `fin.elim0`. * `fin.succ_rec` : Define `C n i` by induction on `i : fin n` interpreted as `(0 : fin (n - i)).succ.succ…`. This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple, and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element of `n`-tuple. * `fin.succ_rec_on` : same as `fin.succ_rec` but `i : fin n` is the first argument; * `fin.induction` : Define `C i` by induction on `i : fin (n + 1)`, separating into the `nat`-like base cases of `C 0` and `C (i.succ)`. * `fin.induction_on` : same as `fin.induction` but with `i : fin (n + 1)` as the first argument. ### Casts * `cast_lt i h` : embed `i` into a `fin` where `h` proves it belongs into; * `cast_le h` : embed `fin n` into `fin m`, `h : n ≤ m`; * `cast eq` : embed `fin n` into `fin m`, `eq : n = m`; * `cast_add m` : embed `fin n` into `fin (n+m)`; * `cast_succ` : embed `fin n` into `fin (n+1)`; * `succ_above p` : embed `fin n` into `fin (n + 1)` with a hole around `p`; * `pred_above (p : fin n) i` : embed `i : fin (n+1)` into `fin n` by subtracting one if `p < i`; * `cast_pred` : embed `fin (n + 2)` into `fin (n + 1)` by mapping `last (n + 1)` to `last n`; * `sub_nat i h` : subtract `m` from `i ≥ m`, generalizes `fin.pred`; * `add_nat m i` : add `m` on `i` on the right, generalizes `fin.succ`; * `nat_add n i` adds `n` on `i` on the left; * `clamp n m` : `min n m` as an element of `fin (m + 1)`; ### Operation on tuples We interpret maps `Π i : fin n, α i` as tuples `(α 0, …, α (n-1))`. If `α i` is a constant map, then tuples are isomorphic (but not definitionally equal) to `vector`s. We define the following operations: * `tail` : the tail of an `n+1` tuple, i.e., its last `n` entries; * `cons` : adding an element at the beginning of an `n`-tuple, to get an `n+1`-tuple; * `init` : the beginning of an `n+1` tuple, i.e., its first `n` entries; * `snoc` : adding an element at the end of an `n`-tuple, to get an `n+1`-tuple. The name `snoc` comes from `cons` (i.e., adding an element to the left of a tuple) read in reverse order. * `insert_nth` : insert an element to a tuple at a given position. * `find p` : returns the first index `n` where `p n` is satisfied, and `none` if it is never satisfied. ### Misc definitions * `fin.last n` : The greatest value of `fin (n+1)`. -/ universes u v open fin nat function /-- Elimination principle for the empty set `fin 0`, dependent version. -/ def fin_zero_elim {α : fin 0 → Sort u} (x : fin 0) : α x := x.elim0 lemma fact.succ.pos {n} : fact (0 < succ n) := ⟨zero_lt_succ _⟩ lemma fact.bit0.pos {n} [h : fact (0 < n)] : fact (0 < bit0 n) := ⟨nat.zero_lt_bit0 $ ne_of_gt h.1⟩ lemma fact.bit1.pos {n} : fact (0 < bit1 n) := ⟨nat.zero_lt_bit1 _⟩ lemma fact.pow.pos {p n : ℕ} [h : fact $ 0 < p] : fact (0 < p ^ n) := ⟨pow_pos h.1 _⟩ localized "attribute [instance] fact.succ.pos" in fin_fact localized "attribute [instance] fact.bit0.pos" in fin_fact localized "attribute [instance] fact.bit1.pos" in fin_fact localized "attribute [instance] fact.pow.pos" in fin_fact namespace fin variables {n m : ℕ} {a b : fin n} instance fin_to_nat (n : ℕ) : has_coe (fin n) nat := ⟨subtype.val⟩ section coe /-! ### coercions and constructions -/ @[simp] protected lemma eta (a : fin n) (h : (a : ℕ) < n) : (⟨(a : ℕ), h⟩ : fin n) = a := by cases a; refl @[ext] lemma ext {a b : fin n} (h : (a : ℕ) = b) : a = b := eq_of_veq h lemma ext_iff (a b : fin n) : a = b ↔ (a : ℕ) = b := iff.intro (congr_arg _) fin.eq_of_veq lemma coe_injective {n : ℕ} : injective (coe : fin n → ℕ) := subtype.coe_injective lemma eq_iff_veq (a b : fin n) : a = b ↔ a.1 = b.1 := ⟨veq_of_eq, eq_of_veq⟩ lemma ne_iff_vne (a b : fin n) : a ≠ b ↔ a.1 ≠ b.1 := ⟨vne_of_ne, ne_of_vne⟩ @[simp] lemma mk_eq_subtype_mk (a : ℕ) (h : a < n) : mk a h = ⟨a, h⟩ := rfl protected lemma mk.inj_iff {n a b : ℕ} {ha : a < n} {hb : b < n} : (⟨a, ha⟩ : fin n) = ⟨b, hb⟩ ↔ a = b := subtype.mk_eq_mk lemma mk_val {m n : ℕ} (h : m < n) : (⟨m, h⟩ : fin n).val = m := rfl lemma eq_mk_iff_coe_eq {k : ℕ} {hk : k < n} : a = ⟨k, hk⟩ ↔ (a : ℕ) = k := fin.eq_iff_veq a ⟨k, hk⟩ @[simp, norm_cast] lemma coe_mk {m n : ℕ} (h : m < n) : ((⟨m, h⟩ : fin n) : ℕ) = m := rfl lemma mk_coe (i : fin n) : (⟨i, i.property⟩ : fin n) = i := fin.eta _ _ lemma coe_eq_val (a : fin n) : (a : ℕ) = a.val := rfl @[simp] lemma val_eq_coe (a : fin n) : a.val = a := rfl /-- Assume `k = l`. If two functions defined on `fin k` and `fin l` are equal on each element, then they coincide (in the heq sense). -/ protected lemma heq_fun_iff {α : Sort*} {k l : ℕ} (h : k = l) {f : fin k → α} {g : fin l → α} : f == g ↔ (∀ (i : fin k), f i = g ⟨(i : ℕ), h ▸ i.2⟩) := by { induction h, simp [heq_iff_eq, function.funext_iff] } protected lemma heq_ext_iff {k l : ℕ} (h : k = l) {i : fin k} {j : fin l} : i == j ↔ (i : ℕ) = (j : ℕ) := by { induction h, simp [ext_iff] } lemma exists_iff {p : fin n → Prop} : (∃ i, p i) ↔ ∃ i h, p ⟨i, h⟩ := ⟨λ h, exists.elim h (λ ⟨i, hi⟩ hpi, ⟨i, hi, hpi⟩), λ h, exists.elim h (λ i hi, ⟨⟨i, hi.fst⟩, hi.snd⟩)⟩ lemma forall_iff {p : fin n → Prop} : (∀ i, p i) ↔ ∀ i h, p ⟨i, h⟩ := ⟨λ h i hi, h ⟨i, hi⟩, λ h ⟨i, hi⟩, h i hi⟩ end coe section order /-! ### order -/ lemma is_lt (i : fin n) : (i : ℕ) < n := i.2 lemma is_le (i : fin (n + 1)) : (i : ℕ) ≤ n := le_of_lt_succ i.is_lt lemma lt_iff_coe_lt_coe : a < b ↔ (a : ℕ) < b := iff.rfl lemma le_iff_coe_le_coe : a ≤ b ↔ (a : ℕ) ≤ b := iff.rfl lemma mk_lt_of_lt_coe {a : ℕ} (h : a < b) : (⟨a, h.trans b.is_lt⟩ : fin n) < b := h lemma mk_le_of_le_coe {a : ℕ} (h : a ≤ b) : (⟨a, h.trans_lt b.is_lt⟩ : fin n) ≤ b := h /-- `a < b` as natural numbers if and only if `a < b` in `fin n`. -/ @[norm_cast, simp] lemma coe_fin_lt {n : ℕ} {a b : fin n} : (a : ℕ) < (b : ℕ) ↔ a < b := iff.rfl /-- `a ≤ b` as natural numbers if and only if `a ≤ b` in `fin n`. -/ @[norm_cast, simp] lemma coe_fin_le {n : ℕ} {a b : fin n} : (a : ℕ) ≤ (b : ℕ) ↔ a ≤ b := iff.rfl instance {n : ℕ} : linear_order (fin n) := { le := (≤), lt := (<), decidable_le := fin.decidable_le, decidable_lt := fin.decidable_lt, decidable_eq := fin.decidable_eq _, ..linear_order.lift (coe : fin n → ℕ) (@fin.eq_of_veq _) } /-- The inclusion map `fin n → ℕ` is a relation embedding. -/ def coe_embedding (n) : (fin n) ↪o ℕ := ⟨⟨coe, @fin.eq_of_veq _⟩, λ a b, iff.rfl⟩ /-- The ordering on `fin n` is a well order. -/ instance fin.lt.is_well_order (n) : is_well_order (fin n) (<) := (coe_embedding n).is_well_order /-- Use the ordering on `fin n` for checking recursive definitions. For example, the following definition is not accepted by the termination checker, unless we declare the `has_well_founded` instance: ```lean def factorial {n : ℕ} : fin n → ℕ | ⟨0, _⟩ := 1 | ⟨i + 1, hi⟩ := (i + 1) * factorial ⟨i, i.lt_succ_self.trans hi⟩ ``` -/ instance {n : ℕ} : has_well_founded (fin n) := ⟨_, measure_wf coe⟩ @[simp] lemma coe_zero {n : ℕ} : ((0 : fin (n+1)) : ℕ) = 0 := rfl attribute [simp] val_zero @[simp] lemma val_zero' (n) : (0 : fin (n+1)).val = 0 := rfl @[simp] lemma mk_zero : (⟨0, nat.succ_pos'⟩ : fin (n + 1)) = (0 : fin _) := rfl lemma zero_le (a : fin (n + 1)) : 0 ≤ a := zero_le a.1 lemma pos_iff_ne_zero (a : fin (n+1)) : 0 < a ↔ a ≠ 0 := begin split, { rintros h rfl, exact lt_irrefl _ h, }, { rintros h, apply (@pos_iff_ne_zero _ _ (a : ℕ)).mpr, cases a, rintro w, apply h, simp at w, subst w, refl, }, end /-- The greatest value of `fin (n+1)` -/ def last (n : ℕ) : fin (n+1) := ⟨_, n.lt_succ_self⟩ @[simp, norm_cast] lemma coe_last (n : ℕ) : (last n : ℕ) = n := rfl lemma last_val (n : ℕ) : (last n).val = n := rfl theorem le_last (i : fin (n+1)) : i ≤ last n := le_of_lt_succ i.is_lt instance : bounded_lattice (fin (n + 1)) := { top := last n, le_top := le_last, bot := 0, bot_le := zero_le, .. fin.linear_order, .. lattice_of_linear_order } lemma last_pos : (0 : fin (n + 2)) < last (n + 1) := by simp [lt_iff_coe_lt_coe] lemma eq_last_of_not_lt {i : fin (n+1)} (h : ¬ (i : ℕ) < n) : i = last n := le_antisymm (le_last i) (not_lt.1 h) section variables {α : Type*} [preorder α] open set /-- If `e` is an `order_iso` between `fin n` and `fin m`, then `n = m` and `e` is the identity map. In this lemma we state that for each `i : fin n` we have `(e i : ℕ) = (i : ℕ)`. -/ @[simp] lemma coe_order_iso_apply (e : fin n ≃o fin m) (i : fin n) : (e i : ℕ) = i := begin rcases i with ⟨i, hi⟩, rw [subtype.coe_mk], induction i using nat.strong_induction_on with i h, refine le_antisymm (forall_lt_iff_le.1 $ λ j hj, _) (forall_lt_iff_le.1 $ λ j hj, _), { have := e.symm.lt_iff_lt.2 (mk_lt_of_lt_coe hj), rw e.symm_apply_apply at this, convert this, simpa using h _ this (e.symm _).is_lt }, { rwa [← h j hj (hj.trans hi), ← lt_iff_coe_lt_coe, e.lt_iff_lt] } end instance order_iso_subsingleton : subsingleton (fin n ≃o α) := ⟨λ e e', by { ext i, rw [← e.symm.apply_eq_iff_eq, e.symm_apply_apply, ← e'.trans_apply, ext_iff, coe_order_iso_apply] }⟩ instance order_iso_subsingleton' : subsingleton (α ≃o fin n) := order_iso.symm_injective.subsingleton instance order_iso_unique : unique (fin n ≃o fin n) := unique.mk' _ /-- Two strictly monotone functions from `fin n` are equal provided that their ranges are equal. -/ lemma strict_mono_unique {f g : fin n → α} (hf : strict_mono f) (hg : strict_mono g) (h : range f = range g) : f = g := have (hf.order_iso f).trans (order_iso.set_congr _ _ h) = hg.order_iso g, from subsingleton.elim _ _, congr_arg (function.comp (coe : range g → α)) (funext $ rel_iso.ext_iff.1 this) /-- Two order embeddings of `fin n` are equal provided that their ranges are equal. -/ lemma order_embedding_eq {f g : fin n ↪o α} (h : range f = range g) : f = g := rel_embedding.ext $ funext_iff.1 $ strict_mono_unique f.strict_mono g.strict_mono h end /-- A function `f` on `fin n` is strictly monotone if and only if `f i < f (i+1)` for all `i`. -/ lemma strict_mono_iff_lt_succ {α : Type*} [preorder α] {f : fin n → α} : strict_mono f ↔ ∀ i (h : i + 1 < n), f ⟨i, lt_of_le_of_lt (nat.le_succ i) h⟩ < f ⟨i+1, h⟩ := begin split, { assume H i hi, apply H, exact nat.lt_succ_self _ }, { assume H, have A : ∀ i j (h : i < j) (h' : j < n), f ⟨i, lt_trans h h'⟩ < f ⟨j, h'⟩, { assume i j h h', induction h with k h IH, { exact H _ _ }, { exact lt_trans (IH (nat.lt_of_succ_lt h')) (H _ _) } }, assume i j hij, convert A (i : ℕ) (j : ℕ) hij j.2; ext; simp only [subtype.coe_eta] } end end order section add /-! ### addition, numerals, and coercion from nat -/ /-- convert a `ℕ` to `fin n`, provided `n` is positive -/ def of_nat' [h : fact (0 < n)] (i : ℕ) : fin n := ⟨i%n, mod_lt _ h.1⟩ lemma one_val {n : ℕ} : (1 : fin (n+1)).val = 1 % (n+1) := rfl lemma coe_one' {n : ℕ} : ((1 : fin (n+1)) : ℕ) = 1 % (n+1) := rfl @[simp] lemma val_one {n : ℕ} : (1 : fin (n+2)).val = 1 := rfl @[simp] lemma coe_one {n : ℕ} : ((1 : fin (n+2)) : ℕ) = 1 := rfl @[simp] lemma mk_one : (⟨1, nat.succ_lt_succ (nat.succ_pos n)⟩ : fin (n + 2)) = (1 : fin _) := rfl instance {n : ℕ} : nontrivial (fin (n + 2)) := ⟨⟨0, 1, dec_trivial⟩⟩ section monoid @[simp] protected lemma add_zero (k : fin (n + 1)) : k + 0 = k := by simp [eq_iff_veq, add_def, mod_eq_of_lt (is_lt k)] @[simp] protected lemma zero_add (k : fin (n + 1)) : (0 : fin (n + 1)) + k = k := by simp [eq_iff_veq, add_def, mod_eq_of_lt (is_lt k)] instance add_comm_monoid (n : ℕ) : add_comm_monoid (fin (n + 1)) := { add := (+), add_assoc := by simp [eq_iff_veq, add_def, add_assoc], zero := 0, zero_add := fin.zero_add, add_zero := fin.add_zero, add_comm := by simp [eq_iff_veq, add_def, add_comm] } end monoid lemma val_add {n : ℕ} : ∀ a b : fin n, (a + b).val = (a.val + b.val) % n | ⟨_, _⟩ ⟨_, _⟩ := rfl lemma coe_add {n : ℕ} : ∀ a b : fin n, ((a + b : fin n) : ℕ) = (a + b) % n | ⟨_, _⟩ ⟨_, _⟩ := rfl lemma coe_bit0 {n : ℕ} (k : fin n) : ((bit0 k : fin n) : ℕ) = bit0 (k : ℕ) % n := by { cases k, refl } lemma coe_bit1 {n : ℕ} (k : fin (n + 1)) : ((bit1 k : fin (n + 1)) : ℕ) = bit1 (k : ℕ) % (n + 1) := begin cases n, { cases k with k h, cases k, {show _ % _ = _, simp}, cases h with _ h, cases h }, simp [bit1, fin.coe_bit0, fin.coe_add, fin.coe_one], end lemma coe_add_one_of_lt {n : ℕ} {i : fin n.succ} (h : i < last _) : (↑(i + 1) : ℕ) = i + 1 := begin -- First show that `((1 : fin n.succ) : ℕ) = 1`, because `n.succ` is at least 2. cases n, { cases h }, -- Then just unfold the definitions. rw [fin.coe_add, fin.coe_one, nat.mod_eq_of_lt (nat.succ_lt_succ _)], exact h end @[simp] lemma last_add_one : ∀ n, last n + 1 = 0 | 0 := subsingleton.elim _ _ | (n + 1) := by { ext, rw [coe_add, coe_zero, coe_last, coe_one, nat.mod_self] } lemma coe_add_one {n : ℕ} (i : fin (n + 1)) : ((i + 1 : fin (n + 1)) : ℕ) = if i = last _ then 0 else i + 1 := begin rcases (le_last i).eq_or_lt with rfl|h, { simp }, { simpa [h.ne] using coe_add_one_of_lt h } end section bit @[simp] lemma mk_bit0 {m n : ℕ} (h : bit0 m < n) : (⟨bit0 m, h⟩ : fin n) = (bit0 ⟨m, (nat.le_add_right m m).trans_lt h⟩ : fin _) := eq_of_veq (nat.mod_eq_of_lt h).symm @[simp] lemma mk_bit1 {m n : ℕ} (h : bit1 m < n + 1) : (⟨bit1 m, h⟩ : fin (n + 1)) = (bit1 ⟨m, (nat.le_add_right m m).trans_lt ((m + m).lt_succ_self.trans h)⟩ : fin _) := begin ext, simp only [bit1, bit0] at h, simp only [bit1, bit0, coe_add, coe_one', coe_mk, ←nat.add_mod, nat.mod_eq_of_lt h], end end bit @[simp] lemma val_two {n : ℕ} : (2 : fin (n+3)).val = 2 := rfl @[simp] lemma coe_two {n : ℕ} : ((2 : fin (n+3)) : ℕ) = 2 := rfl section of_nat_coe @[simp] lemma of_nat_eq_coe (n : ℕ) (a : ℕ) : (of_nat a : fin (n+1)) = a := begin induction a with a ih, { refl }, ext, show (a+1) % (n+1) = subtype.val (a+1 : fin (n+1)), { rw [val_add, ← ih, of_nat], exact add_mod _ _ _ } end /-- Converting an in-range number to `fin (n + 1)` produces a result whose value is the original number. -/ lemma coe_val_of_lt {n : ℕ} {a : ℕ} (h : a < n + 1) : ((a : fin (n + 1)).val) = a := begin rw ←of_nat_eq_coe, exact nat.mod_eq_of_lt h end /-- Converting the value of a `fin (n + 1)` to `fin (n + 1)` results in the same value. -/ lemma coe_val_eq_self {n : ℕ} (a : fin (n + 1)) : (a.val : fin (n + 1)) = a := begin rw fin.eq_iff_veq, exact coe_val_of_lt a.property end /-- Coercing an in-range number to `fin (n + 1)`, and converting back to `ℕ`, results in that number. -/ lemma coe_coe_of_lt {n : ℕ} {a : ℕ} (h : a < n + 1) : ((a : fin (n + 1)) : ℕ) = a := coe_val_of_lt h /-- Converting a `fin (n + 1)` to `ℕ` and back results in the same value. -/ @[simp] lemma coe_coe_eq_self {n : ℕ} (a : fin (n + 1)) : ((a : ℕ) : fin (n + 1)) = a := coe_val_eq_self a lemma coe_nat_eq_last (n) : (n : fin (n + 1)) = fin.last n := by { rw [←fin.of_nat_eq_coe, fin.of_nat, fin.last], simp only [nat.mod_eq_of_lt n.lt_succ_self] } lemma le_coe_last (i : fin (n + 1)) : i ≤ n := by { rw fin.coe_nat_eq_last, exact fin.le_last i } end of_nat_coe lemma add_one_pos (i : fin (n + 1)) (h : i < fin.last n) : (0 : fin (n + 1)) < i + 1 := begin cases n, { exact absurd h (nat.not_lt_zero _) }, { rw [lt_iff_coe_lt_coe, coe_last, ←add_lt_add_iff_right 1] at h, rw [lt_iff_coe_lt_coe, coe_add, coe_zero, coe_one, nat.mod_eq_of_lt h], exact nat.zero_lt_succ _ } end lemma one_pos : (0 : fin (n + 2)) < 1 := succ_pos 0 lemma zero_ne_one : (0 : fin (n + 2)) ≠ 1 := ne_of_lt one_pos @[simp] lemma zero_eq_one_iff : (0 : fin (n + 1)) = 1 ↔ n = 0 := begin split, { cases n; intro h, { refl }, { have := zero_ne_one, contradiction } }, { rintro rfl, refl } end @[simp] lemma one_eq_zero_iff : (1 : fin (n + 1)) = 0 ↔ n = 0 := by rw [eq_comm, zero_eq_one_iff] end add section succ /-! ### succ and casts into larger fin types -/ @[simp] lemma coe_succ (j : fin n) : (j.succ : ℕ) = j + 1 := by cases j; simp [fin.succ] lemma succ_pos (a : fin n) : (0 : fin (n + 1)) < a.succ := by simp [lt_iff_coe_lt_coe] /-- `fin.succ` as an `order_embedding` -/ def succ_embedding (n : ℕ) : fin n ↪o fin (n + 1) := order_embedding.of_strict_mono fin.succ $ λ ⟨i, hi⟩ ⟨j, hj⟩ h, succ_lt_succ h @[simp] lemma coe_succ_embedding : ⇑(succ_embedding n) = fin.succ := rfl @[simp] lemma succ_le_succ_iff : a.succ ≤ b.succ ↔ a ≤ b := (succ_embedding n).le_iff_le @[simp] lemma succ_lt_succ_iff : a.succ < b.succ ↔ a < b := (succ_embedding n).lt_iff_lt lemma succ_injective (n : ℕ) : injective (@fin.succ n) := (succ_embedding n).injective @[simp] lemma succ_inj {a b : fin n} : a.succ = b.succ ↔ a = b := (succ_injective n).eq_iff lemma succ_ne_zero {n} : ∀ k : fin n, fin.succ k ≠ 0 | ⟨k, hk⟩ heq := nat.succ_ne_zero k $ (ext_iff _ _).1 heq @[simp] lemma succ_zero_eq_one : fin.succ (0 : fin (n + 1)) = 1 := rfl @[simp] lemma succ_one_eq_two : fin.succ (1 : fin (n + 2)) = 2 := rfl @[simp] lemma succ_mk (n i : ℕ) (h : i < n) : fin.succ ⟨i, h⟩ = ⟨i + 1, nat.succ_lt_succ h⟩ := rfl lemma mk_succ_pos (i : ℕ) (h : i < n) : (0 : fin (n + 1)) < ⟨i.succ, add_lt_add_right h 1⟩ := by { rw [lt_iff_coe_lt_coe, coe_zero], exact nat.succ_pos i } lemma one_lt_succ_succ (a : fin n) : (1 : fin (n + 2)) < a.succ.succ := begin cases n, { exact fin_zero_elim a }, { rw [←succ_zero_eq_one, succ_lt_succ_iff], exact succ_pos a } end lemma succ_succ_ne_one (a : fin n) : fin.succ (fin.succ a) ≠ 1 := ne_of_gt (one_lt_succ_succ a) /-- `cast_lt i h` embeds `i` into a `fin` where `h` proves it belongs into. -/ def cast_lt (i : fin m) (h : i.1 < n) : fin n := ⟨i.1, h⟩ @[simp] lemma coe_cast_lt (i : fin m) (h : i.1 < n) : (cast_lt i h : ℕ) = i := rfl @[simp] lemma cast_lt_mk (i n m : ℕ) (hn : i < n) (hm : i < m) : cast_lt ⟨i, hn⟩ hm = ⟨i, hm⟩ := rfl /-- `cast_le h i` embeds `i` into a larger `fin` type. -/ def cast_le (h : n ≤ m) : fin n ↪o fin m := order_embedding.of_strict_mono (λ a, cast_lt a (lt_of_lt_of_le a.2 h)) $ λ a b h, h @[simp] lemma coe_cast_le (h : n ≤ m) (i : fin n) : (cast_le h i : ℕ) = i := rfl @[simp] lemma cast_le_mk (i n m : ℕ) (hn : i < n) (h : n ≤ m) : cast_le h ⟨i, hn⟩ = ⟨i, lt_of_lt_of_le hn h⟩ := rfl @[simp] lemma cast_le_zero {n m : ℕ} (h : n.succ ≤ m.succ) : cast_le h 0 = 0 := by simp [eq_iff_veq] @[simp] lemma range_cast_le {n k : ℕ} (h : n ≤ k) : set.range (cast_le h) = {i | (i : ℕ) < n} := set.ext (λ x, ⟨λ ⟨y, hy⟩, hy ▸ y.2, λ hx, ⟨⟨x, hx⟩, fin.ext rfl⟩⟩) @[simp] lemma coe_of_injective_cast_le_symm {n k : ℕ} (h : n ≤ k) (i : fin k) (hi) : ((equiv.of_injective _ (cast_le h).injective).symm ⟨i, hi⟩ : ℕ) = i := begin rw ← coe_cast_le, exact congr_arg coe (equiv.apply_of_injective_symm _ _ _) end /-- `cast eq i` embeds `i` into a equal `fin` type. -/ def cast (eq : n = m) : fin n ≃o fin m := { to_equiv := ⟨cast_le eq.le, cast_le eq.symm.le, λ a, eq_of_veq rfl, λ a, eq_of_veq rfl⟩, map_rel_iff' := λ a b, iff.rfl } @[simp] lemma symm_cast (h : n = m) : (cast h).symm = cast h.symm := rfl lemma coe_cast (h : n = m) (i : fin n) : (cast h i : ℕ) = i := rfl @[simp] lemma cast_mk (h : n = m) (i : ℕ) (hn : i < n) : cast h ⟨i, hn⟩ = ⟨i, lt_of_lt_of_le hn h.le⟩ := rfl @[simp] lemma cast_trans {k : ℕ} (h : n = m) (h' : m = k) {i : fin n} : cast h' (cast h i) = cast (eq.trans h h') i := rfl @[simp] lemma cast_refl (h : n = n := rfl) : cast h = order_iso.refl (fin n) := by { ext, refl } /-- While in many cases `fin.cast` is better than `equiv.cast`/`cast`, sometimes we want to apply a generic theorem about `cast`. -/ lemma cast_to_equiv (h : n = m) : (cast h).to_equiv = equiv.cast (h ▸ rfl) := by { subst h, simp } /-- While in many cases `fin.cast` is better than `equiv.cast`/`cast`, sometimes we want to apply a generic theorem about `cast`. -/ lemma cast_eq_cast (h : n = m) : (cast h : fin n → fin m) = _root_.cast (h ▸ rfl) := by { subst h, ext, simp } /-- `cast_add m i` embeds `i : fin n` in `fin (n+m)`. -/ def cast_add (m) : fin n ↪o fin (n + m) := cast_le $ le_add_right n m @[simp] lemma coe_cast_add (m : ℕ) (i : fin n) : (cast_add m i : ℕ) = i := rfl @[simp] lemma cast_add_mk (m : ℕ) (i : ℕ) (h : i < n) : cast_add m ⟨i, h⟩ = ⟨i, lt_add_right i n m h⟩ := rfl /-- `cast_succ i` embeds `i : fin n` in `fin (n+1)`. -/ def cast_succ : fin n ↪o fin (n + 1) := cast_add 1 @[simp] lemma coe_cast_succ (i : fin n) : (i.cast_succ : ℕ) = i := rfl @[simp] lemma cast_succ_mk (n i : ℕ) (h : i < n) : cast_succ ⟨i, h⟩ = ⟨i, nat.lt.step h⟩ := rfl lemma cast_succ_lt_succ (i : fin n) : i.cast_succ < i.succ := lt_iff_coe_lt_coe.2 $ by simp only [coe_cast_succ, coe_succ, nat.lt_succ_self] lemma le_cast_succ_iff {i : fin (n + 1)} {j : fin n} : i ≤ j.cast_succ ↔ i < j.succ := by simpa [lt_iff_coe_lt_coe, le_iff_coe_le_coe] using nat.succ_le_succ_iff.symm @[simp] lemma succ_last (n : ℕ) : (last n).succ = last (n.succ) := rfl @[simp] lemma succ_eq_last_succ {n : ℕ} (i : fin n.succ) : i.succ = last (n + 1) ↔ i = last n := by rw [← succ_last, (succ_injective _).eq_iff] @[simp] lemma cast_succ_cast_lt (i : fin (n + 1)) (h : (i : ℕ) < n) : cast_succ (cast_lt i h) = i := fin.eq_of_veq rfl @[simp] lemma cast_lt_cast_succ {n : ℕ} (a : fin n) (h : (a : ℕ) < n) : cast_lt (cast_succ a) h = a := by cases a; refl @[simp] lemma cast_succ_lt_cast_succ_iff : a.cast_succ < b.cast_succ ↔ a < b := (@cast_succ n).lt_iff_lt lemma cast_succ_injective (n : ℕ) : injective (@fin.cast_succ n) := (cast_succ : fin n ↪o _).injective lemma cast_succ_inj {a b : fin n} : a.cast_succ = b.cast_succ ↔ a = b := (cast_succ_injective n).eq_iff lemma cast_succ_lt_last (a : fin n) : cast_succ a < last n := lt_iff_coe_lt_coe.mpr a.is_lt @[simp] lemma cast_succ_zero : cast_succ (0 : fin (n + 1)) = 0 := rfl @[simp] lemma cast_succ_one {n : ℕ} : fin.cast_succ (1 : fin (n + 2)) = 1 := rfl /-- `cast_succ i` is positive when `i` is positive -/ lemma cast_succ_pos {i : fin (n + 1)} (h : 0 < i) : 0 < cast_succ i := by simpa [lt_iff_coe_lt_coe] using h lemma cast_succ_fin_succ (n : ℕ) (j : fin n) : cast_succ (fin.succ j) = fin.succ (cast_succ j) := by simp [fin.ext_iff] @[norm_cast, simp] lemma coe_eq_cast_succ : (a : fin (n + 1)) = a.cast_succ := begin ext, exact coe_val_of_lt (nat.lt.step a.is_lt), end @[simp] lemma coe_succ_eq_succ : a.cast_succ + 1 = a.succ := begin cases n, { exact fin_zero_elim a }, { simp [a.is_lt, eq_iff_veq, add_def, nat.mod_eq_of_lt] } end lemma lt_succ : a.cast_succ < a.succ := by { rw [cast_succ, lt_iff_coe_lt_coe, coe_cast_add, coe_succ], exact lt_add_one a.val } @[simp] lemma range_cast_succ {n : ℕ} : set.range (cast_succ : fin n → fin n.succ) = {i | (i : ℕ) < n} := range_cast_le _ @[simp] lemma coe_of_injective_cast_succ_symm {n : ℕ} (i : fin n.succ) (hi) : ((equiv.of_injective cast_succ (cast_succ_injective _)).symm ⟨i, hi⟩ : ℕ) = i := begin rw ← coe_cast_succ, exact congr_arg coe (equiv.apply_of_injective_symm _ _ _) end /-- `add_nat m i` adds `m` to `i`, generalizes `fin.succ`. -/ def add_nat (m) : fin n ↪o fin (n + m) := order_embedding.of_strict_mono (λ i, ⟨(i : ℕ) + m, add_lt_add_right i.2 _⟩) $ λ i j h, lt_iff_coe_lt_coe.2 $ add_lt_add_right h _ @[simp] lemma coe_add_nat (m : ℕ) (i : fin n) : (add_nat m i : ℕ) = i + m := rfl /-- `nat_add n i` adds `n` to `i` "on the left". -/ def nat_add (n) {m} : fin m ↪o fin (n + m) := order_embedding.of_strict_mono (λ i, ⟨n + (i : ℕ), add_lt_add_left i.2 _⟩) $ λ i j h, lt_iff_coe_lt_coe.2 $ add_lt_add_left h _ @[simp] lemma coe_nat_add (n : ℕ) {m : ℕ} (i : fin m) : (nat_add n i : ℕ) = n + i := rfl lemma nat_add_zero {n : ℕ} : fin.nat_add 0 = (fin.cast (zero_add n).symm).to_rel_embedding := by { ext, apply zero_add } end succ section rec /-! ### recursion and induction principles -/ /-- Define `C n i` by induction on `i : fin n` interpreted as `(0 : fin (n - i)).succ.succ…`. This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple, and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element of `n`-tuple. -/ @[elab_as_eliminator] def succ_rec {C : Π n, fin n → Sort*} (H0 : Π n, C (succ n) 0) (Hs : Π n i, C n i → C (succ n) i.succ) : Π {n : ℕ} (i : fin n), C n i | 0 i := i.elim0 | (succ n) ⟨0, _⟩ := H0 _ | (succ n) ⟨succ i, h⟩ := Hs _ _ (succ_rec ⟨i, lt_of_succ_lt_succ h⟩) /-- Define `C n i` by induction on `i : fin n` interpreted as `(0 : fin (n - i)).succ.succ…`. This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple, and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element of `n`-tuple. A version of `fin.succ_rec` taking `i : fin n` as the first argument. -/ @[elab_as_eliminator] def succ_rec_on {n : ℕ} (i : fin n) {C : Π n, fin n → Sort*} (H0 : Π n, C (succ n) 0) (Hs : Π n i, C n i → C (succ n) i.succ) : C n i := i.succ_rec H0 Hs @[simp] theorem succ_rec_on_zero {C : ∀ n, fin n → Sort*} {H0 Hs} (n) : @fin.succ_rec_on (succ n) 0 C H0 Hs = H0 n := rfl @[simp] theorem succ_rec_on_succ {C : ∀ n, fin n → Sort*} {H0 Hs} {n} (i : fin n) : @fin.succ_rec_on (succ n) i.succ C H0 Hs = Hs n i (fin.succ_rec_on i H0 Hs) := by cases i; refl /-- Define `C i` by induction on `i : fin (n + 1)` via induction on the underlying `nat` value. This function has two arguments: `h0` handles the base case on `C 0`, and `hs` defines the inductive step using `C i.cast_succ`. -/ @[elab_as_eliminator] def induction {C : fin (n + 1) → Sort*} (h0 : C 0) (hs : ∀ i : fin n, C i.cast_succ → C i.succ) : Π (i : fin (n + 1)), C i := begin rintro ⟨i, hi⟩, induction i with i IH, { rwa [fin.mk_zero] }, { refine hs ⟨i, lt_of_succ_lt_succ hi⟩ _, exact IH (lt_of_succ_lt hi) } end /-- Define `C i` by induction on `i : fin (n + 1)` via induction on the underlying `nat` value. This function has two arguments: `h0` handles the base case on `C 0`, and `hs` defines the inductive step using `C i.cast_succ`. A version of `fin.induction` taking `i : fin (n + 1)` as the first argument. -/ @[elab_as_eliminator] def induction_on (i : fin (n + 1)) {C : fin (n + 1) → Sort*} (h0 : C 0) (hs : ∀ i : fin n, C i.cast_succ → C i.succ) : C i := induction h0 hs i /-- Define `f : Π i : fin n.succ, C i` by separately handling the cases `i = 0` and `i = j.succ`, `j : fin n`. -/ @[elab_as_eliminator] def cases {C : fin (succ n) → Sort*} (H0 : C 0) (Hs : Π i : fin n, C (i.succ)) : Π (i : fin (succ n)), C i := induction H0 (λ i _, Hs i) @[simp] theorem cases_zero {n} {C : fin (succ n) → Sort*} {H0 Hs} : @fin.cases n C H0 Hs 0 = H0 := rfl @[simp] theorem cases_succ {n} {C : fin (succ n) → Sort*} {H0 Hs} (i : fin n) : @fin.cases n C H0 Hs i.succ = Hs i := by cases i; refl @[simp] theorem cases_succ' {n} {C : fin (succ n) → Sort*} {H0 Hs} {i : ℕ} (h : i + 1 < n + 1) : @fin.cases n C H0 Hs ⟨i.succ, h⟩ = Hs ⟨i, lt_of_succ_lt_succ h⟩ := by cases i; refl lemma forall_fin_succ {P : fin (n+1) → Prop} : (∀ i, P i) ↔ P 0 ∧ (∀ i:fin n, P i.succ) := ⟨λ H, ⟨H 0, λ i, H _⟩, λ ⟨H0, H1⟩ i, fin.cases H0 H1 i⟩ lemma exists_fin_succ {P : fin (n+1) → Prop} : (∃ i, P i) ↔ P 0 ∨ (∃i:fin n, P i.succ) := ⟨λ ⟨i, h⟩, fin.cases or.inl (λ i hi, or.inr ⟨i, hi⟩) i h, λ h, or.elim h (λ h, ⟨0, h⟩) $ λ⟨i, hi⟩, ⟨i.succ, hi⟩⟩ end rec section pred /-! ### pred -/ @[simp] lemma coe_pred (j : fin (n+1)) (h : j ≠ 0) : (j.pred h : ℕ) = j - 1 := by { cases j, refl } @[simp] lemma succ_pred : ∀(i : fin (n+1)) (h : i ≠ 0), (i.pred h).succ = i | ⟨0, h⟩ hi := by contradiction | ⟨n + 1, h⟩ hi := rfl @[simp] lemma pred_succ (i : fin n) {h : i.succ ≠ 0} : i.succ.pred h = i := by { cases i, refl } @[simp] lemma pred_mk_succ (i : ℕ) (h : i < n + 1) : fin.pred ⟨i + 1, add_lt_add_right h 1⟩ (ne_of_vne (ne_of_gt (mk_succ_pos i h))) = ⟨i, h⟩ := by simp only [ext_iff, coe_pred, coe_mk, nat.add_sub_cancel] -- This is not a simp lemma by default, because `pred_mk_succ` is nicer when it applies. lemma pred_mk {n : ℕ} (i : ℕ) (h : i < n + 1) (w) : fin.pred ⟨i, h⟩ w = ⟨i - 1, by rwa nat.sub_lt_right_iff_lt_add (nat.pos_of_ne_zero (fin.vne_of_ne w))⟩ := rfl @[simp] lemma pred_le_pred_iff {n : ℕ} {a b : fin n.succ} {ha : a ≠ 0} {hb : b ≠ 0} : a.pred ha ≤ b.pred hb ↔ a ≤ b := by rw [←succ_le_succ_iff, succ_pred, succ_pred] @[simp] lemma pred_lt_pred_iff {n : ℕ} {a b : fin n.succ} {ha : a ≠ 0} {hb : b ≠ 0} : a.pred ha < b.pred hb ↔ a < b := by rw [←succ_lt_succ_iff, succ_pred, succ_pred] @[simp] lemma pred_inj : ∀ {a b : fin (n + 1)} {ha : a ≠ 0} {hb : b ≠ 0}, a.pred ha = b.pred hb ↔ a = b | ⟨0, _⟩ b ha hb := by contradiction | ⟨i+1, _⟩ ⟨0, _⟩ ha hb := by contradiction | ⟨i+1, hi⟩ ⟨j+1, hj⟩ ha hb := by simp [fin.eq_iff_veq] @[simp] lemma pred_one {n : ℕ} : fin.pred (1 : fin (n + 2)) (ne.symm (ne_of_lt one_pos)) = 0 := rfl lemma pred_add_one (i : fin (n + 2)) (h : (i : ℕ) < n + 1) : pred (i + 1) (ne_of_gt (add_one_pos _ (lt_iff_coe_lt_coe.mpr h))) = cast_lt i h := begin rw [ext_iff, coe_pred, coe_cast_lt, coe_add, coe_one, mod_eq_of_lt, nat.add_sub_cancel], exact add_lt_add_right h 1, end /-- `sub_nat i h` subtracts `m` from `i`, generalizes `fin.pred`. -/ def sub_nat (m) (i : fin (n + m)) (h : m ≤ (i : ℕ)) : fin n := ⟨(i : ℕ) - m, by { rw [nat.sub_lt_right_iff_lt_add h], exact i.is_lt }⟩ @[simp] lemma coe_sub_nat (i : fin (n + m)) (h : m ≤ i) : (i.sub_nat m h : ℕ) = i - m := rfl @[simp] lemma pred_cast_succ_succ (i : fin n) : pred (cast_succ i.succ) (ne_of_gt (cast_succ_pos i.succ_pos)) = i.cast_succ := by simp [eq_iff_veq] end pred section add_group open nat int /-- Negation on `fin n` -/ instance (n : ℕ) : has_neg (fin n) := ⟨λ a, ⟨(n - a) % n, nat.mod_lt _ (lt_of_le_of_lt (nat.zero_le _) a.2)⟩⟩ /-- Abelian group structure on `fin (n+1)`. -/ instance (n : ℕ) : add_comm_group (fin (n+1)) := { add_left_neg := λ ⟨a, ha⟩, fin.ext $ trans (nat.mod_add_mod _ _ _) $ by { rw [fin.coe_mk, fin.coe_zero, nat.sub_add_cancel, nat.mod_self], exact le_of_lt ha }, sub_eq_add_neg := λ ⟨a, ha⟩ ⟨b, hb⟩, fin.ext $ show (a + (n + 1 - b)) % (n + 1) = (a + (n + 1 - b) % (n + 1)) % (n + 1), by simp, sub := fin.sub, ..fin.add_comm_monoid n, ..fin.has_neg n.succ } protected lemma coe_neg (a : fin n) : ((-a : fin n) : ℕ) = (n - a) % n := rfl protected lemma coe_sub (a b : fin n) : ((a - b : fin n) : ℕ) = (a + (n - b)) % n := by cases a; cases b; refl end add_group section succ_above lemma succ_above_aux (p : fin (n + 1)) : strict_mono (λ i : fin n, if i.cast_succ < p then i.cast_succ else i.succ) := (cast_succ : fin n ↪o _).strict_mono.ite (succ_embedding n).strict_mono (λ i j hij hj, lt_trans ((cast_succ : fin n ↪o _).lt_iff_lt.2 hij) hj) (λ i, (cast_succ_lt_succ i).le) /-- `succ_above p i` embeds `fin n` into `fin (n + 1)` with a hole around `p`. -/ def succ_above (p : fin (n + 1)) : fin n ↪o fin (n + 1) := order_embedding.of_strict_mono _ p.succ_above_aux /-- Embedding `i : fin n` into `fin (n + 1)` with a hole around `p : fin (n + 1)` embeds `i` by `cast_succ` when the resulting `i.cast_succ < p`. -/ lemma succ_above_below (p : fin (n + 1)) (i : fin n) (h : i.cast_succ < p) : p.succ_above i = i.cast_succ := by { rw [succ_above], exact if_pos h } /-- Embedding `fin n` into `fin (n + 1)` with a hole around zero embeds by `succ`. -/ @[simp] lemma succ_above_zero : ⇑(succ_above (0 : fin (n + 1))) = fin.succ := rfl /-- Embedding `fin n` into `fin (n + 1)` with a hole around `last n` embeds by `cast_succ`. -/ @[simp] lemma succ_above_last : succ_above (fin.last n) = cast_succ := by { ext, simp only [succ_above_below, cast_succ_lt_last] } lemma succ_above_last_apply (i : fin n) : succ_above (fin.last n) i = i.cast_succ := by rw succ_above_last /-- Embedding `i : fin n` into `fin (n + 1)` with a hole around `p : fin (n + 1)` embeds `i` by `succ` when the resulting `p < i.succ`. -/ lemma succ_above_above (p : fin (n + 1)) (i : fin n) (h : p ≤ i.cast_succ) : p.succ_above i = i.succ := by simp [succ_above, h.not_lt] /-- Embedding `i : fin n` into `fin (n + 1)` is always about some hole `p`. -/ lemma succ_above_lt_ge (p : fin (n + 1)) (i : fin n) : i.cast_succ < p ∨ p ≤ i.cast_succ := lt_or_ge (cast_succ i) p /-- Embedding `i : fin n` into `fin (n + 1)` is always about some hole `p`. -/ lemma succ_above_lt_gt (p : fin (n + 1)) (i : fin n) : i.cast_succ < p ∨ p < i.succ := or.cases_on (succ_above_lt_ge p i) (λ h, or.inl h) (λ h, or.inr (lt_of_le_of_lt h (cast_succ_lt_succ i))) /-- Embedding `i : fin n` into `fin (n + 1)` using a pivot `p` that is greater results in a value that is less than `p`. -/ @[simp] lemma succ_above_lt_iff (p : fin (n + 1)) (i : fin n) : p.succ_above i < p ↔ i.cast_succ < p := begin refine iff.intro _ _, { intro h, cases succ_above_lt_ge p i with H H, { exact H }, { rw succ_above_above _ _ H at h, exact lt_trans (cast_succ_lt_succ i) h } }, { intro h, rw succ_above_below _ _ h, exact h } end /-- Embedding `i : fin n` into `fin (n + 1)` using a pivot `p` that is lesser results in a value that is greater than `p`. -/ lemma lt_succ_above_iff (p : fin (n + 1)) (i : fin n) : p < p.succ_above i ↔ p ≤ i.cast_succ := begin refine iff.intro _ _, { intro h, cases succ_above_lt_ge p i with H H, { rw succ_above_below _ _ H at h, exact le_of_lt h }, { exact H } }, { intro h, rw succ_above_above _ _ h, exact lt_of_le_of_lt h (cast_succ_lt_succ i) }, end /-- Embedding `i : fin n` into `fin (n + 1)` with a hole around `p : fin (n + 1)` never results in `p` itself -/ theorem succ_above_ne (p : fin (n + 1)) (i : fin n) : p.succ_above i ≠ p := begin intro eq, by_cases H : i.cast_succ < p, { simpa [lt_irrefl, ←succ_above_below _ _ H, eq] using H }, { simpa [←succ_above_above _ _ (le_of_not_lt H), eq] using cast_succ_lt_succ i } end /-- Embedding a positive `fin n` results in a positive fin (n + 1)` -/ lemma succ_above_pos (p : fin (n + 2)) (i : fin (n + 1)) (h : 0 < i) : 0 < p.succ_above i := begin by_cases H : i.cast_succ < p, { simpa [succ_above_below _ _ H] using cast_succ_pos h }, { simpa [succ_above_above _ _ (le_of_not_lt H)] using succ_pos _ }, end /-- The range of `p.succ_above` is everything except `p`. -/ lemma range_succ_above (p : fin (n + 1)) : set.range (p.succ_above) = { i | i ≠ p } := begin ext, simp only [set.mem_range, ne.def, set.mem_set_of_eq], split, { rintro ⟨y, rfl⟩, exact succ_above_ne _ _ }, { intro h, cases lt_or_gt_of_ne h with H H, { refine ⟨x.cast_lt _, _⟩, { exact lt_of_lt_of_le H p.le_last }, { rw succ_above_below, { simp }, { exact H } } }, { refine ⟨x.pred _, _⟩, { exact (ne_of_lt (lt_of_le_of_lt p.zero_le H)).symm }, { rw succ_above_above, { simp }, { simpa [le_iff_coe_le_coe] using nat.le_pred_of_lt H } } } } end /-- Given a fixed pivot `x : fin (n + 1)`, `x.succ_above` is injective -/ lemma succ_above_right_injective {x : fin (n + 1)} : injective (succ_above x) := (succ_above x).injective /-- Given a fixed pivot `x : fin (n + 1)`, `x.succ_above` is injective -/ lemma succ_above_right_inj {x : fin (n + 1)} : x.succ_above a = x.succ_above b ↔ a = b := succ_above_right_injective.eq_iff /-- `succ_above` is injective at the pivot -/ lemma succ_above_left_injective : injective (@succ_above n) := λ _ _ h, by simpa [range_succ_above] using congr_arg (λ f : fin n ↪o fin (n + 1), (set.range f)ᶜ) h /-- `succ_above` is injective at the pivot -/ lemma succ_above_left_inj {x y : fin (n + 1)} : x.succ_above = y.succ_above ↔ x = y := succ_above_left_injective.eq_iff @[simp] lemma zero_succ_above {n : ℕ} (i : fin n) : (0 : fin (n + 1)).succ_above i = i.succ := rfl @[simp] lemma succ_succ_above_zero {n : ℕ} (i : fin (n + 1)) : (i.succ).succ_above 0 = 0 := succ_above_below _ _ (succ_pos _) @[simp] lemma succ_succ_above_succ {n : ℕ} (i : fin (n + 1)) (j : fin n) : (i.succ).succ_above j.succ = (i.succ_above j).succ := (lt_or_ge j.cast_succ i).elim (λ h, have h' : j.succ.cast_succ < i.succ, by simpa [lt_iff_coe_lt_coe] using h, by { ext, simp [succ_above_below _ _ h, succ_above_below _ _ h'] }) (λ h, have h' : i.succ ≤ j.succ.cast_succ, by simpa [le_iff_coe_le_coe] using h, by { ext, simp [succ_above_above _ _ h, succ_above_above _ _ h'] }) @[simp] lemma one_succ_above_zero {n : ℕ} : (1 : fin (n + 2)).succ_above 0 = 0 := succ_succ_above_zero 0 /-- By moving `succ` to the outside of this expression, we create opportunities for further simplification using `succ_above_zero` or `succ_succ_above_zero`. -/ @[simp] lemma succ_succ_above_one {n : ℕ} (i : fin (n + 2)) : (i.succ).succ_above 1 = (i.succ_above 0).succ := succ_succ_above_succ i 0 @[simp] lemma one_succ_above_succ {n : ℕ} (j : fin n) : (1 : fin (n + 2)).succ_above j.succ = j.succ.succ := succ_succ_above_succ 0 j @[simp] lemma one_succ_above_one {n : ℕ} : (1 : fin (n + 3)).succ_above 1 = 2 := succ_succ_above_succ 0 0 end succ_above section pred_above /-- `pred_above p i` embeds `i : fin (n+1)` into `fin n` by subtracting one if `p < i`. -/ def pred_above (p : fin n) (i : fin (n+1)) : fin n := if h : p.cast_succ < i then i.pred (ne_of_lt (lt_of_le_of_lt (zero_le p.cast_succ) h)).symm else i.cast_lt (lt_of_le_of_lt (le_of_not_lt h) p.2) lemma pred_above_right_monotone (p : fin n) : monotone p.pred_above := λ a b H, begin dsimp [pred_above], split_ifs with ha hb hb, all_goals { simp only [le_iff_coe_le_coe, coe_pred], }, { exact pred_le_pred H, }, { calc _ ≤ _ : nat.pred_le _ ... ≤ _ : H, }, { simp at ha, exact le_pred_of_lt (lt_of_le_of_lt ha hb), }, { exact H, }, end lemma pred_above_left_monotone (i : fin (n + 1)) : monotone (λ p, pred_above p i) := λ a b H, begin dsimp [pred_above], split_ifs with ha hb hb, all_goals { simp only [le_iff_coe_le_coe, coe_pred] }, { exact pred_le _, }, { have : b < a := cast_succ_lt_cast_succ_iff.mpr (hb.trans_le (le_of_not_gt ha)), exact absurd H this.not_le } end /-- `cast_pred` embeds `i : fin (n + 2)` into `fin (n + 1)` by lowering just `last (n + 1)` to `last n`. -/ def cast_pred (i : fin (n + 2)) : fin (n + 1) := pred_above (last n) i @[simp] lemma cast_pred_zero : cast_pred (0 : fin (n + 2)) = 0 := rfl @[simp] lemma cast_pred_one : cast_pred (1 : fin (n + 2)) = 1 := by { cases n, apply subsingleton.elim, refl } @[simp] theorem pred_above_zero {i : fin (n + 2)} (hi : i ≠ 0) : pred_above 0 i = i.pred hi := begin dsimp [pred_above], rw dif_pos, exact (pos_iff_ne_zero _).mpr hi, end @[simp] lemma cast_pred_last : cast_pred (last (n + 1)) = last n := by simp [eq_iff_veq, cast_pred, pred_above, cast_succ_lt_last] @[simp] lemma cast_pred_mk (n i : ℕ) (h : i < n + 1) : cast_pred ⟨i, lt_succ_of_lt h⟩ = ⟨i, h⟩ := begin have : ¬cast_succ (last n) < ⟨i, lt_succ_of_lt h⟩, { simpa [lt_iff_coe_lt_coe] using le_of_lt_succ h }, simp [cast_pred, pred_above, this] end lemma pred_above_below (p : fin (n + 1)) (i : fin (n + 2)) (h : i ≤ p.cast_succ) : p.pred_above i = i.cast_pred := begin have : i ≤ (last n).cast_succ := h.trans p.le_last, simp [pred_above, cast_pred, h.not_lt, this.not_lt] end @[simp] lemma pred_above_last : pred_above (fin.last n) = cast_pred := rfl lemma pred_above_last_apply (i : fin n) : pred_above (fin.last n) i = i.cast_pred := by rw pred_above_last lemma pred_above_above (p : fin n) (i : fin (n + 1)) (h : p.cast_succ < i) : p.pred_above i = i.pred (p.cast_succ.zero_le.trans_lt h).ne.symm := by simp [pred_above, h] lemma cast_pred_monotone : monotone (@cast_pred n) := pred_above_right_monotone (last _) /-- Sending `fin (n+1)` to `fin n` by subtracting one from anything above `p` then back to `fin (n+1)` with a gap around `p` is the identity away from `p`. -/ @[simp] lemma succ_above_pred_above {p : fin n} {i : fin (n + 1)} (h : i ≠ p.cast_succ) : p.cast_succ.succ_above (p.pred_above i) = i := begin dsimp [pred_above, succ_above], rcases p with ⟨p, _⟩, rcases i with ⟨i, _⟩, cases lt_or_le i p with H H, { rw dif_neg, rw if_pos, refl, exact H, simp, apply le_of_lt H, }, { rw dif_pos, rw if_neg, swap 3, -- For some reason `simp` doesn't fire fully unless we discharge the third goal. { exact lt_of_le_of_ne H (ne.symm h), }, { simp, }, { simp only [subtype.mk_eq_mk, ne.def, fin.cast_succ_mk] at h, simp only [pred, subtype.mk_lt_mk, not_lt], exact nat.le_pred_of_lt (nat.lt_of_le_and_ne H (ne.symm h)), }, }, end /-- Sending `fin n` into `fin (n + 1)` with a gap at `p` then back to `fin n` by subtracting one from anything above `p` is the identity. -/ @[simp] lemma pred_above_succ_above (p : fin n) (i : fin n) : p.pred_above (p.cast_succ.succ_above i) = i := begin dsimp [pred_above, succ_above], rcases p with ⟨p, _⟩, rcases i with ⟨i, _⟩, split_ifs, { rw dif_neg, { refl }, { simp_rw [if_pos h], simp only [subtype.mk_lt_mk, not_lt], exact le_of_lt h, }, }, { rw dif_pos, { refl, }, { simp_rw [if_neg h], exact lt_succ_iff.mpr (not_lt.mp h), }, }, end @[simp] theorem cast_pred_cast_succ (i : fin (n + 1)) : cast_pred i.cast_succ = i := by simp [cast_pred, pred_above, le_last] lemma cast_succ_cast_pred {i : fin (n + 2)} (h : i < last _) : cast_succ i.cast_pred = i := begin rw [cast_pred, pred_above, dif_neg], { simp [fin.eq_iff_veq] }, { exact h.not_le } end lemma coe_cast_pred_le_self (i : fin (n + 2)) : (i.cast_pred : ℕ) ≤ i := begin rcases i.le_last.eq_or_lt with rfl|h, { simp }, { rw [cast_pred, pred_above, dif_neg], { simp }, { simpa [lt_iff_coe_lt_coe, le_iff_coe_le_coe, lt_succ_iff] using h } } end lemma coe_cast_pred_lt_iff {i : fin (n + 2)} : (i.cast_pred : ℕ) < i ↔ i = fin.last _ := begin rcases i.le_last.eq_or_lt with rfl|H, { simp }, { simp only [ne_of_lt H], rw ←cast_succ_cast_pred H, simp } end lemma lt_last_iff_coe_cast_pred {i : fin (n + 2)} : i < fin.last _ ↔ (i.cast_pred : ℕ) = i := begin rcases i.le_last.eq_or_lt with rfl|H, { simp }, { simp only [H], rw ←cast_succ_cast_pred H, simp } end lemma forall_iff_succ_above {p : fin (n + 1) → Prop} (i : fin (n + 1)) : (∀ j, p j) ↔ p i ∧ ∀ j, p (i.succ_above j) := ⟨λ h, ⟨h _, λ j, h _⟩, λ h j, if hj : j = i then (hj.symm ▸ h.1) else begin cases n, { convert h.1 }, { cases lt_or_gt_of_ne hj with lt gt, { rcases j.zero_le.eq_or_lt with rfl|H, { convert h.2 0, rw succ_above_below; simp [lt] }, { have ltl : j < last _ := lt.trans_le i.le_last, convert h.2 j.cast_pred, simp [succ_above_below, cast_succ_cast_pred ltl, lt] } }, { convert h.2 (j.pred (i.zero_le.trans_lt gt).ne.symm), rw succ_above_above; simp [le_cast_succ_iff, gt.lt] } } end⟩ end pred_above /-- `min n m` as an element of `fin (m + 1)` -/ def clamp (n m : ℕ) : fin (m + 1) := of_nat $ min n m @[simp] lemma coe_clamp (n m : ℕ) : (clamp n m : ℕ) = min n m := nat.mod_eq_of_lt $ nat.lt_succ_iff.mpr $ min_le_right _ _ section tuple /-! ### Tuples We can think of the type `Π(i : fin n), α i` as `n`-tuples of elements of possibly varying type `α i`. A particular case is `fin n → α` of elements with all the same type. Here are some relevant operations, first about adding or removing elements at the beginning of a tuple. -/ /-- There is exactly one tuple of size zero. -/ example (α : fin 0 → Sort u) : unique (Π i : fin 0, α i) := by apply_instance @[simp] lemma tuple0_le {α : Π i : fin 0, Type*} [Π i, preorder (α i)] (f g : Π i, α i) : f ≤ g := fin_zero_elim variables {α : fin (n+1) → Type u} (x : α 0) (q : Πi, α i) (p : Π(i : fin n), α (i.succ)) (i : fin n) (y : α i.succ) (z : α 0) /-- The tail of an `n+1` tuple, i.e., its last `n` entries. -/ def tail (q : Πi, α i) : (Π(i : fin n), α (i.succ)) := λ i, q i.succ lemma tail_def {n : ℕ} {α : fin (n+1) → Type*} {q : Π i, α i} : tail (λ k : fin (n+1), q k) = (λ k : fin n, q k.succ) := rfl /-- Adding an element at the beginning of an `n`-tuple, to get an `n+1`-tuple. -/ def cons (x : α 0) (p : Π(i : fin n), α (i.succ)) : Πi, α i := λ j, fin.cases x p j @[simp] lemma tail_cons : tail (cons x p) = p := by simp [tail, cons] @[simp] lemma cons_succ : cons x p i.succ = p i := by simp [cons] @[simp] lemma cons_zero : cons x p 0 = x := by simp [cons] /-- Updating a tuple and adding an element at the beginning commute. -/ @[simp] lemma cons_update : cons x (update p i y) = update (cons x p) i.succ y := begin ext j, by_cases h : j = 0, { rw h, simp [ne.symm (succ_ne_zero i)] }, { let j' := pred j h, have : j'.succ = j := succ_pred j h, rw [← this, cons_succ], by_cases h' : j' = i, { rw h', simp }, { have : j'.succ ≠ i.succ, by rwa [ne.def, succ_inj], rw [update_noteq h', update_noteq this, cons_succ] } } end /-- Adding an element at the beginning of a tuple and then updating it amounts to adding it directly. -/ lemma update_cons_zero : update (cons x p) 0 z = cons z p := begin ext j, by_cases h : j = 0, { rw h, simp }, { simp only [h, update_noteq, ne.def, not_false_iff], let j' := pred j h, have : j'.succ = j := succ_pred j h, rw [← this, cons_succ, cons_succ] } end /-- Concatenating the first element of a tuple with its tail gives back the original tuple -/ @[simp] lemma cons_self_tail : cons (q 0) (tail q) = q := begin ext j, by_cases h : j = 0, { rw h, simp }, { let j' := pred j h, have : j'.succ = j := succ_pred j h, rw [← this, tail, cons_succ] } end /-- Updating the first element of a tuple does not change the tail. -/ @[simp] lemma tail_update_zero : tail (update q 0 z) = tail q := by { ext j, simp [tail, fin.succ_ne_zero] } /-- Updating a nonzero element and taking the tail commute. -/ @[simp] lemma tail_update_succ : tail (update q i.succ y) = update (tail q) i y := begin ext j, by_cases h : j = i, { rw h, simp [tail] }, { simp [tail, (fin.succ_injective n).ne h, h] } end lemma comp_cons {α : Type*} {β : Type*} (g : α → β) (y : α) (q : fin n → α) : g ∘ (cons y q) = cons (g y) (g ∘ q) := begin ext j, by_cases h : j = 0, { rw h, refl }, { let j' := pred j h, have : j'.succ = j := succ_pred j h, rw [← this, cons_succ, comp_app, cons_succ] } end lemma comp_tail {α : Type*} {β : Type*} (g : α → β) (q : fin n.succ → α) : g ∘ (tail q) = tail (g ∘ q) := by { ext j, simp [tail] } lemma le_cons [Π i, preorder (α i)] {x : α 0} {q : Π i, α i} {p : Π i : fin n, α i.succ} : q ≤ cons x p ↔ q 0 ≤ x ∧ tail q ≤ p := forall_fin_succ.trans $ and_congr iff.rfl $ forall_congr $ λ j, by simp [tail] lemma cons_le [Π i, preorder (α i)] {x : α 0} {q : Π i, α i} {p : Π i : fin n, α i.succ} : cons x p ≤ q ↔ x ≤ q 0 ∧ p ≤ tail q := @le_cons _ (λ i, order_dual (α i)) _ x q p @[simp] lemma range_cons {α : Type*} {n : ℕ} (x : α) (b : fin n → α) : set.range (fin.cons x b : fin n.succ → α) = insert x (set.range b) := begin ext y, simp only [set.mem_range, set.mem_insert_iff], split, { rintros ⟨i, rfl⟩, refine cases (or.inl (cons_zero _ _)) (λ i, or.inr ⟨i, _⟩) i, rw cons_succ }, { rintros (rfl | ⟨i, hi⟩), { exact ⟨0, fin.cons_zero _ _⟩ }, { refine ⟨i.succ, _⟩, rw [cons_succ, hi] } } end /-- `fin.append ho u v` appends two vectors of lengths `m` and `n` to produce one of length `o = m + n`. `ho` provides control of definitional equality for the vector length. -/ def append {α : Type*} {o : ℕ} (ho : o = m + n) (u : fin m → α) (v : fin n → α) : fin o → α := λ i, if h : (i : ℕ) < m then u ⟨i, h⟩ else v ⟨(i : ℕ) - m, (nat.sub_lt_left_iff_lt_add (le_of_not_lt h)).2 (ho ▸ i.property)⟩ @[simp] lemma fin_append_apply_zero {α : Type*} {o : ℕ} (ho : (o + 1) = (m + 1) + n) (u : fin (m + 1) → α) (v : fin n → α) : fin.append ho u v 0 = u 0 := rfl end tuple section tuple_right /-! In the previous section, we have discussed inserting or removing elements on the left of a tuple. In this section, we do the same on the right. A difference is that `fin (n+1)` is constructed inductively from `fin n` starting from the left, not from the right. This implies that Lean needs more help to realize that elements belong to the right types, i.e., we need to insert casts at several places. -/ variables {α : fin (n+1) → Type u} (x : α (last n)) (q : Πi, α i) (p : Π(i : fin n), α i.cast_succ) (i : fin n) (y : α i.cast_succ) (z : α (last n)) /-- The beginning of an `n+1` tuple, i.e., its first `n` entries -/ def init (q : Πi, α i) (i : fin n) : α i.cast_succ := q i.cast_succ lemma init_def {n : ℕ} {α : fin (n+1) → Type*} {q : Π i, α i} : init (λ k : fin (n+1), q k) = (λ k : fin n, q k.cast_succ) := rfl /-- Adding an element at the end of an `n`-tuple, to get an `n+1`-tuple. The name `snoc` comes from `cons` (i.e., adding an element to the left of a tuple) read in reverse order. -/ def snoc (p : Π(i : fin n), α i.cast_succ) (x : α (last n)) (i : fin (n+1)) : α i := if h : i.val < n then _root_.cast (by rw fin.cast_succ_cast_lt i h) (p (cast_lt i h)) else _root_.cast (by rw eq_last_of_not_lt h) x @[simp] lemma init_snoc : init (snoc p x) = p := begin ext i, have h' := fin.cast_lt_cast_succ i i.is_lt, simp [init, snoc, i.is_lt, h'], convert cast_eq rfl (p i) end @[simp] lemma snoc_cast_succ : snoc p x i.cast_succ = p i := begin have : i.cast_succ.val < n := i.is_lt, have h' := fin.cast_lt_cast_succ i i.is_lt, simp [snoc, this, h'], convert cast_eq rfl (p i) end @[simp] lemma snoc_last : snoc p x (last n) = x := by { simp [snoc] } /-- Updating a tuple and adding an element at the end commute. -/ @[simp] lemma snoc_update : snoc (update p i y) x = update (snoc p x) i.cast_succ y := begin ext j, by_cases h : j.val < n, { simp only [snoc, h, dif_pos], by_cases h' : j = cast_succ i, { have C1 : α i.cast_succ = α j, by rw h', have E1 : update (snoc p x) i.cast_succ y j = _root_.cast C1 y, { have : update (snoc p x) j (_root_.cast C1 y) j = _root_.cast C1 y, by simp, convert this, { exact h'.symm }, { exact heq_of_cast_eq (congr_arg α (eq.symm h')) rfl } }, have C2 : α i.cast_succ = α (cast_succ (cast_lt j h)), by rw [cast_succ_cast_lt, h'], have E2 : update p i y (cast_lt j h) = _root_.cast C2 y, { have : update p (cast_lt j h) (_root_.cast C2 y) (cast_lt j h) = _root_.cast C2 y, by simp, convert this, { simp [h, h'] }, { exact heq_of_cast_eq C2 rfl } }, rw [E1, E2], exact eq_rec_compose _ _ _ }, { have : ¬(cast_lt j h = i), by { assume E, apply h', rw [← E, cast_succ_cast_lt] }, simp [h', this, snoc, h] } }, { rw eq_last_of_not_lt h, simp [ne.symm (ne_of_lt (cast_succ_lt_last i))] } end /-- Adding an element at the beginning of a tuple and then updating it amounts to adding it directly. -/ lemma update_snoc_last : update (snoc p x) (last n) z = snoc p z := begin ext j, by_cases h : j.val < n, { have : j ≠ last n := ne_of_lt h, simp [h, update_noteq, this, snoc] }, { rw eq_last_of_not_lt h, simp } end /-- Concatenating the first element of a tuple with its tail gives back the original tuple -/ @[simp] lemma snoc_init_self : snoc (init q) (q (last n)) = q := begin ext j, by_cases h : j.val < n, { have : j ≠ last n := ne_of_lt h, simp [h, update_noteq, this, snoc, init, cast_succ_cast_lt], have A : cast_succ (cast_lt j h) = j := cast_succ_cast_lt _ _, rw ← cast_eq rfl (q j), congr' 1; rw A }, { rw eq_last_of_not_lt h, simp } end /-- Updating the last element of a tuple does not change the beginning. -/ @[simp] lemma init_update_last : init (update q (last n) z) = init q := by { ext j, simp [init, ne_of_lt, cast_succ_lt_last] } /-- Updating an element and taking the beginning commute. -/ @[simp] lemma init_update_cast_succ : init (update q i.cast_succ y) = update (init q) i y := begin ext j, by_cases h : j = i, { rw h, simp [init] }, { simp [init, h] } end /-- `tail` and `init` commute. We state this lemma in a non-dependent setting, as otherwise it would involve a cast to convince Lean that the two types are equal, making it harder to use. -/ lemma tail_init_eq_init_tail {β : Type*} (q : fin (n+2) → β) : tail (init q) = init (tail q) := by { ext i, simp [tail, init, cast_succ_fin_succ] } /-- `cons` and `snoc` commute. We state this lemma in a non-dependent setting, as otherwise it would involve a cast to convince Lean that the two types are equal, making it harder to use. -/ lemma cons_snoc_eq_snoc_cons {β : Type*} (a : β) (q : fin n → β) (b : β) : @cons n.succ (λ i, β) a (snoc q b) = snoc (cons a q) b := begin ext i, by_cases h : i = 0, { rw h, refl }, set j := pred i h with ji, have : i = j.succ, by rw [ji, succ_pred], rw [this, cons_succ], by_cases h' : j.val < n, { set k := cast_lt j h' with jk, have : j = k.cast_succ, by rw [jk, cast_succ_cast_lt], rw [this, ← cast_succ_fin_succ], simp }, rw [eq_last_of_not_lt h', succ_last], simp end lemma comp_snoc {α : Type*} {β : Type*} (g : α → β) (q : fin n → α) (y : α) : g ∘ (snoc q y) = snoc (g ∘ q) (g y) := begin ext j, by_cases h : j.val < n, { have : j ≠ last n := ne_of_lt h, simp [h, this, snoc, cast_succ_cast_lt] }, { rw eq_last_of_not_lt h, simp } end lemma comp_init {α : Type*} {β : Type*} (g : α → β) (q : fin n.succ → α) : g ∘ (init q) = init (g ∘ q) := by { ext j, simp [init] } end tuple_right section insert_nth variables {α : fin (n+1) → Type u} {β : Type v} /-- Insert an element into a tuple at a given position, auxiliary definition. For the general definition, see `insert_nth`. -/ def insert_nth' {α : fin (n + 2) → Type u} (i : fin (n + 2)) (x : α i) (p : Π j : fin (n + 1), α (i.succ_above j)) (j : fin (n + 2)) : α j := if h : i = j then _root_.cast (congr_arg α h) x else if h' : j < i then _root_.cast (congr_arg α $ begin obtain ⟨k, hk⟩ : ∃ (k : fin (n + 1)), k.cast_succ = j, { refine ⟨⟨(j : ℕ), _⟩, _⟩, { exact lt_of_lt_of_le h' i.is_le, }, { simp }, }, subst hk, simp [succ_above_below, h'], end) (p j.cast_pred) else _root_.cast (congr_arg α $ begin have lt : i < j := lt_of_le_of_ne (le_of_not_lt h') h, have : j ≠ 0 := (ne_of_gt (lt_of_le_of_lt i.zero_le lt)), rw [←succ_pred j this, ←le_cast_succ_iff] at lt, simp [pred_above_zero this, succ_above_above _ _ lt] end) (p (fin.pred_above 0 j)) /-- Insert an element into a tuple at a given position. For `i = 0` see `fin.cons`, for `i = fin.last n` see `fin.snoc`. -/ def insert_nth : Π {n : ℕ} {α : fin (n + 1) → Type u} (i : fin (n + 1)) (x : α i) (p : Π j : fin n, α (i.succ_above j)) (j : fin (n + 1)), α j | 0 _ _ x _ _ := _root_.cast (by congr) x | (n + 1) _ i x p j := insert_nth' i x p j @[simp] lemma insert_nth_apply_same (i : fin (n + 1)) (x : α i) (p : Π j, α (i.succ_above j)) : insert_nth i x p i = x := by { cases n; simp [insert_nth, insert_nth'] } @[simp] lemma insert_nth_apply_succ_above (i : fin (n + 1)) (x : α i) (p : Π j, α (i.succ_above j)) (j : fin n) : insert_nth i x p (i.succ_above j) = p j := begin cases n, { exact j.elim0 }, simp only [insert_nth, insert_nth', dif_neg (succ_above_ne _ _).symm], cases succ_above_lt_ge i j with h h, { rw dif_pos, refine eq_of_heq ((cast_heq _ _).trans _), { simp [h] }, { congr, simp [succ_above_below, h] } }, { rw dif_neg, refine eq_of_heq ((cast_heq _ _).trans _), { simp [h] }, { congr, simp [succ_above_above, h, succ_ne_zero] } } end @[simp] lemma insert_nth_comp_succ_above (i : fin (n + 1)) (x : β) (p : fin n → β) : insert_nth i x p ∘ i.succ_above = p := funext $ insert_nth_apply_succ_above i x p lemma insert_nth_eq_iff {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q : Π j, α j} : i.insert_nth x p = q ↔ q i = x ∧ p = (λ j, q (i.succ_above j)) := by simp [funext_iff, forall_iff_succ_above i, eq_comm] lemma eq_insert_nth_iff {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q : Π j, α j} : q = i.insert_nth x p ↔ q i = x ∧ p = (λ j, q (i.succ_above j)) := eq_comm.trans insert_nth_eq_iff lemma insert_nth_zero (x : α 0) (p : Π j : fin n, α (succ_above 0 j)) : insert_nth 0 x p = cons x (λ j, _root_.cast (congr_arg α (congr_fun succ_above_zero j)) (p j)) := begin refine insert_nth_eq_iff.2 ⟨by simp, _⟩, ext j, convert (cons_succ _ _ _).symm end @[simp] lemma insert_nth_zero' (x : β) (p : fin n → β) : @insert_nth _ (λ _, β) 0 x p = cons x p := by simp [insert_nth_zero] lemma insert_nth_last (x : α (last n)) (p : Π j : fin n, α ((last n).succ_above j)) : insert_nth (last n) x p = snoc (λ j, _root_.cast (congr_arg α (succ_above_last_apply j)) (p j)) x := begin refine insert_nth_eq_iff.2 ⟨by simp, _⟩, ext j, apply eq_of_heq, transitivity snoc (λ j, _root_.cast (congr_arg α (succ_above_last_apply j)) (p j)) x j.cast_succ, { rw [snoc_cast_succ], exact (cast_heq _ _).symm }, { apply congr_arg_heq, rw [succ_above_last] } end @[simp] lemma insert_nth_last' (x : β) (p : fin n → β) : @insert_nth _ (λ _, β) (last n) x p = snoc p x := by simp [insert_nth_last] variables [Π i, preorder (α i)] lemma insert_nth_le_iff {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q : Π j, α j} : i.insert_nth x p ≤ q ↔ x ≤ q i ∧ p ≤ (λ j, q (i.succ_above j)) := by simp [pi.le_def, forall_iff_succ_above i] lemma le_insert_nth_iff {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q : Π j, α j} : q ≤ i.insert_nth x p ↔ q i ≤ x ∧ (λ j, q (i.succ_above j)) ≤ p := by simp [pi.le_def, forall_iff_succ_above i] open set lemma insert_nth_mem_Icc {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q₁ q₂ : Π j, α j} : i.insert_nth x p ∈ Icc q₁ q₂ ↔ x ∈ Icc (q₁ i) (q₂ i) ∧ p ∈ Icc (λ j, q₁ (i.succ_above j)) (λ j, q₂ (i.succ_above j)) := by simp only [mem_Icc, insert_nth_le_iff, le_insert_nth_iff, and.assoc, and.left_comm] lemma preimage_insert_nth_Icc_of_mem {i : fin (n + 1)} {x : α i} {q₁ q₂ : Π j, α j} (hx : x ∈ Icc (q₁ i) (q₂ i)) : i.insert_nth x ⁻¹' (Icc q₁ q₂) = Icc (λ j, q₁ (i.succ_above j)) (λ j, q₂ (i.succ_above j)) := set.ext $ λ p, by simp only [mem_preimage, insert_nth_mem_Icc, hx, true_and] lemma preimage_insert_nth_Icc_of_not_mem {i : fin (n + 1)} {x : α i} {q₁ q₂ : Π j, α j} (hx : x ∉ Icc (q₁ i) (q₂ i)) : i.insert_nth x ⁻¹' (Icc q₁ q₂) = ∅ := set.ext $ λ p, by simp only [mem_preimage, insert_nth_mem_Icc, hx, false_and, mem_empty_eq] end insert_nth section find /-- `find p` returns the first index `n` where `p n` is satisfied, and `none` if it is never satisfied. -/ def find : Π {n : ℕ} (p : fin n → Prop) [decidable_pred p], option (fin n) | 0 p _ := none | (n+1) p _ := by resetI; exact option.cases_on (@find n (λ i, p (i.cast_lt (nat.lt_succ_of_lt i.2))) _) (if h : p (fin.last n) then some (fin.last n) else none) (λ i, some (i.cast_lt (nat.lt_succ_of_lt i.2))) /-- If `find p = some i`, then `p i` holds -/ lemma find_spec : Π {n : ℕ} (p : fin n → Prop) [decidable_pred p] {i : fin n} (hi : i ∈ by exactI fin.find p), p i | 0 p I i hi := option.no_confusion hi | (n+1) p I i hi := begin dsimp [find] at hi, resetI, cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with j, { rw h at hi, dsimp at hi, split_ifs at hi with hl hl, { exact option.some_inj.1 hi ▸ hl }, { exact option.no_confusion hi } }, { rw h at hi, rw [← option.some_inj.1 hi], exact find_spec _ h } end /-- `find p` does not return `none` if and only if `p i` holds at some index `i`. -/ lemma is_some_find_iff : Π {n : ℕ} {p : fin n → Prop} [decidable_pred p], by exactI (find p).is_some ↔ ∃ i, p i | 0 p _ := iff_of_false (λ h, bool.no_confusion h) (λ ⟨i, _⟩, fin_zero_elim i) | (n+1) p _ := ⟨λ h, begin rw [option.is_some_iff_exists] at h, cases h with i hi, exactI ⟨i, find_spec _ hi⟩ end, λ ⟨⟨i, hin⟩, hi⟩, begin resetI, dsimp [find], cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with j, { split_ifs with hl hl, { exact option.is_some_some }, { have := (@is_some_find_iff n (λ x, p (x.cast_lt (nat.lt_succ_of_lt x.2))) _).2 ⟨⟨i, lt_of_le_of_ne (nat.le_of_lt_succ hin) (λ h, by clear_aux_decl; cases h; exact hl hi)⟩, hi⟩, rw h at this, exact this } }, { simp } end⟩ /-- `find p` returns `none` if and only if `p i` never holds. -/ lemma find_eq_none_iff {n : ℕ} {p : fin n → Prop} [decidable_pred p] : find p = none ↔ ∀ i, ¬ p i := by rw [← not_exists, ← is_some_find_iff]; cases (find p); simp /-- If `find p` returns `some i`, then `p j` does not hold for `j < i`, i.e., `i` is minimal among the indices where `p` holds. -/ lemma find_min : Π {n : ℕ} {p : fin n → Prop} [decidable_pred p] {i : fin n} (hi : i ∈ by exactI fin.find p) {j : fin n} (hj : j < i), ¬ p j | 0 p _ i hi j hj hpj := option.no_confusion hi | (n+1) p _ i hi ⟨j, hjn⟩ hj hpj := begin resetI, dsimp [find] at hi, cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with k, { rw [h] at hi, split_ifs at hi with hl hl, { have := option.some_inj.1 hi, subst this, rw [find_eq_none_iff] at h, exact h ⟨j, hj⟩ hpj }, { exact option.no_confusion hi } }, { rw h at hi, dsimp at hi, have := option.some_inj.1 hi, subst this, exact find_min h (show (⟨j, lt_trans hj k.2⟩ : fin n) < k, from hj) hpj } end lemma find_min' {p : fin n → Prop} [decidable_pred p] {i : fin n} (h : i ∈ fin.find p) {j : fin n} (hj : p j) : i ≤ j := le_of_not_gt (λ hij, find_min h hij hj) lemma nat_find_mem_find {p : fin n → Prop} [decidable_pred p] (h : ∃ i, ∃ hin : i < n, p ⟨i, hin⟩) : (⟨nat.find h, (nat.find_spec h).fst⟩ : fin n) ∈ find p := let ⟨i, hin, hi⟩ := h in begin cases hf : find p with f, { rw [find_eq_none_iff] at hf, exact (hf ⟨i, hin⟩ hi).elim }, { refine option.some_inj.2 (le_antisymm _ _), { exact find_min' hf (nat.find_spec h).snd }, { exact nat.find_min' _ ⟨f.2, by convert find_spec p hf; exact fin.eta _ _⟩ } } end lemma mem_find_iff {p : fin n → Prop} [decidable_pred p] {i : fin n} : i ∈ fin.find p ↔ p i ∧ ∀ j, p j → i ≤ j := ⟨λ hi, ⟨find_spec _ hi, λ _, find_min' hi⟩, begin rintros ⟨hpi, hj⟩, cases hfp : fin.find p, { rw [find_eq_none_iff] at hfp, exact (hfp _ hpi).elim }, { exact option.some_inj.2 (le_antisymm (find_min' hfp hpi) (hj _ (find_spec _ hfp))) } end⟩ lemma find_eq_some_iff {p : fin n → Prop} [decidable_pred p] {i : fin n} : fin.find p = some i ↔ p i ∧ ∀ j, p j → i ≤ j := mem_find_iff lemma mem_find_of_unique {p : fin n → Prop} [decidable_pred p] (h : ∀ i j, p i → p j → i = j) {i : fin n} (hi : p i) : i ∈ fin.find p := mem_find_iff.2 ⟨hi, λ j hj, le_of_eq $ h i j hi hj⟩ end find @[simp] lemma coe_of_nat_eq_mod (m n : ℕ) : ((n : fin (succ m)) : ℕ) = n % succ m := by rw [← of_nat_eq_coe]; refl @[simp] lemma coe_of_nat_eq_mod' (m n : ℕ) [I : fact (0 < m)] : (@fin.of_nat' _ I n : ℕ) = n % m := rfl section mul /-! ### mul -/ lemma val_mul {n : ℕ} : ∀ a b : fin n, (a * b).val = (a.val * b.val) % n | ⟨_, _⟩ ⟨_, _⟩ := rfl lemma coe_mul {n : ℕ} : ∀ a b : fin n, ((a * b : fin n) : ℕ) = (a * b) % n | ⟨_, _⟩ ⟨_, _⟩ := rfl @[simp] protected lemma mul_one (k : fin (n + 1)) : k * 1 = k := by { cases n, simp, simp [eq_iff_veq, mul_def, mod_eq_of_lt (is_lt k)] } @[simp] protected lemma one_mul (k : fin (n + 1)) : (1 : fin (n + 1)) * k = k := by { cases n, simp, simp [eq_iff_veq, mul_def, mod_eq_of_lt (is_lt k)] } @[simp] protected lemma mul_zero (k : fin (n + 1)) : k * 0 = 0 := by simp [eq_iff_veq, mul_def] @[simp] protected lemma zero_mul (k : fin (n + 1)) : (0 : fin (n + 1)) * k = 0 := by simp [eq_iff_veq, mul_def] end mul end fin
77af819efe29916c69391b8133ded40fc904b97b
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/src/Init/Lean/Parser/Transform.lean
d0bf65ae25340739736e02040e20b2eea6fdc898
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
1,561
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Init.Lean.Parser.Parser namespace Lean namespace Syntax def manyToSepBy (stx : Syntax) (sepTk : String) : Syntax := match stx with | node k args => let args := args.foldlFrom (fun (newArgs : Array Syntax) arg => let prevArg := newArgs.back; match prevArg.getTailInfo with | some info => let prevArg := prevArg.setTailInfo info.truncateTrailing; let newArgs := newArgs.set! (newArgs.size - 1) prevArg; let newArgs := newArgs.push (atom info sepTk); newArgs.push arg | none => let newArgs := newArgs.push (atom none sepTk); newArgs.push arg) #[args.get! 0] 1; node k args | stx => stx def removeParen (stx : Syntax) : Syntax := stx.ifNodeKind `Lean.Parser.Term.paren (fun stx => let body := stx.getArg 1; if body.getNumArgs != 2 then stx.val else if (body.getArg 1).isNone then let body := body.getArg 0; match stx.getArg 2, body.getTailInfo with | atom (some info) ")", some bodyInfo => let bodyInfoTrail := bodyInfo.trailing.toString ++ " "; -- add whithespaces for removed parentheses let bodyInfoTrail := bodyInfoTrail ++ info.trailing.toString; -- add close paren trailing spaces body.setTailInfo (some { trailing := bodyInfoTrail.toSubstring, .. bodyInfo }) | _, _ => stx.val else stx.val) (fun _ => stx) end Syntax end Lean
245b74146b4ff2c615055f4fbcf58be5e616c722
626e312b5c1cb2d88fca108f5933076012633192
/src/algebra/lie/classical.lean
bdc163b8d04e711931d38b7d328647b5a0baeecd
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,140
lean
/- Copyright (c) 2020 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.invertible import algebra.lie.skew_adjoint import algebra.lie.abelian import linear_algebra.matrix.trace /-! # Classical Lie algebras This file is the place to find definitions and basic properties of the classical Lie algebras: * Aₗ = sl(l+1) * Bₗ ≃ so(l+1, l) ≃ so(2l+1) * Cₗ = sp(l) * Dₗ ≃ so(l, l) ≃ so(2l) ## Main definitions * `lie_algebra.special_linear.sl` * `lie_algebra.symplectic.sp` * `lie_algebra.orthogonal.so` * `lie_algebra.orthogonal.so'` * `lie_algebra.orthogonal.so_indefinite_equiv` * `lie_algebra.orthogonal.type_D` * `lie_algebra.orthogonal.type_B` * `lie_algebra.orthogonal.type_D_equiv_so'` * `lie_algebra.orthogonal.type_B_equiv_so'` ## Implementation notes ### Matrices or endomorphisms Given a finite type and a commutative ring, the corresponding square matrices are equivalent to the endomorphisms of the corresponding finite-rank free module as Lie algebras, see `lie_equiv_matrix'`. We can thus define the classical Lie algebras as Lie subalgebras either of matrices or of endomorphisms. We have opted for the former. At the time of writing (August 2020) it is unclear which approach should be preferred so the choice should be assumed to be somewhat arbitrary. ### Diagonal quadratic form or diagonal Cartan subalgebra For the algebras of type `B` and `D`, there are two natural definitions. For example since the the `2l × 2l` matrix: $$ J = \left[\begin{array}{cc} 0_l & 1_l\\ 1_l & 0_l \end{array}\right] $$ defines a symmetric bilinear form equivalent to that defined by the identity matrix `I`, we can define the algebras of type `D` to be the Lie subalgebra of skew-adjoint matrices either for `J` or for `I`. Both definitions have their advantages (in particular the `J`-skew-adjoint matrices define a Lie algebra for which the diagonal matrices form a Cartan subalgebra) and so we provide both. We thus also provide equivalences `type_D_equiv_so'`, `so_indefinite_equiv` which show the two definitions are equivalent. Similarly for the algebras of type `B`. ## Tags classical lie algebra, special linear, symplectic, orthogonal -/ universes u₁ u₂ namespace lie_algebra open_locale matrix variables (n p q l : Type*) (R : Type u₂) variables [decidable_eq n] [decidable_eq p] [decidable_eq q] [decidable_eq l] variables [comm_ring R] @[simp] lemma matrix_trace_commutator_zero [fintype n] (X Y : matrix n n R) : matrix.trace n R R ⁅X, Y⁆ = 0 := calc _ = matrix.trace n R R (X ⬝ Y) - matrix.trace n R R (Y ⬝ X) : linear_map.map_sub _ _ _ ... = matrix.trace n R R (X ⬝ Y) - matrix.trace n R R (X ⬝ Y) : congr_arg (λ x, _ - x) (matrix.trace_mul_comm X Y) ... = 0 : sub_self _ namespace special_linear /-- The special linear Lie algebra: square matrices of trace zero. -/ def sl [fintype n] : lie_subalgebra R (matrix n n R) := { lie_mem' := λ X Y _ _, linear_map.mem_ker.2 $ matrix_trace_commutator_zero _ _ _ _, ..linear_map.ker (matrix.trace n R R) } lemma sl_bracket [fintype n] (A B : sl n R) : ⁅A, B⁆.val = A.val ⬝ B.val - B.val ⬝ A.val := rfl section elementary_basis variables {n} (i j : n) /-- It is useful to define these matrices for explicit calculations in sl n R. -/ abbreviation E : matrix n n R := λ i' j', if i = i' ∧ j = j' then 1 else 0 @[simp] lemma E_apply_one : E R i j i j = 1 := if_pos (and.intro rfl rfl) @[simp] lemma E_apply_zero (i' j' : n) (h : ¬(i = i' ∧ j = j')) : E R i j i' j' = 0 := if_neg h @[simp] lemma E_diag_zero (h : j ≠ i) : matrix.diag n R R (E R i j) = 0 := funext $ λ k, if_neg $ λ ⟨e₁, e₂⟩, h (e₂.trans e₁.symm) variable [fintype n] lemma E_trace_zero (h : j ≠ i) : matrix.trace n R R (E R i j) = 0 := by simp [h] /-- When j ≠ i, the elementary matrices are elements of sl n R, in fact they are part of a natural basis of sl n R. -/ def Eb (h : j ≠ i) : sl n R := ⟨E R i j, show E R i j ∈ linear_map.ker (matrix.trace n R R), from E_trace_zero R i j h⟩ @[simp] lemma Eb_val (h : j ≠ i) : (Eb R i j h).val = E R i j := rfl end elementary_basis lemma sl_non_abelian [fintype n] [nontrivial R] (h : 1 < fintype.card n) : ¬is_lie_abelian ↥(sl n R) := begin rcases fintype.exists_pair_of_one_lt_card h with ⟨j, i, hij⟩, let A := Eb R i j hij, let B := Eb R j i hij.symm, intros c, have c' : A.val ⬝ B.val = B.val ⬝ A.val, by { rw [← sub_eq_zero, ← sl_bracket, c.trivial], refl }, have : (1 : R) = 0 := by simpa [matrix.mul_apply, hij] using (congr_fun (congr_fun c' i) i), exact one_ne_zero this, end end special_linear namespace symplectic /-- The matrix defining the canonical skew-symmetric bilinear form. -/ def J : matrix (l ⊕ l) (l ⊕ l) R := matrix.from_blocks 0 (-1) 1 0 /-- The symplectic Lie algebra: skew-adjoint matrices with respect to the canonical skew-symmetric bilinear form. -/ def sp [fintype l] : lie_subalgebra R (matrix (l ⊕ l) (l ⊕ l) R) := skew_adjoint_matrices_lie_subalgebra (J l R) end symplectic namespace orthogonal /-- The definite orthogonal Lie subalgebra: skew-adjoint matrices with respect to the symmetric bilinear form defined by the identity matrix. -/ def so [fintype n] : lie_subalgebra R (matrix n n R) := skew_adjoint_matrices_lie_subalgebra (1 : matrix n n R) @[simp] lemma mem_so [fintype n] (A : matrix n n R) : A ∈ so n R ↔ Aᵀ = -A := begin erw mem_skew_adjoint_matrices_submodule, simp only [matrix.is_skew_adjoint, matrix.is_adjoint_pair, matrix.mul_one, matrix.one_mul], end /-- The indefinite diagonal matrix with `p` 1s and `q` -1s. -/ def indefinite_diagonal : matrix (p ⊕ q) (p ⊕ q) R := matrix.diagonal $ sum.elim (λ _, 1) (λ _, -1) /-- The indefinite orthogonal Lie subalgebra: skew-adjoint matrices with respect to the symmetric bilinear form defined by the indefinite diagonal matrix. -/ def so' [fintype p] [fintype q] : lie_subalgebra R (matrix (p ⊕ q) (p ⊕ q) R) := skew_adjoint_matrices_lie_subalgebra $ indefinite_diagonal p q R /-- A matrix for transforming the indefinite diagonal bilinear form into the definite one, provided the parameter `i` is a square root of -1. -/ def Pso (i : R) : matrix (p ⊕ q) (p ⊕ q) R := matrix.diagonal $ sum.elim (λ _, 1) (λ _, i) variables [fintype p] [fintype q] lemma Pso_inv {i : R} (hi : i*i = -1) : (Pso p q R i) * (Pso p q R (-i)) = 1 := begin ext x y, rcases x; rcases y, { -- x y : p by_cases h : x = y; simp [Pso, indefinite_diagonal, h], }, { -- x : p, y : q simp [Pso, indefinite_diagonal], }, { -- x : q, y : p simp [Pso, indefinite_diagonal], }, { -- x y : q by_cases h : x = y; simp [Pso, indefinite_diagonal, h, hi], }, end lemma is_unit_Pso {i : R} (hi : i*i = -1) : is_unit (Pso p q R i) := ⟨{ val := Pso p q R i, inv := Pso p q R (-i), val_inv := Pso_inv p q R hi, inv_val := by { apply matrix.nonsing_inv_left_right, exact Pso_inv p q R hi, }, }, rfl⟩ lemma indefinite_diagonal_transform {i : R} (hi : i*i = -1) : (Pso p q R i)ᵀ ⬝ (indefinite_diagonal p q R) ⬝ (Pso p q R i) = 1 := begin ext x y, rcases x; rcases y, { -- x y : p by_cases h : x = y; simp [Pso, indefinite_diagonal, h], }, { -- x : p, y : q simp [Pso, indefinite_diagonal], }, { -- x : q, y : p simp [Pso, indefinite_diagonal], }, { -- x y : q by_cases h : x = y; simp [Pso, indefinite_diagonal, h, hi], }, end /-- An equivalence between the indefinite and definite orthogonal Lie algebras, over a ring containing a square root of -1. -/ noncomputable def so_indefinite_equiv {i : R} (hi : i*i = -1) : so' p q R ≃ₗ⁅R⁆ so (p ⊕ q) R := begin apply (skew_adjoint_matrices_lie_subalgebra_equiv (indefinite_diagonal p q R) (Pso p q R i) (is_unit_Pso p q R hi)).trans, apply lie_equiv.of_eq, ext A, rw indefinite_diagonal_transform p q R hi, refl, end lemma so_indefinite_equiv_apply {i : R} (hi : i*i = -1) (A : so' p q R) : (so_indefinite_equiv p q R hi A : matrix (p ⊕ q) (p ⊕ q) R) = (Pso p q R i)⁻¹ ⬝ (A : matrix (p ⊕ q) (p ⊕ q) R) ⬝ (Pso p q R i) := by erw [lie_equiv.trans_apply, lie_equiv.of_eq_apply, skew_adjoint_matrices_lie_subalgebra_equiv_apply] /-- A matrix defining a canonical even-rank symmetric bilinear form. It looks like this as a `2l x 2l` matrix of `l x l` blocks: [ 0 1 ] [ 1 0 ] -/ def JD : matrix (l ⊕ l) (l ⊕ l) R := matrix.from_blocks 0 1 1 0 /-- The classical Lie algebra of type D as a Lie subalgebra of matrices associated to the matrix `JD`. -/ def type_D [fintype l] := skew_adjoint_matrices_lie_subalgebra (JD l R) /-- A matrix transforming the bilinear form defined by the matrix `JD` into a split-signature diagonal matrix. It looks like this as a `2l x 2l` matrix of `l x l` blocks: [ 1 -1 ] [ 1 1 ] -/ def PD : matrix (l ⊕ l) (l ⊕ l) R := matrix.from_blocks 1 (-1) 1 1 /-- The split-signature diagonal matrix. -/ def S := indefinite_diagonal l l R lemma S_as_blocks : S l R = matrix.from_blocks 1 0 0 (-1) := begin rw [← matrix.diagonal_one, matrix.diagonal_neg, matrix.from_blocks_diagonal], refl, end lemma JD_transform [fintype l] : (PD l R)ᵀ ⬝ (JD l R) ⬝ (PD l R) = (2 : R) • (S l R) := begin have h : (PD l R)ᵀ ⬝ (JD l R) = matrix.from_blocks 1 1 1 (-1) := by { simp [PD, JD, matrix.from_blocks_transpose, matrix.from_blocks_multiply], }, erw [h, S_as_blocks, matrix.from_blocks_multiply, matrix.from_blocks_smul], congr; simp [two_smul], end lemma PD_inv [fintype l] [invertible (2 : R)] : (PD l R) * (⅟(2 : R) • (PD l R)ᵀ) = 1 := begin have h : ⅟(2 : R) • (1 : matrix l l R) + ⅟(2 : R) • 1 = 1 := by rw [← smul_add, ← (two_smul R _), smul_smul, inv_of_mul_self, one_smul], erw [matrix.from_blocks_transpose, matrix.from_blocks_smul, matrix.mul_eq_mul, matrix.from_blocks_multiply], simp [h], end lemma is_unit_PD [fintype l] [invertible (2 : R)] : is_unit (PD l R) := ⟨{ val := PD l R, inv := ⅟(2 : R) • (PD l R)ᵀ, val_inv := PD_inv l R, inv_val := by { apply matrix.nonsing_inv_left_right, exact PD_inv l R, }, }, rfl⟩ /-- An equivalence between two possible definitions of the classical Lie algebra of type D. -/ noncomputable def type_D_equiv_so' [fintype l] [invertible (2 : R)] : type_D l R ≃ₗ⁅R⁆ so' l l R := begin apply (skew_adjoint_matrices_lie_subalgebra_equiv (JD l R) (PD l R) (is_unit_PD l R)).trans, apply lie_equiv.of_eq, ext A, rw [JD_transform, ← coe_unit_of_invertible (2 : R), ←units.smul_def, lie_subalgebra.mem_coe, mem_skew_adjoint_matrices_lie_subalgebra_unit_smul], refl, end /-- A matrix defining a canonical odd-rank symmetric bilinear form. It looks like this as a `(2l+1) x (2l+1)` matrix of blocks: [ 2 0 0 ] [ 0 0 1 ] [ 0 1 0 ] where sizes of the blocks are: [`1 x 1` `1 x l` `1 x l`] [`l x 1` `l x l` `l x l`] [`l x 1` `l x l` `l x l`] -/ def JB := matrix.from_blocks ((2 : R) • 1 : matrix unit unit R) 0 0 (JD l R) /-- The classical Lie algebra of type B as a Lie subalgebra of matrices associated to the matrix `JB`. -/ def type_B [fintype l] := skew_adjoint_matrices_lie_subalgebra(JB l R) /-- A matrix transforming the bilinear form defined by the matrix `JB` into an almost-split-signature diagonal matrix. It looks like this as a `(2l+1) x (2l+1)` matrix of blocks: [ 1 0 0 ] [ 0 1 -1 ] [ 0 1 1 ] where sizes of the blocks are: [`1 x 1` `1 x l` `1 x l`] [`l x 1` `l x l` `l x l`] [`l x 1` `l x l` `l x l`] -/ def PB := matrix.from_blocks (1 : matrix unit unit R) 0 0 (PD l R) variable [fintype l] lemma PB_inv [invertible (2 : R)] : (PB l R) * (matrix.from_blocks 1 0 0 (PD l R)⁻¹) = 1 := begin simp [PB, matrix.from_blocks_multiply, (PD l R).mul_nonsing_inv, is_unit_PD, ← (PD l R).is_unit_iff_is_unit_det] end lemma is_unit_PB [invertible (2 : R)] : is_unit (PB l R) := ⟨{ val := PB l R, inv := matrix.from_blocks 1 0 0 (PD l R)⁻¹, val_inv := PB_inv l R, inv_val := by { apply matrix.nonsing_inv_left_right, exact PB_inv l R, }, }, rfl⟩ lemma JB_transform : (PB l R)ᵀ ⬝ (JB l R) ⬝ (PB l R) = (2 : R) • matrix.from_blocks 1 0 0 (S l R) := by simp [PB, JB, JD_transform, matrix.from_blocks_transpose, matrix.from_blocks_multiply, matrix.from_blocks_smul] lemma indefinite_diagonal_assoc : indefinite_diagonal (unit ⊕ l) l R = matrix.reindex_lie_equiv (equiv.sum_assoc unit l l).symm (matrix.from_blocks 1 0 0 (indefinite_diagonal l l R)) := begin ext i j, rcases i with ⟨⟨i₁ | i₂⟩ | i₃⟩; rcases j with ⟨⟨j₁ | j₂⟩ | j₃⟩; simp only [indefinite_diagonal, matrix.diagonal, equiv.sum_assoc_apply_in1, matrix.reindex_lie_equiv_apply, matrix.minor_apply, equiv.symm_symm, matrix.reindex_apply, sum.elim_inl, if_true, eq_self_iff_true, matrix.one_apply_eq, matrix.from_blocks_apply₁₁, dmatrix.zero_apply, equiv.sum_assoc_apply_in2, if_false, matrix.from_blocks_apply₁₂, matrix.from_blocks_apply₂₁, matrix.from_blocks_apply₂₂, equiv.sum_assoc_apply_in3, sum.elim_inr]; congr, end /-- An equivalence between two possible definitions of the classical Lie algebra of type B. -/ noncomputable def type_B_equiv_so' [invertible (2 : R)] : type_B l R ≃ₗ⁅R⁆ so' (unit ⊕ l) l R := begin apply (skew_adjoint_matrices_lie_subalgebra_equiv (JB l R) (PB l R) (is_unit_PB l R)).trans, symmetry, apply (skew_adjoint_matrices_lie_subalgebra_equiv_transpose (indefinite_diagonal (unit ⊕ l) l R) (matrix.reindex_alg_equiv _ (equiv.sum_assoc punit l l)) (matrix.transpose_reindex _ _)).trans, apply lie_equiv.of_eq, ext A, rw [JB_transform, ← coe_unit_of_invertible (2 : R), ←units.smul_def, lie_subalgebra.mem_coe, lie_subalgebra.mem_coe, mem_skew_adjoint_matrices_lie_subalgebra_unit_smul], simpa [indefinite_diagonal_assoc], end end orthogonal end lie_algebra
0a40e3bb5222a9f8a841cd5ad67f1dbab4a6262e
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/data/list/antidiagonal.lean
ca6dbf7312c66dd321044a0d9a64fc367b5bad4b
[ "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
1,634
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import data.list.range open list function nat namespace list namespace nat /-- The antidiagonal of a natural number `n` is the list of pairs `(i,j)` such that `i+j = n`. -/ def antidiagonal (n : ℕ) : list (ℕ × ℕ) := (range (n+1)).map (λ i, (i, n - i)) /-- A pair (i,j) is contained in the antidiagonal of `n` if and only if `i+j=n`. -/ @[simp] lemma mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} : x ∈ antidiagonal n ↔ x.1 + x.2 = n := begin rw [antidiagonal, mem_map], split, { rintros ⟨i, hi, rfl⟩, rw [mem_range, lt_succ_iff] at hi, exact add_sub_of_le hi }, { rintro rfl, refine ⟨x.fst, _, _⟩, { rw [mem_range, add_assoc, lt_add_iff_pos_right], exact zero_lt_succ _ }, { exact prod.ext rfl (nat.add_sub_cancel_left _ _) } } end /-- The length of the antidiagonal of `n` is `n+1`. -/ @[simp] lemma length_antidiagonal (n : ℕ) : (antidiagonal n).length = n+1 := by rw [antidiagonal, length_map, length_range] /-- The antidiagonal of `0` is the list `[(0,0)]` -/ @[simp] lemma antidiagonal_zero : antidiagonal 0 = [(0, 0)] := ext_le (length_antidiagonal 0) $ λ n h₁ h₂, begin rw [length_antidiagonal, lt_succ_iff, le_zero_iff] at h₁, subst n, simp [antidiagonal] end /-- The antidiagonal of `n` does not contain duplicate entries. -/ lemma nodup_antidiagonal (n : ℕ) : nodup (antidiagonal n) := nodup_map (@injective_of_left_inverse ℕ (ℕ × ℕ) prod.fst (λ i, (i, n-i)) $ λ i, rfl) (nodup_range _) end nat end list
47294b4c2b09c68a3e709472fa3bc6a1ea319577
618003631150032a5676f229d13a079ac875ff77
/src/topology/category/Top/basic.lean
9faaee47056c4b0b9c0cda597710a26a3bbeaf0a
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
1,325
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Scott Morrison, Mario Carneiro -/ import category_theory.concrete_category.unbundled_hom import topology.opens open category_theory open topological_space universe u /-- The category of topological spaces and continuous maps. -/ @[reducible] def Top : Type (u+1) := bundled topological_space namespace Top instance topological_space_unbundled (x : Top) : topological_space x := x.str instance concrete_category_continuous : unbundled_hom @continuous := ⟨@continuous_id, @continuous.comp⟩ instance hom_has_coe_to_fun (X Y : Top.{u}) : has_coe_to_fun (X ⟶ Y) := { F := _, coe := subtype.val } @[simp] lemma id_app (X : Top.{u}) (x : X) : @coe_fn (X ⟶ X) (Top.hom_has_coe_to_fun X X) (𝟙 X) x = x := rfl /-- Construct a bundled `Top` from the underlying type and the typeclass. -/ def of (X : Type u) [topological_space X] : Top := ⟨X⟩ /-- The discrete topology on any type. -/ def discrete : Type u ⥤ Top.{u} := { obj := λ X, ⟨X, ⊥⟩, map := λ X Y f, ⟨f, continuous_bot⟩ } /-- The trivial topology on any type. -/ def trivial : Type u ⥤ Top.{u} := { obj := λ X, ⟨X, ⊤⟩, map := λ X Y f, ⟨f, continuous_top⟩ } end Top
46319f05589b9aa84a15d092aa5b6dfd5b5e0b05
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/match_unit.lean
1f64d52f862bf9a30791dab07409a1fda680f982
[ "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
56
lean
theorem ex : ∀ x : Unit, x = () := by intro (); rfl
82a561a9bc5396904b3b56a2b70d8a2bafc5bb2f
ad0c7d243dc1bd563419e2767ed42fb323d7beea
/set_theory/cardinal.lean
7951e85c49584e1e58795c521b981a09718cd9ea
[ "Apache-2.0" ]
permissive
sebzim4500/mathlib
e0b5a63b1655f910dee30badf09bd7e191d3cf30
6997cafbd3a7325af5cb318561768c316ceb7757
refs/heads/master
1,585,549,958,618
1,538,221,723,000
1,538,221,723,000
150,869,076
0
0
Apache-2.0
1,538,229,323,000
1,538,229,323,000
null
UTF-8
Lean
false
false
30,585
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl, Mario Carneiro Cardinal arithmetic. Cardinals are represented as quotient over equinumerous types. -/ import data.set.finite data.quot logic.schroeder_bernstein logic.function open function lattice set local attribute [instance] classical.prop_decidable universes u v w x instance cardinal.is_equivalent : setoid (Type u) := { r := λα β, nonempty (α ≃ β), iseqv := ⟨λα, ⟨equiv.refl α⟩, λα β ⟨e⟩, ⟨e.symm⟩, λα β γ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩⟩ } /-- `cardinal.{u}` is the type of cardinal numbers in `Type u`, defined as the quotient of `Type u` by existence of an equivalence (a bijection with explicit inverse). -/ def cardinal : Type (u + 1) := quotient cardinal.is_equivalent namespace cardinal /-- The cardinal of a type -/ def mk : Type u → cardinal := quotient.mk @[simp] theorem mk_def (α : Type u) : @eq cardinal ⟦α⟧ (mk α) := rfl @[simp] theorem mk_out (c : cardinal) : mk (c.out) = c := quotient.out_eq _ instance : has_le cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, nonempty $ α ↪ β) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, propext ⟨assume ⟨e⟩, ⟨e.congr e₁ e₂⟩, assume ⟨e⟩, ⟨e.congr e₁.symm e₂.symm⟩⟩⟩ theorem le_mk_iff_exists_set {c : cardinal} {α : Type u} : c ≤ mk α ↔ ∃ p : set α, mk p = c := ⟨quotient.induction_on c $ λ β ⟨⟨f, hf⟩⟩, ⟨set.range f, eq.symm $ quot.sound ⟨equiv.set.range f hf⟩⟩, λ ⟨p, e⟩, e ▸ ⟨⟨subtype.val, λ a b, subtype.eq⟩⟩⟩ instance : linear_order cardinal.{u} := { le := (≤), le_refl := by rintros ⟨α⟩; exact ⟨embedding.refl _⟩, le_trans := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.trans e₂⟩, le_antisymm := by rintros ⟨α⟩ ⟨β⟩ ⟨e₁⟩ ⟨e₂⟩; exact quotient.sound (e₁.antisymm e₂), le_total := by rintros ⟨α⟩ ⟨β⟩; exact embedding.total } noncomputable instance : decidable_linear_order cardinal.{u} := classical.DLO _ noncomputable instance : distrib_lattice cardinal.{u} := by apply_instance instance : has_zero cardinal.{u} := ⟨⟦pempty⟧⟩ instance : inhabited cardinal.{u} := ⟨0⟩ theorem ne_zero_iff_nonempty {α : Type u} : mk α ≠ 0 ↔ nonempty α := not_iff_comm.1 ⟨λ h, quotient.sound ⟨(equiv.empty_of_not_nonempty h).trans equiv.empty_equiv_pempty⟩, λ e, let ⟨h⟩ := quotient.exact e in λ ⟨a⟩, (h a).elim⟩ instance : has_one cardinal.{u} := ⟨⟦punit⟧⟩ instance : zero_ne_one_class cardinal.{u} := { zero := 0, one := 1, zero_ne_one := ne.symm $ ne_zero_iff_nonempty.2 ⟨punit.star⟩ } theorem le_one_iff_subsingleton {α : Type u} : mk α ≤ 1 ↔ subsingleton α := ⟨λ ⟨f⟩, ⟨λ a b, f.inj (subsingleton.elim _ _)⟩, λ ⟨h⟩, ⟨⟨λ a, punit.star, λ a b _, h _ _⟩⟩⟩ instance : has_add cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α ⊕ β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.sum_congr e₁ e₂⟩⟩ @[simp] theorem add_def (α β) : mk α + mk β = mk (α ⊕ β) := rfl instance : has_mul cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α × β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.prod_congr e₁ e₂⟩⟩ @[simp] theorem mul_def (α β) : mk α * mk β = mk (α × β) := rfl private theorem add_comm (a b : cardinal.{u}) : a + b = b + a := quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.sum_comm α β⟩ private theorem mul_comm (a b : cardinal.{u}) : a * b = b * a := quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.prod_comm α β⟩ private theorem zero_add (a : cardinal.{u}) : 0 + a = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_sum α⟩ private theorem zero_mul (a : cardinal.{u}) : 0 * a = 0 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_prod α⟩ private theorem one_mul (a : cardinal.{u}) : 1 * a = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.punit_prod α⟩ private theorem left_distrib (a b c : cardinal.{u}) : a * (b + c) = a * b + a * c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_sum_distrib α β γ⟩ instance : comm_semiring cardinal.{u} := { zero := 0, one := 1, add := (+), mul := (*), zero_add := zero_add, add_zero := assume a, by rw [add_comm a 0, zero_add a], add_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.sum_assoc α β γ⟩, add_comm := add_comm, zero_mul := zero_mul, mul_zero := assume a, by rw [mul_comm a 0, zero_mul a], one_mul := one_mul, mul_one := assume a, by rw [mul_comm a 1, one_mul a], mul_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_assoc α β γ⟩, mul_comm := mul_comm, left_distrib := left_distrib, right_distrib := assume a b c, by rw [mul_comm (a + b) c, left_distrib c a b, mul_comm c a, mul_comm c b] } /-- The cardinal exponential. `mk α ^ mk β` is the cardinal of `β → α`. -/ protected def power (a b : cardinal.{u}) : cardinal.{u} := quotient.lift_on₂ a b (λα β, mk (β → α)) $ assume α₁ α₂ β₁ β₂ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.arrow_congr e₂ e₁⟩ instance : has_pow cardinal cardinal := ⟨cardinal.power⟩ local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow @[simp] theorem power_def (α β) : mk α ^ mk β = mk (β → α) := rfl @[simp] theorem power_zero {a : cardinal} : a ^ 0 = 1 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_arrow_equiv_punit α⟩ @[simp] theorem power_one {a : cardinal} : a ^ 1 = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.punit_arrow_equiv α⟩ @[simp] theorem one_power {a : cardinal} : 1 ^ a = 1 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.arrow_punit_equiv_punit α⟩ @[simp] theorem prop_eq_two : mk (ulift Prop) = 2 := quot.sound ⟨equiv.ulift.trans $ equiv.Prop_equiv_bool.trans equiv.bool_equiv_punit_sum_punit⟩ @[simp] theorem zero_power {a : cardinal} : a ≠ 0 → 0 ^ a = 0 := quotient.induction_on a $ assume α heq, nonempty.rec_on (ne_zero_iff_nonempty.1 heq) $ assume a, quotient.sound ⟨equiv.equiv_pempty $ assume f, pempty.rec (λ _, false) (f a)⟩ theorem power_ne_zero {a : cardinal} (b) : a ≠ 0 → a ^ b ≠ 0 := quotient.induction_on₂ a b $ λ α β h, let ⟨a⟩ := ne_zero_iff_nonempty.1 h in ne_zero_iff_nonempty.2 ⟨λ _, a⟩ theorem mul_power {a b c : cardinal} : (a * b) ^ c = a ^ c * b ^ c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.arrow_prod_equiv_prod_arrow α β γ⟩ theorem power_add {a b c : cardinal} : a ^ (b + c) = a ^ b * a ^ c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.sum_arrow_equiv_prod_arrow β γ α⟩ theorem power_mul {a b c : cardinal} : (a ^ b) ^ c = a ^ (b * c) := by rw [_root_.mul_comm b c]; from (quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.arrow_arrow_equiv_prod_arrow γ β α⟩) section order_properties open sum theorem zero_le : ∀(a : cardinal), 0 ≤ a := by rintro ⟨α⟩; exact ⟨embedding.of_not_nonempty $ λ ⟨a⟩, a.elim⟩ theorem le_zero (a : cardinal) : a ≤ 0 ↔ a = 0 := by simp [le_antisymm_iff, zero_le] theorem pos_iff_ne_zero {o : cardinal} : 0 < o ↔ o ≠ 0 := by simp [lt_iff_le_and_ne, eq_comm, zero_le] theorem zero_lt_one : (0 : cardinal) < 1 := lt_of_le_of_ne (zero_le _) zero_ne_one theorem add_le_add : ∀{a b c d : cardinal}, a ≤ b → c ≤ d → a + c ≤ b + d := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨embedding.sum_congr e₁ e₂⟩ theorem add_le_add_left (a) {b c : cardinal} : b ≤ c → a + b ≤ a + c := add_le_add (le_refl _) theorem add_le_add_right {a b : cardinal} (c) (h : a ≤ b) : a + c ≤ b + c := add_le_add h (le_refl _) theorem le_add_right (a b : cardinal) : a ≤ a + b := by simpa using add_le_add_left a (zero_le b) theorem le_add_left (a b : cardinal) : a ≤ b + a := by simpa using add_le_add_right a (zero_le b) theorem mul_le_mul : ∀{a b c d : cardinal}, a ≤ b → c ≤ d → a * c ≤ b * d := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨embedding.prod_congr e₁ e₂⟩ theorem mul_le_mul_left (a) {b c : cardinal} : b ≤ c → a * b ≤ a * c := mul_le_mul (le_refl _) theorem mul_le_mul_right {a b : cardinal} (c) (h : a ≤ b) : a * c ≤ b * c := mul_le_mul h (le_refl _) theorem power_le_power_left : ∀{a b c : cardinal}, a ≠ 0 → b ≤ c → a ^ b ≤ a ^ c := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ hα ⟨e⟩; exact let ⟨a⟩ := ne_zero_iff_nonempty.1 hα in ⟨@embedding.arrow_congr_right _ _ _ ⟨a⟩ e⟩ theorem power_le_power_right {a b c : cardinal} : a ≤ b → a ^ c ≤ b ^ c := quotient.induction_on₃ a b c $ assume α β γ ⟨e⟩, ⟨embedding.arrow_congr_left e⟩ theorem le_iff_exists_add {a b : cardinal} : a ≤ b ↔ ∃ c, b = a + c := ⟨quotient.induction_on₂ a b $ λ α β ⟨⟨f, hf⟩⟩, have (α ⊕ ↥-range f) ≃ β, from (equiv.sum_congr (equiv.set.range f hf) (equiv.refl _)).trans $ (equiv.set.sum_compl (range f)), ⟨⟦(-range f : set β)⟧, quotient.sound ⟨this.symm⟩⟩, λ ⟨c, e⟩, add_zero a ▸ e.symm ▸ add_le_add_left _ (zero_le _)⟩ end order_properties instance : canonically_ordered_monoid cardinal.{u} := { add_le_add_left := λ a b h c, add_le_add_left _ h, lt_of_add_lt_add_left := λ a b c, le_imp_le_iff_lt_imp_lt.1 (add_le_add_left _), le_iff_exists_add := @le_iff_exists_add, ..cardinal.comm_semiring, ..cardinal.linear_order } instance : order_bot cardinal.{u} := { bot := 0, bot_le := zero_le, ..cardinal.linear_order } theorem cantor : ∀(a : cardinal.{u}), a < 2 ^ a := by rw ← prop_eq_two; rintros ⟨a⟩; exact ⟨ ⟨⟨λ a b, ⟨a = b⟩, λ a b h, cast (ulift.up.inj (@congr_fun _ _ _ _ h b)).symm rfl⟩⟩, λ ⟨⟨f, hf⟩⟩, cantor_injective (λ s, f (λ a, ⟨s a⟩)) $ λ s t h, by funext a; injection congr_fun (hf h) a⟩ instance : no_top_order cardinal.{u} := { no_top := λ a, ⟨_, cantor a⟩, ..cardinal.linear_order } /-- The minimum cardinal in a family of cardinals (the existence of which is provided by `injective_min`). -/ noncomputable def min {ι} (I : nonempty ι) (f : ι → cardinal) : cardinal := f $ classical.some $ @embedding.injective_min _ (λ i, (f i).out) I theorem min_eq {ι} (I) (f : ι → cardinal) : ∃ i, min I f = f i := ⟨_, rfl⟩ theorem min_le {ι I} (f : ι → cardinal) (i) : min I f ≤ f i := by rw [← mk_out (min I f), ← mk_out (f i)]; exact let ⟨g⟩ := classical.some_spec (@embedding.injective_min _ (λ i, (f i).out) I) in ⟨g i⟩ theorem le_min {ι I} {f : ι → cardinal} {a} : a ≤ min I f ↔ ∀ i, a ≤ f i := ⟨λ h i, le_trans h (min_le _ _), λ h, let ⟨i, e⟩ := min_eq I f in e.symm ▸ h i⟩ protected theorem wf : @well_founded cardinal.{u} (<) := ⟨λ a, classical.by_contradiction $ λ h, let ι := {c :cardinal // ¬ acc (<) c}, f : ι → cardinal := subtype.val, ⟨⟨c, hc⟩, hi⟩ := @min_eq ι ⟨⟨_, h⟩⟩ f in hc (acc.intro _ (λ j ⟨_, h'⟩, classical.by_contradiction $ λ hj, h' $ by have := min_le f ⟨j, hj⟩; rwa hi at this))⟩ instance has_wf : @has_well_founded cardinal.{u} := ⟨(<), cardinal.wf⟩ instance wo : @is_well_order cardinal.{u} (<) := ⟨cardinal.wf⟩ /-- The successor cardinal - the smallest cardinal greater than `c`. This is not the same as `c + 1` except in the case of finite `c`. -/ noncomputable def succ (c : cardinal) : cardinal := @min {c' // c < c'} ⟨⟨_, cantor _⟩⟩ subtype.val theorem lt_succ_self (c : cardinal) : c < succ c := by cases min_eq _ _ with s e; rw [succ, e]; exact s.2 theorem succ_le {a b : cardinal} : succ a ≤ b ↔ a < b := ⟨lt_of_lt_of_le (lt_succ_self _), λ h, by exact min_le _ (subtype.mk b h)⟩ theorem lt_succ {a b : cardinal} : a < succ b ↔ a ≤ b := by rw [← not_le, succ_le, not_lt] theorem add_one_le_succ (c : cardinal) : c + 1 ≤ succ c := begin refine quot.induction_on c (λ α, _) (lt_succ_self c), refine quot.induction_on (succ (quot.mk setoid.r α)) (λ β h, _), cases h.left with f, have : ¬ surjective f := λ hn, ne_of_lt h (quotient.sound ⟨equiv.of_bijective ⟨f.inj, hn⟩⟩), cases classical.not_forall.1 this with b nex, refine ⟨⟨sum.rec (by exact f) _, _⟩⟩, { exact λ _, b }, { intros a b h, rcases a with a|⟨⟨⟨⟩⟩⟩; rcases b with b|⟨⟨⟨⟩⟩⟩, { rw f.inj h }, { exact nex.elim ⟨_, h⟩ }, { exact nex.elim ⟨_, h.symm⟩ }, { refl } } end /-- The indexed sum of cardinals is the cardinality of the indexed disjoint union, i.e. sigma type. -/ def sum {ι} (f : ι → cardinal) : cardinal := mk Σ i, (f i).out theorem le_sum {ι} (f : ι → cardinal) (i) : f i ≤ sum f := by rw ← quotient.out_eq (f i); exact ⟨⟨λ a, ⟨i, a⟩, λ a b h, eq_of_heq $ by injection h⟩⟩ @[simp] theorem sum_mk {ι} (f : ι → Type*) : sum (λ i, mk (f i)) = mk (Σ i, f i) := quot.sound ⟨equiv.sigma_congr_right $ λ i, classical.choice $ quotient.exact $ quot.out_eq $ mk (f i)⟩ theorem sum_const (ι : Type u) (a : cardinal.{u}) : sum (λ _:ι, a) = mk ι * a := quotient.induction_on a $ λ α, by simp; exact quotient.sound ⟨equiv.sigma_equiv_prod _ _⟩ theorem sum_le_sum {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sum f ≤ sum g := ⟨embedding.sigma_congr_right $ λ i, classical.choice $ by have := H i; rwa [← quot.out_eq (f i), ← quot.out_eq (g i)] at this⟩ /-- The indexed supremum of cardinals is the smallest cardinal above everything in the family. -/ noncomputable def sup {ι} (f : ι → cardinal) : cardinal := @min {c // ∀ i, f i ≤ c} ⟨⟨sum f, le_sum f⟩⟩ (λ a, a.1) theorem le_sup {ι} (f : ι → cardinal) (i) : f i ≤ sup f := by dsimp [sup]; cases min_eq _ _ with c hc; rw hc; exact c.2 i theorem sup_le {ι} {f : ι → cardinal} {a} : sup f ≤ a ↔ ∀ i, f i ≤ a := ⟨λ h i, le_trans (le_sup _ _) h, λ h, by dsimp [sup]; change a with (⟨a, h⟩:subtype _).1; apply min_le⟩ theorem sup_le_sup {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sup f ≤ sup g := sup_le.2 $ λ i, le_trans (H i) (le_sup _ _) theorem sup_le_sum {ι} (f : ι → cardinal) : sup f ≤ sum f := sup_le.2 $ le_sum _ theorem sum_le_sup {ι : Type u} (f : ι → cardinal.{u}) : sum f ≤ mk ι * sup.{u u} f := by rw ← sum_const; exact sum_le_sum _ _ (le_sup _) /-- The indexed product of cardinals is the cardinality of the Pi type (dependent product). -/ def prod {ι : Type u} (f : ι → cardinal) : cardinal := mk (Π i, (f i).out) @[simp] theorem prod_mk {ι} (f : ι → Type*) : prod (λ i, mk (f i)) = mk (Π i, f i) := quot.sound ⟨equiv.Pi_congr_right $ λ i, classical.choice $ quotient.exact $ mk_out $ mk (f i)⟩ theorem prod_const (ι : Type u) (a : cardinal.{u}) : prod (λ _:ι, a) = a ^ mk ι := quotient.induction_on a $ by simp theorem prod_le_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : prod f ≤ prod g := ⟨embedding.Pi_congr_right $ λ i, classical.choice $ by have := H i; rwa [← mk_out (f i), ← mk_out (g i)] at this⟩ theorem prod_ne_zero {ι} (f : ι → cardinal) : prod f ≠ 0 ↔ ∀ i, f i ≠ 0 := begin conv in (f _) {rw ← mk_out (f i)}, simp [prod, ne_zero_iff_nonempty, -mk_out, -ne.def], exact ⟨λ ⟨F⟩ i, ⟨F i⟩, λ h, ⟨λ i, classical.choice (h i)⟩⟩, end theorem prod_eq_zero {ι} (f : ι → cardinal) : prod f = 0 ↔ ∃ i, f i = 0 := not_iff_not.1 $ by simpa using prod_ne_zero f /-- The universe lift operation on cardinals -/ def lift (c : cardinal.{u}) : cardinal.{max u v} := quotient.lift_on c (λ α, ⟦ulift α⟧) $ λ α β ⟨e⟩, quotient.sound ⟨equiv.ulift.trans $ e.trans equiv.ulift.symm⟩ theorem lift_mk (α) : lift.{u v} (mk α) = mk (ulift.{v u} α) := rfl theorem lift_umax : lift.{u (max u v)} = lift.{u v} := funext $ λ a, quot.induction_on a $ λ α, quotient.sound ⟨equiv.ulift.trans equiv.ulift.symm⟩ theorem lift_id' (a : cardinal) : lift a = a := quot.induction_on a $ λ α, quot.sound ⟨equiv.ulift⟩ @[simp] theorem lift_id : ∀ a, lift.{u u} a = a := lift_id'.{u u} @[simp] theorem lift_lift (a : cardinal) : lift.{(max u v) w} (lift.{u v} a) = lift.{u (max v w)} a := quot.induction_on a $ λ α, quotient.sound ⟨equiv.ulift.trans $ equiv.ulift.trans equiv.ulift.symm⟩ theorem lift_mk_le {α : Type u} {β : Type v} : lift.{u (max v w)} (mk α) ≤ lift.{v (max u w)} (mk β) ↔ nonempty (α ↪ β) := ⟨λ ⟨f⟩, ⟨embedding.congr equiv.ulift equiv.ulift f⟩, λ ⟨f⟩, ⟨embedding.congr equiv.ulift.symm equiv.ulift.symm f⟩⟩ theorem lift_mk_eq {α : Type u} {β : Type v} : lift.{u (max v w)} (mk α) = lift.{v (max u w)} (mk β) ↔ nonempty (α ≃ β) := quotient.eq.trans ⟨λ ⟨f⟩, ⟨equiv.ulift.symm.trans $ f.trans equiv.ulift⟩, λ ⟨f⟩, ⟨equiv.ulift.trans $ f.trans equiv.ulift.symm⟩⟩ @[simp] theorem lift_le {a b : cardinal} : lift a ≤ lift b ↔ a ≤ b := quotient.induction_on₂ a b $ λ α β, by rw ← lift_umax; exact lift_mk_le @[simp] theorem lift_inj {a b : cardinal} : lift a = lift b ↔ a = b := by simp [le_antisymm_iff] @[simp] theorem lift_lt {a b : cardinal} : lift a < lift b ↔ a < b := by simp [lt_iff_le_not_le, -not_le] @[simp] theorem lift_zero : lift 0 = 0 := quotient.sound ⟨equiv.ulift.trans equiv.pempty_equiv_pempty⟩ @[simp] theorem lift_one : lift 1 = 1 := quotient.sound ⟨equiv.ulift.trans equiv.punit_equiv_punit⟩ @[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.prod_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_power (a b) : lift (a ^ b) = lift a ^ lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.arrow_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_two_power (a) : lift (2 ^ a) = 2 ^ lift a := by simp [bit0] @[simp] theorem lift_min {ι I} (f : ι → cardinal) : lift (min I f) = min I (lift ∘ f) := le_antisymm (le_min.2 $ λ a, lift_le.2 $ min_le _ a) $ let ⟨i, e⟩ := min_eq I (lift ∘ f) in by rw e; exact lift_le.2 (le_min.2 $ λ j, lift_le.1 $ by have := min_le (lift ∘ f) j; rwa e at this) theorem lift_down {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a → ∃ a', lift a' = b := quotient.induction_on₂ a b $ λ α β, by dsimp; rw [← lift_id (mk β), ← lift_umax, ← lift_umax.{u v}, lift_mk_le]; exact λ ⟨f⟩, ⟨mk (set.range f), eq.symm $ lift_mk_eq.2 ⟨embedding.equiv_of_surjective (embedding.cod_restrict _ f set.mem_range_self) $ λ ⟨a, ⟨b, e⟩⟩, ⟨b, subtype.eq e⟩⟩⟩ theorem le_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a ↔ ∃ a', lift a' = b ∧ a' ≤ a := ⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_le.2 h⟩ theorem lt_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b < lift a ↔ ∃ a', lift a' = b ∧ a' < a := ⟨λ h, let ⟨a', e⟩ := lift_down (le_of_lt h) in ⟨a', e, lift_lt.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_lt.2 h⟩ @[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) := le_antisymm (le_of_not_gt $ λ h, begin rcases lt_lift_iff.1 h with ⟨b, e, h⟩, rw [lt_succ, ← lift_le, e] at h, exact not_lt_of_le h (lt_succ_self _) end) (succ_le.2 $ lift_lt.2 $ lt_succ_self _) /-- `ω` is the smallest infinite cardinal, also known as ℵ₀. -/ def omega : cardinal.{u} := lift (mk ℕ) theorem omega_ne_zero : omega ≠ 0 := ne_zero_iff_nonempty.2 ⟨⟨0⟩⟩ theorem omega_pos : 0 < omega := pos_iff_ne_zero.2 omega_ne_zero @[simp] theorem lift_omega : lift omega = omega := lift_lift _ @[simp] theorem mk_fin : ∀ (n : ℕ), mk (fin n) = n | 0 := quotient.sound ⟨(equiv.pempty_of_not_nonempty $ λ ⟨h⟩, h.elim0)⟩ | (n+1) := by rw [nat.cast_succ, ← mk_fin]; exact quotient.sound (fintype.card_eq.1 $ by simp) @[simp] theorem lift_nat_cast (n : ℕ) : lift n = n := by induction n; simp * theorem lift_mk_fin (n : ℕ) : lift (mk (fin n)) = n := by simp theorem fintype_card (α : Type u) [fintype α] : mk α = fintype.card α := by rw [← lift_mk_fin.{u}, ← lift_id (mk α), lift_mk_eq.{u 0 u}]; exact fintype.card_eq.1 (by simp) theorem card_le_of_finset {α} (s : finset α) : (s.card : cardinal) ≤ cardinal.mk α := begin rw (_ : (s.card : cardinal) = cardinal.mk (↑s : set α)), { exact ⟨function.embedding.subtype _⟩ }, rw [cardinal.fintype_card, fintype.card_coe] end @[simp] theorem nat_cast_pow {m n : ℕ} : (↑(pow m n) : cardinal) = m ^ n := by induction n; simp [nat.pow_succ, -_root_.add_comm, power_add, *] @[simp] theorem nat_cast_le {m n : ℕ} : (m : cardinal) ≤ n ↔ m ≤ n := by rw [← lift_mk_fin, ← lift_mk_fin, lift_le]; exact ⟨λ ⟨⟨f, hf⟩⟩, begin have : _ = fintype.card _ := finset.card_image_of_injective finset.univ hf, simp at this, rw [← fintype.card_fin n, ← this], exact finset.card_le_of_subset (finset.subset_univ _) end, λ h, ⟨⟨λ i, ⟨i.1, lt_of_lt_of_le i.2 h⟩, λ a b h, have _, from fin.veq_of_eq h, fin.eq_of_veq this⟩⟩⟩ @[simp] theorem nat_cast_lt {m n : ℕ} : (m : cardinal) < n ↔ m < n := by simp [lt_iff_le_not_le, -not_le] @[simp] theorem nat_cast_inj {m n : ℕ} : (m : cardinal) = n ↔ m = n := by simp [le_antisymm_iff] @[simp] theorem nat_succ (n : ℕ) : succ n = n.succ := le_antisymm (succ_le.2 $ nat_cast_lt.2 $ nat.lt_succ_self _) (add_one_le_succ _) @[simp] theorem succ_zero : succ 0 = 1 := by simpa using nat_succ 0 theorem cantor' (a) {b : cardinal} (hb : 1 < b) : a < b ^ a := by rw [← succ_le, (by simpa using nat_succ 1 : succ 1 = 2)] at hb; exact lt_of_lt_of_le (cantor _) (power_le_power_right hb) theorem one_le_iff_pos {c : cardinal} : 1 ≤ c ↔ 0 < c := by rw [← succ_zero, succ_le] theorem one_le_iff_ne_zero {c : cardinal} : 1 ≤ c ↔ c ≠ 0 := by rw [one_le_iff_pos, pos_iff_ne_zero] theorem nat_lt_omega (n : ℕ) : (n : cardinal.{u}) < omega := succ_le.1 $ by rw [nat_succ, ← lift_mk_fin, omega, lift_mk_le.{0 0 u}]; exact ⟨⟨fin.val, λ a b, fin.eq_of_veq⟩⟩ theorem one_lt_omega : 1 < omega := by simpa using nat_lt_omega 1 theorem lt_omega {c : cardinal.{u}} : c < omega ↔ ∃ n : ℕ, c = n := ⟨λ h, begin rcases lt_lift_iff.1 h with ⟨c, rfl, h'⟩, rcases le_mk_iff_exists_set.1 h'.1 with ⟨S, rfl⟩, suffices : finite S, { cases this, resetI, existsi fintype.card S, rw [← lift_nat_cast.{0 u}, lift_inj, fintype_card S] }, by_contra nf, have P : ∀ (n : ℕ) (IH : ∀ i<n, S), ∃ a : S, ¬ ∃ y h, IH y h = a := λ n IH, let g : {i | i < n} → S := λ ⟨i, h⟩, IH i h in classical.not_forall.1 (λ h, nf ⟨fintype.of_surjective g (λ a, subtype.exists.2 (h a))⟩), let F : ℕ → S := nat.lt_wf.fix (λ n IH, classical.some (P n IH)), refine not_le_of_lt h' ⟨⟨F, _⟩⟩, suffices : ∀ (n : ℕ) (m < n), F m ≠ F n, { refine λ m n, not_imp_not.1 (λ ne, _), rcases lt_trichotomy m n with h|h|h, { exact this n m h }, { contradiction }, { exact (this m n h).symm } }, intros n m h, have := classical.some_spec (P n (λ y _, F y)), rw [← show F n = classical.some (P n (λ y _, F y)), from nat.lt_wf.fix_eq (λ n IH, classical.some (P n IH)) n] at this, exact λ e, this ⟨m, h, e⟩, end, λ ⟨n, e⟩, e.symm ▸ nat_lt_omega _⟩ theorem omega_le {c : cardinal.{u}} : omega ≤ c ↔ ∀ n : ℕ, (n:cardinal) ≤ c := ⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h, λ h, le_of_not_lt $ λ hn, begin rcases lt_omega.1 hn with ⟨n, rfl⟩, exact not_le_of_lt (nat.lt_succ_self _) (nat_cast_le.1 (h (n+1))) end⟩ theorem lt_omega_iff_fintype {α : Type u} : mk α < omega ↔ nonempty (fintype α) := lt_omega.trans ⟨λ ⟨n, e⟩, begin rw [← lift_mk_fin n] at e, cases quotient.exact e with f, exact ⟨fintype.of_equiv _ f.symm⟩ end, λ ⟨_⟩, by exactI ⟨_, fintype_card _⟩⟩ theorem lt_omega_iff_finite {α} {S : set α} : mk S < omega ↔ finite S := lt_omega_iff_fintype theorem add_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a + b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_omega end theorem mul_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a * b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_mul]; apply nat_lt_omega end theorem power_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a ^ b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_pow]; apply nat_lt_omega end /-- König's theorem -/ theorem sum_lt_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i < g i) : sum f < prod g := lt_of_not_ge $ λ ⟨F⟩, begin have : inhabited (Π (i : ι), (g i).out), { refine ⟨λ i, classical.choice $ ne_zero_iff_nonempty.1 _⟩, rw mk_out, exact ne_of_gt (lt_of_le_of_lt (zero_le _) (H i)) }, resetI, let G := inv_fun F, have sG : surjective G := inv_fun_surjective F.2, have : ∀ i, ¬ ∀ b, ∃ a, G ⟨i, a⟩ i = b, { refine λ i h, not_le_of_lt (H i) _, rw [← mk_out (f i), ← mk_out (g i)], exact ⟨embedding.of_surjective h⟩ }, simp [classical.not_forall] at this, exact let ⟨C, hc⟩ := classical.axiom_of_choice this, ⟨⟨i, a⟩, h⟩ := sG C in hc i a (congr_fun h _), end @[simp] theorem mk_empty : mk empty = 0 := fintype_card empty @[simp] theorem mk_pempty : mk pempty = 0 := fintype_card pempty @[simp] theorem mk_empty' (α : Type u) : mk (∅ : set α) = 0 := quotient.sound ⟨equiv.set.pempty α⟩ @[simp] theorem mk_plift_false : mk (plift false) = 0 := quotient.sound ⟨equiv.plift.trans $ equiv.false_equiv_pempty⟩ @[simp] theorem mk_unit : mk unit = 1 := (fintype_card unit).trans nat.cast_one @[simp] theorem mk_punit : mk punit = 1 := (fintype_card punit).trans nat.cast_one @[simp] theorem mk_singleton {α : Type u} (x : α) : mk ({x} : set α) = 1 := quotient.sound ⟨equiv.set.singleton x⟩ @[simp] theorem mk_plift_true : mk (plift true) = 1 := quotient.sound ⟨equiv.plift.trans equiv.true_equiv_punit⟩ @[simp] theorem mk_bool : mk bool = 2 := quotient.sound ⟨equiv.bool_equiv_punit_sum_punit⟩ @[simp] theorem mk_Prop : mk Prop = 2 := (quotient.sound ⟨equiv.Prop_equiv_bool⟩ : mk Prop = mk bool).trans mk_bool @[simp] theorem mk_option {α : Type u} : mk (option α) = mk α + 1 := quotient.sound ⟨equiv.option_equiv_sum_punit α⟩ theorem mk_eq_of_injective {α β : Type u} {f : α → β} {s : set α} (hf : injective f) : mk (f '' s) = mk s := quotient.sound ⟨(equiv.set.image f s hf).symm⟩ theorem mk_list_eq_sum_pow (α : Type u) : mk (list α) = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) := calc mk (list α) = mk (Σ n, vector α n) : quotient.sound ⟨equiv.equiv_sigma_subtype list.length⟩ ... = mk (Σ n, fin n → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n, ⟨vector.nth, vector.of_fn, vector.of_fn_nth, λ f, funext $ vector.nth_of_fn f⟩⟩ ... = mk (Σ n : ℕ, ulift.{u} (fin n) → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n, equiv.arrow_congr equiv.ulift.symm (equiv.refl α)⟩ ... = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) : by simp only [(lift_mk_fin _).symm, lift_mk, power_def, sum_mk] theorem mk_Union_le_sum_mk {α ι : Type u} {f : ι → set α} : mk (⋃ i, f i) ≤ sum (λ i, mk (f i)) := calc mk (⋃ i, f i) ≤ mk (Σ i, f i) : show nonempty ((⋃ i, f i) ↪ (Σ i, f i)), from ⟨⟨λ x, ⟨classical.some (mem_Union.1 x.2), x.1, classical.some_spec (mem_Union.1 x.2)⟩, λ x y H, subtype.eq $ begin cases sigma.mk.inj H with H1 H2, clear H, generalize_hyp : classical.some_spec _ = H4 at H1 H2, generalize_hyp : classical.some _ = i₀ at H1 H2 H4, subst H1, exact subtype.mk.inj (eq_of_heq H2) end⟩⟩ ... = sum (λ i, mk (f i)) : (sum_mk _).symm @[simp] lemma finset_card {α : Type u} {s : finset α} : ↑(finset.card s) = mk (↑s : set α) := by rw [fintype_card, nat_cast_inj, fintype.card_coe] theorem mk_union_add_mk_inter {α : Type u} {S T : set α} : mk (S ∪ T : set α) + mk (S ∩ T : set α) = mk S + mk T := quotient.sound $ nonempty.intro $ { to_fun := λ x, sum.rec_on x (λ x, if h : x.1 ∈ S then sum.inl ⟨x.1, h⟩ else sum.inr ⟨x.1, x.2.resolve_left h⟩) (λ x, sum.inr ⟨x.1, x.2.2⟩), inv_fun := λ x, sum.rec_on x (λ x, sum.inl ⟨x.1, or.inl x.2⟩) (λ x, if h : x.1 ∈ S then sum.inr ⟨x.1, h, x.2⟩ else sum.inl ⟨x.1, or.inr x.2⟩), left_inv := λ x, sum.rec_on x (λ ⟨x, hx⟩, if h : x ∈ S then by dsimp only; rw [dif_pos h]; refl else by dsimp only; rw [dif_neg h]; dsimp only; rw [dif_neg h]; refl) (λ ⟨x, hx1, hx2⟩, by dsimp only; rw [dif_pos hx1]), right_inv := λ x, sum.rec_on x (λ ⟨x, hx⟩, by dsimp only; rw [dif_pos hx]) (λ ⟨x, hx⟩, if h : x ∈ S then by dsimp only; rw [dif_pos h] else by dsimp only; rw [dif_neg h]; dsimp only; rw [dif_neg h]) } theorem mk_union_of_disjiont {α : Type u} {S T : set α} (H : disjoint S T) : mk (S ∪ T : set α) = mk S + mk T := eq.trans (by simp only [(eq_empty_of_subset_empty H : S ∩ T = ∅), mk_empty', add_zero]) mk_union_add_mk_inter end cardinal
7aea08a9edb3330d45fb5cbf770c0f208ba7c517
c777c32c8e484e195053731103c5e52af26a25d1
/src/order/category/FinPartOrd.lean
ffa0dab0797f1f30300997653885102e7d5c0f56
[ "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
2,731
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import category_theory.Fintype import order.category.PartOrd /-! # The category of finite partial orders This defines `FinPartOrd`, the category of finite partial orders. Note: `FinPartOrd` is *not* a subcategory of `BddOrd` because finite orders are not necessarily bounded. ## TODO `FinPartOrd` is equivalent to a small category. -/ universes u v open category_theory /-- The category of finite partial orders with monotone functions. -/ structure FinPartOrd := (to_PartOrd : PartOrd) [is_fintype : fintype to_PartOrd] namespace FinPartOrd instance : has_coe_to_sort FinPartOrd Type* := ⟨λ X, X.to_PartOrd⟩ instance (X : FinPartOrd) : partial_order X := X.to_PartOrd.str attribute [instance] FinPartOrd.is_fintype @[simp] lemma coe_to_PartOrd (X : FinPartOrd) : ↥X.to_PartOrd = ↥X := rfl /-- Construct a bundled `FinPartOrd` from `fintype` + `partial_order`. -/ def of (α : Type*) [partial_order α] [fintype α] : FinPartOrd := ⟨⟨α⟩⟩ @[simp] lemma coe_of (α : Type*) [partial_order α] [fintype α] : ↥(of α) = α := rfl instance : inhabited FinPartOrd := ⟨of punit⟩ instance large_category : large_category FinPartOrd := induced_category.category FinPartOrd.to_PartOrd instance concrete_category : concrete_category FinPartOrd := induced_category.concrete_category FinPartOrd.to_PartOrd instance has_forget_to_PartOrd : has_forget₂ FinPartOrd PartOrd := induced_category.has_forget₂ FinPartOrd.to_PartOrd instance has_forget_to_Fintype : has_forget₂ FinPartOrd Fintype := { forget₂ := { obj := λ X, ⟨X⟩, map := λ X Y, coe_fn } } /-- Constructs an isomorphism of finite partial orders from an order isomorphism between them. -/ @[simps] def iso.mk {α β : FinPartOrd.{u}} (e : α ≃o β) : α ≅ β := { hom := e, inv := e.symm, hom_inv_id' := by { ext, exact e.symm_apply_apply _ }, inv_hom_id' := by { ext, exact e.apply_symm_apply _ } } /-- `order_dual` as a functor. -/ @[simps] def dual : FinPartOrd ⥤ FinPartOrd := { obj := λ X, of Xᵒᵈ, map := λ X Y, order_hom.dual } /-- The equivalence between `FinPartOrd` and itself induced by `order_dual` both ways. -/ @[simps functor inverse] def dual_equiv : FinPartOrd ≌ FinPartOrd := equivalence.mk dual dual (nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl) (nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl) end FinPartOrd lemma FinPartOrd_dual_comp_forget_to_PartOrd : FinPartOrd.dual ⋙ forget₂ FinPartOrd PartOrd = forget₂ FinPartOrd PartOrd ⋙ PartOrd.dual := rfl
ee6b2dcf3519273598a2ef16aeae3b3bddb58090
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/library/data/sigma/thms.lean
720b700bc02bc35d2fc7486b65d46370f215ab7b
[ "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
3,424
lean
-- Copyright (c) 2014 Microsoft Corporation. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Leonardo de Moura, Jeremy Avigad, Floris van Doorn import data.sigma.decl open inhabited eq.ops sigma.ops namespace sigma universe variables u v variables {A A' : Type.{u}} {B : A → Type.{v}} {B' : A' → Type.{v}} definition unpack {C : (Σa, B a) → Type} {u : Σa, B a} (H : C ⟨u.1 , u.2⟩) : C u := destruct u (λx y H, H) H theorem dpair_eq {a₁ a₂ : A} {b₁ : B a₁} {b₂ : B a₂} (H₁ : a₁ = a₂) (H₂ : eq.rec_on H₁ b₁ = b₂) : dpair a₁ b₁ = dpair a₂ b₂ := dcongr_arg2 dpair H₁ H₂ theorem dpair_heq {a : A} {a' : A'} {b : B a} {b' : B' a'} (HB : B == B') (Ha : a == a') (Hb : b == b') : dpair a b == dpair a' b' := hcongr_arg4 @dpair (heq.type_eq Ha) HB Ha Hb protected theorem equal {p₁ p₂ : Σa : A, B a} : ∀(H₁ : dpr1 p₁ = dpr1 p₂) (H₂ : eq.rec_on H₁ (dpr2 p₁) = dpr2 p₂), p₁ = p₂ := destruct p₁ (take a₁ b₁, destruct p₂ (take a₂ b₂ H₁ H₂, dpair_eq H₁ H₂)) protected theorem hequal {p : Σa : A, B a} {p' : Σa' : A', B' a'} (HB : B == B') : ∀(H₁ : dpr1 p == dpr1 p') (H₂ : dpr2 p == dpr2 p'), p == p' := destruct p (take a₁ b₁, destruct p' (take a₂ b₂ H₁ H₂, dpair_heq HB H₁ H₂)) protected definition is_inhabited [instance] (H₁ : inhabited A) (H₂ : inhabited (B (default A))) : inhabited (sigma B) := inhabited.destruct H₁ (λa, inhabited.destruct H₂ (λb, inhabited.mk (dpair (default A) b))) theorem eq_rec_dpair_commute {C : Πa, B a → Type} {a a' : A} (H : a = a') (b : B a) (c : C a b) : eq.rec_on H (dpair b c) = dpair (eq.rec_on H b) (eq.rec_on (dcongr_arg2 C H rfl) c) := eq.drec_on H (dpair_eq rfl (!eq.rec_on_id⁻¹)) variables {C : Πa, B a → Type} {D : Πa b, C a b → Type} definition dtrip (a : A) (b : B a) (c : C a b) := ⟨a, b, c⟩ definition dquad (a : A) (b : B a) (c : C a b) (d : D a b c) := ⟨a, b, c, d⟩ definition dpr1' (x : Σ a, B a) := x.1 definition dpr2' (x : Σ a b, C a b) := x.2.1 definition dpr3 (x : Σ a b, C a b) := x.2.2 definition dpr3' (x : Σ a b c, D a b c) := x.2.2.1 definition dpr4 (x : Σ a b c, D a b c) := x.2.2.2 theorem dtrip_eq {a₁ a₂ : A} {b₁ : B a₁} {b₂ : B a₂} {c₁ : C a₁ b₁} {c₂ : C a₂ b₂} (H₁ : a₁ = a₂) (H₂ : eq.rec_on H₁ b₁ = b₂) (H₃ : cast (dcongr_arg2 C H₁ H₂) c₁ = c₂) : ⟨a₁, b₁, c₁⟩ = ⟨a₂, b₂, c₂⟩ := dcongr_arg3 dtrip H₁ H₂ H₃ theorem ndtrip_eq {A B : Type} {C : A → B → Type} {a₁ a₂ : A} {b₁ b₂ : B} {c₁ : C a₁ b₁} {c₂ : C a₂ b₂} (H₁ : a₁ = a₂) (H₂ : b₁ = b₂) (H₃ : cast (congr_arg2 C H₁ H₂) c₁ = c₂) : ⟨a₁, b₁, c₁⟩ = ⟨a₂, b₂, c₂⟩ := hdcongr_arg3 dtrip H₁ (heq.from_eq H₂) H₃ theorem ndtrip_equal {A B : Type} {C : A → B → Type} {p₁ p₂ : Σa b, C a b} : ∀(H₁ : dpr1 p₁ = dpr1 p₂) (H₂ : dpr2' p₁ = dpr2' p₂) (H₃ : eq.rec_on (congr_arg2 C H₁ H₂) (dpr3 p₁) = dpr3 p₂), p₁ = p₂ := destruct p₁ (take a₁ q₁, destruct q₁ (take b₁ c₁, destruct p₂ (take a₂ q₂, destruct q₂ (take b₂ c₂ H₁ H₂ H₃, ndtrip_eq H₁ H₂ H₃)))) end sigma
092c310325e65be948d7d6849c40a779d176f30e
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/category_theory/adjunction/limits.lean
13e8a14371883cd77a310fb3dc16d873c20601d1
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
7,619
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Johan Commelin -/ import category_theory.adjunction.basic import category_theory.limits.preserves open opposite namespace category_theory.adjunction open category_theory open category_theory.functor open category_theory.limits universes u₁ u₂ v variables {C : Type u₁} [𝒞 : category.{v} C] {D : Type u₂} [𝒟 : category.{v} D] include 𝒞 𝒟 variables {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) include adj section preservation_colimits variables {J : Type v} [small_category J] (K : J ⥤ C) def functoriality_right_adjoint : cocone (K ⋙ F) ⥤ cocone K := (cocones.functoriality G) ⋙ (cocones.precompose (K.right_unitor.inv ≫ (whisker_left K adj.unit) ≫ (associator _ _ _).inv)) local attribute [reducible] functoriality_right_adjoint @[simps] def functoriality_unit : 𝟭 (cocone K) ⟶ cocones.functoriality F ⋙ functoriality_right_adjoint adj K := { app := λ c, { hom := adj.unit.app c.X } } @[simps] def functoriality_counit : functoriality_right_adjoint adj K ⋙ cocones.functoriality F ⟶ 𝟭 (cocone (K ⋙ F)) := { app := λ c, { hom := adj.counit.app c.X } } def functoriality_is_left_adjoint : is_left_adjoint (@cocones.functoriality _ _ _ _ K _ _ F) := { right := functoriality_right_adjoint adj K, adj := mk_of_unit_counit { unit := functoriality_unit adj K, counit := functoriality_counit adj K } } /-- A left adjoint preserves colimits. -/ instance left_adjoint_preserves_colimits : preserves_colimits F := { preserves_colimits_of_shape := λ J 𝒥, { preserves_colimit := λ F, by exactI { preserves := λ c hc, is_colimit.iso_unique_cocone_morphism.inv (λ s, (((adj.functoriality_is_left_adjoint _).adj).hom_equiv _ _).unique_of_equiv $ is_colimit.iso_unique_cocone_morphism.hom hc _ ) } } }. omit adj instance is_equivalence_preserves_colimits (E : C ⥤ D) [is_equivalence E] : preserves_colimits E := adjunction.left_adjoint_preserves_colimits E.adjunction -- verify the preserve_colimits instance works as expected: example (E : C ⥤ D) [is_equivalence E] (c : cocone K) (h : is_colimit c) : is_colimit (E.map_cocone c) := preserves_colimit.preserves E h instance has_colimit_comp_equivalence (E : C ⥤ D) [is_equivalence E] [has_colimit K] : has_colimit (K ⋙ E) := { cocone := E.map_cocone (colimit.cocone K), is_colimit := preserves_colimit.preserves E (colimit.is_colimit K) } def has_colimit_of_comp_equivalence (E : C ⥤ D) [is_equivalence E] [has_colimit (K ⋙ E)] : has_colimit K := @has_colimit_of_iso _ _ _ _ (K ⋙ E ⋙ inv E) K (@adjunction.has_colimit_comp_equivalence _ _ _ _ _ _ (K ⋙ E) (inv E) _ _) ((functor.right_unitor _).symm ≪≫ (iso_whisker_left K (fun_inv_id E)).symm) end preservation_colimits section preservation_limits variables {J : Type v} [small_category J] (K : J ⥤ D) def functoriality_left_adjoint : cone (K ⋙ G) ⥤ cone K := (cones.functoriality F) ⋙ (cones.postcompose ((associator _ _ _).hom ≫ (whisker_left K adj.counit) ≫ K.right_unitor.hom)) local attribute [reducible] functoriality_left_adjoint @[simps] def functoriality_unit' : 𝟭 (cone (K ⋙ G)) ⟶ functoriality_left_adjoint adj K ⋙ cones.functoriality G := { app := λ c, { hom := adj.unit.app c.X, } } @[simps] def functoriality_counit' : cones.functoriality G ⋙ functoriality_left_adjoint adj K ⟶ 𝟭 (cone K) := { app := λ c, { hom := adj.counit.app c.X, } } def functoriality_is_right_adjoint : is_right_adjoint (@cones.functoriality _ _ _ _ K _ _ G) := { left := functoriality_left_adjoint adj K, adj := mk_of_unit_counit { unit := functoriality_unit' adj K, counit := functoriality_counit' adj K } } /-- A right adjoint preserves limits. -/ instance right_adjoint_preserves_limits : preserves_limits G := { preserves_limits_of_shape := λ J 𝒥, { preserves_limit := λ K, by exactI { preserves := λ c hc, is_limit.iso_unique_cone_morphism.inv (λ s, (((adj.functoriality_is_right_adjoint _).adj).hom_equiv _ _).symm.unique_of_equiv $ is_limit.iso_unique_cone_morphism.hom hc _) } } }. omit adj instance is_equivalence_preserves_limits (E : D ⥤ C) [is_equivalence E] : preserves_limits E := adjunction.right_adjoint_preserves_limits E.inv.adjunction -- verify the preserve_limits instance works as expected: example (E : D ⥤ C) [is_equivalence E] (c : cone K) [h : is_limit c] : is_limit (E.map_cone c) := preserves_limit.preserves E h instance has_limit_comp_equivalence (E : D ⥤ C) [is_equivalence E] [has_limit K] : has_limit (K ⋙ E) := { cone := E.map_cone (limit.cone K), is_limit := preserves_limit.preserves E (limit.is_limit K) } def has_limit_of_comp_equivalence (E : D ⥤ C) [is_equivalence E] [has_limit (K ⋙ E)] : has_limit K := @has_limit_of_iso _ _ _ _ (K ⋙ E ⋙ inv E) K (@adjunction.has_limit_comp_equivalence _ _ _ _ _ _ (K ⋙ E) (inv E) _ _) ((iso_whisker_left K (fun_inv_id E)) ≪≫ (functor.right_unitor _)) end preservation_limits /-- auxilliary construction for `cocones_iso` -/ @[simps] def cocones_iso_component_hom {J : Type v} [small_category J] {K : J ⥤ C} (Y : D) (t : ((cocones J D).obj (op (K ⋙ F))).obj Y) : (G ⋙ (cocones J C).obj (op K)).obj Y := { app := λ j, (adj.hom_equiv (K.obj j) Y) (t.app j), naturality' := λ j j' f, by erw [← adj.hom_equiv_naturality_left, t.naturality]; dsimp; simp } /-- auxilliary construction for `cocones_iso` -/ @[simps] def cocones_iso_component_inv {J : Type v} [small_category J] {K : J ⥤ C} (Y : D) (t : (G ⋙ (cocones J C).obj (op K)).obj Y) : ((cocones J D).obj (op (K ⋙ F))).obj Y := { app := λ j, (adj.hom_equiv (K.obj j) Y).symm (t.app j), naturality' := λ j j' f, begin erw [← adj.hom_equiv_naturality_left_symm, ← adj.hom_equiv_naturality_right_symm, t.naturality], dsimp, simp end } -- Note: this is natural in K, but we do not yet have the tools to formulate that. def cocones_iso {J : Type v} [small_category J] {K : J ⥤ C} : (cocones J D).obj (op (K ⋙ F)) ≅ G ⋙ ((cocones J C).obj (op K)) := nat_iso.of_components (λ Y, { hom := cocones_iso_component_hom adj Y, inv := cocones_iso_component_inv adj Y, }) (by tidy) /-- auxilliary construction for `cones_iso` -/ @[simps] def cones_iso_component_hom {J : Type v} [small_category J] {K : J ⥤ D} (X : Cᵒᵖ) (t : (functor.op F ⋙ (cones J D).obj K).obj X) : ((cones J C).obj (K ⋙ G)).obj X := { app := λ j, (adj.hom_equiv (unop X) (K.obj j)) (t.app j), naturality' := λ j j' f, begin erw [← adj.hom_equiv_naturality_right, ← t.naturality, category.id_comp, category.id_comp], refl end } /-- auxilliary construction for `cones_iso` -/ @[simps] def cones_iso_component_inv {J : Type v} [small_category J] {K : J ⥤ D} (X : Cᵒᵖ) (t : ((cones J C).obj (K ⋙ G)).obj X) : (functor.op F ⋙ (cones J D).obj K).obj X := { app := λ j, (adj.hom_equiv (unop X) (K.obj j)).symm (t.app j), naturality' := λ j j' f, begin erw [← adj.hom_equiv_naturality_right_symm, ← t.naturality, category.id_comp, category.id_comp] end } -- Note: this is natural in K, but we do not yet have the tools to formulate that. def cones_iso {J : Type v} [small_category J] {K : J ⥤ D} : F.op ⋙ ((cones J D).obj K) ≅ (cones J C).obj (K ⋙ G) := nat_iso.of_components (λ X, { hom := cones_iso_component_hom adj X, inv := cones_iso_component_inv adj X, } ) (by tidy) end category_theory.adjunction
8345b83824e299ea74dde35dbcec2ffd8c5d7670
367134ba5a65885e863bdc4507601606690974c1
/src/topology/paracompact.lean
7d8bd67563e8ea0d79aecdaef511d412e192f850
[ "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
15,310
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Yury Kudryashov -/ import topology.subset_properties import topology.separation import data.option.basic /-! # Paracompact topological spaces A topological space `X` is said to be paracompact if every open covering of `X` admits a locally finite refinement. The definition requires that each set of the new covering is a subset of one of the sets of the initial covering. However, one can ensure that each open covering `s : ι → set X` admits a *precise* locally finite refinement, i.e., an open covering `t : ι → set X` with the same index set such that `∀ i, t i ⊆ s i`, see lemma `precise_refinement`. We also provide a convenience lemma `precise_refinement_set` that deals with open coverings of a closed subset of `X` instead of the whole space. We also prove the following facts. * Every compact space is paracompact, see instance `paracompact_of_compact`. * A locally compact sigma compact Hausdorff space is paracompact, see instance `paracompact_of_locally_compact_sigma_compact`. Moreover, we can choose a locally finite refinement with sets in a given collection of filter bases of `𝓝 x, `x : X`, see `refinement_of_locally_compact_sigma_compact_of_nhds_basis`. For example, in a proper metric space every open covering `⋃ i, s i` admits a refinement `⋃ i, metric.ball (c i) (r i)`. * Every paracompact Hausdorff space is normal. This statement is not an instance to avoid loops in the instance graph. * Every `emetric_space` is a paracompact space, see instance `emetric_space.paracompact_space` in `topology/metric_space/emetric_space`. ## TODO * Define partition of unity. * Prove (some of) [Michael's theorems](https://ncatlab.org/nlab/show/Michael%27s+theorem). ## Tags compact space, paracompact space, locally finite covering -/ open set filter function open_locale filter topological_space universes u v /-- A topological space is called paracompact, if every open covering of this space admits a locally finite refinement. We use the same universe for all types in the definition to avoid creating a class like `paracompact_space.{u v}`. Due to lemma `precise_refinement` below, every open covering `s : α → set X` indexed on `α : Type v` has a *precise* locally finite refinement, i.e., a locally finite refinement `t : α → set X` indexed on the same type such that each `∀ i, t i ⊆ s i`. -/ class paracompact_space (X : Type v) [topological_space X] : Prop := (locally_finite_refinement : ∀ (α : Type v) (s : α → set X) (ho : ∀ a, is_open (s a)) (hc : (⋃ a, s a) = univ), ∃ (β : Type v) (t : β → set X) (ho : ∀ b, is_open (t b)) (hc : (⋃ b, t b) = univ), locally_finite t ∧ ∀ b, ∃ a, t b ⊆ s a) variables {ι : Type u} {X : Type v} [topological_space X] /-- Any open cover of a paracompact space has a locally finite *precise* refinement, that is, one indexed on the same type with each open set contained in the corresponding original one. -/ lemma precise_refinement [paracompact_space X] (u : ι → set X) (uo : ∀ a, is_open (u a)) (uc : (⋃ i, u i) = univ) : ∃ v : ι → set X, (∀ a, is_open (v a)) ∧ (⋃ i, v i) = univ ∧ locally_finite v ∧ (∀ a, v a ⊆ u a) := begin -- Apply definition to `range u`, then turn existence quantifiers into functions using `choose` have := paracompact_space.locally_finite_refinement (range u) coe (set_coe.forall.2 $ forall_range_iff.2 uo) (by rwa [← sUnion_range, subtype.range_coe]), simp only [set_coe.exists, subtype.coe_mk, exists_range_iff', Union_eq_univ_iff, exists_prop] at this, choose α t hto hXt htf ind hind, choose t_inv ht_inv using hXt, choose U hxU hU using htf, -- Send each `i` to the union of `t a` over `a ∈ ind ⁻¹' {i}` refine ⟨λ i, ⋃ (a : α) (ha : ind a = i), t a, _, _, _, _⟩, { exact λ a, is_open_Union (λ a, is_open_Union $ λ ha, hto a) }, { simp only [eq_univ_iff_forall, mem_Union], exact λ x, ⟨ind (t_inv x), _, rfl, ht_inv _⟩ }, { refine λ x, ⟨U x, hxU x, ((hU x).image ind).subset _⟩, simp only [subset_def, mem_Union, mem_set_of_eq, set.nonempty, mem_inter_eq], rintro i ⟨y, ⟨a, rfl, hya⟩, hyU⟩, exact mem_image_of_mem _ ⟨y, hya, hyU⟩ }, { simp only [subset_def, mem_Union], rintro i x ⟨a, rfl, hxa⟩, exact hind _ hxa } end /-- In a paracompact space, every open covering of a closed set admits a locally finite refinement indexed by the same type. -/ lemma precise_refinement_set [paracompact_space X] {s : set X} (hs : is_closed s) (u : ι → set X) (uo : ∀ i, is_open (u i)) (us : s ⊆ ⋃ i, u i) : ∃ v : ι → set X, (∀ i, is_open (v i)) ∧ (s ⊆ ⋃ i, v i) ∧ locally_finite v ∧ (∀ i, v i ⊆ u i) := begin rcases precise_refinement (λ i, option.elim i sᶜ u) (option.forall.2 ⟨is_open_compl_iff.2 hs, uo⟩) _ with ⟨v, vo, vc, vf, vu⟩, refine ⟨v ∘ some, λ i, vo _, _, vf.comp_injective (option.some_injective _), λ i, vu _⟩, { simp only [Union_option, ← compl_subset_iff_union] at vc, exact subset.trans (subset_compl_comm.1 $ vu option.none) vc }, { simpa only [Union_option, option.elim, ← compl_subset_iff_union, compl_compl] } end /-- A compact space is paracompact. -/ @[priority 100] -- See note [lower instance priority] instance paracompact_of_compact [compact_space X] : paracompact_space X := begin -- the proof is trivial: we choose a finite subcover using compactness, and use it refine ⟨λ ι s ho hu, _⟩, rcases compact_univ.elim_finite_subcover _ ho hu.ge with ⟨T, hT⟩, have := hT, simp only [subset_def, mem_Union] at this, choose i hiT hi using λ x, this x (mem_univ x), refine ⟨(T : set ι), λ t, s t, λ t, ho _, _, locally_finite_of_fintype _, λ t, ⟨t, subset.rfl⟩⟩, rwa [Union_subtype, finset.set_bUnion_coe, ← univ_subset_iff], end /-- Let `X` be a locally compact sigma compact Hausdorff topological space, let `s` be a closed set in `X`. Suppose that for each `x ∈ s` the sets `B x : ι x → set X` with the predicate `p x : ι x → Prop` form a basis of the filter `𝓝 x`. Then there exists a locally finite covering `λ i, B (c i) (r i)` of `s` such that all “centers” `c i` belong to `s` and each `r i` satisfies `p (c i)`. The notation is inspired by the case `B x r = metric.ball x r` but the theorem applies to `nhds_basis_opens` as well. If the covering must be subordinate to some open covering of `s`, then the user should use a basis obtained by `filter.has_basis.restrict_subset` or a similar lemma, see the proof of `paracompact_of_locally_compact_sigma_compact` for an example. The formalization is based on two [ncatlab](https://ncatlab.org/) proofs: * [locally compact and sigma compact spaces are paracompact](https://ncatlab.org/nlab/show/locally+compact+and+sigma-compact+spaces+are+paracompact); * [open cover of smooth manifold admits locally finite refinement by closed balls](https://ncatlab.org/nlab/show/partition+of+unity#ExistenceOnSmoothManifolds). See also `refinement_of_locally_compact_sigma_compact_of_nhds_basis` for a version of this lemma dealing with a covering of the whole space. In most cases (namely, if `B c r ∪ B c r'` is again a set of the form `B c r''`) it is possible to choose `α = X`. This fact is not yet formalized in `mathlib`. -/ theorem refinement_of_locally_compact_sigma_compact_of_nhds_basis_set [locally_compact_space X] [sigma_compact_space X] [t2_space X] {ι : X → Type u} {p : Π x, ι x → Prop} {B : Π x, ι x → set X} {s : set X} (hs : is_closed s) (hB : ∀ x ∈ s, (𝓝 x).has_basis (p x) (B x)) : ∃ (α : Type v) (c : α → X) (r : Π a, ι (c a)), (∀ a, c a ∈ s ∧ p (c a) (r a)) ∧ (s ⊆ ⋃ a, B (c a) (r a)) ∧ locally_finite (λ a, B (c a) (r a)) := begin classical, -- For technical reasons we prepend two empty sets to the sequence `compact_exhaustion.choice X` set K' : compact_exhaustion X := compact_exhaustion.choice X, set K : compact_exhaustion X := K'.shiftr.shiftr, set Kdiff := λ n, K (n + 1) \ interior (K n), -- Now we restate some properties of `compact_exhaustion` for `K`/`Kdiff` have hKcov : ∀ x, x ∈ Kdiff (K'.find x + 1), { intro x, simpa only [K'.find_shiftr] using diff_subset_diff_right interior_subset (K'.shiftr.mem_diff_shiftr_find x) }, have Kdiffc : ∀ n, is_compact (Kdiff n ∩ s), from λ n, (compact_diff (K.is_compact _) is_open_interior).inter_right hs, -- Next we choose a finite covering `B (c n i) (r n i)` of each -- `Kdiff (n + 1) ∩ s` such that `B (c n i) (r n i) ∩ s` is disjoint with `K n` have : ∀ n (x : Kdiff (n + 1) ∩ s), (K n)ᶜ ∈ 𝓝 (x : X), from λ n x, mem_nhds_sets (K.is_closed n).is_open_compl (λ hx', x.2.1.2 $ K.subset_interior_succ _ hx'), haveI : ∀ n (x : Kdiff n ∩ s), nonempty (ι x) := λ n x, (hB x x.2.2).nonempty, choose! r hrp hr using (λ n (x : Kdiff (n + 1) ∩ s), (hB x x.2.2).mem_iff.1 (this n x)), have hxr : ∀ n x (hx : x ∈ Kdiff (n + 1) ∩ s), B x (r n ⟨x, hx⟩) ∈ 𝓝 x, from λ n x hx, (hB x hx.2).mem_of_mem (hrp _ ⟨x, hx⟩), choose T hT using λ n, (Kdiffc (n + 1)).elim_nhds_subcover' _ (hxr n), set T' : Π n, set ↥(Kdiff (n + 1) ∩ s) := λ n, T n, -- Finally, we take the union of all these coverings refine ⟨Σ n, T' n, λ a, a.2, λ a, r a.1 a.2, _, _, _⟩, { rintro ⟨n, x, hx⟩, exact ⟨x.2.2, hrp _ _⟩ }, { refine (λ x hx, mem_Union.2 _), rcases mem_bUnion_iff.1 (hT _ ⟨hKcov x, hx⟩) with ⟨⟨c, hc⟩, hcT, hcx⟩, exact ⟨⟨_, ⟨c, hc⟩, hcT⟩, hcx⟩ }, { intro x, refine ⟨interior (K (K'.find x + 3)), mem_nhds_sets is_open_interior (K.subset_interior_succ _ (hKcov x).1), _⟩, have : (⋃ k ≤ K'.find x + 2, (range $ sigma.mk k) : set (Σ n, T' n)).finite, from (finite_le_nat _).bUnion (λ k hk, finite_range _), apply this.subset, rintro ⟨k, c, hc⟩, simp only [mem_Union, mem_set_of_eq, mem_image_eq, subtype.coe_mk], rintro ⟨x, hxB : x ∈ B c (r k c), hxK⟩, refine ⟨k, _, ⟨c, hc⟩, rfl⟩, have := (mem_compl_iff _ _).1 (hr k c hxB), contrapose! this with hnk, exact K.subset hnk (interior_subset hxK) }, end /-- Let `X` be a locally compact sigma compact Hausdorff topological space. Suppose that for each `x` the sets `B x : ι x → set X` with the predicate `p x : ι x → Prop` form a basis of the filter `𝓝 x`. Then there exists a locally finite covering `λ i, B (c i) (r i)` of `X` such that each `r i` satisfies `p (c i)` The notation is inspired by the case `B x r = metric.ball x r` but the theorem applies to `nhds_basis_opens` as well. If the covering must be subordinate to some open covering of `s`, then the user should use a basis obtained by `filter.has_basis.restrict_subset` or a similar lemma, see the proof of `paracompact_of_locally_compact_sigma_compact` for an example. The formalization is based on two [ncatlab](https://ncatlab.org/) proofs: * [locally compact and sigma compact spaces are paracompact](https://ncatlab.org/nlab/show/locally+compact+and+sigma-compact+spaces+are+paracompact); * [open cover of smooth manifold admits locally finite refinement by closed balls](https://ncatlab.org/nlab/show/partition+of+unity#ExistenceOnSmoothManifolds). See also `refinement_of_locally_compact_sigma_compact_of_nhds_basis_set` for a version of this lemma dealing with a covering of a closed set. In most cases (namely, if `B c r ∪ B c r'` is again a set of the form `B c r''`) it is possible to choose `α = X`. This fact is not yet formalized in `mathlib`. -/ theorem refinement_of_locally_compact_sigma_compact_of_nhds_basis [locally_compact_space X] [sigma_compact_space X] [t2_space X] {ι : X → Type u} {p : Π x, ι x → Prop} {B : Π x, ι x → set X} (hB : ∀ x, (𝓝 x).has_basis (p x) (B x)) : ∃ (α : Type v) (c : α → X) (r : Π a, ι (c a)), (∀ a, p (c a) (r a)) ∧ (⋃ a, B (c a) (r a)) = univ ∧ locally_finite (λ a, B (c a) (r a)) := let ⟨α, c, r, hp, hU, hfin⟩ := refinement_of_locally_compact_sigma_compact_of_nhds_basis_set is_closed_univ (λ x _, hB x) in ⟨α, c, r, λ a, (hp a).2, univ_subset_iff.1 hU, hfin⟩ /-- A locally compact sigma compact Hausdorff space is paracompact. See also `refinement_of_locally_compact_sigma_compact_of_nhds_basis` for a more precise statement. -/ @[priority 100] -- See note [lower instance priority] instance paracompact_of_locally_compact_sigma_compact [locally_compact_space X] [sigma_compact_space X] [t2_space X] : paracompact_space X := begin refine ⟨λ α s ho hc, _⟩, choose i hi using Union_eq_univ_iff.1 hc, have : ∀ x : X, (𝓝 x).has_basis (λ t : set X, (x ∈ t ∧ is_open t) ∧ t ⊆ s (i x)) id, from λ x : X, (nhds_basis_opens x).restrict_subset (mem_nhds_sets (ho (i x)) (hi x)), rcases refinement_of_locally_compact_sigma_compact_of_nhds_basis this with ⟨β, c, t, hto, htc, htf⟩, exact ⟨β, t, λ x, (hto x).1.2, htc, htf, λ b, ⟨i $ c b, (hto b).2⟩⟩ end /- Dieudonné‘s theorem: a paracompact Hausdorff space is normal. Formalization is based on the proof at [ncatlab](https://ncatlab.org/nlab/show/paracompact+Hausdorff+spaces+are+normal). -/ lemma normal_of_paracompact_t2 [t2_space X] [paracompact_space X] : normal_space X := begin /- First we show how to go from points to a set on one side. -/ have : ∀ (s t : set X), is_closed s → is_closed t → (∀ x ∈ s, ∃ u v, is_open u ∧ is_open v ∧ x ∈ u ∧ t ⊆ v ∧ disjoint u v) → ∃ u v, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ disjoint u v, { /- For each `x ∈ s` we choose open disjoint `u x ∋ x` and `v x ⊇ t`. The sets `u x` form an open covering of `s`. We choose a locally finite refinement `u' : s → set X`, then `⋃ i, u' i` and `(closure (⋃ i, u' i))ᶜ` are disjoint open neighborhoods of `s` and `t`. -/ intros s t hs ht H, choose u v hu hv hxu htv huv using set_coe.forall'.1 H, rcases precise_refinement_set hs u hu (λ x hx, mem_Union.2 ⟨⟨x, hx⟩, hxu _⟩) with ⟨u', hu'o, hcov', hu'fin, hsub⟩, refine ⟨⋃ i, u' i, (closure (⋃ i, u' i))ᶜ, is_open_Union hu'o, is_closed_closure.is_open_compl, hcov', _, disjoint_compl_right.mono le_rfl (compl_le_compl subset_closure)⟩, rw [hu'fin.closure_Union, compl_Union, subset_Inter_iff], refine λ i x hxt hxu, absurd (htv i hxt) (closure_minimal _ (is_closed_compl_iff.2 $ hv _) hxu), exact λ y hyu hyv, huv i ⟨hsub _ hyu, hyv⟩ }, /- Now we apply the lemma twice: first to `s` and `t`, then to `t` and each point of `s`. -/ refine ⟨λ s t hs ht hst, this s t hs ht (λ x hx, _)⟩, rcases this t {x} ht is_closed_singleton (λ y hyt, _) with ⟨v, u, hv, hu, htv, hxu, huv⟩, { exact ⟨u, v, hu, hv, singleton_subset_iff.1 hxu, htv, huv.symm⟩ }, { have : x ≠ y, by { rintro rfl, exact hst ⟨hx, hyt⟩ }, rcases t2_separation this with ⟨v, u, hv, hu, hxv, hyu, hd⟩, exact ⟨u, v, hu, hv, hyu, singleton_subset_iff.2 hxv, disjoint.symm hd.le⟩ } end
3f4cc625ef82cf4d6f11a2113bf7fb2ad8db3aee
934eae675a9d997202bb021816325184e7d694aa
/_notes/Languages/lean/basics.lean
edd16952028f23f71ebc61117add7937384537d1
[]
no_license
philzook58/philzook58.github.io
da78841df4ffd9a19c81e0eab833983d95a64b70
76000a5847bd6ee41dff25937ae916835bbcf03f
refs/heads/master
1,692,951,958,916
1,692,631,945,000
1,692,631,945,000
91,513,884
9
4
null
1,677,330,791,000
1,494,977,989,000
Jupyter Notebook
UTF-8
Lean
false
false
608
lean
#eval 1 + 1 -- it's a nat #eval String.append "hello" "world" #eval if 1 > 2 then "yes" else "no" #eval (1 + 1 : Int) /- block comment -/ def hello := "hello" def Str : Type := String abbrev N : Type := Nat #check 1.2 structure Point where x : Float y : Float deriving Repr #check ({x := 1, y := 2} : Point) inductive MyBool where | MyTrue : MyBool | MyFalse : MyBool #check MyBool.MyTrue #eval Lean.versionString #check fun (x : Nat) => x #check λ x => x #eval let y := 2; y + y theorem foo : p -> q -> p /\ q := by intros x y apply And.intro apply x apply y done
707eefa2d27656eb5711532dc35b5e9c96320e12
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/calc1.lean
b8a19cee4e9d5b45767fb080f7bd1707b5a5449e
[ "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
1,651
lean
prelude constant A : Type.{1} definition bool : Type.{1} := Type.{0} constant eq : A → A → bool infixl ` = `:50 := eq axiom subst (P : A → bool) (a b : A) (H1 : a = b) (H2 : P a) : P b axiom eq_trans (a b c : A) (H1 : a = b) (H2 : b = c) : a = c axiom eq_refl (a : A) : a = a constant le : A → A → bool infixl ` ≤ `:50 := le axiom le_trans (a b c : A) (H1 : a ≤ b) (H2 : b ≤ c) : a ≤ c axiom le_refl (a : A) : a ≤ a axiom eq_le_trans (a b c : A) (H1 : a = b) (H2 : b ≤ c) : a ≤ c axiom le_eq_trans (a b c : A) (H1 : a ≤ b) (H2 : b = c) : a ≤ c attribute [subst] subst attribute [refl] eq_refl attribute [refl] le_refl attribute [trans] eq_trans attribute [trans] le_trans attribute [trans] eq_le_trans attribute [trans] le_eq_trans constants a b c d e f : A axiom H1 : a = b axiom H2 : b ≤ c axiom H3 : c ≤ d axiom H4 : d = e check calc a = b : H1 ... ≤ c : H2 ... ≤ d : H3 ... = e : H4 constant lt : A → A → bool infixl ` < `:50 := lt axiom lt_trans (a b c : A) (H1 : a < b) (H2 : b < c) : a < c axiom le_lt_trans (a b c : A) (H1 : a ≤ b) (H2 : b < c) : a < c axiom lt_le_trans (a b c : A) (H1 : a < b) (H2 : b ≤ c) : a < c axiom H5 : c < d -- check calc b ≤ c : H2 -- ... < d : H5 -- Error le_lt_trans was not registered yet attribute [trans] le_lt_trans check calc b ≤ c : H2 ... < d : H5 constant le2 : A → A → bool infixl ` ≤ `:50 := le2 constant le2_trans (a b c : A) (H1 : le2 a b) (H2 : le2 b c) : le2 a c attribute [trans] le2_trans -- print raw calc b ≤ c : H2 -- ... ≤ d : H3 -- ... ≤ e : H4
e9717780cafa23159a189ecd57b3223f75995190
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/group_theory/group_action/defs.lean
8c4de95dfd9687b12a6d9832e74ab5fcd50885e7
[ "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
29,165
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Yury Kudryashov -/ import algebra.group.defs import algebra.group.hom import algebra.group.type_tags import algebra.opposites import logic.embedding /-! # Definitions of group actions This file defines a hierarchy of group action type-classes on top of the previously defined notation classes `has_scalar` and its additive version `has_vadd`: * `mul_action M α` and its additive version `add_action G P` are typeclasses used for actions of multiplicative and additive monoids and groups; they extend notation classes `has_scalar` and `has_vadd` that are defined in `algebra.group.defs`; * `distrib_mul_action M A` is a typeclass for an action of a multiplicative monoid on an additive monoid such that `a • (b + c) = a • b + a • c` and `a • 0 = 0`. The hierarchy is extended further by `module`, defined elsewhere. Also provided are typeclasses for faithful and transitive actions, and typeclasses regarding the interaction of different group actions, * `smul_comm_class M N α` and its additive version `vadd_comm_class M N α`; * `is_scalar_tower M N α` (no additive version). * `is_central_scalar M α` (no additive version). ## Notation - `a • b` is used as notation for `has_scalar.smul a b`. - `a +ᵥ b` is used as notation for `has_vadd.vadd a b`. ## Implementation details This file should avoid depending on other parts of `group_theory`, to avoid import cycles. More sophisticated lemmas belong in `group_theory.group_action`. ## Tags group action -/ variables {M N G A B α β γ : Type*} open function /-! ### Faithful actions -/ /-- Typeclass for faithful actions. -/ class has_faithful_vadd (G : Type*) (P : Type*) [has_vadd G P] : Prop := (eq_of_vadd_eq_vadd : ∀ {g₁ g₂ : G}, (∀ p : P, g₁ +ᵥ p = g₂ +ᵥ p) → g₁ = g₂) /-- Typeclass for faithful actions. -/ @[to_additive has_faithful_vadd] class has_faithful_scalar (M : Type*) (α : Type*) [has_scalar M α] : Prop := (eq_of_smul_eq_smul : ∀ {m₁ m₂ : M}, (∀ a : α, m₁ • a = m₂ • a) → m₁ = m₂) export has_faithful_scalar (eq_of_smul_eq_smul) has_faithful_vadd (eq_of_vadd_eq_vadd) @[to_additive] lemma smul_left_injective' [has_scalar M α] [has_faithful_scalar M α] : function.injective ((•) : M → α → α) := λ m₁ m₂ h, has_faithful_scalar.eq_of_smul_eq_smul (congr_fun h) /-- See also `monoid.to_mul_action` and `mul_zero_class.to_smul_with_zero`. -/ @[priority 910, to_additive] -- see Note [lower instance priority] instance has_mul.to_has_scalar (α : Type*) [has_mul α] : has_scalar α α := ⟨(*)⟩ @[simp, to_additive] lemma smul_eq_mul (α : Type*) [has_mul α] {a a' : α} : a • a' = a * a' := rfl /-- Type class for additive monoid actions. -/ @[protect_proj] class add_action (G : Type*) (P : Type*) [add_monoid G] extends has_vadd G P := (zero_vadd : ∀ p : P, (0 : G) +ᵥ p = p) (add_vadd : ∀ (g₁ g₂ : G) (p : P), (g₁ + g₂) +ᵥ p = g₁ +ᵥ (g₂ +ᵥ p)) /-- Typeclass for multiplicative actions by monoids. This generalizes group actions. -/ @[protect_proj, to_additive] class mul_action (α : Type*) (β : Type*) [monoid α] extends has_scalar α β := (one_smul : ∀ b : β, (1 : α) • b = b) (mul_smul : ∀ (x y : α) (b : β), (x * y) • b = x • y • b) /-! ### (Pre)transitive action `M` acts pretransitively on `α` if for any `x y` there is `g` such that `g • x = y` (or `g +ᵥ x = y` for an additive action). A transitive action should furthermore have `α` nonempty. In this section we define typeclasses `mul_action.is_pretransitive` and `add_action.is_pretransitive` and provide `mul_action.exists_smul_eq`/`add_action.exists_vadd_eq`, `mul_action.surjective_smul`/`add_action.surjective_vadd` as public interface to access this property. We do not provide typeclasses `*_action.is_transitive`; users should assume `[mul_action.is_pretransitive M α] [nonempty α]` instead. -/ /-- `M` acts pretransitively on `α` if for any `x y` there is `g` such that `g +ᵥ x = y`. A transitive action should furthermore have `α` nonempty. -/ class add_action.is_pretransitive (M α : Type*) [has_vadd M α] : Prop := (exists_vadd_eq : ∀ x y : α, ∃ g : M, g +ᵥ x = y) /-- `M` acts pretransitively on `α` if for any `x y` there is `g` such that `g • x = y`. A transitive action should furthermore have `α` nonempty. -/ @[to_additive] class mul_action.is_pretransitive (M α : Type*) [has_scalar M α] : Prop := (exists_smul_eq : ∀ x y : α, ∃ g : M, g • x = y) namespace mul_action variables (M) {α} [has_scalar M α] [is_pretransitive M α] @[to_additive] lemma exists_smul_eq (x y : α) : ∃ m : M, m • x = y := is_pretransitive.exists_smul_eq x y @[to_additive] lemma surjective_smul (x : α) : surjective (λ c : M, c • x) := exists_smul_eq M x /-- The regular action of a group on itself is transitive. -/ @[to_additive] instance regular.is_pretransitive [group G] : is_pretransitive G G := ⟨λ x y, ⟨y * x⁻¹, inv_mul_cancel_right _ _⟩⟩ end mul_action /-! ### Scalar tower and commuting actions -/ /-- A typeclass mixin saying that two additive actions on the same space commute. -/ class vadd_comm_class (M N α : Type*) [has_vadd M α] [has_vadd N α] : Prop := (vadd_comm : ∀ (m : M) (n : N) (a : α), m +ᵥ (n +ᵥ a) = n +ᵥ (m +ᵥ a)) /-- A typeclass mixin saying that two multiplicative actions on the same space commute. -/ @[to_additive] class smul_comm_class (M N α : Type*) [has_scalar M α] [has_scalar N α] : Prop := (smul_comm : ∀ (m : M) (n : N) (a : α), m • n • a = n • m • a) export mul_action (mul_smul) add_action (add_vadd) smul_comm_class (smul_comm) vadd_comm_class (vadd_comm) /-- Frequently, we find ourselves wanting to express a bilinear map `M →ₗ[R] N →ₗ[R] P` or an equivalence between maps `(M →ₗ[R] N) ≃ₗ[R] (M' →ₗ[R] N')` where the maps have an associated ring `R`. Unfortunately, using definitions like these requires that `R` satisfy `comm_semiring R`, and not just `semiring R`. Using `M →ₗ[R] N →+ P` and `(M →ₗ[R] N) ≃+ (M' →ₗ[R] N')` avoids this problem, but throws away structure that is useful for when we _do_ have a commutative (semi)ring. To avoid making this compromise, we instead state these definitions as `M →ₗ[R] N →ₗ[S] P` or `(M →ₗ[R] N) ≃ₗ[S] (M' →ₗ[R] N')` and require `smul_comm_class S R` on the appropriate modules. When the caller has `comm_semiring R`, they can set `S = R` and `smul_comm_class_self` will populate the instance. If the caller only has `semiring R` they can still set either `R = ℕ` or `S = ℕ`, and `add_comm_monoid.nat_smul_comm_class` or `add_comm_monoid.nat_smul_comm_class'` will populate the typeclass, which is still sufficient to recover a `≃+` or `→+` structure. An example of where this is used is `linear_map.prod_equiv`. -/ library_note "bundled maps over different rings" /-- Commutativity of actions is a symmetric relation. This lemma can't be an instance because this would cause a loop in the instance search graph. -/ @[to_additive] lemma smul_comm_class.symm (M N α : Type*) [has_scalar M α] [has_scalar N α] [smul_comm_class M N α] : smul_comm_class N M α := ⟨λ a' a b, (smul_comm a a' b).symm⟩ /-- Commutativity of additive actions is a symmetric relation. This lemma can't be an instance because this would cause a loop in the instance search graph. -/ add_decl_doc vadd_comm_class.symm @[to_additive] instance smul_comm_class_self (M α : Type*) [comm_monoid M] [mul_action M α] : smul_comm_class M M α := ⟨λ a a' b, by rw [← mul_smul, mul_comm, mul_smul]⟩ /-- An instance of `is_scalar_tower M N α` states that the multiplicative action of `M` on `α` is determined by the multiplicative actions of `M` on `N` and `N` on `α`. -/ class is_scalar_tower (M N α : Type*) [has_scalar M N] [has_scalar N α] [has_scalar M α] : Prop := (smul_assoc : ∀ (x : M) (y : N) (z : α), (x • y) • z = x • (y • z)) @[simp] lemma smul_assoc {M N} [has_scalar M N] [has_scalar N α] [has_scalar M α] [is_scalar_tower M N α] (x : M) (y : N) (z : α) : (x • y) • z = x • y • z := is_scalar_tower.smul_assoc x y z instance semigroup.is_scalar_tower [semigroup α] : is_scalar_tower α α α := ⟨mul_assoc⟩ /-- A typeclass indicating that the right (aka `mul_opposite`) and left actions by `M` on `α` are equal, that is that `M` acts centrally on `α`. This can be thought of as a version of commutativity for `•`. -/ class is_central_scalar (M α : Type*) [has_scalar M α] [has_scalar Mᵐᵒᵖ α] : Prop := (op_smul_eq_smul : ∀ (m : M) (a : α), mul_opposite.op m • a = m • a) lemma is_central_scalar.unop_smul_eq_smul {M α : Type*} [has_scalar M α] [has_scalar Mᵐᵒᵖ α] [is_central_scalar M α] (m : Mᵐᵒᵖ) (a : α) : (mul_opposite.unop m) • a = m • a := mul_opposite.rec (by exact λ m, (is_central_scalar.op_smul_eq_smul _ _).symm) m export is_central_scalar (op_smul_eq_smul unop_smul_eq_smul) -- these instances are very low priority, as there is usually a faster way to find these instances @[priority 50] instance smul_comm_class.op_left [has_scalar M α] [has_scalar Mᵐᵒᵖ α] [is_central_scalar M α] [has_scalar N α] [smul_comm_class M N α] : smul_comm_class Mᵐᵒᵖ N α := ⟨λ m n a, by rw [←unop_smul_eq_smul m (n • a), ←unop_smul_eq_smul m a, smul_comm]⟩ @[priority 50] instance smul_comm_class.op_right [has_scalar M α] [has_scalar N α] [has_scalar Nᵐᵒᵖ α] [is_central_scalar N α] [smul_comm_class M N α] : smul_comm_class M Nᵐᵒᵖ α := ⟨λ m n a, by rw [←unop_smul_eq_smul n (m • a), ←unop_smul_eq_smul n a, smul_comm]⟩ @[priority 50] instance is_scalar_tower.op_left [has_scalar M α] [has_scalar Mᵐᵒᵖ α] [is_central_scalar M α] [has_scalar M N] [has_scalar Mᵐᵒᵖ N] [is_central_scalar M N] [has_scalar N α] [is_scalar_tower M N α] : is_scalar_tower Mᵐᵒᵖ N α := ⟨λ m n a, by rw [←unop_smul_eq_smul m (n • a), ←unop_smul_eq_smul m n, smul_assoc]⟩ @[priority 50] instance is_scalar_tower.op_right [has_scalar M α] [has_scalar M N] [has_scalar N α] [has_scalar Nᵐᵒᵖ α] [is_central_scalar N α] [is_scalar_tower M N α] : is_scalar_tower M Nᵐᵒᵖ α := ⟨λ m n a, by rw [←unop_smul_eq_smul n a, ←unop_smul_eq_smul (m • n) a, mul_opposite.unop_smul, smul_assoc]⟩ namespace has_scalar variables [has_scalar M α] /-- Auxiliary definition for `has_scalar.comp`, `mul_action.comp_hom`, `distrib_mul_action.comp_hom`, `module.comp_hom`, etc. -/ @[simp, to_additive /-" Auxiliary definition for `has_vadd.comp`, `add_action.comp_hom`, etc. "-/] def comp.smul (g : N → M) (n : N) (a : α) : α := g n • a variables (α) /-- An action of `M` on `α` and a function `N → M` induces an action of `N` on `α`. See note [reducible non-instances]. Since this is reducible, we make sure to go via `has_scalar.comp.smul` to prevent typeclass inference unfolding too far. -/ @[reducible, to_additive /-" An additive action of `M` on `α` and a function `N → M` induces an additive action of `N` on `α` "-/] def comp (g : N → M) : has_scalar N α := { smul := has_scalar.comp.smul g } variables {α} /-- Given a tower of scalar actions `M → α → β`, if we use `has_scalar.comp` to pull back both of `M`'s actions by a map `g : N → M`, then we obtain a new tower of scalar actions `N → α → β`. This cannot be an instance because it can cause infinite loops whenever the `has_scalar` arguments are still metavariables. -/ @[priority 100] lemma comp.is_scalar_tower [has_scalar M β] [has_scalar α β] [is_scalar_tower M α β] (g : N → M) : (by haveI := comp α g; haveI := comp β g; exact is_scalar_tower N α β) := by exact {smul_assoc := λ n, @smul_assoc _ _ _ _ _ _ _ (g n) } /-- This cannot be an instance because it can cause infinite loops whenever the `has_scalar` arguments are still metavariables. -/ @[priority 100] lemma comp.smul_comm_class [has_scalar β α] [smul_comm_class M β α] (g : N → M) : (by haveI := comp α g; exact smul_comm_class N β α) := by exact {smul_comm := λ n, @smul_comm _ _ _ _ _ _ (g n) } /-- This cannot be an instance because it can cause infinite loops whenever the `has_scalar` arguments are still metavariables. -/ @[priority 100] lemma comp.smul_comm_class' [has_scalar β α] [smul_comm_class β M α] (g : N → M) : (by haveI := comp α g; exact smul_comm_class β N α) := by exact {smul_comm := λ _ n, @smul_comm _ _ _ _ _ _ _ (g n) } end has_scalar section ite variables [has_scalar M α] (p : Prop) [decidable p] @[to_additive] lemma ite_smul (a₁ a₂ : M) (b : α) : (ite p a₁ a₂) • b = ite p (a₁ • b) (a₂ • b) := by split_ifs; refl @[to_additive] lemma smul_ite (a : M) (b₁ b₂ : α) : a • (ite p b₁ b₂) = ite p (a • b₁) (a • b₂) := by split_ifs; refl end ite section variables [monoid M] [mul_action M α] @[to_additive] lemma smul_smul (a₁ a₂ : M) (b : α) : a₁ • a₂ • b = (a₁ * a₂) • b := (mul_smul _ _ _).symm variable (M) @[simp, to_additive] theorem one_smul (b : α) : (1 : M) • b = b := mul_action.one_smul _ variables {M} /-- Pullback a multiplicative action along an injective map respecting `•`. See note [reducible non-instances]. -/ @[reducible, to_additive "Pullback an additive action along an injective map respecting `+ᵥ`."] protected def function.injective.mul_action [has_scalar M β] (f : β → α) (hf : injective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : mul_action M β := { smul := (•), one_smul := λ x, hf $ (smul _ _).trans $ one_smul _ (f x), mul_smul := λ c₁ c₂ x, hf $ by simp only [smul, mul_smul] } /-- Pushforward a multiplicative action along a surjective map respecting `•`. See note [reducible non-instances]. -/ @[reducible, to_additive "Pushforward an additive action along a surjective map respecting `+ᵥ`."] protected def function.surjective.mul_action [has_scalar M β] (f : α → β) (hf : surjective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : mul_action M β := { smul := (•), one_smul := λ y, by { rcases hf y with ⟨x, rfl⟩, rw [← smul, one_smul] }, mul_smul := λ c₁ c₂ y, by { rcases hf y with ⟨x, rfl⟩, simp only [← smul, mul_smul] } } /-- Push forward the action of `R` on `M` along a compatible surjective map `f : R →* S`. See also `function.surjective.distrib_mul_action_left` and `function.surjective.module_left`. -/ @[reducible, to_additive "Push forward the action of `R` on `M` along a compatible surjective map `f : R →+ S`."] def function.surjective.mul_action_left {R S M : Type*} [monoid R] [mul_action R M] [monoid S] [has_scalar S M] (f : R →* S) (hf : function.surjective f) (hsmul : ∀ c (x : M), f c • x = c • x) : mul_action S M := { smul := (•), one_smul := λ b, by rw [← f.map_one, hsmul, one_smul], mul_smul := hf.forall₂.mpr $ λ a b x, by simp only [← f.map_mul, hsmul, mul_smul] } section variables (M) /-- The regular action of a monoid on itself by left multiplication. This is promoted to a module by `semiring.to_module`. -/ @[priority 910, to_additive] -- see Note [lower instance priority] instance monoid.to_mul_action : mul_action M M := { smul := (*), one_smul := one_mul, mul_smul := mul_assoc } /-- The regular action of a monoid on itself by left addition. This is promoted to an `add_torsor` by `add_group_is_add_torsor`. -/ add_decl_doc add_monoid.to_add_action instance is_scalar_tower.left : is_scalar_tower M M α := ⟨λ x y z, mul_smul x y z⟩ variables {M} /-- Note that the `smul_comm_class α β β` typeclass argument is usually satisfied by `algebra α β`. -/ @[to_additive] lemma mul_smul_comm [has_mul β] [has_scalar α β] [smul_comm_class α β β] (s : α) (x y : β) : x * (s • y) = s • (x * y) := (smul_comm s x y).symm /-- Note that the `is_scalar_tower α β β` typeclass argument is usually satisfied by `algebra α β`. -/ lemma smul_mul_assoc [has_mul β] [has_scalar α β] [is_scalar_tower α β β] (r : α) (x y : β) : (r • x) * y = r • (x * y) := smul_assoc r x y /-- Note that the `is_scalar_tower M α α` and `smul_comm_class M α α` typeclass arguments are usually satisfied by `algebra M α`. -/ lemma smul_mul_smul [has_mul α] (r s : M) (x y : α) [is_scalar_tower M α α] [smul_comm_class M α α] : (r • x) * (s • y) = (r * s) • (x * y) := by rw [smul_mul_assoc, mul_smul_comm, ← smul_assoc, smul_eq_mul] end namespace mul_action variables (M α) /-- Embedding of `α` into functions `M → α` induced by a multiplicative action of `M` on `α`. -/ @[to_additive] def to_fun : α ↪ (M → α) := ⟨λ y x, x • y, λ y₁ y₂ H, one_smul M y₁ ▸ one_smul M y₂ ▸ by convert congr_fun H 1⟩ /-- Embedding of `α` into functions `M → α` induced by an additive action of `M` on `α`. -/ add_decl_doc add_action.to_fun variables {M α} @[simp, to_additive] lemma to_fun_apply (x : M) (y : α) : mul_action.to_fun M α y x = x • y := rfl variable (α) /-- A multiplicative action of `M` on `α` and a monoid homomorphism `N → M` induce a multiplicative action of `N` on `α`. See note [reducible non-instances]. -/ @[reducible, to_additive] def comp_hom [monoid N] (g : N →* M) : mul_action N α := { smul := has_scalar.comp.smul g, one_smul := by simp [g.map_one, mul_action.one_smul], mul_smul := by simp [g.map_mul, mul_action.mul_smul] } /-- An additive action of `M` on `α` and an additive monoid homomorphism `N → M` induce an additive action of `N` on `α`. See note [reducible non-instances]. -/ add_decl_doc add_action.comp_hom end mul_action end section compatible_scalar @[simp] lemma smul_one_smul {M} (N) [monoid N] [has_scalar M N] [mul_action N α] [has_scalar M α] [is_scalar_tower M N α] (x : M) (y : α) : (x • (1 : N)) • y = x • y := by rw [smul_assoc, one_smul] @[simp] lemma smul_one_mul {M N} [monoid N] [has_scalar M N] [is_scalar_tower M N N] (x : M) (y : N) : (x • 1) * y = x • y := smul_one_smul N x y @[simp, to_additive] lemma mul_smul_one {M N} [monoid N] [has_scalar M N] [smul_comm_class M N N] (x : M) (y : N) : y * (x • 1) = x • y := by rw [← smul_eq_mul, ← smul_comm, smul_eq_mul, mul_one] lemma is_scalar_tower.of_smul_one_mul {M N} [monoid N] [has_scalar M N] (h : ∀ (x : M) (y : N), (x • (1 : N)) * y = x • y) : is_scalar_tower M N N := ⟨λ x y z, by rw [← h, smul_eq_mul, mul_assoc, h, smul_eq_mul]⟩ @[to_additive] lemma smul_comm_class.of_mul_smul_one {M N} [monoid N] [has_scalar M N] (H : ∀ (x : M) (y : N), y * (x • (1 : N)) = x • y) : smul_comm_class M N N := ⟨λ x y z, by rw [← H x z, smul_eq_mul, ← H, smul_eq_mul, mul_assoc]⟩ end compatible_scalar /-- Typeclass for multiplicative actions on additive structures. This generalizes group modules. -/ class distrib_mul_action (M : Type*) (A : Type*) [monoid M] [add_monoid A] extends mul_action M A := (smul_add : ∀(r : M) (x y : A), r • (x + y) = r • x + r • y) (smul_zero : ∀(r : M), r • (0 : A) = 0) section variables [monoid M] [add_monoid A] [distrib_mul_action M A] theorem smul_add (a : M) (b₁ b₂ : A) : a • (b₁ + b₂) = a • b₁ + a • b₂ := distrib_mul_action.smul_add _ _ _ @[simp] theorem smul_zero (a : M) : a • (0 : A) = 0 := distrib_mul_action.smul_zero _ /-- Pullback a distributive multiplicative action along an injective additive monoid homomorphism. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.distrib_mul_action [add_monoid B] [has_scalar M B] (f : B →+ A) (hf : injective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : distrib_mul_action M B := { smul := (•), smul_add := λ c x y, hf $ by simp only [smul, f.map_add, smul_add], smul_zero := λ c, hf $ by simp only [smul, f.map_zero, smul_zero], .. hf.mul_action f smul } /-- Pushforward a distributive multiplicative action along a surjective additive monoid homomorphism. See note [reducible non-instances]. -/ @[reducible] protected def function.surjective.distrib_mul_action [add_monoid B] [has_scalar M B] (f : A →+ B) (hf : surjective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : distrib_mul_action M B := { smul := (•), smul_add := λ c x y, by { rcases hf x with ⟨x, rfl⟩, rcases hf y with ⟨y, rfl⟩, simp only [smul_add, ← smul, ← f.map_add] }, smul_zero := λ c, by simp only [← f.map_zero, ← smul, smul_zero], .. hf.mul_action f smul } /-- Push forward the action of `R` on `M` along a compatible surjective map `f : R →* S`. See also `function.surjective.mul_action_left` and `function.surjective.module_left`. -/ @[reducible] def function.surjective.distrib_mul_action_left {R S M : Type*} [monoid R] [add_monoid M] [distrib_mul_action R M] [monoid S] [has_scalar S M] (f : R →* S) (hf : function.surjective f) (hsmul : ∀ c (x : M), f c • x = c • x) : distrib_mul_action S M := { smul := (•), smul_zero := hf.forall.mpr $ λ c, by rw [hsmul, smul_zero], smul_add := hf.forall.mpr $ λ c x y, by simp only [hsmul, smul_add], .. hf.mul_action_left f hsmul } variable (A) /-- Compose a `distrib_mul_action` with a `monoid_hom`, with action `f r' • m`. See note [reducible non-instances]. -/ @[reducible] def distrib_mul_action.comp_hom [monoid N] (f : N →* M) : distrib_mul_action N A := { smul := has_scalar.comp.smul f, smul_zero := λ x, smul_zero (f x), smul_add := λ x, smul_add (f x), .. mul_action.comp_hom A f } /-- Each element of the monoid defines a additive monoid homomorphism. -/ @[simps] def distrib_mul_action.to_add_monoid_hom (x : M) : A →+ A := { to_fun := (•) x, map_zero' := smul_zero x, map_add' := smul_add x } variables (M) /-- Each element of the monoid defines an additive monoid homomorphism. -/ @[simps] def distrib_mul_action.to_add_monoid_End : M →* add_monoid.End A := { to_fun := distrib_mul_action.to_add_monoid_hom A, map_one' := add_monoid_hom.ext $ one_smul M, map_mul' := λ x y, add_monoid_hom.ext $ mul_smul x y } end section variables [monoid M] [add_group A] [distrib_mul_action M A] @[simp] theorem smul_neg (r : M) (x : A) : r • (-x) = -(r • x) := eq_neg_of_add_eq_zero $ by rw [← smul_add, neg_add_self, smul_zero] theorem smul_sub (r : M) (x y : A) : r • (x - y) = r • x - r • y := by rw [sub_eq_add_neg, sub_eq_add_neg, smul_add, smul_neg] end /-- Typeclass for multiplicative actions on multiplicative structures. This generalizes conjugation actions. -/ class mul_distrib_mul_action (M : Type*) (A : Type*) [monoid M] [monoid A] extends mul_action M A := (smul_mul : ∀ (r : M) (x y : A), r • (x * y) = (r • x) * (r • y)) (smul_one : ∀ (r : M), r • (1 : A) = 1) export mul_distrib_mul_action (smul_one) section variables [monoid M] [monoid A] [mul_distrib_mul_action M A] theorem smul_mul' (a : M) (b₁ b₂ : A) : a • (b₁ * b₂) = (a • b₁) * (a • b₂) := mul_distrib_mul_action.smul_mul _ _ _ /-- Pullback a multiplicative distributive multiplicative action along an injective monoid homomorphism. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.mul_distrib_mul_action [monoid B] [has_scalar M B] (f : B →* A) (hf : injective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : mul_distrib_mul_action M B := { smul := (•), smul_mul := λ c x y, hf $ by simp only [smul, f.map_mul, smul_mul'], smul_one := λ c, hf $ by simp only [smul, f.map_one, smul_one], .. hf.mul_action f smul } /-- Pushforward a multiplicative distributive multiplicative action along a surjective monoid homomorphism. See note [reducible non-instances]. -/ @[reducible] protected def function.surjective.mul_distrib_mul_action [monoid B] [has_scalar M B] (f : A →* B) (hf : surjective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : mul_distrib_mul_action M B := { smul := (•), smul_mul := λ c x y, by { rcases hf x with ⟨x, rfl⟩, rcases hf y with ⟨y, rfl⟩, simp only [smul_mul', ← smul, ← f.map_mul] }, smul_one := λ c, by simp only [← f.map_one, ← smul, smul_one], .. hf.mul_action f smul } variable (A) /-- Compose a `mul_distrib_mul_action` with a `monoid_hom`, with action `f r' • m`. See note [reducible non-instances]. -/ @[reducible] def mul_distrib_mul_action.comp_hom [monoid N] (f : N →* M) : mul_distrib_mul_action N A := { smul := has_scalar.comp.smul f, smul_one := λ x, smul_one (f x), smul_mul := λ x, smul_mul' (f x), .. mul_action.comp_hom A f } /-- Scalar multiplication by `r` as a `monoid_hom`. -/ def mul_distrib_mul_action.to_monoid_hom (r : M) : A →* A := { to_fun := (•) r, map_one' := smul_one r, map_mul' := smul_mul' r } variable {A} @[simp] lemma mul_distrib_mul_action.to_monoid_hom_apply (r : M) (x : A) : mul_distrib_mul_action.to_monoid_hom A r x = r • x := rfl variables (M A) /-- Each element of the monoid defines a monoid homomorphism. -/ @[simps] def mul_distrib_mul_action.to_monoid_End : M →* monoid.End A := { to_fun := mul_distrib_mul_action.to_monoid_hom A, map_one' := monoid_hom.ext $ one_smul M, map_mul' := λ x y, monoid_hom.ext $ mul_smul x y } end section variables [monoid M] [group A] [mul_distrib_mul_action M A] @[simp] theorem smul_inv' (r : M) (x : A) : r • (x⁻¹) = (r • x)⁻¹ := (mul_distrib_mul_action.to_monoid_hom A r).map_inv x theorem smul_div' (r : M) (x y : A) : r • (x / y) = (r • x) / (r • y) := (mul_distrib_mul_action.to_monoid_hom A r).map_div x y end variable (α) /-- The monoid of endomorphisms. Note that this is generalized by `category_theory.End` to categories other than `Type u`. -/ protected def function.End := α → α instance : monoid (function.End α) := { one := id, mul := (∘), mul_assoc := λ f g h, rfl, mul_one := λ f, rfl, one_mul := λ f, rfl, } instance : inhabited (function.End α) := ⟨1⟩ variable {α} /-- The tautological action by `function.End α` on `α`. This is generalized to bundled endomorphisms by: * `equiv.perm.apply_mul_action` * `add_monoid.End.apply_distrib_mul_action` * `add_aut.apply_distrib_mul_action` * `mul_aut.apply_mul_distrib_mul_action` * `ring_hom.apply_distrib_mul_action` * `linear_equiv.apply_distrib_mul_action` * `linear_map.apply_module` * `ring_hom.apply_mul_semiring_action` * `alg_equiv.apply_mul_semiring_action` -/ instance function.End.apply_mul_action : mul_action (function.End α) α := { smul := ($), one_smul := λ _, rfl, mul_smul := λ _ _ _, rfl } @[simp] lemma function.End.smul_def (f : function.End α) (a : α) : f • a = f a := rfl /-- `function.End.apply_mul_action` is faithful. -/ instance function.End.apply_has_faithful_scalar : has_faithful_scalar (function.End α) α := ⟨λ x y, funext⟩ /-- The tautological action by `add_monoid.End α` on `α`. This generalizes `function.End.apply_mul_action`. -/ instance add_monoid.End.apply_distrib_mul_action [add_monoid α] : distrib_mul_action (add_monoid.End α) α := { smul := ($), smul_zero := add_monoid_hom.map_zero, smul_add := add_monoid_hom.map_add, one_smul := λ _, rfl, mul_smul := λ _ _ _, rfl } @[simp] lemma add_monoid.End.smul_def [add_monoid α] (f : add_monoid.End α) (a : α) : f • a = f a := rfl /-- `add_monoid.End.apply_distrib_mul_action` is faithful. -/ instance add_monoid.End.apply_has_faithful_scalar [add_monoid α] : has_faithful_scalar (add_monoid.End α) α := ⟨add_monoid_hom.ext⟩ /-- The monoid hom representing a monoid action. When `M` is a group, see `mul_action.to_perm_hom`. -/ def mul_action.to_End_hom [monoid M] [mul_action M α] : M →* function.End α := { to_fun := (•), map_one' := funext (one_smul M), map_mul' := λ x y, funext (mul_smul x y) } /-- The monoid action induced by a monoid hom to `function.End α` See note [reducible non-instances]. -/ @[reducible] def mul_action.of_End_hom [monoid M] (f : M →* function.End α) : mul_action M α := mul_action.comp_hom α f /-- The tautological additive action by `additive (function.End α)` on `α`. -/ instance add_action.function_End : add_action (additive (function.End α)) α := { vadd := ($), zero_vadd := λ _, rfl, add_vadd := λ _ _ _, rfl } /-- The additive monoid hom representing an additive monoid action. When `M` is a group, see `add_action.to_perm_hom`. -/ def add_action.to_End_hom [add_monoid M] [add_action M α] : M →+ additive (function.End α) := { to_fun := (+ᵥ), map_zero' := funext (zero_vadd M), map_add' := λ x y, funext (add_vadd x y) } /-- The additive action induced by a hom to `additive (function.End α)` See note [reducible non-instances]. -/ @[reducible] def add_action.of_End_hom [add_monoid M] (f : M →+ additive (function.End α)) : add_action M α := add_action.comp_hom α f
fdf533094d30318d7070a956a5cf7f5f384b9e16
e514e8b939af519a1d5e9b30a850769d058df4e9
/src/tactic/rewrite_search/metric/edit_distance/core.lean
1bac1a16d41325e3050df3e3580aa51a95611858
[]
no_license
semorrison/lean-rewrite-search
dca317c5a52e170fb6ffc87c5ab767afb5e3e51a
e804b8f2753366b8957be839908230ee73f9e89f
refs/heads/master
1,624,051,754,485
1,614,160,817,000
1,614,160,817,000
162,660,605
0
1
null
null
null
null
UTF-8
Lean
false
false
5,355
lean
import tactic.rewrite_search.core import tactic.rewrite_search.module import data.rat.basic open tactic.rewrite_search open tactic.rewrite_search.bound_progress namespace tactic.rewrite_search.edit_distance variables {α : Type} [decidable_eq α] @[derive decidable_eq] structure ed_partial := (prefix_length : dnum) (suffix : list (table_ref × dnum)) (l₂_toks : list (table_ref × dnum)) (distances : list dnum) -- distances from the prefix of l₁ to each non-empty prefix of l₂ def compute_initial_distances_aux (weights : table dnum) : dnum → list table_ref → list dnum | _ [] := [] | so_far (a :: rest) := let so_far := so_far + (weights.iget a) in list.cons so_far (compute_initial_distances_aux so_far rest) @[inline] def compute_initial_distances (weights : table dnum) (l : list table_ref) : list dnum := compute_initial_distances_aux weights 0 l @[inline] def empty_partial_edit_distance_data (weights : table dnum) (l₁ l₂ : list table_ref) : ed_partial := ⟨ 0, l₁.map (λ r, (r, weights.iget r)), l₂.map (λ r, (r, weights.iget r)), compute_initial_distances weights l₂ ⟩ @[inline] def triples {α : Type} (p : ed_partial) (l₂ : list (α × dnum)): list (dnum × dnum × α × dnum) := p.distances.zip ((list.cons p.prefix_length p.distances).zip l₂) universe u --TODO explain me @[inline] meta def fold_fn (h : table_ref) (wh : dnum) (n : dnum × list dnum) : dnum × dnum × table_ref × dnum → dnum × list dnum | (a, b, r, wr) := let m := if h = r then b else dnum.minl [ /- deletion -/ a + wh, /- substitution -/ b + dnum.max wr wh, /- insertion -/ n.2.head + wh ] in (dnum.min m n.1, list.cons m n.2) --TODO explain me @[inline] meta def improve_bound_once (cur : dnum) (p : ed_partial) : bound_progress ed_partial := match p.suffix with | [] := exactly p.distances.ilast p | ((h, wh) :: t) := let new_prefix_length := p.prefix_length + wh in let initial : dnum × list dnum := (new_prefix_length, [new_prefix_length]) in let new_distances : dnum × list dnum := (triples p p.l₂_toks).foldl (fold_fn h wh) initial in at_least new_distances.1 ⟨ new_prefix_length, t, p.l₂_toks, new_distances.2.reverse.drop 1 ⟩ end meta def improve_bound_over (m : dnum) : bound_progress ed_partial → bound_progress ed_partial | (exactly n p) := exactly n p | (at_least n p) := if n > m then at_least n p else improve_bound_over (improve_bound_once n p) end tactic.rewrite_search.edit_distance namespace tactic.rewrite_search.metric.edit_distance open tactic.rewrite_search.edit_distance @[derive has_reflect] structure ed_config := (refresh_freq : ℕ := 10) (explain_thoughts : bool := ff) (trace_weights : bool := ff) structure ed_state := (cfg : ed_config) (weights : table dnum) def ed_state.init (cfg : ed_config := {}) : ed_state := ⟨cfg, table.create⟩ -- In future we might allow init_fn to return some internal weight state. At -- the moment, it is just used to ensure that an external depedency (e.g. -- external program or custom lean fork) is present. meta def calc_weights_fn (α δ : Type) := search_state α ed_state ed_partial δ → tactic (table dnum) meta structure calc_weights_block := (α δ : Type) (fn : calc_weights_fn α δ) meta structure ed_weight (α δ : Type) := (init : init_fn unit) (calc_weights : calc_weights_fn α δ) meta def ed_weight_constructor := Π α δ, ed_weight α δ variables {α δ : Type} (g : search_state α ed_state ed_partial δ) meta def ed_init (cfg : ed_config) (weight_init : init_fn unit) : tactic (init_result ed_state) := do init_result.chain "weight" weight_init $ λ _, init_result.pure $ ed_state.init cfg meta def ed_decode (icfg : iconfig.result) (w : init_fn unit) : tactic (init_result ed_state) := do cfg ← icfg.struct `tactic.rewrite_search.metric.edit_distance.ed_config ed_config, ed_init cfg w meta def ed_init_bound (l r : vertex) : bound_progress ed_partial := at_least 0 (empty_partial_edit_distance_data g.metric_state.weights l.tokens r.tokens) meta def ed_reweight (fn : search_state α ed_state ed_partial δ → tactic (table dnum)) (g : search_state α ed_state ed_partial δ) : tactic (search_state α ed_state ed_partial δ) := do g ← g.reset_all_estimates ed_init_bound, weights ← fn g, if g.metric_state.cfg.trace_weights then let weight_pairs := (g.tokens.to_list.zip weights.to_list).map ( λ p : token × dnum, to_string format!"{p.1.str}={p.2}" ) in tactic.trace format!"reweighted: {weight_pairs}" else tactic.skip, return $ g.mutate_metric {g.metric_state with weights := weights} meta def ed_update (fn : calc_weights_fn α δ) (g : search_state α ed_state ed_partial δ) (itr : ℕ) : tactic (search_state α ed_state ed_partial δ) := if g.metric_state.cfg.refresh_freq > 0 ∧ (itr % (g.metric_state.cfg.refresh_freq + 1) = 0) then do if g.metric_state.cfg.explain_thoughts then tactic.trace "pause! refreshing weights..." else tactic.skip, ed_reweight fn g else return g meta def ed_improve_estimate_over (g : search_state α ed_state ed_partial δ) (m : dnum) (l r : vertex) (bnd : bound_progress ed_partial) : bound_progress ed_partial := improve_bound_over m bnd end tactic.rewrite_search.metric.edit_distance
679fcf12c240ea4eb6d382bdd822f88bad91bcef
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/run/match2.lean
2d8be25158f3410285590cb7b4d1d9197d62c909
[ "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
279
lean
inductive imf (f : nat → nat) : nat → Type | mk1 : ∀ (a : nat), imf (f a) | mk2 : imf (f 0 + 1) definition inv_2 (f : nat → nat) : ∀ (b : nat), imf f b → {x : nat // x > b} → nat | .(f a) (imf.mk1 .f a) x := a | .(f 0 + 1) (imf.mk2 .f) x := subtype.elt_of x
ce56f9b237bd86d6c26531670056a9a4cf0894a4
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/field_theory/subfield.lean
90333bc429b146bdc8d88f42ab0b0f2ae35dfb65
[ "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
4,449
lean
/- Copyright (c) 2018 Andreas Swerdlow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andreas Swerdlow -/ import ring_theory.subring variables {F : Type*} [field F] (S : set F) section prio set_option default_priority 100 -- see Note [default priority] class is_subfield extends is_subring S : Prop := (inv_mem : ∀ {x : F}, x ∈ S → x⁻¹ ∈ S) end prio instance is_subfield.field [is_subfield S] : field S := { inv := λ x, ⟨x⁻¹, is_subfield.inv_mem x.2⟩, zero_ne_one := λ h : 0 = 1, (@zero_ne_one F _) (subtype.ext.1 h), mul_inv_cancel := λ a ha, subtype.ext.2 (mul_inv_cancel (λ h, ha $ subtype.ext.2 h)), inv_zero := subtype.ext.2 inv_zero, ..show comm_ring S, by apply_instance } instance univ.is_subfield : is_subfield (@set.univ F) := { inv_mem := by intros; trivial } /- note: in the next two declarations, if we let type-class inference figure out the instance `is_ring_hom.is_subring_preimage` then that instance only applies when particular instances of `is_add_subgroup _` and `is_submonoid _` are chosen (which are not the default ones). If we specify it explicitly, then it doesn't complain. -/ instance preimage.is_subfield {K : Type*} [field K] (f : F →+* K) (s : set K) [is_subfield s] : is_subfield (f ⁻¹' s) := { inv_mem := λ a (ha : f a ∈ s), show f a⁻¹ ∈ s, by { rw [f.map_inv], exact is_subfield.inv_mem ha }, ..f.is_subring_preimage s } instance image.is_subfield {K : Type*} [field K] (f : F →+* K) (s : set F) [is_subfield s] : is_subfield (f '' s) := { inv_mem := λ a ⟨x, xmem, ha⟩, ⟨x⁻¹, is_subfield.inv_mem xmem, ha ▸ f.map_inv⟩, ..f.is_subring_image s } instance range.is_subfield {K : Type*} [field K] (f : F →+* K) : is_subfield (set.range f) := by { rw ← set.image_univ, apply_instance } namespace field def closure : set F := { x | ∃ y ∈ ring.closure S, ∃ z ∈ ring.closure S, y / z = x } variables {S} theorem ring_closure_subset : ring.closure S ⊆ closure S := λ x hx, ⟨x, hx, 1, is_submonoid.one_mem, div_one x⟩ instance closure.is_submonoid : is_submonoid (closure S) := { mul_mem := by rintros _ _ ⟨p, hp, q, hq, hq0, rfl⟩ ⟨r, hr, s, hs, hs0, rfl⟩; exact ⟨p * r, is_submonoid.mul_mem hp hr, q * s, is_submonoid.mul_mem hq hs, (div_mul_div _ _ _ _).symm⟩, one_mem := ring_closure_subset $ is_submonoid.one_mem } instance closure.is_subfield : is_subfield (closure S) := have h0 : (0:F) ∈ closure S, from ring_closure_subset $ is_add_submonoid.zero_mem, { add_mem := begin intros a b ha hb, rcases (id ha) with ⟨p, hp, q, hq, rfl⟩, rcases (id hb) with ⟨r, hr, s, hs, rfl⟩, classical, by_cases hq0 : q = 0, by simp [hb, hq0], by_cases hs0 : s = 0, by simp [ha, hs0], exact ⟨p * s + q * r, is_add_submonoid.add_mem (is_submonoid.mul_mem hp hs) (is_submonoid.mul_mem hq hr), q * s, is_submonoid.mul_mem hq hs, (div_add_div p r hq0 hs0).symm⟩ end, zero_mem := h0, neg_mem := begin rintros _ ⟨p, hp, q, hq, rfl⟩, exact ⟨-p, is_add_subgroup.neg_mem hp, q, hq, neg_div q p⟩ end, inv_mem := begin rintros _ ⟨p, hp, q, hq, rfl⟩, classical, by_cases hp0 : p = 0, by simp [hp0, h0], exact ⟨q, hq, p, hp, inv_div.symm⟩ end } theorem mem_closure {a : F} (ha : a ∈ S) : a ∈ closure S := ring_closure_subset $ ring.mem_closure ha theorem subset_closure : S ⊆ closure S := λ _, mem_closure theorem closure_subset {T : set F} [is_subfield T] (H : S ⊆ T) : closure S ⊆ T := by rintros _ ⟨p, hp, q, hq, hq0, rfl⟩; exact is_submonoid.mul_mem (ring.closure_subset H hp) (is_subfield.inv_mem $ ring.closure_subset H hq) theorem closure_subset_iff (s t : set F) [is_subfield t] : closure s ⊆ t ↔ s ⊆ t := ⟨set.subset.trans subset_closure, closure_subset⟩ theorem closure_mono {s t : set F} (H : s ⊆ t) : closure s ⊆ closure t := closure_subset $ set.subset.trans H subset_closure end field lemma is_subfield_Union_of_directed {ι : Type*} [hι : nonempty ι] (s : ι → set F) [∀ i, is_subfield (s i)] (directed : ∀ i j, ∃ k, s i ⊆ s k ∧ s j ⊆ s k) : is_subfield (⋃i, s i) := { inv_mem := λ x hx, let ⟨i, hi⟩ := set.mem_Union.1 hx in set.mem_Union.2 ⟨i, is_subfield.inv_mem hi⟩, to_is_subring := is_subring_Union_of_directed s directed }
aa2a1df45767dee77451d94af698a7117278d0f2
1dd482be3f611941db7801003235dc84147ec60a
/src/ring_theory/unique_factorization_domain.lean
bb2ec618c2c0995747f0ef9954e5a0e9b64e5e20
[ "Apache-2.0" ]
permissive
sanderdahmen/mathlib
479039302bd66434bb5672c2a4cecf8d69981458
8f0eae75cd2d8b7a083cf935666fcce4565df076
refs/heads/master
1,587,491,322,775
1,549,672,060,000
1,549,672,060,000
169,748,224
0
0
Apache-2.0
1,549,636,694,000
1,549,636,694,000
null
UTF-8
Lean
false
false
19,735
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jens Wagemaker Theory of unique factorization domains. @TODO: setup the complete lattice structure on `factor_set`. -/ import ring_theory.associated algebra.gcd_domain variables {α : Type*} local infix ` ~ᵤ ` : 50 := associated /-- Unique factorization domains. In a unique factorization domain each element (except zero) is uniquely represented as a multiset of irreducible factors. Uniqueness is only up to associated elements. This is equivalent to defining a unique factorization domain as a domain in which each element (except zero) is non-uniquely represented as a multiset of prime factors. This definition is used. To define a UFD using the traditional definition in terms of multisets of irreducible factors, use the definition `of_unique_irreducible_factorization` -/ class unique_factorization_domain (α : Type*) [integral_domain α] := (factors : α → multiset α) (factors_prod : ∀{a : α}, a ≠ 0 → (factors a).prod ~ᵤ a) (prime_factors : ∀{a : α}, a ≠ 0 → ∀x∈factors a, prime x) namespace unique_factorization_domain variables [integral_domain α] [unique_factorization_domain α] @[elab_as_eliminator] lemma induction_on_prime {P : α → Prop} (a : α) (h₁ : P 0) (h₂ : ∀ x : α, is_unit x → P x) (h₃ : ∀ a p : α, a ≠ 0 → prime p → P a → P (p * a)) : P a := by haveI := classical.dec_eq α; exact if ha0 : a = 0 then ha0.symm ▸ h₁ else @multiset.induction_on _ (λ s : multiset α, ∀ (a : α), a ≠ 0 → s.prod ~ᵤ a → (∀ p ∈ s, prime p) → P a) (factors a) (λ _ _ h _, h₂ _ ((is_unit_iff_of_associated h.symm).2 is_unit_one)) (λ p s ih a ha0 ⟨u, hu⟩ hsp, have ha : a = (p * u) * s.prod, by simp [hu.symm, mul_comm, mul_assoc], have hs0 : s.prod ≠ 0, from λ _ : s.prod = 0, by simp * at *, ha.symm ▸ h₃ _ _ hs0 (prime_of_associated ⟨u, rfl⟩ (hsp p (multiset.mem_cons_self _ _))) (ih _ hs0 (by refl) (λ p hp, hsp p (multiset.mem_cons.2 (or.inr hp))))) _ ha0 (factors_prod ha0) (prime_factors ha0) lemma factors_irreducible {a : α} (ha : irreducible a) : ∃ p, a ~ᵤ p ∧ factors a = p :: 0 := by haveI := classical.dec_eq α; exact multiset.induction_on (factors a) (λ h, (ha.1 (associated_one_iff_is_unit.1 h.symm)).elim) (λ p s _ hp hs, let ⟨u, hu⟩ := hp in ⟨p, have hs0 : s = 0, from classical.by_contradiction (λ hs0, let ⟨q, hq⟩ := multiset.exists_mem_of_ne_zero hs0 in (hs q (by simp [hq])).2.1 $ (ha.2 ((p * u) * (s.erase q).prod) _ (by rw [mul_right_comm _ _ q, mul_assoc, ← multiset.prod_cons, multiset.cons_erase hq]; simp [hu.symm, mul_comm, mul_assoc])).resolve_left $ mt is_unit_of_mul_is_unit_left $ mt is_unit_of_mul_is_unit_left (hs p (multiset.mem_cons_self _ _)).2.1), ⟨associated.symm (by clear _let_match; simp * at *), hs0 ▸ rfl⟩⟩) (factors_prod (nonzero_of_irreducible ha)) (prime_factors (nonzero_of_irreducible ha)) lemma irreducible_iff_prime {p : α} : irreducible p ↔ prime p := by letI := classical.dec_eq α; exact if hp0 : p = 0 then by simp [hp0] else ⟨λ h, let ⟨q, hq⟩ := factors_irreducible h in have prime q, from hq.2 ▸ prime_factors hp0 _ (by simp [hq.2]), suffices prime (factors p).prod, from prime_of_associated (factors_prod hp0) this, hq.2.symm ▸ by simp [this], irreducible_of_prime⟩ lemma irreducible_factors : ∀{a : α}, a ≠ 0 → ∀x∈factors a, irreducible x := by simp only [irreducible_iff_prime]; exact @prime_factors _ _ _ lemma unique : ∀{f g : multiset α}, (∀x∈f, irreducible x) → (∀x∈g, irreducible x) → f.prod ~ᵤ g.prod → multiset.rel associated f g := by haveI := classical.dec_eq α; exact λ f, multiset.induction_on f (λ g _ hg h, multiset.rel_zero_left.2 $ multiset.eq_zero_of_forall_not_mem (λ x hx, have is_unit g.prod, by simpa [associated_one_iff_is_unit] using h.symm, (hg x hx).1 (is_unit_iff_dvd_one.2 (dvd.trans (multiset.dvd_prod hx) (is_unit_iff_dvd_one.1 this))))) (λ p f ih g hf hg hfg, let ⟨b, hbg, hb⟩ := exists_associated_mem_of_dvd_prod (irreducible_iff_prime.1 (hf p (by simp))) (λ q hq, irreducible_iff_prime.1 (hg _ hq)) $ (dvd_iff_dvd_of_rel_right hfg).1 (show p ∣ (p :: f).prod, by simp) in begin rw ← multiset.cons_erase hbg, exact multiset.rel.cons hb (ih (λ q hq, hf _ (by simp [hq])) (λ q (hq : q ∈ g.erase b), hg q (multiset.mem_of_mem_erase hq)) (associated_mul_left_cancel (by rwa [← multiset.prod_cons, ← multiset.prod_cons, multiset.cons_erase hbg]) hb (nonzero_of_irreducible (hf p (by simp))))) end) end unique_factorization_domain structure unique_irreducible_factorization (α : Type*) [integral_domain α] := (factors : α → multiset α) (factors_prod : ∀{a : α}, a ≠ 0 → (factors a).prod ~ᵤ a) (irreducible_factors : ∀{a : α}, a ≠ 0 → ∀x∈factors a, irreducible x) (unique : ∀{f g : multiset α}, (∀x∈f, irreducible x) → (∀x∈g, irreducible x) → f.prod ~ᵤ g.prod → multiset.rel associated f g) namespace unique_factorization_domain open unique_factorization_domain associated lattice variables [integral_domain α] [unique_factorization_domain α] [decidable_eq (associates α)] lemma exists_mem_factors_of_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) : p ∣ a → ∃ q ∈ factors a, p ~ᵤ q := λ ⟨b, hb⟩, have hb0 : b ≠ 0, from λ hb0, by simp * at *, have multiset.rel associated (p :: factors b) (factors a), from unique (λ x hx, (multiset.mem_cons.1 hx).elim (λ h, h.symm ▸ hp) (irreducible_factors hb0 _)) (irreducible_factors ha0) (associated.symm $ calc multiset.prod (factors a) ~ᵤ a : factors_prod ha0 ... = p * b : hb ... ~ᵤ multiset.prod (p :: factors b) : by rw multiset.prod_cons; exact associated_mul_mul (associated.refl _) (associated.symm (factors_prod hb0))), multiset.exists_mem_of_rel_of_mem this (by simp) def of_unique_irreducible_factorization {α : Type*} [integral_domain α] (o : unique_irreducible_factorization α) : unique_factorization_domain α := by letI := classical.dec_eq α; exact { prime_factors := λ a h p (hpa : p ∈ o.factors a), have hpi : irreducible p, from o.irreducible_factors h _ hpa, ⟨nonzero_of_irreducible hpi, hpi.1, λ a b ⟨x, hx⟩, if hab0 : a * b = 0 then (eq_zero_or_eq_zero_of_mul_eq_zero hab0).elim (λ ha0, by simp [ha0]) (λ hb0, by simp [hb0]) else have hx0 : x ≠ 0, from λ hx0, by simp * at *, have ha0 : a ≠ 0, from ne_zero_of_mul_ne_zero_right hab0, have hb0 : b ≠ 0, from ne_zero_of_mul_ne_zero_left hab0, have multiset.rel associated (p :: o.factors x) (o.factors a + o.factors b), from o.unique (λ i hi, (multiset.mem_cons.1 hi).elim (λ hip, hip.symm ▸ hpi) (o.irreducible_factors hx0 _)) (show ∀ x ∈ o.factors a + o.factors b, irreducible x, from λ x hx, (multiset.mem_add.1 hx).elim (o.irreducible_factors (ne_zero_of_mul_ne_zero_right hab0) _) (o.irreducible_factors (ne_zero_of_mul_ne_zero_left hab0) _)) $ calc multiset.prod (p :: o.factors x) ~ᵤ a * b : by rw [hx, multiset.prod_cons]; exact associated_mul_mul (by refl) (o.factors_prod hx0) ... ~ᵤ (o.factors a).prod * (o.factors b).prod : associated_mul_mul (o.factors_prod ha0).symm (o.factors_prod hb0).symm ... = _ : by rw multiset.prod_add, let ⟨q, hqf, hq⟩ := multiset.exists_mem_of_rel_of_mem this (multiset.mem_cons_self p _) in (multiset.mem_add.1 hqf).elim (λ hqa, or.inl $ (dvd_iff_dvd_of_rel_left hq).2 $ (dvd_iff_dvd_of_rel_right (o.factors_prod ha0)).1 (multiset.dvd_prod hqa)) (λ hqb, or.inr $ (dvd_iff_dvd_of_rel_left hq).2 $ (dvd_iff_dvd_of_rel_right (o.factors_prod hb0)).1 (multiset.dvd_prod hqb))⟩, ..o } end unique_factorization_domain namespace associates open unique_factorization_domain associated lattice variables [integral_domain α] [unique_factorization_domain α] [decidable_eq (associates α)] /-- `factor_set α` representation elements of unique factorization domain as multisets. `multiset α` produced by `factors` are only unique up to associated elements, while the multisets in `factor_set α` are unqiue by equality and restricted to irreducible elements. This gives us a representation of each element as a unique multisets (or the added ⊤ for 0), which has a complete lattice struture. Infimum is the greatest common divisor and supremum is the least common multiple. -/ @[reducible] def {u} factor_set (α : Type u) [integral_domain α] [unique_factorization_domain α] : Type u := with_top (multiset { a : associates α // irreducible a }) local attribute [instance] associated.setoid theorem unique' {p q : multiset (associates α)} : (∀a∈p, irreducible a) → (∀a∈q, irreducible a) → p.prod = q.prod → p = q := begin apply multiset.induction_on_multiset_quot p, apply multiset.induction_on_multiset_quot q, assume s t hs ht eq, refine multiset.map_mk_eq_map_mk_of_rel (unique_factorization_domain.unique _ _ _), { exact assume a ha, ((irreducible_mk_iff _).1 $ hs _ $ multiset.mem_map_of_mem _ ha) }, { exact assume a ha, ((irreducible_mk_iff _).1 $ ht _ $ multiset.mem_map_of_mem _ ha) }, simpa [quot_mk_eq_mk, prod_mk, mk_eq_mk_iff_associated] using eq end private theorem forall_map_mk_factors_irreducible (x : α) (hx : x ≠ 0) : ∀(a : associates α), a ∈ multiset.map associates.mk (factors x) → irreducible a := begin assume a ha, rcases multiset.mem_map.1 ha with ⟨c, hc, rfl⟩, exact (irreducible_mk_iff c).2 (irreducible_factors hx _ hc) end theorem prod_le_prod_iff_le {p q : multiset (associates α)} (hp : ∀a∈p, irreducible a) (hq : ∀a∈q, irreducible a) : p.prod ≤ q.prod ↔ p ≤ q := iff.intro begin rintros ⟨⟨c⟩, eq⟩, have : c ≠ 0, from (mt mk_eq_zero_iff_eq_zero.2 $ assume (hc : quot.mk setoid.r c = 0), have (0 : associates α) ∈ q, from prod_eq_zero_iff.1 $ eq ▸ hc.symm ▸ mul_zero _, not_irreducible_zero ((irreducible_mk_iff 0).1 $ hq _ this)), have : associates.mk (factors c).prod = quot.mk setoid.r c, from mk_eq_mk_iff_associated.2 (factors_prod this), refine le_iff_exists_add.2 ⟨(factors c).map associates.mk, unique' hq _ _⟩, { assume x hx, rcases multiset.mem_add.1 hx with h | h, exact hp x h, exact forall_map_mk_factors_irreducible c ‹c ≠ 0› _ h }, { simp [multiset.prod_add, prod_mk, *] at * } end prod_le_prod @[simp] theorem factor_set.coe_add {a b : multiset { a : associates α // irreducible a }} : (↑a + ↑b : factor_set α) = ↑(a + b) := with_top.coe_add lemma factor_set.sup_add_inf_eq_add : ∀(a b : factor_set α), a ⊔ b + a ⊓ b = a + b | none b := show ⊤ ⊔ b + ⊤ ⊓ b = ⊤ + b, by simp | a none := show a ⊔ ⊤ + a ⊓ ⊤ = a + ⊤, by simp | (some a) (some b) := show (a : factor_set α) ⊔ b + a ⊓ b = a + b, from begin rw [← with_top.coe_sup, ← with_top.coe_inf, ← with_top.coe_add, ← with_top.coe_add, with_top.coe_eq_coe], exact multiset.union_add_inter _ _ end def factors' (a : α) (ha : a ≠ 0) : multiset { a : associates α // irreducible a } := (factors a).pmap (λa ha, ⟨associates.mk a, (irreducible_mk_iff _).2 ha⟩) (irreducible_factors $ ha) @[simp] theorem map_subtype_val_factors' {a : α} (ha : a ≠ 0) : (factors' a ha).map subtype.val = (factors a).map associates.mk := by simp [factors', multiset.map_pmap, multiset.pmap_eq_map] theorem factors'_cong {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) (h : a ~ᵤ b) : factors' a ha = factors' b hb := have multiset.rel associated (factors a) (factors b), from unique (irreducible_factors ha) (irreducible_factors hb) ((factors_prod ha).trans $ h.trans $ (factors_prod hb).symm), by simpa [(multiset.map_eq_map subtype.val_injective).symm, rel_associated_iff_map_eq_map.symm] def factors (a : associates α) : factor_set α := begin refine (if h : a = 0 then ⊤ else quotient.hrec_on a (λx h, some $ factors' x (mt mk_eq_zero_iff_eq_zero.2 h)) _ h), assume a b hab, apply function.hfunext, { have : a ~ᵤ 0 ↔ b ~ᵤ 0, from iff.intro (assume ha0, hab.symm.trans ha0) (assume hb0, hab.trans hb0), simp [quotient_mk_eq_mk, mk_eq_zero_iff_eq_zero, (associated_zero_iff_eq_zero _).symm, this] }, exact (assume ha hb eq, heq_of_eq $ congr_arg some $ factors'_cong _ _ hab) end @[simp] theorem factors_0 : (0 : associates α).factors = ⊤ := dif_pos rfl @[simp] theorem factors_mk (a : α) (h : a ≠ 0) : (associates.mk a).factors = factors' a h := dif_neg (mt mk_eq_zero_iff_eq_zero.1 h) def factor_set.prod : factor_set α → associates α | none := 0 | (some s) := (s.map subtype.val).prod @[simp] theorem prod_top : (⊤ : factor_set α).prod = 0 := rfl @[simp] theorem prod_coe {s : multiset { a : associates α // irreducible a }} : (s : factor_set α).prod = (s.map subtype.val).prod := rfl theorem prod_factors : ∀(s : factor_set α), s.prod.factors = s | none := by simp [factor_set.prod]; refl | (some s) := begin unfold factor_set.prod, generalize eq_a : (s.map subtype.val).prod = a, rcases a with ⟨a⟩, rw quot_mk_eq_mk at *, have : (s.map subtype.val).prod ≠ 0, from assume ha, let ⟨⟨a, ha⟩, h, eq⟩ := multiset.mem_map.1 (prod_eq_zero_iff.1 ha) in have irreducible (0 : associates α), from eq ▸ ha, not_irreducible_zero ((irreducible_mk_iff _).1 this), have ha : a ≠ 0, by simp [*] at *, suffices : (unique_factorization_domain.factors a).map associates.mk = s.map subtype.val, { rw [factors_mk a ha], apply congr_arg some _, simpa [(multiset.map_eq_map subtype.val_injective).symm] }, refine unique' (forall_map_mk_factors_irreducible _ ha) (assume a ha, let ⟨⟨x, hx⟩, ha, eq⟩ := multiset.mem_map.1 ha in eq ▸ hx) _, rw [prod_mk, eq_a, mk_eq_mk_iff_associated], exact factors_prod ha end theorem factors_prod (a : associates α) : a.factors.prod = a := quotient.induction_on a $ assume a, decidable.by_cases (assume : associates.mk a = 0, by simp [quotient_mk_eq_mk, this]) (assume : associates.mk a ≠ 0, have a ≠ 0, by simp * at *, by simp [this, quotient_mk_eq_mk, prod_mk, mk_eq_mk_iff_associated.2 (factors_prod this)]) theorem eq_of_factors_eq_factors {a b : associates α} (h : a.factors = b.factors) : a = b := have a.factors.prod = b.factors.prod, by rw h, by rwa [factors_prod, factors_prod] at this theorem eq_of_prod_eq_prod {a b : factor_set α} (h : a.prod = b.prod) : a = b := have a.prod.factors = b.prod.factors, by rw h, by rwa [prod_factors, prod_factors] at this @[simp] theorem prod_add : ∀(a b : factor_set α), (a + b).prod = a.prod * b.prod | none b := show (⊤ + b).prod = (⊤:factor_set α).prod * b.prod, by simp | a none := show (a + ⊤).prod = a.prod * (⊤:factor_set α).prod, by simp | (some a) (some b) := show (↑a + ↑b:factor_set α).prod = (↑a:factor_set α).prod * (↑b:factor_set α).prod, by rw [factor_set.coe_add, prod_coe, prod_coe, prod_coe, multiset.map_add, multiset.prod_add] theorem prod_mono : ∀{a b : factor_set α}, a ≤ b → a.prod ≤ b.prod | none b h := have b = ⊤, from top_unique h, by rw [this, prod_top]; exact le_refl _ | a none h := show a.prod ≤ (⊤ : factor_set α).prod, by simp; exact le_top | (some a) (some b) h := prod_le_prod $ multiset.map_le_map $ with_top.coe_le_coe.1 $ h @[simp] theorem factors_mul (a b : associates α) : (a * b).factors = a.factors + b.factors := eq_of_prod_eq_prod $ eq_of_factors_eq_factors $ by rw [prod_add, factors_prod, factors_prod, factors_prod] theorem factors_mono : ∀{a b : associates α}, a ≤ b → a.factors ≤ b.factors | s t ⟨d, rfl⟩ := by rw [factors_mul] ; exact le_add_of_nonneg_right' bot_le theorem factors_le {a b : associates α} : a.factors ≤ b.factors ↔ a ≤ b := iff.intro (assume h, have a.factors.prod ≤ b.factors.prod, from prod_mono h, by rwa [factors_prod, factors_prod] at this) factors_mono theorem prod_le {a b : factor_set α} : a.prod ≤ b.prod ↔ a ≤ b := iff.intro (assume h, have a.prod.factors ≤ b.prod.factors, from factors_mono h, by rwa [prod_factors, prod_factors] at this) prod_mono instance : has_sup (associates α) := ⟨λa b, (a.factors ⊔ b.factors).prod⟩ instance : has_inf (associates α) := ⟨λa b, (a.factors ⊓ b.factors).prod⟩ instance : bounded_lattice (associates α) := { sup := (⊔), inf := (⊓), sup_le := assume a b c hac hbc, factors_prod c ▸ prod_mono (sup_le (factors_mono hac) (factors_mono hbc)), le_sup_left := assume a b, le_trans (le_of_eq (factors_prod a).symm) $ prod_mono $ le_sup_left, le_sup_right := assume a b, le_trans (le_of_eq (factors_prod b).symm) $ prod_mono $ le_sup_right, le_inf := assume a b c hac hbc, factors_prod a ▸ prod_mono (le_inf (factors_mono hac) (factors_mono hbc)), inf_le_left := assume a b, le_trans (prod_mono inf_le_left) (le_of_eq (factors_prod a)), inf_le_right := assume a b, le_trans (prod_mono inf_le_right) (le_of_eq (factors_prod b)), .. associates.partial_order, .. associates.lattice.order_top, .. associates.lattice.order_bot } lemma sup_mul_inf (a b : associates α) : (a ⊔ b) * (a ⊓ b) = a * b := show (a.factors ⊔ b.factors).prod * (a.factors ⊓ b.factors).prod = a * b, begin refine eq_of_factors_eq_factors _, rw [← prod_add, prod_factors, factors_mul, factor_set.sup_add_inf_eq_add] end end associates section open associates unique_factorization_domain lattice /-- `to_gcd_domain` constructs a GCD domain out of a unique factorization domain over a normalization domain. -/ def unique_factorization_domain.to_gcd_domain (α : Type*) [normalization_domain α] [unique_factorization_domain α] [decidable_eq (associates α)] : gcd_domain α := { gcd := λa b, (associates.mk a ⊓ associates.mk b).out, lcm := λa b, (associates.mk a ⊔ associates.mk b).out, gcd_dvd_left := assume a b, (out_dvd_iff a (associates.mk a ⊓ associates.mk b)).2 $ inf_le_left, gcd_dvd_right := assume a b, (out_dvd_iff b (associates.mk a ⊓ associates.mk b)).2 $ inf_le_right, dvd_gcd := assume a b c hac hab, show a ∣ (associates.mk c ⊓ associates.mk b).out, by rw [dvd_out_iff, le_inf_iff, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff]; exact ⟨hac, hab⟩, lcm_zero_left := assume a, show (⊤ ⊔ associates.mk a).out = 0, by simp, lcm_zero_right := assume a, show (associates.mk a ⊔ ⊤).out = 0, by simp, gcd_mul_lcm := assume a b, show (associates.mk a ⊓ associates.mk b).out * (associates.mk a ⊔ associates.mk b).out = a * b * norm_unit (a * b), by rw [← out_mk, ← out_mul, mul_comm, sup_mul_inf]; refl, norm_unit_gcd := assume a b, norm_unit_out _, .. ‹normalization_domain α› } end
d107361a771cc197bd4f991a4aade72e7c288db4
a9fe717b93ccfa4b2e64faeb24f96dfefb390240
/ee.lean
d58789f8428c4c6ab3587f1e5a38342aee6c2c0f
[]
no_license
skbaek/omega
ab1f4a6daadfc8c855f14c39d9459ab841527141
715e384ed14e8eb177a326700066e7c98269e078
refs/heads/master
1,588,000,876,352
1,552,645,917,000
1,552,645,917,000
174,442,914
1
0
null
null
null
null
UTF-8
Lean
false
false
13,018
lean
import .int .clause def sgm (v : nat → int) (b : int) (as : list int) (n) := let a_n : int := as.get n in let m : int := a_n + 1 in ((symmod b m) + (coeffs.val v (as.map (λ x, symmod x m)))) / m /- Given a term t such that 0 = t and t = b + a₀ * x₀ + ... aₘ * xₘ, solve for the nth variable xₙ, obtain equation of the form xₙ = r, and return r (the rhs r has no occurrences of xₙ and includes a new variable σ, which is assigned the index n which is no longer used). -/ def rhs : nat → int → coeffs → term | n b as := let m := as.get n + 1 in ⟨(symmod b m), (as.map (λ x, symmod x m)){n ↦ -m}⟩ lemma rhs_correct_aux {m v} {as : coeffs} : ∀ {k}, ∃ d, (m * d + coeffs.val_btw v (as.map (λ (x : ℤ), symmod x m)) 0 k = coeffs.val_btw v as 0 k) | 0 := begin existsi (0 : int), simp_omega end | (k+1) := begin simp_omega, cases @rhs_correct_aux k with d h1, rw ← h1, by_cases hk : k < as.length, { rw [list.get_map hk, symmod_eq, sub_mul], existsi (d + (symdiv (list.get k as) m * v k)), ring }, { rw not_lt at hk, repeat {rw list.get_eq_zero_of_le}, existsi d, rw add_assoc, exact hk, simp only [hk, list.length_map] } end lemma rhs_correct {v b} {as : coeffs} (n) : 0 < as.get n → 0 = term.val v (b,as) → v n = term.val (v⟨n ↦ sgm v b as n⟩) (rhs n b as) := begin intros h0 h1, let a_n := as.get n, let m := a_n + 1, have h3 : m ≠ 0 := begin apply ne_of_gt, apply lt_trans h0, simp [a_n, m], end, have h2 : m * (sgm v b as n) = (symmod b m) + coeffs.val v (as.map (λ x, symmod x m)), { simp only [sgm, mul_comm m], rw [int.div_mul_cancel], have h4 : ∃ c, m * c + (symmod b (list.get n as + 1) + coeffs.val v (as.map (λ (x : ℤ), symmod x m))) = term.val v (b,as), { have h5: ∃ d, m * d + (coeffs.val v (as.map (λ x, symmod x m))) = coeffs.val v as, { simp only [coeffs.val, list.length_map], apply rhs_correct_aux }, cases h5 with d h5, rw symmod_eq, existsi (symdiv b m + d), simp only [term.val], rw ← h5, simp only [term.val, mul_add, add_mul, m, a_n], ring }, cases h4 with c h4, rw [dvd_add_iff_right (dvd_mul_right m c), h4, ← h1], apply dvd_zero }, apply calc v n = -(m * sgm v b as n) + (symmod b m) + (coeffs.val_except n v (as.map (λ x, symmod x m))) : begin rw h2, simp, rw ← coeffs.val_except_add_eq n, simp, have hn : n < as.length, { by_contra hc, rw not_lt at hc, rw (list.get_eq_zero_of_le n hc) at h0, cases h0 }, rw list.get_map hn, simp [a_n, m], rw [add_comm, symmod_add_one h0], ring end ... = term.val (v⟨n↦sgm v b as n⟩) (rhs n b as) : begin simp only [rhs, term.val], rw [← coeffs.val_except_add_eq n, list.get_set, update_eq], have h2 : ∀ a b c : int, a + b + c = b + (c + a) := by {intros, ring}, rw (h2 (- _)), apply fun_mono_2 rfl, apply fun_mono_2, { rw coeffs.val_except_update_set }, { simp [m, a_n], ring } end end def sym_sym (m b : int) : int := symdiv b m + symmod b m -- Requires : 0 < as[n] def coeffs_reduce : nat → int → list int → term | n b as := let a := as.get n in let m := a + 1 in (sym_sym m b, (as.map (sym_sym m)){n ↦ -a}) lemma coeffs_reduce_correct {v b} {as : coeffs} {n} : 0 < as.get n → 0 = term.val v (b,as) → 0 = term.val (v⟨n ↦ sgm v b as n⟩) (coeffs_reduce n b as) := begin intros h1 h2, let a_n := as.get n, let m := a_n + 1, have h3 : m ≠ 0 := begin apply ne_of_gt, apply lt_trans h1, simp [m] end, have h4 : 0 = (term.val (v⟨n↦sgm v b as n⟩) (coeffs_reduce n b as)) * m := calc 0 = term.val v (b,as) : h2 ... = b + coeffs.val_except n v as + a_n * ((rhs n b as).val (v⟨n ↦ sgm v b as n⟩)) : begin simp only [term.val], rw [← coeffs.val_except_add_eq n, rhs_correct n h1 h2], simp only [a_n, add_assoc], end ... = -(m * a_n * sgm v b as n) + (b + a_n * (symmod b m)) + (coeffs.val_except n v as + a_n * coeffs.val_except n v (as.map (λ x, symmod x m))) : begin simp [term.val, rhs, mul_add, m, a_n], rw [← coeffs.val_except_add_eq n, list.get_set, update_eq, mul_add], apply fun_mono_2, { rw coeffs.val_except_eq_val_except update_eq_of_ne list.get_set_eq_of_ne }, { simp only [m], ring }, end ... = -(m * a_n * sgm v b as n) + (b + a_n * (symmod b m)) + coeffs.val_except n v (as.map (λ a_i, a_i + a_n * (symmod a_i m))) : begin apply fun_mono_2 rfl, simp only [coeffs.val_except, mul_add], repeat {rw ← coeffs.val_btw_map_mul}, have h4 : ∀ {a b c d : int}, a + b + (c + d) = (a + c) + (b + d), { intros, ring }, rw h4, have h5 : list.add as (list.map (has_mul.mul a_n) (list.map (λ (x : ℤ), symmod x (list.get n as + 1)) as)) = list.map (λ (a_i : ℤ), a_i + a_n * symmod a_i m) as, { rw [list.map_map, list.map_add_map], apply fun_mono_2, { have h5 : (λ x : int, x) = id, { rw function.funext_iff, intro x, refl }, rw [h5, list.map_id] }, { apply fun_mono_2 _ rfl, rw function.funext_iff, intro x, simp only [m] } }, simp only [list.length_map], repeat { rw [← coeffs.val_btw_add, h5] }, end ... = -(m * a_n * sgm v b as n) + (m * sym_sym m b) + coeffs.val_except n v (as.map (λ a_i, m * sym_sym m a_i)) : begin repeat {rw add_assoc}, apply fun_mono_2, refl, rw ← add_assoc, have h4 : ∀ (x : ℤ), x + a_n * symmod x m = m * sym_sym m x, { intro x, have h5 : a_n = m - 1, { simp only [m], rw add_sub_cancel }, rw [h5, sub_mul, one_mul, add_sub, add_comm, add_sub_assoc, ← mul_symdiv_eq], simp only [sym_sym, mul_add, add_comm] }, apply fun_mono_2 (h4 _), apply coeffs.val_except_eq_val_except; intros x h5, refl, apply congr_arg, apply fun_mono_2 _ rfl, rw function.funext_iff, apply h4, end ... = (-(a_n * sgm v b as n) + (sym_sym m b) + coeffs.val_except n v (as.map (sym_sym m))) * m : begin simp only [add_mul _ _ m], apply fun_mono_2, ring, simp only [coeffs.val_except], simp only [add_mul _ _ m], apply fun_mono_2, { rw [mul_comm _ m, ← coeffs.val_btw_map_mul, list.map_map] }, { simp only [list.length_map, mul_comm _ m], rw [← coeffs.val_btw_map_mul, list.map_map] } end ... = (term.val (v⟨n↦sgm v b as n⟩) (coeffs_reduce n b as)) * m : begin simp_omega [coeffs_reduce, add_mul], rw [add_comm _ (sym_sym m b * m), add_assoc], apply fun_mono_2, refl, rw [← coeffs.val_except_add_eq n, list.get_set, update_eq, add_comm, add_mul], apply fun_mono_2, { apply congr_arg (λ x, x * m), apply coeffs.val_except_eq_val_except; intros x h4, { rw update_eq_of_ne _ h4 }, { rw list.get_set_eq_of_ne _ h4 } }, { apply congr_arg (λ x, x * m), simp only [neg_mul_eq_neg_mul] } end, rw [← int.mul_div_cancel (term.val _ _) h3, ← h4, int.zero_div] end -- Requires : t1.coeffs[m] = 1 def cancel (m : nat) (t1 t2 : term) : term := term.add (t1.mul (-t2.snd.get m)) t2 def subst (n : nat) (t1 t2 : term) : term := term.add (t1.mul (t2.snd.get n)) (t2.fst,t2.snd{n ↦ 0}) lemma subst_correct {v t n b} {as : coeffs} : 0 < as.get n → 0 = term.val v (b,as) → term.val v t = term.val (v⟨n↦sgm v b as n⟩) (subst n (rhs n b as) t) := begin intros h1 h2, simp_omega [subst], rw ← rhs_correct _ h1 h2, cases t with b' as', simp_omega, have h3 : coeffs.val (v⟨n↦sgm v b as n⟩) (as'{n↦0}) = coeffs.val_except n v as', { rw [← coeffs.val_except_add_eq n, list.get_set, zero_mul, add_zero, coeffs.val_except_update_set] }, rw [h3, ← coeffs.val_except_add_eq n], ring end @[derive has_reflect] inductive ee : Type | drop : ee | nondiv : int → ee | factor : int → ee | neg : ee | reduce : nat → ee | cancel : nat → ee namespace ee def repr : ee → string | drop := "↓" | (nondiv i) := i.repr ++ "∤" | (factor i) := "/" ++ i.repr | neg := "-" | (reduce n) := "≻" ++ n.repr | (cancel n) := "+" ++ n.repr instance has_repr : has_repr ee := ⟨repr⟩ meta instance has_to_format : has_to_format ee := ⟨λ x, x.repr⟩ end ee def conc : list ee → clause → clause | [] ([], les) := ([],les) | [] ((_::_), les) := ([],[]) | (_::_) ([], les) := ([],[]) | (ee.drop::es) ((eq::eqs), les) := conc es (eqs, les) | (ee.neg::es) ((eq::eqs), les) := conc es ((eq.neg::eqs), les) | (ee.nondiv i::es) ((b,as)::eqs, les) := if ¬(i ∣ b) ∧ (∀ x ∈ as, i ∣ x) then ([],[⟨-1,[]⟩]) else ([],[]) | (ee.factor i::es) ((b,as)::eqs, les) := if (i ∣ b) ∧ (∀ x ∈ as, i ∣ x) then conc es ((term.div i (b,as)::eqs), les) else ([],[]) | (ee.reduce n::es) ((b,as)::eqs, les) := if 0 < as.get n then let eq' := coeffs_reduce n b as in let r := rhs n b as in let eqs' := eqs.map (subst n r) in let les' := les.map (subst n r) in conc es ((eq'::eqs'), les') else ([],[]) | (ee.cancel m::es) ((eq::eqs), les) := conc es ((eqs.map (_root_.cancel m eq)), (les.map (_root_.cancel m eq))) open tactic lemma sat_empty : clause.sat ([],[]) := ⟨λ _,0, ⟨dec_trivial, dec_trivial⟩⟩ lemma sat_conc : ∀ {es} {c : clause}, c.sat → (conc es c).sat | [] ([], les) h := h | (e::_) ([], les) h := begin cases e; simp only [conc]; apply sat_empty end | [] ((_::_), les) h := sat_empty | (ee.drop::es) ((eq::eqs), les) h := begin apply (@sat_conc es _ _), apply clause.sat_of_weaker _ h, constructor, apply list.subset_cons, apply list.subset.refl end | (ee.neg::es) ((eq::eqs), les) h1 := begin simp only [conc], apply sat_conc, cases h1 with v h1, existsi v, cases h1 with hl hr, apply and.intro _ hr, rw list.forall_mem_cons at *, apply and.intro _ hl.right, rw term.val_neg, rw ← hl.left, refl end | (ee.nondiv i::es) ((b,as)::eqs, les) h1 := begin simp only [conc], by_cases h2 : (¬i ∣ b ∧ ∀ (x : ℤ), x ∈ as → i ∣ x), { exfalso, cases h1 with v h1, have h3 : 0 = b + coeffs.val v as := h1.left _ (or.inl rfl), have h4 : i ∣ coeffs.val v as := coeffs.dvd_val h2.right, have h5 : i ∣ b + coeffs.val v as := by { rw ← h3, apply dvd_zero }, rw ← dvd_add_iff_left h4 at h5, apply h2.left h5 }, { rw if_neg h2, apply sat_empty } end | (ee.factor i::es) ((b,as)::eqs, les) h1 := begin simp only [conc], by_cases h2 : (i ∣ b) ∧ (∀ x ∈ as, i ∣ x), { rw if_pos h2, apply sat_conc, cases h1 with v h1, existsi v, cases h1 with h3 h4, apply and.intro _ h4, rw list.forall_mem_cons at *, cases h3 with h5 h6, apply and.intro _ h6, rw [term.val_div h2.left h2.right, ← h5, int.zero_div] }, { rw if_neg h2, apply sat_empty } end | (ee.reduce n::es) ((b,as)::eqs, les) h1 := begin simp only [conc], by_cases h2 : 0 < list.get n as, tactic.rotate 1, { rw if_neg h2, apply sat_empty }, rw if_pos h2, apply sat_conc, cases h1 with v h1, existsi v⟨n ↦ sgm v b as n⟩, cases h1 with h1 h3, rw list.forall_mem_cons at h1, cases h1 with h4 h5, constructor, apply list.forall_mem_cons_of, apply coeffs_reduce_correct h2 h4, { intros x h6, rw list.mem_map at h6, cases h6 with t h6, cases h6 with h6 h7, rw [← h7, ← subst_correct h2 h4], apply h5 _ h6 }, { intros x h6, rw list.mem_map at h6, cases h6 with t h6, cases h6 with h6 h7, rw [← h7, ← subst_correct h2 h4], apply h3 _ h6 } end | (ee.cancel m::es) ((eq::eqs), les) h1 := begin simp only [conc], apply sat_conc, cases h1 with v h1, existsi v, cases h1 with h1 h2, rw list.forall_mem_cons at h1, cases h1 with h1 h3, constructor; intros t h4; rw list.mem_map at h4; rcases h4 with ⟨s,h4,h5⟩; rw ← h5; simp only [term.val_add, term.val_mul, cancel]; rw [← h1, mul_zero, zero_add], { apply h3 _ h4 }, { apply h2 _ h4} end lemma unsat_of_unsat_conc (ee c) : (conc ee c).unsat → c.unsat := begin intros h1 h2, apply h1, apply sat_conc h2 end
64a07b4781b3eb0a4dc014f460101a8509add909
947b78d97130d56365ae2ec264df196ce769371a
/stage0/src/Lean/Meta/Tactic/Util.lean
6b19ceda3771b534e63c3b0d3a647752afe71347
[ "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
2,087
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Basic import Lean.Meta.AppBuilder import Lean.Meta.LevelDefEq namespace Lean namespace Meta /-- Aka user name -/ def getMVarTag (mvarId : MVarId) : MetaM Name := do mvarDecl ← getMVarDecl mvarId; pure mvarDecl.userName def setMVarTag (mvarId : MVarId) (tag : Name) : MetaM Unit := do modify $ fun s => { s with mctx := s.mctx.setMVarUserName mvarId tag } def appendTag (tag : Name) (suffix : Name) : Name := let view := extractMacroScopes tag; let view := { view with name := view.name ++ suffix.eraseMacroScopes }; view.review def appendTagSuffix (mvarId : MVarId) (suffix : Name) : MetaM Unit := do tag ← getMVarTag mvarId; setMVarTag mvarId (appendTag tag suffix) def mkFreshExprSyntheticOpaqueMVar (type : Expr) (userName : Name := Name.anonymous) : MetaM Expr := mkFreshExprMVar type MetavarKind.syntheticOpaque userName def throwTacticEx {α} (tacticName : Name) (mvarId : MVarId) (msg : MessageData) (ref := Syntax.missing) : MetaM α := throwError $ "tactic '" ++ tacticName ++ "' failed, " ++ msg ++ Format.line ++ MessageData.ofGoal mvarId def checkNotAssigned (mvarId : MVarId) (tacticName : Name) : MetaM Unit := whenM (isExprMVarAssigned mvarId) $ throwTacticEx tacticName mvarId "metavariable has already been assigned" def getMVarType (mvarId : MVarId) : MetaM Expr := do mvarDecl ← getMVarDecl mvarId; pure mvarDecl.type def ppGoal (mvarId : MVarId) : MetaM Format := do env ← getEnv; mctx ← getMCtx; opts ← getOptions; liftIO $ Lean.ppGoal { env := env, mctx := mctx, opts := opts } mvarId @[init] private def regTraceClasses : IO Unit := registerTraceClass `Meta.Tactic /-- Assign `mvarId` to `sorryAx` -/ def admit (mvarId : MVarId) (synthetic := true) : MetaM Unit := withMVarContext mvarId $ do checkNotAssigned mvarId `admit; mvarType ← getMVarType mvarId; val ← mkSorry mvarType synthetic; assignExprMVar mvarId val; pure () end Meta end Lean
7fae3b5e5d06350af346498162fb0b8cfbb8e533
75c54c8946bb4203e0aaf196f918424a17b0de99
/old/language_term_ln2.lean
a52c131f2352d9279c28ab17bdc81565f10c48e6
[ "Apache-2.0" ]
permissive
urkud/flypitch
261e2a45f1038130178575406df8aea78255ba77
2250f5eda14b6ef9fc3e4e1f4a9ac4005634de5c
refs/heads/master
1,653,266,469,246
1,577,819,679,000
1,577,819,679,000
259,862,235
1
0
Apache-2.0
1,588,147,244,000
1,588,147,244,000
null
UTF-8
Lean
false
false
16,847
lean
/- Another implementation of locally nameless representation, more faithful to Chaugeuraud's specification. Thank you to Floris for the code underlying preterms and preformulas. ---Jesse 2018-10-15T19:59:39 -/ structure Language := (relations : Π n : nat, Type) (functions : Π n : nat, Type) section parameter L : Language /-- preterm n is a partially applied term. If applied to n terms, it becomes a term. --/ inductive preterm : ℕ → Type | bvar : ℕ → preterm 0 | fvar : ℕ → preterm 0 -- this should be fine; later we can pretty-print free variables with the indices as the underscores. | func : ∀ {n : nat}, L.functions n → preterm n | apply : ∀ {n : nat}, preterm (n + 1) → preterm 0 → preterm n open preterm def term := preterm 0 /-- Given a preterm, return a list of free variables which occur in it--/ def free_vars_preterm : Π n : ℕ, preterm n → list ℕ | _ (bvar L k) := [] | _ (fvar L s) := [s] | _ (@func L _ f) := [] | _ (@apply L n t1 t2) := (free_vars_preterm (n+1) t1 ∪ free_vars_preterm 0 t2) /-- Given a preterm, return a list of bound variables which occur in it--/ def bound_vars_preterm : Π n : ℕ, preterm n → list ℕ | _ (bvar L k) := [k] | _ (fvar L s) := [] | _ (@func L _ f) := [] | _ (@apply L n t1 t2) := (free_vars_preterm (n+1) t1 ∪ free_vars_preterm 0 t2) def free_vars_term : term → list ℕ := free_vars_preterm 0 def bound_vars_term : term → list ℕ := bound_vars_preterm 0 -- lemma free_var_preterm_coercionl (n : ℕ) (t1 : preterm (n+1)) (t2 : term) : {x : ℕ // x ∈ (free_vars_preterm (n+1) t1)} → {x : ℕ // x ∈ (free_vars_preterm n (apply t1 t2))} := sorry -- def substitute_preterm : Π n : ℕ, Π (t : preterm n), term → {x : ℕ // x ∈ (free_vars_preterm n t)} → preterm n -- | _ (bvar L k) t x := (bvar k) -- | _ (fvar L s) t x := sorry -- | _ (@func L _ f) t x := (func f) -- | _ (@apply L n t1 t2) t x := sorry end section parameter L : Language /- preformula n is a partially applied formula. if applied to n terms, it becomes a formula -/ inductive preformula : ℕ → Type | true : preformula 0 | false : preformula 0 | equal : (term L) → (term L) → preformula 0 | rel : ∀ {n : nat}, L.relations n → preformula n | apprel : ∀ {n : nat}, preformula (n + 1) → (term L) → preformula n | imp : preformula 0 → preformula 0 → preformula 0 | all : preformula 0 → preformula 0 open preformula def formula := preformula 0 def free_vars_preformula : Π n : ℕ, preformula n → list ℕ | _ (true L) := [] | _ (false L) := [] | _ (equal t1 t2) := free_vars_term L t1 ∪ free_vars_term L t2 | _ (@rel L n R) := [] | _ (@apprel L n ψ t) := free_vars_preformula _ ψ ∪ free_vars_term L t | _ (imp ϕ ψ) := free_vars_preformula _ ϕ ∪ free_vars_preformula _ ψ | _ (all ψ) := free_vars_preformula _ ψ def bound_vars_preformula : Π n : ℕ, preformula n → list ℕ | _ (true L) := [] | _ (false L) := [] | _ (equal t1 t2) := bound_vars_term L t1 ∪ bound_vars_term L t2 | _ (@rel L n R) := [] | _ (@apprel L n ψ t) := bound_vars_preformula _ ψ ∪ bound_vars_term L t | _ (imp ϕ ψ) := bound_vars_preformula _ ϕ ∪ bound_vars_preformula _ ψ | _ (all ψ) := bound_vars_preformula _ ψ def free_vars_formula : formula → list ℕ := free_vars_preformula 0 def bound_vars_formula : formula → list ℕ := bound_vars_preformula 0 -- def fresh_var : list ℕ → ℕ := λ xs, xs.foldr max 0 /- OPERATIONS ON LOCALLY NAMELESS FORMULAS -/ /- Variable opening -/ -- I quote: -- With the named representation, an abstraction takes the form “λx. t”. To investigate -- the body of this abstraction, we simply works with the term t. With the locally nameless -- representation, an abstraction has the form “abs t” and it is our responsibility to provide -- a fresh name x to open the abstraction. The result of applying the variable opening oper- -- ation to t and x is a term, written t x , that describes the body of the abstraction “abs t”. -- More precisely, given an abstraction “abs t” and a variable name x that does not appear -- in t, the term t x is a copy of t in which all the bound variables referring to the outer -- abstraction of “abs t” have been replaced with the free variable “fvar x”. For example, -- consider the abstraction “abs (app (abs (app (bvar 0) (bvar 1))) (bvar 0))”; the opening of -- its body with the name x is the term “app (abs (app (bvar 0) (fvar x)))(fvar x) ”. -- The implementation of variable opening needs to traverse a term recursively, and -- find all the leaves of the form “bvar i” whose index i is equal to the number of abstrac- -- tions enclosing that variable. Variable opening is thus defined in terms of a recursive -- function, written “{k → x} t”, that keeps track of the number k of abstractions that -- have been passed by. Initially, the value of k is 0, so variable opening is defined as: -- t x ≡ {0 → x} t -- The value of k is then incremented each time an abstraction is traversed. When reaching -- a bound variable with index i, the value of i is compared against the current value of k. -- If i is equal to k, then the bound variable is replaced with the free variable named x, -- otherwise it is unchanged. Note that free variables already occurring in the term are -- never affected by a variable opening operation. -- We will need this to perform generalization of constants. -- def var_open_term : ℕ → term L → term L -- | k (preterm.bvar _ i) := if (i = k) -- then preterm.fvar _ (fresh_var (free_vars_term _ (preterm.bvar L i))) -- else (preterm.bvar _ i) -- | k (preterm.fvar _ y) := preterm.fvar _ y -- | k (preterm.func f) := preterm.func f -- | k (preterm.apply (t1 : preterm L 1) (t2 : preterm L 0) := preterm.apply (var_open_term k t1) (var_open_term k t2) --- funnily enough, if you try to do this for *just* terms, like above, the equation compiler complains about well-founded recursion. But as you see below, there's *no* problem if we do it for all preterms def fresh_var : list ℕ → ℕ := λ xs, (xs.foldr max 0) + 1 def var_open_preterm : Π n : ℕ, ℕ → preterm L n → preterm L n -- first ℕ is the preterm level, second is the bound index we're opening | 0 k (preterm.bvar L i) := if (i = k) then preterm.fvar _ (fresh_var (free_vars_term _ (preterm.bvar L i))) else (preterm.bvar _ i) | 0 k (preterm.fvar L y) := preterm.fvar _ y | n k (preterm.func f) := preterm.func f | n k (preterm.apply (t1 : preterm L (n+1)) (t2 : preterm L 0)) := preterm.apply (var_open_preterm (n+1) k t1) (var_open_preterm 0 k t2) /- opens the outermost abstraction of an n-preformula with a free variable fvar k-/ def var_open_preformula : Π (n : ℕ), ℕ → preformula n → preformula n | 0 k (true L) := true | 0 k (false L) := false | 0 k (equal t1 t2) := equal (var_open_preterm _ k t1) (var_open_preterm _ k t2) | 0 k (imp ϕ ψ) := imp (var_open_preformula 0 k ϕ) (var_open_preformula 0 k ψ) | 0 0 (all ϕ) := var_open_preformula 0 1 ϕ -- careful! we only strip the quantifier and increase the count when we hit the _first_ quantifier, after that, only increase the count | 0 (n+1) (all ϕ) := (all (var_open_preformula 0 (n+1) ϕ)) | n k (rel R) := (rel R) | n k (apprel (ψ : preformula (n+1)) t) := apprel (var_open_preformula (n+1) k ψ) (var_open_preterm 0 k t) /-Variable closing-/ -- I quote: Symmetrically to variable opening, we may want to build an abstraction given its -- body. With the named representation, we consider a term t and a name x, and we -- simply build the abstraction “λx. t”. All the variables named x are abstracted, except -- those that already appear below an abstraction named x. With the locally nameless -- representation, we consider a term t and a name x to be abstracted in t, and we -- build a term, written \x t, by applying the variable closing operation to t and x. All -- the variables named x occurring in t are abstracted, without exception (indeed, no -- shadowing is possible with the locally nameless syntax). The abstraction may then be -- constructed as “abs ( \x t)”. More precisely, the term \x t is a copy of t in which all the -- free variables named x have been replaced with a bound variable. The indices of those -- variables are chosen in such a way that all the bound variables introduced are pointing -- towards the outer abstraction of “abs ( \x t)”. -- The implementation of variable closing follows a pattern similar to the implemen- -- tation of variable opening. Its implementation is based on a recursive function, written -- “{k ← x} t”, that keeps track of the number k of abstractions that have been passed by. -- Again, the value of k is 0 initially and it is incremented at each abstraction. Variable -- closing is defined as follows: -- \x -- t ≡ {0 ← x} t -- When the recursive function reaches a free variable with name y, it compares the name -- y with the name x. If the two names match, then the free variable y is replaced with -- a bound variable of index k, otherwise it is left unchanged. Note that bound variables -- already occurring in the term are never affected by variable closing. def var_close_preterm : Π n : ℕ, ℕ → preterm L n → preterm L n -- first ℕ is the preterm level, second is the open index we're closing | 0 k (preterm.fvar L i) := if (i = k) then preterm.bvar _ k else (preterm.fvar _ i) | 0 k (preterm.bvar L y) := preterm.fvar _ y | n k (preterm.func f) := preterm.func f | n k (preterm.apply (t1 : preterm L (n+1)) (t2 : preterm L 0)) := preterm.apply (var_close_preterm (n+1) k t1) (var_close_preterm 0 k t2) /- wraps an abstraction around an n-preformula, binding a specified free variable-/ def var_close_preformula : Π (n : ℕ), ℕ → preformula n → preformula n | 0 k (true L) := true | 0 k (false L) := false | 0 k (equal t1 t2) := equal (var_close_preterm _ k t1) (var_close_preterm _ k t2) | 0 k (imp ϕ ψ) := imp (var_close_preformula 0 k ϕ) (var_close_preformula 0 k ψ) | 0 k (all ϕ) := all (var_close_preformula 0 (k+1) ϕ) | n k (rel R) := (rel R) | n k (apprel (ψ : preformula (n+1)) t) := apprel (var_close_preformula (n+1) k ψ) (var_close_preterm 0 k t) /-***********************************-/ /- LOCALLY CLOSED TERMS -/ -- unfortunately, we need a well-formedness predicate. Again, to quote Chargueraud: -- As suggested in the previous section, the locally nameless syntax contains objects -- that do not correspond to any valid λ-term. For instance, “abs 3” is such an improper -- syntactic object, since the bound variable with index 3 does not refer to any abstraction -- inside the term. We need to ensure that terms do not contain any such dangling bound -- variable. We say of well-formed terms that they are locally closed. The purpose of this -- section is to give a formal characterization of the set of locally closed terms. -- Two approaches are possible. The first one consists in investigating the term recur- -- sively, opening every abstraction with a name, and checking that no bound variable is -- ever reached. The second possible approach relies on an analysis of bound variables, -- for checking that each bound variable has an index smaller than the number of enclos- -- ing abstractions. We start by describing the first approach, which is the most helpful -- for formally reasoning on terms represented in locally nameless style, and study the -- approach based on indices afterwards. -- The local closure predicate, written “lc t”, characterizes terms that are locally -- closed. It is defined using three inductive rules. The first one states that any free -- variable is locally closed. The second one states that an application is locally closed if -- its two branches are locally closed. The third and last one states that an abstraction -- is locally closed if its body opened with some name is itself locally closed. Notice that -- a bound variable on its own is never locally closed. -- In practice, we use a slightly different rule to deal with abstractions. In the rule -- lc-var’, the premise lc (t x ) is required to hold for one single name x. Instead, we are -- going to require lc (t x ) to hold for cofinitely-many names x. More precisely, we consider -- that an abstraction “abs t” is locally closed if there exists a finite set of names L such -- that, for any name x not in L, the term t x is locally closed. -- The motivation for the cofinite quantification will be discussed in details later on (§4.2) -- Arthur's talking crazy. I'm going with the counting-of-bound-variables. end variable L : Language def locally_closed_preterm : Π n : ℕ, ℕ → preterm L n → Prop | 0 k (preterm.bvar L i) := nat.lt i k | 0 k (preterm.fvar L i) := true | n k (preterm.func f) := true | n k (preterm.apply t1 t2) := (locally_closed_preterm (n+1) k t1) ∧ (locally_closed_preterm 0 k t2) def locally_closed_preformula : Π n : ℕ, ℕ → preformula L n → Prop | 0 k (preformula.true L) := true | 0 k (preformula.false L) := tt | 0 k (preformula.equal t1 t2) := (locally_closed_preterm L 0 k t1) ∧ (locally_closed_preterm L 0 k t2) | 0 k (preformula.imp ψ ϕ) := (locally_closed_preformula 0 k ψ) ∧ (locally_closed_preformula 0 k ϕ) | 0 k (preformula.all ψ) := (locally_closed_preformula 0 (k+1) ψ) | n k (preformula.rel R) := tt | n k (preformula.apprel ψ t) := (locally_closed_preformula (n+1) k ψ) ∧ (locally_closed_preterm L 0 k t) -- NOTE: "locally closed" means the same as "well-formed". Therefore, we introduce the following aliases /-- A well-formed term, by itself, has no bound variables --/ def well_formed_term : term L → Prop := locally_closed_preterm L 0 0 /-- A well-formed formula is a locally closed preformula. Remember the second nat parameter counts the number of quantifiers we have passed.--/ def well_formed_formula : formula L → Prop := locally_closed_preformula L 0 0 /-***********************************-/ /-FREE VARIABLES AND SUBSTITUTION-/ -- Note that we can define the substitution t/x for x not even occuring in a term or formula. In that case, the substitution operation does nothing. If we have to prove this later, it shouldn't be hard. /-- Given an n-preterm, a term t, and a fvar x, return that n-preterm with all instances of x replaced with t--/ def substitute_preterm : Π n : ℕ, preterm L n → term L → ℕ → preterm L n | 0 (preterm.bvar L i) t k := preterm.bvar L i | 0 (preterm.fvar _ i) t k := if i = k then t else (preterm.fvar _ i) | n (preterm.func f) t k := (preterm.func f) | n (preterm.apply t1 t2) t k := preterm.apply (substitute_preterm (n+1) t1 t k) (substitute_preterm 0 t2 t k) /-- Given an n-preformula, a term t, and a fvar x, return that n-preterm with all instances of x replaced with t--/ def substitute_preformula : Π n : ℕ, preformula L n → term L → ℕ → preformula L n | _ (preformula.true L) _ _ := preformula.true L | _ (preformula.false L) _ _ := preformula.false L | _ (preformula.equal t1 t2) t k := preformula.equal (substitute_preterm L 0 t1 t k) (substitute_preterm L 0 t2 t k) | _ (preformula.rel R) t k := preformula.rel R | _ (preformula.apprel ϕ s) t k := preformula.apprel (substitute_preformula _ ϕ t k) (substitute_preterm L _ s t k) | _ (preformula.imp ϕ ψ) t k := preformula.imp (substitute_preformula _ ϕ t k) (substitute_preformula _ ψ t k) | _ (preformula.all ψ) t k := preformula.all (substitute_preformula _ ψ t k) /-***********************************-/ /- ignore the rest of this file-/ -- def raise_depth_formula : ∀ {l}, preformula l → ℕ → ℕ → preformula l -- | _ (true L) n m := true -- | _ (false L) n m := false -- | _ (equal t1 t2) n m := equal (raise_depth_term t1 n m) (raise_depth_term t2 n m) -- | _ (rel R) n m := rel R -- | _ (apprel f t) n m := apprel (raise_depth_formula f n m) (raise_depth_term t n m) -- | _ (imp f1 f2) n m := imp (raise_depth_formula f1 n m) (raise_depth_formula f2 n m) -- | _ (all f) n m := all (raise_depth_formula f n (m+1)) -- def substitute_formula : ∀ {l}, preformula l → (term L) → ℕ → preformula l -- | _ (true L) s n := true -- | _ (false L) s n := false -- | _ (equal t1 t2) s n := equal (substitute_term L t1 s n) (substitute_term L t2 s n) -- | _ (rel R) s n := rel R -- | _ (apprel f t) s n := apprel (substitute_formula f s n) (substitute_term t s n) -- | _ (imp f1 f2) s n := imp (substitute_formula f1 s n) (substitute_formula f2 s n) -- | _ (all f) s n := all (substitute_formula f s (n+1)) -- def substitute_preformula : Π n : ℕ, Π (ψ : preformula n), term → {x : ℕ // x ∈ (free_vars_preformula _ ψ)} → preformula n -- | _ (true L) t x := true -- | _ (false L) t x := false -- | _ (equal t1 t2) := equal (substitute_preformula _ _ _ _ t1) (substitute_preformula _ _ _ _ t2)
ead006d74ffed7041cbc87927b8da5efa951af61
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/13_More_Tactics.org.1.lean
71d65114dfbdf4cbfa27be4ffab1e84fddbca922
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
515
lean
import standard import data.nat open nat theorem zero_add (x : ℕ) : 0 + x = x := begin induction x with x ih, {exact rfl}, rewrite [add_succ, ih] end theorem succ_add (x y : ℕ) : succ x + y = succ (x + y) := begin induction y with y ih, {exact rfl}, rewrite [add_succ, ih] end theorem add.comm (x y : ℕ) : x + y = y + x := begin induction x with x ih, {show 0 + y = y + 0, by rewrite zero_add}, show succ x + y = y + succ x, begin induction y with y ihy, {rewrite zero_add}, rewrite [succ_add, ih] end end
4d04a911e52f66a6c22cb649f6e30d45497075c6
5e42295de7f5bcdf224b94603a8ec29b17c2d367
/control.lean
fce7aa073324d7b9a50aa6acc4080a1d3e93d3eb
[]
no_license
pnmadelaine/lean_polya
9369e0d87dce773f91383bb58ac6fde0a00a1a40
1c62b0b3fa71044b0225ce28030627d251b08ebc
refs/heads/master
1,590,161,172,243
1,515,010,019,000
1,515,010,019,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,968
lean
import .blackboard .proof_reconstruction .sum_form .prod_form data.hash_map .normalizer3 open polya tactic meta def expr_to_ineq : expr → tactic (expr × expr × ineq) | `(%%x ≤ (%%c : ℚ)*%%y) := do c' ← eval_expr rat c, return $ (x, y, ineq.of_comp_and_slope comp.le (slope.some c')) | `(%%x < (%%c : ℚ)*%%y) := do c' ← eval_expr rat c, return $ (x, y, ineq.of_comp_and_slope comp.lt (slope.some c')) | `(%%x ≥ (%%c : ℚ)*%%y) := do c' ← eval_expr rat c, return $ (x, y, ineq.of_comp_and_slope comp.ge (slope.some c')) | `(%%x > (%%c : ℚ)*%%y) := do c' ← eval_expr rat c, return $ (x, y, ineq.of_comp_and_slope comp.gt (slope.some c')) | _ := failed meta def expr_to_eq : expr → tactic (expr × expr × ℚ) | `(%%x = (%%c : ℚ)*%%y) := do c' ← eval_expr rat c, return $ (x, y, c') | _ := failed meta def expr_to_diseq : expr → tactic (expr × expr × ℚ) | `(%%x ≠ (%%c : ℚ)*%%y) := do c' ← eval_expr rat c, return (x, y, c') | _ := failed -- for efficiency??? meta def expr_to_sign_aux : expr → tactic (expr × gen_comp) | `(@eq ℚ (has_zero.zero ℚ) %%x) := return (x, gen_comp.eq) | `((has_zero.zero ℚ) > %%x) := return (x, gen_comp.lt) | `((has_zero.zero ℚ) < %%x) := return (x, gen_comp.gt) | `((has_zero.zero ℚ) ≥ %%x) := return (x, gen_comp.le) | `((has_zero.zero ℚ) ≤ %%x) := return (x, gen_comp.ge) | `((has_zero.zero ℚ) ≠ %%x) := return (x, gen_comp.ne) | _ := failed meta def expr_to_sign : expr → tactic (expr × gen_comp) | `(@eq ℚ %%x (has_zero.zero ℚ)) := return (x, gen_comp.eq) | `(%%x > (has_zero.zero ℚ)) := return (x, gen_comp.gt) | `(%%x < (has_zero.zero ℚ)) := return (x, gen_comp.lt) | `(%%x ≥ (has_zero.zero ℚ)) := return (x, gen_comp.ge) | `(%%x ≤ (has_zero.zero ℚ)) := return (x, gen_comp.le) | `(%%x ≠ (has_zero.zero ℚ)) := return (x, gen_comp.ne) | a := expr_to_sign_aux a /-meta def add_comp_to_blackboard (e : expr) (b : blackboard) : tactic blackboard := (do (x, y, ie1) ← expr_to_ineq e, id ← return $ ineq_data.mk ie1 (ineq_proof.hyp x y _ e), -- trace "tac_add_ineq", tac_add_ineq b id) -- return (add_ineq id b).2) <|> (do (x, y, ie1) ← expr_to_eq e, id ← return $ eq_data.mk ie1 (eq_proof.hyp x y _ e), -- trace "tac_add_eq", tac_add_eq b id) --return (add_eq id b).2) <|> (do (x, c) ← expr_to_sign e, sd ← return $ sign_data.mk c (sign_proof.hyp x _ e), -- trace "calling tac-add-sign", bb ← tac_add_sign b sd, trace "tac_add_sign done", return bb) <|> fail "add_comp_to_blackboard failed"-/ meta def coeff_of_expr (ex : expr) : tactic (option ℚ × expr) := match ex with | `(%%c * %%e) := if is_num c then do q ← eval_expr ℚ c, return (some q, e) else return (none, ex) | _ := return (none, ex) end meta def add_proof_to_blackboard (b : blackboard) (e : expr) : tactic blackboard := --infer_type e >>= trace >> do e ← canonize_hyp e, tp ← infer_type e, trace e, trace tp, (do (x, y, ie1) ← expr_to_ineq tp, -- trace x, trace y, trace ie1, id ← return $ ineq_data.mk ie1 (ineq_proof.hyp x y _ e), --return (add_ineq id b).2) tac_add_ineq b id) <|> (do (x, y, ie1) ← expr_to_eq tp, id ← return $ eq_data.mk ie1 (eq_proof.hyp x y _ e), --return (add_eq id b).2) tac_add_eq b id) <|> (do (x, c) ← expr_to_sign tp, cf ← coeff_of_expr x, match cf with | (none, e') := do sd ← return $ sign_data.mk c (sign_proof.hyp x _ e), -- trace "calling tac-add-sign", bb ← tac_add_sign b sd, -- trace "tac_add_sign done", return bb | (some q, e') := do trace q, trace e', sd ← return $ trace_val $ sign_data.mk (if q > 0 then c else c.reverse) (sign_proof.scaled_hyp e' _ e q), tac_add_sign b sd end) <|> (do (x, y, ie1) ← expr_to_diseq tp, sd ← return $ diseq_data.mk ie1 (diseq_proof.hyp x y _ e), tac_add_diseq b sd) <|> trace "failed" >> trace e >> fail "add_comp_to_blackboard failed" meta def add_proofs_to_blackboard (b : blackboard) (l : list expr) : tactic blackboard := monad.foldl add_proof_to_blackboard b l meta structure module_op (α : Type) := (a : α) (op : α → polya_state α) meta def module_op.update {α} : module_op α → polya_state (module_op α) | ⟨a, op⟩ := do a' ← op a, return ⟨a', op⟩ meta structure polya_bundle := (modules : hash_map ℕ (λ _, sigma module_op)) (num_modules : ℕ) (bb : blackboard) meta def polya_bundle.set_changed (b : bool) : polya_bundle → polya_bundle | ⟨modules, n, bb⟩ := ⟨modules, n, bb.set_changed b⟩ meta def polya_bundle.is_changed (pb : polya_bundle) : bool := pb.bb.is_changed meta def polya_bundle.contr_found (pb : polya_bundle) : bool := pb.bb.contr_found meta def polya_bundle.set_blackboard (pb : polya_bundle) (bb' : blackboard) : polya_bundle := {pb with bb := bb'} meta def polya_bundle.update_ith (i : ℕ) : polya_bundle → polya_bundle | ⟨modules, n, bb⟩ := match modules.find i with | some ⟨α, a, op⟩ := let (a', bb') := op a bb, modules' := modules.insert i ⟨α, a', op⟩ in ⟨modules', n, bb'⟩ | none := ⟨modules, n, bb⟩ end meta def polya_bundle.one_cycle (bundle : polya_bundle) : polya_bundle := (list.upto bundle.num_modules).reverse.foldl (λ pb k, pb.update_ith k) bundle meta def polya_bundle.cycle : ℕ → polya_bundle → (ℕ × polya_bundle) | n pb := let pb' := pb.set_changed ff, pb' := pb'.one_cycle, ch := pb'.is_changed, cont := pb'.contr_found in if ch && bnot cont then polya_bundle.cycle (trace_val (n+1)) pb' else ((n+1), pb') meta def add_module : module_op (rb_set sum_form_comp_data) := { a := mk_rb_set, op := @sum_form.add_new_ineqs } meta def mul_module : module_op (rb_set prod_form_comp_data) := { a := mk_rb_set, op := @prod_form.add_new_ineqs } meta def polya_bundle.default : polya_bundle := { modules := let m' : hash_map ℕ (λ _, sigma module_op) := ((mk_hash_map id).insert 0 ⟨_, add_module⟩) in m'.insert 1 ⟨_, mul_module⟩, -- elab issues num_modules := 2, bb := blackboard.mk_empty } lemma rat_one_gt_zero : (1 : ℚ) > 0 := zero_lt_one meta def polya_on_hyps (hys : list name) (rct : bool := tt) : tactic unit := do exps ← hys.mmap get_local, bb ← add_proof_to_blackboard blackboard.mk_empty `(rat_one_gt_zero), bb ← add_proofs_to_blackboard bb exps, let pb := polya_bundle.default.set_blackboard bb, let (n, pb) := pb.cycle 0, trace ("number of cycles:", n), trace ("contr found", pb.contr_found), if bnot pb.contr_found then /-bb.trace >>-/ fail "polya failed, no contradiction found" else if rct then pb.bb.contr.reconstruct >>= apply else skip private meta def try_add_hyp (h : expr) (bb : blackboard) : tactic blackboard := add_proof_to_blackboard bb h <|> return bb private meta def try_add_hyps : list expr → blackboard → tactic blackboard | [] bb := return bb | (h::t) bb := do b ← try_add_hyp h bb, try_add_hyps t b meta def polya_on_all_hyps (rct : bool := tt) : tactic unit := do hyps ← local_context, bb ← add_proof_to_blackboard blackboard.mk_empty `(rat_one_gt_zero), bb ← try_add_hyps hyps bb, bb.trace_exprs, let pb := polya_bundle.default.set_blackboard bb, let (n, pb) := pb.cycle 0, trace ("number of cycles:", n), trace ("contr found", pb.contr_found), if bnot pb.contr_found then /-bb.trace >>-/ fail "polya failed, no contradiction found" else if rct then pb.bb.contr.reconstruct >>= apply else skip /-meta def cycle_ops : ℕ → list (Σ α, module_op α) → polya_state ℕ | n ops := do set_changed ff, ops' ← ops.mmap (λ m, do m' ← m.2.update, return $ sigma.mk m.1 m'), ch ← is_changed, cntr ← contr_found, if ch && bnot cntr then cycle_ops (n+1) ops' else return (n+1) meta def polya_on_hyps (hys : list name) : tactic unit := do exps ← hys.mmap get_local, bb ← add_proofs_to_blackboard blackboard.mk_empty exps, bb.trace_expr_pairs, (n, bb) ← return $ cycle_ops 0 [add_new_ineqs, prod_form.add_new_ineqs] bb, trace ("number of cycles:", n), trace ("contr found", bb.contr_found), pf ← bb.contr.reconstruct, apply pf-/ section open tactic interactive interactive.types lean.parser --meta def tactic.interactive.add_comp_to_blackboard' (e : parse texpr) (b : blackboard) : tactic blackboard := --do e' ← i_to_expr e, add_comp_to_blackboard e' b meta def tactic.interactive.polya (ns : parse (many ident)) : tactic unit := polya_on_hyps ns meta def tactic.interactive.polya_l (ns : parse (many ident)) : tactic unit := polya_on_hyps ns ff meta def tactic.interactive.polya_all (rct : parse (optional (tk "!"))) : tactic unit := polya_on_all_hyps rct.is_some end
1f316fbfcbddccd516084e2b4c8894f207ae2640
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/examples/targets/src/c.lean
7148b3c48f06f7db56e825a25c79fdaf8fe3c225
[ "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
40
lean
def main : IO PUnit := IO.println "c"
a04818985247a283d825ea67859a2890665ed6e0
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/apply4.lean
4e6439af8d6cfbb14ac4a90c34c0cfa3726321ba
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
1,081
lean
open tactic bool universe variables u constant foo {A : Type u} [inhabited A] (a b : A) : a = default → a = b example (a b : nat) : a = 0 → a = b := by do intro `H, apply (expr.const `foo [level.of_nat 0]), trace_state, assumption definition ex : inhabited (nat × nat × bool) := by apply_instance set_option pp.all true #print ex set_option pp.all false example (a b : nat) : a = 0 → a = b := by do intro `H, apply_core (expr.const `foo [level.of_nat 0]) {approx := ff, new_goals := new_goals.all, instances := ff }, trace_state, a ← get_local `a, trace_state, mk_app `inhabited.mk [a] >>= exact, trace "--------", trace_state, reflexivity #print "----------------" set_option pp.all true example (a b : nat) : a = 0 → a = b := by do intro `H, foo ← mk_const `foo, trace foo, apply foo, trace_state, assumption example (a b : nat) : a = 0 → a = b := by do `[intro], apply_core (expr.const `foo [level.of_nat 0]) {approx := ff, new_goals := new_goals.all, instances := ff}, `[exact inhabited.mk a], reflexivity
72d91cd4f47ecda07ba09105051f17a7914f0a35
f5f7e6fae601a5fe3cac7cc3ed353ed781d62419
/src/data/list/defs.lean
5545a4d90120e9998835ff87e1f95990e40fbaf1
[ "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
17,349
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro Extra definitions on lists. -/ import data.option.defs logic.basic logic.relator namespace list open function nat universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} instance [decidable_eq α] : has_sdiff (list α) := ⟨ list.diff ⟩ /-- Split a list at an index. split_at 2 [a, b, c] = ([a, b], [c]) -/ def split_at : ℕ → list α → list α × list α | 0 a := ([], a) | (succ n) [] := ([], []) | (succ n) (x :: xs) := let (l, r) := split_at n xs in (x :: l, r) def split_on_p_aux {α : Type u} (P : α → Prop) [decidable_pred P] : list α → (list α → list α) → list (list α) | [] f := [f []] | (h :: t) f := if P h then f [] :: split_on_p_aux t id else split_on_p_aux t (λ l, f (h :: l)) /-- Split a list at every element satisfying a predicate. -/ def split_on_p {α : Type u} (P : α → Prop) [decidable_pred P] (l : list α) : list (list α) := split_on_p_aux P l id /-- Split a list at every occurrence of an element. [1,1,2,3,2,4,4].split_on 2 = [[1,1],[3],[4,4]] -/ def split_on {α : Type u} [decidable_eq α] (a : α) (as : list α) : list (list α) := as.split_on_p (=a) /-- Concatenate an element at the end of a list. concat [a, b] c = [a, b, c] -/ @[simp] def concat : list α → α → list α | [] a := [a] | (b::l) a := b :: concat l a @[simp] def head' : list α → option α | [] := none | (a :: l) := some a /-- Convert a list into an array (whose length is the length of `l`). -/ def to_array (l : list α) : array l.length α := {data := λ v, l.nth_le v.1 v.2} /-- "inhabited" `nth` function: returns `default` instead of `none` in the case that the index is out of bounds. -/ @[simp] def inth [h : inhabited α] (l : list α) (n : nat) : α := (nth l n).iget /-- Apply a function to the nth tail of `l`. Returns the input without using `f` if the index is larger than the length of the list. modify_nth_tail f 2 [a, b, c] = [a, b] ++ f [c] -/ @[simp] def modify_nth_tail (f : list α → list α) : ℕ → list α → list α | 0 l := f l | (n+1) [] := [] | (n+1) (a::l) := a :: modify_nth_tail n l /-- Apply `f` to the head of the list, if it exists. -/ @[simp] def modify_head (f : α → α) : list α → list α | [] := [] | (a::l) := f a :: l /-- Apply `f` to the nth element of the list, if it exists. -/ def modify_nth (f : α → α) : ℕ → list α → list α := modify_nth_tail (modify_head f) def insert_nth (n : ℕ) (a : α) : list α → list α := modify_nth_tail (list.cons a) n section take' variable [inhabited α] def take' : ∀ n, list α → list α | 0 l := [] | (n+1) l := l.head :: take' n l.tail end take' /-- Get the longest initial segment of the list whose members all satisfy `p`. take_while (λ x, x < 3) [0, 2, 5, 1] = [0, 2] -/ def take_while (p : α → Prop) [decidable_pred p] : list α → list α | [] := [] | (a::l) := if p a then a :: take_while l else [] /-- Fold a function `f` over the list from the left, returning the list of partial results. scanl (+) 0 [1, 2, 3] = [0, 1, 3, 6] -/ def scanl (f : α → β → α) : α → list β → list α | a [] := [a] | a (b::l) := a :: scanl (f a b) l def scanr_aux (f : α → β → β) (b : β) : list α → β × list β | [] := (b, []) | (a::l) := let (b', l') := scanr_aux l in (f a b', b' :: l') /-- Fold a function `f` over the list from the right, returning the list of partial results. scanr (+) 0 [1, 2, 3] = [6, 5, 3, 0] -/ def scanr (f : α → β → β) (b : β) (l : list α) : list β := let (b', l') := scanr_aux f b l in b' :: l' /-- Product of a list. prod [a, b, c] = ((1 * a) * b) * c -/ def prod [has_mul α] [has_one α] : list α → α := foldl (*) 1 def partition_map (f : α → β ⊕ γ) : list α → list β × list γ | [] := ([],[]) | (x::xs) := match f x with | (sum.inr r) := prod.map id (cons r) $ partition_map xs | (sum.inl l) := prod.map (cons l) id $ partition_map xs end /-- `find p l` is the first element of `l` satisfying `p`, or `none` if no such element exists. -/ def find (p : α → Prop) [decidable_pred p] : list α → option α | [] := none | (a::l) := if p a then some a else find l def find_indexes_aux (p : α → Prop) [decidable_pred p] : list α → nat → list nat | [] n := [] | (a::l) n := let t := find_indexes_aux l (succ n) in if p a then n :: t else t /-- `find_indexes p l` is the list of indexes of elements of `l` that satisfy `p`. -/ def find_indexes (p : α → Prop) [decidable_pred p] (l : list α) : list nat := find_indexes_aux p l 0 /-- `lookmap` is a combination of `lookup` and `filter_map`. `lookmap f l` will apply `f : α → option α` to each element of the list, replacing `a -> b` at the first value `a` in the list such that `f a = some b`. -/ def lookmap (f : α → option α) : list α → list α | [] := [] | (a::l) := match f a with | some b := b :: l | none := a :: lookmap l end /-- `indexes_of a l` is the list of all indexes of `a` in `l`. indexes_of a [a, b, a, a] = [0, 2, 3] -/ def indexes_of [decidable_eq α] (a : α) : list α → list nat := find_indexes (eq a) /-- `countp p l` is the number of elements of `l` that satisfy `p`. -/ def countp (p : α → Prop) [decidable_pred p] : list α → nat | [] := 0 | (x::xs) := if p x then succ (countp xs) else countp xs /-- `count a l` is the number of occurrences of `a` in `l`. -/ def count [decidable_eq α] (a : α) : list α → nat := countp (eq a) /-- `is_prefix l₁ l₂`, or `l₁ <+: l₂`, means that `l₁` is a prefix of `l₂`, that is, `l₂` has the form `l₁ ++ t` for some `t`. -/ def is_prefix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, l₁ ++ t = l₂ /-- `is_suffix l₁ l₂`, or `l₁ <:+ l₂`, means that `l₁` is a suffix of `l₂`, that is, `l₂` has the form `t ++ l₁` for some `t`. -/ def is_suffix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, t ++ l₁ = l₂ /-- `is_infix l₁ l₂`, or `l₁ <:+: l₂`, means that `l₁` is a contiguous substring of `l₂`, that is, `l₂` has the form `s ++ l₁ ++ t` for some `s, t`. -/ def is_infix (l₁ : list α) (l₂ : list α) : Prop := ∃ s t, s ++ l₁ ++ t = l₂ infix ` <+: `:50 := is_prefix infix ` <:+ `:50 := is_suffix infix ` <:+: `:50 := is_infix /-- `inits l` is the list of initial segments of `l`. inits [1, 2, 3] = [[], [1], [1, 2], [1, 2, 3]] -/ @[simp] def inits : list α → list (list α) | [] := [[]] | (a::l) := [] :: map (λt, a::t) (inits l) /-- `tails l` is the list of terminal segments of `l`. tails [1, 2, 3] = [[1, 2, 3], [2, 3], [3], []] -/ @[simp] def tails : list α → list (list α) | [] := [[]] | (a::l) := (a::l) :: tails l def sublists'_aux : list α → (list α → list β) → list (list β) → list (list β) | [] f r := f [] :: r | (a::l) f r := sublists'_aux l f (sublists'_aux l (f ∘ cons a) r) /-- `sublists' l` is the list of all (non-contiguous) sublists of `l`. It differs from `sublists` only in the order of appearance of the sublists; `sublists'` uses the first element of the list as the MSB, `sublists` uses the first element of the list as the LSB. sublists' [1, 2, 3] = [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]] -/ def sublists' (l : list α) : list (list α) := sublists'_aux l id [] def sublists_aux : list α → (list α → list β → list β) → list β | [] f := [] | (a::l) f := f [a] (sublists_aux l (λys r, f ys (f (a :: ys) r))) /-- `sublists l` is the list of all (non-contiguous) sublists of `l`; cf. `sublists'` for a different ordering. sublists [1, 2, 3] = [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]] -/ def sublists (l : list α) : list (list α) := [] :: sublists_aux l cons def sublists_aux₁ : list α → (list α → list β) → list β | [] f := [] | (a::l) f := f [a] ++ sublists_aux₁ l (λys, f ys ++ f (a :: ys)) section forall₂ variables {r : α → β → Prop} {p : γ → δ → Prop} open relator inductive forall₂ (R : α → β → Prop) : list α → list β → Prop | nil {} : forall₂ [] [] | cons {a b l₁ l₂} : R a b → forall₂ l₁ l₂ → forall₂ (a::l₁) (b::l₂) attribute [simp] forall₂.nil end forall₂ def transpose_aux : list α → list (list α) → list (list α) | [] ls := ls | (a::i) [] := [a] :: transpose_aux i [] | (a::i) (l::ls) := (a::l) :: transpose_aux i ls /-- transpose of a list of lists, treated as a matrix. transpose [[1, 2], [3, 4], [5, 6]] = [[1, 3, 5], [2, 4, 6]] -/ def transpose : list (list α) → list (list α) | [] := [] | (l::ls) := transpose_aux l (transpose ls) /-- List of all sections through a list of lists. A section of `[L₁, L₂, ..., Lₙ]` is a list whose first element comes from `L₁`, whose second element comes from `L₂`, and so on. -/ def sections : list (list α) → list (list α) | [] := [[]] | (l::L) := bind (sections L) $ λ s, map (λ a, a::s) l section permutations def permutations_aux2 (t : α) (ts : list α) (r : list β) : list α → (list α → β) → list α × list β | [] f := (ts, r) | (y::ys) f := let (us, zs) := permutations_aux2 ys (λx : list α, f (y::x)) in (y :: us, f (t :: y :: us) :: zs) private def meas : (Σ'_:list α, list α) → ℕ × ℕ | ⟨l, i⟩ := (length l + length i, length l) local infix ` ≺ `:50 := inv_image (prod.lex (<) (<)) meas @[elab_as_eliminator] def permutations_aux.rec {C : list α → list α → Sort v} (H0 : ∀ is, C [] is) (H1 : ∀ t ts is, C ts (t::is) → C is [] → C (t::ts) is) : ∀ l₁ l₂, C l₁ l₂ | [] is := H0 is | (t::ts) is := have h1 : ⟨ts, t :: is⟩ ≺ ⟨t :: ts, is⟩, from show prod.lex _ _ (succ (length ts + length is), length ts) (succ (length ts) + length is, length (t :: ts)), by rw nat.succ_add; exact prod.lex.right _ _ (lt_succ_self _), have h2 : ⟨is, []⟩ ≺ ⟨t :: ts, is⟩, from prod.lex.left _ _ _ (lt_add_of_pos_left _ (succ_pos _)), H1 t ts is (permutations_aux.rec ts (t::is)) (permutations_aux.rec is []) using_well_founded { dec_tac := tactic.assumption, rel_tac := λ _ _, `[exact ⟨(≺), @inv_image.wf _ _ _ meas (prod.lex_wf lt_wf lt_wf)⟩] } def permutations_aux : list α → list α → list (list α) := @@permutations_aux.rec (λ _ _, list (list α)) (λ is, []) (λ t ts is IH1 IH2, foldr (λy r, (permutations_aux2 t ts r y id).2) IH1 (is :: IH2)) /-- List of all permutations of `l`. permutations [1, 2, 3] = [[1, 2, 3], [2, 1, 3], [3, 2, 1], [2, 3, 1], [3, 1, 2], [1, 3, 2]] -/ def permutations (l : list α) : list (list α) := l :: permutations_aux l [] end permutations def erasep (p : α → Prop) [decidable_pred p] : list α → list α | [] := [] | (a::l) := if p a then l else a :: erasep l def extractp (p : α → Prop) [decidable_pred p] : list α → option α × list α | [] := (none, []) | (a::l) := if p a then (some a, l) else let (a', l') := extractp l in (a', a :: l') def revzip (l : list α) : list (α × α) := zip l l.reverse /-- `product l₁ l₂` is the list of pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂`. product [1, 2] [5, 6] = [(1, 5), (1, 6), (2, 5), (2, 6)] -/ def product (l₁ : list α) (l₂ : list β) : list (α × β) := l₁.bind $ λ a, l₂.map $ prod.mk a /-- `sigma l₁ l₂` is the list of dependent pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂ a`. sigma [1, 2] (λ_, [(5 : ℕ), 6]) = [(1, 5), (1, 6), (2, 5), (2, 6)] -/ protected def sigma {σ : α → Type*} (l₁ : list α) (l₂ : Π a, list (σ a)) : list (Σ a, σ a) := l₁.bind $ λ a, (l₂ a).map $ sigma.mk a def of_fn_aux {n} (f : fin n → α) : ∀ m, m ≤ n → list α → list α | 0 h l := l | (succ m) h l := of_fn_aux m (le_of_lt h) (f ⟨m, h⟩ :: l) def of_fn {n} (f : fin n → α) : list α := of_fn_aux f n (le_refl _) [] def of_fn_nth_val {n} (f : fin n → α) (i : ℕ) : option α := if h : _ then some (f ⟨i, h⟩) else none /-- `disjoint l₁ l₂` means that `l₁` and `l₂` have no elements in common. -/ def disjoint (l₁ l₂ : list α) : Prop := ∀ ⦃a⦄, a ∈ l₁ → a ∈ l₂ → false section pairwise variables (R : α → α → Prop) /-- `pairwise R l` means that all the elements with earlier indexes are `R`-related to all the elements with later indexes. pairwise R [1, 2, 3] ↔ R 1 2 ∧ R 1 3 ∧ R 2 3 For example if `R = (≠)` then it asserts `l` has no duplicates, and if `R = (<)` then it asserts that `l` is (strictly) sorted. -/ inductive pairwise : list α → Prop | nil {} : pairwise [] | cons : ∀ {a : α} {l : list α}, (∀ a' ∈ l, R a a') → pairwise l → pairwise (a::l) variables {R} @[simp] theorem pairwise_cons {a : α} {l : list α} : pairwise R (a::l) ↔ (∀ a' ∈ l, R a a') ∧ pairwise R l := ⟨λ p, by cases p with a l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩ instance decidable_pairwise [decidable_rel R] (l : list α) : decidable (pairwise R l) := by induction l with hd tl ih; [exact is_true pairwise.nil, exactI decidable_of_iff' _ pairwise_cons] end pairwise /-- `pw_filter R l` is a maximal sublist of `l` which is `pairwise R`. `pw_filter (≠)` is the erase duplicates function (cf. `erase_dup`), and `pw_filter (<)` finds a maximal increasing subsequence in `l`. For example, pw_filter (<) [0, 1, 5, 2, 6, 3, 4] = [0, 1, 2, 3, 4] -/ def pw_filter (R : α → α → Prop) [decidable_rel R] : list α → list α | [] := [] | (x :: xs) := let IH := pw_filter xs in if ∀ y ∈ IH, R x y then x :: IH else IH section chain variable (R : α → α → Prop) /-- `chain R a l` means that `R` holds between adjacent elements of `a::l`. chain R a [b, c, d] ↔ R a b ∧ R b c ∧ R c d -/ inductive chain : α → list α → Prop | nil {} {a : α} : chain a [] | cons : ∀ {a b : α} {l : list α}, R a b → chain b l → chain a (b::l) /-- `chain' R l` means that `R` holds between adjacent elements of `l`. chain' R [a, b, c, d] ↔ R a b ∧ R b c ∧ R c d -/ def chain' : list α → Prop | [] := true | (a :: l) := chain R a l variable {R} @[simp] theorem chain_cons {a b : α} {l : list α} : chain R a (b::l) ↔ R a b ∧ chain R b l := ⟨λ p, by cases p with _ a b l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩ instance decidable_chain [decidable_rel R] (a : α) (l : list α) : decidable (chain R a l) := by induction l generalizing a; simp only [chain.nil, chain_cons]; resetI; apply_instance instance decidable_chain' [decidable_rel R] (a : α) (l : list α) : decidable (chain' R l) := by cases l; dunfold chain'; apply_instance end chain /-- `nodup l` means that `l` has no duplicates, that is, any element appears at most once in the list. It is defined as `pairwise (≠)`. -/ def nodup : list α → Prop := pairwise (≠) instance nodup_decidable [decidable_eq α] : ∀ l : list α, decidable (nodup l) := list.decidable_pairwise /-- `erase_dup l` removes duplicates from `l` (taking only the first occurrence). Defined as `pw_filter (≠)`. erase_dup [1, 0, 2, 2, 1] = [0, 2, 1] -/ def erase_dup [decidable_eq α] : list α → list α := pw_filter (≠) /-- `range' s n` is the list of numbers `[s, s+1, ..., s+n-1]`. It is intended mainly for proving properties of `range` and `iota`. -/ @[simp] def range' : ℕ → ℕ → list ℕ | s 0 := [] | s (n+1) := s :: range' (s+1) n def reduce_option {α} : list (option α) → list α := list.filter_map id def map_head {α} (f : α → α) : list α → list α | [] := [] | (x :: xs) := f x :: xs def map_last {α} (f : α → α) : list α → list α | [] := [] | [x] := [f x] | (x :: xs) := x :: map_last xs @[simp] def last' {α} : α → list α → α | a [] := a | a (b::l) := last' b l /- tfae: The Following (propositions) Are Equivalent -/ def tfae (l : list Prop) : Prop := ∀ x ∈ l, ∀ y ∈ l, x ↔ y /-- `rotate l n` rotates the elements of `l` to the left by `n` rotate [0, 1, 2, 3, 4, 5] 2 = [2, 3, 4, 5, 0, 1] -/ def rotate (l : list α) (n : ℕ) : list α := let (l₁, l₂) := list.split_at (n % l.length) l in l₂ ++ l₁ /-- rotate' is the same as `rotate`, but slower. Used for proofs about `rotate`-/ def rotate' : list α → ℕ → list α | [] n := [] | l 0 := l | (a::l) (n+1) := rotate' (l ++ [a]) n section choose variables (p : α → Prop) [decidable_pred p] (l : list α) def choose_x : Π l : list α, Π hp : (∃ a, a ∈ l ∧ p a), { a // a ∈ l ∧ p a } | [] hp := false.elim (exists.elim hp (assume a h, not_mem_nil a h.left)) | (l :: ls) hp := if pl : p l then ⟨l, ⟨or.inl rfl, pl⟩⟩ else let ⟨a, ⟨a_mem_ls, pa⟩⟩ := choose_x ls (hp.imp (λ b ⟨o, h₂⟩, ⟨o.resolve_left (λ e, pl $ e ▸ h₂), h₂⟩)) in ⟨a, ⟨or.inr a_mem_ls, pa⟩⟩ def choose (hp : ∃ a, a ∈ l ∧ p a) : α := choose_x p l hp end choose end list
dcf2ccf4ef65c5cf03d537c21d4767cdf3fee14f
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/src/Init/Core.lean
7c00722efb9c6a86156a57721097a3b6e2092265
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
34,451
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 notation, basic datatypes and type classes -/ prelude import Init.Prelude import Init.Notation universes u v w def inline {α : Sort u} (a : α) : α := a @[inline] def flip {α : Sort u} {β : Sort v} {φ : Sort w} (f : α → β → φ) : β → α → φ := fun b a => f a b /- Remark: thunks have an efficient implementation in the runtime. -/ structure Thunk (α : Type u) : Type u where fn : Unit → α attribute [extern "lean_mk_thunk"] Thunk.mk @[noinline, extern "lean_thunk_pure"] protected def Thunk.pure {α : Type u} (a : α) : Thunk α := ⟨fun _ => a⟩ @[noinline, extern "lean_thunk_get_own"] protected def Thunk.get {α : Type u} (x : @& Thunk α) : α := x.fn () @[noinline, extern "lean_thunk_map"] protected def Thunk.map {α : Type u} {β : Type v} (f : α → β) (x : Thunk α) : Thunk β := ⟨fun _ => f x.get⟩ @[noinline, extern "lean_thunk_bind"] protected def Thunk.bind {α : Type u} {β : Type v} (x : Thunk α) (f : α → Thunk β) : Thunk β := ⟨fun _ => (f x.get).get⟩ abbrev Eq.ndrecOn.{u1, u2} {α : Sort u2} {a : α} {motive : α → Sort u1} {b : α} (h : Eq a b) (m : motive a) : motive b := Eq.ndrec m h structure Iff (a b : Prop) : Prop where intro :: (mp : a → b) (mpr : b → a) infix:20 " <-> " => Iff infix:20 " ↔ " => Iff /- Eq basic support -/ theorem Eq.trans {α : Sort u} {a b c : α} (h₁ : a = b) (h₂ : b = c) : a = c := h₂ ▸ h₁ inductive Sum (α : Type u) (β : Type v) where | inl (val : α) : Sum α β | inr (val : β) : Sum α β inductive PSum (α : Sort u) (β : Sort v) where | inl (val : α) : PSum α β | inr (val : β) : PSum α β structure Sigma {α : Type u} (β : α → Type v) where fst : α snd : β fst attribute [unbox] Sigma structure PSigma {α : Sort u} (β : α → Sort v) where fst : α snd : β fst inductive Exists {α : Sort u} (p : α → Prop) : Prop where | intro (w : α) (h : p w) : Exists p /- Auxiliary type used to compile `for x in xs` notation. -/ inductive ForInStep (α : Type u) where | done : α → ForInStep α | yield : α → ForInStep α /- Auxiliary type used to compile `do` notation. -/ inductive DoResultPRBC (α β σ : Type u) where | «pure» : α → σ → DoResultPRBC α β σ | «return» : β → σ → DoResultPRBC α β σ | «break» : σ → DoResultPRBC α β σ | «continue» : σ → DoResultPRBC α β σ /- Auxiliary type used to compile `do` notation. -/ inductive DoResultPR (α β σ : Type u) where | «pure» : α → σ → DoResultPR α β σ | «return» : β → σ → DoResultPR α β σ /- Auxiliary type used to compile `do` notation. -/ inductive DoResultBC (σ : Type u) where | «break» : σ → DoResultBC σ | «continue» : σ → DoResultBC σ /- Auxiliary type used to compile `do` notation. -/ inductive DoResultSBC (α σ : Type u) where | «pureReturn» : α → σ → DoResultSBC α σ | «break» : σ → DoResultSBC α σ | «continue» : σ → DoResultSBC α σ class HasEquiv (α : Sort u) where Equiv : α → α → Prop infix:50 " ≈ " => HasEquiv.Equiv class EmptyCollection (α : Type u) where emptyCollection : α /- Remark: tasks have an efficient implementation in the runtime. -/ structure Task (α : Type u) : Type u where pure :: (get : α) attribute [extern "lean_task_pure"] Task.pure attribute [extern "lean_task_get_own"] Task.get namespace Task /-- Task priority. Tasks with higher priority will always be scheduled before ones with lower priority. -/ abbrev Priority := Nat def Priority.default : Priority := 0 -- see `LEAN_MAX_PRIO` def Priority.max : Priority := 8 /-- Any priority higher than `Task.Priority.max` will result in the task being scheduled immediately on a dedicated thread. This is particularly useful for long-running and/or I/O-bound tasks since Lean will by default allocate no more non-dedicated workers than the number of cores to reduce context switches. -/ def Priority.dedicated : Priority := 9 @[noinline, extern "lean_task_spawn"] protected def spawn {α : Type u} (fn : Unit → α) (prio := Priority.default) : Task α := ⟨fn ()⟩ @[noinline, extern "lean_task_map"] protected def map {α : Type u} {β : Type v} (f : α → β) (x : Task α) (prio := Priority.default) : Task β := ⟨f x.get⟩ @[noinline, extern "lean_task_bind"] protected def bind {α : Type u} {β : Type v} (x : Task α) (f : α → Task β) (prio := Priority.default) : Task β := ⟨(f x.get).get⟩ end Task /- Some type that is not a scalar value in our runtime. -/ structure NonScalar where val : Nat /- Some type that is not a scalar value in our runtime and is universe polymorphic. -/ inductive PNonScalar : Type u where | mk (v : Nat) : PNonScalar theorem natAddZero (n : Nat) : n + 0 = n := rfl theorem optParamEq (α : Sort u) (default : α) : optParam α default = α := rfl /- Boolean operators -/ @[extern c inline "#1 || #2"] def strictOr (b₁ b₂ : Bool) := b₁ || b₂ @[extern c inline "#1 && #2"] def strictAnd (b₁ b₂ : Bool) := b₁ && b₂ @[inline] def bne {α : Type u} [BEq α] (a b : α) : Bool := !(a == b) infix:50 " != " => bne /- Logical connectives an equality -/ def implies (a b : Prop) := a → b theorem implies.trans {p q r : Prop} (h₁ : implies p q) (h₂ : implies q r) : implies p r := fun hp => h₂ (h₁ hp) def trivial : True := ⟨⟩ theorem mt {a b : Prop} (h₁ : a → b) (h₂ : ¬b) : ¬a := fun ha => h₂ (h₁ ha) theorem notFalse : ¬False := id -- proof irrelevance is built in theorem proofIrrel {a : Prop} (h₁ h₂ : a) : h₁ = h₂ := rfl theorem id.def {α : Sort u} (a : α) : id a = a := rfl @[macroInline] def Eq.mp {α β : Sort u} (h : α = β) (a : α) : β := h ▸ a @[macroInline] def Eq.mpr {α β : Sort u} (h : α = β) (b : β) : α := h ▸ b theorem Eq.substr {α : Sort u} {p : α → Prop} {a b : α} (h₁ : b = a) (h₂ : p a) : p b := h₁ ▸ h₂ theorem congr {α : Sort u} {β : Sort v} {f₁ f₂ : α → β} {a₁ a₂ : α} (h₁ : f₁ = f₂) (h₂ : a₁ = a₂) : f₁ a₁ = f₂ a₂ := h₁ ▸ h₂ ▸ rfl theorem congrFun {α : Sort u} {β : α → Sort v} {f g : ∀ x, β x} (h : f = g) (a : α) : f a = g a := h ▸ rfl theorem castEq {α : Sort u} (h : α = α) (a : α) : cast h a = a := rfl @[reducible] def Ne {α : Sort u} (a b : α) := ¬(a = b) infix:50 " ≠ " => Ne section Ne variable {α : Sort u} variables {a b : α} {p : Prop} theorem Ne.intro (h : a = b → False) : a ≠ b := h theorem Ne.elim (h : a ≠ b) : a = b → False := h theorem Ne.irrefl (h : a ≠ a) : False := h rfl theorem Ne.symm (h : a ≠ b) : b ≠ a := fun h₁ => h (h₁.symm) theorem falseOfNe : a ≠ a → False := Ne.irrefl theorem neFalseOfSelf : p → p ≠ False := fun (hp : p) (h : p = False) => h ▸ hp theorem neTrueOfNot : ¬p → p ≠ True := fun (hnp : ¬p) (h : p = True) => have ¬True from h ▸ hnp this trivial theorem trueNeFalse : ¬True = False := neFalseOfSelf trivial end Ne section variables {α β φ : Sort u} {a a' : α} {b b' : β} {c : φ} theorem HEq.ndrec.{u1, u2} {α : Sort u2} {a : α} {motive : {β : Sort u2} → β → Sort u1} (m : motive a) {β : Sort u2} {b : β} (h : a ≅ b) : motive b := @HEq.rec α a (fun b _ => motive b) m β b h theorem HEq.ndrecOn.{u1, u2} {α : Sort u2} {a : α} {motive : {β : Sort u2} → β → Sort u1} {β : Sort u2} {b : β} (h : a ≅ b) (m : motive a) : motive b := @HEq.rec α a (fun b _ => motive b) m β b h theorem HEq.elim {α : Sort u} {a : α} {p : α → Sort v} {b : α} (h₁ : a ≅ b) (h₂ : p a) : p b := eqOfHEq h₁ ▸ h₂ theorem HEq.subst {p : (T : Sort u) → T → Prop} (h₁ : a ≅ b) (h₂ : p α a) : p β b := HEq.ndrecOn h₁ h₂ theorem HEq.symm (h : a ≅ b) : b ≅ a := HEq.ndrecOn (motive := fun x => x ≅ a) h (HEq.refl a) theorem heqOfEq (h : a = a') : a ≅ a' := Eq.subst h (HEq.refl a) theorem HEq.trans (h₁ : a ≅ b) (h₂ : b ≅ c) : a ≅ c := HEq.subst h₂ h₁ theorem heqOfHEqOfEq (h₁ : a ≅ b) (h₂ : b = b') : a ≅ b' := HEq.trans h₁ (heqOfEq h₂) theorem heqOfEqOfHEq (h₁ : a = a') (h₂ : a' ≅ b) : a ≅ b := HEq.trans (heqOfEq h₁) h₂ def typeEqOfHEq (h : a ≅ b) : α = β := HEq.ndrecOn (motive := @fun (x : Sort u) _ => α = x) h (Eq.refl α) end theorem eqRecHEq {α : Sort u} {φ : α → Sort v} : {a a' : α} → (h : a = a') → (p : φ a) → (Eq.recOn (motive := fun x _ => φ x) h p) ≅ p | a, _, rfl, p => HEq.refl p theorem heqOfEqRecEq {α β : Sort u} {a : α} {b : β} (h₁ : α = β) (h₂ : Eq.rec (motive := fun α _ => α) a h₁ = b) : a ≅ b := by subst h₁ apply heqOfEq exact h₂ done theorem castHEq : ∀ {α β : Sort u} (h : α = β) (a : α), cast h a ≅ a | α, _, rfl, a => HEq.refl a variables {a b c d : Prop} theorem iffIffImpliesAndImplies (a b : Prop) : (a ↔ b) ↔ (a → b) ∧ (b → a) := Iff.intro (fun h => And.intro h.mp h.mpr) (fun h => Iff.intro h.left h.right) theorem Iff.refl (a : Prop) : a ↔ a := Iff.intro (fun h => h) (fun h => h) theorem Iff.rfl {a : Prop} : a ↔ a := Iff.refl a theorem Iff.trans (h₁ : a ↔ b) (h₂ : b ↔ c) : a ↔ c := Iff.intro (fun ha => Iff.mp h₂ (Iff.mp h₁ ha)) (fun hc => Iff.mpr h₁ (Iff.mpr h₂ hc)) theorem Iff.symm (h : a ↔ b) : b ↔ a := Iff.intro (Iff.mpr h) (Iff.mp h) theorem Iff.comm : (a ↔ b) ↔ (b ↔ a) := Iff.intro Iff.symm Iff.symm /- Exists -/ theorem Exists.elim {α : Sort u} {p : α → Prop} {b : Prop} (h₁ : Exists (fun x => p x)) (h₂ : ∀ (a : α), p a → b) : b := h₂ h₁.1 h₁.2 /- Decidable -/ theorem decideTrueEqTrue (h : Decidable True) : @decide True h = true := match h with | isTrue h => rfl | isFalse h => False.elim <| h ⟨⟩ theorem decideFalseEqFalse (h : Decidable False) : @decide False h = false := match h with | isFalse h => rfl | isTrue h => False.elim h /-- Similar to `decide`, but uses an explicit instance -/ @[inline] def toBoolUsing {p : Prop} (d : Decidable p) : Bool := @decide p d theorem toBoolUsingEqTrue {p : Prop} (d : Decidable p) (h : p) : toBoolUsing d = true := @decideEqTrue _ d h theorem ofBoolUsingEqTrue {p : Prop} {d : Decidable p} (h : toBoolUsing d = true) : p := @ofDecideEqTrue _ d h theorem ofBoolUsingEqFalse {p : Prop} {d : Decidable p} (h : toBoolUsing d = false) : ¬ p := @ofDecideEqFalse _ d h instance : Decidable True := isTrue trivial instance : Decidable False := isFalse notFalse namespace Decidable variables {p q : Prop} @[macroInline] def byCases {q : Sort u} [dec : Decidable p] (h1 : p → q) (h2 : ¬p → q) : q := match dec with | isTrue h => h1 h | isFalse h => h2 h theorem em (p : Prop) [Decidable p] : p ∨ ¬p := byCases Or.inl Or.inr theorem byContradiction [dec : Decidable p] (h : ¬p → False) : p := byCases id (fun np => False.elim (h np)) theorem ofNotNot [Decidable p] : ¬ ¬ p → p := fun hnn => byContradiction (fun hn => absurd hn hnn) theorem notAndIffOrNot (p q : Prop) [d₁ : Decidable p] [d₂ : Decidable q] : ¬ (p ∧ q) ↔ ¬ p ∨ ¬ q := Iff.intro (fun h => match d₁, d₂ with | isTrue h₁, isTrue h₂ => absurd (And.intro h₁ h₂) h | _, isFalse h₂ => Or.inr h₂ | isFalse h₁, _ => Or.inl h₁) (fun (h) ⟨hp, hq⟩ => match h with | Or.inl h => h hp | Or.inr h => h hq) end Decidable section variables {p q : Prop} @[inline] def decidableOfDecidableOfIff (hp : Decidable p) (h : p ↔ q) : Decidable q := if hp : p then isTrue (Iff.mp h hp) else isFalse fun hq => absurd (Iff.mpr h hq) hp @[inline] def decidableOfDecidableOfEq (hp : Decidable p) (h : p = q) : Decidable q := h ▸ hp end @[macroInline] instance {p q} [Decidable p] [Decidable q] : Decidable (p → q) := if hp : p then if hq : q then isTrue (fun h => hq) else isFalse (fun h => absurd (h hp) hq) else isTrue (fun h => absurd h hp) instance {p q} [Decidable p] [Decidable q] : Decidable (p ↔ q) := if hp : p then if hq : q then isTrue ⟨fun _ => hq, fun _ => hp⟩ else isFalse fun h => hq (h.1 hp) else if hq : q then isFalse fun h => hp (h.2 hq) else isTrue ⟨fun h => absurd h hp, fun h => absurd h hq⟩ /- if-then-else expression theorems -/ theorem ifPos {c : Prop} [h : Decidable c] (hc : c) {α : Sort u} {t e : α} : (ite c t e) = t := match h with | (isTrue hc) => rfl | (isFalse hnc) => absurd hc hnc theorem ifNeg {c : Prop} [h : Decidable c] (hnc : ¬c) {α : Sort u} {t e : α} : (ite c t e) = e := match h with | (isTrue hc) => absurd hc hnc | (isFalse hnc) => rfl theorem difPos {c : Prop} [h : Decidable c] (hc : c) {α : Sort u} {t : c → α} {e : ¬ c → α} : (dite c t e) = t hc := match h with | (isTrue hc) => rfl | (isFalse hnc) => absurd hc hnc theorem difNeg {c : Prop} [h : Decidable c] (hnc : ¬c) {α : Sort u} {t : c → α} {e : ¬ c → α} : (dite c t e) = e hnc := match h with | (isTrue hc) => absurd hc hnc | (isFalse hnc) => rfl -- Remark: dite and ite are "defally equal" when we ignore the proofs. theorem difEqIf (c : Prop) [h : Decidable c] {α : Sort u} (t : α) (e : α) : dite c (fun h => t) (fun h => e) = ite c t e := match h with | (isTrue hc) => rfl | (isFalse hnc) => rfl instance {c t e : Prop} [dC : Decidable c] [dT : Decidable t] [dE : Decidable e] : Decidable (if c then t else e) := match dC with | (isTrue hc) => dT | (isFalse hc) => dE instance {c : Prop} {t : c → Prop} {e : ¬c → Prop} [dC : Decidable c] [dT : ∀ h, Decidable (t h)] [dE : ∀ h, Decidable (e h)] : Decidable (if h : c then t h else e h) := match dC with | (isTrue hc) => dT hc | (isFalse hc) => dE hc /- Inhabited -/ instance : Inhabited Prop where default := True deriving instance Inhabited for Bool, NonScalar, PNonScalar, True, ForInStep class inductive Nonempty (α : Sort u) : Prop where | intro (val : α) : Nonempty α protected def Nonempty.elim {α : Sort u} {p : Prop} (h₁ : Nonempty α) (h₂ : α → p) : p := h₂ h₁.1 instance {α : Sort u} [Inhabited α] : Nonempty α where val := arbitrary theorem nonemptyOfExists {α : Sort u} {p : α → Prop} : Exists (fun x => p x) → Nonempty α | ⟨w, h⟩ => ⟨w⟩ /- Subsingleton -/ class Subsingleton (α : Sort u) : Prop where intro :: allEq : (a b : α) → a = b protected def Subsingleton.elim {α : Sort u} [h : Subsingleton α] : (a b : α) → a = b := h.allEq protected def Subsingleton.helim {α β : Sort u} [h₁ : Subsingleton α] (h₂ : α = β) (a : α) (b : β) : a ≅ b := by subst h₂ apply heqOfEq apply Subsingleton.elim instance (p : Prop) : Subsingleton p := ⟨fun a b => proofIrrel a b⟩ instance (p : Prop) : Subsingleton (Decidable p) := Subsingleton.intro fun | (isTrue t₁) => fun | (isTrue t₂) => proofIrrel t₁ t₂ ▸ rfl | (isFalse f₂) => absurd t₁ f₂ | (isFalse f₁) => fun | (isTrue t₂) => absurd t₂ f₁ | (isFalse f₂) => proofIrrel f₁ f₂ ▸ rfl theorem recSubsingleton {p : Prop} [h : Decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} [h₃ : ∀ (h : p), Subsingleton (h₁ h)] [h₄ : ∀ (h : ¬p), Subsingleton (h₂ h)] : Subsingleton (Decidable.casesOn (motive := fun _ => Sort u) h h₂ h₁) := match h with | (isTrue h) => h₃ h | (isFalse h) => h₄ h structure Equivalence {α : Sort u} (r : α → α → Prop) : Prop where refl : ∀ x, r x x symm : ∀ {x y}, r x y → r y x trans : ∀ {x y z}, r x y → r y z → r x z def emptyRelation {α : Sort u} (a₁ a₂ : α) : Prop := False def Subrelation {α : Sort u} (q r : α → α → Prop) := ∀ {x y}, q x y → r x y def InvImage {α : Sort u} {β : Sort v} (r : β → β → Prop) (f : α → β) : α → α → Prop := fun a₁ a₂ => r (f a₁) (f a₂) inductive TC {α : Sort u} (r : α → α → Prop) : α → α → Prop where | base : ∀ a b, r a b → TC r a b | trans : ∀ a b c, TC r a b → TC r b c → TC r a c /- Subtype -/ namespace Subtype def existsOfSubtype {α : Type u} {p : α → Prop} : { x // p x } → Exists (fun x => p x) | ⟨a, h⟩ => ⟨a, h⟩ variables {α : Type u} {p : α → Prop} protected theorem eq : ∀ {a1 a2 : {x // p x}}, val a1 = val a2 → a1 = a2 | ⟨x, h1⟩, ⟨_, _⟩, rfl => rfl theorem eta (a : {x // p x}) (h : p (val a)) : mk (val a) h = a := by cases a exact rfl instance {α : Type u} {p : α → Prop} {a : α} (h : p a) : Inhabited {x // p x} where default := ⟨a, h⟩ instance {α : Type u} {p : α → Prop} [DecidableEq α] : DecidableEq {x : α // p x} := fun ⟨a, h₁⟩ ⟨b, h₂⟩ => if h : a = b then isTrue (by subst h; exact rfl) else isFalse (fun h' => Subtype.noConfusion h' (fun h' => absurd h' h)) end Subtype /- Sum -/ section variables {α : Type u} {β : Type v} instance Sum.inhabitedLeft [h : Inhabited α] : Inhabited (Sum α β) where default := Sum.inl arbitrary instance Sum.inhabitedRight [h : Inhabited β] : Inhabited (Sum α β) where default := Sum.inr arbitrary instance {α : Type u} {β : Type v} [DecidableEq α] [DecidableEq β] : DecidableEq (Sum α β) := fun a b => match a, b with | (Sum.inl a), (Sum.inl b) => if h : a = b then isTrue (h ▸ rfl) else isFalse (fun h' => Sum.noConfusion h' (fun h' => absurd h' h)) | (Sum.inr a), (Sum.inr b) => if h : a = b then isTrue (h ▸ rfl) else isFalse (fun h' => Sum.noConfusion h' (fun h' => absurd h' h)) | (Sum.inr a), (Sum.inl b) => isFalse (fun h => Sum.noConfusion h) | (Sum.inl a), (Sum.inr b) => isFalse (fun h => Sum.noConfusion h) end /- Product -/ section variables {α : Type u} {β : Type v} instance [Inhabited α] [Inhabited β] : Inhabited (α × β) where default := (arbitrary, arbitrary) instance [DecidableEq α] [DecidableEq β] : DecidableEq (α × β) := fun ⟨a, b⟩ ⟨a', b'⟩ => match (decEq a a') with | (isTrue e₁) => match (decEq b b') with | (isTrue e₂) => isTrue (e₁ ▸ e₂ ▸ rfl) | (isFalse n₂) => isFalse (fun h => Prod.noConfusion h (fun e₁' e₂' => absurd e₂' n₂)) | (isFalse n₁) => isFalse (fun h => Prod.noConfusion h (fun e₁' e₂' => absurd e₁' n₁)) instance [BEq α] [BEq β] : BEq (α × β) where beq := fun ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ => a₁ == a₂ && b₁ == b₂ instance [HasLess α] [HasLess β] : HasLess (α × β) where Less s t := s.1 < t.1 ∨ (s.1 = t.1 ∧ s.2 < t.2) instance prodHasDecidableLt [HasLess α] [HasLess β] [DecidableEq α] [DecidableEq β] [(a b : α) → Decidable (a < b)] [(a b : β) → Decidable (a < b)] : (s t : α × β) → Decidable (s < t) := fun t s => inferInstanceAs (Decidable (_ ∨ _)) theorem Prod.ltDef [HasLess α] [HasLess β] (s t : α × β) : (s < t) = (s.1 < t.1 ∨ (s.1 = t.1 ∧ s.2 < t.2)) := rfl end def Prod.map.{u₁, u₂, v₁, v₂} {α₁ : Type u₁} {α₂ : Type u₂} {β₁ : Type v₁} {β₂ : Type v₂} (f : α₁ → α₂) (g : β₁ → β₂) : α₁ × β₁ → α₂ × β₂ | (a, b) => (f a, g b) /- Dependent products -/ theorem exOfPsig {α : Type u} {p : α → Prop} : (PSigma (fun x => p x)) → Exists (fun x => p x) | ⟨x, hx⟩ => ⟨x, hx⟩ protected theorem PSigma.eta {α : Sort u} {β : α → Sort v} {a₁ a₂ : α} {b₁ : β a₁} {b₂ : β a₂} (h₁ : a₁ = a₂) (h₂ : Eq.ndrec b₁ h₁ = b₂) : PSigma.mk a₁ b₁ = PSigma.mk a₂ b₂ := by subst h₁ subst h₂ exact rfl /- Universe polymorphic unit -/ theorem punitEq (a b : PUnit) : a = b := by cases a; cases b; exact rfl theorem punitEqPUnit (a : PUnit) : a = () := punitEq a () instance : Subsingleton PUnit := Subsingleton.intro punitEq instance : Inhabited PUnit where default := ⟨⟩ instance : DecidableEq PUnit := fun a b => isTrue (punitEq a b) /- Setoid -/ class Setoid (α : Sort u) where r : α → α → Prop iseqv {} : Equivalence r instance {α : Sort u} [Setoid α] : HasEquiv α := ⟨Setoid.r⟩ namespace Setoid variables {α : Sort u} [Setoid α] theorem refl (a : α) : a ≈ a := (Setoid.iseqv α).refl a theorem symm {a b : α} (hab : a ≈ b) : b ≈ a := (Setoid.iseqv α).symm hab theorem trans {a b c : α} (hab : a ≈ b) (hbc : b ≈ c) : a ≈ c := (Setoid.iseqv α).trans hab hbc end Setoid /- Propositional extensionality -/ axiom propext {a b : Prop} : (a ↔ b) → a = b /- Quotients -/ -- Iff can now be used to do substitutions in a calculation theorem iffSubst {a b : Prop} {p : Prop → Prop} (h₁ : a ↔ b) (h₂ : p a) : p b := Eq.subst (propext h₁) h₂ namespace Quot axiom sound : ∀ {α : Sort u} {r : α → α → Prop} {a b : α}, r a b → Quot.mk r a = Quot.mk r b protected theorem liftBeta {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) (c : (a b : α) → r a b → f a = f b) (a : α) : lift f c (Quot.mk r a) = f a := rfl protected theorem indBeta {α : Sort u} {r : α → α → Prop} {motive : Quot r → Prop} (p : (a : α) → motive (Quot.mk r a)) (a : α) : (ind p (Quot.mk r a) : motive (Quot.mk r a)) = p a := rfl protected abbrev liftOn {α : Sort u} {β : Sort v} {r : α → α → Prop} (q : Quot r) (f : α → β) (c : (a b : α) → r a b → f a = f b) : β := lift f c q protected theorem inductionOn {α : Sort u} {r : α → α → Prop} {motive : Quot r → Prop} (q : Quot r) (h : (a : α) → motive (Quot.mk r a)) : motive q := ind h q theorem existsRep {α : Sort u} {r : α → α → Prop} (q : Quot r) : Exists (fun a => (Quot.mk r a) = q) := Quot.inductionOn (motive := fun q => Exists (fun a => (Quot.mk r a) = q)) q (fun a => ⟨a, rfl⟩) section variable {α : Sort u} variable {r : α → α → Prop} variable {motive : Quot r → Sort v} @[reducible, macroInline] protected def indep (f : (a : α) → motive (Quot.mk r a)) (a : α) : PSigma motive := ⟨Quot.mk r a, f a⟩ protected theorem indepCoherent (f : (a : α) → motive (Quot.mk r a)) (h : (a b : α) → (p : r a b) → Eq.ndrec (f a) (sound p) = f b) : (a b : α) → r a b → Quot.indep f a = Quot.indep f b := fun a b e => PSigma.eta (sound e) (h a b e) protected theorem liftIndepPr1 (f : (a : α) → motive (Quot.mk r a)) (h : ∀ (a b : α) (p : r a b), Eq.ndrec (f a) (sound p) = f b) (q : Quot r) : (lift (Quot.indep f) (Quot.indepCoherent f h) q).1 = q := by induction q using Quot.ind exact rfl protected abbrev rec (f : (a : α) → motive (Quot.mk r a)) (h : (a b : α) → (p : r a b) → Eq.ndrec (f a) (sound p) = f b) (q : Quot r) : motive q := Eq.ndrecOn (Quot.liftIndepPr1 f h q) ((lift (Quot.indep f) (Quot.indepCoherent f h) q).2) protected abbrev recOn (q : Quot r) (f : (a : α) → motive (Quot.mk r a)) (h : (a b : α) → (p : r a b) → Eq.ndrec (f a) (sound p) = f b) : motive q := Quot.rec f h q protected abbrev recOnSubsingleton [h : (a : α) → Subsingleton (motive (Quot.mk r a))] (q : Quot r) (f : (a : α) → motive (Quot.mk r a)) : motive q := by induction q using Quot.rec apply f apply Subsingleton.elim protected abbrev hrecOn (q : Quot r) (f : (a : α) → motive (Quot.mk r a)) (c : (a b : α) → (p : r a b) → f a ≅ f b) : motive q := Quot.recOn q f fun a b p => eqOfHEq <| have p₁ : Eq.ndrec (f a) (sound p) ≅ f a := eqRecHEq (sound p) (f a) HEq.trans p₁ (c a b p) end end Quot def Quotient {α : Sort u} (s : Setoid α) := @Quot α Setoid.r namespace Quotient @[inline] protected def mk {α : Sort u} [s : Setoid α] (a : α) : Quotient s := Quot.mk Setoid.r a def sound {α : Sort u} [s : Setoid α] {a b : α} : a ≈ b → Quotient.mk a = Quotient.mk b := Quot.sound protected abbrev lift {α : Sort u} {β : Sort v} [s : Setoid α] (f : α → β) : ((a b : α) → a ≈ b → f a = f b) → Quotient s → β := Quot.lift f protected theorem ind {α : Sort u} [s : Setoid α] {motive : Quotient s → Prop} : ((a : α) → motive (Quotient.mk a)) → (q : Quot Setoid.r) → motive q := Quot.ind protected abbrev liftOn {α : Sort u} {β : Sort v} [s : Setoid α] (q : Quotient s) (f : α → β) (c : (a b : α) → a ≈ b → f a = f b) : β := Quot.liftOn q f c protected theorem inductionOn {α : Sort u} [s : Setoid α] {motive : Quotient s → Prop} (q : Quotient s) (h : (a : α) → motive (Quotient.mk a)) : motive q := Quot.inductionOn q h theorem existsRep {α : Sort u} [s : Setoid α] (q : Quotient s) : Exists (fun (a : α) => Quotient.mk a = q) := Quot.existsRep q section variable {α : Sort u} variable [s : Setoid α] variable {motive : Quotient s → Sort v} @[inline] protected def rec (f : (a : α) → motive (Quotient.mk a)) (h : (a b : α) → (p : a ≈ b) → Eq.ndrec (f a) (Quotient.sound p) = f b) (q : Quotient s) : motive q := Quot.rec f h q protected abbrev recOn (q : Quotient s) (f : (a : α) → motive (Quotient.mk a)) (h : (a b : α) → (p : a ≈ b) → Eq.ndrec (f a) (Quotient.sound p) = f b) : motive q := Quot.recOn q f h protected abbrev recOnSubsingleton [h : (a : α) → Subsingleton (motive (Quotient.mk a))] (q : Quotient s) (f : (a : α) → motive (Quotient.mk a)) : motive q := Quot.recOnSubsingleton (h := h) q f protected abbrev hrecOn (q : Quotient s) (f : (a : α) → motive (Quotient.mk a)) (c : (a b : α) → (p : a ≈ b) → f a ≅ f b) : motive q := Quot.hrecOn q f c end section universes uA uB uC variables {α : Sort uA} {β : Sort uB} {φ : Sort uC} variables [s₁ : Setoid α] [s₂ : Setoid β] protected abbrev lift₂ (f : α → β → φ) (c : (a₁ : α) → (b₁ : β) → (a₂ : α) → (b₂ : β) → a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ = f a₂ b₂) (q₁ : Quotient s₁) (q₂ : Quotient s₂) : φ := by apply Quotient.lift (fun (a₁ : α) => Quotient.lift (f a₁) (fun (a b : β) => c a₁ a a₁ b (Setoid.refl a₁)) q₂) _ q₁ intros induction q₂ using Quotient.ind apply c; assumption; apply Setoid.refl protected abbrev liftOn₂ (q₁ : Quotient s₁) (q₂ : Quotient s₂) (f : α → β → φ) (c : (a₁ : α) → (b₁ : β) → (a₂ : α) → (b₂ : β) → a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ = f a₂ b₂) : φ := Quotient.lift₂ f c q₁ q₂ protected theorem ind₂ {motive : Quotient s₁ → Quotient s₂ → Prop} (h : (a : α) → (b : β) → motive (Quotient.mk a) (Quotient.mk b)) (q₁ : Quotient s₁) (q₂ : Quotient s₂) : motive q₁ q₂ := by induction q₁ using Quotient.ind induction q₂ using Quotient.ind apply h protected theorem inductionOn₂ {motive : Quotient s₁ → Quotient s₂ → Prop} (q₁ : Quotient s₁) (q₂ : Quotient s₂) (h : (a : α) → (b : β) → motive (Quotient.mk a) (Quotient.mk b)) : motive q₁ q₂ := by induction q₁ using Quotient.ind induction q₂ using Quotient.ind apply h protected theorem inductionOn₃ [s₃ : Setoid φ] {motive : Quotient s₁ → Quotient s₂ → Quotient s₃ → Prop} (q₁ : Quotient s₁) (q₂ : Quotient s₂) (q₃ : Quotient s₃) (h : (a : α) → (b : β) → (c : φ) → motive (Quotient.mk a) (Quotient.mk b) (Quotient.mk c)) : motive q₁ q₂ q₃ := by induction q₁ using Quotient.ind induction q₂ using Quotient.ind induction q₃ using Quotient.ind apply h end section Exact variable {α : Sort u} private def rel [s : Setoid α] (q₁ q₂ : Quotient s) : Prop := Quotient.liftOn₂ q₁ q₂ (fun a₁ a₂ => a₁ ≈ a₂) (fun a₁ a₂ b₁ b₂ a₁b₁ a₂b₂ => propext (Iff.intro (fun a₁a₂ => Setoid.trans (Setoid.symm a₁b₁) (Setoid.trans a₁a₂ a₂b₂)) (fun b₁b₂ => Setoid.trans a₁b₁ (Setoid.trans b₁b₂ (Setoid.symm a₂b₂))))) private theorem rel.refl [s : Setoid α] (q : Quotient s) : rel q q := Quot.inductionOn (motive := fun q => rel q q) q (fun a => Setoid.refl a) private theorem eqImpRel [s : Setoid α] {q₁ q₂ : Quotient s} : q₁ = q₂ → rel q₁ q₂ := fun h => Eq.ndrecOn h (rel.refl q₁) theorem exact [s : Setoid α] {a b : α} : Quotient.mk a = Quotient.mk b → a ≈ b := fun h => eqImpRel h end Exact section universes uA uB uC variables {α : Sort uA} {β : Sort uB} variables [s₁ : Setoid α] [s₂ : Setoid β] protected abbrev recOnSubsingleton₂ {motive : Quotient s₁ → Quotient s₂ → Sort uC} [s : (a : α) → (b : β) → Subsingleton (motive (Quotient.mk a) (Quotient.mk b))] (q₁ : Quotient s₁) (q₂ : Quotient s₂) (g : (a : α) → (b : β) → motive (Quotient.mk a) (Quotient.mk b)) : motive q₁ q₂ := by induction q₁ using Quot.recOnSubsingleton induction q₂ using Quot.recOnSubsingleton intro a; apply s induction q₂ using Quot.recOnSubsingleton intro a; apply s apply g end end Quotient section variable {α : Type u} variable (r : α → α → Prop) instance {α : Sort u} {s : Setoid α} [d : ∀ (a b : α), Decidable (a ≈ b)] : DecidableEq (Quotient s) := fun (q₁ q₂ : Quotient s) => Quotient.recOnSubsingleton₂ (motive := fun a b => Decidable (a = b)) q₁ q₂ (fun a₁ a₂ => match (d a₁ a₂) with | (isTrue h₁) => isTrue (Quotient.sound h₁) | (isFalse h₂) => isFalse (fun h => absurd (Quotient.exact h) h₂)) /- Function extensionality -/ namespace Function variables {α : Sort u} {β : α → Sort v} def Equiv (f₁ f₂ : ∀ (x : α), β x) : Prop := ∀ x, f₁ x = f₂ x protected theorem Equiv.refl (f : ∀ (x : α), β x) : Equiv f f := fun x => rfl protected theorem Equiv.symm {f₁ f₂ : ∀ (x : α), β x} : Equiv f₁ f₂ → Equiv f₂ f₁ := fun h x => Eq.symm (h x) protected theorem Equiv.trans {f₁ f₂ f₃ : ∀ (x : α), β x} : Equiv f₁ f₂ → Equiv f₂ f₃ → Equiv f₁ f₃ := fun h₁ h₂ x => Eq.trans (h₁ x) (h₂ x) protected theorem Equiv.isEquivalence (α : Sort u) (β : α → Sort v) : Equivalence (@Function.Equiv α β) := { refl := Equiv.refl, symm := Equiv.symm, trans := Equiv.trans } end Function section open Quotient variables {α : Sort u} {β : α → Sort v} @[instance] private def funSetoid (α : Sort u) (β : α → Sort v) : Setoid (∀ (x : α), β x) := Setoid.mk (@Function.Equiv α β) (Function.Equiv.isEquivalence α β) private def extfunApp (f : Quotient <| funSetoid α β) (x : α) : β x := Quot.liftOn f (fun (f : ∀ (x : α), β x) => f x) (fun f₁ f₂ h => h x) theorem funext {f₁ f₂ : ∀ (x : α), β x} (h : ∀ x, f₁ x = f₂ x) : f₁ = f₂ := by show extfunApp (Quotient.mk f₁) = extfunApp (Quotient.mk f₂) apply congrArg apply Quotient.sound exact h end instance {α : Sort u} {β : α → Sort v} [∀ a, Subsingleton (β a)] : Subsingleton (∀ a, β a) := ⟨fun f₁ f₂ => funext (fun a => Subsingleton.elim (f₁ a) (f₂ a))⟩ /- Squash -/ def Squash (α : Type u) := Quot (fun (a b : α) => True) def Squash.mk {α : Type u} (x : α) : Squash α := Quot.mk _ x theorem Squash.ind {α : Type u} {motive : Squash α → Prop} (h : ∀ (a : α), motive (Squash.mk a)) : ∀ (q : Squash α), motive q := Quot.ind h @[inline] def Squash.lift {α β} [Subsingleton β] (s : Squash α) (f : α → β) : β := Quot.lift f (fun a b _ => Subsingleton.elim _ _) s instance {α} : Subsingleton (Squash α) := ⟨fun a b => Squash.ind (motive := fun a => a = b) (fun a => Squash.ind (motive := fun b => Squash.mk a = b) (fun b => show Quot.mk _ a = Quot.mk _ b by apply Quot.sound; exact trivial) b) a⟩ namespace Lean /- Kernel reduction hints -/ /-- When the kernel tries to reduce a term `Lean.reduceBool c`, it will invoke the Lean interpreter to evaluate `c`. The kernel will not use the interpreter if `c` is not a constant. This feature is useful for performing proofs by reflection. Remark: the Lean frontend allows terms of the from `Lean.reduceBool t` where `t` is a term not containing free variables. The frontend automatically declares a fresh auxiliary constant `c` and replaces the term with `Lean.reduceBool c`. The main motivation is that the code for `t` will be pre-compiled. Warning: by using this feature, the Lean compiler and interpreter become part of your trusted code base. This is extra 30k lines of code. More importantly, you will probably not be able to check your developement using external type checkers (e.g., Trepplein) that do not implement this feature. Keep in mind that if you are using Lean as programming language, you are already trusting the Lean compiler and interpreter. So, you are mainly losing the capability of type checking your developement using external checkers. Recall that the compiler trusts the correctness of all `[implementedBy ...]` and `[extern ...]` annotations. If an extern function is executed, then the trusted code base will also include the implementation of the associated foreign function. -/ constant reduceBool (b : Bool) : Bool := b /-- Similar to `Lean.reduceBool` for closed `Nat` terms. Remark: we do not have plans for supporting a generic `reduceValue {α} (a : α) : α := a`. The main issue is that it is non-trivial to convert an arbitrary runtime object back into a Lean expression. We believe `Lean.reduceBool` enables most interesting applications (e.g., proof by reflection). -/ constant reduceNat (n : Nat) : Nat := n axiom ofReduceBool (a b : Bool) (h : reduceBool a = b) : a = b axiom ofReduceNat (a b : Nat) (h : reduceNat a = b) : a = b end Lean
833574307a13cb7df854946eb9a436f1a2c22d23
7cef822f3b952965621309e88eadf618da0c8ae9
/src/linear_algebra/sesquilinear_form.lean
e48724c3387ce6a8c476492818e3ccf386d1979f
[ "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
8,616
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 M, is a function from M x M 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 S 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 (R : Type u) (M : Type v) [ring R] (I : ring_anti_equiv R R) [add_comm_group M] [module R M] := (sesq : M → M → R) (sesq_add_left : ∀ (x y z : M), sesq (x + y) z = sesq x z + sesq y z) (sesq_smul_left : ∀ (a : R) (x y : M), sesq (a • x) y = a * (sesq x y)) (sesq_add_right : ∀ (x y z : M), sesq x (y + z) = sesq x y + sesq x z) (sesq_smul_right : ∀ (a : R) (x y : M), sesq x (a • y) = (I a) * (sesq x y)) namespace sesq_form section general_ring variables {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : ring_anti_equiv R R} {S : sesq_form R M I} instance : has_coe_to_fun (sesq_form R M I) := ⟨_, λ S, S.sesq⟩ lemma add_left (x y z : M) : S (x + y) z = S x z + S y z := sesq_add_left S x y z lemma smul_left (a : R) (x y : M) : S (a • x) y = a * (S x y) := sesq_smul_left S a x y lemma add_right (x y z : M) : S x (y + z) = S x y + S x z := sesq_add_right S x y z lemma smul_right (a : R) (x y : M) : S x (a • y) = (I a) * (S x y) := sesq_smul_right S a x y lemma zero_left (x : M) : S 0 x = 0 := by {rw [←@zero_smul R _ _ _ _ (0 : M), smul_left, zero_mul]} lemma zero_right (x : M) : S x 0 = 0 := by rw [←@zero_smul _ _ _ _ _ (0 : M), smul_right, map_zero, ring.zero_mul] lemma neg_left (x y : M) : S (-x) y = -(S x y) := by rw [←@neg_one_smul R _ _, smul_left, neg_one_mul] lemma neg_right (x y : M) : S x (-y) = -(S x y) := by rw [←@neg_one_smul R _ _, smul_right, map_neg_one, neg_one_mul] lemma sub_left (x y z : M) : 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 : M) : 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 R M I} @[ext] lemma ext (H : ∀ (x y : M), S x y = D x y) : S = D := by {cases S, cases D, congr, funext, exact H _ _} instance : add_comm_group (sesq_form R M 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} } /-- The proposition that two elements of a sesquilinear form space are orthogonal -/ def is_ortho (S : sesq_form R M I) (x y : M) : Prop := S x y = 0 lemma ortho_zero (x : M) : is_ortho S (0 : M) x := zero_left x end general_ring section comm_ring variables {R : Type*} [comm_ring R] {M : Type v} [add_comm_group M] [module R M] {J : ring_anti_equiv R R} (F : sesq_form R M J) (f : M → M) instance to_module : module R (sesq_form R M 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 comm_ring section domain variables {R : Type*} [domain R] {M : Type v} [add_comm_group M] [module R M] {K : ring_anti_equiv R R} {G : sesq_form R M K} theorem ortho_smul_left {x y : M} {a : R} (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 : M} {a : R} (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 domain end sesq_form namespace refl_sesq_form open refl_sesq_form sesq_form variables {R : Type*} {M : Type*} [ring R] [add_comm_group M] [module R M] {I : ring_anti_equiv R R} {S : sesq_form R M I} /-- The proposition that a sesquilinear form is reflexive -/ def is_refl (S : sesq_form R M I) : Prop := ∀ (x y : M), S x y = 0 → S y x = 0 variable (H : is_refl S) lemma eq_zero : ∀ {x y : M}, S x y = 0 → S y x = 0 := λ x y, H x y lemma ortho_sym {x y : M} : 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 {R : Type*} {M : Type*} [ring R] [add_comm_group M] [module R M] {I : ring_anti_equiv R R} {S : sesq_form R M I} /-- The proposition that a sesquilinear form is symmetric -/ def is_sym (S : sesq_form R M I) : Prop := ∀ (x y : M), I (S x y) = S y x variable (H : is_sym S) include H lemma sym (x y : M) : 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 : M} : 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 {R : Type*} {M : Type*} [ring R] [add_comm_group M] [module R M] {I : ring_anti_equiv R R} {S : sesq_form R M I} /-- The proposition that a sesquilinear form is alternating -/ def is_alt (S : sesq_form R M I) : Prop := ∀ (x : M), S x x = 0 variable (H : is_alt S) include H lemma self_eq_zero (x : M) : S x x = 0 := H x lemma neg (x y : M) : - 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
f5e2b593d9d8c0e96071128cc13411b254152065
c777c32c8e484e195053731103c5e52af26a25d1
/src/geometry/euclidean/sphere/ptolemy.lean
aa5d6eaa4fec350493a1b51b9eaea53cebe7b855
[ "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
3,420
lean
/- Copyright (c) 2021 Manuel Candales. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Manuel Candales, Benjamin Davidson -/ import geometry.euclidean.sphere.power import geometry.euclidean.triangle /-! # Ptolemy's theorem This file proves Ptolemy's theorem on the lengths of the diagonals and sides of a cyclic quadrilateral. ## Main theorems * `mul_dist_add_mul_dist_eq_mul_dist_of_cospherical`: Ptolemy’s Theorem (Freek No. 95). TODO: The current statement of Ptolemy’s theorem works around the lack of a "cyclic polygon" concept in mathlib, which is what the theorem statement would naturally use (or two such concepts, since both a strict version, where all vertices must be distinct, and a weak version, where consecutive vertices may be equal, would be useful; Ptolemy's theorem should then use the weak one). An API needs to be built around that concept, which would include: - strict cyclic implies weak cyclic, - weak cyclic and consecutive points distinct implies strict cyclic, - weak/strict cyclic implies weak/strict cyclic for any subsequence, - any three points on a sphere are weakly or strictly cyclic according to whether they are distinct, - any number of points on a sphere intersected with a two-dimensional affine subspace are cyclic in some order, - a list of points is cyclic if and only if its reversal is, - a list of points is cyclic if and only if any cyclic permutation is, while other permutations are not when the points are distinct, - a point P where the diagonals of a cyclic polygon cross exists (and is unique) with weak/strict betweenness depending on weak/strict cyclicity, - four points on a sphere with such a point P are cyclic in the appropriate order, and so on. -/ open real open_locale euclidean_geometry real_inner_product_space real namespace euclidean_geometry variables {V : Type*} [normed_add_comm_group V] [inner_product_space ℝ V] variables {P : Type*} [metric_space P] [normed_add_torsor V P] include V /-- **Ptolemy’s Theorem**. -/ theorem mul_dist_add_mul_dist_eq_mul_dist_of_cospherical {a b c d p : P} (h : cospherical ({a, b, c, d} : set P)) (hapc : ∠ a p c = π) (hbpd : ∠ b p d = π) : dist a b * dist c d + dist b c * dist d a = dist a c * dist b d := begin have h' : cospherical ({a, c, b, d} : set P), { rwa set.insert_comm c b {d} }, have hmul := mul_dist_eq_mul_dist_of_cospherical_of_angle_eq_pi h' hapc hbpd, have hbp := left_dist_ne_zero_of_angle_eq_pi hbpd, have h₁ : dist c d = dist c p / dist b p * dist a b, { rw [dist_mul_of_eq_angle_of_dist_mul b p a c p d, dist_comm a b], { rw [angle_eq_angle_of_angle_eq_pi_of_angle_eq_pi hbpd hapc, angle_comm] }, all_goals { field_simp [mul_comm, hmul] } }, have h₂ : dist d a = dist a p / dist b p * dist b c, { rw [dist_mul_of_eq_angle_of_dist_mul c p b d p a, dist_comm c b], { rwa [angle_comm, angle_eq_angle_of_angle_eq_pi_of_angle_eq_pi], rwa angle_comm }, all_goals { field_simp [mul_comm, hmul] } }, have h₃ : dist d p = dist a p * dist c p / dist b p, { field_simp [mul_comm, hmul] }, have h₄ : ∀ x y : ℝ, x * (y * x) = x * x * y := λ x y, by rw [mul_left_comm, mul_comm], field_simp [h₁, h₂, dist_eq_add_dist_of_angle_eq_pi hbpd, h₃, hbp, dist_comm a b, h₄, ← sq, dist_sq_mul_dist_add_dist_sq_mul_dist b, hapc], end end euclidean_geometry
af7965c075c5df49398af36e5c3675057b07c6ce
64874bd1010548c7f5a6e3e8902efa63baaff785
/tests/lean/run/e15.lean
3ef931c2f850a685c2fe417eee05bdb1e6e00fc9
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
708
lean
prelude inductive nat : Type := zero : nat, succ : nat → nat namespace nat end nat open nat inductive list (A : Type) : Type := nil {} : list A, cons : A → list A → list A namespace list end list open list check nil check nil.{1} check @nil.{1} nat check @nil nat check cons zero nil inductive vector (A : Type) : nat → Type := vnil {} : vector A zero, vcons : forall {n : nat}, A → vector A n → vector A (succ n) namespace vector end vector open vector check vcons zero vnil constant n : nat check vcons n vnil check vector.rec definition vector_to_list {A : Type} {n : nat} (v : vector A n) : list A := vector.rec nil (fun (n : nat) (a : A) (v : vector A n) (l : list A), cons a l) v
d763cb37afa797a622c1aea1417c5dcc9012775a
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/polynomial/basic_auto.lean
6837f1c83e77e227f40dbb7939f39e31cdd97f4a
[]
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
7,946
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.ring_exp import Mathlib.tactic.chain import Mathlib.algebra.monoid_algebra import Mathlib.data.finset.sort import Mathlib.PostPort universes u_1 u namespace Mathlib /-! # Theory of univariate polynomials Polynomials are represented as `add_monoid_algebra R ℕ`, where `R` is a commutative semiring. In this file, we define `polynomial`, provide basic instances, and prove an `ext` lemma. -/ /-- `polynomial R` is the type of univariate polynomials over `R`. Polynomials should be seen as (semi-)rings with the additional constructor `X`. The embedding from `R` is called `C`. -/ def polynomial (R : Type u_1) [semiring R] := add_monoid_algebra R ℕ namespace polynomial protected instance inhabited {R : Type u} [semiring R] : Inhabited (polynomial R) := add_monoid_algebra.inhabited R ℕ protected instance semiring {R : Type u} [semiring R] : semiring (polynomial R) := add_monoid_algebra.semiring protected instance semimodule {R : Type u} [semiring R] {S : Type u_1} [semiring S] [semimodule S R] : semimodule S (polynomial R) := add_monoid_algebra.semimodule protected instance unique {R : Type u} [semiring R] [subsingleton R] : unique (polynomial R) := add_monoid_algebra.unique @[simp] theorem support_zero {R : Type u} [semiring R] : finsupp.support 0 = ∅ := rfl /-- `monomial s a` is the monomial `a * X^s` -/ def monomial {R : Type u} [semiring R] (n : ℕ) : linear_map R R (polynomial R) := finsupp.lsingle n theorem monomial_zero_right {R : Type u} [semiring R] (n : ℕ) : coe_fn (monomial n) 0 = 0 := finsupp.single_zero theorem monomial_def {R : Type u} [semiring R] (n : ℕ) (a : R) : coe_fn (monomial n) a = finsupp.single n a := rfl theorem monomial_add {R : Type u} [semiring R] (n : ℕ) (r : R) (s : R) : coe_fn (monomial n) (r + s) = coe_fn (monomial n) r + coe_fn (monomial n) s := finsupp.single_add theorem monomial_mul_monomial {R : Type u} [semiring R] (n : ℕ) (m : ℕ) (r : R) (s : R) : coe_fn (monomial n) r * coe_fn (monomial m) s = coe_fn (monomial (n + m)) (r * s) := add_monoid_algebra.single_mul_single theorem smul_monomial {R : Type u} [semiring R] {S : Type u_1} [semiring S] [semimodule S R] (a : S) (n : ℕ) (b : R) : a • coe_fn (monomial n) b = coe_fn (monomial n) (a • b) := finsupp.smul_single a n b /-- `X` is the polynomial variable (aka indeterminant). -/ def X {R : Type u} [semiring R] : polynomial R := coe_fn (monomial 1) 1 /-- `X` commutes with everything, even when the coefficients are noncommutative. -/ theorem X_mul {R : Type u} [semiring R] {p : polynomial R} : X * p = p * X := sorry theorem X_pow_mul {R : Type u} [semiring R] {p : polynomial R} {n : ℕ} : X ^ n * p = p * X ^ n := sorry theorem X_pow_mul_assoc {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R} {n : ℕ} : p * X ^ n * q = p * q * X ^ n := sorry theorem commute_X {R : Type u} [semiring R] (p : polynomial R) : commute X p := X_mul /-- coeff p n is the coefficient of X^n in p -/ def coeff {R : Type u} [semiring R] (p : polynomial R) : ℕ → R := ⇑p @[simp] theorem coeff_mk {R : Type u} [semiring R] (s : finset ℕ) (f : ℕ → R) (h : ∀ (a : ℕ), a ∈ s ↔ f a ≠ 0) : coeff (finsupp.mk s f h) = f := rfl theorem coeff_monomial {R : Type u} {a : R} {m : ℕ} {n : ℕ} [semiring R] : coeff (coe_fn (monomial n) a) m = ite (n = m) a 0 := sorry @[simp] theorem coeff_zero {R : Type u} [semiring R] (n : ℕ) : coeff 0 n = 0 := rfl @[simp] theorem coeff_one_zero {R : Type u} [semiring R] : coeff 1 0 = 1 := coeff_monomial @[simp] theorem coeff_X_one {R : Type u} [semiring R] : coeff X 1 = 1 := coeff_monomial @[simp] theorem coeff_X_zero {R : Type u} [semiring R] : coeff X 0 = 0 := coeff_monomial theorem coeff_X {R : Type u} {n : ℕ} [semiring R] : coeff X n = ite (1 = n) 1 0 := coeff_monomial theorem coeff_X_of_ne_one {R : Type u} [semiring R] {n : ℕ} (hn : n ≠ 1) : coeff X n = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (coeff X n = 0)) coeff_X)) (eq.mpr (id (Eq._oldrec (Eq.refl (ite (1 = n) 1 0 = 0)) (if_neg (ne.symm hn)))) (Eq.refl 0)) theorem ext_iff {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R} : p = q ↔ ∀ (n : ℕ), coeff p n = coeff q n := finsupp.ext_iff theorem ext {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R} : (∀ (n : ℕ), coeff p n = coeff q n) → p = q := finsupp.ext theorem add_hom_ext' {R : Type u} [semiring R] {M : Type u_1} [add_monoid M] {f : polynomial R →+ M} {g : polynomial R →+ M} (h : ∀ (n : ℕ), add_monoid_hom.comp f (linear_map.to_add_monoid_hom (monomial n)) = add_monoid_hom.comp g (linear_map.to_add_monoid_hom (monomial n))) : f = g := finsupp.add_hom_ext' h theorem add_hom_ext {R : Type u} [semiring R] {M : Type u_1} [add_monoid M] {f : polynomial R →+ M} {g : polynomial R →+ M} (h : ∀ (n : ℕ) (a : R), coe_fn f (coe_fn (monomial n) a) = coe_fn g (coe_fn (monomial n) a)) : f = g := finsupp.add_hom_ext h theorem lhom_ext' {R : Type u} [semiring R] {M : Type u_1} [add_comm_monoid M] [semimodule R M] {f : linear_map R (polynomial R) M} {g : linear_map R (polynomial R) M} (h : ∀ (n : ℕ), linear_map.comp f (monomial n) = linear_map.comp g (monomial n)) : f = g := finsupp.lhom_ext' h -- this has the same content as the subsingleton theorem eq_zero_of_eq_zero {R : Type u} [semiring R] (h : 0 = 1) (p : polynomial R) : p = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (p = 0)) (Eq.symm (one_smul R p)))) (eq.mpr (id (Eq._oldrec (Eq.refl (1 • p = 0)) (Eq.symm h))) (eq.mpr (id (Eq._oldrec (Eq.refl (0 • p = 0)) (zero_smul R p))) (Eq.refl 0))) theorem support_monomial {R : Type u} [semiring R] (n : ℕ) (a : R) (H : a ≠ 0) : finsupp.support (coe_fn (monomial n) a) = singleton n := finsupp.support_single_ne_zero H theorem support_monomial' {R : Type u} [semiring R] (n : ℕ) (a : R) : finsupp.support (coe_fn (monomial n) a) ⊆ singleton n := finsupp.support_single_subset theorem X_pow_eq_monomial {R : Type u} [semiring R] (n : ℕ) : X ^ n = coe_fn (monomial n) 1 := sorry theorem support_X_pow {R : Type u} [semiring R] (H : ¬1 = 0) (n : ℕ) : finsupp.support (X ^ n) = singleton n := sorry theorem support_X_empty {R : Type u} [semiring R] (H : 1 = 0) : finsupp.support X = ∅ := sorry theorem support_X {R : Type u} [semiring R] (H : ¬1 = 0) : finsupp.support X = singleton 1 := eq.mpr (id (Eq._oldrec (Eq.refl (finsupp.support X = singleton 1)) (Eq.symm (pow_one X)))) (eq.mpr (id (Eq._oldrec (Eq.refl (finsupp.support (X ^ 1) = singleton 1)) (support_X_pow H 1))) (Eq.refl (singleton 1))) protected instance comm_semiring {R : Type u} [comm_semiring R] : comm_semiring (polynomial R) := add_monoid_algebra.comm_semiring protected instance ring {R : Type u} [ring R] : ring (polynomial R) := add_monoid_algebra.ring @[simp] theorem coeff_neg {R : Type u} [ring R] (p : polynomial R) (n : ℕ) : coeff (-p) n = -coeff p n := rfl @[simp] theorem coeff_sub {R : Type u} [ring R] (p : polynomial R) (q : polynomial R) (n : ℕ) : coeff (p - q) n = coeff p n - coeff q n := rfl protected instance comm_ring {R : Type u} [comm_ring R] : comm_ring (polynomial R) := add_monoid_algebra.comm_ring protected instance nontrivial {R : Type u} [semiring R] [nontrivial R] : nontrivial (polynomial R) := add_monoid_algebra.nontrivial theorem X_ne_zero {R : Type u} [semiring R] [nontrivial R] : X ≠ 0 := sorry protected instance has_repr {R : Type u} [semiring R] [has_repr R] : has_repr (polynomial R) := sorry end Mathlib
80dc714fed90c676badce9d1af7cdfa3bd7fde64
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/measure_theory/measure/portmanteau.lean
634dd2cf2dbff474a6ec471548f4d27df9927916
[ "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
22,733
lean
/- Copyright (c) 2021 Kalle Kytölä. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kalle Kytölä -/ import measure_theory.measure.probability_measure /-! # Characterizations of weak convergence of finite measures and probability measures This file will provide portmanteau characterizations of the weak convergence of finite measures and of probability measures, i.e., the standard characterizations of convergence in distribution. ## Main definitions This file does not introduce substantial new definitions: the topologies of weak convergence on the types of finite measures and probability measures are already defined in their corresponding files. ## Main results The main result will be the portmanteau theorem providing various characterizations of the weak convergence of measures. The separate implications are: * `measure_theory.finite_measure.limsup_measure_closed_le_of_tendsto` proves that weak convergence implies a limsup-condition for closed sets. * `measure_theory.limsup_measure_closed_le_iff_liminf_measure_open_ge` proves for probability measures the equivalence of the limsup condition for closed sets and the liminf condition for open sets. * `measure_theory.tendsto_measure_of_null_frontier` proves that the liminf condition for open sets (which is equivalent to the limsup condition for closed sets) implies the convergence of probabilities of sets whose boundary carries no mass under the limit measure. * `measure_theory.probability_measure.tendsto_measure_of_null_frontier_of_tendsto` is a combination of earlier implications, which shows that weak convergence of probability measures implies the convergence of probabilities of sets whose boundary carries no mass under the limit measure. TODO: * Prove the rest of the implications. ## Implementation notes Many of the characterizations of weak convergence hold for finite measures and are proven in that generality and then specialized to probability measures. Some implications hold with slightly weaker assumptions than usually stated. The full portmanteau theorem, however, is most convenient for probability measures on metrizable spaces with their Borel sigmas. Some specific considerations on the assumptions in the different implications: * `measure_theory.finite_measure.limsup_measure_closed_le_of_tendsto` assumes `pseudo_emetric_space`. The only reason is to have bounded continuous pointwise approximations to the indicator function of a closed set. Clearly for example metrizability or pseudo-emetrizability would be sufficient assumptions. The typeclass assumptions should be later adjusted in a way that takes into account use cases, but the proof will presumably remain essentially the same. * Where formulations are currently only provided for probability measures, one can obtain the finite measure formulations using the characterization of convergence of finite measures by their total masses and their probability-normalized versions, i.e., by `measure_theory.finite_measure.tendsto_normalize_iff_tendsto`. ## References * [Billingsley, *Convergence of probability measures*][billingsley1999] ## Tags weak convergence of measures, convergence in distribution, convergence in law, finite measure, probability measure -/ noncomputable theory open measure_theory open set open filter open bounded_continuous_function open_locale topological_space ennreal nnreal bounded_continuous_function namespace measure_theory section limsup_closed_le_and_le_liminf_open /-! ### Portmanteau: limsup condition for closed sets iff liminf condition for open sets In this section we prove that for a sequence of Borel probability measures on a topological space and its candidate limit measure, the following two conditions are equivalent: (C) For any closed set `F` in `Ω` the limsup of the measures of `F` is at most the limit measure of `F`. (O) For any open set `G` in `Ω` the liminf of the measures of `G` is at least the limit measure of `G`. Either of these will later be shown to be equivalent to the weak convergence of the sequence of measures. -/ variables {Ω : Type*} [measurable_space Ω] lemma le_measure_compl_liminf_of_limsup_measure_le {ι : Type*} {L : filter ι} {μ : measure Ω} {μs : ι → measure Ω} [is_probability_measure μ] [∀ i, is_probability_measure (μs i)] {E : set Ω} (E_mble : measurable_set E) (h : L.limsup (λ i, μs i E) ≤ μ E) : μ Eᶜ ≤ L.liminf (λ i, μs i Eᶜ) := begin by_cases L_bot : L = ⊥, { simp only [L_bot, le_top, (show liminf (λ i, μs i Eᶜ) ⊥ = ⊤, by simp only [liminf, filter.map_bot, Liminf_bot])], }, haveI : L.ne_bot, from {ne' := L_bot}, have meas_Ec : μ Eᶜ = 1 - μ E, { simpa only [measure_univ] using measure_compl E_mble (measure_lt_top μ E).ne, }, have meas_i_Ec : ∀ i, μs i Eᶜ = 1 - μs i E, { intro i, simpa only [measure_univ] using measure_compl E_mble (measure_lt_top (μs i) E).ne, }, simp_rw [meas_Ec, meas_i_Ec], have obs : L.liminf (λ (i : ι), 1 - μs i E) = L.liminf ((λ x, 1 - x) ∘ (λ (i : ι), μs i E)), by refl, rw obs, simp_rw ← antitone_const_tsub.map_limsup_of_continuous_at (λ i, μs i E) (ennreal.continuous_sub_left ennreal.one_ne_top).continuous_at, exact antitone_const_tsub h, end lemma le_measure_liminf_of_limsup_measure_compl_le {ι : Type*} {L : filter ι} {μ : measure Ω} {μs : ι → measure Ω} [is_probability_measure μ] [∀ i, is_probability_measure (μs i)] {E : set Ω} (E_mble : measurable_set E) (h : L.limsup (λ i, μs i Eᶜ) ≤ μ Eᶜ) : μ E ≤ L.liminf (λ i, μs i E) := compl_compl E ▸ (le_measure_compl_liminf_of_limsup_measure_le (measurable_set.compl E_mble) h) lemma limsup_measure_compl_le_of_le_liminf_measure {ι : Type*} {L : filter ι} {μ : measure Ω} {μs : ι → measure Ω} [is_probability_measure μ] [∀ i, is_probability_measure (μs i)] {E : set Ω} (E_mble : measurable_set E) (h : μ E ≤ L.liminf (λ i, μs i E)) : L.limsup (λ i, μs i Eᶜ) ≤ μ Eᶜ := begin by_cases L_bot : L = ⊥, { simp only [L_bot, bot_le, (show limsup (λ i, μs i Eᶜ) ⊥ = ⊥, by simp only [limsup, filter.map_bot, Limsup_bot])], }, haveI : L.ne_bot, from {ne' := L_bot}, have meas_Ec : μ Eᶜ = 1 - μ E, { simpa only [measure_univ] using measure_compl E_mble (measure_lt_top μ E).ne, }, have meas_i_Ec : ∀ i, μs i Eᶜ = 1 - μs i E, { intro i, simpa only [measure_univ] using measure_compl E_mble (measure_lt_top (μs i) E).ne, }, simp_rw [meas_Ec, meas_i_Ec], have obs : L.limsup (λ (i : ι), 1 - μs i E) = L.limsup ((λ x, 1 - x) ∘ (λ (i : ι), μs i E)), by refl, rw obs, simp_rw ← antitone_const_tsub.map_liminf_of_continuous_at (λ i, μs i E) (ennreal.continuous_sub_left ennreal.one_ne_top).continuous_at, exact antitone_const_tsub h, end lemma limsup_measure_le_of_le_liminf_measure_compl {ι : Type*} {L : filter ι} {μ : measure Ω} {μs : ι → measure Ω} [is_probability_measure μ] [∀ i, is_probability_measure (μs i)] {E : set Ω} (E_mble : measurable_set E) (h : μ Eᶜ ≤ L.liminf (λ i, μs i Eᶜ)) : L.limsup (λ i, μs i E) ≤ μ E := compl_compl E ▸ (limsup_measure_compl_le_of_le_liminf_measure (measurable_set.compl E_mble) h) variables [topological_space Ω] [opens_measurable_space Ω] /-- One pair of implications of the portmanteau theorem: For a sequence of Borel probability measures, the following two are equivalent: (C) The limsup of the measures of any closed set is at most the measure of the closed set under a candidate limit measure. (O) The liminf of the measures of any open set is at least the measure of the open set under a candidate limit measure. -/ lemma limsup_measure_closed_le_iff_liminf_measure_open_ge {ι : Type*} {L : filter ι} {μ : measure Ω} {μs : ι → measure Ω} [is_probability_measure μ] [∀ i, is_probability_measure (μs i)] : (∀ F, is_closed F → L.limsup (λ i, μs i F) ≤ μ F) ↔ (∀ G, is_open G → μ G ≤ L.liminf (λ i, μs i G)) := begin split, { intros h G G_open, exact le_measure_liminf_of_limsup_measure_compl_le G_open.measurable_set (h Gᶜ (is_closed_compl_iff.mpr G_open)), }, { intros h F F_closed, exact limsup_measure_le_of_le_liminf_measure_compl F_closed.measurable_set (h Fᶜ (is_open_compl_iff.mpr F_closed)), }, end end limsup_closed_le_and_le_liminf_open -- section section tendsto_of_null_frontier /-! ### Portmanteau: limit of measures of Borel sets whose boundary carries no mass in the limit In this section we prove that for a sequence of Borel probability measures on a topological space and its candidate limit measure, either of the following equivalent conditions: (C) For any closed set `F` in `Ω` the limsup of the measures of `F` is at most the limit measure of `F` (O) For any open set `G` in `Ω` the liminf of the measures of `G` is at least the limit measure of `G` implies that (B) For any Borel set `E` in `Ω` whose boundary `∂E` carries no mass under the candidate limit measure, we have that the limit of measures of `E` is the measure of `E` under the candidate limit measure. -/ variables {Ω : Type*} [measurable_space Ω] lemma tendsto_measure_of_le_liminf_measure_of_limsup_measure_le {ι : Type*} {L : filter ι} {μ : measure Ω} {μs : ι → measure Ω} {E₀ E E₁ : set Ω} (E₀_subset : E₀ ⊆ E) (subset_E₁ : E ⊆ E₁) (nulldiff : μ (E₁ \ E₀) = 0) (h_E₀ : μ E₀ ≤ L.liminf (λ i, μs i E₀)) (h_E₁ : L.limsup (λ i, μs i E₁) ≤ μ E₁) : L.tendsto (λ i, μs i E) (𝓝 (μ E)) := begin apply tendsto_of_le_liminf_of_limsup_le, { have E₀_ae_eq_E : E₀ =ᵐ[μ] E, from eventually_le.antisymm E₀_subset.eventually_le (subset_E₁.eventually_le.trans (ae_le_set.mpr nulldiff)), calc μ(E) = μ(E₀) : measure_congr E₀_ae_eq_E.symm ... ≤ L.liminf (λ i, μs i E₀) : h_E₀ ... ≤ L.liminf (λ i, μs i E) : _, { refine liminf_le_liminf (eventually_of_forall (λ _, measure_mono E₀_subset)) _, apply_auto_param, }, }, { have E_ae_eq_E₁ : E =ᵐ[μ] E₁, from eventually_le.antisymm subset_E₁.eventually_le ((ae_le_set.mpr nulldiff).trans E₀_subset.eventually_le), calc L.limsup (λ i, μs i E) ≤ L.limsup (λ i, μs i E₁) : _ ... ≤ μ E₁ : h_E₁ ... = μ E : measure_congr E_ae_eq_E₁.symm, { refine limsup_le_limsup (eventually_of_forall (λ _, measure_mono subset_E₁)) _, apply_auto_param, }, }, end variables [topological_space Ω] [opens_measurable_space Ω] /-- One implication of the portmanteau theorem: For a sequence of Borel probability measures, if the liminf of the measures of any open set is at least the measure of the open set under a candidate limit measure, then for any set whose boundary carries no probability mass under the candidate limit measure, then its measures under the sequence converge to its measure under the candidate limit measure. -/ lemma tendsto_measure_of_null_frontier {ι : Type*} {L : filter ι} {μ : measure Ω} {μs : ι → measure Ω} [is_probability_measure μ] [∀ i, is_probability_measure (μs i)] (h_opens : ∀ G, is_open G → μ G ≤ L.liminf (λ i, μs i G)) {E : set Ω} (E_nullbdry : μ (frontier E) = 0) : L.tendsto (λ i, μs i E) (𝓝 (μ E)) := begin have h_closeds : ∀ F, is_closed F → L.limsup (λ i, μs i F) ≤ μ F, from limsup_measure_closed_le_iff_liminf_measure_open_ge.mpr h_opens, exact tendsto_measure_of_le_liminf_measure_of_limsup_measure_le interior_subset subset_closure E_nullbdry (h_opens _ is_open_interior) (h_closeds _ is_closed_closure), end end tendsto_of_null_frontier --section section convergence_implies_limsup_closed_le /-! ### Portmanteau implication: weak convergence implies a limsup condition for closed sets In this section we prove, under the assumption that the underlying topological space `Ω` is pseudo-emetrizable, that the weak convergence of measures on `measure_theory.finite_measure Ω` implies that for any closed set `F` in `Ω` the limsup of the measures of `F` is at most the limit measure of `F`. This is one implication of the portmanteau theorem characterizing weak convergence of measures. Combining with an earlier implication we also get that weak convergence implies that for any Borel set `E` in `Ω` whose boundary `∂E` carries no mass under the limit measure, the limit of measures of `E` is the measure of `E` under the limit measure. -/ variables {Ω : Type*} [measurable_space Ω] /-- If bounded continuous functions tend to the indicator of a measurable set and are uniformly bounded, then their integrals against a finite measure tend to the measure of the set. This formulation assumes: * the functions tend to a limit along a countably generated filter; * the limit is in the almost everywhere sense; * boundedness holds almost everywhere. -/ lemma measure_of_cont_bdd_of_tendsto_filter_indicator {ι : Type*} {L : filter ι} [L.is_countably_generated] [topological_space Ω] [opens_measurable_space Ω] (μ : measure Ω) [is_finite_measure μ] {c : ℝ≥0} {E : set Ω} (E_mble : measurable_set E) (fs : ι → (Ω →ᵇ ℝ≥0)) (fs_bdd : ∀ᶠ i in L, ∀ᵐ (ω : Ω) ∂μ, fs i ω ≤ c) (fs_lim : ∀ᵐ (ω : Ω) ∂μ, tendsto (λ (i : ι), (coe_fn : (Ω →ᵇ ℝ≥0) → (Ω → ℝ≥0)) (fs i) ω) L (𝓝 (indicator E (λ x, (1 : ℝ≥0)) ω))) : tendsto (λ n, lintegral μ (λ ω, fs n ω)) L (𝓝 (μ E)) := begin convert finite_measure.tendsto_lintegral_nn_filter_of_le_const μ fs_bdd fs_lim, have aux : ∀ ω, indicator E (λ ω, (1 : ℝ≥0∞)) ω = ↑(indicator E (λ ω, (1 : ℝ≥0)) ω), from λ ω, by simp only [ennreal.coe_indicator, ennreal.coe_one], simp_rw [←aux, lintegral_indicator _ E_mble], simp only [lintegral_one, measure.restrict_apply, measurable_set.univ, univ_inter], end /-- If a sequence of bounded continuous functions tends to the indicator of a measurable set and the functions are uniformly bounded, then their integrals against a finite measure tend to the measure of the set. A similar result with more general assumptions is `measure_theory.measure_of_cont_bdd_of_tendsto_filter_indicator`. -/ lemma measure_of_cont_bdd_of_tendsto_indicator [topological_space Ω] [opens_measurable_space Ω] (μ : measure Ω) [is_finite_measure μ] {c : ℝ≥0} {E : set Ω} (E_mble : measurable_set E) (fs : ℕ → (Ω →ᵇ ℝ≥0)) (fs_bdd : ∀ n ω, fs n ω ≤ c) (fs_lim : tendsto (λ (n : ℕ), (coe_fn : (Ω →ᵇ ℝ≥0) → (Ω → ℝ≥0)) (fs n)) at_top (𝓝 (indicator E (λ x, (1 : ℝ≥0))))) : tendsto (λ n, lintegral μ (λ ω, fs n ω)) at_top (𝓝 (μ E)) := begin have fs_lim' : ∀ ω, tendsto (λ (n : ℕ), (fs n ω : ℝ≥0)) at_top (𝓝 (indicator E (λ x, (1 : ℝ≥0)) ω)), by { rw tendsto_pi_nhds at fs_lim, exact λ ω, fs_lim ω, }, apply measure_of_cont_bdd_of_tendsto_filter_indicator μ E_mble fs (eventually_of_forall (λ n, eventually_of_forall (fs_bdd n))) (eventually_of_forall fs_lim'), end /-- The integrals of thickened indicators of a closed set against a finite measure tend to the measure of the closed set if the thickening radii tend to zero. -/ lemma tendsto_lintegral_thickened_indicator_of_is_closed {Ω : Type*} [measurable_space Ω] [pseudo_emetric_space Ω] [opens_measurable_space Ω] (μ : measure Ω) [is_finite_measure μ] {F : set Ω} (F_closed : is_closed F) {δs : ℕ → ℝ} (δs_pos : ∀ n, 0 < δs n) (δs_lim : tendsto δs at_top (𝓝 0)) : tendsto (λ n, lintegral μ (λ ω, (thickened_indicator (δs_pos n) F ω : ℝ≥0∞))) at_top (𝓝 (μ F)) := begin apply measure_of_cont_bdd_of_tendsto_indicator μ F_closed.measurable_set (λ n, thickened_indicator (δs_pos n) F) (λ n ω, thickened_indicator_le_one (δs_pos n) F ω), have key := thickened_indicator_tendsto_indicator_closure δs_pos δs_lim F, rwa F_closed.closure_eq at key, end /-- One implication of the portmanteau theorem: Weak convergence of finite measures implies that the limsup of the measures of any closed set is at most the measure of the closed set under the limit measure. -/ lemma finite_measure.limsup_measure_closed_le_of_tendsto {Ω ι : Type*} {L : filter ι} [measurable_space Ω] [pseudo_emetric_space Ω] [opens_measurable_space Ω] {μ : finite_measure Ω} {μs : ι → finite_measure Ω} (μs_lim : tendsto μs L (𝓝 μ)) {F : set Ω} (F_closed : is_closed F) : L.limsup (λ i, (μs i : measure Ω) F) ≤ (μ : measure Ω) F := begin by_cases L = ⊥, { simp only [h, limsup, filter.map_bot, Limsup_bot, ennreal.bot_eq_zero, zero_le], }, apply ennreal.le_of_forall_pos_le_add, intros ε ε_pos μ_F_finite, set δs := λ (n : ℕ), (1 : ℝ) / (n+1) with def_δs, have δs_pos : ∀ n, 0 < δs n, from λ n, nat.one_div_pos_of_nat, have δs_lim : tendsto δs at_top (𝓝 0), from tendsto_one_div_add_at_top_nhds_0_nat, have key₁ := tendsto_lintegral_thickened_indicator_of_is_closed (μ : measure Ω) F_closed δs_pos δs_lim, have room₁ : (μ : measure Ω) F < (μ : measure Ω) F + ε / 2, { apply ennreal.lt_add_right (measure_lt_top (μ : measure Ω) F).ne ((ennreal.div_pos_iff.mpr ⟨(ennreal.coe_pos.mpr ε_pos).ne.symm, ennreal.two_ne_top⟩).ne.symm), }, rcases eventually_at_top.mp (eventually_lt_of_tendsto_lt room₁ key₁) with ⟨M, hM⟩, have key₂ := finite_measure.tendsto_iff_forall_lintegral_tendsto.mp μs_lim (thickened_indicator (δs_pos M) F), have room₂ : lintegral (μ : measure Ω) (λ a, thickened_indicator (δs_pos M) F a) < lintegral (μ : measure Ω) (λ a, thickened_indicator (δs_pos M) F a) + ε / 2, { apply ennreal.lt_add_right (lintegral_lt_top_of_bounded_continuous_to_nnreal (μ : measure Ω) _).ne ((ennreal.div_pos_iff.mpr ⟨(ennreal.coe_pos.mpr ε_pos).ne.symm, ennreal.two_ne_top⟩).ne.symm), }, have ev_near := eventually.mono (eventually_lt_of_tendsto_lt room₂ key₂) (λ n, le_of_lt), have aux := λ n, le_trans (measure_le_lintegral_thickened_indicator (μs n : measure Ω) F_closed.measurable_set (δs_pos M)), have ev_near' := eventually.mono ev_near aux, apply (filter.limsup_le_limsup ev_near').trans, haveI : ne_bot L, from ⟨h⟩, rw limsup_const, apply le_trans (add_le_add (hM M rfl.le).le (le_refl (ε/2 : ℝ≥0∞))), simp only [add_assoc, ennreal.add_halves, le_refl], end /-- One implication of the portmanteau theorem: Weak convergence of probability measures implies that the limsup of the measures of any closed set is at most the measure of the closed set under the limit probability measure. -/ lemma probability_measure.limsup_measure_closed_le_of_tendsto {Ω ι : Type*} {L : filter ι} [measurable_space Ω] [pseudo_emetric_space Ω] [opens_measurable_space Ω] {μ : probability_measure Ω} {μs : ι → probability_measure Ω} (μs_lim : tendsto μs L (𝓝 μ)) {F : set Ω} (F_closed : is_closed F) : L.limsup (λ i, (μs i : measure Ω) F) ≤ (μ : measure Ω) F := by apply finite_measure.limsup_measure_closed_le_of_tendsto ((probability_measure.tendsto_nhds_iff_to_finite_measures_tendsto_nhds L).mp μs_lim) F_closed /-- One implication of the portmanteau theorem: Weak convergence of probability measures implies that the liminf of the measures of any open set is at least the measure of the open set under the limit probability measure. -/ lemma probability_measure.le_liminf_measure_open_of_tendsto {Ω ι : Type*} {L : filter ι} [measurable_space Ω] [pseudo_emetric_space Ω] [opens_measurable_space Ω] {μ : probability_measure Ω} {μs : ι → probability_measure Ω} (μs_lim : tendsto μs L (𝓝 μ)) {G : set Ω} (G_open : is_open G) : (μ : measure Ω) G ≤ L.liminf (λ i, (μs i : measure Ω) G) := begin have h_closeds : ∀ F, is_closed F → L.limsup (λ i, (μs i : measure Ω) F) ≤ (μ : measure Ω) F, from λ F F_closed, probability_measure.limsup_measure_closed_le_of_tendsto μs_lim F_closed, exact le_measure_liminf_of_limsup_measure_compl_le G_open.measurable_set (h_closeds _ (is_closed_compl_iff.mpr G_open)), end lemma probability_measure.tendsto_measure_of_null_frontier_of_tendsto' {Ω ι : Type*} {L : filter ι} [measurable_space Ω] [pseudo_emetric_space Ω] [opens_measurable_space Ω] {μ : probability_measure Ω} {μs : ι → probability_measure Ω} (μs_lim : tendsto μs L (𝓝 μ)) {E : set Ω} (E_nullbdry : (μ : measure Ω) (frontier E) = 0) : tendsto (λ i, (μs i : measure Ω) E) L (𝓝 ((μ : measure Ω) E)) := begin have h_opens : ∀ G, is_open G → (μ : measure Ω) G ≤ L.liminf (λ i, (μs i : measure Ω) G), from λ G G_open, probability_measure.le_liminf_measure_open_of_tendsto μs_lim G_open, exact tendsto_measure_of_null_frontier h_opens E_nullbdry, end /-- One implication of the portmanteau theorem: Weak convergence of probability measures implies that if the boundary of a Borel set carries no probability mass under the limit measure, then the limit of the measures of the set equals the measure of the set under the limit probability measure. A version with coercions to ordinary `ℝ≥0∞`-valued measures is `measure_theory.probability_measure.tendsto_measure_of_null_frontier_of_tendsto'`. -/ lemma probability_measure.tendsto_measure_of_null_frontier_of_tendsto {Ω ι : Type*} {L : filter ι} [measurable_space Ω] [pseudo_emetric_space Ω] [opens_measurable_space Ω] {μ : probability_measure Ω} {μs : ι → probability_measure Ω} (μs_lim : tendsto μs L (𝓝 μ)) {E : set Ω} (E_nullbdry : μ (frontier E) = 0) : tendsto (λ i, μs i E) L (𝓝 (μ E)) := begin have E_nullbdry' : (μ : measure Ω) (frontier E) = 0, by rw [← probability_measure.ennreal_coe_fn_eq_coe_fn_to_measure, E_nullbdry, ennreal.coe_zero], have key := probability_measure.tendsto_measure_of_null_frontier_of_tendsto' μs_lim E_nullbdry', exact (ennreal.tendsto_to_nnreal (measure_ne_top ↑μ E)).comp key, end end convergence_implies_limsup_closed_le --section end measure_theory --namespace
6d48e016af3124ef500698a6bb4966a251d34e4e
c777c32c8e484e195053731103c5e52af26a25d1
/src/measure_theory/group/add_circle.lean
50e9ffcab8e9cca805900db6ae79ae88fd2605cd
[ "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
5,347
lean
/- Copyright (c) 2022 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import measure_theory.integral.periodic import data.zmod.quotient /-! # Measure-theoretic results about the additive circle The file is a place to collect measure-theoretic results about the additive circle. ## Main definitions: * `add_circle.closed_ball_ae_eq_ball`: open and closed balls in the additive circle are almost equal * `add_circle.is_add_fundamental_domain_of_ae_ball`: a ball is a fundamental domain for rational angle rotation in the additive circle -/ open set function filter measure_theory measure_theory.measure metric open_locale measure_theory pointwise big_operators topology ennreal namespace add_circle variables {T : ℝ} [hT : fact (0 < T)] include hT lemma closed_ball_ae_eq_ball {x : add_circle T} {ε : ℝ} : closed_ball x ε =ᵐ[volume] ball x ε := begin cases le_or_lt ε 0 with hε hε, { rw [ball_eq_empty.mpr hε, ae_eq_empty, volume_closed_ball, min_eq_right (by linarith [hT.out] : 2 * ε ≤ T), ennreal.of_real_eq_zero], exact mul_nonpos_of_nonneg_of_nonpos zero_le_two hε, }, { suffices : volume (closed_ball x ε) ≤ volume (ball x ε), { exact (ae_eq_of_subset_of_measure_ge ball_subset_closed_ball this measurable_set_ball (measure_ne_top _ _)).symm, }, have : tendsto (λ δ, volume (closed_ball x δ)) (𝓝[<] ε) (𝓝 $ volume (closed_ball x ε)), { simp_rw volume_closed_ball, refine ennreal.tendsto_of_real (tendsto.min tendsto_const_nhds $ tendsto.const_mul _ _), convert (@monotone_id ℝ _).tendsto_nhds_within_Iio ε, simp, }, refine le_of_tendsto this (mem_nhds_within_Iio_iff_exists_Ioo_subset.mpr ⟨0, hε, λ r hr, _⟩), exact measure_mono (closed_ball_subset_ball hr.2), }, end /-- Let `G` be the subgroup of `add_circle T` generated by a point `u` of finite order `n : ℕ`. Then any set `I` that is almost equal to a ball of radius `T / 2n` is a fundamental domain for the action of `G` on `add_circle T` by left addition. -/ lemma is_add_fundamental_domain_of_ae_ball (I : set $ add_circle T) (u x : add_circle T) (hu : is_of_fin_add_order u) (hI : I =ᵐ[volume] ball x (T / (2 * add_order_of u))) : is_add_fundamental_domain (add_subgroup.zmultiples u) I := begin set G := add_subgroup.zmultiples u, set n := add_order_of u, set B := ball x (T / (2 * n)), have hn : 1 ≤ (n : ℝ), { norm_cast, linarith [add_order_of_pos' hu], }, refine is_add_fundamental_domain.mk_of_measure_univ_le _ _ _ _, { -- `null_measurable_set I volume` exact (measurable_set_ball.null_measurable_set.congr hI.symm), }, { -- `∀ (g : G), g ≠ 0 → ae_disjoint volume (g +ᵥ I) I` rintros ⟨g, hg⟩ hg', replace hg' : g ≠ 0, by simpa only [ne.def, add_subgroup.mk_eq_zero_iff] using hg', change ae_disjoint volume (g +ᵥ I) I, refine ae_disjoint.congr (disjoint.ae_disjoint _) ((quasi_measure_preserving_add_left volume (-g)).vadd_ae_eq_of_ae_eq g hI) hI, have hBg : g +ᵥ B = ball (g + x) (T / (2 * n)), { rw [add_comm g x, ← singleton_add_ball _ x g, add_ball, thickening_singleton], }, rw hBg, apply ball_disjoint_ball, rw [dist_eq_norm, add_sub_cancel, div_mul_eq_div_div, ← add_div, ← add_div, add_self_div_two, div_le_iff' (by positivity : 0 < (n : ℝ)), ← nsmul_eq_mul], refine (le_add_order_smul_norm_of_is_of_fin_add_order (hu.of_mem_zmultiples hg) hg').trans (nsmul_le_nsmul (norm_nonneg g) _), exact nat.le_of_dvd (add_order_of_pos_iff.mpr hu) (add_order_of_dvd_of_mem_zmultiples hg), }, { -- `∀ (g : G), quasi_measure_preserving (has_vadd.vadd g) volume volume` exact (λ g, quasi_measure_preserving_add_left volume g), }, { -- `volume univ ≤ ∑' (g : G), volume (g +ᵥ I)` replace hI : I =ᵐ[volume] closed_ball x (T / (2 * ↑n)) := hI.trans closed_ball_ae_eq_ball.symm, haveI : fintype G := @fintype.of_finite _ hu.finite_zmultiples, have hG_card : (finset.univ : finset G).card = n, { show _ = add_order_of u, rw [add_order_eq_card_zmultiples', nat.card_eq_fintype_card], refl }, simp_rw [measure_vadd], rw [add_circle.measure_univ, tsum_fintype, finset.sum_const, measure_congr hI, volume_closed_ball, ← ennreal.of_real_nsmul, mul_div, mul_div_mul_comm, div_self (@two_ne_zero ℝ _ _ _ _), one_mul, min_eq_right (div_le_self hT.out.le hn), hG_card, nsmul_eq_mul, mul_div_cancel' T (lt_of_lt_of_le zero_lt_one hn).ne.symm], exact le_refl _, }, end lemma volume_of_add_preimage_eq (s I : set $ add_circle T) (u x : add_circle T) (hu : is_of_fin_add_order u) (hs : (u +ᵥ s : set $ add_circle T) =ᵐ[volume] s) (hI : I =ᵐ[volume] ball x (T / (2 * add_order_of u))) : volume s = add_order_of u • volume (s ∩ I) := begin let G := add_subgroup.zmultiples u, haveI : fintype G := @fintype.of_finite _ hu.finite_zmultiples, have hsG : ∀ (g : G), (g +ᵥ s : set $ add_circle T) =ᵐ[volume] s, { rintros ⟨y, hy⟩, exact (vadd_ae_eq_self_of_mem_zmultiples hs hy : _), }, rw [(is_add_fundamental_domain_of_ae_ball I u x hu hI).measure_eq_card_smul_of_vadd_ae_eq_self s hsG, add_order_eq_card_zmultiples' u, nat.card_eq_fintype_card], end end add_circle
5bb1431a657e036b0175e1639e8fb6d479f64d90
761fea1362b10b4c588c2dfc0ae90c70b119e35d
/src/imports.lean
3af10d035ea920529fd08afcf079266bbeac9b9e
[]
no_license
holtzermann17/mm-lean
382a29fca5245f97cf488c525ed0c9594917f73b
a9130d71ed448f62df28d4128043b707bad85ccd
refs/heads/master
1,588,477,413,982
1,553,885,046,000
1,553,885,046,000
178,404,617
0
0
null
1,553,863,829,000
1,553,863,828,000
null
UTF-8
Lean
false
false
2,223
lean
import algebra --default -- import algebra.archimedean -- import algebra.big_operators -- import algebra.char_zero -- import algebra.euclidean_domain -- import algebra.ordered_field -- import algebra.pi_instances -- import analysis.complex -- import analysis.ennreal -- import analysis.limits -- import analysis.measure_theory.borel_space -- import analysis.measure_theory.lebesgue_measure -- import analysis.measure_theory.measurable_space -- import analysis.measure_theory.measure_space -- import analysis.measure_theory.outer_measure -- import analysis.metric_space -- import analysis.nnreal -- import analysis.probability_mass_function -- import analysis.real -- import analysis.topology.continuity -- import analysis.topology.infinite_sum -- import analysis.topology.topological_space -- import analysis.topology.topological_structures -- import analysis.topology.uniform_space -- import category.basic -- import computability.halting -- import computability.partrec_code -- import computability.partrec -- import computability.primrec -- import computability.turing_machine -- import group_theory.coset -- import group_theory.free_group -- import group_theory.order_of_element -- import group_theory.subgroup -- import group_theory.submonoid -- import linear_algebra.basic -- import linear_algebra.dimension -- import linear_algebra.linear_map_module -- import linear_algebra.multivariate_polynomial -- import linear_algebra.prod_module -- import linear_algebra.quotient_module -- import linear_algebra.subtype_module -- import logic.basic -- import logic.embedding -- import logic.function -- import logic.relation -- import logic.relator -- import logic.schroeder_bernstein -- import number_theory.dioph -- import number_theory.pell -- import order -- default -- import order.bounds -- import order.complete_boolean_algebra -- import order.conditionally_complete_lattice -- import order.filter -- import order.fixed_points -- import order.galois_connection -- import order.liminf_limsup -- import order.order_iso -- import order.zorn -- import ring_theory.ideals -- import ring_theory.localization -- import set_theory.cardinal -- import set_theory.cofinality -- import set_theory.ordinal -- import set_theory.zfc
e8ade872e41548cdc8b25a27b5edb2d55f3491f3
35b83be3126daae10419b573c55e1fed009d3ae8
/_target/deps/mathlib/data/zmod/quadratic_reciprocity.lean
fff4181f57e16c1b6b54e43288eb65882bd85d29
[]
no_license
AHassan1024/Lean_Playground
ccb25b72029d199c0d23d002db2d32a9f2689ebc
a00b004c3a2eb9e3e863c361aa2b115260472414
refs/heads/master
1,586,221,905,125
1,544,951,310,000
1,544,951,310,000
157,934,290
0
0
null
null
null
null
UTF-8
Lean
false
false
32,423
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import field_theory.finite data.zmod.basic algebra.pi_instances open function finset nat finite_field zmodp namespace zmodp variables {p q : ℕ} (hp : prime p) (hq : prime q) @[simp] lemma card_units_zmodp : fintype.card (units (zmodp p hp)) = p - 1 := by rw [card_units, card_zmodp] theorem fermat_little {p : ℕ} (hp : prime p) {a : zmodp p hp} (ha : a ≠ 0) : a ^ (p - 1) = 1 := by rw [← units.mk0_val ha, ← @units.coe_one (zmodp p hp), ← units.coe_pow, ← units.ext_iff, ← card_units_zmodp hp, pow_card_eq_one] lemma euler_criterion_units {x : units (zmodp p hp)} : (∃ y : units (zmodp p hp), y ^ 2 = x) ↔ x ^ (p / 2) = 1 := hp.eq_two_or_odd.elim (λ h, by subst h; revert x; exact dec_trivial) (λ hp1, let ⟨g, hg⟩ := is_cyclic.exists_generator (units (zmodp p hp)) in let ⟨n, hn⟩ := show x ∈ powers g, from (powers_eq_gpowers g).symm ▸ hg x in ⟨λ ⟨y, hy⟩, by rw [← hy, ← pow_mul, two_mul_odd_div_two hp1, ← card_units_zmodp hp, pow_card_eq_one], λ hx, have 2 * (p / 2) ∣ n * (p / 2), by rw [two_mul_odd_div_two hp1, ← card_units_zmodp hp, ← order_of_eq_card_of_forall_mem_gppowers hg]; exact order_of_dvd_of_pow_eq_one (by rwa [pow_mul, hn]), let ⟨m, hm⟩ := dvd_of_mul_dvd_mul_right (nat.div_pos hp.ge_two dec_trivial) this in ⟨g ^ m, by rwa [← pow_mul, mul_comm, ← hm]⟩⟩) lemma euler_criterion {a : zmodp p hp} (ha : a ≠ 0) : (∃ y : zmodp p hp, y ^ 2 = a) ↔ a ^ (p / 2) = 1 := ⟨λ ⟨y, hy⟩, have hy0 : y ≠ 0, from λ h, by simp [h, _root_.zero_pow (succ_pos 1)] at hy; cc, by simpa using (units.ext_iff.1 $ (euler_criterion_units hp).1 ⟨units.mk0 _ hy0, show _ = units.mk0 _ ha, by rw [units.ext_iff]; simpa⟩), λ h, let ⟨y, hy⟩ := (euler_criterion_units hp).2 (show units.mk0 _ ha ^ (p / 2) = 1, by simpa [units.ext_iff]) in ⟨y, by simpa [units.ext_iff] using hy⟩⟩ lemma pow_div_two_eq_neg_one_or_one {a : zmodp p hp} (ha : a ≠ 0) : a ^ (p / 2) = 1 ∨ a ^ (p / 2) = -1 := hp.eq_two_or_odd.elim (λ h, by revert a ha; subst h; exact dec_trivial) (λ hp1, by rw [← mul_self_eq_one_iff, ← _root_.pow_add, ← two_mul, two_mul_odd_div_two hp1]; exact fermat_little hp ha) @[simp] lemma wilsons_lemma {p : ℕ} (hp : prime p) : (fact (p - 1) : zmodp p hp) = -1 := begin rw [← finset.prod_range_id_eq_fact, ← @units.coe_one (zmodp p hp), ← units.coe_neg, ← @prod_univ_units_id_eq_neg_one (zmodp p hp), ← prod_hom (coe : units (zmodp p hp) → zmodp p hp) units.coe_one units.coe_mul, ← prod_hom (coe : ℕ → zmodp p hp) nat.cast_one nat.cast_mul], exact eq.symm (prod_bij (λ a _, (a : zmodp p hp).1) (λ a ha, mem_erase.2 ⟨λ h, units.coe_ne_zero a $ fin.eq_of_veq h, by rw [mem_range, ← succ_sub hp.pos, succ_sub_one]; exact a.1.2⟩) (λ a _, by simp) (λ _ _ _ _, units.ext_iff.2 ∘ fin.eq_of_veq) (λ b hb, have b ≠ 0 ∧ b < p, by rwa [mem_erase, mem_range, ← succ_sub hp.pos, succ_sub_one] at hb, ⟨units.mk0 _ (show (b : zmodp p hp) ≠ 0, from fin.ne_of_vne $ by rw [zmod.val_cast_nat, ← @nat.cast_zero (zmodp p hp), zmod.val_cast_nat]; simp [mod_eq_of_lt this.2, this.1]), mem_univ _, by simp [val_cast_of_lt hp this.2]⟩)) end @[simp] lemma prod_range_prime_erase_zero {p : ℕ} (hp : prime p) : ((range p).erase 0).prod (λ x, (x : zmodp p hp)) = -1 := by conv in (range p) { rw [← succ_sub_one p, succ_sub hp.pos] }; rw [prod_hom (coe : ℕ → zmodp p hp) nat.cast_one nat.cast_mul, finset.prod_range_id_eq_fact, wilsons_lemma] end zmodp namespace quadratic_reciprocity_aux variables {p q : ℕ} (hp : prime p) (hq : prime q) (hp1 : p % 2 = 1) (hq1 : q % 2 = 1) (hpq : p ≠ q) include hp hq hp1 hq1 hpq lemma filter_range_p_mul_q_div_two_eq : (range ((p * q) / 2).succ).filter (coprime p) = (range (q / 2)).bind (λ x, (erase (range p) 0).image (+ p * x)) ∪ (erase (range (succ (p / 2))) 0).image (+ q / 2 * p) := finset.ext.2 $ λ x, ⟨λ h, have hxp0 : x % p ≠ 0, by rw [ne.def, ← dvd_iff_mod_eq_zero, ← hp.coprime_iff_not_dvd]; exact (mem_filter.1 h).2, mem_union.2 $ or_iff_not_imp_right.2 (λ h₁, mem_bind.2 ⟨x / p, mem_range.2 $ nat.div_lt_of_lt_mul (by_contradiction (λ h₂, let ⟨c, hc⟩ := le_iff_exists_add.1 (le_of_not_gt h₂) in have hcp : c ≤ p / 2, from @nat.le_of_add_le_add_left (p * (q / 2)) _ _ (by rw [← hc, ← odd_mul_odd_div_two hp1 hq1]; exact le_of_lt_succ (mem_range.1 (mem_filter.1 h).1)), h₁ $ mem_image.2 ⟨c, mem_erase.2 ⟨λ h, hxp0 $ by simp [h, hc], mem_range.2 $ lt_succ_of_le $ hcp⟩, by rw hc; simp [mul_comm]⟩)), mem_image.2 ⟨x % p, mem_erase.2 $ by rw [ne.def, ← dvd_iff_mod_eq_zero, ← hp.coprime_iff_not_dvd, mem_range]; exact ⟨(mem_filter.1 h).2, mod_lt _ hp.pos⟩, nat.mod_add_div _ _⟩⟩), λ h, mem_filter.2 $ (mem_union.1 h).elim (λ h, let ⟨m, hm₁, hm₂⟩ := mem_bind.1 h in let ⟨k, hk₁, hk₂⟩ := mem_image.1 hm₂ in ⟨mem_range.2 $ hk₂ ▸ (mul_lt_mul_left (show 0 < 2, from dec_trivial)).1 begin rw [mul_succ, two_mul_odd_div_two (nat.odd_mul_odd hp1 hq1), mul_add], clear _let_match _let_match, exact calc 2 * k + 2 * (p * m) < 2 * p + 2 * (p * m) : add_lt_add_right ((mul_lt_mul_left dec_trivial).2 (by simp at hk₁; tauto)) _ ... = 2 * (p * (m + 1)) : by simp [mul_add, mul_assoc, mul_comm, mul_left_comm] ... ≤ 2 * (p * (q / 2)) : (mul_le_mul_left (show 0 < 2, from dec_trivial)).2 ((mul_le_mul_left hp.pos).2 $ succ_le_of_lt $ mem_range.1 hm₁) ... ≤ _ : by rw [mul_left_comm, two_mul_odd_div_two hq1, nat.mul_sub_left_distrib, ← nat.sub_add_comm (mul_pos hp.pos hq.pos), add_succ, succ_eq_add_one, nat.add_sub_cancel]; exact le_trans (nat.sub_le_self _ _) (nat.le_add_right _ _), end, by rw [prime.coprime_iff_not_dvd hp, ← hk₂, ← nat.dvd_add_iff_left (dvd_mul_right _ _), dvd_iff_mod_eq_zero, mod_eq_of_lt]; clear _let_match _let_match; simp at hk₁; tauto⟩) (λ h, let ⟨m, hm₁, hm₂⟩ := mem_image.1 h in ⟨mem_range.2 $ hm₂ ▸ begin refine (mul_lt_mul_left (show 0 < 2, from dec_trivial)).1 _, rw [mul_succ, two_mul_odd_div_two (nat.odd_mul_odd hp1 hq1), mul_add, ← mul_assoc 2, two_mul_odd_div_two hq1], exact calc 2 * m + (q - 1) * p ≤ 2 * (p / 2) + (q - 1) * p : add_le_add_right ((mul_le_mul_left dec_trivial).2 (le_of_lt_succ (mem_range.1 (by simp * at *)))) _ ... < _ : begin rw [two_mul_odd_div_two hp1, nat.mul_sub_right_distrib, one_mul], rw [← nat.sub_add_comm hp.pos, nat.add_sub_cancel' (le_mul_of_ge_one_left' (nat.zero_le _) hq.pos), mul_comm], exact lt_add_of_pos_right _ dec_trivial end, end, by rw [hp.coprime_iff_not_dvd, dvd_iff_mod_eq_zero, ← hm₂, nat.add_mul_mod_self_right, mod_eq_of_lt (lt_of_lt_of_le _ (nat.div_lt_self hp.pos (show 1 < 2, from dec_trivial)))]; simp [-range_succ] at hm₁; clear _let_match; tauto⟩)⟩ lemma prod_filter_range_p_mul_q_div_two_eq : (range (q / 2)).prod (λ n, ((range p).erase 0).prod (+ p * n)) * ((range (p / 2).succ).erase 0).prod (+ (q / 2) * p) = ((range ((p * q) / 2).succ).filter (coprime p)).prod (λ x, x) := calc (range (q / 2)).prod (λ n, ((range p).erase 0).prod (+ p * n)) * ((range (p / 2).succ).erase 0).prod (+ (q / 2) * p) = (range (q / 2)).prod (λ n, (((range p).erase 0).image (+ p * n)).prod (λ x, x)) * (((range (p / 2).succ).erase 0).image (+ (q / 2) * p)).prod (λ x, x) : by simp only [prod_image (λ _ _ _ _ h, add_right_cancel h)]; refl ... = ((range (q / 2)).bind (λ x, (erase (range p) 0).image (+ p * x)) ∪ (erase (range (succ (p / 2))) 0).image (+ q / 2 * p)).prod (λ x, x) : have h₁ : finset.bind (range (q / 2)) (λ x, ((range p).erase 0).image (+ p * x)) ∩ image (+ q / 2 * p) (erase (range (succ (p / 2))) 0) = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x, begin suffices : ∀ a, a ≠ 0 → a ≤ p / 2 → a + q / 2 * p = x → ∀ b, b < q / 2 → ∀ c, c ≠ 0 → c < p → ¬c + p * b = x, { simpa [- range_succ, lt_succ_iff] }, assume a ha0 hap ha b hbq c hc0 hcp hc, rw mul_comm at ha, rw [← ((nat.div_mod_unique hp.pos).2 ⟨hc, hcp⟩).1, ← ((nat.div_mod_unique hp.pos).2 ⟨ha, lt_of_le_of_lt hap (nat.div_lt_self hp.pos dec_trivial)⟩).1] at hbq, exact lt_irrefl _ hbq end, have h₂ : ∀ x, x ∈ range (q / 2) → ∀ y, y ∈ range (q / 2) → x ≠ y → (erase (range p) 0).image (+ p * x) ∩ image (+ p * y) (erase (range p) 0) = ∅ := λ x hx y hy hxy, begin suffices : ∀ z a, a ≠ 0 → a < p → a + p * x = z → ∀ b, b ≠ 0 → b < p → b + p * y ≠ z, { simpa [finset.ext] }, assume z a ha0 hap ha b hb0 hbp hb, have : (a + p * x) / p = (b + p * y) / p, { rw [ha, hb] }, rw [nat.add_mul_div_left _ _ hp.pos, nat.add_mul_div_left _ _ hp.pos, (nat.div_eq_zero_iff hp.pos).2 hap, (nat.div_eq_zero_iff hp.pos).2 hbp] at this, simpa [hxy] end, by rw [prod_union h₁, prod_bind h₂] ... = (((range ((p * q) / 2).succ)).filter (coprime p)).prod (λ x, x) : prod_congr (filter_range_p_mul_q_div_two_eq hp hq hp1 hq1 hpq).symm (λ _ _, rfl) lemma prod_filter_range_p_mul_q_div_two_mod_p_eq : ((((range ((p * q) / 2).succ).filter (coprime p)).prod (λ x, x) : ℕ) : zmodp p hp) = (-1) ^ (q / 2) * ((range (p / 2).succ).erase 0).prod (λ x, x) := begin rw [← prod_filter_range_p_mul_q_div_two_eq hp hq hp1 hq1 hpq, nat.cast_mul, ← prod_hom (coe : ℕ → zmodp p hp) nat.cast_one nat.cast_mul, ← prod_hom (coe : ℕ → zmodp p hp) nat.cast_one nat.cast_mul], conv in ((finset.prod (erase (range p) 0) _ : ℕ) : zmodp p hp) { rw ← prod_hom (coe : ℕ → zmodp p hp) nat.cast_one nat.cast_mul }, simp end lemma prod_filter_range_p_mul_q_not_coprime_eq : (((((range ((p * q) / 2).succ).filter (coprime p)).filter (λ x, ¬ coprime q x)).prod (λ x, x) : ℕ) : zmodp p hp) = q ^ (p / 2) * ((range (p / 2).succ).erase 0).prod (λ x, x) := have hcard : ((range (p / 2).succ).erase 0).card = p / 2 := by rw [card_erase_of_mem (mem_range.2 (succ_pos _)), card_range, pred_succ], begin conv in ((q : zmodp p hp) ^ (p / 2)) { rw ← hcard }, rw [← prod_const, ← prod_mul_distrib, ← prod_hom (coe : ℕ → zmodp p hp) nat.cast_one nat.cast_mul], exact eq.symm (prod_bij (λ a _, a * q) (λ a ha, have ha' : a ≤ p / 2 ∧ a > 0, by simp [nat.pos_iff_ne_zero, -range_succ, lt_succ_iff] at *; tauto, mem_filter.2 ⟨mem_filter.2 ⟨mem_range.2 $ lt_succ_of_le $ (calc a * q ≤ q * (p / 2) : by rw mul_comm; exact mul_le_mul_left _ ha'.1 ... ≤ _ : by rw [mul_comm p, odd_mul_odd_div_two hq1 hp1]; exact nat.le_add_right _ _), by rw [hp.coprime_iff_not_dvd, hp.dvd_mul, not_or_distrib]; refine ⟨λ hpa, not_le_of_gt (show p / 2 < p, from nat.div_lt_self hp.pos dec_trivial) (le_trans (le_of_dvd ha'.2 hpa) ha'.1), by rwa [← hp.coprime_iff_not_dvd, coprime_primes hp hq]⟩⟩, by simp [hq.coprime_iff_not_dvd]⟩) (by simp [mul_comm]) (by simp [nat.mul_right_inj hq.pos]) (λ b hb, have hb' : (b ≤ p * q / 2 ∧ coprime p b) ∧ q ∣ b, by simpa [hq.coprime_iff_not_dvd, -range_succ, lt_succ_iff] using hb, have hb0 : b > 0, from nat.pos_of_ne_zero (λ hb0, by simpa [hb0, hp.coprime_iff_not_dvd] using hb'), ⟨b / q, mem_erase.2 ⟨nat.pos_iff_ne_zero.1 (nat.div_pos (le_of_dvd hb0 hb'.2) hq.pos), mem_range.2 $ lt_succ_of_le $ by rw [mul_comm, odd_mul_odd_div_two hq1 hp1] at hb'; have := @nat.div_le_div_right _ _ hb'.1.1 q; rwa [add_comm, nat.add_mul_div_left _ _ hq.pos, ((nat.div_eq_zero_iff hq.pos).2 (nat.div_lt_self hq.pos (lt_succ_self _))), zero_add] at this⟩, by rw nat.div_mul_cancel hb'.2⟩)) end lemma prod_range_p_mul_q_filter_coprime_mod_p (hq : prime q) (hp1 : p % 2 = 1) (hq1 : q % 2 = 1) (hpq : p ≠ q) : ((((range ((p * q) / 2).succ).filter (coprime (p * q))).prod (λ x, x) : ℕ) : zmodp p hp) = (-1) ^ (q / 2) * q ^ (p / 2) := have hq0 : (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], (domain.mul_right_inj (show (q ^ (p / 2) * ((range (p / 2).succ).erase 0).prod (λ x, x) : zmodp p hp) ≠ 0, from mul_ne_zero (pow_ne_zero _ hq0) (suffices h : ∀ (x : ℕ), ¬x = 0 → x ≤ p / 2 → ¬(x : zmodp p hp) = 0, by simpa [prod_eq_zero_iff, -range_succ, lt_succ_iff], assume x hx0 hxp, by rwa [← @nat.cast_zero (zmodp p hp), zmodp.eq_iff_modeq_nat, nat.modeq, zero_mod, mod_eq_of_lt (lt_of_le_of_lt hxp (nat.div_lt_self hp.pos (lt_succ_self _)))]))).1 $ have h₁ : (range (succ (p * q / 2))).filter (coprime (p * q)) ∩ filter (λ x, ¬coprime q x) (filter (coprime p) (range (succ (p * q / 2)))) = ∅, by have := @coprime.coprime_mul_left p q; simp [finset.ext, *] at * {contextual := tt}, calc ((((range ((p * q) / 2).succ).filter (coprime (p * q))).prod (λ x, x) : ℕ) : zmodp p hp) * (q ^ (p / 2) * ((range (p / 2).succ).erase 0).prod (λ x, x) : zmodp p hp) = (((range (succ (p * q / 2))).filter (coprime (p * q)) ∪ filter (λ x, ¬coprime q x) (filter (coprime p) (range (succ (p * q / 2))))).prod (λ x, x) : ℕ) : by rw [← prod_filter_range_p_mul_q_not_coprime_eq hp hq hp1 hq1 hpq, ← nat.cast_mul, ← prod_union h₁] ... = (((range ((p * q) / 2).succ).filter (coprime p)).prod (λ x, x) : ℕ) : congr_arg coe (prod_congr (by simp [finset.ext, coprime_mul_iff_left]; tauto) (λ _ _, rfl)) ... = _ : by rw [prod_filter_range_p_mul_q_div_two_mod_p_eq hp hq hp1 hq1 hpq]; cases zmodp.pow_div_two_eq_neg_one_or_one hp hq0; simp [h, _root_.pow_succ] lemma card_range_p_mul_q_filter_not_coprime : card (filter (λ x, ¬coprime p x) (range (succ (p * q / 2)))) = (q / 2).succ := calc card (filter (λ x, ¬coprime p x) (range (succ (p * q / 2)))) = card ((range (q / 2).succ).image (* p)) : congr_arg card $ finset.ext.2 $ λ x, begin rw [mem_filter, mem_range, hp.coprime_iff_not_dvd, not_not, mem_image], exact ⟨λ ⟨h, ⟨m, hm⟩⟩, ⟨m, mem_range.2 (lt_of_mul_lt_mul_left (by rw ← hm; exact lt_of_lt_of_le h (by rw [succ_le_iff, mul_succ, odd_mul_odd_div_two hp1 hq1]; exact add_lt_add_left (div_lt_self hp.pos (lt_succ_self 1)) _)) (nat.zero_le p)), hm.symm ▸ mul_comm m p⟩, λ ⟨m, hm₁, hm₂⟩, ⟨lt_succ_of_le (by rw [← hm₂, odd_mul_odd_div_two hp1 hq1]; exact le_trans (by rw mul_comm; exact mul_le_mul_left _ (le_of_lt_succ (mem_range.1 hm₁))) (le_add_right _ _)), by simp [hm₂.symm]⟩⟩ end ... = _ : by rw [card_image_of_injective _ (λ _ _ h, (nat.mul_right_inj hp.pos).1 h), card_range] lemma prod_filter_range_p_mul_q_div_two_eq_prod_product : ((range ((p * q) / 2).succ).filter (coprime (p * q))).prod (λ x, if (x : zmodp q hq).1 ≤ q / 2 then ((x : zmodp p hp), (x : zmodp q hq)) else -((x : zmodp p hp), (x : zmodp q hq))) = (((range p).erase 0).product ((range (q / 2).succ).erase 0)).prod (λ x, ((x.1 : zmodp p hp), (x.2 : zmodp q hq))) := have hpqpnat : (((⟨p * q, mul_pos hp.pos hq.pos⟩ : ℕ+) : ℕ) : ℤ) = (p * q : ℤ), by simp, have hpqpnat' : ((⟨p * q, mul_pos hp.pos hq.pos⟩ : ℕ+) : ℕ) = p * q, by simp, have hpq1 : ((⟨p * q, mul_pos hp.pos hq.pos⟩ : ℕ+) : ℕ) % 2 = 1, from nat.odd_mul_odd hp1 hq1, have hpq1' : p * q > 1, from one_lt_mul hp.pos hq.gt_one, have hhq0 : ∀ a : ℕ, coprime q a → a ≠ 0, from λ a, imp_not_comm.1 $ by simp [hq.coprime_iff_not_dvd] {contextual := tt}, have hpq0 : 0 < p * q / 2, from nat.div_pos (succ_le_of_lt $ one_lt_mul hp.pos hq.gt_one) dec_trivial, have hinj : ∀ a₁ a₂ : ℕ, a₁ ∈ (range (p * q / 2).succ).filter (coprime (p * q)) → a₂ ∈ (range (p * q / 2).succ).filter (coprime (p * q)) → (if (a₁ : zmodp q hq).1 ≤ q / 2 then ((a₁ : zmodp p hp).1, (a₁ : zmodp q hq).1) else ((-a₁ : zmodp p hp).1, (-a₁ : zmodp q hq).1)) = (if (a₂ : zmodp q hq).1 ≤ q / 2 then ((a₂ : zmodp p hp).1, (a₂ : zmodp q hq).1) else ((-a₂ : zmodp p hp).1, (-a₂ : zmodp q hq).1)) → a₁ = a₂, from λ a b ha hb h, have ha' : a ≤ (p * q) / 2 ∧ coprime (p * q) a, by simpa [-range_succ, lt_succ_iff] using ha, have hapq' : a < ((⟨p * q, mul_pos hp.pos hq.pos⟩ : ℕ+) : ℕ) := lt_of_le_of_lt ha'.1 (div_lt_self (mul_pos hp.pos hq.pos) dec_trivial), have hb' : b ≤ (p * q) / 2 ∧ coprime (p * q) b, by simpa [-range_succ, lt_succ_iff, coprime_mul_iff_left] using hb, have hbpq' : b < ((⟨p * q, mul_pos hp.pos hq.pos⟩ : ℕ+) : ℕ) := lt_of_le_of_lt hb'.1 (div_lt_self (mul_pos hp.pos hq.pos) dec_trivial), have val_inj : ∀ {p : ℕ} (hp : prime p) (x y : zmodp p hp), x.val = y.val ↔ x = y, from λ _ _ _ _, ⟨fin.eq_of_veq, fin.veq_of_eq⟩, have hbpq0 : (b : zmod (⟨p * q, mul_pos hp.pos hq.pos⟩)) ≠ 0, by rw [ne.def, zmod.eq_zero_iff_dvd_nat]; exact λ h, not_coprime_of_dvd_of_dvd hpq1' (dvd_refl (p * q)) h hb'.2, have habneg : ¬((a : zmodp p hp) = -b ∧ (a : zmodp q hq) = -b), begin rw [← int.cast_coe_nat a, ← int.cast_coe_nat b, ← int.cast_coe_nat a, ← int.cast_coe_nat b, ← int.cast_neg, ← int.cast_neg, zmodp.eq_iff_modeq_int, zmodp.eq_iff_modeq_int, @int.modeq.modeq_and_modeq_iff_modeq_mul _ _ p q ((coprime_primes hp hq).2 hpq), ← hpqpnat, ← zmod.eq_iff_modeq_int, int.cast_coe_nat, int.cast_neg, int.cast_coe_nat], assume h, rw [← hpqpnat', ← zmod.val_cast_of_lt hbpq', zmod.le_div_two_iff_lt_neg hpq1 hbpq0, ← h, zmod.val_cast_of_lt hapq', ← not_le] at hb', exact hb'.1 ha'.1, end, have habneg' : ¬((-a : zmodp p hp) = b ∧ (-a : zmodp q hq) = b), by rwa [← neg_inj', neg_neg, ← @neg_inj' _ _ (-a : zmodp q hq), neg_neg], suffices (a : zmodp p hp) = b ∧ (a : zmodp q hq) = b, by rw [← mod_eq_of_lt hapq', ← mod_eq_of_lt hbpq']; rwa [zmodp.eq_iff_modeq_nat, zmodp.eq_iff_modeq_nat, nat.modeq.modeq_and_modeq_iff_modeq_mul ((coprime_primes hp hq).2 hpq)] at this, by split_ifs at h; simp * at *, have hmem : ∀ a : ℕ, a ∈ (range (p * q / 2).succ).filter (coprime (p * q)) → (if (a : zmodp q hq).1 ≤ q / 2 then ((a : zmodp p hp).1, (a : zmodp q hq).1) else ((-a : zmodp p hp).1, (-a : zmodp q hq).1)) ∈ ((range p).erase 0).product ((range (succ (q / 2))).erase 0), from λ x, have hxp : ∀ {p : ℕ} (hp : prime p), (x : zmodp p hp).val = 0 ↔ p ∣ x, from λ p hp, by rw [zmodp.val_cast_nat, nat.dvd_iff_mod_eq_zero], have hxpneg : ∀ {p : ℕ} (hp : prime p), (-x : zmodp p hp).val = 0 ↔ p ∣ x, from λ p hp, by rw [← int.cast_coe_nat x, ← int.cast_neg, ← int.coe_nat_inj', zmodp.coe_val_cast_int, int.coe_nat_zero, ← int.dvd_iff_mod_eq_zero, dvd_neg, int.coe_nat_dvd], have hxplt : (x : zmodp p hp).val < p := (x : zmodp p hp).2, have hxpltneg : (-x : zmodp p hp).val < p := (-x : zmodp p hp).2, have hneglt : ¬(x : zmodp q hq).val ≤ q / 2 → (x : zmodp q hq) ≠ 0 → (-x : zmodp q hq).val ≤ q / 2, from λ hx₁ hx0, by rwa [zmodp.le_div_two_iff_lt_neg hq hq1 hx0, not_lt] at hx₁, by split_ifs; simp [zmodp.eq_zero_iff_dvd_nat hq, (x : zmodp p hp).2, coprime_mul_iff_left, -range_succ, lt_succ_iff, h, *, hp.coprime_iff_not_dvd, hq.coprime_iff_not_dvd, (x : zmodp p hp).2, (-x : zmodp p hp).2] {contextual := tt}, prod_bij (λ x _, if (x : zmodp q hq).1 ≤ (q / 2) then ((x : zmodp p hp).val, (x : zmodp q hq).val) else ((-x : zmodp p hp).val, (-x : zmodp q hq).val)) hmem (λ a ha, by split_ifs; simp [*, prod.ext_iff] at *) hinj (surj_on_of_inj_on_of_card_le _ hmem hinj (@nat.le_of_add_le_add_right (q / 2 + (p / 2).succ) _ _ (calc card (finset.product (erase (range p) 0) (erase (range (succ (q / 2))) 0)) + (q / 2 + (p / 2).succ) = (p * q) / 2 + 1 : by rw [card_product, card_erase_of_mem (mem_range.2 hp.pos), card_erase_of_mem (mem_range.2 (succ_pos _)), card_range, card_range, pred_succ, ← add_assoc, ← succ_mul, succ_pred_eq_of_pos hp.pos, odd_mul_odd_div_two hp1 hq1, add_succ] ... = card (range (p * q / 2).succ) : by rw card_range ... = card ((range (p * q / 2).succ).filter (coprime (p * q)) ∪ ((range (p * q / 2).succ).filter (λ x, ¬coprime p x)).erase 0 ∪ (range (p * q / 2).succ).filter (λ x, ¬coprime q x)) : congr_arg card (by simp [finset.ext, coprime_mul_iff_left, -range_succ]; tauto) ... ≤ card ((range (p * q / 2).succ).filter (coprime (p * q))) + card (((range (p * q / 2).succ).filter (λ x, ¬coprime p x)).erase 0) + card ((range (p * q / 2).succ).filter (λ x, ¬coprime q x)) : le_trans (card_union_le _ _) (add_le_add_right (card_union_le _ _) _) ... = _ : by rw [card_erase_of_mem, card_range_p_mul_q_filter_not_coprime hp hq hp1 hq1 hpq, mul_comm p q, card_range_p_mul_q_filter_not_coprime hq hp hq1 hp1 hpq.symm, pred_succ, add_assoc]; simp [hp.coprime_iff_not_dvd, hpq0]))) lemma prod_range_div_two_erase_zero : ((range (p / 2).succ).erase 0).prod (λ x, (x : zmodp p hp)) ^ 2 * (-1) ^ (p / 2) = -1 := have hcard : card (erase (range (succ (p / 2))) 0) = p / 2, by rw [card_erase_of_mem (mem_range.2 (succ_pos _)), card_range, pred_succ], have hp2 : p / 2 < p, from div_lt_self hp.pos dec_trivial, have h₁ : (range (p / 2).succ).erase 0 = ((range p).erase 0).filter (λ x, (x : zmodp p hp).val ≤ p / 2) := finset.ext.2 (λ a, ⟨λ h, mem_filter.2 $ by rw [mem_erase, mem_range, lt_succ_iff] at h; exact ⟨mem_erase.2 ⟨h.1, mem_range.2 (lt_of_le_of_lt h.2 hp2)⟩, by rw zmodp.val_cast_of_lt hp (lt_of_le_of_lt h.2 hp2); exact h.2⟩, λ h, mem_erase.2 ⟨by simp at h; tauto, by rw [mem_filter, mem_erase, mem_range] at h; rw [mem_range, lt_succ_iff, ← zmodp.val_cast_of_lt hp h.1.2]; exact h.2⟩⟩), have hmem : ∀ x ∈ (range (p / 2).succ).erase 0, x ≠ 0 ∧ x ≤ p / 2, from λ x hx, by simpa [-range_succ, lt_succ_iff] using hx, have hmemv : ∀ x ∈ (range (p / 2).succ).erase 0, (x : zmodp p hp).val = x, from λ x hx, zmodp.val_cast_of_lt hp (lt_of_le_of_lt (hmem x hx).2 hp2), have hmem0 : ∀ x ∈ (range (p / 2).succ).erase 0, (x : zmodp p hp) ≠ 0, from λ x hx, fin.ne_of_vne $ by simp [hmemv x hx, (hmem x hx).1], have hmem0' : ∀ x ∈ (range (p / 2).succ).erase 0, (-x : zmodp p hp) ≠ 0, from λ x hx, neg_ne_zero.2 (hmem0 x hx), have h₂ : ((range (p / 2).succ).erase 0).prod (λ x : ℕ, (x : zmodp p hp) * -1) = (((range p).erase 0).filter (λ x : ℕ, ¬(x : zmodp p hp).val ≤ p / 2)).prod (λ x, (x : zmodp p hp)) := prod_bij (λ a _, (-a : zmodp p hp).1) (λ a ha, mem_filter.2 ⟨mem_erase.2 ⟨fin.vne_of_ne (hmem0' a ha), mem_range.2 (-a : zmodp p hp).2⟩, by simp [zmodp.le_div_two_iff_lt_neg hp hp1 (hmem0' a ha), hmemv a ha, (hmem a ha).2]; tauto⟩) (by simp) (λ a₁ a₂ ha₁ ha₂ h, by rw [← hmemv a₁ ha₁, ← hmemv a₂ ha₂]; exact fin.veq_of_eq (by rw neg_inj (fin.eq_of_veq h))) (λ b hb, have hb' : (b ≠ 0 ∧ b < p) ∧ (¬(b : zmodp p hp).1 ≤ p / 2), by simpa using hb, have hbv : (b : zmodp p hp).1 = b, from zmodp.val_cast_of_lt hp hb'.1.2, have hb0 : (b : zmodp p hp) ≠ 0, from fin.ne_of_vne $ by simp [hbv, hb'.1.1], ⟨(-b : zmodp p hp).1, mem_erase.2 ⟨fin.vne_of_ne (neg_ne_zero.2 hb0 : _), mem_range.2 $ lt_succ_of_le $ by rw [← not_lt, ← zmodp.le_div_two_iff_lt_neg hp hp1 hb0]; exact hb'.2⟩, by simp [hbv]⟩), calc ((((range (p / 2).succ).erase 0).prod (λ x, (x : zmodp p hp)) ^ 2)) * (-1) ^ (p / 2) = ((range (p / 2).succ).erase 0).prod (λ x, (x : zmodp p hp)) * ((range (p / 2).succ).erase 0).prod (λ x, (x : zmodp p hp) * -1) : by rw prod_mul_distrib; simp [_root_.pow_two, -range_succ, hcard, mul_assoc] ... = (((range p).erase 0).filter (λ x : ℕ, (x : zmodp p hp).val ≤ p / 2)).prod (λ x, (x : zmodp p hp)) * (((range p).erase 0).filter (λ x : ℕ, ¬(x : zmodp p hp).val ≤ p / 2)).prod (λ x, (x : zmodp p hp)) : by rw [h₂, h₁] ... = ((range p).erase 0).prod (λ x, (x : zmodp p hp)) : begin rw ← prod_union, { exact finset.prod_congr (by simp [finset.ext, -not_lt, -not_le]; tauto) (λ _ _, rfl) }, { simp [finset.ext, -not_lt, - not_le]; tauto } end ... = -1 : by simp lemma range_p_product_range_q_div_two_prod : (((range p).erase 0).product ((range (q / 2).succ).erase 0)).prod (λ x, ((x.1 : zmodp p hp), (x.2 : zmodp q hq))) = ((-1) ^ (q / 2), (-1) ^ (p / 2) * (-1) ^ (p / 2 * (q / 2))) := have hcard : card (erase (range (succ (q / 2))) 0) = q / 2, by rw [card_erase_of_mem (mem_range.2 (succ_pos _)), card_range, pred_succ], have finset.prod (erase (range (succ (q / 2))) 0) (λ x : ℕ, (x : zmodp q hq)) ^ 2 = -((-1 : zmodp q hq) ^ (q / 2)), from (domain.mul_right_inj (show (-1 : zmodp q hq) ^ (q / 2) ≠ 0, from pow_ne_zero _ (neg_ne_zero.2 zero_ne_one.symm))).1 $ by rw [prod_range_div_two_erase_zero hq hp hq1 hp1 hpq.symm, ← neg_mul_eq_neg_mul, ← _root_.pow_add, ← two_mul, pow_mul, _root_.pow_two]; simp, have finset.prod (erase (range (succ (q / 2))) 0) (λ x, (x : zmodp q hq)) ^ card (erase (range p) 0) = (- 1) ^ (p / 2) * ((-1) ^ (p / 2 * (q / 2))), by rw [card_erase_of_mem (mem_range.2 hp.pos), card_range, pred_eq_sub_one, ← two_mul_odd_div_two hp1, pow_mul, this, mul_comm (p / 2), pow_mul, ← _root_.mul_pow]; simp, by simp [prod_product, (prod_mk_prod _ _ _).symm, prod_pow, -range_succ, prod_nat_pow, prod_const, *, zmodp.prod_range_prime_erase_zero hp] lemma prod_range_p_mul_q_div_two_ite_eq : ((range ((p * q) / 2).succ).filter (coprime (p * q))).prod (λ x, if (x : zmodp q hq).1 ≤ (q / 2) then ((x : zmodp p hp), (x : zmodp q hq)) else -((x : zmodp p hp), (x : zmodp q hq))) = ((range ((p * q) / 2).succ).filter (coprime (p * q))).prod (λ x, if (x : zmodp q hq).1 ≤ q / 2 then 1 else -1) * ((-1) ^ (q / 2) * q ^ (p / 2), (-1) ^ (p / 2) * p ^ (q / 2)) := calc ((range ((p * q) / 2).succ).filter (coprime (p * q))).prod (λ x, if (x : zmodp q hq).1 ≤ (q / 2) then ((x : zmodp p hp), (x : zmodp q hq)) else -((x : zmodp p hp), (x : zmodp q hq))) = ((range ((p * q) / 2).succ).filter (coprime (p * q))).prod (λ x, (if (x : zmodp q hq).1 ≤ (q / 2) then 1 else -1) * ((x : zmodp p hp), (x : zmodp q hq))) : prod_congr rfl (λ _ _, by split_ifs; simp) ... = _ : by rw [prod_mul_distrib, ← prod_mk_prod, prod_hom (coe : ℕ → zmodp p hp) nat.cast_one nat.cast_mul, prod_range_p_mul_q_filter_coprime_mod_p hp hq hp1 hq1 hpq, prod_hom (coe : ℕ → zmodp q hq) nat.cast_one nat.cast_mul, mul_comm p q, prod_range_p_mul_q_filter_coprime_mod_p hq hp hq1 hp1 hpq.symm] end quadratic_reciprocity_aux open quadratic_reciprocity_aux variables {p q : ℕ} (hp : prime p) (hq : prime q) namespace zmodp def legendre_sym (a p : ℕ) (hp : prime p) : ℤ := if (a : zmodp p hp) = 0 then 0 else if ∃ b : zmodp p hp, b ^ 2 = a then 1 else -1 lemma legendre_sym_eq_pow (a p : ℕ) (hp : prime p) : (legendre_sym a p hp : zmodp p hp) = (a ^ (p / 2)) := if ha : (a : zmodp p hp) = 0 then by simp [*, legendre_sym, _root_.zero_pow (nat.div_pos hp.ge_two (succ_pos 1))] else (prime.eq_two_or_odd hp).elim (λ hp2, begin subst hp2, suffices : ∀ a : zmodp 2 prime_two, (((ite (a = 0) 0 (ite (∃ (b : zmodp 2 hp), b ^ 2 = a) 1 (-1))) : ℤ) : zmodp 2 prime_two) = a ^ (2 / 2), { exact this a }, exact dec_trivial, end) (λ hp1, have _ := euler_criterion hp ha, have (-1 : zmodp p hp) ≠ 1, from (ne_neg_self hp hp1 zero_ne_one.symm).symm, by cases zmodp.pow_div_two_eq_neg_one_or_one hp ha; simp [legendre_sym, *] at *) lemma legendre_sym_eq_one_or_neg_one (a : ℕ) (hp : prime p) (ha : (a : zmodp p hp) ≠ 0) : legendre_sym a p hp = -1 ∨ legendre_sym a p hp = 1 := by unfold legendre_sym; split_ifs; simp * at * theorem quadratic_reciprocity (hp : prime p) (hq : prime q) (hp1 : p % 2 = 1) (hq1 : q % 2 = 1) (hpq : p ≠ q) : legendre_sym p q hq * legendre_sym q p hp = (-1) ^ ((p / 2) * (q / 2)) := have hneg_one_or_one : ((range (p * q / 2).succ).filter (coprime (p * q))).prod (λ (x : ℕ), if (x : zmodp q hq).val ≤ q / 2 then (1 : zmodp p hp × zmodp q hq) else -1) = 1 ∨ ((range (p * q / 2).succ).filter (coprime (p * q))).prod (λ (x : ℕ), if (x : zmodp q hq).val ≤ q / 2 then (1 : zmodp p hp × zmodp q hq) else -1) = -1 := finset.induction_on ((range (p * q / 2).succ).filter (coprime (p * q))) (or.inl rfl) (λ a s h, by simp [prod_insert h]; split_ifs; finish), have h : (((-1) ^ (q / 2), (-1) ^ (p / 2) * (-1) ^ (p / 2 * (q / 2))) : zmodp p hp × zmodp q hq) = ((-1) ^ (q / 2) * q ^ (p / 2), (-1) ^ (p / 2) * p ^ (q / 2)) ∨ (((-1) ^ (q / 2), (-1) ^ (p / 2) * (-1) ^ (p / 2 * (q / 2))) : zmodp p hp × zmodp q hq) = - ((-1) ^ (q / 2) * q ^ (p / 2), (-1) ^ (p / 2) * p ^ (q / 2)) := begin have := prod_filter_range_p_mul_q_div_two_eq_prod_product hp hq hp1 hq1 hpq, rw [prod_range_p_mul_q_div_two_ite_eq hp hq hp1 hq1 hpq, range_p_product_range_q_div_two_prod hp hq hp1 hq1 hpq] at this, cases hneg_one_or_one with h h; simp * at * end, begin have := ne_neg_self hp hp1 one_ne_zero, have := ne_neg_self hq hq1 one_ne_zero, generalize hnp : (-1 : ℤ) ^ (p / 2) = np, have hnpp : (-1 : zmodp q hq) ^ (p / 2) = np, by simp [hnp.symm], generalize hnq : (-1 : ℤ) ^ (q / 2) = nq, have hnqp : (-1 : zmodp p hp) ^ (q / 2) = nq, by simp [hnq.symm], have hnqq : (-1 : zmodp q hq) ^ (q / 2) = nq, by simp [hnq.symm], cases legendre_sym_eq_one_or_neg_one q hp (zmodp.prime_ne_zero hp hq hpq); cases legendre_sym_eq_one_or_neg_one p hq (zmodp.prime_ne_zero hq hp hpq.symm); cases @neg_one_pow_eq_or ℤ _ (p / 2); cases @neg_one_pow_eq_or ℤ _ (q / 2); simp [*, pow_mul, (legendre_sym_eq_pow p q hq).symm, (legendre_sym_eq_pow q p hp).symm, prod.ext_iff] at *; cc end lemma is_square_iff_is_square_of_mod_four_eq_one (hp1 : p % 4 = 1) (hq1 : q % 2 = 1) : (∃ a : zmodp p hp, a ^ 2 = q) ↔ ∃ b : zmodp q hq, b ^ 2 = p := if hpq : p = q then by subst hpq else have h1 : ((p / 2) * (q / 2)) % 2 = 0, from (dvd_iff_mod_eq_zero _ _).1 (dvd_mul_of_dvd_left ((dvd_iff_mod_eq_zero _ _).2 $ by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp1]; refl) _), begin have := quadratic_reciprocity hp hq (odd_of_mod_four_eq_one hp1) hq1 hpq, rw [neg_one_pow_eq_pow_mod_two, h1, legendre_sym, legendre_sym, if_neg (zmodp.prime_ne_zero hp hq hpq), if_neg (zmodp.prime_ne_zero hq hp (ne.symm hpq))] at this, split_ifs at this; simp *; contradiction end lemma is_square_iff_is_not_square_of_mod_four_eq_three (hp3 : p % 4 = 3) (hq3 : q % 4 = 3) (hpq : p ≠ q) : (∃ a : zmodp p hp, a ^ 2 = q) ↔ ¬∃ b : zmodp q hq, b ^ 2 = p := have h1 : ((p / 2) * (q / 2)) % 2 = 1, from nat.odd_mul_odd (by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp3]; refl) (by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hq3]; refl), begin have := quadratic_reciprocity hp hq (odd_of_mod_four_eq_three hp3) (odd_of_mod_four_eq_three hq3) hpq, rw [neg_one_pow_eq_pow_mod_two, h1, legendre_sym, legendre_sym, if_neg (zmodp.prime_ne_zero hp hq hpq), if_neg (zmodp.prime_ne_zero hq hp hpq.symm)] at this, split_ifs at this; simp *; contradiction end end zmodp
00ee95af7eadd526ded231b31c2585998f9104c3
94e33a31faa76775069b071adea97e86e218a8ee
/src/ring_theory/polynomial/cyclotomic/basic.lean
0fe57a78fdc297b783f616ed9b852453f5bbdd16
[ "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
48,143
lean
/- Copyright (c) 2020 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import algebra.polynomial.big_operators import analysis.complex.roots_of_unity import data.polynomial.lifts import field_theory.separable import field_theory.splitting_field import number_theory.arithmetic_function import ring_theory.roots_of_unity import field_theory.ratfunc import algebra.ne_zero /-! # Cyclotomic polynomials. For `n : ℕ` and an integral domain `R`, we define a modified version of the `n`-th cyclotomic polynomial with coefficients in `R`, denoted `cyclotomic' n R`, as `∏ (X - μ)`, where `μ` varies over the primitive `n`th roots of unity. If there is a primitive `n`th root of unity in `R` then this the standard definition. We then define the standard cyclotomic polynomial `cyclotomic n R` with coefficients in any ring `R`. ## Main definition * `cyclotomic n R` : the `n`-th cyclotomic polynomial with coefficients in `R`. ## Main results * `int_coeff_of_cycl` : If there is a primitive `n`-th root of unity in `K`, then `cyclotomic' n K` comes from a polynomial with integer coefficients. * `deg_of_cyclotomic` : The degree of `cyclotomic n` is `totient n`. * `prod_cyclotomic_eq_X_pow_sub_one` : `X ^ n - 1 = ∏ (cyclotomic i)`, where `i` divides `n`. * `cyclotomic_eq_prod_X_pow_sub_one_pow_moebius` : The Möbius inversion formula for `cyclotomic n R` over an abstract fraction field for `polynomial R`. * `cyclotomic.irreducible` : `cyclotomic n ℤ` is irreducible. ## Implementation details Our definition of `cyclotomic' n R` makes sense in any integral domain `R`, but the interesting results hold if there is a primitive `n`-th root of unity in `R`. In particular, our definition is not the standard one unless there is a primitive `n`th root of unity in `R`. For example, `cyclotomic' 3 ℤ = 1`, since there are no primitive cube roots of unity in `ℤ`. The main example is `R = ℂ`, we decided to work in general since the difficulties are essentially the same. To get the standard cyclotomic polynomials, we use `int_coeff_of_cycl`, with `R = ℂ`, to get a polynomial with integer coefficients and then we map it to `polynomial R`, for any ring `R`. To prove `cyclotomic.irreducible`, the irreducibility of `cyclotomic n ℤ`, we show in `cyclotomic_eq_minpoly` that `cyclotomic n ℤ` is the minimal polynomial of any `n`-th primitive root of unity `μ : K`, where `K` is a field of characteristic `0`. -/ open_locale classical big_operators polynomial noncomputable theory universe u namespace polynomial section cyclotomic' section is_domain variables {R : Type*} [comm_ring R] [is_domain R] /-- The modified `n`-th cyclotomic polynomial with coefficients in `R`, it is the usual cyclotomic polynomial if there is a primitive `n`-th root of unity in `R`. -/ def cyclotomic' (n : ℕ) (R : Type*) [comm_ring R] [is_domain R] : R[X] := ∏ μ in primitive_roots n R, (X - C μ) /-- The zeroth modified cyclotomic polyomial is `1`. -/ @[simp] lemma cyclotomic'_zero (R : Type*) [comm_ring R] [is_domain R] : cyclotomic' 0 R = 1 := by simp only [cyclotomic', finset.prod_empty, is_primitive_root.primitive_roots_zero] /-- The first modified cyclotomic polyomial is `X - 1`. -/ @[simp] lemma cyclotomic'_one (R : Type*) [comm_ring R] [is_domain R] : cyclotomic' 1 R = X - 1 := begin simp only [cyclotomic', finset.prod_singleton, ring_hom.map_one, is_primitive_root.primitive_roots_one] end /-- The second modified cyclotomic polyomial is `X + 1` if the characteristic of `R` is not `2`. -/ @[simp] lemma cyclotomic'_two (R : Type*) [comm_ring R] [is_domain R] (p : ℕ) [char_p R p] (hp : p ≠ 2) : cyclotomic' 2 R = X + 1 := begin rw [cyclotomic'], have prim_root_two : primitive_roots 2 R = {(-1 : R)}, { apply finset.eq_singleton_iff_unique_mem.2, split, { simp only [is_primitive_root.neg_one p hp, nat.succ_pos', mem_primitive_roots] }, { intros x hx, rw [mem_primitive_roots zero_lt_two] at hx, exact is_primitive_root.eq_neg_one_of_two_right hx } }, simp only [prim_root_two, finset.prod_singleton, ring_hom.map_neg, ring_hom.map_one, sub_neg_eq_add] end /-- `cyclotomic' n R` is monic. -/ lemma cyclotomic'.monic (n : ℕ) (R : Type*) [comm_ring R] [is_domain R] : (cyclotomic' n R).monic := monic_prod_of_monic _ _ $ λ z hz, monic_X_sub_C _ /-- `cyclotomic' n R` is different from `0`. -/ lemma cyclotomic'_ne_zero (n : ℕ) (R : Type*) [comm_ring R] [is_domain R] : cyclotomic' n R ≠ 0 := (cyclotomic'.monic n R).ne_zero /-- The natural degree of `cyclotomic' n R` is `totient n` if there is a primitive root of unity in `R`. -/ lemma nat_degree_cyclotomic' {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) : (cyclotomic' n R).nat_degree = nat.totient n := begin rw [cyclotomic'], rw nat_degree_prod (primitive_roots n R) (λ (z : R), (X - C z)), simp only [is_primitive_root.card_primitive_roots h, mul_one, nat_degree_X_sub_C, nat.cast_id, finset.sum_const, nsmul_eq_mul], intros z hz, exact X_sub_C_ne_zero z end /-- The degree of `cyclotomic' n R` is `totient n` if there is a primitive root of unity in `R`. -/ lemma degree_cyclotomic' {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) : (cyclotomic' n R).degree = nat.totient n := by simp only [degree_eq_nat_degree (cyclotomic'_ne_zero n R), nat_degree_cyclotomic' h] /-- The roots of `cyclotomic' n R` are the primitive `n`-th roots of unity. -/ lemma roots_of_cyclotomic (n : ℕ) (R : Type*) [comm_ring R] [is_domain R] : (cyclotomic' n R).roots = (primitive_roots n R).val := by { rw cyclotomic', exact roots_prod_X_sub_C (primitive_roots n R) } /-- If there is a primitive `n`th root of unity in `K`, then `X ^ n - 1 = ∏ (X - μ)`, where `μ` varies over the `n`-th roots of unity. -/ lemma X_pow_sub_one_eq_prod {ζ : R} {n : ℕ} (hpos : 0 < n) (h : is_primitive_root ζ n) : X ^ n - 1 = ∏ ζ in nth_roots_finset n R, (X - C ζ) := begin rw [nth_roots_finset, ← multiset.to_finset_eq (is_primitive_root.nth_roots_nodup h)], simp only [finset.prod_mk, ring_hom.map_one], rw [nth_roots], have hmonic : (X ^ n - C (1 : R)).monic := monic_X_pow_sub_C (1 : R) (ne_of_lt hpos).symm, symmetry, apply prod_multiset_X_sub_C_of_monic_of_roots_card_eq hmonic, rw [@nat_degree_X_pow_sub_C R _ _ n 1, ← nth_roots], exact is_primitive_root.card_nth_roots h end end is_domain section field variables {K : Type*} [field K] /-- `cyclotomic' n K` splits. -/ lemma cyclotomic'_splits (n : ℕ) : splits (ring_hom.id K) (cyclotomic' n K) := begin apply splits_prod (ring_hom.id K), intros z hz, simp only [splits_X_sub_C (ring_hom.id K)] end /-- If there is a primitive `n`-th root of unity in `K`, then `X ^ n - 1`splits. -/ lemma X_pow_sub_one_splits {ζ : K} {n : ℕ} (h : is_primitive_root ζ n) : splits (ring_hom.id K) (X ^ n - C (1 : K)) := by rw [splits_iff_card_roots, ← nth_roots, is_primitive_root.card_nth_roots h, nat_degree_X_pow_sub_C] /-- If there is a primitive `n`-th root of unity in `K`, then `∏ i in nat.divisors n, cyclotomic' i K = X ^ n - 1`. -/ lemma prod_cyclotomic'_eq_X_pow_sub_one {K : Type*} [comm_ring K] [is_domain K] {ζ : K} {n : ℕ} (hpos : 0 < n) (h : is_primitive_root ζ n) : ∏ i in nat.divisors n, cyclotomic' i K = X ^ n - 1 := begin rw [X_pow_sub_one_eq_prod hpos h], have rwcyc : ∀ i ∈ nat.divisors n, cyclotomic' i K = ∏ μ in primitive_roots i K, (X - C μ), { intros i hi, simp only [cyclotomic'] }, conv_lhs { apply_congr, skip, simp [rwcyc, H] }, rw ← finset.prod_bUnion, { simp only [is_primitive_root.nth_roots_one_eq_bUnion_primitive_roots h] }, intros x hx y hy hdiff, exact is_primitive_root.disjoint hdiff, end /-- If there is a primitive `n`-th root of unity in `K`, then `cyclotomic' n K = (X ^ k - 1) /ₘ (∏ i in nat.proper_divisors k, cyclotomic' i K)`. -/ lemma cyclotomic'_eq_X_pow_sub_one_div {K : Type*} [comm_ring K] [is_domain K] {ζ : K} {n : ℕ} (hpos : 0 < n) (h : is_primitive_root ζ n) : cyclotomic' n K = (X ^ n - 1) /ₘ (∏ i in nat.proper_divisors n, cyclotomic' i K) := begin rw [←prod_cyclotomic'_eq_X_pow_sub_one hpos h, nat.divisors_eq_proper_divisors_insert_self_of_pos hpos, finset.prod_insert nat.proper_divisors.not_self_mem], have prod_monic : (∏ i in nat.proper_divisors n, cyclotomic' i K).monic, { apply monic_prod_of_monic, intros i hi, exact cyclotomic'.monic i K }, rw (div_mod_by_monic_unique (cyclotomic' n K) 0 prod_monic _).1, simp only [degree_zero, zero_add], refine ⟨by rw mul_comm, _⟩, rw [bot_lt_iff_ne_bot], intro h, exact monic.ne_zero prod_monic (degree_eq_bot.1 h) end /-- If there is a primitive `n`-th root of unity in `K`, then `cyclotomic' n K` comes from a monic polynomial with integer coefficients. -/ lemma int_coeff_of_cyclotomic' {K : Type*} [comm_ring K] [is_domain K] {ζ : K} {n : ℕ} (h : is_primitive_root ζ n) : (∃ (P : ℤ[X]), map (int.cast_ring_hom K) P = cyclotomic' n K ∧ P.degree = (cyclotomic' n K).degree ∧ P.monic) := begin refine lifts_and_degree_eq_and_monic _ (cyclotomic'.monic n K), induction n using nat.strong_induction_on with k hk generalizing ζ h, cases nat.eq_zero_or_pos k with hzero hpos, { use 1, simp only [hzero, cyclotomic'_zero, set.mem_univ, subsemiring.coe_top, eq_self_iff_true, coe_map_ring_hom, polynomial.map_one, and_self] }, let B : K[X] := ∏ i in nat.proper_divisors k, cyclotomic' i K, have Bmo : B.monic, { apply monic_prod_of_monic, intros i hi, exact (cyclotomic'.monic i K) }, have Bint : B ∈ lifts (int.cast_ring_hom K), { refine subsemiring.prod_mem (lifts (int.cast_ring_hom K)) _, intros x hx, have xsmall := (nat.mem_proper_divisors.1 hx).2, obtain ⟨d, hd⟩ := (nat.mem_proper_divisors.1 hx).1, rw [mul_comm] at hd, exact hk x xsmall (is_primitive_root.pow hpos h hd) }, replace Bint := lifts_and_degree_eq_and_monic Bint Bmo, obtain ⟨B₁, hB₁, hB₁deg, hB₁mo⟩ := Bint, let Q₁ : ℤ[X] := (X ^ k - 1) /ₘ B₁, have huniq : 0 + B * cyclotomic' k K = X ^ k - 1 ∧ (0 : K[X]).degree < B.degree, { split, { rw [zero_add, mul_comm, ←(prod_cyclotomic'_eq_X_pow_sub_one hpos h), nat.divisors_eq_proper_divisors_insert_self_of_pos hpos], simp only [true_and, finset.prod_insert, not_lt, nat.mem_proper_divisors, dvd_refl] }, rw [degree_zero, bot_lt_iff_ne_bot], intro habs, exact (monic.ne_zero Bmo) (degree_eq_bot.1 habs) }, replace huniq := div_mod_by_monic_unique (cyclotomic' k K) (0 : K[X]) Bmo huniq, simp only [lifts, ring_hom.mem_srange], use Q₁, rw [coe_map_ring_hom, (map_div_by_monic (int.cast_ring_hom K) hB₁mo), hB₁, ← huniq.1], simp end /-- If `K` is of characteristic `0` and there is a primitive `n`-th root of unity in `K`, then `cyclotomic n K` comes from a unique polynomial with integer coefficients. -/ lemma unique_int_coeff_of_cycl {K : Type*} [comm_ring K] [is_domain K] [char_zero K] {ζ : K} {n : ℕ+} (h : is_primitive_root ζ n) : (∃! (P : ℤ[X]), map (int.cast_ring_hom K) P = cyclotomic' n K) := begin obtain ⟨P, hP⟩ := int_coeff_of_cyclotomic' h, refine ⟨P, hP.1, λ Q hQ, _⟩, apply (map_injective (int.cast_ring_hom K) int.cast_injective), rw [hP.1, hQ] end end field end cyclotomic' section cyclotomic /-- The `n`-th cyclotomic polynomial with coefficients in `R`. -/ def cyclotomic (n : ℕ) (R : Type*) [ring R] : R[X] := if h : n = 0 then 1 else map (int.cast_ring_hom R) ((int_coeff_of_cyclotomic' (complex.is_primitive_root_exp n h)).some) lemma int_cyclotomic_rw {n : ℕ} (h : n ≠ 0) : cyclotomic n ℤ = (int_coeff_of_cyclotomic' (complex.is_primitive_root_exp n h)).some := begin simp only [cyclotomic, h, dif_neg, not_false_iff], ext i, simp only [coeff_map, int.cast_id, ring_hom.eq_int_cast] end /-- `cyclotomic n R` comes from `cyclotomic n ℤ`. -/ lemma map_cyclotomic_int (n : ℕ) (R : Type*) [ring R] : map (int.cast_ring_hom R) (cyclotomic n ℤ) = cyclotomic n R := begin by_cases hzero : n = 0, { simp only [hzero, cyclotomic, dif_pos, polynomial.map_one] }, simp only [cyclotomic, int_cyclotomic_rw, hzero, ne.def, dif_neg, not_false_iff] end lemma int_cyclotomic_spec (n : ℕ) : map (int.cast_ring_hom ℂ) (cyclotomic n ℤ) = cyclotomic' n ℂ ∧ (cyclotomic n ℤ).degree = (cyclotomic' n ℂ).degree ∧ (cyclotomic n ℤ).monic := begin by_cases hzero : n = 0, { simp only [hzero, cyclotomic, degree_one, monic_one, cyclotomic'_zero, dif_pos, eq_self_iff_true, polynomial.map_one, and_self] }, rw int_cyclotomic_rw hzero, exact (int_coeff_of_cyclotomic' (complex.is_primitive_root_exp n hzero)).some_spec end lemma int_cyclotomic_unique {n : ℕ} {P : ℤ[X]} (h : map (int.cast_ring_hom ℂ) P = cyclotomic' n ℂ) : P = cyclotomic n ℤ := begin apply map_injective (int.cast_ring_hom ℂ) int.cast_injective, rw [h, (int_cyclotomic_spec n).1] end /-- The definition of `cyclotomic n R` commutes with any ring homomorphism. -/ @[simp] lemma map_cyclotomic (n : ℕ) {R S : Type*} [ring R] [ring S] (f : R →+* S) : map f (cyclotomic n R) = cyclotomic n S := begin rw [←map_cyclotomic_int n R, ←map_cyclotomic_int n S], ext i, simp only [coeff_map, ring_hom.eq_int_cast, ring_hom.map_int_cast] end lemma cyclotomic.eval_apply {R S : Type*} (q : R) (n : ℕ) [ring R] [ring S] (f : R →+* S) : eval (f q) (cyclotomic n S) = f (eval q (cyclotomic n R)) := by rw [← map_cyclotomic n f, eval_map, eval₂_at_apply] /-- The zeroth cyclotomic polyomial is `1`. -/ @[simp] lemma cyclotomic_zero (R : Type*) [ring R] : cyclotomic 0 R = 1 := by simp only [cyclotomic, dif_pos] /-- The first cyclotomic polyomial is `X - 1`. -/ @[simp] lemma cyclotomic_one (R : Type*) [ring R] : cyclotomic 1 R = X - 1 := begin have hspec : map (int.cast_ring_hom ℂ) (X - 1) = cyclotomic' 1 ℂ, { simp only [cyclotomic'_one, pnat.one_coe, map_X, polynomial.map_one, polynomial.map_sub] }, symmetry, rw [←map_cyclotomic_int, ←(int_cyclotomic_unique hspec)], simp only [map_X, polynomial.map_one, polynomial.map_sub] end /-- The second cyclotomic polyomial is `X + 1`. -/ @[simp] lemma cyclotomic_two (R : Type*) [ring R] : cyclotomic 2 R = X + 1 := begin have hspec : map (int.cast_ring_hom ℂ) (X + 1) = cyclotomic' 2 ℂ, { simp only [cyclotomic'_two ℂ 0 two_ne_zero.symm, polynomial.map_add, map_X, polynomial.map_one], }, symmetry, rw [←map_cyclotomic_int, ←(int_cyclotomic_unique hspec)], simp only [polynomial.map_add, map_X, polynomial.map_one] end /-- `cyclotomic n` is monic. -/ lemma cyclotomic.monic (n : ℕ) (R : Type*) [ring R] : (cyclotomic n R).monic := begin rw ←map_cyclotomic_int, exact (int_cyclotomic_spec n).2.2.map _, end /-- `cyclotomic n` is primitive. -/ lemma cyclotomic.is_primitive (n : ℕ) (R : Type*) [comm_ring R] : (cyclotomic n R).is_primitive := (cyclotomic.monic n R).is_primitive /-- `cyclotomic n R` is different from `0`. -/ lemma cyclotomic_ne_zero (n : ℕ) (R : Type*) [ring R] [nontrivial R] : cyclotomic n R ≠ 0 := (cyclotomic.monic n R).ne_zero /-- The degree of `cyclotomic n` is `totient n`. -/ lemma degree_cyclotomic (n : ℕ) (R : Type*) [ring R] [nontrivial R] : (cyclotomic n R).degree = nat.totient n := begin rw ←map_cyclotomic_int, rw degree_map_eq_of_leading_coeff_ne_zero (int.cast_ring_hom R) _, { cases n with k, { simp only [cyclotomic, degree_one, dif_pos, nat.totient_zero, with_top.coe_zero]}, rw [←degree_cyclotomic' (complex.is_primitive_root_exp k.succ (nat.succ_ne_zero k))], exact (int_cyclotomic_spec k.succ).2.1 }, simp only [(int_cyclotomic_spec n).right.right, ring_hom.eq_int_cast, monic.leading_coeff, int.cast_one, ne.def, not_false_iff, one_ne_zero] end /-- The natural degree of `cyclotomic n` is `totient n`. -/ lemma nat_degree_cyclotomic (n : ℕ) (R : Type*) [ring R] [nontrivial R] : (cyclotomic n R).nat_degree = nat.totient n := begin have hdeg := degree_cyclotomic n R, rw degree_eq_nat_degree (cyclotomic_ne_zero n R) at hdeg, exact_mod_cast hdeg end /-- The degree of `cyclotomic n R` is positive. -/ lemma degree_cyclotomic_pos (n : ℕ) (R : Type*) (hpos : 0 < n) [ring R] [nontrivial R] : 0 < (cyclotomic n R).degree := by { rw degree_cyclotomic n R, exact_mod_cast (nat.totient_pos hpos) } /-- `∏ i in nat.divisors n, cyclotomic i R = X ^ n - 1`. -/ lemma prod_cyclotomic_eq_X_pow_sub_one {n : ℕ} (hpos : 0 < n) (R : Type*) [comm_ring R] : ∏ i in nat.divisors n, cyclotomic i R = X ^ n - 1 := begin have integer : ∏ i in nat.divisors n, cyclotomic i ℤ = X ^ n - 1, { apply map_injective (int.cast_ring_hom ℂ) int.cast_injective, rw polynomial.map_prod (int.cast_ring_hom ℂ) (λ i, cyclotomic i ℤ), simp only [int_cyclotomic_spec, polynomial.map_pow, nat.cast_id, map_X, polynomial.map_one, polynomial.map_sub], exact prod_cyclotomic'_eq_X_pow_sub_one hpos (complex.is_primitive_root_exp n (ne_of_lt hpos).symm) }, have coerc : X ^ n - 1 = map (int.cast_ring_hom R) (X ^ n - 1), { simp only [polynomial.map_pow, polynomial.map_X, polynomial.map_one, polynomial.map_sub] }, have h : ∀ i ∈ n.divisors, cyclotomic i R = map (int.cast_ring_hom R) (cyclotomic i ℤ), { intros i hi, exact (map_cyclotomic_int i R).symm }, rw [finset.prod_congr (refl n.divisors) h, coerc, ← polynomial.map_prod (int.cast_ring_hom R) (λ i, cyclotomic i ℤ), integer] end lemma cyclotomic.dvd_X_pow_sub_one (n : ℕ) (R : Type*) [comm_ring R] : (cyclotomic n R) ∣ X ^ n - 1 := begin rcases n.eq_zero_or_pos with rfl | hn, { simp }, refine ⟨∏ i in n.proper_divisors, cyclotomic i R, _⟩, rw [←prod_cyclotomic_eq_X_pow_sub_one hn, nat.divisors_eq_proper_divisors_insert_self_of_pos hn, finset.prod_insert], exact nat.proper_divisors.not_self_mem end open_locale big_operators open finset lemma prod_cyclotomic_eq_geom_sum {n : ℕ} (h : 0 < n) (R) [comm_ring R] [is_domain R] : ∏ i in n.divisors \ {1}, cyclotomic i R = ∑ i in range n, X ^ i := begin apply_fun (* cyclotomic 1 R) using mul_left_injective₀ (cyclotomic_ne_zero 1 R), have : ∏ i in {1}, cyclotomic i R = cyclotomic 1 R := finset.prod_singleton, simp_rw [←this, finset.prod_sdiff $ show {1} ⊆ n.divisors, by simp [h.ne'], this, cyclotomic_one, geom_sum_mul, prod_cyclotomic_eq_X_pow_sub_one h] end lemma cyclotomic_dvd_geom_sum_of_dvd (R) [comm_ring R] {d n : ℕ} (hdn : d ∣ n) (hd : d ≠ 1) : cyclotomic d R ∣ ∑ i in range n, X ^ i := begin suffices : (cyclotomic d ℤ).map (int.cast_ring_hom R) ∣ (∑ i in range n, X ^ i).map (int.cast_ring_hom R), { have key := (map_ring_hom (int.cast_ring_hom R)).map_geom_sum X n, simp only [coe_map_ring_hom, map_X] at key, rwa [map_cyclotomic, key] at this }, apply map_dvd, rcases n.eq_zero_or_pos with rfl | hn, { simp }, rw ←prod_cyclotomic_eq_geom_sum hn, apply finset.dvd_prod_of_mem, simp [hd, hdn, hn.ne'] end lemma X_pow_sub_one_mul_prod_cyclotomic_eq_X_pow_sub_one_of_dvd (R) [comm_ring R] {d n : ℕ} (h : d ∈ n.proper_divisors) : (X ^ d - 1) * ∏ x in n.divisors \ d.divisors, cyclotomic x R = X ^ n - 1 := begin obtain ⟨hd, hdn⟩ := nat.mem_proper_divisors.mp h, have h0n := pos_of_gt hdn, rcases d.eq_zero_or_pos with rfl | h0d, { exfalso, linarith [eq_zero_of_zero_dvd hd] }, rw [←prod_cyclotomic_eq_X_pow_sub_one h0d, ←prod_cyclotomic_eq_X_pow_sub_one h0n, mul_comm, finset.prod_sdiff (nat.divisors_subset_of_dvd h0n.ne' hd)] end lemma X_pow_sub_one_mul_cyclotomic_dvd_X_pow_sub_one_of_dvd (R) [comm_ring R] {d n : ℕ} (h : d ∈ n.proper_divisors) : (X ^ d - 1) * cyclotomic n R ∣ X ^ n - 1 := begin have hdn := (nat.mem_proper_divisors.mp h).2, use ∏ x in n.proper_divisors \ d.divisors, cyclotomic x R, symmetry, convert X_pow_sub_one_mul_prod_cyclotomic_eq_X_pow_sub_one_of_dvd R h using 1, rw mul_assoc, congr' 1, rw [nat.divisors_eq_proper_divisors_insert_self_of_pos $ pos_of_gt hdn, finset.insert_sdiff_of_not_mem, finset.prod_insert], { exact finset.not_mem_sdiff_of_not_mem_left nat.proper_divisors.not_self_mem }, { exact λ hk, hdn.not_le $ nat.divisor_le hk } end lemma _root_.is_root_of_unity_iff {n : ℕ} (h : 0 < n) (R : Type*) [comm_ring R] [is_domain R] {ζ : R} : ζ ^ n = 1 ↔ ∃ i ∈ n.divisors, (cyclotomic i R).is_root ζ := by rw [←mem_nth_roots h, nth_roots, mem_roots $ X_pow_sub_C_ne_zero h _, C_1, ←prod_cyclotomic_eq_X_pow_sub_one h, is_root_prod]; apply_instance lemma is_root_of_unity_of_root_cyclotomic {n : ℕ} {R} [comm_ring R] {ζ : R} {i : ℕ} (hi : i ∈ n.divisors) (h : (cyclotomic i R).is_root ζ) : ζ ^ n = 1 := begin rcases n.eq_zero_or_pos with rfl | hn, { exact pow_zero _ }, have := congr_arg (eval ζ) (prod_cyclotomic_eq_X_pow_sub_one hn R).symm, rw [eval_sub, eval_pow, eval_X, eval_one] at this, convert eq_add_of_sub_eq' this, convert (add_zero _).symm, apply eval_eq_zero_of_dvd_of_eval_eq_zero _ h, exact finset.dvd_prod_of_mem _ hi end section arithmetic_function open nat.arithmetic_function open_locale arithmetic_function /-- `cyclotomic n R` can be expressed as a product in a fraction field of `polynomial R` using Möbius inversion. -/ lemma cyclotomic_eq_prod_X_pow_sub_one_pow_moebius {n : ℕ} (R : Type*) [comm_ring R] [is_domain R] : algebra_map _ (ratfunc R) (cyclotomic n R) = ∏ i in n.divisors_antidiagonal, (algebra_map R[X] _ (X ^ i.snd - 1)) ^ μ i.fst := begin rcases n.eq_zero_or_pos with rfl | hpos, { simp }, have h : ∀ (n : ℕ), 0 < n → ∏ i in nat.divisors n, algebra_map _ (ratfunc R) (cyclotomic i R) = algebra_map _ _ (X ^ n - 1), { intros n hn, rw [← prod_cyclotomic_eq_X_pow_sub_one hn R, ring_hom.map_prod] }, rw (prod_eq_iff_prod_pow_moebius_eq_of_nonzero (λ n hn, _) (λ n hn, _)).1 h n hpos; rw [ne.def, is_fraction_ring.to_map_eq_zero_iff], { apply cyclotomic_ne_zero }, { apply monic.ne_zero, apply monic_X_pow_sub_C _ (ne_of_gt hn) } end end arithmetic_function /-- We have `cyclotomic n R = (X ^ k - 1) /ₘ (∏ i in nat.proper_divisors k, cyclotomic i K)`. -/ lemma cyclotomic_eq_X_pow_sub_one_div {R : Type*} [comm_ring R] {n : ℕ} (hpos: 0 < n) : cyclotomic n R = (X ^ n - 1) /ₘ (∏ i in nat.proper_divisors n, cyclotomic i R) := begin nontriviality R, rw [←prod_cyclotomic_eq_X_pow_sub_one hpos, nat.divisors_eq_proper_divisors_insert_self_of_pos hpos, finset.prod_insert nat.proper_divisors.not_self_mem], have prod_monic : (∏ i in nat.proper_divisors n, cyclotomic i R).monic, { apply monic_prod_of_monic, intros i hi, exact cyclotomic.monic i R }, rw (div_mod_by_monic_unique (cyclotomic n R) 0 prod_monic _).1, simp only [degree_zero, zero_add], split, { rw mul_comm }, rw [bot_lt_iff_ne_bot], intro h, exact monic.ne_zero prod_monic (degree_eq_bot.1 h) end /-- If `m` is a proper divisor of `n`, then `X ^ m - 1` divides `∏ i in nat.proper_divisors n, cyclotomic i R`. -/ lemma X_pow_sub_one_dvd_prod_cyclotomic (R : Type*) [comm_ring R] {n m : ℕ} (hpos : 0 < n) (hm : m ∣ n) (hdiff : m ≠ n) : X ^ m - 1 ∣ ∏ i in nat.proper_divisors n, cyclotomic i R := begin replace hm := nat.mem_proper_divisors.2 ⟨hm, lt_of_le_of_ne (nat.divisor_le (nat.mem_divisors.2 ⟨hm, (ne_of_lt hpos).symm⟩)) hdiff⟩, rw [← finset.sdiff_union_of_subset (nat.divisors_subset_proper_divisors (ne_of_lt hpos).symm (nat.mem_proper_divisors.1 hm).1 (ne_of_lt (nat.mem_proper_divisors.1 hm).2)), finset.prod_union finset.sdiff_disjoint, prod_cyclotomic_eq_X_pow_sub_one (nat.pos_of_mem_proper_divisors hm)], exact ⟨(∏ (x : ℕ) in n.proper_divisors \ m.divisors, cyclotomic x R), by rw mul_comm⟩ end /-- If there is a primitive `n`-th root of unity in `K`, then `cyclotomic n K = ∏ μ in primitive_roots n R, (X - C μ)`. In particular, `cyclotomic n K = cyclotomic' n K` -/ lemma cyclotomic_eq_prod_X_sub_primitive_roots {K : Type*} [comm_ring K] [is_domain K] {ζ : K} {n : ℕ} (hz : is_primitive_root ζ n) : cyclotomic n K = ∏ μ in primitive_roots n K, (X - C μ) := begin rw ←cyclotomic', induction n using nat.strong_induction_on with k hk generalizing ζ hz, obtain hzero | hpos := k.eq_zero_or_pos, { simp only [hzero, cyclotomic'_zero, cyclotomic_zero] }, have h : ∀ i ∈ k.proper_divisors, cyclotomic i K = cyclotomic' i K, { intros i hi, obtain ⟨d, hd⟩ := (nat.mem_proper_divisors.1 hi).1, rw mul_comm at hd, exact hk i (nat.mem_proper_divisors.1 hi).2 (is_primitive_root.pow hpos hz hd) }, rw [@cyclotomic_eq_X_pow_sub_one_div _ _ _ hpos, cyclotomic'_eq_X_pow_sub_one_div hpos hz, finset.prod_congr (refl k.proper_divisors) h] end section roots variables {R : Type*} {n : ℕ} [comm_ring R] [is_domain R] /-- Any `n`-th primitive root of unity is a root of `cyclotomic n K`.-/ lemma _root_.is_primitive_root.is_root_cyclotomic (hpos : 0 < n) {μ : R} (h : is_primitive_root μ n) : is_root (cyclotomic n R) μ := begin rw [← mem_roots (cyclotomic_ne_zero n R), cyclotomic_eq_prod_X_sub_primitive_roots h, roots_prod_X_sub_C, ← finset.mem_def], rwa [← mem_primitive_roots hpos] at h, end private lemma is_root_cyclotomic_iff' {n : ℕ} {K : Type*} [field K] {μ : K} [ne_zero (n : K)] : is_root (cyclotomic n K) μ ↔ is_primitive_root μ n := begin -- in this proof, `o` stands for `order_of μ` have hnpos : 0 < n := (ne_zero.of_ne_zero_coe K).out.bot_lt, refine ⟨λ hμ, _, is_primitive_root.is_root_cyclotomic hnpos⟩, have hμn : μ ^ n = 1, { rw is_root_of_unity_iff hnpos, exact ⟨n, n.mem_divisors_self hnpos.ne', hμ⟩ }, by_contra hnμ, have ho : 0 < order_of μ, { apply order_of_pos', rw is_of_fin_order_iff_pow_eq_one, exact ⟨n, hnpos, hμn⟩ }, have := pow_order_of_eq_one μ, rw is_root_of_unity_iff ho at this, obtain ⟨i, hio, hiμ⟩ := this, replace hio := nat.dvd_of_mem_divisors hio, rw is_primitive_root.not_iff at hnμ, rw ←order_of_dvd_iff_pow_eq_one at hμn, have key : i < n := (nat.le_of_dvd ho hio).trans_lt ((nat.le_of_dvd hnpos hμn).lt_of_ne hnμ), have key' : i ∣ n := hio.trans hμn, rw ←polynomial.dvd_iff_is_root at hμ hiμ, have hni : {i, n} ⊆ n.divisors, { simpa [finset.insert_subset, key'] using hnpos.ne' }, obtain ⟨k, hk⟩ := hiμ, obtain ⟨j, hj⟩ := hμ, have := prod_cyclotomic_eq_X_pow_sub_one hnpos K, rw [←finset.prod_sdiff hni, finset.prod_pair key.ne, hk, hj] at this, have hn := (X_pow_sub_one_separable_iff.mpr $ ne_zero.ne' n K).squarefree, rw [←this, squarefree] at hn, contrapose! hn, refine ⟨X - C μ, ⟨(∏ x in n.divisors \ {i, n}, cyclotomic x K) * k * j, by ring⟩, _⟩, simp [polynomial.is_unit_iff_degree_eq_zero] end lemma is_root_cyclotomic_iff [ne_zero (n : R)] {μ : R} : is_root (cyclotomic n R) μ ↔ is_primitive_root μ n := begin have hf : function.injective _ := is_fraction_ring.injective R (fraction_ring R), haveI : ne_zero (n : fraction_ring R) := ne_zero.nat_of_injective hf, rw [←is_root_map_iff hf, ←is_primitive_root.map_iff_of_injective hf, map_cyclotomic, ←is_root_cyclotomic_iff'] end lemma roots_cyclotomic_nodup [ne_zero (n : R)] : (cyclotomic n R).roots.nodup := begin obtain h | ⟨ζ, hζ⟩ := (cyclotomic n R).roots.empty_or_exists_mem, { exact h.symm ▸ multiset.nodup_zero }, rw [mem_roots $ cyclotomic_ne_zero n R, is_root_cyclotomic_iff] at hζ, refine multiset.nodup_of_le (roots.le_of_dvd (X_pow_sub_C_ne_zero (ne_zero.pos_of_ne_zero_coe R) 1) $ cyclotomic.dvd_X_pow_sub_one n R) hζ.nth_roots_nodup, end lemma cyclotomic.roots_to_finset_eq_primitive_roots [ne_zero (n : R)] : (⟨(cyclotomic n R).roots, roots_cyclotomic_nodup⟩ : finset _) = primitive_roots n R := by { ext, simp [cyclotomic_ne_zero n R, is_root_cyclotomic_iff, mem_primitive_roots, ne_zero.pos_of_ne_zero_coe R] } lemma cyclotomic.roots_eq_primitive_roots_val [ne_zero (n : R)] : (cyclotomic n R).roots = (primitive_roots n R).val := by rw ←cyclotomic.roots_to_finset_eq_primitive_roots end roots /-- If `R` is of characteristic zero, then `ζ` is a root of `cyclotomic n R` if and only if it is a primitive `n`-th root of unity. -/ lemma is_root_cyclotomic_iff_char_zero {n : ℕ} {R : Type*} [comm_ring R] [is_domain R] [char_zero R] {μ : R} (hn : 0 < n) : (polynomial.cyclotomic n R).is_root μ ↔ is_primitive_root μ n := by { letI := ne_zero.of_gt hn, exact is_root_cyclotomic_iff } /-- Over a ring `R` of characteristic zero, `λ n, cyclotomic n R` is injective. -/ lemma cyclotomic_injective {R : Type*} [comm_ring R] [char_zero R] : function.injective (λ n, cyclotomic n R) := begin intros n m hnm, simp only at hnm, rcases eq_or_ne n 0 with rfl | hzero, { rw [cyclotomic_zero] at hnm, replace hnm := congr_arg nat_degree hnm, rw [nat_degree_one, nat_degree_cyclotomic] at hnm, by_contra, exact (nat.totient_pos (zero_lt_iff.2 (ne.symm h))).ne hnm }, { haveI := ne_zero.mk hzero, rw [← map_cyclotomic_int _ R, ← map_cyclotomic_int _ R] at hnm, replace hnm := map_injective (int.cast_ring_hom R) int.cast_injective hnm, replace hnm := congr_arg (map (int.cast_ring_hom ℂ)) hnm, rw [map_cyclotomic_int, map_cyclotomic_int] at hnm, have hprim := complex.is_primitive_root_exp _ hzero, have hroot := is_root_cyclotomic_iff.2 hprim, rw hnm at hroot, haveI hmzero : ne_zero m := ⟨λ h, by simpa [h] using hroot⟩, rw is_root_cyclotomic_iff at hroot, replace hprim := hprim.eq_order_of, rwa [← is_primitive_root.eq_order_of hroot] at hprim} end lemma eq_cyclotomic_iff {R : Type*} [comm_ring R] {n : ℕ} (hpos: 0 < n) (P : R[X]) : P = cyclotomic n R ↔ P * (∏ i in nat.proper_divisors n, polynomial.cyclotomic i R) = X ^ n - 1 := begin nontriviality R, refine ⟨λ hcycl, _, λ hP, _⟩, { rw [hcycl, ← finset.prod_insert (@nat.proper_divisors.not_self_mem n), ← nat.divisors_eq_proper_divisors_insert_self_of_pos hpos], exact prod_cyclotomic_eq_X_pow_sub_one hpos R }, { have prod_monic : (∏ i in nat.proper_divisors n, cyclotomic i R).monic, { apply monic_prod_of_monic, intros i hi, exact cyclotomic.monic i R }, rw [@cyclotomic_eq_X_pow_sub_one_div R _ _ hpos, (div_mod_by_monic_unique P 0 prod_monic _).1], refine ⟨by rwa [zero_add, mul_comm], _⟩, rw [degree_zero, bot_lt_iff_ne_bot], intro h, exact monic.ne_zero prod_monic (degree_eq_bot.1 h) }, end /-- If `p` is prime, then `cyclotomic p R = ∑ i in range p, X ^ i`. -/ lemma cyclotomic_eq_geom_sum {R : Type*} [comm_ring R] {p : ℕ} (hp : nat.prime p) : cyclotomic p R = ∑ i in range p, X ^ i := begin refine ((eq_cyclotomic_iff hp.pos _).mpr _).symm, simp only [nat.prime.proper_divisors hp, geom_sum_mul, finset.prod_singleton, cyclotomic_one], end lemma cyclotomic_prime_mul_X_sub_one (R : Type*) [comm_ring R] (p : ℕ) [hn : fact (nat.prime p)] : (cyclotomic p R) * (X - 1) = X ^ p - 1 := by rw [cyclotomic_eq_geom_sum hn.out, geom_sum_mul] /-- If `p ^ k` is a prime power, then `cyclotomic (p ^ (n + 1)) R = ∑ i in range p, (X ^ (p ^ n)) ^ i`. -/ lemma cyclotomic_prime_pow_eq_geom_sum {R : Type*} [comm_ring R] {p n : ℕ} (hp : nat.prime p) : cyclotomic (p ^ (n + 1)) R = ∑ i in range p, (X ^ (p ^ n)) ^ i := begin have : ∀ m, cyclotomic (p ^ (m + 1)) R = ∑ i in range p, (X ^ (p ^ m)) ^ i ↔ (∑ i in range p, (X ^ (p ^ m)) ^ i) * ∏ (x : ℕ) in finset.range (m + 1), cyclotomic (p ^ x) R = X ^ p ^ (m + 1) - 1, { intro m, have := eq_cyclotomic_iff (pow_pos hp.pos (m + 1)) _, rw eq_comm at this, rw [this, nat.prod_proper_divisors_prime_pow hp], }, induction n with n_n n_ih, { simp [cyclotomic_eq_geom_sum hp], }, rw ((eq_cyclotomic_iff (pow_pos hp.pos (n_n.succ + 1)) _).mpr _).symm, rw [nat.prod_proper_divisors_prime_pow hp, finset.prod_range_succ, n_ih], rw this at n_ih, rw [mul_comm _ (∑ i in _, _), n_ih, geom_sum_mul, sub_left_inj, ← pow_mul, pow_add, pow_one], end lemma cyclotomic_prime_pow_mul_X_pow_sub_one (R : Type*) [comm_ring R] (p k : ℕ) [hn : fact (nat.prime p)] : (cyclotomic (p ^ (k + 1)) R) * (X ^ (p ^ k) - 1) = X ^ (p ^ (k + 1)) - 1 := by rw [cyclotomic_prime_pow_eq_geom_sum hn.out, geom_sum_mul, ← pow_mul, pow_succ, mul_comm] /-- The constant term of `cyclotomic n R` is `1` if `2 ≤ n`. -/ lemma cyclotomic_coeff_zero (R : Type*) [comm_ring R] {n : ℕ} (hn : 2 ≤ n) : (cyclotomic n R).coeff 0 = 1 := begin induction n using nat.strong_induction_on with n hi, have hprod : (∏ i in nat.proper_divisors n, (polynomial.cyclotomic i R).coeff 0) = -1, { rw [←finset.insert_erase (nat.one_mem_proper_divisors_iff_one_lt.2 (lt_of_lt_of_le one_lt_two hn)), finset.prod_insert (finset.not_mem_erase 1 _), cyclotomic_one R], have hleq : ∀ j ∈ n.proper_divisors.erase 1, 2 ≤ j, { intros j hj, apply nat.succ_le_of_lt, exact (ne.le_iff_lt ((finset.mem_erase.1 hj).1).symm).mp (nat.succ_le_of_lt (nat.pos_of_mem_proper_divisors (finset.mem_erase.1 hj).2)) }, have hcongr : ∀ j ∈ n.proper_divisors.erase 1, (cyclotomic j R).coeff 0 = 1, { intros j hj, exact hi j (nat.mem_proper_divisors.1 (finset.mem_erase.1 hj).2).2 (hleq j hj) }, have hrw : ∏ (x : ℕ) in n.proper_divisors.erase 1, (cyclotomic x R).coeff 0 = 1, { rw finset.prod_congr (refl (n.proper_divisors.erase 1)) hcongr, simp only [finset.prod_const_one] }, simp only [hrw, mul_one, zero_sub, coeff_one_zero, coeff_X_zero, coeff_sub] }, have heq : (X ^ n - 1).coeff 0 = -(cyclotomic n R).coeff 0, { rw [←prod_cyclotomic_eq_X_pow_sub_one (lt_of_lt_of_le zero_lt_two hn), nat.divisors_eq_proper_divisors_insert_self_of_pos (lt_of_lt_of_le zero_lt_two hn), finset.prod_insert nat.proper_divisors.not_self_mem, mul_coeff_zero, coeff_zero_prod, hprod, mul_neg, mul_one] }, have hzero : (X ^ n - 1).coeff 0 = (-1 : R), { rw coeff_zero_eq_eval_zero _, simp only [zero_pow (lt_of_lt_of_le zero_lt_two hn), eval_X, eval_one, zero_sub, eval_pow, eval_sub] }, rw hzero at heq, exact neg_inj.mp (eq.symm heq) end /-- If `(a : ℕ)` is a root of `cyclotomic n (zmod p)`, where `p` is a prime, then `a` and `p` are coprime. -/ lemma coprime_of_root_cyclotomic {n : ℕ} (hpos : 0 < n) {p : ℕ} [hprime : fact p.prime] {a : ℕ} (hroot : is_root (cyclotomic n (zmod p)) (nat.cast_ring_hom (zmod p) a)) : a.coprime p := begin apply nat.coprime.symm, rw [hprime.1.coprime_iff_not_dvd], intro h, replace h := (zmod.nat_coe_zmod_eq_zero_iff_dvd a p).2 h, rw [is_root.def, eq_nat_cast, h, ← coeff_zero_eq_eval_zero] at hroot, by_cases hone : n = 1, { simp only [hone, cyclotomic_one, zero_sub, coeff_one_zero, coeff_X_zero, neg_eq_zero, one_ne_zero, coeff_sub] at hroot, exact hroot }, rw [cyclotomic_coeff_zero (zmod p) (nat.succ_le_of_lt (lt_of_le_of_ne (nat.succ_le_of_lt hpos) (ne.symm hone)))] at hroot, exact one_ne_zero hroot end end cyclotomic section order /-- If `(a : ℕ)` is a root of `cyclotomic n (zmod p)`, then the multiplicative order of `a` modulo `p` divides `n`. -/ lemma order_of_root_cyclotomic_dvd {n : ℕ} (hpos : 0 < n) {p : ℕ} [fact p.prime] {a : ℕ} (hroot : is_root (cyclotomic n (zmod p)) (nat.cast_ring_hom (zmod p) a)) : order_of (zmod.unit_of_coprime a (coprime_of_root_cyclotomic hpos hroot)) ∣ n := begin apply order_of_dvd_of_pow_eq_one, suffices hpow : eval (nat.cast_ring_hom (zmod p) a) (X ^ n - 1 : (zmod p)[X]) = 0, { simp only [eval_X, eval_one, eval_pow, eval_sub, eq_nat_cast] at hpow, apply units.coe_eq_one.1, simp only [sub_eq_zero.mp hpow, zmod.coe_unit_of_coprime, units.coe_pow] }, rw [is_root.def] at hroot, rw [← prod_cyclotomic_eq_X_pow_sub_one hpos (zmod p), nat.divisors_eq_proper_divisors_insert_self_of_pos hpos, finset.prod_insert nat.proper_divisors.not_self_mem, eval_mul, hroot, zero_mul] end end order section minpoly open is_primitive_root complex /-- The minimal polynomial of a primitive `n`-th root of unity `μ` divides `cyclotomic n ℤ`. -/ lemma _root_.is_primitive_root.minpoly_dvd_cyclotomic {n : ℕ} {K : Type*} [field K] {μ : K} (h : is_primitive_root μ n) (hpos : 0 < n) [char_zero K] : minpoly ℤ μ ∣ cyclotomic n ℤ := begin apply minpoly.gcd_domain_dvd (is_integral h hpos) (cyclotomic_ne_zero n ℤ), simpa [aeval_def, eval₂_eq_eval_map, is_root.def] using is_root_cyclotomic hpos h end lemma _root_.is_primitive_root.minpoly_eq_cyclotomic_of_irreducible {K : Type*} [field K] {R : Type*} [comm_ring R] [is_domain R] {μ : R} {n : ℕ} [algebra K R] (hμ : is_primitive_root μ n) (h : irreducible $ cyclotomic n K) [ne_zero (n : K)] : cyclotomic n K = minpoly K μ := begin haveI := ne_zero.of_no_zero_smul_divisors K R n, refine minpoly.eq_of_irreducible_of_monic h _ (cyclotomic.monic n K), rwa [aeval_def, eval₂_eq_eval_map, map_cyclotomic, ←is_root.def, is_root_cyclotomic_iff] end /-- `cyclotomic n ℤ` is the minimal polynomial of a primitive `n`-th root of unity `μ`. -/ lemma cyclotomic_eq_minpoly {n : ℕ} {K : Type*} [field K] {μ : K} (h : is_primitive_root μ n) (hpos : 0 < n) [char_zero K] : cyclotomic n ℤ = minpoly ℤ μ := begin refine eq_of_monic_of_dvd_of_nat_degree_le (minpoly.monic (is_integral h hpos)) (cyclotomic.monic n ℤ) (h.minpoly_dvd_cyclotomic hpos) _, simpa [nat_degree_cyclotomic n ℤ] using totient_le_degree_minpoly h end /-- `cyclotomic n ℚ` is the minimal polynomial of a primitive `n`-th root of unity `μ`. -/ lemma cyclotomic_eq_minpoly_rat {n : ℕ} {K : Type*} [field K] {μ : K} (h : is_primitive_root μ n) (hpos : 0 < n) [char_zero K] : cyclotomic n ℚ = minpoly ℚ μ := begin rw [← map_cyclotomic_int, cyclotomic_eq_minpoly h hpos], exact (minpoly.gcd_domain_eq_field_fractions' _ (is_integral h hpos)).symm end /-- `cyclotomic n ℤ` is irreducible. -/ lemma cyclotomic.irreducible {n : ℕ} (hpos : 0 < n) : irreducible (cyclotomic n ℤ) := begin rw [cyclotomic_eq_minpoly (is_primitive_root_exp n hpos.ne') hpos], apply minpoly.irreducible, exact (is_primitive_root_exp n hpos.ne').is_integral hpos, end /-- `cyclotomic n ℚ` is irreducible. -/ lemma cyclotomic.irreducible_rat {n : ℕ} (hpos : 0 < n) : irreducible (cyclotomic n ℚ) := begin rw [← map_cyclotomic_int], exact (is_primitive.int.irreducible_iff_irreducible_map_cast (cyclotomic.is_primitive n ℤ)).1 (cyclotomic.irreducible hpos), end /-- If `n ≠ m`, then `(cyclotomic n ℚ)` and `(cyclotomic m ℚ)` are coprime. -/ lemma cyclotomic.is_coprime_rat {n m : ℕ} (h : n ≠ m) : is_coprime (cyclotomic n ℚ) (cyclotomic m ℚ) := begin rcases n.eq_zero_or_pos with rfl | hnzero, { exact is_coprime_one_left }, rcases m.eq_zero_or_pos with rfl | hmzero, { exact is_coprime_one_right }, rw (irreducible.coprime_iff_not_dvd $ cyclotomic.irreducible_rat $ hnzero), exact (λ hdiv, h $ cyclotomic_injective $ eq_of_monic_of_associated (cyclotomic.monic n ℚ) (cyclotomic.monic m ℚ) $ irreducible.associated_of_dvd (cyclotomic.irreducible_rat hnzero) (cyclotomic.irreducible_rat hmzero) hdiv), end end minpoly section expand /-- If `p` is a prime such that `¬ p ∣ n`, then `expand R p (cyclotomic n R) = (cyclotomic (n * p) R) * (cyclotomic n R)`. -/ @[simp] lemma cyclotomic_expand_eq_cyclotomic_mul {p n : ℕ} (hp : nat.prime p) (hdiv : ¬p ∣ n) (R : Type*) [comm_ring R] : expand R p (cyclotomic n R) = (cyclotomic (n * p) R) * (cyclotomic n R) := begin rcases nat.eq_zero_or_pos n with rfl | hnpos, { simp }, haveI := ne_zero.of_pos hnpos, suffices : expand ℤ p (cyclotomic n ℤ) = (cyclotomic (n * p) ℤ) * (cyclotomic n ℤ), { rw [← map_cyclotomic_int, ← map_expand, this, polynomial.map_mul, map_cyclotomic_int] }, refine eq_of_monic_of_dvd_of_nat_degree_le ((cyclotomic.monic _ _).mul (cyclotomic.monic _ _)) ((cyclotomic.monic n ℤ).expand hp.pos) _ _, { refine (is_primitive.int.dvd_iff_map_cast_dvd_map_cast _ _ (is_primitive.mul (cyclotomic.is_primitive (n * p) ℤ) (cyclotomic.is_primitive n ℤ)) ((cyclotomic.monic n ℤ).expand hp.pos).is_primitive).2 _, rw [polynomial.map_mul, map_cyclotomic_int, map_cyclotomic_int, map_expand, map_cyclotomic_int], refine is_coprime.mul_dvd (cyclotomic.is_coprime_rat (λ h, _)) _ _, { replace h : n * p = n * 1 := by simp [h], exact nat.prime.ne_one hp (nat.eq_of_mul_eq_mul_left hnpos h) }, { have hpos : 0 < n * p := mul_pos hnpos hp.pos, have hprim := complex.is_primitive_root_exp _ hpos.ne', rw [cyclotomic_eq_minpoly_rat hprim hpos], refine @minpoly.dvd ℚ ℂ _ _ algebra_rat _ _ _, rw [aeval_def, ← eval_map, map_expand, map_cyclotomic, expand_eval, ← is_root.def, is_root_cyclotomic_iff], convert is_primitive_root.pow_of_dvd hprim hp.ne_zero (dvd_mul_left p n), rw [nat.mul_div_cancel _ (nat.prime.pos hp)] }, { have hprim := complex.is_primitive_root_exp _ hnpos.ne.symm, rw [cyclotomic_eq_minpoly_rat hprim hnpos], refine @minpoly.dvd ℚ ℂ _ _ algebra_rat _ _ _, rw [aeval_def, ← eval_map, map_expand, expand_eval, ← is_root.def, ← cyclotomic_eq_minpoly_rat hprim hnpos, map_cyclotomic, is_root_cyclotomic_iff], exact is_primitive_root.pow_of_prime hprim hp hdiv,} }, { rw [nat_degree_expand, nat_degree_cyclotomic, nat_degree_mul (cyclotomic_ne_zero _ ℤ) (cyclotomic_ne_zero _ ℤ), nat_degree_cyclotomic, nat_degree_cyclotomic, mul_comm n, nat.totient_mul ((nat.prime.coprime_iff_not_dvd hp).2 hdiv), nat.totient_prime hp, mul_comm (p - 1), ← nat.mul_succ, nat.sub_one, nat.succ_pred_eq_of_pos hp.pos] } end /-- If `p` is a prime such that `p ∣ n`, then `expand R p (cyclotomic n R) = cyclotomic (p * n) R`. -/ @[simp] lemma cyclotomic_expand_eq_cyclotomic {p n : ℕ} (hp : nat.prime p) (hdiv : p ∣ n) (R : Type*) [comm_ring R] : expand R p (cyclotomic n R) = cyclotomic (n * p) R := begin rcases n.eq_zero_or_pos with rfl | hzero, { simp }, haveI := ne_zero.of_pos hzero, suffices : expand ℤ p (cyclotomic n ℤ) = cyclotomic (n * p) ℤ, { rw [← map_cyclotomic_int, ← map_expand, this, map_cyclotomic_int] }, refine eq_of_monic_of_dvd_of_nat_degree_le (cyclotomic.monic _ _) ((cyclotomic.monic n ℤ).expand hp.pos) _ _, { have hpos := nat.mul_pos hzero hp.pos, have hprim := complex.is_primitive_root_exp _ hpos.ne.symm, rw [cyclotomic_eq_minpoly hprim hpos], refine minpoly.gcd_domain_dvd (hprim.is_integral hpos) ((cyclotomic.monic n ℤ).expand hp.pos).ne_zero _, rw [aeval_def, ← eval_map, map_expand, map_cyclotomic, expand_eval, ← is_root.def, is_root_cyclotomic_iff], { convert is_primitive_root.pow_of_dvd hprim hp.ne_zero (dvd_mul_left p n), rw [nat.mul_div_cancel _ hp.pos] } }, { rw [nat_degree_expand, nat_degree_cyclotomic, nat_degree_cyclotomic, mul_comm n, nat.totient_mul_of_prime_of_dvd hp hdiv, mul_comm] } end /-- If the `p ^ n`th cyclotomic polynomial is irreducible, so is the `p ^ m`th, for `m ≤ n`. -/ lemma cyclotomic_irreducible_pow_of_irreducible_pow {p : ℕ} (hp : nat.prime p) {R} [comm_ring R] [is_domain R] {n m : ℕ} (hmn : m ≤ n) (h : irreducible (cyclotomic (p ^ n) R)) : irreducible (cyclotomic (p ^ m) R) := begin unfreezingI { rcases m.eq_zero_or_pos with rfl | hm, { simpa using irreducible_X_sub_C (1 : R) }, obtain ⟨k, rfl⟩ := nat.exists_eq_add_of_le hmn, induction k with k hk }, { simpa using h }, have : m + k ≠ 0 := (add_pos_of_pos_of_nonneg hm k.zero_le).ne', rw [nat.add_succ, pow_succ', ←cyclotomic_expand_eq_cyclotomic hp $ dvd_pow_self p this] at h, exact hk (by linarith) (of_irreducible_expand hp.ne_zero h) end /-- If `irreducible (cyclotomic (p ^ n) R)` then `irreducible (cyclotomic p R).` -/ lemma cyclotomic_irreducible_of_irreducible_pow {p : ℕ} (hp : nat.prime p) {R} [comm_ring R] [is_domain R] {n : ℕ} (hn : n ≠ 0) (h : irreducible (cyclotomic (p ^ n) R)) : irreducible (cyclotomic p R) := pow_one p ▸ cyclotomic_irreducible_pow_of_irreducible_pow hp hn.bot_lt h end expand section char_p /-- If `R` is of characteristic `p` and `¬p ∣ n`, then `cyclotomic (n * p) R = (cyclotomic n R) ^ (p - 1)`. -/ lemma cyclotomic_mul_prime_eq_pow_of_not_dvd (R : Type*) {p n : ℕ} [hp : fact (nat.prime p)] [ring R] [char_p R p] (hn : ¬p ∣ n) : cyclotomic (n * p) R = (cyclotomic n R) ^ (p - 1) := begin suffices : cyclotomic (n * p) (zmod p) = (cyclotomic n (zmod p)) ^ (p - 1), { rw [← map_cyclotomic _ (algebra_map (zmod p) R), ← map_cyclotomic _ (algebra_map (zmod p) R), this, polynomial.map_pow] }, apply mul_right_injective₀ (cyclotomic_ne_zero n $ zmod p), rw [←pow_succ, tsub_add_cancel_of_le hp.out.one_lt.le, mul_comm, ← zmod.expand_card], nth_rewrite 2 [← map_cyclotomic_int], rw [← map_expand, cyclotomic_expand_eq_cyclotomic_mul hp.out hn, polynomial.map_mul, map_cyclotomic, map_cyclotomic] end /-- If `R` is of characteristic `p` and `p ∣ n`, then `cyclotomic (n * p) R = (cyclotomic n R) ^ p`. -/ lemma cyclotomic_mul_prime_dvd_eq_pow (R : Type*) {p n : ℕ} [hp : fact (nat.prime p)] [ring R] [char_p R p] (hn : p ∣ n) : cyclotomic (n * p) R = (cyclotomic n R) ^ p := begin suffices : cyclotomic (n * p) (zmod p) = (cyclotomic n (zmod p)) ^ p, { rw [← map_cyclotomic _ (algebra_map (zmod p) R), ← map_cyclotomic _ (algebra_map (zmod p) R), this, polynomial.map_pow] }, rw [← zmod.expand_card, ← map_cyclotomic_int n, ← map_expand, cyclotomic_expand_eq_cyclotomic hp.out hn, map_cyclotomic, mul_comm] end /-- If `R` is of characteristic `p` and `¬p ∣ m`, then `cyclotomic (p ^ k * m) R = (cyclotomic m R) ^ (p ^ k - p ^ (k - 1))`. -/ lemma cyclotomic_mul_prime_pow_eq (R : Type*) {p m : ℕ} [fact (nat.prime p)] [ring R] [char_p R p] (hm : ¬p ∣ m) : ∀ {k}, 0 < k → cyclotomic (p ^ k * m) R = (cyclotomic m R) ^ (p ^ k - p ^ (k - 1)) | 1 _ := by rw [pow_one, nat.sub_self, pow_zero, mul_comm, cyclotomic_mul_prime_eq_pow_of_not_dvd R hm] | (a + 2) _ := begin have hdiv : p ∣ p ^ a.succ * m := ⟨p ^ a * m, by rw [← mul_assoc, pow_succ]⟩, rw [pow_succ, mul_assoc, mul_comm, cyclotomic_mul_prime_dvd_eq_pow R hdiv, cyclotomic_mul_prime_pow_eq a.succ_pos, ← pow_mul], congr' 1, simp only [tsub_zero, nat.succ_sub_succ_eq_sub], rw [nat.mul_sub_right_distrib, mul_comm, pow_succ'] end /-- If `R` is of characteristic `p` and `¬p ∣ m`, then `ζ` is a root of `cyclotomic (p ^ k * m) R` if and only if it is a primitive `m`-th root of unity. -/ lemma is_root_cyclotomic_prime_pow_mul_iff_of_char_p {m k p : ℕ} {R : Type*} [comm_ring R] [is_domain R] [hp : fact (nat.prime p)] [hchar : char_p R p] {μ : R} [ne_zero (m : R)] : (polynomial.cyclotomic (p ^ k * m) R).is_root μ ↔ is_primitive_root μ m := begin rcases k.eq_zero_or_pos with rfl | hk, { rw [pow_zero, one_mul, is_root_cyclotomic_iff] }, refine ⟨λ h, _, λ h, _⟩, { rw [is_root.def, cyclotomic_mul_prime_pow_eq R (ne_zero.not_char_dvd R p m) hk, eval_pow] at h, replace h := pow_eq_zero h, rwa [← is_root.def, is_root_cyclotomic_iff] at h }, { rw [← is_root_cyclotomic_iff, is_root.def] at h, rw [cyclotomic_mul_prime_pow_eq R (ne_zero.not_char_dvd R p m) hk, is_root.def, eval_pow, h, zero_pow], simp only [tsub_pos_iff_lt], apply strict_mono_pow hp.out.one_lt (nat.pred_lt hk.ne') } end end char_p end polynomial
07e4b6cbdb5efcb97251d7f3c9ac4e433d60edf4
f618aea02cb4104ad34ecf3b9713065cc0d06103
/src/data/zsqrtd/gaussian_int.lean
27a89827f21a226bbe84a3274c82a7e9eb9f5845
[ "Apache-2.0" ]
permissive
joehendrix/mathlib
84b6603f6be88a7e4d62f5b1b0cbb523bb82b9a5
c15eab34ad754f9ecd738525cb8b5a870e834ddc
refs/heads/master
1,589,606,591,630
1,555,946,393,000
1,555,946,393,000
182,813,854
0
0
null
1,555,946,309,000
1,555,946,308,000
null
UTF-8
Lean
false
false
7,167
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Chris Hughes The gaussian integers ℤ[i]. -/ import data.zsqrtd.basic data.complex.basic algebra.euclidean_domain algebra.associated open zsqrtd complex local attribute [instance, priority 0] int.cast_coe @[reducible] def gaussian_int : Type := zsqrtd (-1) local notation `ℤ[i]` := gaussian_int namespace gaussian_int instance : has_repr ℤ[i] := ⟨λ x, "⟨" ++ repr x.re ++ ", " ++ repr x.im ++ "⟩"⟩ instance : comm_ring ℤ[i] := zsqrtd.comm_ring def to_complex (x : ℤ[i]) : ℂ := x.re + x.im * I instance : has_coe (ℤ[i]) ℂ := ⟨to_complex⟩ lemma to_complex_def (x : ℤ[i]) : (x : ℂ) = x.re + x.im * I := rfl lemma to_complex_def' (x y : ℤ) : ((⟨x, y⟩ : ℤ[i]) : ℂ) = x + y * I := by simp [to_complex_def] lemma to_complex_def₂ (x : ℤ[i]) : (x : ℂ) = ⟨x.re, x.im⟩ := by apply complex.ext; simp [to_complex_def] instance to_complex.is_ring_hom : is_ring_hom to_complex:= by refine_struct {..}; intros; apply complex.ext; simp [to_complex] instance : is_ring_hom (coe : ℤ[i] → ℂ) := to_complex.is_ring_hom @[simp] lemma to_real_re (x : ℤ[i]) : ((x.re : ℤ) : ℝ) = (x : ℂ).re := by simp [to_complex_def] @[simp] lemma to_real_im (x : ℤ[i]) : ((x.im : ℤ) : ℝ) = (x : ℂ).im := by simp [to_complex_def] @[simp] lemma to_complex_re (x y : ℤ) : ((⟨x, y⟩ : ℤ[i]) : ℂ).re = x := by simp [to_complex_def] @[simp] lemma to_complex_im (x y : ℤ) : ((⟨x, y⟩ : ℤ[i]) : ℂ).im = y := by simp [to_complex_def] @[simp] lemma to_complex_add (x y : ℤ[i]) : ((x + y : ℤ[i]) : ℂ) = x + y := is_ring_hom.map_add coe @[simp] lemma to_complex_mul (x y : ℤ[i]) : ((x * y : ℤ[i]) : ℂ) = x * y := is_ring_hom.map_mul coe @[simp] lemma to_complex_one : ((1 : ℤ[i]) : ℂ) = 1 := is_ring_hom.map_one coe @[simp] lemma to_complex_zero : ((0 : ℤ[i]) : ℂ) = 0 := is_ring_hom.map_zero coe @[simp] lemma to_complex_neg (x : ℤ[i]) : ((-x : ℤ[i]) : ℂ) = -x := is_ring_hom.map_neg coe @[simp] lemma to_complex_sub (x y : ℤ[i]) : ((x - y : ℤ[i]) : ℂ) = x - y := is_ring_hom.map_sub coe @[simp] lemma to_complex_inj {x y : ℤ[i]} : (x : ℂ) = y ↔ x = y := by cases x; cases y; simp [to_complex_def₂] @[simp] lemma to_complex_eq_zero {x : ℤ[i]} : (x : ℂ) = 0 ↔ x = 0 := by rw [← to_complex_zero, to_complex_inj] @[simp] lemma nat_cast_real_norm (x : ℤ[i]) : (x.norm : ℝ) = (x : ℂ).norm_sq := by rw [norm, norm_sq]; simp @[simp] lemma nat_cast_complex_norm (x : ℤ[i]) : (x.norm : ℂ) = (x : ℂ).norm_sq := by cases x; rw [norm, norm_sq]; simp lemma norm_nonneg (x : ℤ[i]) : 0 ≤ norm x := norm_nonneg trivial _ @[simp] lemma norm_eq_zero {x : ℤ[i]} : norm x = 0 ↔ x = 0 := by rw [← @int.cast_inj ℝ _ _ _]; simp lemma norm_pos {x : ℤ[i]} : 0 < norm x ↔ x ≠ 0 := by rw [lt_iff_le_and_ne, ne.def, eq_comm, norm_eq_zero]; simp [norm_nonneg] @[simp] lemma coe_nat_abs_norm (x : ℤ[i]) : (x.norm.nat_abs : ℤ) = x.norm := int.nat_abs_of_nonneg (norm_nonneg _) @[simp] lemma nat_cast_nat_abs_norm {α : Type*} [ring α] (x : ℤ[i]) : (x.norm.nat_abs : α) = x.norm := by rw [← int.cast_coe_nat, coe_nat_abs_norm] lemma nat_abs_norm_eq (x : ℤ[i]) : x.norm.nat_abs = x.re.nat_abs * x.re.nat_abs + x.im.nat_abs * x.im.nat_abs := int.coe_nat_inj $ begin simp, simp [norm] end protected def div (x y : ℤ[i]) : ℤ[i] := ⟨round ((x * conj y).re / norm y : ℚ), round ((x * conj y).im / norm y : ℚ)⟩ instance : has_div ℤ[i] := ⟨gaussian_int.div⟩ lemma div_def (x y : ℤ[i]) : x / y = ⟨round ((x * conj y).re / norm y : ℚ), round ((x * conj y).im / norm y : ℚ)⟩ := rfl lemma to_complex_div_re (x y : ℤ[i]) : ((x / y : ℤ[i]) : ℂ).re = round ((x / y : ℂ).re) := by rw [div_def, ← @rat.cast_round ℝ _ _]; simp [-rat.cast_round, mul_assoc, div_eq_mul_inv, mul_add, add_mul] lemma to_complex_div_im (x y : ℤ[i]) : ((x / y : ℤ[i]) : ℂ).im = round ((x / y : ℂ).im) := by rw [div_def, ← @rat.cast_round ℝ _ _, ← @rat.cast_round ℝ _ _]; simp [-rat.cast_round, mul_assoc, div_eq_mul_inv, mul_add, add_mul] local notation `abs'` := _root_.abs lemma norm_sq_le_norm_sq_of_re_le_of_im_le {x y : ℂ} (hre : abs' x.re ≤ abs' y.re) (him : abs' x.im ≤ abs' y.im) : x.norm_sq ≤ y.norm_sq := by rw [norm_sq, norm_sq, ← _root_.abs_mul_self, _root_.abs_mul, ← _root_.abs_mul_self y.re, _root_.abs_mul y.re, ← _root_.abs_mul_self x.im, _root_.abs_mul x.im, ← _root_.abs_mul_self y.im, _root_.abs_mul y.im]; exact (add_le_add (mul_self_le_mul_self (abs_nonneg _) hre) (mul_self_le_mul_self (abs_nonneg _) him)) lemma norm_sq_div_sub_div_lt_one (x y : ℤ[i]) : ((x / y : ℂ) - ((x / y : ℤ[i]) : ℂ)).norm_sq < 1 := calc ((x / y : ℂ) - ((x / y : ℤ[i]) : ℂ)).norm_sq = ((x / y : ℂ).re - ((x / y : ℤ[i]) : ℂ).re + ((x / y : ℂ).im - ((x / y : ℤ[i]) : ℂ).im) * I : ℂ).norm_sq : congr_arg _ $ by apply complex.ext; simp ... ≤ (1 / 2 + 1 / 2 * I).norm_sq : have abs' (2 / (2 * 2) : ℝ) = 1 / 2, by rw _root_.abs_of_nonneg; norm_num, norm_sq_le_norm_sq_of_re_le_of_im_le (by rw [to_complex_div_re]; simp [norm_sq, this]; simpa using abs_sub_round (x / y : ℂ).re) (by rw [to_complex_div_im]; simp [norm_sq, this]; simpa using abs_sub_round (x / y : ℂ).im) ... < 1 : by simp [norm_sq]; norm_num protected def mod (x y : ℤ[i]) : ℤ[i] := x - y * (x / y) instance : has_mod ℤ[i] := ⟨gaussian_int.mod⟩ lemma mod_def (x y : ℤ[i]) : x % y = x - y * (x / y) := rfl lemma norm_mod_lt (x : ℤ[i]) {y : ℤ[i]} (hy : y ≠ 0) : (x % y).norm < y.norm := have (y : ℂ) ≠ 0, by rwa [ne.def, ← to_complex_zero, to_complex_inj], (@int.cast_lt ℝ _ _ _).1 $ calc ↑(norm (x % y)) = (x - y * (x / y : ℤ[i]) : ℂ).norm_sq : by simp [mod_def] ... = (y : ℂ).norm_sq * (((x / y) - (x / y : ℤ[i])) : ℂ).norm_sq : by rw [← norm_sq_mul, mul_sub, mul_div_cancel' _ this] ... < (y : ℂ).norm_sq * 1 : mul_lt_mul_of_pos_left (norm_sq_div_sub_div_lt_one _ _) (norm_sq_pos.2 this) ... = norm y : by simp lemma nat_abs_norm_mod_lt (x : ℤ[i]) {y : ℤ[i]} (hy : y ≠ 0) : (x % y).norm.nat_abs < y.norm.nat_abs := int.coe_nat_lt.1 (by simp [-int.coe_nat_lt, norm_mod_lt x hy]) lemma norm_le_norm_mul_left (x : ℤ[i]) {y : ℤ[i]} (hy : y ≠ 0) : (norm x).nat_abs ≤ (norm (x * y)).nat_abs := by rw [norm_mul, int.nat_abs_mul]; exact le_mul_of_ge_one_right' (nat.zero_le _) (int.coe_nat_le.1 (by rw [coe_nat_abs_norm]; exact norm_pos.2 hy)) instance : nonzero_comm_ring ℤ[i] := { zero_ne_one := dec_trivial, ..gaussian_int.comm_ring } instance : euclidean_domain ℤ[i] := { quotient := (/), remainder := (%), quotient_zero := λ _, by simp [div_def]; refl, quotient_mul_add_remainder_eq := λ _ _, by simp [mod_def], r := _, r_well_founded := measure_wf (int.nat_abs ∘ norm), remainder_lt := nat_abs_norm_mod_lt, mul_left_not_lt := λ a b hb0, not_lt_of_ge $ norm_le_norm_mul_left a hb0 } end gaussian_int
1fc7874bc3782d2bb04840ce408d0198ec6ad469
1d02a718c550dba762f0c3d2ad13d16a43649ca1
/src/theorem.lean
eb1ba055e607d95293115f34ff2ec4bf98df9411
[ "Apache-2.0" ]
permissive
mhuisi/rc-correctness
48488dfbbe18e222399b0c5252d2803a9dd1be74
2b7878ac594ba285b0b5cdabe96f41c6e3bbcc87
refs/heads/master
1,590,988,773,033
1,585,334,858,000
1,585,334,858,000
190,653,803
0
1
null
null
null
null
UTF-8
Lean
false
false
42,462
lean
import compiler import well_formedness namespace rc_correctness open rc_correctness.expr open rc_correctness.fn_body open rc_correctness.lin_type lemma not_𝔹_iff_𝕆 {τ : lin_type} : τ ≠ 𝔹 ↔ τ = 𝕆 := begin cases τ; split; intro h; contradiction <|> refl end lemma not_𝕆_iff_𝔹 {τ : lin_type} : τ ≠ 𝕆 ↔ τ = 𝔹 := begin cases τ; split; intro h; contradiction <|> refl end section FV_wf open finset open list theorem FV_sub_wf_context {δ : program} {β : const → var → lin_type} {Γ : finset var} {F : fn_body} (h : β; δ; Γ ⊢ F) : FV F ⊆ Γ := begin with_cases { induction F using rc_correctness.fn_body.rec_wf generalizing Γ }; simp only [subset_iff], case ret : x { intros y h₁, simp only [FV, finset.mem_singleton, insert_empty_eq_singleton] at h₁, cases h, rwa h₁ }, case «let» : x e F ih { intros y h₁, simp only [FV, mem_erase, finset.mem_union] at h₁, cases h₁, { cases h; simp only [FV_expr, mem_to_finset, mem_insert, finset.mem_singleton, has_insert_eq_insert, insert_empty_eq_singleton] at h₁; try { simp only [subset_iff, mem_to_finset] at h_ys_def }; try { exact h_ys_def h₁ }; try { rwa h₁ }, cases h₁; rwa h₁ }, { cases h₁, cases h; { replace ih := subset_iff.mp (ih h_F_wf) h₁_right, rw mem_insert at ih, cases ih, { contradiction }, { assumption } } } }, case «case» : x Fs ih { intros y h₁, simp only [FV, mem_insert, finset.mem_join] at h₁, cases h, cases h₁, { rwa h₁ }, rw map_wf_eq_map at h₁, simp only [exists_prop, list.mem_map] at h₁, rcases h₁ with ⟨l, ⟨⟨a, ⟨a_in_Fs, FV_a_eq_l⟩⟩, y_in_l⟩⟩, rw ←FV_a_eq_l at y_in_l, have a_wf : (β; δ; Γ ⊢ a), from h_Fs_wf a a_in_Fs, have FV_a_sub_Γ : FV a ⊆ Γ, from ih a a_in_Fs a_wf, exact subset_iff.mp FV_a_sub_Γ y_in_l }, all_goals { intros x F ih Γ h y h₁, cases h } end end FV_wf section FV_C open finset lemma FV_inc_𝕆_var_eq_FV {x : var} {F : fn_body} (V : finset var) (βₗ : var → lin_type) (h : x ∈ FV F) : FV (inc_𝕆_var x V F βₗ) = FV F := begin unfold inc_𝕆_var, split_ifs, { refl }, unfold FV, exact insert_eq_of_mem h end lemma FV_sub_FV_dec_𝕆 (ys : list var) (F : fn_body) (βₗ : var → lin_type) : FV F ⊆ FV (dec_𝕆 ys F βₗ) := begin apply subset_iff.mpr, intros x h, unfold dec_𝕆 dec_𝕆_var, induction ys, { simpa only [list.foldr_nil] }, simp only [list.foldr_cons], split_ifs, { simp only [FV, mem_insert], exact or.inr ys_ih }, { exact ys_ih } end lemma FV_dec_𝕆_filter (ys : list var) (F : fn_body) (βₗ : var → lin_type) : FV (dec_𝕆 ys F βₗ) = ys.to_finset.filter (λ y, βₗ y = 𝕆 ∧ y ∉ FV F) ∪ FV F := begin induction ys, { simp only [dec_𝕆, filter_empty, finset.empty_union, list.to_finset_nil, list.foldr_nil] }, simp only [dec_𝕆, dec_𝕆_var, filter_insert, list.foldr_cons, list.to_finset_cons] at *, split_ifs; try { simp only [FV, insert_union] }, { rw ys_ih }, { simp only [not_and, not_not] at h_1, have ys_hd_in_FV, from h_1 h.left, have : FV (list.foldr (λ (x : var) (acc : fn_body), ite (βₗ x = 𝕆 ∧ x ∉ FV acc) (dec x; acc) acc) F ys_tl) = FV (dec_𝕆 ys_tl F βₗ), from rfl, rw this at h, exact absurd (subset_iff.mp (FV_sub_FV_dec_𝕆 ys_tl F βₗ) ys_hd_in_FV) h.right }, { simp only [not_and, not_not] at h, have ys_hd_in_FV, from h h_1.left, rw ys_ih at *, rw insert_eq_of_mem ys_hd_in_FV }, { rw ys_ih } end lemma FV_dec_𝕆_sub_vars_FV (vars : list var) (F : fn_body) (βₗ : var → lin_type) : FV (dec_𝕆 vars F βₗ) ⊆ vars.to_finset ∪ FV F := begin simp only [FV_dec_𝕆_filter, subset_iff, mem_union, mem_filter, list.mem_to_finset], intros x h, cases h, { exact or.inl h.left }, { exact or.inr h } end lemma FV_dec_eq_FV {e : expr} {x z : var} {F : fn_body} (h : x ∈ FV_expr e ∪ erase (FV F) z) : FV_expr e ∪ erase (FV (dec x; F)) z = FV_expr e ∪ erase (FV F) z := begin unfold FV, have hem : x = z ∨ x ≠ z, from dec_em (x = z), cases hem, { rw hem, rw erase_insert_eq_erase }, { rw erase_insert_eq_insert_erase _ hem, simp only [union_insert], exact insert_eq_of_mem h } end lemma FV_Capp_eq_FV {xs : list (var × lin_type)} {z : var} {e : expr} {F1 F2 : fn_body} (βₗ : var → lin_type) (heq : FV F1 = FV F2) (h : ∀ xτ ∈ xs, (xτ : var × lin_type).1 ∈ FV (z ≔ e; F1)) : FV (C_app xs (z ≔ e; F1) βₗ) = FV (z ≔ e; F2) := begin induction xs generalizing F1 F2, { simp only [FV, C_app], rw heq }, cases xs_hd with x τ, simp only [list.mem_cons_iff, list.forall_mem_cons'] at h, cases h with x_in_FV h, simp only [C_app, FV] at *, cases τ, { rw if_pos rfl, unfold inc_𝕆_var, split_ifs, { exact xs_ih heq h }, unfold FV, rw xs_ih heq h, rw heq at x_in_FV, exact insert_eq_of_mem x_in_FV }, { simp only [dec_𝕆_var, if_false], split_ifs, { suffices h2 : ∀ (xτ : var × lin_type), xτ ∈ xs_tl → xτ.fst ∈ FV_expr e ∪ erase (FV (dec x; F1)) z, { have h3 : FV (dec x; F1) = FV (dec x; F2), from by { unfold FV, rw heq }, rw xs_ih h3 h2, rw heq at x_in_FV, exact FV_dec_eq_FV x_in_FV }, { intros yτ yτ_in_tl, have y_in_FV, from h yτ yτ_in_tl, rwa FV_dec_eq_FV x_in_FV } }, { exact xs_ih heq h } } end theorem FV_C_eq_FV (β : const → var → lin_type) (F : fn_body) (βₗ : var → lin_type) : FV (C β F βₗ) = FV F := begin with_cases { induction F using rc_correctness.fn_body.rec_wf generalizing βₗ }, case ret : x { unfold FV C inc_𝕆_var, split_ifs; simp only [FV, insert_eq_of_mem, insert_empty_eq_singleton, mem_singleton] }, case «case» : x Fs ih { unfold C FV, repeat { rw list.map_wf_eq_map }, simp only [list.map_map], ext, apply iff.intro, { intro h, apply mem_insert.mpr, replace h := mem_insert.mp h, cases h, { exact or.inl h }, { rw mem_join at h, rcases h with ⟨S, h, a_in_S⟩, simp only [list.mem_map, function.comp_app] at h, rcases h with ⟨b, b_in_Fs, h⟩, rw ←h at a_in_S, have h2, from FV_dec_𝕆_sub_vars_FV (sort var_le (insert x (join (list.map FV Fs)))) (C β b βₗ) βₗ, rw sort_to_finset _ at h2, have h3, from mem_of_subset h2 a_in_S, simp only [mem_union, mem_insert] at h3, rcases h3 with ⟨l, m, r⟩, { exact or.inl h3 }, { exact or.inr h3 }, rw ih b b_in_Fs βₗ at h3, simp only [exists_prop, list.mem_map, mem_join], exact or.inr ⟨FV b, ⟨⟨b, ⟨b_in_Fs, rfl⟩⟩, h3⟩⟩ } }, { intro h, apply mem_insert.mpr, replace h := mem_insert.mp h, cases h, { exact or.inl h }, { rw mem_join at h, rcases h with ⟨S, h, a_in_S⟩, rw list.mem_map at h, rcases h with ⟨b, ⟨b_in_Fs, FV_b_eq_S⟩⟩, apply or.inr, simp only [mem_join, exists_prop, list.mem_map, function.comp_app], apply exists.intro (FV (dec_𝕆 (sort var_le (insert x (join (list.map FV Fs)))) (C β b βₗ) βₗ)), apply and.intro, { exact ⟨b, ⟨b_in_Fs, rfl⟩⟩ }, rw ←ih b b_in_Fs βₗ at FV_b_eq_S, rw ←FV_b_eq_S at a_in_S, have h, from FV_sub_FV_dec_𝕆 (sort var_le (insert x (join (list.map FV Fs)))) (C β b βₗ) βₗ, exact mem_of_subset h a_in_S } } }, case «let» : x e F ih { induction e; unfold C; try { apply FV_Capp_eq_FV βₗ (ih (βₗ[x↦𝕆])), intros xτ h }; try { rw list.mem_map at h, apply Exists.rec_on h, intros x h_h, apply and.rec_on h_h, intros x_in_ys xτ_def, cases xτ, rw ←xτ_def, simp only [FV, FV_expr, mem_union, mem_insert, insert_union, list.mem_to_finset, mem_erase] }, { exact or.inl x_in_ys }, { exact or.inl x_in_ys }, { simp only [list.mem_cons_iff, list.mem_singleton] at h, simp only [FV, FV_expr, mem_union, mem_insert, insert_union, has_insert_eq_insert, insert_empty_eq_singleton, mem_singleton], cases h; rw h, { exact or.inr (or.inl rfl) }, { exact or.inl (rfl) } }, { exact or.inl x_in_ys }, { simp only [FV, C, dec_𝕆_var, FV_expr, insert_empty_eq_singleton], split_ifs; simp only [FV, erase_insert_eq_erase, FV_expr, insert_empty_eq_singleton], { rw ih (βₗ[x↦𝕆]) at *, have hem : e_x = x ∨ e_x ≠ x, from dec_em (e_x = x), cases hem, { rw hem at *, rw erase_insert_eq_erase, }, { rw erase_insert_eq_insert_erase _ hem, simp } }, { rw ih (βₗ[x↦𝕆]) }, { rw ih (βₗ[x↦𝔹]) } }, }, all_goals { intros x F ih βₗ, simp only [FV, C] } end end FV_C section sandwich open finset lemma wf_sandwich {β : const → var → lin_type} {δ : program} {Γ Γ' Γ'' : finset var} {F : fn_body} (Γ_sub_Γ' : Γ ⊆ Γ') (Γ'_sub_Γ'' : Γ' ⊆ Γ'') (hΓ : β; δ; Γ ⊢ F) (hΓ'' : β; δ; Γ'' ⊢ F) : β; δ; Γ' ⊢ F := begin with_cases { induction F using rc_correctness.fn_body.rec_wf generalizing Γ Γ' Γ'' }, case ret : x { apply fn_body_wf.ret, cases hΓ, exact subset_iff.mp Γ_sub_Γ' hΓ_x_def }, case «let» : x e F ih { cases e; cases hΓ; cases hΓ''; let h1 := insert_subset_insert x Γ_sub_Γ'; let h2 := insert_subset_insert x Γ'_sub_Γ'', any_goals { apply fn_body_wf.let_const_app_full <|> apply fn_body_wf.let_const_app_part <|> apply fn_body_wf.let_var_app <|> apply fn_body_wf.let_ctor <|> apply fn_body_wf.let_proj }, any_goals { assumption }, any_goals { transitivity, { exact hΓ_ys_def }, { assumption } }, any_goals { intro h, have h', from subset_iff.mp Γ'_sub_Γ'' h, contradiction }, any_goals { exact ih h1 h2 hΓ_F_wf hΓ''_F_wf }, any_goals { exact subset_iff.mp Γ_sub_Γ' hΓ_x_def }, any_goals { exact subset_iff.mp Γ_sub_Γ' hΓ_y_in_Γ } }, case «case» : x Fs ih { cases hΓ, cases hΓ'', apply fn_body_wf.case, { exact subset_iff.mp Γ_sub_Γ' hΓ_x_def }, intros F F_in_Fs, exact ih F F_in_Fs Γ_sub_Γ' Γ'_sub_Γ'' (hΓ_Fs_wf F F_in_Fs) (hΓ''_Fs_wf F F_in_Fs) }, case «inc» : x F ih { cases hΓ }, case «dec» : x F ih { cases hΓ } end lemma FV_wf {β : const → var → lin_type} {δ : program} {Γ : finset var} {F : fn_body} (h : β; δ; Γ ⊢ F) : β; δ; FV F ⊢ F := begin induction h, { apply fn_body_wf.ret, simp only [FV, insert_empty_eq_singleton, mem_singleton] }, any_goals { apply fn_body_wf.let_const_app_full <|> apply fn_body_wf.let_const_app_part <|> apply fn_body_wf.let_var_app <|> apply fn_body_wf.let_ctor <|> apply fn_body_wf.let_proj }, any_goals { simp [FV, FV_expr, subset_union_left, not_or_distrib] }, any_goals { intro h, simp only [subset_iff, list.mem_to_finset] at h_ys_def, have : h_z ∈ h_Γ, from h_ys_def h, contradiction }, any_goals { split }, any_goals { intro h, rw h at h_z_undef, contradiction }, any_goals { apply wf_sandwich _ _ h_ih h_F_wf }, any_goals { simp only [subset_iff, mem_union, mem_insert, mem_erase], intros x x_in_FV, by_cases eq : x = h_z, { exact or.inl eq }, { repeat { apply or.inr }, exact ⟨eq, x_in_FV⟩ } }, any_goals { apply insert_subset_insert, simp only [subset_iff, mem_union, list.mem_to_finset, mem_erase, mem_insert, mem_singleton], intros x h, repeat { cases h } }, any_goals { simp only [subset_iff, list.mem_to_finset] at h_ys_def, exact h_ys_def h }, any_goals { cases mem_insert.mp (subset_iff.mp (FV_sub_wf_context h_F_wf) h_right), { contradiction }, { assumption } }, any_goals { assumption }, { apply fn_body_wf.case, { exact mem_insert_self h_x _ }, intros F F_in_Fs, apply wf_sandwich _ _ (h_ih F F_in_Fs) (h_Fs_wf F F_in_Fs); simp only [subset_iff, list.map_wf_eq_map, exists_prop, mem_join, mem_insert, list.mem_map], { intros x x_in_FV, apply or.inr, use FV F, use F, { exact ⟨F_in_Fs, rfl⟩ }, { assumption } }, { intros x h, cases h, { rwa h }, rcases h with ⟨S, ⟨⟨a, ⟨a_in_Fs, a_def⟩⟩, x_in_S⟩⟩, rw ←a_def at x_in_S, exact subset_iff.mp (FV_sub_wf_context (h_Fs_wf a a_in_Fs)) x_in_S } } end lemma wf_FV_sandwich {β : const → var → lin_type} {δ : program} {Γ Γ' : finset var} {F : fn_body} (Γ'_low : FV F ⊆ Γ') (Γ'_high : Γ' ⊆ Γ) (h : β; δ; Γ ⊢ F) : β; δ; Γ' ⊢ F := wf_sandwich Γ'_low Γ'_high (FV_wf h) h end sandwich lemma vars_sub_FV_dec_𝕆 (ys : list var) (F : fn_body) (βₗ : var → lin_type) : ∀ y ∈ ys, βₗ y = 𝕆 → y ∈ FV (dec_𝕆 ys F βₗ) := begin intros y y_in_ys y𝕆, rw FV_dec_𝕆_filter, simp only [list.mem_to_finset, finset.mem_union, finset.mem_filter], by_cases y ∈ FV F, { exact or.inr h }, { exact or.inl ⟨y_in_ys, y𝕆, h⟩ } end lemma dec_𝕆_eq_dec_𝕆'_of_nodup {ys : list var} (F : fn_body) (βₗ : var → lin_type) (d : list.nodup ys) : dec_𝕆 ys F βₗ = dec_𝕆' ys F βₗ := begin unfold dec_𝕆 dec_𝕆_var dec_𝕆', induction ys, { simp only [list.foldr_nil] }, cases list.nodup_cons.mp d with ys_hd_not_in_ys_tl nodup_ys_tl, simp only [list.foldr_cons], split_ifs, { exact ⟨rfl, ys_ih nodup_ys_tl⟩ }, { simp only [not_and, not_not] at h_1, have g1, from h.right, have g2, from finset.subset_iff.mp (FV_sub_FV_dec_𝕆 ys_tl F βₗ) (h_1 h.left), contradiction }, { simp only [not_and, not_not] at h, have g1, from h_1.right, have g2, from finset.subset_iff.mp (FV_dec_𝕆_sub_vars_FV ys_tl F βₗ) (h h_1.left), simp only [list.mem_to_finset, finset.mem_union] at g2, cases g2; contradiction }, { exact ys_ih nodup_ys_tl } end open multiset (hiding coe_sort) lemma inductive_dec' {β : const → var → lin_type} {ys : list var} {y𝕆 y𝔹 : multiset var} {F : fn_body} {βₗ : var → lin_type} (ys_sub_vars : ↑ys ⊆ y𝕆 + y𝔹) (d : list.nodup ys) (y𝕆_𝕆 : ∀ y ∈ y𝕆, βₗ y = 𝕆) (y𝔹_𝔹 : ∀ y ∈ y𝔹, βₗ y = 𝔹) (nd_y𝕆 : nodup y𝕆) (nd_y𝔹 : nodup y𝔹) (h : β; (filter (λ y, y ∉ ys ∨ y ∈ FV F) y𝕆 {∶} 𝕆) + (y𝔹 {∶} 𝔹) ⊩ F ∷ 𝕆) : β; (y𝕆 {∶} 𝕆) + (y𝔹 {∶} 𝔹) ⊩ dec_𝕆 ys F βₗ ∷ 𝕆 := begin have h_congr : ∀ {ys_hd : var} {ys_tl : list var} {ys' : multiset var} (f : ∀ y ∈ ys', y ∉ ys_tl → ¬y = ys_hd ∧ y ∉ ys_tl ∨ y ∈ FV F), ∀ y ∈ ys', y ∉ (ys_hd :: ys_tl : list var) ∨ y ∈ FV F ↔ y ∉ ys_tl ∨ y ∈ FV F, { intros ys_hd ys_tl ys' f y y_in_ys', rw [list.mem_cons_iff, not_or_distrib], exact ⟨λ h', h'.elim (λ h'', or.inl h''.right) (λ h'', or.inr h''), λ h', h'.elim (λ h'', f y y_in_ys' h'') (λ h'', or.inr h'')⟩ }, rw dec_𝕆_eq_dec_𝕆'_of_nodup F βₗ d, induction ys generalizing y𝕆 y𝔹, { rw [dec_𝕆', list.foldr_nil], simp only [list.not_mem_nil, true_or, not_false_iff, filter_true] at h, assumption }, cases list.nodup_cons.mp d with ys_hd_not_in_ys_tl nodup_ys_tl, rw ←cons_coe at ys_sub_vars, simp only [cons_subset, mem_add] at ys_sub_vars, cases ys_sub_vars with ys_hd_def ys_tl_sub_vars, rw [dec_𝕆', list.foldr_cons], split_ifs, { cases ys_hd_def, swap, { rw y𝔹_𝔹 ys_hd ys_hd_def at h_1, simp only [false_and] at h_1, contradiction }, cases exists_cons_of_mem ys_hd_def with y𝕆' y𝕆_def, rw [y𝕆_def, map_cons, cons_add], apply linear.dec, apply ys_ih, { assumption }, { rw y𝕆_def at ys_tl_sub_vars, rw subset_iff at ys_tl_sub_vars ⊢, intros x x_in_tl, let := ys_tl_sub_vars x_in_tl, simp only [mem_add, mem_cons] at this, repeat { cases this }, { contradiction }, { exact mem_add.mpr (or.inl this) }, { exact mem_add.mpr (or.inr this) } }, { simp only [y𝕆_def, mem_cons] at y𝕆_𝕆, intros y y_in_y𝕆', exact y𝕆_𝕆 y (or.inr y_in_y𝕆') }, { assumption }, { simp only [y𝕆_def, nodup_cons] at nd_y𝕆, exact nd_y𝕆.right }, { assumption }, { rw y𝕆_def at h nd_y𝕆, rw filter_cons_of_neg at h, swap, { simp, exact h_1.right }, rw nodup_cons at nd_y𝕆, have : ∀ y ∈ y𝕆', y ∉ ys_tl → ¬y = ys_hd ∧ y ∉ ys_tl ∨ y ∈ FV F, { intros y y_in_y𝕆' h', apply or.inl (and.intro _ h'), intro h', rw h' at y_in_y𝕆', exact absurd y_in_y𝕆' nd_y𝕆.left }, rwa filter_congr (h_congr this) at h } }, apply ys_ih, any_goals { assumption }, rw not_and_distrib at h_1, cases h_1, { rw [←ne.def, not_𝕆_iff_𝔹] at h_1, cases ys_hd_def, { rw y𝕆_𝕆 ys_hd ys_hd_def at h_1, contradiction }, have : ∀ y ∈ y𝕆, y ∉ ys_tl → ¬y = ys_hd ∧ y ∉ ys_tl ∨ y ∈ FV F, { intros y y_in_y𝕆 h', apply or.inl (and.intro _ h'), intro h'', rw h'' at y_in_y𝕆, rw y𝕆_𝕆 ys_hd y_in_y𝕆 at h_1, contradiction }, rwa filter_congr (h_congr this) at h }, { have : ∀ y ∈ y𝕆, y ∉ ys_tl → ¬y = ys_hd ∧ y ∉ ys_tl ∨ y ∈ FV F, { intros y y_in_y𝕆 h', rw not_not at h_1, by_cases h'' : y = ys_hd, { rw h'', exact or.inr h_1 }, { exact or.inl ⟨h'', h'⟩ } }, rwa filter_congr (h_congr this) at h } end lemma inductive_dec {β : const → var → lin_type} {ys : list var} {y𝕆 y𝔹 : multiset var} {F : fn_body} {βₗ : var → lin_type} (y𝕆_sub_ys : y𝕆 ⊆ ↑ys) (ys_sub_vars : ↑ys ⊆ y𝕆 + y𝔹) (d : list.nodup ys) (y𝕆_𝕆 : ∀ y ∈ y𝕆, βₗ y = 𝕆) (y𝔹_𝔹 : ∀ y ∈ y𝔹, βₗ y = 𝔹) (nd_y𝕆 : nodup y𝕆) (nd_y𝔹 : nodup y𝔹) (h : β; (filter (λ y, y ∈ FV F) y𝕆 {∶} 𝕆) + (y𝔹 {∶} 𝔹) ⊩ F ∷ 𝕆) : β; (y𝕆 {∶} 𝕆) + (y𝔹 {∶} 𝔹) ⊩ dec_𝕆 ys F βₗ ∷ 𝕆 := begin have : ∀ y ∈ y𝕆, y ∈ FV F ↔ y ∉ ys ∨ y ∈ FV F, { intros y y_in_y𝕆, split; intro h', { exact or.inr h' }, { cases h', { exact absurd (y𝕆_sub_ys y_in_y𝕆) h' }, { assumption } } }, rw filter_congr this at h, exact inductive_dec' ys_sub_vars d y𝕆_𝕆 y𝔹_𝔹 nd_y𝕆 nd_y𝔹 h end lemma inductive_weakening {β : const → var → lin_type} {ys : multiset typed_var} {y𝔹 : multiset var} {r : rc} {τ : lin_type} (h : β; ys ⊩ r ∷ τ) : β; ys + (y𝔹 {∶} 𝔹) ⊩ r ∷ τ := begin apply multiset.induction_on y𝔹, { simp only [map_zero, add_zero], assumption }, intros a s ih, simp only [map_cons, add_cons], apply linear.weaken, assumption end theorem C_app_rc_insertion_correctness {β : const → var → lin_type} {βₗ : var → lin_type} {δ : program} {y : var} {e : expr} {F : fn_body} {y𝕆 y𝔹 : multiset var} {Γ : list (var × lin_type)} (ih : ∀ (βₗ : var → lin_type), nodup y𝕆 → nodup y𝔹 → (∀ (y : var), y ∈ y𝕆 → βₗ y = 𝕆) → (∀ (y : var), y ∈ y𝔹 → βₗ y = 𝔹) → (β; δ; to_finset y𝕆 ∪ to_finset y𝔹 ⊢ F) → (∀ ⦃x : var⦄, x ∈ y𝕆 → x ∈ FV F) → (β; (y𝕆 {∶} 𝕆) + (y𝔹 {∶} 𝔹) ⊩ ↑(C β F βₗ) ∷ 𝕆)) (nd_y𝕆 : nodup y𝕆) (nd_y𝔹 : nodup y𝔹) (y𝕆_𝕆 : ∀ (y : var), y ∈ y𝕆 → βₗ y = 𝕆) (y𝔹_𝔹 : ∀ (y : var), y ∈ y𝔹 → βₗ y = 𝔹) (wf : β; δ; to_finset y𝕆 ∪ to_finset y𝔹 ⊢ (y ≔ e; F)) (y𝕆_free : ∀ ⦃x : var⦄, x ∈ y𝕆 → x ∈ FV (y ≔ e; F)) (ty : β; (Γ.map (λ (yτ : var × lin_type), yτ.1 ∶ yτ.2)) ⊩ e ∷ 𝕆) : (β; (y𝕆 {∶} 𝕆) + (y𝔹 {∶} 𝔹) ⊩ ↑(C_app Γ (y ≔ e; C β F (βₗ[y↦𝕆])) βₗ) ∷ 𝕆) := begin sorry end theorem rc_insertion_correctness' {β : const → var → lin_type} {δ : program} {c : const} {y𝕆 y𝔹 : multiset var} (nd_y𝕆 : nodup y𝕆) (nd_y𝔹 : nodup y𝔹) (y𝕆_𝕆 : ∀ y ∈ y𝕆, β c y = 𝕆) (y𝔹_𝔹 : ∀ y ∈ y𝔹, β c y = 𝔹) (y𝕆_sub_FV : y𝕆.to_finset ⊆ FV (δ c).F) (wf : β; δ; y𝕆.to_finset ∪ y𝔹.to_finset ⊢ (δ c).F) : β; (y𝕆 {∶} 𝕆) + (y𝔹 {∶} 𝔹) ⊩ C β ((δ c).F) (β c) ∷ 𝕆 := begin generalize h : β c = βₗ, rw h at *, clear h, simp only [finset.subset_iff, mem_to_finset] at y𝕆_sub_FV, generalize h : (δ c).F = F, rw h at *, clear h, with_cases { induction F using rc_correctness.fn_body.rec_wf generalizing y𝕆 y𝔹 βₗ }, case ret : x { unfold C, unfold FV at y𝕆_sub_FV, cases wf, simp only [mem_union, ndunion_eq_union, to_finset_val, nodup_erase_dup, mem_erase_dup, finset.mem_mk] at wf_x_def, unfold inc_𝕆_var, cases wf_x_def, { have : βₗ x = 𝕆 ∧ x ∉ finset.empty, from ⟨y𝕆_𝕆 x wf_x_def, finset.not_mem_empty x⟩, rw if_pos this, have : y𝕆 = x :: 0, { rw nodup_ext nd_y𝕆 (nodup_singleton x), intro a, split; intro h, { exact y𝕆_sub_FV h }, { rw mem_singleton at h, rwa h } }, rw this, simp only [finset.singleton_val, finset.insert_empty_eq_singleton, zero_add, map_cons, cons_add, map_zero], rw ←singleton_add, apply inductive_weakening, apply linear.ret }, { have : ¬(βₗ x = 𝕆 ∧ x ∉ finset.empty), { simp only [not_and], intro h, rw y𝔹_𝔹 x wf_x_def at h, simp only [] at h, contradiction }, rw if_neg this, apply linear.inc_𝔹, { apply mem_add.mpr, apply or.inr, exact mem_map_of_mem _ wf_x_def }, have : y𝕆 = ∅, { apply eq_zero_of_forall_not_mem, simp only [finset.insert_empty_eq_singleton, finset.mem_singleton] at y𝕆_sub_FV, intros y y_in_y𝕆, have x_in_y𝕆, from (y𝕆_sub_FV y_in_y𝕆).subst y_in_y𝕆, have dj : multiset.disjoint y𝕆 y𝔹, { rw disjoint_iff_ne, intros a a_in_y𝕆 b b_in_y𝔹 h, rw h at a_in_y𝕆, let := y𝕆_𝕆 b a_in_y𝕆, rw y𝔹_𝔹 b b_in_y𝔹 at this, contradiction }, let := disjoint_right.mp dj wf_x_def, contradiction }, simp only [this, empty_eq_zero, zero_add, map_zero], rw ←singleton_add, apply inductive_weakening, apply linear.ret } }, case «let» : y e F ih { with_cases { cases e }, case rc_correctness.expr.proj : i x wf { unfold C, split_ifs, { have x_in_y𝕆 : x ∈ y𝕆, { let := subset_iff.mp (FV_sub_wf_context wf), simp only [FV, FV_expr, mem_union, finset.singleton_val, to_finset_val, finset.insert_empty_eq_singleton, mem_erase_dup, finset.erase_val, finset.union_val, mem_singleton] at this, have h : x ∈ y𝕆 ∨ x ∈ y𝔹, from this (or.inl rfl), cases h, { assumption }, { rw y𝔹_𝔹 x h_1 at h, contradiction } }, apply linear.proj_𝕆, { simpa }, unfold dec_𝕆_var, split_ifs, { rcases exists_cons_of_mem x_in_y𝕆 with ⟨y𝕆', y𝕆_def⟩, rw y𝕆_def at *, simp only [map_cons, cons_add], rw cons_swap, apply linear.dec, rw ←cons_add, rw ←map_cons (∶ 𝕆), apply ih, any_goals { assumption }, { cases wf, simp only [not_or_distrib, mem_ndinsert, mem_ndunion, to_finset_val, mem_erase_dup, to_finset_cons, finset.insert_val, finset.mem_mk] at wf_z_undef, simp only [nodup_cons] at ⊢ nd_y𝕆, exact ⟨wf_z_undef.left.right, nd_y𝕆.right⟩ }, { simp only [mem_cons], intros z z_in_y𝕆', cases z_in_y𝕆', { rw z_in_y𝕆', rw function.update_same }, { by_cases z = y, { rw [h, function.update_same] }, { rw function.update_noteq, { exact y𝕆_𝕆 z (mem_cons_of_mem z_in_y𝕆') }, { assumption } } } }, { intros z z_in_y𝔹, by_cases z = y, { cases wf, simp [not_or_distrib] at wf_z_undef, rw h at z_in_y𝔹, exact absurd z_in_y𝔹 wf_z_undef.right }, { rw function.update_noteq, { exact y𝔹_𝔹 z z_in_y𝔹 }, { assumption } } }, { cases wf, apply wf_FV_sandwich _ _ wf_F_wf, { let := FV_sub_wf_context wf_F_wf, rw finset.subset_iff at ⊢ this, simp only [mem_ndinsert, mem_ndunion, to_finset_val, finset.insert_union, finset.mem_union, finset.mem_insert, mem_erase_dup, to_finset_cons, finset.insert_val, finset.mem_mk, mem_to_finset] at ⊢ this, intros z z_in_FV, have h', from this z_in_FV, repeat { cases h' }, { exact or.inl rfl }, { rw FV_C_eq_FV at h_1, exact absurd z_in_FV h_1.right }, { exact or.inr (or.inl h') }, { exact or.inr (or.inr h') } }, { rw finset.subset_iff, simp only [mem_ndinsert, mem_ndunion, to_finset_val, finset.insert_union, finset.mem_union, finset.mem_insert, mem_erase_dup, to_finset_cons, finset.insert_val, finset.mem_mk, mem_to_finset], intros y h', repeat { cases h' }, { exact or.inl rfl }, { exact or.inr (or.inl (or.inr h')) }, { exact or.inr (or.inr h') } } }, { cases wf, simp only [FV, FV_expr, mem_cons, finset.insert_empty_eq_singleton, finset.mem_union, finset.mem_singleton, finset.mem_erase] at ⊢ y𝕆_sub_FV, intros z h', cases h', { rwa h' }, have h'', from y𝕆_sub_FV (or.inr h'), cases h'', { rw h'' at h', rw nodup_cons at nd_y𝕆, exact absurd h' nd_y𝕆.left }, { exact h''.right } } }, simp only [not_and_distrib, not_not] at h_1, rw [←ne.def, not_𝕆_iff_𝔹] at h_1, cases h_1, { rw h at h_1, contradiction }, rw ←cons_add, rw ←map_cons (∶ 𝕆), apply ih, any_goals { assumption }, { cases wf, simp only [nodup_cons], simp only [not_or_distrib, mem_union, ndunion_eq_union, to_finset_val, nodup_erase_dup, mem_erase_dup, finset.mem_mk] at wf_z_undef, exact ⟨wf_z_undef.left, nd_y𝕆⟩ }, { simp only [mem_cons], intros z h', cases h', { rw h', rw function.update_same }, { by_cases eq : y = z, { rw eq, rw function.update_same }, rw function.update_noteq, { exact y𝕆_𝕆 z h' }, symmetry, assumption } }, { intros z z_in_y𝔹, by_cases z = y, { cases wf, simp only [not_or_distrib, mem_union, ndunion_eq_union, to_finset_val, nodup_erase_dup, mem_erase_dup, finset.mem_mk] at wf_z_undef, rw h at z_in_y𝔹, exact absurd z_in_y𝔹 wf_z_undef.right }, { rw function.update_noteq, { exact y𝔹_𝔹 z z_in_y𝔹 }, { assumption } } }, { cases wf, apply wf_FV_sandwich _ _ wf_F_wf, { let := FV_sub_wf_context wf_F_wf, rw finset.subset_iff at ⊢ this, simp only [mem_union, ndunion_eq_union, to_finset_val, nodup_erase_dup, finset.insert_union, finset.mem_union, finset.mem_insert, mem_erase_dup, to_finset_cons, finset.mem_mk, mem_to_finset] at ⊢ this, assumption }, { rw finset.subset_iff, simp only [multiset.mem_erase_dup, multiset.mem_union, multiset.nodup_erase_dup, imp_self, multiset.to_finset_val, multiset.mem_to_finset, multiset.to_finset_cons, finset.insert_union, finset.mem_union, finset.mem_insert, finset.mem_mk, multiset.ndunion_eq_union, forall_true_iff] } }, { cases wf, simp only [mem_cons], simp only [FV, FV_expr, finset.insert_empty_eq_singleton, finset.mem_union, finset.mem_singleton, finset.mem_erase] at y𝕆_sub_FV, intros z h', cases h', { rwa h' }, have h'', from y𝕆_sub_FV h', cases h'', { rw h'', rwa FV_C_eq_FV at h_1 }, { exact h''.right } } }, rw [←ne.def, not_𝕆_iff_𝔹] at h, have x_in_y𝔹 : x ∈ y𝔹, { let := subset_iff.mp (FV_sub_wf_context wf), simp only [FV, FV_expr, mem_union, finset.singleton_val, to_finset_val, finset.insert_empty_eq_singleton, mem_erase_dup, finset.erase_val, finset.union_val, mem_singleton] at this, have h : x ∈ y𝕆 ∨ x ∈ y𝔹, from this (or.inl rfl), cases h, { rw y𝕆_𝕆 x h_1 at h, contradiction }, { assumption } }, apply linear.proj_𝔹, { simpa }, rw [add_comm, ←cons_add, add_comm, ←map_cons (∶ 𝔹)], apply ih, any_goals { assumption }, { cases wf, simp only [nodup_cons], simp only [not_or_distrib, mem_union, ndunion_eq_union, to_finset_val, nodup_erase_dup, mem_erase_dup, finset.mem_mk] at wf_z_undef, exact ⟨wf_z_undef.right, nd_y𝔹⟩ }, { intros z z_in_y𝕆, by_cases z = y, { cases wf, simp only [not_or_distrib, mem_union, ndunion_eq_union, to_finset_val, nodup_erase_dup, mem_erase_dup, finset.mem_mk] at wf_z_undef, rw h at z_in_y𝕆, exact absurd z_in_y𝕆 wf_z_undef.left }, { rw function.update_noteq, { exact y𝕆_𝕆 z z_in_y𝕆 }, { assumption } } }, { simp only [mem_cons], intros z h', cases h', { rw h', rw function.update_same }, { by_cases eq : y = z, { rw eq, rw function.update_same }, rw function.update_noteq, { exact y𝔹_𝔹 z h' }, symmetry, assumption } }, { cases wf, apply wf_FV_sandwich _ _ wf_F_wf, { let := FV_sub_wf_context wf_F_wf, rw finset.subset_iff at ⊢ this, simp only [mem_union, ndunion_eq_union, to_finset_val, nodup_erase_dup, finset.mem_union, finset.union_insert, finset.mem_insert, mem_erase_dup, to_finset_cons, finset.mem_mk, mem_to_finset] at ⊢ this, assumption }, { rw finset.subset_iff, simp only [mem_erase_dup,mem_union, nodup_erase_dup, imp_self, to_finset_val, mem_to_finset, to_finset_cons, finset.mem_union, finset.union_insert, finset.mem_insert, finset.mem_mk, ndunion_eq_union, forall_true_iff] } }, { simp only [FV, FV_expr, finset.insert_empty_eq_singleton, finset.mem_union, finset.mem_singleton, finset.mem_erase] at y𝕆_sub_FV, intros z z_in_y𝕆, have h', from y𝕆_sub_FV z_in_y𝕆, cases h', { rw h' at z_in_y𝕆, rw y𝕆_𝕆 x z_in_y𝕆 at h, contradiction }, { exact h'.right } } }, case rc_correctness.expr.const_app_full : c' ys { unfold C, apply C_app_rc_insertion_correctness ih nd_y𝕆 nd_y𝔹 y𝕆_𝕆 y𝔹_𝔹 wf y𝕆_sub_FV, simp only [list.map_map], have : ∀ y ∈ ys, ((λ (yτ : var × lin_type), yτ.fst ∶ yτ.snd) ∘ (λ (y : var), (y, β c' y))) y = (λ (y : var), y ∶ β c' y) y, { intros y' y'_in_ys, refl }, rw list.map_congr this, exact linear.const_app_full β ys c' }, case rc_correctness.expr.const_app_part : c' ys { unfold C, have : ∀ y ∈ ys, (y, β c' y) = (y, 𝕆), { cases wf, intros y' y'_in_ys, have not_𝔹, from wf_no_𝔹_var y', rw not_𝔹_iff_𝕆 at not_𝔹, rw not_𝔹 }, rw list.map_congr this, apply C_app_rc_insertion_correctness ih nd_y𝕆 nd_y𝔹 y𝕆_𝕆 y𝔹_𝔹 wf y𝕆_sub_FV, rw list.map_map, have : ∀ y ∈ ys, ((λ (yτ : var × lin_type), yτ.fst ∶ yτ.snd) ∘ (λ (y : var), (y, 𝕆))) y = (λ (y : var), y ∶ 𝕆) y, { intros y' y'_in_ys, refl }, rw list.map_congr this, exact linear.const_app_part β ys c' }, case rc_correctness.expr.var_app : x z { unfold C, apply C_app_rc_insertion_correctness ih nd_y𝕆 nd_y𝔹 y𝕆_𝕆 y𝔹_𝔹 wf y𝕆_sub_FV, simp only [list.map], exact linear.var_app β x z }, case rc_correctness.expr.ctor : i ys { unfold C, apply C_app_rc_insertion_correctness ih nd_y𝕆 nd_y𝔹 y𝕆_𝕆 y𝔹_𝔹 wf y𝕆_sub_FV, rw list.map_map, have : ∀ y ∈ ys, ((λ (yτ : var × lin_type), yτ.fst ∶ yτ.snd) ∘ (λ (y : var), (y, 𝕆))) y = (λ (y : var), y ∶ 𝕆) y, { intros y' y'_in_ys, refl }, rw list.map_congr this, exact linear.ctor_app β ys i } }, case «case» : x Fs ih { unfold C, have FV_sub_y𝕆_y𝔹 : (FV (case x of Fs)).val ⊆ y𝕆 + y𝔹, { let := FV_sub_wf_context wf, rw finset.subset_def at this, rw subset_iff at ⊢ this, simp only [mem_union, to_finset_val, mem_add, mem_erase_dup, finset.union_val] at ⊢ this, assumption }, cases wf, simp only [mem_union, ndunion_eq_union, to_finset_val, nodup_erase_dup, mem_erase_dup, finset.mem_mk] at wf_x_def, cases wf_x_def, apply linear.case_𝕆, { simpa }, swap, apply linear.case_𝔹, { simpa }, all_goals { intros F' h, rw list.map_wf_eq_map at h, rw list.mem_map at h, rcases h with ⟨F, ⟨F_in_Fs, F'_def⟩⟩, rw ←F'_def, apply inductive_dec, any_goals { assumption }, { rw subset_iff, rw finset.sort_eq, intros y y_in_y𝕆, exact y𝕆_sub_FV y_in_y𝕆 }, { simp only [finset.sort_eq], assumption }, { exact finset.sort_nodup var_le (FV (case x of Fs)) }, apply ih, any_goals { assumption }, { apply nodup_filter, assumption }, { simp only [and_imp, mem_filter, finset.mem_sort], intros y y_in_y𝕆 h, exact y𝕆_𝕆 y y_in_y𝕆 }, { have wf, from wf_Fs_wf F F_in_Fs, apply wf_FV_sandwich _ _ wf, { rw finset.subset_iff, rw subset_iff at FV_sub_y𝕆_y𝔹, simp only [FV, list.map_wf_eq_map, mem_ndinsert, mem_add, finset.insert_val] at FV_sub_y𝕆_y𝔹, simp [FV, list.map_wf_eq_map, not_or_distrib], intros y y_in_FV, replace FV_sub_y𝕆_y𝔹 := @FV_sub_y𝕆_y𝔹 y, rw ←finset.mem_def at FV_sub_y𝕆_y𝔹, simp only [exists_prop, list.mem_map, finset.mem_join] at FV_sub_y𝕆_y𝔹, rw FV_C_eq_FV, have : ∃ (S : finset var), (∃ (a : fn_body), a ∈ Fs ∧ FV a = S) ∧ y ∈ S, { use FV F, apply and.intro _ y_in_FV, use F, exact ⟨F_in_Fs, rfl⟩ }, have : y ∈ y𝕆 ∨ y ∈ y𝔹, from FV_sub_y𝕆_y𝔹 (or.inr this), cases this, { exact or.inr ⟨this_1, y_in_FV⟩ }, { exact or.inl this_1 } }, { rw finset.subset_iff, simp only [mem_union, ndunion_eq_union, mem_filter, to_finset_val, nodup_erase_dup, finset.mem_union, mem_erase_dup, finset.mem_mk, mem_to_finset], intros y h, cases h, { exact or.inl (h.left) }, { exact or.inr h } } }, { simp only [and_imp, mem_filter, FV_C_eq_FV, imp_self, forall_true_iff] } } }, case «inc» : x F ih { cases wf }, case «dec» : x F ih { cases wf } end theorem rc_insertion_correctness (β : const → var → lin_type) (δ : program) (wf : β ⊢ δ) : β ⊩ C_prog β δ := begin cases wf, split, intro c, replace wf_const_wf := wf_const_wf c, cases wf_const_wf, rename wf_const_wf_F_wf wf, split, simp only [C_prog], let ys := (δ c).ys, let Γ := (↑(list.map (λ (y : var), y ∶ β c y) ys) : multiset typed_var), let y𝕆 := filter (λ y, β c y = 𝕆) ys, let y𝔹 := filter (λ y, β c y = 𝔹) ys, obtain ⟨y𝕆_𝕆, y𝔹_𝔹⟩ : (∀ y ∈ y𝕆, β c y = 𝕆) ∧ (∀ y ∈ y𝔹, β c y = 𝔹), { repeat { split }; { intros y h, rw (mem_filter.mp h).right } }, obtain ⟨y𝕆_sub_ys, y𝔹_sub_ys⟩ : (y𝕆 ⊆ ys ∧ y𝔹 ⊆ ys), { repeat { split }; simp only [filter_subset] }, obtain ⟨ys_𝕆_sub_y𝕆, ys_𝔹_sub_y𝔹⟩ : (∀ y ∈ ys, β c y = 𝕆 → y ∈ y𝕆) ∧ (∀ y ∈ ys, β c y = 𝔹 → y ∈ y𝔹), { repeat { split }; { intros y y_in_ys y_ty, simp only [mem_filter, mem_coe], try { rw ←coe_eq_coe }, exact ⟨y_in_ys, y_ty⟩ } }, obtain ⟨nd_y𝕆, nd_y𝔹⟩ : multiset.nodup y𝕆 ∧ multiset.nodup y𝔹, { split; exact nodup_filter _ (coe_nodup.mpr wf_const_wf_nd_ys) }, have ys_subdiv : ↑ys = y𝕆 + y𝔹, { have : ∀ y ∈ (↑ys : multiset var), β c y = 𝔹 ↔ β c y ≠ 𝕆, { intros y y_in_ys, split; intro h; cases β c y; simp at h ⊢; assumption }, simp only [y𝕆, y𝔹], rw filter_congr this, exact (filter_add_not ↑ys).symm }, have Γ_subdiv : ↑(list.map (λ (y : var), y ∶ β c y) ys) = (y𝕆 {∶} 𝕆) + (y𝔹 {∶} 𝔹), { have : ↑(list.map (λ (y : var), y ∶ β c y) ys) = map (λ (y : var), y ∶ β c y) ↑ys, from rfl, rw this, rw ys_subdiv, simp only [map_add], have : ∀ (τ : lin_type) (yτ : multiset var), (∀ y ∈ yτ, β c y = τ) → ∀ y ∈ yτ, (y ∶ β c y) = (y ∶ τ), { intros τ yτ h y y_in_yτ, rw h y y_in_yτ }, simp only [map_congr (this 𝕆 y𝕆 y𝕆_𝕆), map_congr (this 𝔹 y𝔹 y𝔹_𝔹)] }, have y𝕆_sub_FV : y𝕆.to_finset ⊆ FV (dec_𝕆 ((δ c).ys) (C β ((δ c).F) (β c)) (β c)), { rw finset.subset_iff, intros y y_in_y𝕆, simp only [mem_filter, mem_coe, mem_to_finset] at y_in_y𝕆, exact vars_sub_FV_dec_𝕆 ys (C β ((δ c).F) (β c)) (β c) y y_in_y𝕆.left y_in_y𝕆.right }, rw Γ_subdiv, unfold list.to_finset at wf, rw ys_subdiv at wf, have : ↑ys ⊆ y𝕆 + y𝔹, { rw ys_subdiv, exact subset.refl _ }, apply inductive_dec y𝕆_sub_ys this wf_const_wf_nd_ys y𝕆_𝕆 y𝔹_𝔹 nd_y𝕆 nd_y𝔹, let y𝕆' := filter (λ (y : var), y ∈ FV (C β ((δ c).F) (β c))) y𝕆, have y𝕆'_𝕆 : ∀ y ∈ y𝕆', β c y = 𝕆, { simp only [and_imp, mem_filter, mem_coe], intros y y_in_ys y_𝕆 y_in_FV, assumption }, have nd_y𝕆' : nodup y𝕆', from nodup_filter _ nd_y𝕆, have y𝕆'_sub_y𝕆 : y𝕆' ⊆ y𝕆, from filter_subset y𝕆, have y𝕆'_sub_FV : y𝕆'.to_finset ⊆ FV (δ c).F, { rw finset.subset_iff, rw finset.subset_iff at y𝕆_sub_FV, rw subset_iff at y𝕆'_sub_y𝕆, simp only [mem_to_finset], simp only [mem_to_finset] at y𝕆_sub_FV, rw FV_dec_𝕆_filter at y𝕆_sub_FV, intros x x_in_y𝕆', have h, from y𝕆_sub_FV (y𝕆'_sub_y𝕆 x_in_y𝕆'), simp only [mem_filter, mem_coe] at x_in_y𝕆', simp only [list.mem_to_finset, finset.mem_union, finset.mem_filter] at h, cases h, { exact absurd x_in_y𝕆'.right h.right.right }, rwa FV_C_eq_FV at h }, have wf' : (β; δ; to_finset y𝕆' ∪ to_finset y𝔹 ⊢ (δ c).F), { rw to_finset_add at wf, have h1 : FV (δ c).F ⊆ to_finset y𝕆' ∪ to_finset y𝔹, { have : FV (δ c).F ⊆ to_finset y𝕆 ∪ to_finset y𝔹, from FV_sub_wf_context wf, rw finset.subset_iff at this, rw finset.subset_iff, intros x x_in_FV, let := this x_in_FV, simp only [mem_filter, mem_coe, finset.mem_union, mem_to_finset] at this ⊢, cases this, { rw FV_C_eq_FV, exact or.inl ⟨this_1, x_in_FV ⟩ }, { exact or.inr this_1 } }, have h2 : to_finset y𝕆' ∪ to_finset y𝔹 ⊆ to_finset y𝕆 ∪ to_finset y𝔹, { rw subset_iff at y𝕆'_sub_y𝕆, simp only [finset.subset_iff, finset.mem_union, mem_to_finset], intros x h, cases h, { exact or.inl (y𝕆'_sub_y𝕆 h) }, { exact or.inr h } }, exact wf_FV_sandwich h1 h2 wf }, exact rc_insertion_correctness' nd_y𝕆' nd_y𝔹 y𝕆'_𝕆 y𝔹_𝔹 y𝕆'_sub_FV wf' end end rc_correctness
5ee51bc2642c61e03dac7c3b7965b9fdb96f2c4c
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/analysis/specific_limits.lean
5064060955ff916739cdb5b8d0a221cd90ceb785
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
21,549
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 A collection of specific limit computations. -/ import analysis.normed_space.basic algebra.geom_sum import topology.instances.ennreal noncomputable theory open_locale classical topological_space open classical function filter finset metric variables {α : Type*} {β : Type*} {ι : Type*} lemma tendsto_norm_at_top_at_top : tendsto (norm : ℝ → ℝ) at_top at_top := tendsto_abs_at_top_at_top /-- If a function tends to infinity along a filter, then this function multiplied by a positive constant (on the left) also tends to infinity. The archimedean assumption is convenient to get a statement that works on `ℕ`, `ℤ` and `ℝ`, although not necessary (a version in ordered fields is given in `tendsto_at_top_mul_left'`). -/ lemma tendsto_at_top_mul_left [decidable_linear_ordered_semiring α] [archimedean α] {l : filter β} {r : α} (hr : 0 < r) {f : β → α} (hf : tendsto f l at_top) : tendsto (λx, r * f x) l at_top := begin apply (tendsto_at_top _ _).2 (λb, _), obtain ⟨n, hn⟩ : ∃ (n : ℕ), (1 : α) ≤ n • r := archimedean.arch 1 hr, have hn' : 1 ≤ r * n, by rwa add_monoid.smul_eq_mul' at hn, filter_upwards [(tendsto_at_top _ _).1 hf (n * max b 0)], assume x hx, calc b ≤ 1 * max b 0 : by { rw [one_mul], exact le_max_left _ _ } ... ≤ (r * n) * max b 0 : mul_le_mul_of_nonneg_right hn' (le_max_right _ _) ... = r * (n * max b 0) : by rw [mul_assoc] ... ≤ r * f x : mul_le_mul_of_nonneg_left hx (le_of_lt hr) end /-- If a function tends to infinity along a filter, then this function multiplied by a positive constant (on the right) also tends to infinity. The archimedean assumption is convenient to get a statement that works on `ℕ`, `ℤ` and `ℝ`, although not necessary (a version in ordered fields is given in `tendsto_at_top_mul_right'`). -/ lemma tendsto_at_top_mul_right [decidable_linear_ordered_semiring α] [archimedean α] {l : filter β} {r : α} (hr : 0 < r) {f : β → α} (hf : tendsto f l at_top) : tendsto (λx, f x * r) l at_top := begin apply (tendsto_at_top _ _).2 (λb, _), obtain ⟨n, hn⟩ : ∃ (n : ℕ), (1 : α) ≤ n • r := archimedean.arch 1 hr, have hn' : 1 ≤ (n : α) * r, by rwa add_monoid.smul_eq_mul at hn, filter_upwards [(tendsto_at_top _ _).1 hf (max b 0 * n)], assume x hx, calc b ≤ max b 0 * 1 : by { rw [mul_one], exact le_max_left _ _ } ... ≤ max b 0 * (n * r) : mul_le_mul_of_nonneg_left hn' (le_max_right _ _) ... = (max b 0 * n) * r : by rw [mul_assoc] ... ≤ f x * r : mul_le_mul_of_nonneg_right hx (le_of_lt hr) end /-- If a function tends to infinity along a filter, then this function multiplied by a positive constant (on the left) also tends to infinity. For a version working in `ℕ` or `ℤ`, use `tendsto_at_top_mul_left` instead. -/ lemma tendsto_at_top_mul_left' [linear_ordered_field α] {l : filter β} {r : α} (hr : 0 < r) {f : β → α} (hf : tendsto f l at_top) : tendsto (λx, r * f x) l at_top := begin apply (tendsto_at_top _ _).2 (λb, _), filter_upwards [(tendsto_at_top _ _).1 hf (b/r)], assume x hx, simpa [div_le_iff' hr] using hx end /-- If a function tends to infinity along a filter, then this function multiplied by a positive constant (on the right) also tends to infinity. For a version working in `ℕ` or `ℤ`, use `tendsto_at_top_mul_right` instead. -/ lemma tendsto_at_top_mul_right' [linear_ordered_field α] {l : filter β} {r : α} (hr : 0 < r) {f : β → α} (hf : tendsto f l at_top) : tendsto (λx, f x * r) l at_top := by simpa [mul_comm] using tendsto_at_top_mul_left' hr hf /-- If a function tends to infinity along a filter, then this function divided by a positive constant also tends to infinity. -/ lemma tendsto_at_top_div [linear_ordered_field α] {l : filter β} {r : α} (hr : 0 < r) {f : β → α} (hf : tendsto f l at_top) : tendsto (λx, f x / r) l at_top := tendsto_at_top_mul_right' (inv_pos.2 hr) hf /-- The function `x ↦ x⁻¹` tends to `+∞` on the right of `0`. -/ lemma tendsto_inv_zero_at_top [discrete_linear_ordered_field α] [topological_space α] [order_topology α] : tendsto (λx:α, x⁻¹) (nhds_within (0 : α) (set.Ioi 0)) at_top := begin apply (tendsto_at_top _ _).2 (λb, _), refine mem_nhds_within_Ioi_iff_exists_Ioo_subset.2 ⟨(max b 1)⁻¹, by simp [zero_lt_one], λx hx, _⟩, calc b ≤ max b 1 : le_max_left _ _ ... ≤ x⁻¹ : begin apply (le_inv _ hx.1).2 (le_of_lt hx.2), exact lt_of_lt_of_le zero_lt_one (le_max_right _ _) end end /-- The function `r ↦ r⁻¹` tends to `0` on the right as `r → +∞`. -/ lemma tendsto_inv_at_top_zero' [discrete_linear_ordered_field α] [topological_space α] [order_topology α] : tendsto (λr:α, r⁻¹) at_top (nhds_within (0 : α) (set.Ioi 0)) := begin assume s hs, rw mem_nhds_within_Ioi_iff_exists_Ioc_subset at hs, rcases hs with ⟨C, C0, hC⟩, change 0 < C at C0, refine filter.mem_map.2 (mem_sets_of_superset (mem_at_top C⁻¹) (λ x hx, hC _)), have : 0 < x, from lt_of_lt_of_le (inv_pos.2 C0) hx, exact ⟨inv_pos.2 this, (inv_le C0 this).1 hx⟩ end lemma tendsto_inv_at_top_zero [discrete_linear_ordered_field α] [topological_space α] [order_topology α] : tendsto (λr:α, r⁻¹) at_top (𝓝 0) := tendsto_le_right inf_le_left tendsto_inv_at_top_zero' lemma summable_of_absolute_convergence_real {f : ℕ → ℝ} : (∃r, tendsto (λn, (range n).sum (λi, abs (f i))) at_top (𝓝 r)) → summable f | ⟨r, hr⟩ := begin refine summable_of_summable_norm ⟨r, (has_sum_iff_tendsto_nat_of_nonneg _ _).2 _⟩, exact assume i, norm_nonneg _, simpa only using hr end lemma tendsto_pow_at_top_at_top_of_gt_1 {r : ℝ} (h : 1 < r) : tendsto (λn:ℕ, r ^ n) at_top at_top := (tendsto_at_top_at_top _).2 $ assume p, let ⟨n, hn⟩ := pow_unbounded_of_one_lt p h in ⟨n, λ m hnm, le_of_lt $ lt_of_lt_of_le hn (pow_le_pow (le_of_lt h) hnm)⟩ lemma lim_norm_zero' {𝕜 : Type*} [normed_group 𝕜] : tendsto (norm : 𝕜 → ℝ) (nhds_within 0 {x | x ≠ 0}) (nhds_within 0 (set.Ioi 0)) := lim_norm_zero.inf $ tendsto_principal_principal.2 $ λ x hx, norm_pos_iff.2 hx lemma normed_field.tendsto_norm_inverse_nhds_within_0_at_top {𝕜 : Type*} [normed_field 𝕜] : tendsto (λ x:𝕜, ∥x⁻¹∥) (nhds_within 0 {x | x ≠ 0}) at_top := (tendsto_inv_zero_at_top.comp lim_norm_zero').congr $ λ x, (normed_field.norm_inv x).symm lemma tendsto_pow_at_top_nhds_0_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : tendsto (λn:ℕ, r^n) at_top (𝓝 0) := by_cases (assume : r = 0, (tendsto_add_at_top_iff_nat 1).mp $ by simp [pow_succ, this, tendsto_const_nhds]) (assume : r ≠ 0, have tendsto (λn, (r⁻¹ ^ n)⁻¹) at_top (𝓝 0), from tendsto_inv_at_top_zero.comp (tendsto_pow_at_top_at_top_of_gt_1 $ one_lt_inv (lt_of_le_of_ne h₁ this.symm) h₂), tendsto.congr' (univ_mem_sets' $ by simp *) this) lemma nnreal.tendsto_pow_at_top_nhds_0_of_lt_1 {r : nnreal} (hr : r < 1) : tendsto (λ n:ℕ, r^n) at_top (𝓝 0) := nnreal.tendsto_coe.1 $ by simp only [nnreal.coe_pow, nnreal.coe_zero, tendsto_pow_at_top_nhds_0_of_lt_1 r.coe_nonneg hr] lemma ennreal.tendsto_pow_at_top_nhds_0_of_lt_1 {r : ennreal} (hr : r < 1) : tendsto (λ n:ℕ, r^n) at_top (𝓝 0) := begin rcases ennreal.lt_iff_exists_coe.1 hr with ⟨r, rfl, hr'⟩, rw [← ennreal.coe_zero], norm_cast at *, apply nnreal.tendsto_pow_at_top_nhds_0_of_lt_1 hr end lemma tendsto_pow_at_top_nhds_0_of_lt_1_normed_field {K : Type*} [normed_field K] {ξ : K} (_ : ∥ξ∥ < 1) : tendsto (λ n : ℕ, ξ^n) at_top (𝓝 0) := begin rw[tendsto_iff_norm_tendsto_zero], convert tendsto_pow_at_top_nhds_0_of_lt_1 (norm_nonneg ξ) ‹∥ξ∥ < 1›, ext n, simp end lemma tendsto_pow_at_top_at_top_of_gt_1_nat {k : ℕ} (h : 1 < k) : tendsto (λn:ℕ, k ^ n) at_top at_top := tendsto_coe_nat_real_at_top_iff.1 $ have hr : 1 < (k : ℝ), by rw [← nat.cast_one, nat.cast_lt]; exact h, by simpa using tendsto_pow_at_top_at_top_of_gt_1 hr lemma tendsto_inverse_at_top_nhds_0_nat : tendsto (λ n : ℕ, (n : ℝ)⁻¹) at_top (𝓝 0) := tendsto_inv_at_top_zero.comp (tendsto_coe_nat_real_at_top_iff.2 tendsto_id) lemma tendsto_const_div_at_top_nhds_0_nat (C : ℝ) : tendsto (λ n : ℕ, C / n) at_top (𝓝 0) := by simpa only [mul_zero] using tendsto_const_nhds.mul tendsto_inverse_at_top_nhds_0_nat lemma nnreal.tendsto_inverse_at_top_nhds_0_nat : tendsto (λ n : ℕ, (n : nnreal)⁻¹) at_top (𝓝 0) := by { rw ← nnreal.tendsto_coe, convert tendsto_inverse_at_top_nhds_0_nat, simp } lemma nnreal.tendsto_const_div_at_top_nhds_0_nat (C : nnreal) : tendsto (λ n : ℕ, C / n) at_top (𝓝 0) := by simpa using tendsto_const_nhds.mul nnreal.tendsto_inverse_at_top_nhds_0_nat lemma tendsto_one_div_add_at_top_nhds_0_nat : tendsto (λ n : ℕ, 1 / ((n : ℝ) + 1)) at_top (𝓝 0) := suffices tendsto (λ n : ℕ, 1 / (↑(n + 1) : ℝ)) at_top (𝓝 0), by simpa, (tendsto_add_at_top_iff_nat 1).2 (tendsto_const_div_at_top_nhds_0_nat 1) lemma has_sum_geometric {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : has_sum (λn:ℕ, r ^ n) (1 - r)⁻¹ := have r ≠ 1, from ne_of_lt h₂, have r + -1 ≠ 0, by rw [←sub_eq_add_neg, ne, sub_eq_iff_eq_add]; simp; assumption, have tendsto (λn, (r ^ n - 1) * (r - 1)⁻¹) at_top (𝓝 ((0 - 1) * (r - 1)⁻¹)), from ((tendsto_pow_at_top_nhds_0_of_lt_1 h₁ h₂).sub tendsto_const_nhds).mul tendsto_const_nhds, have (λ n, (range n).sum (λ i, r ^ i)) = (λ n, geom_series r n) := rfl, (has_sum_iff_tendsto_nat_of_nonneg (pow_nonneg h₁) _).mpr $ by simp [neg_inv, geom_sum, div_eq_mul_inv, *] at * lemma summable_geometric {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : summable (λn:ℕ, r ^ n) := ⟨_, has_sum_geometric h₁ h₂⟩ lemma tsum_geometric {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : (∑n:ℕ, r ^ n) = (1 - r)⁻¹ := tsum_eq_has_sum (has_sum_geometric h₁ h₂) lemma has_sum_geometric_two : has_sum (λn:ℕ, ((1:ℝ)/2) ^ n) 2 := by convert has_sum_geometric _ _; norm_num lemma summable_geometric_two : summable (λn:ℕ, ((1:ℝ)/2) ^ n) := ⟨_, has_sum_geometric_two⟩ lemma tsum_geometric_two : (∑n:ℕ, ((1:ℝ)/2) ^ n) = 2 := tsum_eq_has_sum has_sum_geometric_two lemma has_sum_geometric_two' (a : ℝ) : has_sum (λn:ℕ, (a / 2) / 2 ^ n) a := begin convert has_sum.mul_left (a / 2) (has_sum_geometric (le_of_lt one_half_pos) one_half_lt_one), { funext n, simp, refl, }, { norm_num, rw div_mul_cancel, norm_num } end lemma summable_geometric_two' (a : ℝ) : summable (λ n:ℕ, (a / 2) / 2 ^ n) := ⟨a, has_sum_geometric_two' a⟩ lemma tsum_geometric_two' (a : ℝ) : (∑ n:ℕ, (a / 2) / 2^n) = a := tsum_eq_has_sum $ has_sum_geometric_two' a lemma nnreal.has_sum_geometric {r : nnreal} (hr : r < 1) : has_sum (λ n : ℕ, r ^ n) (1 - r)⁻¹ := begin apply nnreal.has_sum_coe.1, push_cast, rw [nnreal.coe_sub (le_of_lt hr)], exact has_sum_geometric r.coe_nonneg hr end lemma nnreal.summable_geometric {r : nnreal} (hr : r < 1) : summable (λn:ℕ, r ^ n) := ⟨_, nnreal.has_sum_geometric hr⟩ lemma tsum_geometric_nnreal {r : nnreal} (hr : r < 1) : (∑n:ℕ, r ^ n) = (1 - r)⁻¹ := tsum_eq_has_sum (nnreal.has_sum_geometric hr) /-- The series `pow r` converges to `(1-r)⁻¹`. For `r < 1` the RHS is a finite number, and for `1 ≤ r` the RHS equals `∞`. -/ lemma ennreal.tsum_geometric (r : ennreal) : (∑n:ℕ, r ^ n) = (1 - r)⁻¹ := begin cases lt_or_le r 1 with hr hr, { rcases ennreal.lt_iff_exists_coe.1 hr with ⟨r, rfl, hr'⟩, norm_cast at *, convert ennreal.tsum_coe_eq (nnreal.has_sum_geometric hr), rw [ennreal.coe_inv $ ne_of_gt $ nnreal.sub_pos.2 hr] }, { rw [ennreal.sub_eq_zero_of_le hr, ennreal.inv_zero, ennreal.tsum_eq_supr_nat, supr_eq_top], refine λ a ha, (ennreal.exists_nat_gt (lt_top_iff_ne_top.1 ha)).imp (λ n hn, lt_of_lt_of_le hn _), have : ∀ k:ℕ, 1 ≤ r^k, by simpa using canonically_ordered_semiring.pow_le_pow_of_le_left hr, calc (n:ennreal) = (range n).sum (λ _, 1) : by rw [sum_const, add_monoid.smul_one, card_range] ... ≤ (range n).sum (pow r) : sum_le_sum (λ k _, this k) } end /-- For any positive `ε`, define on an encodable type a positive sequence with sum less than `ε` -/ def pos_sum_of_encodable {ε : ℝ} (hε : 0 < ε) (ι) [encodable ι] : {ε' : ι → ℝ // (∀ i, 0 < ε' i) ∧ ∃ c, has_sum ε' c ∧ c ≤ ε} := begin let f := λ n, (ε / 2) / 2 ^ n, have hf : has_sum f ε := has_sum_geometric_two' _, have f0 : ∀ n, 0 < f n := λ n, div_pos (half_pos hε) (pow_pos two_pos _), refine ⟨f ∘ encodable.encode, λ i, f0 _, _⟩, rcases hf.summable.summable_comp_of_injective (@encodable.encode_injective ι _) with ⟨c, hg⟩, refine ⟨c, hg, has_sum_le_inj _ (@encodable.encode_injective ι _) _ _ hg hf⟩, { assume i _, exact le_of_lt (f0 _) }, { assume n, exact le_refl _ } end section edist_le_geometric variables [emetric_space α] (r C : ennreal) (hr : r < 1) (hC : C ≠ ⊤) {f : ℕ → α} (hu : ∀n, edist (f n) (f (n+1)) ≤ C * r^n) include hr hC hu /-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, `C ≠ ∞`, `r < 1`, then `f` is a Cauchy sequence.-/ lemma cauchy_seq_of_edist_le_geometric : cauchy_seq f := begin refine cauchy_seq_of_edist_le_of_tsum_ne_top _ hu _, rw [ennreal.tsum_mul_left, ennreal.tsum_geometric], refine ennreal.mul_ne_top hC (ennreal.inv_ne_top.2 _), exact ne_of_gt (ennreal.zero_lt_sub_iff_lt.2 hr) end omit hr hC /-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, then the distance from `f n` to the limit of `f` is bounded above by `C * r^n / (1 - r)`. -/ lemma edist_le_of_edist_le_geometric_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : edist (f n) a ≤ (C * r^n) / (1 - r) := begin convert edist_le_tsum_of_edist_le_of_tendsto _ hu ha _, simp only [pow_add, ennreal.tsum_mul_left, ennreal.tsum_geometric, ennreal.div_def, mul_assoc] end /-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, then the distance from `f 0` to the limit of `f` is bounded above by `C / (1 - r)`. -/ lemma edist_le_of_edist_le_geometric_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) : edist (f 0) a ≤ C / (1 - r) := by simpa only [pow_zero, mul_one] using edist_le_of_edist_le_geometric_of_tendsto r C hu ha 0 end edist_le_geometric section edist_le_geometric_two variables [emetric_space α] (C : ennreal) (hC : C ≠ ⊤) {f : ℕ → α} (hu : ∀n, edist (f n) (f (n+1)) ≤ C / 2^n) {a : α} (ha : tendsto f at_top (𝓝 a)) include hC hu /-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then `f` is a Cauchy sequence.-/ lemma cauchy_seq_of_edist_le_geometric_two : cauchy_seq f := begin simp only [ennreal.div_def, ennreal.inv_pow'] at hu, refine cauchy_seq_of_edist_le_geometric 2⁻¹ C _ hC hu, simp [ennreal.one_lt_two] end omit hC include ha /-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then the distance from `f n` to the limit of `f` is bounded above by `2 * C * 2^-n`. -/ lemma edist_le_of_edist_le_geometric_two_of_tendsto (n : ℕ) : edist (f n) a ≤ 2 * C / 2^n := begin simp only [ennreal.div_def, ennreal.inv_pow'] at hu, rw [ennreal.div_def, mul_assoc, mul_comm, ennreal.inv_pow'], convert edist_le_of_edist_le_geometric_of_tendsto 2⁻¹ C hu ha n, rw [ennreal.one_sub_inv_two, ennreal.inv_inv] end /-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then the distance from `f 0` to the limit of `f` is bounded above by `2 * C`. -/ lemma edist_le_of_edist_le_geometric_two_of_tendsto₀: edist (f 0) a ≤ 2 * C := by simpa only [pow_zero, ennreal.div_def, ennreal.inv_one, mul_one] using edist_le_of_edist_le_geometric_two_of_tendsto C hu ha 0 end edist_le_geometric_two section le_geometric variables [metric_space α] {r C : ℝ} (hr : r < 1) {f : ℕ → α} (hu : ∀n, dist (f n) (f (n+1)) ≤ C * r^n) include hr hu lemma aux_has_sum_of_le_geometric : has_sum (λ n : ℕ, C * r^n) (C / (1 - r)) := begin have h0 : 0 ≤ C, by simpa using le_trans dist_nonneg (hu 0), rcases eq_or_lt_of_le h0 with rfl | Cpos, { simp [has_sum_zero] }, { have rnonneg: r ≥ 0, from nonneg_of_mul_nonneg_left (by simpa only [pow_one] using le_trans dist_nonneg (hu 1)) Cpos, refine has_sum.mul_left C _, by simpa using has_sum_geometric rnonneg hr } end variables (r C) /-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then `f` is a Cauchy sequence. Note that this lemma does not assume `0 ≤ C` or `0 ≤ r`. -/ lemma cauchy_seq_of_le_geometric : cauchy_seq f := cauchy_seq_of_dist_le_of_summable _ hu ⟨_, aux_has_sum_of_le_geometric hr hu⟩ /-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then the distance from `f n` to the limit of `f` is bounded above by `C * r^n / (1 - r)`. -/ lemma dist_le_of_le_geometric_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ C / (1 - r) := (tsum_eq_has_sum $ aux_has_sum_of_le_geometric hr hu) ▸ dist_le_tsum_of_dist_le_of_tendsto₀ _ hu ⟨_, aux_has_sum_of_le_geometric hr hu⟩ ha /-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then the distance from `f 0` to the limit of `f` is bounded above by `C / (1 - r)`. -/ lemma dist_le_of_le_geometric_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : dist (f n) a ≤ (C * r^n) / (1 - r) := begin have := aux_has_sum_of_le_geometric hr hu, convert dist_le_tsum_of_dist_le_of_tendsto _ hu ⟨_, this⟩ ha n, simp only [pow_add, mul_left_comm C, mul_div_right_comm], rw [mul_comm], exact (eq.symm $ tsum_eq_has_sum $ this.mul_left _) end omit hr hu variable (hu₂ : ∀ n, dist (f n) (f (n+1)) ≤ (C / 2) / 2^n) /-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then `f` is a Cauchy sequence. -/ lemma cauchy_seq_of_le_geometric_two : cauchy_seq f := cauchy_seq_of_dist_le_of_summable _ hu₂ $ ⟨_, has_sum_geometric_two' C⟩ /-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then the distance from `f 0` to the limit of `f` is bounded above by `C`. -/ lemma dist_le_of_le_geometric_two_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ C := (tsum_geometric_two' C) ▸ dist_le_tsum_of_dist_le_of_tendsto₀ _ hu₂ (summable_geometric_two' C) ha include hu₂ /-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then the distance from `f n` to the limit of `f` is bounded above by `C / 2^n`. -/ lemma dist_le_of_le_geometric_two_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : dist (f n) a ≤ C / 2^n := begin convert dist_le_tsum_of_dist_le_of_tendsto _ hu₂ (summable_geometric_two' C) ha n, simp only [add_comm n, pow_add, (div_div_eq_div_mul _ _ _).symm], symmetry, exact tsum_eq_has_sum (has_sum.mul_right _ $ has_sum_geometric_two' C) end end le_geometric section summable_le_geometric variables [normed_group α] {r C : ℝ} {f : ℕ → α} lemma dist_partial_sum_le_of_le_geometric (hf : ∀n, ∥f n∥ ≤ C * r^n) (n : ℕ) : dist ((finset.range n).sum f) ((finset.range (n+1)).sum f) ≤ C * r ^ n := begin rw [sum_range_succ, dist_eq_norm, ← norm_neg], convert hf n, abel end /-- If `∥f n∥ ≤ C * r ^ n` for all `n : ℕ` and some `r < 1`, then the partial sums of `f` form a Cauchy sequence. This lemma does not assume `0 ≤ r` or `0 ≤ C`. -/ lemma cauchy_seq_finset_of_geometric_bound (hr : r < 1) (hf : ∀n, ∥f n∥ ≤ C * r^n) : cauchy_seq (λ s : finset (ℕ), s.sum f) := cauchy_seq_finset_of_norm_bounded _ (aux_has_sum_of_le_geometric hr (dist_partial_sum_le_of_le_geometric hf)).summable hf /-- If `∥f n∥ ≤ C * r ^ n` for all `n : ℕ` and some `r < 1`, then the partial sums of `f` are within distance `C * r ^ n / (1 - r)` of the sum of the series. This lemma does not assume `0 ≤ r` or `0 ≤ C`. -/ lemma norm_sub_le_of_geometric_bound_of_has_sum (hr : r < 1) (hf : ∀n, ∥f n∥ ≤ C * r^n) {a : α} (ha : has_sum f a) (n : ℕ) : ∥(finset.range n).sum f - a∥ ≤ (C * r ^ n) / (1 - r) := begin rw ← dist_eq_norm, apply dist_le_of_le_geometric_of_tendsto r C hr (dist_partial_sum_le_of_le_geometric hf), exact ha.tendsto_sum_nat end end summable_le_geometric namespace nnreal theorem exists_pos_sum_of_encodable {ε : nnreal} (hε : 0 < ε) (ι) [encodable ι] : ∃ ε' : ι → nnreal, (∀ i, 0 < ε' i) ∧ ∃c, has_sum ε' c ∧ c < ε := let ⟨a, a0, aε⟩ := dense hε in let ⟨ε', hε', c, hc, hcε⟩ := pos_sum_of_encodable a0 ι in ⟨ λi, ⟨ε' i, le_of_lt $ hε' i⟩, assume i, nnreal.coe_lt_coe.2 $ hε' i, ⟨c, has_sum_le (assume i, le_of_lt $ hε' i) has_sum_zero hc ⟩, nnreal.has_sum_coe.1 hc, lt_of_le_of_lt (nnreal.coe_le_coe.1 hcε) aε ⟩ end nnreal namespace ennreal theorem exists_pos_sum_of_encodable {ε : ennreal} (hε : 0 < ε) (ι) [encodable ι] : ∃ ε' : ι → nnreal, (∀ i, 0 < ε' i) ∧ (∑ i, (ε' i : ennreal)) < ε := begin rcases dense hε with ⟨r, h0r, hrε⟩, rcases lt_iff_exists_coe.1 hrε with ⟨x, rfl, hx⟩, rcases nnreal.exists_pos_sum_of_encodable (coe_lt_coe.1 h0r) ι with ⟨ε', hp, c, hc, hcr⟩, exact ⟨ε', hp, (ennreal.tsum_coe_eq hc).symm ▸ lt_trans (coe_lt_coe.2 hcr) hrε⟩ end end ennreal
a0dc39f96d6fd75096f2f6cc3c50bbed53669a66
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/category_theory/pi/basic.lean
d69225d400c307f6390fa376a180699708fe8a91
[ "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
4,343
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Scott Morrison -/ import category_theory.natural_isomorphism import category_theory.eq_to_hom /-! # Categories of indexed families of objects. We define the pointwise category structure on indexed families of objects in a category (and also the dependent generalization). -/ namespace category_theory universes w₀ w₁ w₂ v₁ v₂ u₁ u₂ variables {I : Type w₀} (C : I → Type u₁) [Π i, category.{v₁} (C i)] /-- `pi C` gives the cartesian product of an indexed family of categories. -/ instance pi : category.{max w₀ v₁} (Π i, C i) := { hom := λ X Y, Π i, X i ⟶ Y i, id := λ X i, 𝟙 (X i), comp := λ X Y Z f g i, f i ≫ g i } /-- This provides some assistance to typeclass search in a common situation, which otherwise fails. (Without this `category_theory.pi.has_limit_of_has_limit_comp_eval` fails.) -/ abbreviation pi' {I : Type v₁} (C : I → Type u₁) [Π i, category.{v₁} (C i)] : category.{v₁} (Π i, C i) := category_theory.pi C attribute [instance] pi' namespace pi @[simp] lemma id_apply (X : Π i, C i) (i) : (𝟙 X : Π i, X i ⟶ X i) i = 𝟙 (X i) := rfl @[simp] lemma comp_apply {X Y Z : Π i, C i} (f : X ⟶ Y) (g : Y ⟶ Z) (i) : (f ≫ g : Π i, X i ⟶ Z i) i = f i ≫ g i := rfl /-- The evaluation functor at `i : I`, sending an `I`-indexed family of objects to the object over `i`. -/ @[simps] def eval (i : I) : (Π i, C i) ⥤ C i := { obj := λ f, f i, map := λ f g α, α i, } section variables {J : Type w₁} /-- Pull back an `I`-indexed family of objects to an `J`-indexed family, along a function `J → I`. -/ @[simps] def comap (h : J → I) : (Π i, C i) ⥤ (Π j, C (h j)) := { obj := λ f i, f (h i), map := λ f g α i, α (h i), } variables (I) /-- The natural isomorphism between pulling back a grading along the identity function, and the identity functor. -/ @[simps] def comap_id : comap C (id : I → I) ≅ 𝟭 (Π i, C i) := { hom := { app := λ X, 𝟙 X }, inv := { app := λ X, 𝟙 X } }. variables {I} variables {K : Type w₂} /-- The natural isomorphism comparing between pulling back along two successive functions, and pulling back along their composition -/ @[simps] def comap_comp (f : K → J) (g : J → I) : comap C g ⋙ comap (C ∘ g) f ≅ comap C (g ∘ f) := { hom := { app := λ X b, 𝟙 (X (g (f b))) }, inv := { app := λ X b, 𝟙 (X (g (f b))) } } /-- The natural isomorphism between pulling back then evaluating, and just evaluating. -/ @[simps] def comap_eval_iso_eval (h : J → I) (j : J) : comap C h ⋙ eval (C ∘ h) j ≅ eval C (h j) := nat_iso.of_components (λ f, iso.refl _) (by tidy) end section variables {J : Type w₀} {D : J → Type u₁} [Π j, category.{v₁} (D j)] instance sum_elim_category : Π (s : I ⊕ J), category.{v₁} (sum.elim C D s) | (sum.inl i) := by { dsimp, apply_instance, } | (sum.inr j) := by { dsimp, apply_instance, } /-- The bifunctor combining an `I`-indexed family of objects with a `J`-indexed family of objects to obtain an `I ⊕ J`-indexed family of objects. -/ @[simps] def sum : (Π i, C i) ⥤ (Π j, D j) ⥤ (Π s : I ⊕ J, sum.elim C D s) := { obj := λ f, { obj := λ g s, sum.rec f g s, map := λ g g' α s, sum.rec (λ i, 𝟙 (f i)) α s }, map := λ f f' α, { app := λ g s, sum.rec α (λ j, 𝟙 (g j)) s, }} end end pi namespace functor variables {C} variables {D : I → Type u₁} [∀ i, category.{v₁} (D i)] /-- Assemble an `I`-indexed family of functors into a functor between the pi types. -/ @[simps] def pi (F : Π i, C i ⥤ D i) : (Π i, C i) ⥤ (Π i, D i) := { obj := λ f i, (F i).obj (f i), map := λ f g α i, (F i).map (α i) } -- One could add some natural isomorphisms showing -- how `functor.pi` commutes with `pi.eval` and `pi.comap`. end functor namespace nat_trans variables {C} variables {D : I → Type u₁} [∀ i, category.{v₁} (D i)] variables {F G : Π i, C i ⥤ D i} /-- Assemble an `I`-indexed family of natural transformations into a single natural transformation. -/ @[simps] def pi (α : Π i, F i ⟶ G i) : functor.pi F ⟶ functor.pi G := { app := λ f i, (α i).app (f i), } end nat_trans end category_theory
8a72bd0cf06f56bb07891d183184e13d7ca82c7b
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/measure_theory/lp_space.lean
fb453c38d20fab06345c3c142d808f6d2ddd15ff
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
31,905
lean
/- Copyright (c) 2020 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Rémy Degenne. -/ import measure_theory.ess_sup import measure_theory.l1_space import analysis.mean_inequalities /-! # ℒp space and Lp space This file describes properties of almost everywhere measurable functions with finite seminorm, denoted by `snorm f p μ` and defined for `p:ennreal` as `0` if `p=0`, `(∫ ∥f a∥^p ∂μ) ^ (1/p)` for `0 < p < ∞` and `ess_sup ∥f∥ μ` for `p=∞`. The Prop-valued `mem_ℒp f p μ` states that a function `f : α → E` has finite seminorm. The space `Lp α E p μ` is the subtype of elements of `α →ₘ[μ] E` (see ae_eq_fun) such that `snorm f p μ` is finite. For `1 ≤ p`, `snorm` defines a norm and Lp is a metric space. TODO: prove that Lp is complete. ## Main definitions * `snorm' f p μ` : `(∫ ∥f a∥^p ∂μ) ^ (1/p)` for `f : α → F` and `p : ℝ`, where `α` is a measurable space and `F` is a normed group. * `snorm_ess_sup f μ` : seminorm in `ℒ∞`, equal to the essential supremum `ess_sup ∥f∥ μ`. * `snorm f p μ` : for `p : ennreal`, seminorm in `ℒp`, equal to `0` for `p=0`, to `snorm' f p μ` for `0 < p < ∞` and to `snorm_ess_sup f μ` for `p = ∞`. * `mem_ℒp f p μ` : property that the function `f` is almost everywhere measurable and has finite p-seminorm for measure `μ` (`snorm f p μ < ∞`) * `Lp E p μ` : elements of `α →ₘ[μ] E` (see ae_eq_fun) such that `snorm f p μ` is finite. Defined as an `add_subgroup` of `α →ₘ[μ] E`. -/ noncomputable theory namespace measure_theory section ℒp variables {α E F : Type*} [measurable_space α] {μ : measure α} [measurable_space E] [normed_group E] [normed_group F] {p : ℝ} {q : ennreal} section ℒp_space_definition /-- `(∫ ∥f a∥^p ∂μ) ^ (1/p)`, which is a seminorm on the space of measurable functions for which this quantity is finite -/ def snorm' (f : α → F) (p : ℝ) (μ : measure α) : ennreal := (∫⁻ a, (nnnorm (f a))^p ∂μ) ^ (1/p) /-- seminorm for `ℒ∞`, equal to the essential supremum of `∥f∥`. -/ def snorm_ess_sup (f : α → F) (μ : measure α) := ess_sup (λ x, (nnnorm (f x) : ennreal)) μ /-- `ℒp` seminorm, equal to `0` for `p=0`, to `(∫ ∥f a∥^p ∂μ) ^ (1/p)` for `0 < p < ∞` and to `ess_sup ∥f∥ μ` for `p = ∞`. -/ def snorm (f : α → F) (q : ennreal) (μ : measure α) : ennreal := if q = 0 then 0 else (if q = ⊤ then snorm_ess_sup f μ else snorm' f (ennreal.to_real q) μ) lemma snorm_eq_snorm' (hq_ne_zero : q ≠ 0) (hq_ne_top : q ≠ ⊤) {f : α → F} : snorm f q μ = snorm' f (ennreal.to_real q) μ := by simp [snorm, hq_ne_zero, hq_ne_top] @[simp] lemma snorm_exponent_top {f : α → F} : snorm f ⊤ μ = snorm_ess_sup f μ := by simp [snorm] /-- The property that `f:α→E` is ae_measurable and `(∫ ∥f a∥^p ∂μ)^(1/p)` is finite -/ def mem_ℒp (f : α → E) (p : ennreal) (μ : measure α) : Prop := ae_measurable f μ ∧ snorm f p μ < ⊤ lemma lintegral_rpow_nnnorm_eq_rpow_snorm' {f : α → F} (hp0_lt : 0 < p) : ∫⁻ a, (nnnorm (f a)) ^ p ∂μ = (snorm' f p μ) ^ p := begin rw [snorm', ←ennreal.rpow_mul, one_div, inv_mul_cancel, ennreal.rpow_one], exact (ne_of_lt hp0_lt).symm, end end ℒp_space_definition lemma mem_ℒp_one_iff_integrable {f : α → E} : mem_ℒp f 1 μ ↔ integrable f μ := by simp_rw [integrable, has_finite_integral, mem_ℒp, snorm_eq_snorm' one_ne_zero ennreal.one_ne_top, ennreal.one_to_real, snorm', one_div_one, ennreal.rpow_one] section top lemma mem_ℒp.snorm_lt_top {f : α → E} (hfp : mem_ℒp f q μ) : snorm f q μ < ⊤ := hfp.2 lemma mem_ℒp.snorm_ne_top {f : α → E} (hfp : mem_ℒp f q μ) : snorm f q μ ≠ ⊤ := ne_of_lt (hfp.2) lemma lintegral_rpow_nnnorm_lt_top_of_snorm'_lt_top {f : α → F} (hp0_lt : 0 < p) (hfp : snorm' f p μ < ⊤) : ∫⁻ a, (nnnorm (f a)) ^ p ∂μ < ⊤ := begin rw lintegral_rpow_nnnorm_eq_rpow_snorm' hp0_lt, exact ennreal.rpow_lt_top_of_nonneg (le_of_lt hp0_lt) (ne_of_lt hfp), end end top section zero @[simp] lemma snorm'_exponent_zero {f : α → F} : snorm' f 0 μ = 1 := by rw [snorm', div_zero, ennreal.rpow_zero] @[simp] lemma snorm_exponent_zero {f : α → F} : snorm f 0 μ = 0 := by simp [snorm] lemma mem_ℒp_zero_iff_ae_measurable {f : α → E} : mem_ℒp f 0 μ ↔ ae_measurable f μ := by simp [mem_ℒp, snorm_exponent_zero] @[simp] lemma snorm'_zero (hp0_lt : 0 < p) : snorm' (0 : α → F) p μ = 0 := by simp [snorm', hp0_lt] @[simp] lemma snorm'_zero' (hp0_ne : p ≠ 0) (hμ : μ ≠ 0) : snorm' (0 : α → F) p μ = 0 := begin cases le_or_lt 0 p with hp0 hp_neg, { exact snorm'_zero (lt_of_le_of_ne hp0 hp0_ne.symm), }, { simp [snorm', ennreal.rpow_eq_zero_iff, hμ, hp_neg], }, end @[simp] lemma snorm_ess_sup_zero : snorm_ess_sup (0 : α → F) μ = 0 := begin simp_rw [snorm_ess_sup, pi.zero_apply, nnnorm_zero, ennreal.coe_zero, ←ennreal.bot_eq_zero], exact ess_sup_const_bot, end @[simp] lemma snorm_zero : snorm (0 : α → F) q μ = 0 := begin by_cases h0 : q = 0, { simp [h0], }, by_cases h_top : q = ⊤, { simp only [h_top, snorm_exponent_top, snorm_ess_sup_zero], }, rw ←ne.def at h0, simp [snorm_eq_snorm' h0 h_top, ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩], end lemma zero_mem_ℒp : mem_ℒp (0 : α → E) q μ := ⟨measurable_zero.ae_measurable, by { rw snorm_zero, exact ennreal.coe_lt_top, } ⟩ lemma snorm'_measure_zero_of_pos {f : α → F} (hp_pos : 0 < p) : snorm' f p 0 = 0 := by simp [snorm', hp_pos] lemma snorm'_measure_zero_of_exponent_zero {f : α → F} : snorm' f 0 0 = 1 := by simp [snorm'] lemma snorm'_measure_zero_of_neg {f : α → F} (hp_neg : p < 0) : snorm' f p 0 = ⊤ := by simp [snorm', hp_neg] @[simp] lemma snorm_ess_sup_measure_zero {f : α → F} : snorm_ess_sup f 0 = 0 := by simp [snorm_ess_sup] @[simp] lemma snorm_measure_zero {f : α → F} : snorm f q 0 = 0 := begin by_cases h0 : q = 0, { simp [h0], }, by_cases h_top : q = ⊤, { simp [h_top], }, rw ←ne.def at h0, simp [snorm_eq_snorm' h0 h_top, snorm', ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩], end end zero section const lemma snorm'_const (c : F) (hp_pos : 0 < p) : snorm' (λ x : α , c) p μ = (nnnorm c : ennreal) * (μ set.univ) ^ (1/p) := begin rw [snorm', lintegral_const, @ennreal.mul_rpow_of_nonneg _ _ (1/p) (by simp [le_of_lt hp_pos])], congr, rw ←ennreal.rpow_mul, suffices hp_cancel : p * (1/p) = 1, by rw [hp_cancel, ennreal.rpow_one], rw [one_div, mul_inv_cancel (ne_of_lt hp_pos).symm], end lemma snorm'_const' [finite_measure μ] (c : F) (hc_ne_zero : c ≠ 0) (hp_ne_zero : p ≠ 0) : snorm' (λ x : α , c) p μ = (nnnorm c : ennreal) * (μ set.univ) ^ (1/p) := begin rw [snorm', lintegral_const, ennreal.mul_rpow_of_ne_top _ (measure_ne_top μ set.univ)], { congr, rw ←ennreal.rpow_mul, suffices hp_cancel : p * (1/p) = 1, by rw [hp_cancel, ennreal.rpow_one], rw [one_div, mul_inv_cancel hp_ne_zero], }, { rw [ne.def, ennreal.rpow_eq_top_iff, auto.not_or_eq, auto.not_and_eq, auto.not_and_eq], split, { left, rwa [ennreal.coe_eq_zero, nnnorm_eq_zero], }, { exact or.inl ennreal.coe_ne_top, }, }, end lemma snorm_ess_sup_const (c : F) (hμ : μ ≠ 0) : snorm_ess_sup (λ x : α, c) μ = (nnnorm c : ennreal) := by rw [snorm_ess_sup, ess_sup_const _ hμ] lemma snorm'_const_of_probability_measure (c : F) (hp_pos : 0 < p) [probability_measure μ] : snorm' (λ x : α , c) p μ = (nnnorm c : ennreal) := by simp [snorm'_const c hp_pos, measure_univ] lemma snorm_const (c : F) (h0 : q ≠ 0) (hμ : μ ≠ 0) : snorm (λ x : α , c) q μ = (nnnorm c : ennreal) * (μ set.univ) ^ (1/(ennreal.to_real q)) := begin by_cases h_top : q = ⊤, { simp [h_top, snorm_ess_sup_const c hμ], }, simp [snorm_eq_snorm' h0 h_top, snorm'_const, ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩], end lemma snorm_const' (c : F) (h0 : q ≠ 0) (h_top: q ≠ ⊤) : snorm (λ x : α , c) q μ = (nnnorm c : ennreal) * (μ set.univ) ^ (1/(ennreal.to_real q)) := begin simp [snorm_eq_snorm' h0 h_top, snorm'_const, ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩], end lemma mem_ℒp_const (c : E) [finite_measure μ] : mem_ℒp (λ a:α, c) q μ := begin refine ⟨measurable_const.ae_measurable, _⟩, by_cases h0 : q = 0, { simp [h0], }, by_cases hμ : μ = 0, { simp [hμ], }, rw snorm_const c h0 hμ, refine ennreal.mul_lt_top ennreal.coe_lt_top _, refine ennreal.rpow_lt_top_of_nonneg _ (measure_ne_top μ set.univ), simp, end end const lemma snorm'_congr_ae {f g : α → F} (hfg : f =ᵐ[μ] g) : snorm' f p μ = snorm' g p μ := begin suffices h_no_pow : ∫⁻ a, (nnnorm (f a)) ^ p ∂μ = ∫⁻ a, (nnnorm (g a)) ^ p ∂μ, { simp_rw [snorm', h_no_pow], }, exact lintegral_congr_ae (hfg.mono (λ x hx, by simp [*])), end lemma snorm_ess_sup_congr_ae {f g : α → F} (hfg : f =ᵐ[μ] g) : snorm_ess_sup f μ = snorm_ess_sup g μ := ess_sup_congr_ae (hfg.mono (λ x hx, by rw hx)) lemma snorm_congr_ae {f g : α → F} (hfg : f =ᵐ[μ] g) : snorm f q μ = snorm g q μ := begin by_cases h0 : q = 0, { simp [h0], }, by_cases h_top : q = ⊤, { rw [h_top, snorm_exponent_top], exact snorm_ess_sup_congr_ae hfg, }, repeat { rw snorm_eq_snorm' h0 h_top, }, exact snorm'_congr_ae hfg, end lemma mem_ℒp.ae_eq {f g : α → E} (hfg : f =ᵐ[μ] g) (hf_Lp : mem_ℒp f q μ) : mem_ℒp g q μ := begin split, { cases hf_Lp.1 with f' hf', exact ⟨f', ⟨hf'.1, ae_eq_trans hfg.symm hf'.2⟩⟩, }, { rw snorm_congr_ae hfg.symm, exact hf_Lp.2, }, end lemma mem_ℒp_congr_ae {f g : α → E} (hfg : f =ᵐ[μ] g) : mem_ℒp f q μ ↔ mem_ℒp g q μ := ⟨λ h, h.ae_eq hfg, λ h, h.ae_eq hfg.symm⟩ section opens_measurable_space variable [opens_measurable_space E] lemma snorm'_eq_zero_of_ae_zero {f : α → F} (hp0_lt : 0 < p) (hf_zero : f =ᵐ[μ] 0) : snorm' f p μ = 0 := by rw [snorm'_congr_ae hf_zero, snorm'_zero hp0_lt] lemma snorm'_eq_zero_of_ae_zero' (hp0_ne : p ≠ 0) (hμ : μ ≠ 0) {f : α → F} (hf_zero : f =ᵐ[μ] 0) : snorm' f p μ = 0 := by rw [snorm'_congr_ae hf_zero, snorm'_zero' hp0_ne hμ] lemma ae_eq_zero_of_snorm'_eq_zero {f : α → E} (hp0 : 0 ≤ p) (hf : ae_measurable f μ) (h : snorm' f p μ = 0) : f =ᵐ[μ] 0 := begin rw [snorm', ennreal.rpow_eq_zero_iff] at h, cases h, { rw lintegral_eq_zero_iff' hf.nnnorm.ennreal_coe.ennreal_rpow_const at h, refine h.left.mono (λ x hx, _), rw [pi.zero_apply, ennreal.rpow_eq_zero_iff] at hx, cases hx, { cases hx with hx _, rwa [←ennreal.coe_zero, ennreal.coe_eq_coe, nnnorm_eq_zero] at hx, }, { exact absurd hx.left ennreal.coe_ne_top, }, }, { exfalso, rw [one_div, inv_lt_zero] at h, linarith, }, end lemma snorm'_eq_zero_iff (hp0_lt : 0 < p) {f : α → E} (hf : ae_measurable f μ) : snorm' f p μ = 0 ↔ f =ᵐ[μ] 0 := ⟨ae_eq_zero_of_snorm'_eq_zero (le_of_lt hp0_lt) hf, snorm'_eq_zero_of_ae_zero hp0_lt⟩ lemma coe_nnnorm_ae_le_snorm_ess_sup (f : α → F) (μ : measure α) : ∀ᵐ x ∂μ, (nnnorm (f x) : ennreal) ≤ snorm_ess_sup f μ := ennreal.ae_le_ess_sup (λ x, (nnnorm (f x) : ennreal)) lemma snorm_ess_sup_eq_zero_iff {f : α → F} : snorm_ess_sup f μ = 0 ↔ f =ᵐ[μ] 0 := begin rw [snorm_ess_sup, ennreal.ess_sup_eq_zero_iff], split; intro h; { refine h.mono (λ x hx, _), simp_rw pi.zero_apply at hx ⊢, simpa using hx, }, end lemma snorm_eq_zero_iff {f : α → E} (hf : ae_measurable f μ) (h0 : q ≠ 0) : snorm f q μ = 0 ↔ f =ᵐ[μ] 0 := begin by_cases h_top : q = ⊤, { rw [h_top, snorm_exponent_top, snorm_ess_sup_eq_zero_iff], }, rw snorm_eq_snorm' h0 h_top, exact snorm'_eq_zero_iff (ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩) hf, end end opens_measurable_space @[simp] lemma snorm'_neg {f : α → F} : snorm' (-f) p μ = snorm' f p μ := by simp [snorm'] @[simp] lemma snorm_neg {f : α → F} : snorm (-f) q μ = snorm f q μ := begin by_cases h0 : q = 0, { simp [h0], }, by_cases h_top : q = ⊤, { simp [h_top, snorm_ess_sup], }, simp [snorm_eq_snorm' h0 h_top], end section borel_space variable [borel_space E] lemma mem_ℒp.neg {f : α → E} (hf : mem_ℒp f q μ) : mem_ℒp (-f) q μ := ⟨ae_measurable.neg hf.1, by simp [hf.right]⟩ lemma snorm'_le_snorm'_mul_rpow_measure_univ {p q : ℝ} (hp0_lt : 0 < p) (hpq : p ≤ q) {f : α → E} (hf : ae_measurable f μ) : snorm' f p μ ≤ snorm' f q μ * (μ set.univ) ^ (1/p - 1/q) := begin have hq0_lt : 0 < q, from lt_of_lt_of_le hp0_lt hpq, by_cases hpq_eq : p = q, { rw [hpq_eq, sub_self, ennreal.rpow_zero, mul_one], exact le_refl _, }, have hpq : p < q, from lt_of_le_of_ne hpq hpq_eq, let g := λ a : α, (1 : ennreal), have h_rw : ∫⁻ a, ↑(nnnorm (f a))^p ∂ μ = ∫⁻ a, (nnnorm (f a) * (g a))^p ∂ μ, from lintegral_congr (λ a, by simp), repeat {rw snorm'}, rw h_rw, let r := p * q / (q - p), have hpqr : 1/p = 1/q + 1/r, { field_simp [(ne_of_lt hp0_lt).symm, (ne_of_lt hq0_lt).symm], ring, }, calc (∫⁻ (a : α), (↑(nnnorm (f a)) * g a) ^ p ∂μ) ^ (1/p) ≤ (∫⁻ (a : α), ↑(nnnorm (f a)) ^ q ∂μ) ^ (1/q) * (∫⁻ (a : α), (g a) ^ r ∂μ) ^ (1/r) : ennreal.lintegral_Lp_mul_le_Lq_mul_Lr hp0_lt hpq hpqr μ hf.nnnorm.ennreal_coe ae_measurable_const ... = (∫⁻ (a : α), ↑(nnnorm (f a)) ^ q ∂μ) ^ (1/q) * μ set.univ ^ (1/p - 1/q) : by simp [hpqr], end lemma snorm'_le_snorm_ess_sup_mul_rpow_measure_univ (hp_pos : 0 < p) {f : α → F} : snorm' f p μ ≤ snorm_ess_sup f μ * (μ set.univ) ^ (1/p) := begin have h_le : ∫⁻ (a : α), ↑(nnnorm (f a)) ^ p ∂μ ≤ ∫⁻ (a : α), (snorm_ess_sup f μ) ^ p ∂μ, { refine lintegral_mono_ae _, have h_nnnorm_le_snorm_ess_sup := coe_nnnorm_ae_le_snorm_ess_sup f μ, refine h_nnnorm_le_snorm_ess_sup.mono (λ x hx, ennreal.rpow_le_rpow hx (le_of_lt hp_pos)), }, rw [snorm', ←ennreal.rpow_one (snorm_ess_sup f μ)], nth_rewrite 1 ←mul_inv_cancel (ne_of_lt hp_pos).symm, rw [ennreal.rpow_mul, one_div, ←@ennreal.mul_rpow_of_nonneg _ _ p⁻¹ (by simp [le_of_lt hp_pos])], refine ennreal.rpow_le_rpow _ (by simp [le_of_lt hp_pos]), rwa lintegral_const at h_le, end lemma snorm'_le_snorm'_of_exponent_le {p q : ℝ} (hp0_lt : 0 < p) (hpq : p ≤ q) (μ : measure α) [probability_measure μ] {f : α → E} (hf : ae_measurable f μ) : snorm' f p μ ≤ snorm' f q μ := begin have h_le_μ := snorm'_le_snorm'_mul_rpow_measure_univ hp0_lt hpq hf, rwa [measure_univ, ennreal.one_rpow, mul_one] at h_le_μ, end lemma snorm'_le_snorm_ess_sup (hp_pos : 0 < p) {f : α → F} [probability_measure μ] : snorm' f p μ ≤ snorm_ess_sup f μ := le_trans (snorm'_le_snorm_ess_sup_mul_rpow_measure_univ hp_pos) (le_of_eq (by simp [measure_univ])) lemma snorm_le_snorm_of_exponent_le {p q : ennreal} (hpq : p ≤ q) [probability_measure μ] {f : α → E} (hf : ae_measurable f μ) : snorm f p μ ≤ snorm f q μ := begin by_cases hp0 : p = 0, { simp [hp0], }, rw ←ne.def at hp0, by_cases hq_top : q = ⊤, { by_cases hp_top : p = ⊤, { rw [hq_top, hp_top], exact le_refl _, }, { have hp_pos : 0 < p.to_real, from ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) hp0.symm, hp_top⟩, rw [snorm_eq_snorm' hp0 hp_top, hq_top, snorm_exponent_top], refine le_trans (snorm'_le_snorm_ess_sup_mul_rpow_measure_univ hp_pos) (le_of_eq _), simp [measure_univ], }, }, { have hp_top : p ≠ ⊤, { by_contra hp_eq_top, push_neg at hp_eq_top, refine hq_top _, rwa [hp_eq_top, top_le_iff] at hpq, }, have hp_pos : 0 < p.to_real, from ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) hp0.symm, hp_top⟩, have hq0 : q ≠ 0, { by_contra hq_eq_zero, push_neg at hq_eq_zero, have hp_eq_zero : p = 0, from le_antisymm (by rwa hq_eq_zero at hpq) (zero_le _), rw [hp_eq_zero, ennreal.zero_to_real] at hp_pos, exact (lt_irrefl _) hp_pos, }, have hpq_real : p.to_real ≤ q.to_real, by rwa ennreal.to_real_le_to_real hp_top hq_top, rw [snorm_eq_snorm' hp0 hp_top, snorm_eq_snorm' hq0 hq_top], exact snorm'_le_snorm'_of_exponent_le hp_pos hpq_real _ hf, }, end lemma snorm'_lt_top_of_snorm'_lt_top_of_exponent_le {p q : ℝ} [finite_measure μ] {f : α → E} (hf : ae_measurable f μ) (hfq_lt_top : snorm' f q μ < ⊤) (hp_nonneg : 0 ≤ p) (hpq : p ≤ q) : snorm' f p μ < ⊤ := begin cases le_or_lt p 0 with hp_nonpos hp_pos, { rw le_antisymm hp_nonpos hp_nonneg, simp, }, have hq_pos : 0 < q, from lt_of_lt_of_le hp_pos hpq, calc snorm' f p μ ≤ snorm' f q μ * (μ set.univ) ^ (1/p - 1/q) : snorm'_le_snorm'_mul_rpow_measure_univ hp_pos hpq hf ... < ⊤ : begin rw ennreal.mul_lt_top_iff, refine or.inl ⟨hfq_lt_top, ennreal.rpow_lt_top_of_nonneg _ (measure_ne_top μ set.univ)⟩, rwa [le_sub, sub_zero, one_div, one_div, inv_le_inv hq_pos hp_pos], end end lemma mem_ℒp.mem_ℒp_of_exponent_le {p q : ennreal} [finite_measure μ] {f : α → E} (hfq : mem_ℒp f q μ) (hpq : p ≤ q) : mem_ℒp f p μ := begin cases hfq with hfq_m hfq_lt_top, by_cases hp0 : p = 0, { rwa [hp0, mem_ℒp_zero_iff_ae_measurable], }, rw ←ne.def at hp0, refine ⟨hfq_m, _⟩, by_cases hp_top : p = ⊤, { have hq_top : q = ⊤, by rwa [hp_top, top_le_iff] at hpq, rw [hp_top], rwa hq_top at hfq_lt_top, }, have hp_pos : 0 < p.to_real, from ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) hp0.symm, hp_top⟩, by_cases hq_top : q = ⊤, { rw snorm_eq_snorm' hp0 hp_top, rw [hq_top, snorm_exponent_top] at hfq_lt_top, refine lt_of_le_of_lt (snorm'_le_snorm_ess_sup_mul_rpow_measure_univ hp_pos) _, refine ennreal.mul_lt_top hfq_lt_top _, exact ennreal.rpow_lt_top_of_nonneg (by simp [le_of_lt hp_pos]) (measure_ne_top μ set.univ), }, have hq0 : q ≠ 0, { by_contra hq_eq_zero, push_neg at hq_eq_zero, have hp_eq_zero : p = 0, from le_antisymm (by rwa hq_eq_zero at hpq) (zero_le _), rw [hp_eq_zero, ennreal.zero_to_real] at hp_pos, exact (lt_irrefl _) hp_pos, }, have hpq_real : p.to_real ≤ q.to_real, by rwa ennreal.to_real_le_to_real hp_top hq_top, rw snorm_eq_snorm' hp0 hp_top, rw snorm_eq_snorm' hq0 hq_top at hfq_lt_top, exact snorm'_lt_top_of_snorm'_lt_top_of_exponent_le hfq_m hfq_lt_top (le_of_lt hp_pos) hpq_real, end lemma mem_ℒp.integrable (hq1 : 1 ≤ q) {f : α → E} [finite_measure μ] (hfq : mem_ℒp f q μ) : integrable f μ := mem_ℒp_one_iff_integrable.mp (hfq.mem_ℒp_of_exponent_le hq1) lemma snorm'_add_le {f g : α → E} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hp1 : 1 ≤ p) : snorm' (f + g) p μ ≤ snorm' f p μ + snorm' g p μ := calc (∫⁻ a, ↑(nnnorm ((f + g) a)) ^ p ∂μ) ^ (1 / p) ≤ (∫⁻ a, (((λ a, (nnnorm (f a) : ennreal)) + (λ a, (nnnorm (g a) : ennreal))) a) ^ p ∂μ) ^ (1 / p) : begin refine @ennreal.rpow_le_rpow _ _ (1/p) _ (by simp [le_trans zero_le_one hp1]), refine lintegral_mono (λ a, ennreal.rpow_le_rpow _ (le_trans zero_le_one hp1)), simp [←ennreal.coe_add, nnnorm_add_le], end ... ≤ snorm' f p μ + snorm' g p μ : ennreal.lintegral_Lp_add_le hf.nnnorm.ennreal_coe hg.nnnorm.ennreal_coe hp1 lemma snorm_ess_sup_add_le {f g : α → F} : snorm_ess_sup (f + g) μ ≤ snorm_ess_sup f μ + snorm_ess_sup g μ := begin refine le_trans (ess_sup_mono_ae (filter.eventually_of_forall (λ x, _))) (ennreal.ess_sup_add_le _ _), simp_rw [pi.add_apply, ←ennreal.coe_add, ennreal.coe_le_coe], exact nnnorm_add_le _ _, end lemma snorm_add_le {f g : α → E} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hq1 : 1 ≤ q) : snorm (f + g) q μ ≤ snorm f q μ + snorm g q μ := begin by_cases hq0 : q = 0, { simp [hq0], }, by_cases hq_top : q = ⊤, { simp [hq_top, snorm_ess_sup_add_le], }, have hq1_real : 1 ≤ q.to_real, by rwa [←ennreal.one_to_real, ennreal.to_real_le_to_real ennreal.one_ne_top hq_top], repeat { rw snorm_eq_snorm' hq0 hq_top, }, exact snorm'_add_le hf hg hq1_real, end lemma snorm_add_lt_top_of_one_le {f g : α → E} (hf : mem_ℒp f q μ) (hg : mem_ℒp g q μ) (hq1 : 1 ≤ q) : snorm (f + g) q μ < ⊤ := lt_of_le_of_lt (snorm_add_le hf.1 hg.1 hq1) (ennreal.add_lt_top.mpr ⟨hf.2, hg.2⟩) lemma snorm'_add_lt_top_of_le_one {f g : α → E} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hf_snorm : snorm' f p μ < ⊤) (hg_snorm : snorm' g p μ < ⊤) (hp_pos : 0 < p) (hp1 : p ≤ 1) : snorm' (f + g) p μ < ⊤ := calc (∫⁻ a, ↑(nnnorm ((f + g) a)) ^ p ∂μ) ^ (1 / p) ≤ (∫⁻ a, (((λ a, (nnnorm (f a) : ennreal)) + (λ a, (nnnorm (g a) : ennreal))) a) ^ p ∂μ) ^ (1 / p) : begin refine @ennreal.rpow_le_rpow _ _ (1/p) _ (by simp [hp_pos.le]), refine lintegral_mono (λ a, ennreal.rpow_le_rpow _ hp_pos.le), simp [←ennreal.coe_add, nnnorm_add_le], end ... ≤ (∫⁻ a, (nnnorm (f a) : ennreal) ^ p + (nnnorm (g a) : ennreal) ^ p ∂μ) ^ (1 / p) : begin refine @ennreal.rpow_le_rpow _ _ (1/p) (lintegral_mono (λ a, _)) (by simp [hp_pos.le]), exact ennreal.rpow_add_le_add_rpow _ _ hp_pos hp1, end ... < ⊤ : begin refine @ennreal.rpow_lt_top_of_nonneg _ (1/p) (by simp [hp_pos.le]) _, rw [lintegral_add' hf.nnnorm.ennreal_coe.ennreal_rpow_const hg.nnnorm.ennreal_coe.ennreal_rpow_const, ennreal.add_ne_top, ←lt_top_iff_ne_top, ←lt_top_iff_ne_top], exact ⟨lintegral_rpow_nnnorm_lt_top_of_snorm'_lt_top hp_pos hf_snorm, lintegral_rpow_nnnorm_lt_top_of_snorm'_lt_top hp_pos hg_snorm⟩, end lemma snorm_add_lt_top {f g : α → E} (hf : mem_ℒp f q μ) (hg : mem_ℒp g q μ) : snorm (f + g) q μ < ⊤ := begin by_cases h0 : q = 0, { simp [h0], }, rw ←ne.def at h0, cases le_total 1 q with hq1 hq1, { exact snorm_add_lt_top_of_one_le hf hg hq1, }, have hq_top : q ≠ ⊤, from (lt_of_le_of_lt hq1 ennreal.coe_lt_top).ne, have hq_pos : 0 < q.to_real, { rw [←ennreal.zero_to_real, @ennreal.to_real_lt_to_real 0 q ennreal.coe_ne_top hq_top], exact ((zero_le q).lt_of_ne h0.symm), }, have hq1_real : q.to_real ≤ 1, { rwa [←ennreal.one_to_real, @ennreal.to_real_le_to_real q 1 hq_top ennreal.coe_ne_top], }, rw snorm_eq_snorm' h0 hq_top, rw [mem_ℒp, snorm_eq_snorm' h0 hq_top] at hf hg, exact snorm'_add_lt_top_of_le_one hf.1 hg.1 hf.2 hg.2 hq_pos hq1_real, end section second_countable_topology variable [topological_space.second_countable_topology E] lemma mem_ℒp.add {f g : α → E} (hf : mem_ℒp f q μ) (hg : mem_ℒp g q μ) : mem_ℒp (f + g) q μ := ⟨ae_measurable.add hf.1 hg.1, snorm_add_lt_top hf hg⟩ lemma mem_ℒp.sub {f g : α → E} (hf : mem_ℒp f q μ) (hg : mem_ℒp g q μ) : mem_ℒp (f - g) q μ := by { rw sub_eq_add_neg, exact hf.add hg.neg } end second_countable_topology end borel_space section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E] [normed_space 𝕜 F] lemma snorm'_const_smul {f : α → F} (c : 𝕜) (hp0_lt : 0 < p) : snorm' (c • f) p μ = (nnnorm c : ennreal) * snorm' f p μ := begin rw snorm', simp_rw [pi.smul_apply, nnnorm_smul, ennreal.coe_mul, ennreal.mul_rpow_of_nonneg _ _ (le_of_lt hp0_lt)], suffices h_integral : ∫⁻ a, ↑(nnnorm c) ^ p * ↑(nnnorm (f a)) ^ p ∂μ = (nnnorm c : ennreal)^p * ∫⁻ a, (nnnorm (f a)) ^ p ∂μ, { apply_fun (λ x, x ^ (1/p)) at h_integral, rw [h_integral, @ennreal.mul_rpow_of_nonneg _ _ (1/p) (by simp [le_of_lt hp0_lt])], congr, simp_rw [←ennreal.rpow_mul, one_div, mul_inv_cancel (ne_of_lt hp0_lt).symm, ennreal.rpow_one], }, rw lintegral_const_mul', rw ennreal.coe_rpow_of_nonneg _ (le_of_lt hp0_lt), exact ennreal.coe_ne_top, end lemma snorm_ess_sup_const_smul {f : α → F} (c : 𝕜) : snorm_ess_sup (c • f) μ = (nnnorm c : ennreal) * snorm_ess_sup f μ := by simp_rw [snorm_ess_sup, pi.smul_apply, nnnorm_smul, ennreal.coe_mul, ennreal.ess_sup_const_mul] lemma snorm_const_smul {f : α → F} (c : 𝕜) : snorm (c • f) q μ = (nnnorm c : ennreal) * snorm f q μ := begin by_cases h0 : q = 0, { simp [h0], }, by_cases h_top : q = ⊤, { simp [h_top, snorm_ess_sup_const_smul], }, repeat { rw snorm_eq_snorm' h0 h_top, }, rw ←ne.def at h0, exact snorm'_const_smul c (ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩), end lemma mem_ℒp.const_smul [borel_space E] {f : α → E} (hf : mem_ℒp f q μ) (c : 𝕜) : mem_ℒp (c • f) q μ := ⟨ae_measurable.const_smul hf.1 c, lt_of_le_of_lt (le_of_eq (snorm_const_smul c)) (ennreal.mul_lt_top ennreal.coe_lt_top hf.2)⟩ lemma snorm'_smul_le_mul_snorm' [opens_measurable_space E] [measurable_space 𝕜] [opens_measurable_space 𝕜] {q r : ℝ} {f : α → E} (hf : ae_measurable f μ) {φ : α → 𝕜} (hφ : ae_measurable φ μ) (hp0_lt : 0 < p) (hpq : p < q) (hpqr : 1/p = 1/q + 1/r) : snorm' (φ • f) p μ ≤ snorm' φ q μ * snorm' f r μ := begin simp_rw [snorm', pi.smul_apply', nnnorm_smul, ennreal.coe_mul], exact ennreal.lintegral_Lp_mul_le_Lq_mul_Lr hp0_lt hpq hpqr μ hφ.nnnorm.ennreal_coe hf.nnnorm.ennreal_coe, end end normed_space end ℒp /-! ### Lp space The space of equivalence classes of measurable functions for which `snorm f p μ < ⊤`. -/ @[simp] lemma snorm_ae_eq_fun {α E : Type*} [measurable_space α] {μ : measure α} [measurable_space E] [normed_group E] {p : ennreal} {f : α → E} (hf : ae_measurable f μ) : snorm (ae_eq_fun.mk f hf) p μ = snorm f p μ := snorm_congr_ae (ae_eq_fun.coe_fn_mk _ _) lemma mem_ℒp.snorm_mk_lt_top {α E : Type*} [measurable_space α] {μ : measure α} [measurable_space E] [normed_group E] {p : ennreal} {f : α → E} (hfp : mem_ℒp f p μ) : snorm (ae_eq_fun.mk f hfp.1) p μ < ⊤ := by simp [hfp.2] /-- Lp space -/ def Lp {α} (E : Type*) [measurable_space α] [measurable_space E] [normed_group E] [borel_space E] [topological_space.second_countable_topology E] (p : ennreal) (μ : measure α) : add_subgroup (α →ₘ[μ] E) := { carrier := {f | snorm f p μ < ⊤}, zero_mem' := by simp [snorm_congr_ae ae_eq_fun.coe_fn_zero, snorm_zero], add_mem' := λ f g hf hg, by simp [snorm_congr_ae (ae_eq_fun.coe_fn_add _ _), snorm_add_lt_top ⟨f.ae_measurable, hf⟩ ⟨g.ae_measurable, hg⟩], neg_mem' := λ f hf, by rwa [set.mem_set_of_eq, snorm_congr_ae (ae_eq_fun.coe_fn_neg _), snorm_neg] } /-- make an element of Lp from a function verifying `mem_ℒp` -/ def mem_ℒp.to_Lp {α E} [measurable_space α] [measurable_space E] [normed_group E] [borel_space E] [topological_space.second_countable_topology E] (f : α → E) {p : ennreal} {μ : measure α} (h_mem_ℒp : mem_ℒp f p μ) : Lp E p μ := ⟨ae_eq_fun.mk f h_mem_ℒp.1, h_mem_ℒp.snorm_mk_lt_top⟩ lemma mem_ℒp.coe_fn_to_Lp {α E} [measurable_space α] [measurable_space E] [normed_group E] [borel_space E] [topological_space.second_countable_topology E] {μ : measure α} {p : ennreal} {f : α → E} (hf : mem_ℒp f p μ) : hf.to_Lp f =ᵐ[μ] f := ae_eq_fun.coe_fn_mk _ _ namespace Lp variables {α E F : Type*} [measurable_space α] {μ : measure α} [measurable_space E] [normed_group E] [borel_space E] [topological_space.second_countable_topology E] {p : ennreal} lemma mem_Lp_iff_snorm_lt_top {f : α →ₘ[μ] E} : f ∈ Lp E p μ ↔ snorm f p μ < ⊤ := iff.refl _ lemma antimono [finite_measure μ] {p q : ennreal} (hpq : p ≤ q) : Lp E q μ ≤ Lp E p μ := λ f hf, (mem_ℒp.mem_ℒp_of_exponent_le ⟨f.ae_measurable, hf⟩ hpq).2 lemma coe_fn_mk {f : α →ₘ[μ] E} (hf : snorm f p μ < ⊤) : ⇑(⟨f, hf⟩ : Lp E p μ) =ᵐ[μ] f := by simp only [coe_fn_coe_base, subtype.coe_mk] lemma snorm_lt_top (f : Lp E p μ) : snorm f p μ < ⊤ := f.prop lemma snorm_ne_top (f : Lp E p μ) : snorm f p μ ≠ ⊤ := (snorm_lt_top f).ne lemma measurable (f : Lp E p μ) : measurable f := f.val.measurable lemma ae_measurable (f : Lp E p μ) : ae_measurable f μ := f.val.ae_measurable lemma mem_ℒp (f : Lp E p μ) : mem_ℒp f p μ := ⟨ae_measurable f, f.prop⟩ lemma coe_fn_zero : ⇑(0 : Lp E p μ) =ᵐ[μ] 0 := ae_eq_fun.coe_fn_zero lemma coe_fn_neg {f : Lp E p μ} : ⇑(-f) =ᵐ[μ] -f := ae_eq_fun.coe_fn_neg _ lemma coe_fn_add {f g : Lp E p μ} : ⇑(f + g) =ᵐ[μ] f + g := ae_eq_fun.coe_fn_add _ _ lemma coe_fn_sub {f g : Lp E p μ} : ⇑(f - g) =ᵐ[μ] f - g := ae_eq_fun.coe_fn_sub _ _ lemma mem_Lp_const (α) [measurable_space α] (μ : measure α) (c : E) [finite_measure μ] : @ae_eq_fun.const α _ _ μ _ c ∈ Lp E p μ := (mem_ℒp_const c).snorm_mk_lt_top instance : has_norm (Lp E p μ) := { norm := λ f, ennreal.to_real (snorm f p μ) } lemma norm_def (f : Lp E p μ) : ∥f∥ = ennreal.to_real (snorm f p μ) := rfl @[simp] lemma norm_zero : ∥(0 : Lp E p μ)∥ = 0 := by simp [norm, snorm_congr_ae ae_eq_fun.coe_fn_zero, snorm_zero] lemma norm_eq_zero_iff {f : Lp E p μ} (hp : 0 < p) : ∥f∥ = 0 ↔ f = 0 := begin refine ⟨λ hf, _, λ hf, by simp [hf]⟩, rw [norm_def, ennreal.to_real_eq_zero_iff] at hf, cases hf, { rw snorm_eq_zero_iff (ae_measurable f) hp.ne.symm at hf, exact subtype.eq (ae_eq_fun.ext (hf.trans ae_eq_fun.coe_fn_zero.symm)), }, { exact absurd hf (snorm_ne_top f), }, end @[simp] lemma norm_neg {f : Lp E p μ} : ∥-f∥ = ∥f∥ := by rw [norm_def, norm_def, snorm_congr_ae coe_fn_neg, snorm_neg] instance [hp : fact (1 ≤ p)] : normed_group (Lp E p μ) := normed_group.of_core _ { norm_eq_zero_iff := λ f, norm_eq_zero_iff (ennreal.zero_lt_one.trans_le hp), triangle := begin assume f g, simp only [norm_def], rw ← ennreal.to_real_add (snorm_ne_top f) (snorm_ne_top g), suffices h_snorm : snorm ⇑(f + g) p μ ≤ snorm ⇑f p μ + snorm ⇑g p μ, { rwa ennreal.to_real_le_to_real (snorm_ne_top (f + g)), exact ennreal.add_ne_top.mpr ⟨snorm_ne_top f, snorm_ne_top g⟩, }, rw [snorm_congr_ae coe_fn_add], exact snorm_add_le (ae_measurable f) (ae_measurable g) hp, end, norm_neg := by simp } section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E] lemma mem_Lp_const_smul (c : 𝕜) (f : Lp E p μ) : c • ↑f ∈ Lp E p μ := begin rw [mem_Lp_iff_snorm_lt_top, snorm_congr_ae (ae_eq_fun.coe_fn_smul _ _), snorm_const_smul, ennreal.mul_lt_top_iff], exact or.inl ⟨ennreal.coe_lt_top, f.prop⟩, end instance : has_scalar 𝕜 (Lp E p μ) := { smul := λ c f, ⟨c • ↑f, mem_Lp_const_smul c f⟩ } lemma coe_fn_smul {f : Lp E p μ} {c : 𝕜} : ⇑(c • f) =ᵐ[μ] c • f := ae_eq_fun.coe_fn_smul _ _ instance : semimodule 𝕜 (Lp E p μ) := { one_smul := λ _, subtype.eq (one_smul 𝕜 _), mul_smul := λ _ _ _, subtype.eq (mul_smul _ _ _), smul_add := λ _ _ _, subtype.eq (smul_add _ _ _), smul_zero := λ _, subtype.eq (smul_zero _), add_smul := λ _ _ _, subtype.eq (add_smul _ _ _), zero_smul := λ _, subtype.eq (zero_smul _ _) } lemma norm_const_smul (c : 𝕜) (f : Lp E p μ) : ∥c • f∥ = ∥c∥ * ∥f∥ := by rw [norm_def, snorm_congr_ae coe_fn_smul, snorm_const_smul c, ennreal.to_real_mul, ennreal.coe_to_real, coe_nnnorm, norm_def] instance [fact (1 ≤ p)] : normed_space 𝕜 (Lp E p μ) := { norm_smul_le := λ _ _, by simp [norm_const_smul] } end normed_space end Lp end measure_theory
7cc292853aa56d38b095bc07d570d09e13974098
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/socket_server.lean
14ca12d25d21563b8a6cb40e0c5e38db31c79c3c
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
1,430
lean
import system.io def SECRET : string := "SECRET_DATA" meta def start_client : io io.proc.child := do test_dir ← io.env.get "TEST_DIR", (bin_dir, test_dir) ← return $ match test_dir with | some s := (s ++ "/../../../", s ++ "/") | none := ("", "tests/lean/run/") end, io.proc.spawn { cmd := bin_dir ++ "bin/lean", args := ["--run", test_dir ++ "socket_client.lean", "client"] } meta def init : io unit := io.fs.remove "hello.unix" <|> return () meta def start_server : io (option io.net.socket) := do io.run_tactic $ tactic.trace "listen", some <$> io.net.listen "hello.unix" SECRET.length -- Some versions of windows don't support UNIX sockets, -- so just roll with it <|> return none meta def do_server (sock : io.net.socket) : io unit := do io.run_tactic $ tactic.trace "accept", sock ← io.net.accept sock, io.run_tactic $ tactic.trace "send", io.net.send sock SECRET.to_char_buffer, io.run_tactic $ tactic.trace "bye" meta def go : io unit := do init, sock ← start_server, match sock with | none := return () | some sock := do io.run_tactic $ tactic.trace "startup", c ← start_client, do_server sock, n ← io.proc.wait c, io.net.close sock, init, match n with | 0 := return () | n := io.fail sformat!"exit code {n}!" end end run_cmd (tactic.unsafe_run_io go)
118b042862fdd0af0765683a0d1bd6f2d2032c34
d7189ea2ef694124821b033e533f18905b5e87ef
/galois/crypto/sha2.lean
7aa232adb66bde76235aeb6d73b7a0964976ac69
[ "Apache-2.0" ]
permissive
digama0/lean-protocol-support
eaa7e6f8b8e0d5bbfff1f7f52bfb79a3b11b0f59
cabfa3abedbdd6fdca6e2da6fbbf91a13ed48dda
refs/heads/master
1,625,421,450,627
1,506,035,462,000
1,506,035,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,037
lean
import galois.bitvec.join import galois.bitvec.rotate namespace crypto section pair_list open list definition pair_list_aux {α β : Type} (z : α) (f : α → α → β) : option α → list α → list β | none [] := [] | (some x) [] := [f x z] | none (x :: l) := pair_list_aux (some x) l | (some x) (a :: l) := f x a :: pair_list_aux none l definition pair_list {α β : Type} (z : α) (f : α → α → β) : list α → list β := pair_list_aux z f none end pair_list section common parameter (n : ℕ) parameters (s0 s1 : bitvec n → bitvec n) parameters (S0 S1 : bitvec n → bitvec n) parameters (cuberoots : list (bitvec n)) /- 8n-bit hash, made up of eight n-bit words -/ inductive hash : Type | mk : bitvec n → bitvec n → bitvec n → bitvec n → bitvec n → bitvec n → bitvec n → bitvec n → hash /- element-wise addition of two hash values -/ definition hash_add : hash → hash → hash | (hash.mk x0 x1 x2 x3 x4 x5 x6 x7) (hash.mk y0 y1 y2 y3 y4 y5 y6 y7) := hash.mk (bitvec.add x0 y0) (bitvec.add x1 y1) (bitvec.add x2 y2) (bitvec.add x3 y3) (bitvec.add x4 y4) (bitvec.add x5 y5) (bitvec.add x6 y6) (bitvec.add x7 y7) local notation `[` l:(foldr `, ` (h t, vector.cons h t) vector.nil `]`) := l /- concatenate the elements of a hash value into a single bitvector -/ definition bitvec_of_hash : hash → bitvec (n * 8) | (hash.mk x0 x1 x2 x3 x4 x5 x6 x7) := bitvec.join ([x0,x1,x2,x3,x4,x5,x6,x7] : vector (bitvec n) 8) /- 16*n-bit chunk, made up of sixteen n-bit words -/ inductive chunk : Type | mk : bitvec n → bitvec n → bitvec n → bitvec n → bitvec n → bitvec n → bitvec n → bitvec n → bitvec n → bitvec n → bitvec n → bitvec n → bitvec n → bitvec n → bitvec n → bitvec n → chunk definition chunk_hd : chunk → bitvec n | (chunk.mk w0 w1 w2 w3 w4 w5 w6 w7 w8 w9 w10 w11 w12 w13 w14 w15) := w0 /- a single iteration of the expansion function -/ definition expand1 : chunk → chunk | (chunk.mk w0 w1 w2 w3 w4 w5 w6 w7 w8 w9 w10 w11 w12 w13 w14 w15) := let w16 := bitvec.add (bitvec.add (bitvec.add w0 (s0 w1)) w9) (s1 w14) in chunk.mk w1 w2 w3 w4 w5 w6 w7 w8 w9 w10 w11 w12 w13 w14 w15 w16 open list /- expand a chunk into a message schedule -/ definition expand : list (bitvec n) → chunk → list (bitvec n) | list.nil c := list.nil | (k :: l) c := list.cons (bitvec.add (chunk_hd c) k) (expand l (expand1 c)) /- a single round of the compression function -/ definition compress1 : bitvec n → hash → hash | kw (hash.mk a b c d e f g h) := let ch := bitvec.xor (bitvec.and e f) (bitvec.and (bitvec.not e) g), temp1 := bitvec.add (bitvec.add (bitvec.add h (S1 e)) ch) kw, maj := bitvec.xor (bitvec.xor (bitvec.and a b) (bitvec.and a c)) (bitvec.and b c), temp2 := bitvec.add (S0 a) maj in hash.mk (bitvec.add temp1 temp2) a b c (bitvec.add d temp1) e f g /- hash a single expanded chunk -/ definition hash1 : hash → list (bitvec n) → hash | h nil := h | h (cons k l) := hash1 (compress1 k h) l /- expand and hash a list of chunks -/ definition hash_chunks : hash → list chunk → hash | h nil := h | h (cons c l) := hash_chunks (hash_add h (hash1 h (expand cuberoots c))) l /- type abbreviation -/ definition pair : Type := bitvec n × bitvec n inductive chunk_part : Type | mk0 {} : chunk_part | mk1 : pair → chunk_part | mk2 : pair → pair → chunk_part | mk3 : pair → pair → pair → chunk_part | mk4 : pair → pair → pair → pair → chunk_part | mk5 : pair → pair → pair → pair → pair → chunk_part | mk6 : pair → pair → pair → pair → pair → pair → chunk_part | mk7 : pair → pair → pair → pair → pair → pair → pair → chunk_part definition pairs_to_chunk : pair → pair → pair → pair → pair → pair → pair → pair → chunk | (prod.mk a b) (prod.mk c d) (prod.mk e f) (prod.mk g h) (prod.mk i j) (prod.mk k l) (prod.mk m n) (prod.mk o p) := chunk.mk a b c d e f g h i j k l m n o p definition z : pair := prod.mk 0 0 /- first parameter is the 64-bit size to put at the end -/ definition pairs_to_chunks_aux : pair → chunk_part → list pair → list chunk | s (chunk_part.mk0) nil := pairs_to_chunk z z z z z z z s :: nil | s (chunk_part.mk1 a) nil := pairs_to_chunk a z z z z z z s :: nil | s (chunk_part.mk2 a b) nil := pairs_to_chunk a b z z z z z s :: nil | s (chunk_part.mk3 a b c) nil := pairs_to_chunk a b c z z z z s :: nil | s (chunk_part.mk4 a b c d) nil := pairs_to_chunk a b c d z z z s :: nil | s (chunk_part.mk5 a b c d e) nil := pairs_to_chunk a b c d e z z s :: nil | s (chunk_part.mk6 a b c d e f) nil := pairs_to_chunk a b c d e f z s :: nil | s (chunk_part.mk7 a b c d e f g) nil := pairs_to_chunk a b c d e f g s :: nil | s chunk_part.mk0 (cons a l) := pairs_to_chunks_aux s (chunk_part.mk1 a) l | s (chunk_part.mk1 a) (cons b l) := pairs_to_chunks_aux s (chunk_part.mk2 a b) l | s (chunk_part.mk2 a b) (cons c l) := pairs_to_chunks_aux s (chunk_part.mk3 a b c) l | s (chunk_part.mk3 a b c) (cons d l) := pairs_to_chunks_aux s (chunk_part.mk4 a b c d) l | s (chunk_part.mk4 a b c d) (cons e l) := pairs_to_chunks_aux s (chunk_part.mk5 a b c d e) l | s (chunk_part.mk5 a b c d e) (cons f l) := pairs_to_chunks_aux s (chunk_part.mk6 a b c d e f) l | s (chunk_part.mk6 a b c d e f) (cons g l) := pairs_to_chunks_aux s (chunk_part.mk7 a b c d e f g) l | s (chunk_part.mk7 a b c d e f g) (cons h l) := pairs_to_chunk a b c d e f g h :: pairs_to_chunks_aux s chunk_part.mk0 l definition pairs_to_chunks : pair → list pair → list chunk | s := pairs_to_chunks_aux s chunk_part.mk0 definition words_to_chunks : bitvec n → bitvec n → list (bitvec n) → list chunk | hi lo data := pairs_to_chunks (prod.mk hi lo) (pair_list 0 prod.mk data) end common namespace sha256 /- first 32 bits of the fractional parts of the cube roots of the first 64 primes -/ definition cuberoots : list (bitvec 32) := [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2] definition hash0 : hash 32 := hash.mk 0x6a09e667 0xbb67ae85 0x3c6ef372 0xa54ff53a 0x510e527f 0x9b05688c 0x1f83d9ab 0x5be0cd19 definition s0 : bitvec 32 → bitvec 32 | x := bitvec.xor (bitvec.xor (bitvec.ror x 7) (bitvec.ror x 18)) (bitvec.ushr x 3) definition s1 : bitvec 32 → bitvec 32 | x := bitvec.xor (bitvec.xor (bitvec.ror x 17) (bitvec.ror x 19)) (bitvec.ushr x 10) definition S0 : bitvec 32 → bitvec 32 | x := bitvec.xor (bitvec.xor (bitvec.ror x 2) (bitvec.ror x 13)) (bitvec.ror x 22) definition S1 : bitvec 32 → bitvec 32 | x := bitvec.xor (bitvec.xor (bitvec.ror x 6) (bitvec.ror x 11)) (bitvec.ror x 25) definition hash_chunks_32 := hash_chunks 32 s0 s1 S0 S1 cuberoots definition bytes_to_words : list (bitvec 8) → list (bitvec 32) | l := pair_list 0 bitvec.append (pair_list 0 bitvec.append l) definition preprocess (msg : list (bitvec 8)) : list (chunk 32) := let len : bitvec 64 := list.foldl (λ n a, bitvec.add n 8) 0 msg, hi : bitvec 32 := vector.drop 32 (bitvec.ushr len 32), lo : bitvec 32 := vector.drop 32 len in words_to_chunks 32 hi lo (bytes_to_words (msg ++ [0x80])) definition sha256 (msg : list (bitvec 8)) : bitvec 256 := bitvec_of_hash 32 (hash_chunks_32 hash0 (preprocess msg)) end sha256 namespace sha224 /- The second 32 bits of the fractional parts of the square roots of the 9th through 16th primes 23..53 -/ definition hash0 : hash 32 := hash.mk 0xc1059ed8 0x367cd507 0x3070dd17 0xf70e5939 0xffc00b31 0x68581511 0x64f98fa7 0xbefa4fa4 definition sha224 (msg : list (bitvec 8)) : bitvec 224 := vector.drop 32 (bitvec.ushr (bitvec_of_hash 32 (sha256.hash_chunks_32 hash0 (sha256.preprocess msg))) 32) /- should use "vector.firstn 224" but it fails to infer the less-than-or-equal constraint -/ end sha224 namespace sha512 /- first 64 bits of the fractional parts of the cube roots of the first 80 primes -/ definition cuberoots : list (bitvec 64) := [0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc, 0x3956c25bf348b538, 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118, 0xd807aa98a3030242, 0x12835b0145706fbe, 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2, 0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235, 0xc19bf174cf692694, 0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65, 0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5, 0x983e5152ee66dfab, 0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4, 0xc6e00bf33da88fc2, 0xd5a79147930aa725, 0x06ca6351e003826f, 0x142929670a0e6e70, 0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, 0x53380d139d95b3df, 0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b, 0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30, 0xd192e819d6ef5218, 0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8, 0x19a4c116b8d2d0c8, 0x1e376c085141ab53, 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8, 0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373, 0x682e6ff3d6b2b8a3, 0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec, 0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b, 0xca273eceea26619c, 0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178, 0x06f067aa72176fba, 0x0a637dc5a2c898a6, 0x113f9804bef90dae, 0x1b710b35131c471b, 0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc, 0x431d67c49c100d4c, 0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817] definition hash0 : hash 64 := hash.mk 0x6a09e667f3bcc908 0xbb67ae8584caa73b 0x3c6ef372fe94f82b 0xa54ff53a5f1d36f1 0x510e527fade682d1 0x9b05688c2b3e6c1f 0x1f83d9abfb41bd6b 0x5be0cd19137e2179 definition s0 : bitvec 64 → bitvec 64 | x := bitvec.xor (bitvec.xor (bitvec.ror x 1) (bitvec.ror x 8)) (bitvec.ushr x 7) definition s1 : bitvec 64 → bitvec 64 | x := bitvec.xor (bitvec.xor (bitvec.ror x 19) (bitvec.ror x 61)) (bitvec.ushr x 6) definition S0 : bitvec 64 → bitvec 64 | x := bitvec.xor (bitvec.xor (bitvec.ror x 28) (bitvec.ror x 34)) (bitvec.ror x 39) definition S1 : bitvec 64 → bitvec 64 | x := bitvec.xor (bitvec.xor (bitvec.ror x 14) (bitvec.ror x 18)) (bitvec.ror x 41) definition hash_chunks_64 := hash_chunks 64 s0 s1 S0 S1 cuberoots definition bytes_to_words : list (bitvec 8) → list (bitvec 64) | l := pair_list 0 bitvec.append (pair_list 0 bitvec.append (pair_list 0 bitvec.append l)) definition preprocess (msg : list (bitvec 8)) : list (chunk 64) := let len : bitvec 128 := list.foldl (λ n a, bitvec.add n 8) 0 msg, hi : bitvec 64 := vector.drop 64 (bitvec.ushr len 64), lo : bitvec 64 := vector.drop 64 len in words_to_chunks 64 hi lo (bytes_to_words (msg ++ [0x80])) definition sha512 (msg : list (bitvec 8)) : bitvec 512 := bitvec_of_hash 64 (hash_chunks_64 hash0 (preprocess msg)) end sha512 namespace sha384 definition hash0 : hash 64 := hash.mk 0xcbbb9d5dc1059ed8 0x629a292a367cd507 0x9159015a3070dd17 0x152fecd8f70e5939 0x67332667ffc00b31 0x8eb44a8768581511 0xdb0c2e0d64f98fa7 0x47b5481dbefa4fa4 definition sha384 (msg : list (bitvec 8)) : bitvec 384 := vector.drop 128 (bitvec.ushr (bitvec_of_hash 64 (sha512.hash_chunks_64 hash0 (sha512.preprocess msg))) 128) /- should use "vector.firstn 384" but it fails to infer the less-than-or-equal constraint -/ end sha384 namespace sha512_224 definition hash0 : hash 64 := hash.mk 0x8c3d37c819544da2 0x73e1996689dcd4d6 0x1dfab7ae32ff9c82 0x679dd514582f9fcf 0x0f6d2b697bd44da8 0x77e36f7304c48942 0x3f9d85a86a1d36c8 0x1112e6ad91d692a1 definition sha512_224 (msg : list (bitvec 8)) : bitvec 224 := vector.drop 288 (bitvec.ushr (bitvec_of_hash 64 (sha512.hash_chunks_64 hash0 (sha512.preprocess msg))) 288) /- should use "vector.firstn 288" but it fails to infer the less-than-or-equal constraint -/ end sha512_224 namespace sha512_256 definition hash0 : hash 64 := hash.mk 0x22312194fc2bf72c 0x9f555fa3c84c64c2 0x2393b86b6f53b151 0x963877195940eabd 0x96283ee2a88effe3 0xbe5e1e2553863992 0x2b0199fc2c85b8aa 0x0eb72ddc81c52ca2 definition sha512_256 (msg : list (bitvec 8)) : bitvec 256 := vector.take 256 (bitvec_of_hash 64 (sha512.hash_chunks_64 hash0 (sha512.preprocess msg))) end sha512_256 definition sha224 : list (bitvec 8) → bitvec 224 := sha224.sha224 definition sha256 : list (bitvec 8) → bitvec 256 := sha256.sha256 definition sha384 : list (bitvec 8) → bitvec 384 := sha384.sha384 definition sha512 : list (bitvec 8) → bitvec 512 := sha512.sha512 definition sha512_224 : list (bitvec 8) → bitvec 224 := sha512_224.sha512_224 definition sha512_256 : list (bitvec 8) → bitvec 256 := sha512_256.sha512_256 end crypto
c64503f946b0a884909396905a416c4b5a1a93cc
3618c6e11aa822fd542440674dfb9a7b9921dba0
/src/HNN_normalize.lean
f83587bf14788260e68ed5a4bd335a216c34422d
[]
no_license
ChrisHughes24/single_relation
99ceedcc02d236ce46d6c65d72caa669857533c5
057e157a59de6d0e43b50fcb537d66792ec20450
refs/heads/master
1,683,652,062,698
1,683,360,089,000
1,683,360,089,000
279,346,432
0
0
null
null
null
null
UTF-8
Lean
false
false
14,418
lean
import initial import P import data.list.min_max /-! # HNN normalization for the group_thingy tactic This file implements the HNN normalization process and proof certificate generation for the `group_thingy` tactic. ## Main definitions This file contains the definition `HNN_normalize`, which is the only definition in this file used outside of this file. ## Implementation notes Both `HNN_normalize_core` and `reduce_mul` use an ad-hoc implementation of the binary coproduct of `P (free_group (ι × C∞))` and `C∞` as a `list (P (free_group (ι × C∞)) × C∞)`. The representation is in reverse, i.e. the list `[(p, a), (q, b)]` represents the word `b * q * a * p` in the coproduct. The word returned will be reduced in the sense that the only occurence of `1` will be either `prod.fst` of the first element of the list, or `prod.snd` of the final element. -/ variables {ι : Type} [decidable_eq ι] (r : free_group ι) (T : set ι) [decidable_pred T] open free_group P semidirect_product multiplicative /-- `mul_subscript` is the action of `C∞` on `free_group (ι × C∞)`. `mul_subscript n (of (i, m)) = of (i, n * m)` -/ def mul_subscript : C∞ →* free_group (ι × C∞) ≃* free_group (ι × C∞) := { to_fun := λ n, free_group.equiv (equiv.prod_congr (equiv.refl _) (equiv.mul_left n)), map_one' := mul_equiv.to_monoid_hom_injective (free_group.hom_ext (by simp)), map_mul' := λ _ _, mul_equiv.to_monoid_hom_injective (free_group.hom_ext (by simp [mul_assoc])) } /-- `remove_subscript t (of (i, n)) = (of t)^n * of i * (of t)^(-n)` -/ def remove_subscript (t : ι) : free_group (ι × C∞) →* free_group ι := free_group.lift' (λ g, (mul_aut.conj (of' t g.2)).to_monoid_hom.comp (of' g.1)) /-- `add_subscript t` is a one sided inverse to `semidirect_product.inl ∘ remove_subscript t` -/ def add_subscript (t : ι) : free_group ι →* free_group (ι × C∞) ⋊[mul_subscript] C∞ := free_group.lift' (λ j, if t = j then semidirect_product.inr else semidirect_product.inl.comp (of' (j, 1))) /-- `max_subscript x w`, returns the largest `k` such that the letter `(x, k)` appears in `w`, or `none` if there is no such occurence -/ @[inline] def max_subscript (x : ι) (w : free_group (ι × C∞)) : option C∞ := (w.to_list.filter_map (λ i : Σ i : ι × C∞, C∞, if i.1.1 = x then some i.1.2 else none)).maximum /-- `min_subscript x w`, returns the smallext `k` such that the letter `(x, k)` appears in `w`, or `none` if there is no such occurence -/ @[inline] def min_subscript (x : ι) (w : free_group (ι × C∞)) : option C∞ := (w.to_list.filter_map (λ i : Σ i : ι × C∞, C∞, if i.1.1 = x then some i.1.2 else none)).minimum -- /-- `Icc_prod x a b` is the set of pairs `(i, n)` such that if -- `i = x` then `a ≤ n ≤ b` -/ -- def Icc_prod (x : ι) (a b : C∞) : set (ι × C∞) := -- { p | p.1 = x → a ≤ p.2 ∧ p.2 ≤ b } -- instance (x : ι) (a b : C∞) : decidable_pred (Icc_prod x a b) := -- by dunfold Icc_prod; apply_instance /-- If `p` is a certificate that `a` and `b` are equal, then `remove_subscript t (conj_P t k p)`, will return a certificate that `t^k * remove_subscript t a * t^(-k)` is congruent to `t^k * remove_subscript t b * t^(-k)` -/ def conj_P (t : ι) (k : C∞) (p : P (free_group (ι × C∞))) : P (free_group (ι × C∞)) := ⟨mul_free (of' (t, 1) k) p.left, mul_subscript k p.right⟩ /-- `reduce_mul (p, n) l`, returns `l * n * p` if `l`is thought of as an element of the binary coproduct of `P (free_group (ι × C∞))` and `C∞`. -/ def reduce_mul : P (free_group (ι × C∞)) × C∞ → list (P (free_group (ι × C∞)) × C∞) → list (P (free_group (ι × C∞)) × C∞) | p [] := [p] | (p, n) ((q, m)::l) := if n = 1 then (q * p, m) :: l else (p, n) :: (q, m) :: l -- /-- `reduce_mul (p, n) l`, returns `l * n * p` if `l`is thought -- of as an element of the binary coproduct of `P (free_group (ι × C∞))` and `C∞`. -/ -- def reduce_mul' : C∞ × P (free_group (ι × C∞)) × C∞ → -- list (C∞ × P (free_group (ι × C∞))) → -- list (C∞ × P (free_group (ι × C∞))) -- | (m, p, n) [] := -- if m = 1 -- then [(n, p)] -- else [(n, p), (m, 1)] -- | (m, p, n) ((k, q)::l) := -- if m * k = 1 -- then (n, q * p) :: l -- else (n, p) ::(m * k, q) :: l /-- `HNN_normalize_core` returns a normalized word in the `HNN` extension. It is returned as a `list (P (free_group (ι × C∞)) × C∞)` which can be thought of as an element of the binary conproduct of `P (free_group (ι × C∞))` and `C∞`. The representation is in reverse, i.e. the list `[(p, a), (q, b)]` represents the word `b * q * a * p` in the coproduct. The word returned will be reduced in the sense that the only occurence of `1` will be either `prod.fst` of the first element of the list, or `prod.snd` of the final element. The function takes an already HNN normalized word `l₁` in the coproduct as a `list (P (free_group (ι × C∞)) × C∞)`, and an unnormalized word `l₂` in `free_group ι`, as a `list (Σ i : ι, C∞)`. The function effectively returns the product `l₁ * l₂` as an HNN normalized word in the coproduct. -/ @[inline] meta def HNN_normalize_core (t x : ι) (r' : free_group (ι × C∞)) (a b : C∞) (hs : Π (r : free_group (ι × C∞)) (T : set (ι × C∞)) [decidable_pred T], solver r T) : list (P (free_group (ι × C∞)) × C∞) → list (Σ i : ι, C∞) → list (P (free_group (ι × C∞)) × C∞) | p [] := p | [] (i::l) := if i.1 = t then HNN_normalize_core [(1, i.2)] l else HNN_normalize_core [(inr (of_list [⟨(i.1, 1), i.2⟩]), 1)] l | ((p, n) :: l₁) (i::l₂) := if i.1 = t then if 1 ≤ i.2 then match hs r' {s | s ≠ (x, a)} p.right with | none := HNN_normalize_core ((1, i.2) :: (p, n) :: l₁) l₂ | some q := -- k is the minimum amount I can subtract from the subscripts -- and stay between a and b let k : C∞ := match min_subscript x q.right with | some m := if n < 1 then max (max (i.2⁻¹) (a * m⁻¹)) n else max (i.2⁻¹) (a * m⁻¹) | none := if n < 1 then max i.2⁻¹ n else i.2⁻¹ end in HNN_normalize_core (reduce_mul ((conj_P t k (P.trans p q)), n * k⁻¹) l₁) --BUG when |k| > |n| (let m := i.2 * k in if m = 1 then l₂ else ⟨t, m⟩ :: l₂) end else match hs r' {s | s ≠ (x, b)} p.right with | none := HNN_normalize_core ((1, i.2) :: (p, n) :: l₁) l₂ | some q := -- k is the maximum amount I can subtract from the subscripts -- and stay between a and b let k : C∞ := match max_subscript x q.right with | some m := if 1 < n then min (min (i.2⁻¹) (b * m⁻¹)) n else min (i.2⁻¹) (b * m⁻¹) | none := if 1 < n then max i.2⁻¹ n else i.2⁻¹ end in HNN_normalize_core (reduce_mul ((conj_P t k (P.trans p q)), n * k⁻¹) l₁) (let m := i.2 * k in if m = 1 then l₂ else ⟨t, m⟩ :: l₂) end else HNN_normalize_core ((⟨p.left, p.right * of' (i.1, 1) i.2⟩, n) :: l₁) l₂ meta def HNN_normalize'_single_pos (t x : ι) (r' : free_group (ι × C∞)) (a b : C∞) (hs : Π (r : free_group (ι × C∞)) (T : set (ι × C∞)) [decidable_pred T], solver r T) : C∞ × P (free_group (ι × C∞)) → option (C∞ × P (free_group (ι × C∞))) | (n, p) := match hs r' {s | s ≠ (x, b)} p.right with | none := none | some q := -- k is the maximum amount I can subtract from the subscripts -- and stay between a and b let k : C∞ := match max_subscript x q.right with | some m := min n (b * m⁻¹) | none := n end in let m := n * k⁻¹ in some (m, conj_P t k (p.trans q)) end -- meta def HNN_normalize'_single' (t x : ι) (r' : free_group (ι × C∞)) (a b : C∞) -- (hs : Π (r : free_group (ι × C∞)) (T : set (ι × C∞)) [decidable_pred T], solver r T) : -- P (free_group (ι × C∞)) × C∞ → option (list (P (free_group (ι × C∞)) × C∞)) -- | (p, n) := -- if 1 ≤ n -- then HNN_normalize'_single_pos' t x r' a b hs n p -- else HNN_normalize'_single_neg' t x r' a b hs n p meta def HNN_normalize'_single_neg (t x : ι) (r' : free_group (ι × C∞)) (a b : C∞) (hs : Π (r : free_group (ι × C∞)) (T : set (ι × C∞)) [decidable_pred T], solver r T) : C∞ × P (free_group (ι × C∞)) → option (C∞ × P (free_group (ι × C∞))) | (n, p) := match hs r' {s | s ≠ (x, a)} p.right with | none := none | some q := -- k is the minimum amount I can subtract from the subscripts -- and stay between a and b let k : C∞ := match min_subscript x q.right with | some m := max n (a * m⁻¹) | none := n end in let m := n * k⁻¹ in some (m, conj_P t k (p.trans q)) end meta def HNN_normalize'_single (t x : ι) (r' : free_group (ι × C∞)) (a b : C∞) (hs : Π (r : free_group (ι × C∞)) (T : set (ι × C∞)) [decidable_pred T], solver r T) : C∞ × P (free_group (ι × C∞)) → option (C∞ × P (free_group (ι × C∞))) | (n, p) := if 1 ≤ n then HNN_normalize'_single_pos t x r' a b hs (n, p) else HNN_normalize'_single_neg t x r' a b hs (n, p) -- meta def HNN_normalize'_single (t x : ι) (r' : free_group (ι × C∞)) (a b : C∞) -- (hs : Π (r : free_group (ι × C∞)) (T : set (ι × C∞)) [decidable_pred T], solver r T) : -- C∞ × P (free_group (ι × C∞)) → C∞ × P (free_group (ι × C∞)) -- | (n, p) := -- if 1 ≤ n -- then HNN_normalize'_single_pos t x r' a b hs (n, p) -- else HNN_normalize'_single_neg t x r' a b hs (n, p) -- meta def HNN_normalize'_cons (t x : ι) (r' : free_group (ι × C∞)) (a b : C∞) -- (hs : Π (r : free_group (ι × C∞)) (T : set (ι × C∞)) [decidable_pred T], solver r T) : -- list (C∞ × P (free_group (ι × C∞))) → -- C∞ × P (free_group (ι × C∞)) → -- list (C∞ × P (free_group (ι × C∞))) -- | [] (n, p) := -- let (n', p') := HNN_normalize'_single t x r' a b hs (n, p) in -- if n' = 1 -- then [(n, p')] -- else [(n * n'⁻¹, p'), (n', 1)] -- | ((m, q)::l) (n, p) := -- let (n', p') := HNN_normalize'_single t x r' a b hs (n, p) in -- if n' * m = 1 -- then HNN_normalize'_cons l (n', q * p') -- else (1, p') :: (n' * m, q) :: l -- def reduce_mul''' : list (P (free_group (ι × C∞)) × C∞) → list (P (free_group (ι × C∞)) × C∞) -- → list (P (free_group (ι × C∞)) × C∞) -- | [] l₂ := l₂ -- | l₁ [] := l₁.reverse -- | ((p, n)::l₁) ((q, m)::l₂) := -- if n = 1 -- then l₁.reverse_core ((q * p, m) :: l₂) -- else l₁.reverse_core ((p, n) :: (q, m) :: l₂) -- @[inline] meta def HNN_normalize'_core -- (t x : ι) (r' : free_group (ι × C∞)) (a b : C∞) -- (hs : Π (r : free_group (ι × C∞)) (T : set (ι × C∞)) [decidable_pred T], solver r T) : -- list (P (free_group (ι × C∞)) × C∞) → --reversed and normalized -- list (P (free_group (ι × C∞)) × C∞) → -- not reversed or normalized -- list (P (free_group (ι × C∞)) × C∞) -- reversed and normalized -- | l [] := l -- | l₁ ((p, n) :: l₂) := -- match HNN_normalize'_single' t x r' a b hs (p, n) with -- | none := HNN_normalize'_core (reduce_mul (p, n) l₁) l₂ -- | some l := HNN_normalize'_core l₁ (reduce_mul''' l l₂) --not quite right if `l` has a one at the end -- end @[inline] meta def HNN_normalize'_core (t x : ι) (r' : free_group (ι × C∞)) (a b : C∞) (hs : Π (r : free_group (ι × C∞)) (T : set (ι × C∞)) [decidable_pred T], solver r T) : list (C∞ × P (free_group (ι × C∞))) → P (free_group (ι × C∞)) → C∞ → list (Σ i : ι, C∞) → list (C∞ × P (free_group (ι × C∞))) | [] q m [] := [(m, q)] | [] q m (i::l₂) := if i.1 = t then HNN_normalize'_core [] q (m * i.2) l₂ else if m = 1 then HNN_normalize'_core [] (q * inr (of_list [⟨(i.1, 1), i.2⟩])) 1 l₂ else HNN_normalize'_core [(m, q)] (inr (of_list [⟨(i.1, 1), i.2⟩])) 1 l₂ | ((n, p)::l₁) q m [] := match HNN_normalize'_single t x r' a b hs (n, q) with | none := (m, q)::(n, p)::l₁ | some (n', q') := if n' = 1 then HNN_normalize'_core l₁ (p * q') (n * m) [] else HNN_normalize'_core ((n', p)::l₁) q' (n * n'⁻¹ * m) [] end | ((n, p)::l₁) q m (i::l₂) := if m = 1 then if i.1 = t then HNN_normalize'_core ((n, p)::l₁) q i.2 l₂ else HNN_normalize'_core ((n, p)::l₁) (q * inr (of_list [⟨(i.1, 1), i.2⟩])) 1 l₂ else match HNN_normalize'_single t x r' a b hs (n, q) with | none := HNN_normalize'_core ((m, q)::(n,p)::l₁) 1 1 (i::l₂) | some (n', q') := if n' = 1 then HNN_normalize'_core l₁ (p * q') (n * m) (i::l₂) else HNN_normalize'_core ((n', p)::l₁) q' (n * n'⁻¹ * m) (i::l₂) end @[inline] meta def HNN_normalize' (t x : ι) (r' : free_group (ι × C∞)) (a b : C∞) (hs : Π (r : free_group (ι × C∞)) (T : set (ι × C∞)) [decidable_pred T], solver r T) (w : free_group ι) : option (C∞ × P (free_group (ι × C∞))) := match HNN_normalize'_core t x r' a b hs [] 1 1 w.to_list with | [] := some 1 | [(n, p)] := some (n, p) | (a::b::l) := none end /-- Given a word `w` in `free_group ι`, `HNN_normalize` checks whether it can be written in the form `t^n * g`, with `g` a `t`-free word in the HNN extension. If it cannot be written in this form `HNN_normalize` returns `none`, if it can then `HNN_normalize` returns this pair, along with a proof. More precisely, it returns a pair `(p, n)` where `p` is a certificate that `t^(-n) * w` is equal to a `t`-free term. -/ @[inline] meta def HNN_normalize (t x : ι) (r' : free_group (ι × C∞)) (a b : C∞) (hs : Π (r : free_group (ι × C∞)) (T : set (ι × C∞)) [decidable_pred T], solver r T) (w : free_group ι) : option (P (free_group (ι × C∞)) × C∞) := match HNN_normalize_core t x r' a b hs [] w.to_list with | [] := some 1 | [a] := some a | (a::b::l) := none end
64f4c34e482ef2ba834b622525532d1687422efd
50b3917f95cf9fe84639812ea0461b38f8f0dbe1
/canonical_isomorphism/equiv_question.lean
df7664d045dd77c2ddea303a3b8e04df85a95447
[]
no_license
roro47/xena
6389bcd7dcf395656a2c85cfc90a4366e9b825bb
237910190de38d6ff43694ffe3a9b68f79363e6c
refs/heads/master
1,598,570,061,948
1,570,052,567,000
1,570,052,567,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
778
lean
import data.equiv universes u v y z def αu (X Y : Type u) := X → Y def αuv (X : Type u) (Y : Type v) := X → Y def αv (X Y : Type v) := X → Y definition u_v {X : Type z} {Y : Type z} : equiv (αu X Y) (αv X Y) := { to_fun := λ f,f, inv_fun := λ f,f, left_inv := λ x,rfl, right_inv := λ x,rfl, } definition u_uv {X : Type z} {Y : Type z} : equiv (αu X Y) (αuv X Y) := { to_fun := λ f,f, inv_fun := λ f,f, left_inv := λ x,rfl, right_inv := λ x,rfl, } definition u_uv' {X : Type*} {Y : Type*} : equiv (αu X Y) (αuv X Y) := { to_fun := λ f,f, inv_fun := λ f,f, left_inv := λ x,rfl, right_inv := λ x,rfl, } definition u_uv'' {X : Type u} {Y : Type v} : equiv.{max u v} (αu (ulift X) (ulift Y)) (αuv X Y) := sorry #print ulift
286b13269462d3c2287c1c2f0ce00fdff90f8374
9dc8cecdf3c4634764a18254e94d43da07142918
/src/logic/equiv/local_equiv.lean
ffdc7f1f2075fbc88ea4f513182e71930c682e04
[ "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
35,625
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import data.set.function import logic.equiv.basic /-! # Local equivalences This files defines equivalences between subsets of given types. An element `e` of `local_equiv α β` is made of two maps `e.to_fun` and `e.inv_fun` respectively from α to β and from β to α (just like equivs), which are inverse to each other on the subsets `e.source` and `e.target` of respectively α and β. They are designed in particular to define charts on manifolds. The main functionality is `e.trans f`, which composes the two local equivalences by restricting the source and target to the maximal set where the composition makes sense. As for equivs, we register a coercion to functions and use it in our simp normal form: we write `e x` and `e.symm y` instead of `e.to_fun x` and `e.inv_fun y`. ## Main definitions `equiv.to_local_equiv`: associating a local equiv to an equiv, with source = target = univ `local_equiv.symm` : the inverse of a local equiv `local_equiv.trans` : the composition of two local equivs `local_equiv.refl` : the identity local equiv `local_equiv.of_set` : the identity on a set `s` `eq_on_source` : equivalence relation describing the "right" notion of equality for local equivs (see below in implementation notes) ## Implementation notes There are at least three possible implementations of local equivalences: * equivs on subtypes * pairs of functions taking values in `option α` and `option β`, equal to none where the local equivalence is not defined * pairs of functions defined everywhere, keeping the source and target as additional data Each of these implementations has pros and cons. * When dealing with subtypes, one still need to define additional API for composition and restriction of domains. Checking that one always belongs to the right subtype makes things very tedious, and leads quickly to DTT hell (as the subtype `u ∩ v` is not the "same" as `v ∩ u`, for instance). * With option-valued functions, the composition is very neat (it is just the usual composition, and the domain is restricted automatically). These are implemented in `pequiv.lean`. For manifolds, where one wants to discuss thoroughly the smoothness of the maps, this creates however a lot of overhead as one would need to extend all classes of smoothness to option-valued maps. * The local_equiv version as explained above is easier to use for manifolds. The drawback is that there is extra useless data (the values of `to_fun` and `inv_fun` outside of `source` and `target`). In particular, the equality notion between local equivs is not "the right one", i.e., coinciding source and target and equality there. Moreover, there are no local equivs in this sense between an empty type and a nonempty type. Since empty types are not that useful, and since one almost never needs to talk about equal local equivs, this is not an issue in practice. Still, we introduce an equivalence relation `eq_on_source` that captures this right notion of equality, and show that many properties are invariant under this equivalence relation. ### Local coding conventions If a lemma deals with the intersection of a set with either source or target of a `local_equiv`, then it should use `e.source ∩ s` or `e.target ∩ t`, not `s ∩ e.source` or `t ∩ e.target`. -/ mk_simp_attribute mfld_simps "The simpset `mfld_simps` records several simp lemmas that are especially useful in manifolds. It is a subset of the whole set of simp lemmas, but it makes it possible to have quicker proofs (when used with `squeeze_simp` or `simp only`) while retaining readability. The typical use case is the following, in a file on manifolds: If `simp [foo, bar]` is slow, replace it with `squeeze_simp [foo, bar] with mfld_simps` and paste its output. The list of lemmas should be reasonable (contrary to the output of `squeeze_simp [foo, bar]` which might contain tens of lemmas), and the outcome should be quick enough. " -- register in the simpset `mfld_simps` several lemmas that are often useful when dealing -- with manifolds attribute [mfld_simps] id.def function.comp.left_id set.mem_set_of_eq set.image_eq_empty set.univ_inter set.preimage_univ set.prod_mk_mem_set_prod_eq and_true set.mem_univ set.mem_image_of_mem true_and set.mem_inter_eq set.mem_preimage function.comp_app set.inter_subset_left set.mem_prod set.range_id set.range_prod_map and_self set.mem_range_self eq_self_iff_true forall_const forall_true_iff set.inter_univ set.preimage_id function.comp.right_id not_false_iff and_imp set.prod_inter_prod set.univ_prod_univ true_or or_true prod.map_mk set.preimage_inter heq_iff_eq equiv.sigma_equiv_prod_apply equiv.sigma_equiv_prod_symm_apply subtype.coe_mk equiv.to_fun_as_coe equiv.inv_fun_as_coe /-- Common `@[simps]` configuration options used for manifold-related declarations. -/ def mfld_cfg : simps_cfg := {attrs := [`simp, `mfld_simps], fully_applied := ff} namespace tactic.interactive /-- A very basic tactic to show that sets showing up in manifolds coincide or are included in one another. -/ meta def mfld_set_tac : tactic unit := do goal ← tactic.target, match goal with | `(%%e₁ = %%e₂) := `[ext my_y, split; { assume h_my_y, try { simp only [*, -h_my_y] with mfld_simps at h_my_y }, simp only [*] with mfld_simps }] | `(%%e₁ ⊆ %%e₂) := `[assume my_y h_my_y, try { simp only [*, -h_my_y] with mfld_simps at h_my_y }, simp only [*] with mfld_simps] | _ := tactic.fail "goal should be an equality or an inclusion" end end tactic.interactive open function set variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} /-- Local equivalence between subsets `source` and `target` of α and β respectively. The (global) maps `to_fun : α → β` and `inv_fun : β → α` map `source` to `target` and conversely, and are inverse to each other there. The values of `to_fun` outside of `source` and of `inv_fun` outside of `target` are irrelevant. -/ structure local_equiv (α : Type*) (β : Type*) := (to_fun : α → β) (inv_fun : β → α) (source : set α) (target : set β) (map_source' : ∀ {{x}}, x ∈ source → to_fun x ∈ target) (map_target' : ∀ {{x}}, x ∈ target → inv_fun x ∈ source) (left_inv' : ∀ {{x}}, x ∈ source → inv_fun (to_fun x) = x) (right_inv' : ∀ {{x}}, x ∈ target → to_fun (inv_fun x) = x) namespace local_equiv variables (e : local_equiv α β) (e' : local_equiv β γ) instance [inhabited α] [inhabited β] : inhabited (local_equiv α β) := ⟨⟨const α default, const β default, ∅, ∅, maps_to_empty _ _, maps_to_empty _ _, eq_on_empty _ _, eq_on_empty _ _⟩⟩ /-- The inverse of a local equiv -/ protected def symm : local_equiv β α := { to_fun := e.inv_fun, inv_fun := e.to_fun, source := e.target, target := e.source, map_source' := e.map_target', map_target' := e.map_source', left_inv' := e.right_inv', right_inv' := e.left_inv' } instance : has_coe_to_fun (local_equiv α β) (λ _, α → β) := ⟨local_equiv.to_fun⟩ /-- See Note [custom simps projection] -/ def simps.symm_apply (e : local_equiv α β) : β → α := e.symm initialize_simps_projections local_equiv (to_fun → apply, inv_fun → symm_apply) @[simp, mfld_simps] theorem coe_mk (f : α → β) (g s t ml mr il ir) : (local_equiv.mk f g s t ml mr il ir : α → β) = f := rfl @[simp, mfld_simps] theorem coe_symm_mk (f : α → β) (g s t ml mr il ir) : ((local_equiv.mk f g s t ml mr il ir).symm : β → α) = g := rfl @[simp, mfld_simps] lemma to_fun_as_coe : e.to_fun = e := rfl @[simp, mfld_simps] lemma inv_fun_as_coe : e.inv_fun = e.symm := rfl @[simp, mfld_simps] lemma map_source {x : α} (h : x ∈ e.source) : e x ∈ e.target := e.map_source' h @[simp, mfld_simps] lemma map_target {x : β} (h : x ∈ e.target) : e.symm x ∈ e.source := e.map_target' h @[simp, mfld_simps] lemma left_inv {x : α} (h : x ∈ e.source) : e.symm (e x) = x := e.left_inv' h @[simp, mfld_simps] lemma right_inv {x : β} (h : x ∈ e.target) : e (e.symm x) = x := e.right_inv' h lemma eq_symm_apply {x : α} {y : β} (hx : x ∈ e.source) (hy : y ∈ e.target) : x = e.symm y ↔ e x = y := ⟨λ h, by rw [← e.right_inv hy, h], λ h, by rw [← e.left_inv hx, h]⟩ protected lemma maps_to : maps_to e e.source e.target := λ x, e.map_source lemma symm_maps_to : maps_to e.symm e.target e.source := e.symm.maps_to protected lemma left_inv_on : left_inv_on e.symm e e.source := λ x, e.left_inv protected lemma right_inv_on : right_inv_on e.symm e e.target := λ x, e.right_inv protected lemma inv_on : inv_on e.symm e e.source e.target := ⟨e.left_inv_on, e.right_inv_on⟩ protected lemma inj_on : inj_on e e.source := e.left_inv_on.inj_on protected lemma bij_on : bij_on e e.source e.target := e.inv_on.bij_on e.maps_to e.symm_maps_to protected lemma surj_on : surj_on e e.source e.target := e.bij_on.surj_on /-- Associating a local_equiv to an equiv-/ @[simps (mfld_cfg)] def _root_.equiv.to_local_equiv (e : α ≃ β) : local_equiv α β := { to_fun := e, inv_fun := e.symm, source := univ, target := univ, map_source' := λx hx, mem_univ _, map_target' := λy hy, mem_univ _, left_inv' := λx hx, e.left_inv x, right_inv' := λx hx, e.right_inv x } instance inhabited_of_empty [is_empty α] [is_empty β] : inhabited (local_equiv α β) := ⟨((equiv.equiv_empty α).trans (equiv.equiv_empty β).symm).to_local_equiv⟩ /-- Create a copy of a `local_equiv` providing better definitional equalities. -/ @[simps {fully_applied := ff}] def copy (e : local_equiv α β) (f : α → β) (hf : ⇑e = f) (g : β → α) (hg : ⇑e.symm = g) (s : set α) (hs : e.source = s) (t : set β) (ht : e.target = t) : local_equiv α β := { to_fun := f, inv_fun := g, source := s, target := t, map_source' := λ x, ht ▸ hs ▸ hf ▸ e.map_source, map_target' := λ y, hs ▸ ht ▸ hg ▸ e.map_target, left_inv' := λ x, hs ▸ hf ▸ hg ▸ e.left_inv, right_inv' := λ x, ht ▸ hf ▸ hg ▸ e.right_inv } lemma copy_eq_self (e : local_equiv α β) (f : α → β) (hf : ⇑e = f) (g : β → α) (hg : ⇑e.symm = g) (s : set α) (hs : e.source = s) (t : set β) (ht : e.target = t) : e.copy f hf g hg s hs t ht = e := by { substs f g s t, cases e, refl } /-- Associating to a local_equiv an equiv between the source and the target -/ protected def to_equiv : equiv (e.source) (e.target) := { to_fun := λ x, ⟨e x, e.map_source x.mem⟩, inv_fun := λ y, ⟨e.symm y, e.map_target y.mem⟩, left_inv := λ⟨x, hx⟩, subtype.eq $ e.left_inv hx, right_inv := λ⟨y, hy⟩, subtype.eq $ e.right_inv hy } @[simp, mfld_simps] lemma symm_source : e.symm.source = e.target := rfl @[simp, mfld_simps] lemma symm_target : e.symm.target = e.source := rfl @[simp, mfld_simps] lemma symm_symm : e.symm.symm = e := by { cases e, refl } lemma image_source_eq_target : e '' e.source = e.target := e.bij_on.image_eq lemma forall_mem_target {p : β → Prop} : (∀ y ∈ e.target, p y) ↔ ∀ x ∈ e.source, p (e x) := by rw [← image_source_eq_target, ball_image_iff] lemma exists_mem_target {p : β → Prop} : (∃ y ∈ e.target, p y) ↔ ∃ x ∈ e.source, p (e x) := by rw [← image_source_eq_target, bex_image_iff] /-- We say that `t : set β` is an image of `s : set α` under a local equivalence if any of the following equivalent conditions hold: * `e '' (e.source ∩ s) = e.target ∩ t`; * `e.source ∩ e ⁻¹ t = e.source ∩ s`; * `∀ x ∈ e.source, e x ∈ t ↔ x ∈ s` (this one is used in the definition). -/ def is_image (s : set α) (t : set β) : Prop := ∀ ⦃x⦄, x ∈ e.source → (e x ∈ t ↔ x ∈ s) namespace is_image variables {e} {s : set α} {t : set β} {x : α} {y : β} lemma apply_mem_iff (h : e.is_image s t) (hx : x ∈ e.source) : e x ∈ t ↔ x ∈ s := h hx lemma symm_apply_mem_iff (h : e.is_image s t) : ∀ ⦃y⦄, y ∈ e.target → (e.symm y ∈ s ↔ y ∈ t) := e.forall_mem_target.mpr $ λ x hx, by rw [e.left_inv hx, h hx] protected lemma symm (h : e.is_image s t) : e.symm.is_image t s := h.symm_apply_mem_iff @[simp] lemma symm_iff : e.symm.is_image t s ↔ e.is_image s t := ⟨λ h, h.symm, λ h, h.symm⟩ protected lemma maps_to (h : e.is_image s t) : maps_to e (e.source ∩ s) (e.target ∩ t) := λ x hx, ⟨e.maps_to hx.1, (h hx.1).2 hx.2⟩ lemma symm_maps_to (h : e.is_image s t) : maps_to e.symm (e.target ∩ t) (e.source ∩ s) := h.symm.maps_to /-- Restrict a `local_equiv` to a pair of corresponding sets. -/ @[simps {fully_applied := ff}] def restr (h : e.is_image s t) : local_equiv α β := { to_fun := e, inv_fun := e.symm, source := e.source ∩ s, target := e.target ∩ t, map_source' := h.maps_to, map_target' := h.symm_maps_to, left_inv' := e.left_inv_on.mono (inter_subset_left _ _), right_inv' := e.right_inv_on.mono (inter_subset_left _ _) } lemma image_eq (h : e.is_image s t) : e '' (e.source ∩ s) = e.target ∩ t := h.restr.image_source_eq_target lemma symm_image_eq (h : e.is_image s t) : e.symm '' (e.target ∩ t) = e.source ∩ s := h.symm.image_eq lemma iff_preimage_eq : e.is_image s t ↔ e.source ∩ e ⁻¹' t = e.source ∩ s := by simp only [is_image, set.ext_iff, mem_inter_eq, and.congr_right_iff, mem_preimage] alias iff_preimage_eq ↔ preimage_eq of_preimage_eq lemma iff_symm_preimage_eq : e.is_image s t ↔ e.target ∩ e.symm ⁻¹' s = e.target ∩ t := symm_iff.symm.trans iff_preimage_eq alias iff_symm_preimage_eq ↔ symm_preimage_eq of_symm_preimage_eq lemma of_image_eq (h : e '' (e.source ∩ s) = e.target ∩ t) : e.is_image s t := of_symm_preimage_eq $ eq.trans (of_symm_preimage_eq rfl).image_eq.symm h lemma of_symm_image_eq (h : e.symm '' (e.target ∩ t) = e.source ∩ s) : e.is_image s t := of_preimage_eq $ eq.trans (of_preimage_eq rfl).symm_image_eq.symm h protected lemma compl (h : e.is_image s t) : e.is_image sᶜ tᶜ := λ x hx, not_congr (h hx) protected lemma inter {s' t'} (h : e.is_image s t) (h' : e.is_image s' t') : e.is_image (s ∩ s') (t ∩ t') := λ x hx, and_congr (h hx) (h' hx) protected lemma union {s' t'} (h : e.is_image s t) (h' : e.is_image s' t') : e.is_image (s ∪ s') (t ∪ t') := λ x hx, or_congr (h hx) (h' hx) protected lemma diff {s' t'} (h : e.is_image s t) (h' : e.is_image s' t') : e.is_image (s \ s') (t \ t') := h.inter h'.compl lemma left_inv_on_piecewise {e' : local_equiv α β} [∀ i, decidable (i ∈ s)] [∀ i, decidable (i ∈ t)] (h : e.is_image s t) (h' : e'.is_image s t) : left_inv_on (t.piecewise e.symm e'.symm) (s.piecewise e e') (s.ite e.source e'.source) := begin rintro x (⟨he, hs⟩|⟨he, hs : x ∉ s⟩), { rw [piecewise_eq_of_mem _ _ _ hs, piecewise_eq_of_mem _ _ _ ((h he).2 hs), e.left_inv he], }, { rw [piecewise_eq_of_not_mem _ _ _ hs, piecewise_eq_of_not_mem _ _ _ ((h'.compl he).2 hs), e'.left_inv he] } end lemma inter_eq_of_inter_eq_of_eq_on {e' : local_equiv α β} (h : e.is_image s t) (h' : e'.is_image s t) (hs : e.source ∩ s = e'.source ∩ s) (Heq : eq_on e e' (e.source ∩ s)) : e.target ∩ t = e'.target ∩ t := by rw [← h.image_eq, ← h'.image_eq, ← hs, Heq.image_eq] lemma symm_eq_on_of_inter_eq_of_eq_on {e' : local_equiv α β} (h : e.is_image s t) (hs : e.source ∩ s = e'.source ∩ s) (Heq : eq_on e e' (e.source ∩ s)) : eq_on e.symm e'.symm (e.target ∩ t) := begin rw [← h.image_eq], rintros y ⟨x, hx, rfl⟩, have hx' := hx, rw hs at hx', rw [e.left_inv hx.1, Heq hx, e'.left_inv hx'.1] end end is_image lemma is_image_source_target : e.is_image e.source e.target := λ x hx, by simp [hx] lemma is_image_source_target_of_disjoint (e' : local_equiv α β) (hs : disjoint e.source e'.source) (ht : disjoint e.target e'.target) : e.is_image e'.source e'.target := is_image.of_image_eq $ by rw [hs.inter_eq, ht.inter_eq, image_empty] lemma image_source_inter_eq' (s : set α) : e '' (e.source ∩ s) = e.target ∩ e.symm ⁻¹' s := by rw [inter_comm, e.left_inv_on.image_inter', image_source_eq_target, inter_comm] lemma image_source_inter_eq (s : set α) : e '' (e.source ∩ s) = e.target ∩ e.symm ⁻¹' (e.source ∩ s) := by rw [inter_comm, e.left_inv_on.image_inter, image_source_eq_target, inter_comm] lemma image_eq_target_inter_inv_preimage {s : set α} (h : s ⊆ e.source) : e '' s = e.target ∩ e.symm ⁻¹' s := by rw [← e.image_source_inter_eq', inter_eq_self_of_subset_right h] lemma symm_image_eq_source_inter_preimage {s : set β} (h : s ⊆ e.target) : e.symm '' s = e.source ∩ e ⁻¹' s := e.symm.image_eq_target_inter_inv_preimage h lemma symm_image_target_inter_eq (s : set β) : e.symm '' (e.target ∩ s) = e.source ∩ e ⁻¹' (e.target ∩ s) := e.symm.image_source_inter_eq _ lemma symm_image_target_inter_eq' (s : set β) : e.symm '' (e.target ∩ s) = e.source ∩ e ⁻¹' s := e.symm.image_source_inter_eq' _ lemma source_inter_preimage_inv_preimage (s : set α) : e.source ∩ e ⁻¹' (e.symm ⁻¹' s) = e.source ∩ s := set.ext $ λ x, and.congr_right_iff.2 $ λ hx, by simp only [mem_preimage, e.left_inv hx] lemma source_inter_preimage_target_inter (s : set β) : e.source ∩ (e ⁻¹' (e.target ∩ s)) = e.source ∩ (e ⁻¹' s) := ext $ λ x, ⟨λ hx, ⟨hx.1, hx.2.2⟩, λ hx, ⟨hx.1, e.map_source hx.1, hx.2⟩⟩ lemma target_inter_inv_preimage_preimage (s : set β) : e.target ∩ e.symm ⁻¹' (e ⁻¹' s) = e.target ∩ s := e.symm.source_inter_preimage_inv_preimage _ lemma symm_image_image_of_subset_source {s : set α} (h : s ⊆ e.source) : e.symm '' (e '' s) = s := (e.left_inv_on.mono h).image_image lemma image_symm_image_of_subset_target {s : set β} (h : s ⊆ e.target) : e '' (e.symm '' s) = s := e.symm.symm_image_image_of_subset_source h lemma source_subset_preimage_target : e.source ⊆ e ⁻¹' e.target := e.maps_to lemma symm_image_target_eq_source : e.symm '' e.target = e.source := e.symm.image_source_eq_target lemma target_subset_preimage_source : e.target ⊆ e.symm ⁻¹' e.source := e.symm_maps_to /-- Two local equivs that have the same `source`, same `to_fun` and same `inv_fun`, coincide. -/ @[ext] protected lemma ext {e e' : local_equiv α β} (h : ∀x, e x = e' x) (hsymm : ∀x, e.symm x = e'.symm x) (hs : e.source = e'.source) : e = e' := begin have A : (e : α → β) = e', by { ext x, exact h x }, have B : (e.symm : β → α) = e'.symm, by { ext x, exact hsymm x }, have I : e '' e.source = e.target := e.image_source_eq_target, have I' : e' '' e'.source = e'.target := e'.image_source_eq_target, rw [A, hs, I'] at I, cases e; cases e', simp * at * end /-- Restricting a local equivalence to e.source ∩ s -/ protected def restr (s : set α) : local_equiv α β := (@is_image.of_symm_preimage_eq α β e s (e.symm ⁻¹' s) rfl).restr @[simp, mfld_simps] lemma restr_coe (s : set α) : (e.restr s : α → β) = e := rfl @[simp, mfld_simps] lemma restr_coe_symm (s : set α) : ((e.restr s).symm : β → α) = e.symm := rfl @[simp, mfld_simps] lemma restr_source (s : set α) : (e.restr s).source = e.source ∩ s := rfl @[simp, mfld_simps] lemma restr_target (s : set α) : (e.restr s).target = e.target ∩ e.symm ⁻¹' s := rfl lemma restr_eq_of_source_subset {e : local_equiv α β} {s : set α} (h : e.source ⊆ s) : e.restr s = e := local_equiv.ext (λ_, rfl) (λ_, rfl) (by simp [inter_eq_self_of_subset_left h]) @[simp, mfld_simps] lemma restr_univ {e : local_equiv α β} : e.restr univ = e := restr_eq_of_source_subset (subset_univ _) /-- The identity local equiv -/ protected def refl (α : Type*) : local_equiv α α := (equiv.refl α).to_local_equiv @[simp, mfld_simps] lemma refl_source : (local_equiv.refl α).source = univ := rfl @[simp, mfld_simps] lemma refl_target : (local_equiv.refl α).target = univ := rfl @[simp, mfld_simps] lemma refl_coe : (local_equiv.refl α : α → α) = id := rfl @[simp, mfld_simps] lemma refl_symm : (local_equiv.refl α).symm = local_equiv.refl α := rfl @[simp, mfld_simps] lemma refl_restr_source (s : set α) : ((local_equiv.refl α).restr s).source = s := by simp @[simp, mfld_simps] lemma refl_restr_target (s : set α) : ((local_equiv.refl α).restr s).target = s := by { change univ ∩ id⁻¹' s = s, simp } /-- The identity local equiv on a set `s` -/ def of_set (s : set α) : local_equiv α α := { to_fun := id, inv_fun := id, source := s, target := s, map_source' := λx hx, hx, map_target' := λx hx, hx, left_inv' := λx hx, rfl, right_inv' := λx hx, rfl } @[simp, mfld_simps] lemma of_set_source (s : set α) : (local_equiv.of_set s).source = s := rfl @[simp, mfld_simps] lemma of_set_target (s : set α) : (local_equiv.of_set s).target = s := rfl @[simp, mfld_simps] lemma of_set_coe (s : set α) : (local_equiv.of_set s : α → α) = id := rfl @[simp, mfld_simps] lemma of_set_symm (s : set α) : (local_equiv.of_set s).symm = local_equiv.of_set s := rfl /-- Composing two local equivs if the target of the first coincides with the source of the second. -/ protected def trans' (e' : local_equiv β γ) (h : e.target = e'.source) : local_equiv α γ := { to_fun := e' ∘ e, inv_fun := e.symm ∘ e'.symm, source := e.source, target := e'.target, map_source' := λx hx, by simp [h.symm, hx], map_target' := λy hy, by simp [h, hy], left_inv' := λx hx, by simp [hx, h.symm], right_inv' := λy hy, by simp [hy, h] } /-- Composing two local equivs, by restricting to the maximal domain where their composition is well defined. -/ protected def trans : local_equiv α γ := local_equiv.trans' (e.symm.restr (e'.source)).symm (e'.restr (e.target)) (inter_comm _ _) @[simp, mfld_simps] lemma coe_trans : (e.trans e' : α → γ) = e' ∘ e := rfl @[simp, mfld_simps] lemma coe_trans_symm : ((e.trans e').symm : γ → α) = e.symm ∘ e'.symm := rfl lemma trans_apply {x : α} : (e.trans e') x = e' (e x) := rfl lemma trans_symm_eq_symm_trans_symm : (e.trans e').symm = e'.symm.trans e.symm := by cases e; cases e'; refl @[simp, mfld_simps] lemma trans_source : (e.trans e').source = e.source ∩ e ⁻¹' e'.source := rfl lemma trans_source' : (e.trans e').source = e.source ∩ e ⁻¹' (e.target ∩ e'.source) := by mfld_set_tac lemma trans_source'' : (e.trans e').source = e.symm '' (e.target ∩ e'.source) := by rw [e.trans_source', e.symm_image_target_inter_eq] lemma image_trans_source : e '' (e.trans e').source = e.target ∩ e'.source := (e.symm.restr e'.source).symm.image_source_eq_target @[simp, mfld_simps] lemma trans_target : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' e.target := rfl lemma trans_target' : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' (e'.source ∩ e.target) := trans_source' e'.symm e.symm lemma trans_target'' : (e.trans e').target = e' '' (e'.source ∩ e.target) := trans_source'' e'.symm e.symm lemma inv_image_trans_target : e'.symm '' (e.trans e').target = e'.source ∩ e.target := image_trans_source e'.symm e.symm lemma trans_assoc (e'' : local_equiv γ δ) : (e.trans e').trans e'' = e.trans (e'.trans e'') := local_equiv.ext (λx, rfl) (λx, rfl) (by simp [trans_source, @preimage_comp α β γ, inter_assoc]) @[simp, mfld_simps] lemma trans_refl : e.trans (local_equiv.refl β) = e := local_equiv.ext (λx, rfl) (λx, rfl) (by simp [trans_source]) @[simp, mfld_simps] lemma refl_trans : (local_equiv.refl α).trans e = e := local_equiv.ext (λx, rfl) (λx, rfl) (by simp [trans_source, preimage_id]) lemma trans_refl_restr (s : set β) : e.trans ((local_equiv.refl β).restr s) = e.restr (e ⁻¹' s) := local_equiv.ext (λx, rfl) (λx, rfl) (by simp [trans_source]) lemma trans_refl_restr' (s : set β) : e.trans ((local_equiv.refl β).restr s) = e.restr (e.source ∩ e ⁻¹' s) := local_equiv.ext (λx, rfl) (λx, rfl) $ by { simp [trans_source], rw [← inter_assoc, inter_self] } lemma restr_trans (s : set α) : (e.restr s).trans e' = (e.trans e').restr s := local_equiv.ext (λx, rfl) (λx, rfl) $ by { simp [trans_source, inter_comm], rwa inter_assoc } /-- A lemma commonly useful when `e` and `e'` are charts of a manifold. -/ lemma mem_symm_trans_source {e' : local_equiv α γ} {x : α} (he : x ∈ e.source) (he' : x ∈ e'.source) : e x ∈ (e.symm.trans e').source := ⟨e.maps_to he, by rwa [mem_preimage, local_equiv.symm_symm, e.left_inv he]⟩ /-- Postcompose a local equivalence with an equivalence. We modify the source and target to have better definitional behavior. -/ @[simps] def trans_equiv (e' : β ≃ γ) : local_equiv α γ := (e.trans e'.to_local_equiv).copy _ rfl _ rfl e.source (inter_univ _) (e'.symm ⁻¹' e.target) (univ_inter _) lemma trans_equiv_eq_trans (e' : β ≃ γ) : e.trans_equiv e' = e.trans e'.to_local_equiv := copy_eq_self _ _ _ _ _ _ _ _ _ /-- Precompose a local equivalence with an equivalence. We modify the source and target to have better definitional behavior. -/ @[simps] def _root_.equiv.trans_local_equiv (e : α ≃ β) : local_equiv α γ := (e.to_local_equiv.trans e').copy _ rfl _ rfl (e ⁻¹' e'.source) (univ_inter _) e'.target (inter_univ _) lemma _root_.equiv.trans_local_equiv_eq_trans (e : α ≃ β) : e.trans_local_equiv e' = e.to_local_equiv.trans e' := copy_eq_self _ _ _ _ _ _ _ _ _ /-- `eq_on_source e e'` means that `e` and `e'` have the same source, and coincide there. Then `e` and `e'` should really be considered the same local equiv. -/ def eq_on_source (e e' : local_equiv α β) : Prop := e.source = e'.source ∧ (e.source.eq_on e e') /-- `eq_on_source` is an equivalence relation -/ instance eq_on_source_setoid : setoid (local_equiv α β) := { r := eq_on_source, iseqv := ⟨ λe, by simp [eq_on_source], λe e' h, by { simp [eq_on_source, h.1.symm], exact λx hx, (h.2 hx).symm }, λe e' e'' h h', ⟨by rwa [← h'.1, ← h.1], λx hx, by { rw [← h'.2, h.2 hx], rwa ← h.1 }⟩⟩ } lemma eq_on_source_refl : e ≈ e := setoid.refl _ /-- Two equivalent local equivs have the same source -/ lemma eq_on_source.source_eq {e e' : local_equiv α β} (h : e ≈ e') : e.source = e'.source := h.1 /-- Two equivalent local equivs coincide on the source -/ lemma eq_on_source.eq_on {e e' : local_equiv α β} (h : e ≈ e') : e.source.eq_on e e' := h.2 /-- Two equivalent local equivs have the same target -/ lemma eq_on_source.target_eq {e e' : local_equiv α β} (h : e ≈ e') : e.target = e'.target := by simp only [← image_source_eq_target, ← h.source_eq, h.2.image_eq] /-- If two local equivs are equivalent, so are their inverses. -/ lemma eq_on_source.symm' {e e' : local_equiv α β} (h : e ≈ e') : e.symm ≈ e'.symm := begin refine ⟨h.target_eq, eq_on_of_left_inv_on_of_right_inv_on e.left_inv_on _ _⟩; simp only [symm_source, h.target_eq, h.source_eq, e'.symm_maps_to], exact e'.right_inv_on.congr_right e'.symm_maps_to (h.source_eq ▸ h.eq_on.symm), end /-- Two equivalent local equivs have coinciding inverses on the target -/ lemma eq_on_source.symm_eq_on {e e' : local_equiv α β} (h : e ≈ e') : eq_on e.symm e'.symm e.target := h.symm'.eq_on /-- Composition of local equivs respects equivalence -/ lemma eq_on_source.trans' {e e' : local_equiv α β} {f f' : local_equiv β γ} (he : e ≈ e') (hf : f ≈ f') : e.trans f ≈ e'.trans f' := begin split, { rw [trans_source'', trans_source'', ← he.target_eq, ← hf.1], exact (he.symm'.eq_on.mono $ inter_subset_left _ _).image_eq }, { assume x hx, rw trans_source at hx, simp [(he.2 hx.1).symm, hf.2 hx.2] } end /-- Restriction of local equivs respects equivalence -/ lemma eq_on_source.restr {e e' : local_equiv α β} (he : e ≈ e') (s : set α) : e.restr s ≈ e'.restr s := begin split, { simp [he.1] }, { assume x hx, simp only [mem_inter_eq, restr_source] at hx, exact he.2 hx.1 } end /-- Preimages are respected by equivalence -/ lemma eq_on_source.source_inter_preimage_eq {e e' : local_equiv α β} (he : e ≈ e') (s : set β) : e.source ∩ e ⁻¹' s = e'.source ∩ e' ⁻¹' s := by rw [he.eq_on.inter_preimage_eq, he.source_eq] /-- Composition of a local equiv and its inverse is equivalent to the restriction of the identity to the source -/ lemma trans_self_symm : e.trans e.symm ≈ local_equiv.of_set e.source := begin have A : (e.trans e.symm).source = e.source, by mfld_set_tac, refine ⟨by simp [A], λx hx, _⟩, rw A at hx, simp only [hx] with mfld_simps end /-- Composition of the inverse of a local equiv and this local equiv is equivalent to the restriction of the identity to the target -/ lemma trans_symm_self : e.symm.trans e ≈ local_equiv.of_set e.target := trans_self_symm (e.symm) /-- Two equivalent local equivs are equal when the source and target are univ -/ lemma eq_of_eq_on_source_univ (e e' : local_equiv α β) (h : e ≈ e') (s : e.source = univ) (t : e.target = univ) : e = e' := begin apply local_equiv.ext (λx, _) (λx, _) h.1, { apply h.2, rw s, exact mem_univ _ }, { apply h.symm'.2, rw [symm_source, t], exact mem_univ _ } end section prod /-- The product of two local equivs, as a local equiv on the product. -/ def prod (e : local_equiv α β) (e' : local_equiv γ δ) : local_equiv (α × γ) (β × δ) := { source := e.source ×ˢ e'.source, target := e.target ×ˢ e'.target, to_fun := λp, (e p.1, e' p.2), inv_fun := λp, (e.symm p.1, e'.symm p.2), map_source' := λp hp, by { simp at hp, simp [hp] }, map_target' := λp hp, by { simp at hp, simp [map_target, hp] }, left_inv' := λp hp, by { simp at hp, simp [hp] }, right_inv' := λp hp, by { simp at hp, simp [hp] } } @[simp, mfld_simps] lemma prod_source (e : local_equiv α β) (e' : local_equiv γ δ) : (e.prod e').source = e.source ×ˢ e'.source := rfl @[simp, mfld_simps] lemma prod_target (e : local_equiv α β) (e' : local_equiv γ δ) : (e.prod e').target = e.target ×ˢ e'.target := rfl @[simp, mfld_simps] lemma prod_coe (e : local_equiv α β) (e' : local_equiv γ δ) : ((e.prod e') : α × γ → β × δ) = (λp, (e p.1, e' p.2)) := rfl lemma prod_coe_symm (e : local_equiv α β) (e' : local_equiv γ δ) : ((e.prod e').symm : β × δ → α × γ) = (λp, (e.symm p.1, e'.symm p.2)) := rfl @[simp, mfld_simps] lemma prod_symm (e : local_equiv α β) (e' : local_equiv γ δ) : (e.prod e').symm = (e.symm.prod e'.symm) := by ext x; simp [prod_coe_symm] @[simp, mfld_simps] lemma prod_trans {η : Type*} {ε : Type*} (e : local_equiv α β) (f : local_equiv β γ) (e' : local_equiv δ η) (f' : local_equiv η ε) : (e.prod e').trans (f.prod f') = (e.trans f).prod (e'.trans f') := by ext x; simp [ext_iff]; tauto end prod /-- Combine two `local_equiv`s using `set.piecewise`. The source of the new `local_equiv` is `s.ite e.source e'.source = e.source ∩ s ∪ e'.source \ s`, and similarly for target. The function sends `e.source ∩ s` to `e.target ∩ t` using `e` and `e'.source \ s` to `e'.target \ t` using `e'`, and similarly for the inverse function. The definition assumes `e.is_image s t` and `e'.is_image s t`. -/ @[simps {fully_applied := ff}] def piecewise (e e' : local_equiv α β) (s : set α) (t : set β) [∀ x, decidable (x ∈ s)] [∀ y, decidable (y ∈ t)] (H : e.is_image s t) (H' : e'.is_image s t) : local_equiv α β := { to_fun := s.piecewise e e', inv_fun := t.piecewise e.symm e'.symm, source := s.ite e.source e'.source, target := t.ite e.target e'.target, map_source' := H.maps_to.piecewise_ite H'.compl.maps_to, map_target' := H.symm.maps_to.piecewise_ite H'.symm.compl.maps_to, left_inv' := H.left_inv_on_piecewise H', right_inv' := H.symm.left_inv_on_piecewise H'.symm } lemma symm_piecewise (e e' : local_equiv α β) {s : set α} {t : set β} [∀ x, decidable (x ∈ s)] [∀ y, decidable (y ∈ t)] (H : e.is_image s t) (H' : e'.is_image s t) : (e.piecewise e' s t H H').symm = e.symm.piecewise e'.symm t s H.symm H'.symm := rfl /-- Combine two `local_equiv`s with disjoint sources and disjoint targets. We reuse `local_equiv.piecewise`, then override `source` and `target` to ensure better definitional equalities. -/ @[simps {fully_applied := ff}] def disjoint_union (e e' : local_equiv α β) (hs : disjoint e.source e'.source) (ht : disjoint e.target e'.target) [∀ x, decidable (x ∈ e.source)] [∀ y, decidable (y ∈ e.target)] : local_equiv α β := (e.piecewise e' e.source e.target e.is_image_source_target $ e'.is_image_source_target_of_disjoint _ hs.symm ht.symm).copy _ rfl _ rfl (e.source ∪ e'.source) (ite_left _ _) (e.target ∪ e'.target) (ite_left _ _) lemma disjoint_union_eq_piecewise (e e' : local_equiv α β) (hs : disjoint e.source e'.source) (ht : disjoint e.target e'.target) [∀ x, decidable (x ∈ e.source)] [∀ y, decidable (y ∈ e.target)] : e.disjoint_union e' hs ht = e.piecewise e' e.source e.target e.is_image_source_target (e'.is_image_source_target_of_disjoint _ hs.symm ht.symm) := copy_eq_self _ _ _ _ _ _ _ _ _ section pi variables {ι : Type*} {αi βi : ι → Type*} (ei : Π i, local_equiv (αi i) (βi i)) /-- The product of a family of local equivs, as a local equiv on the pi type. -/ @[simps (mfld_cfg)] protected def pi : local_equiv (Π i, αi i) (Π i, βi i) := { to_fun := λ f i, ei i (f i), inv_fun := λ f i, (ei i).symm (f i), source := pi univ (λ i, (ei i).source), target := pi univ (λ i, (ei i).target), map_source' := λ f hf i hi, (ei i).map_source (hf i hi), map_target' := λ f hf i hi, (ei i).map_target (hf i hi), left_inv' := λ f hf, funext $ λ i, (ei i).left_inv (hf i trivial), right_inv' := λ f hf, funext $ λ i, (ei i).right_inv (hf i trivial) } end pi end local_equiv namespace set -- All arguments are explicit to avoid missing information in the pretty printer output /-- A bijection between two sets `s : set α` and `t : set β` provides a local equivalence between `α` and `β`. -/ @[simps {fully_applied := ff}] noncomputable def bij_on.to_local_equiv [nonempty α] (f : α → β) (s : set α) (t : set β) (hf : bij_on f s t) : local_equiv α β := { to_fun := f, inv_fun := inv_fun_on f s, source := s, target := t, map_source' := hf.maps_to, map_target' := hf.surj_on.maps_to_inv_fun_on, left_inv' := hf.inv_on_inv_fun_on.1, right_inv' := hf.inv_on_inv_fun_on.2 } /-- A map injective on a subset of its domain provides a local equivalence. -/ @[simp, mfld_simps] noncomputable def inj_on.to_local_equiv [nonempty α] (f : α → β) (s : set α) (hf : inj_on f s) : local_equiv α β := hf.bij_on_image.to_local_equiv f s (f '' s) end set namespace equiv /- equivs give rise to local_equiv. We set up simp lemmas to reduce most properties of the local equiv to that of the equiv. -/ variables (e : α ≃ β) (e' : β ≃ γ) @[simp, mfld_simps] lemma refl_to_local_equiv : (equiv.refl α).to_local_equiv = local_equiv.refl α := rfl @[simp, mfld_simps] lemma symm_to_local_equiv : e.symm.to_local_equiv = e.to_local_equiv.symm := rfl @[simp, mfld_simps] lemma trans_to_local_equiv : (e.trans e').to_local_equiv = e.to_local_equiv.trans e'.to_local_equiv := local_equiv.ext (λx, rfl) (λx, rfl) (by simp [local_equiv.trans_source, equiv.to_local_equiv]) end equiv