path
stringlengths
11
71
content
stringlengths
75
124k
Combinatorics\SetFamily\Compression\Down.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 Mathlib.Data.Finset.Lattice /-! # Down-compressions This file defines down-compression. Down-compressing `𝒜 : Finset (Finset α)` along `a : α` means removing `a` from the elements of `𝒜`, when the resulting set is not already in `𝒜`. ## Main declarations * `Finset.nonMemberSubfamily`: `𝒜.nonMemberSubfamily a` is the subfamily of sets not containing `a`. * `Finset.memberSubfamily`: `𝒜.memberSubfamily a` is the image of the subfamily of sets containing `a` under removing `a`. * `Down.compression`: Down-compression. ## Notation `𝓓 a 𝒜` is notation for `Down.compress a 𝒜` in locale `SetFamily`. ## References * https://github.com/b-mehta/maths-notes/blob/master/iii/mich/combinatorics.pdf ## Tags compression, down-compression -/ variable {α : Type*} [DecidableEq α] {𝒜 ℬ : Finset (Finset α)} {s : Finset α} {a : α} namespace Finset /-- Elements of `𝒜` that do not contain `a`. -/ def nonMemberSubfamily (a : α) (𝒜 : Finset (Finset α)) : Finset (Finset α) := 𝒜.filter fun s => a ∉ s /-- Image of the elements of `𝒜` which contain `a` under removing `a`. Finsets that do not contain `a` such that `insert a s ∈ 𝒜`. -/ def memberSubfamily (a : α) (𝒜 : Finset (Finset α)) : Finset (Finset α) := (𝒜.filter fun s => a ∈ s).image fun s => erase s a @[simp] theorem mem_nonMemberSubfamily : s ∈ 𝒜.nonMemberSubfamily a ↔ s ∈ 𝒜 ∧ a ∉ s := by simp [nonMemberSubfamily] @[simp] theorem mem_memberSubfamily : s ∈ 𝒜.memberSubfamily a ↔ insert a s ∈ 𝒜 ∧ a ∉ s := by simp_rw [memberSubfamily, mem_image, mem_filter] refine ⟨?_, fun h => ⟨insert a s, ⟨h.1, by simp⟩, erase_insert h.2⟩⟩ rintro ⟨s, ⟨hs1, hs2⟩, rfl⟩ rw [insert_erase hs2] exact ⟨hs1, not_mem_erase _ _⟩ theorem nonMemberSubfamily_inter (a : α) (𝒜 ℬ : Finset (Finset α)) : (𝒜 ∩ ℬ).nonMemberSubfamily a = 𝒜.nonMemberSubfamily a ∩ ℬ.nonMemberSubfamily a := filter_inter_distrib _ _ _ theorem memberSubfamily_inter (a : α) (𝒜 ℬ : Finset (Finset α)) : (𝒜 ∩ ℬ).memberSubfamily a = 𝒜.memberSubfamily a ∩ ℬ.memberSubfamily a := by unfold memberSubfamily rw [filter_inter_distrib, image_inter_of_injOn _ _ ((erase_injOn' _).mono _)] simp theorem nonMemberSubfamily_union (a : α) (𝒜 ℬ : Finset (Finset α)) : (𝒜 ∪ ℬ).nonMemberSubfamily a = 𝒜.nonMemberSubfamily a ∪ ℬ.nonMemberSubfamily a := filter_union _ _ _ theorem memberSubfamily_union (a : α) (𝒜 ℬ : Finset (Finset α)) : (𝒜 ∪ ℬ).memberSubfamily a = 𝒜.memberSubfamily a ∪ ℬ.memberSubfamily a := by simp_rw [memberSubfamily, filter_union, image_union] theorem card_memberSubfamily_add_card_nonMemberSubfamily (a : α) (𝒜 : Finset (Finset α)) : (𝒜.memberSubfamily a).card + (𝒜.nonMemberSubfamily a).card = 𝒜.card := by rw [memberSubfamily, nonMemberSubfamily, card_image_of_injOn] · conv_rhs => rw [← filter_card_add_filter_neg_card_eq_card (fun s => (a ∈ s))] · apply (erase_injOn' _).mono simp theorem memberSubfamily_union_nonMemberSubfamily (a : α) (𝒜 : Finset (Finset α)) : 𝒜.memberSubfamily a ∪ 𝒜.nonMemberSubfamily a = 𝒜.image fun s => s.erase a := by ext s simp only [mem_union, mem_memberSubfamily, mem_nonMemberSubfamily, mem_image, exists_prop] constructor · rintro (h | h) · exact ⟨_, h.1, erase_insert h.2⟩ · exact ⟨_, h.1, erase_eq_of_not_mem h.2⟩ · rintro ⟨s, hs, rfl⟩ by_cases ha : a ∈ s · exact Or.inl ⟨by rwa [insert_erase ha], not_mem_erase _ _⟩ · exact Or.inr ⟨by rwa [erase_eq_of_not_mem ha], not_mem_erase _ _⟩ @[simp] theorem memberSubfamily_memberSubfamily : (𝒜.memberSubfamily a).memberSubfamily a = ∅ := by ext simp @[simp] theorem memberSubfamily_nonMemberSubfamily : (𝒜.nonMemberSubfamily a).memberSubfamily a = ∅ := by ext simp @[simp] theorem nonMemberSubfamily_memberSubfamily : (𝒜.memberSubfamily a).nonMemberSubfamily a = 𝒜.memberSubfamily a := by ext simp @[simp] theorem nonMemberSubfamily_nonMemberSubfamily : (𝒜.nonMemberSubfamily a).nonMemberSubfamily a = 𝒜.nonMemberSubfamily a := by ext simp lemma memberSubfamily_image_insert (h𝒜 : ∀ s ∈ 𝒜, a ∉ s) : (𝒜.image <| insert a).memberSubfamily a = 𝒜 := by ext s simp only [mem_memberSubfamily, mem_image] refine ⟨?_, fun hs ↦ ⟨⟨s, hs, rfl⟩, h𝒜 _ hs⟩⟩ rintro ⟨⟨t, ht, hts⟩, hs⟩ rwa [← insert_erase_invOn.2.injOn (h𝒜 _ ht) hs hts] @[simp] lemma nonMemberSubfamily_image_insert : (𝒜.image <| insert a).nonMemberSubfamily a = ∅ := by simp [eq_empty_iff_forall_not_mem] @[simp] lemma memberSubfamily_image_erase : (𝒜.image (erase · a)).memberSubfamily a = ∅ := by simp [eq_empty_iff_forall_not_mem, (ne_of_mem_of_not_mem' (mem_insert_self _ _) (not_mem_erase _ _)).symm] lemma image_insert_memberSubfamily (𝒜 : Finset (Finset α)) (a : α) : (𝒜.memberSubfamily a).image (insert a) = 𝒜.filter (a ∈ ·) := by ext s simp only [mem_memberSubfamily, mem_image, mem_filter] refine ⟨?_, fun ⟨hs, ha⟩ ↦ ⟨erase s a, ⟨?_, not_mem_erase _ _⟩, insert_erase ha⟩⟩ · rintro ⟨s, ⟨hs, -⟩, rfl⟩ exact ⟨hs, mem_insert_self _ _⟩ · rwa [insert_erase ha] /-- Induction principle for finset families. To prove a statement for every finset family, it suffices to prove it for * the empty finset family. * the finset family which only contains the empty finset. * `ℬ ∪ {s ∪ {a} | s ∈ 𝒞}` assuming the property for `ℬ` and `𝒞`, where `a` is an element of the ground type and `𝒜` and `ℬ` are families of finsets not containing `a`. Note that instead of giving `ℬ` and `𝒞`, the `subfamily` case gives you `𝒜 = ℬ ∪ {s ∪ {a} | s ∈ 𝒞}`, so that `ℬ = 𝒜.nonMemberSubfamily` and `𝒞 = 𝒜.memberSubfamily`. This is a way of formalising induction on `n` where `𝒜` is a finset family on `n` elements. See also `Finset.family_induction_on.`-/ @[elab_as_elim] lemma memberFamily_induction_on {p : Finset (Finset α) → Prop} (𝒜 : Finset (Finset α)) (empty : p ∅) (singleton_empty : p {∅}) (subfamily : ∀ (a : α) ⦃𝒜 : Finset (Finset α)⦄, p (𝒜.nonMemberSubfamily a) → p (𝒜.memberSubfamily a) → p 𝒜) : p 𝒜 := by set u := 𝒜.sup id have hu : ∀ s ∈ 𝒜, s ⊆ u := fun s ↦ le_sup (f := id) clear_value u induction' u using Finset.induction with a u _ ih generalizing 𝒜 · simp_rw [subset_empty] at hu rw [← subset_singleton_iff', subset_singleton_iff] at hu obtain rfl | rfl := hu <;> assumption refine subfamily a (ih _ ?_) (ih _ ?_) · simp only [mem_nonMemberSubfamily, and_imp] exact fun s hs has ↦ (subset_insert_iff_of_not_mem has).1 <| hu _ hs · simp only [mem_memberSubfamily, and_imp] exact fun s hs ha ↦ (insert_subset_insert_iff ha).1 <| hu _ hs /-- Induction principle for finset families. To prove a statement for every finset family, it suffices to prove it for * the empty finset family. * the finset family which only contains the empty finset. * `{s ∪ {a} | s ∈ 𝒜}` assuming the property for `𝒜` a family of finsets not containing `a`. * `ℬ ∪ 𝒞` assuming the property for `ℬ` and `𝒞`, where `a` is an element of the ground type and `ℬ`is a family of finsets not containing `a` and `𝒞` a family of finsets containing `a`. Note that instead of giving `ℬ` and `𝒞`, the `subfamily` case gives you `𝒜 = ℬ ∪ 𝒞`, so that `ℬ = 𝒜.filter (a ∉ ·)` and `𝒞 = 𝒜.filter (a ∈ ·)`. This is a way of formalising induction on `n` where `𝒜` is a finset family on `n` elements. See also `Finset.memberFamily_induction_on.`-/ @[elab_as_elim] protected lemma family_induction_on {p : Finset (Finset α) → Prop} (𝒜 : Finset (Finset α)) (empty : p ∅) (singleton_empty : p {∅}) (image_insert : ∀ (a : α) ⦃𝒜 : Finset (Finset α)⦄, (∀ s ∈ 𝒜, a ∉ s) → p 𝒜 → p (𝒜.image <| insert a)) (subfamily : ∀ (a : α) ⦃𝒜 : Finset (Finset α)⦄, p (𝒜.filter (a ∉ ·)) → p (𝒜.filter (a ∈ ·)) → p 𝒜) : p 𝒜 := by refine memberFamily_induction_on 𝒜 empty singleton_empty fun a 𝒜 h𝒜₀ h𝒜₁ ↦ subfamily a h𝒜₀ ?_ rw [← image_insert_memberSubfamily] exact image_insert _ (by simp) h𝒜₁ end Finset open Finset -- The namespace is here to distinguish from other compressions. namespace Down /-- `a`-down-compressing `𝒜` means removing `a` from the elements of `𝒜` that contain it, when the resulting Finset is not already in `𝒜`. -/ def compression (a : α) (𝒜 : Finset (Finset α)) : Finset (Finset α) := (𝒜.filter fun s => erase s a ∈ 𝒜).disjUnion ((𝒜.image fun s => erase s a).filter fun s => s ∉ 𝒜) <| disjoint_left.2 fun s h₁ h₂ => by have := (mem_filter.1 h₂).2 exact this (mem_filter.1 h₁).1 @[inherit_doc] scoped[FinsetFamily] notation "𝓓 " => Down.compression -- Porting note: had to open this open FinsetFamily /-- `a` is in the down-compressed family iff it's in the original and its compression is in the original, or it's not in the original but it's the compression of something in the original. -/ theorem mem_compression : s ∈ 𝓓 a 𝒜 ↔ s ∈ 𝒜 ∧ s.erase a ∈ 𝒜 ∨ s ∉ 𝒜 ∧ insert a s ∈ 𝒜 := by simp_rw [compression, mem_disjUnion, mem_filter, mem_image, and_comm (a := (¬ s ∈ 𝒜))] refine or_congr_right (and_congr_left fun hs => ⟨?_, fun h => ⟨_, h, erase_insert <| insert_ne_self.1 <| ne_of_mem_of_not_mem h hs⟩⟩) rintro ⟨t, ht, rfl⟩ rwa [insert_erase (erase_ne_self.1 (ne_of_mem_of_not_mem ht hs).symm)] theorem erase_mem_compression (hs : s ∈ 𝒜) : s.erase a ∈ 𝓓 a 𝒜 := by simp_rw [mem_compression, erase_idem, and_self_iff] refine (em _).imp_right fun h => ⟨h, ?_⟩ rwa [insert_erase (erase_ne_self.1 (ne_of_mem_of_not_mem hs h).symm)] -- This is a special case of `erase_mem_compression` once we have `compression_idem`. theorem erase_mem_compression_of_mem_compression : s ∈ 𝓓 a 𝒜 → s.erase a ∈ 𝓓 a 𝒜 := by simp_rw [mem_compression, erase_idem] refine Or.imp (fun h => ⟨h.2, h.2⟩) fun h => ?_ rwa [erase_eq_of_not_mem (insert_ne_self.1 <| ne_of_mem_of_not_mem h.2 h.1)] theorem mem_compression_of_insert_mem_compression (h : insert a s ∈ 𝓓 a 𝒜) : s ∈ 𝓓 a 𝒜 := by by_cases ha : a ∈ s · rwa [insert_eq_of_mem ha] at h · rw [← erase_insert ha] exact erase_mem_compression_of_mem_compression h /-- Down-compressing a family is idempotent. -/ @[simp] theorem compression_idem (a : α) (𝒜 : Finset (Finset α)) : 𝓓 a (𝓓 a 𝒜) = 𝓓 a 𝒜 := by ext s refine mem_compression.trans ⟨?_, fun h => Or.inl ⟨h, erase_mem_compression_of_mem_compression h⟩⟩ rintro (h | h) · exact h.1 · cases h.1 (mem_compression_of_insert_mem_compression h.2) /-- Down-compressing a family doesn't change its size. -/ @[simp] theorem card_compression (a : α) (𝒜 : Finset (Finset α)) : (𝓓 a 𝒜).card = 𝒜.card := by rw [compression, card_disjUnion, filter_image, card_image_of_injOn ((erase_injOn' _).mono fun s hs => _), ← card_union_of_disjoint] · conv_rhs => rw [← filter_union_filter_neg_eq (fun s => (erase s a ∈ 𝒜)) 𝒜] · exact disjoint_filter_filter_neg 𝒜 𝒜 (fun s => (erase s a ∈ 𝒜)) intro s hs rw [mem_coe, mem_filter] at hs exact not_imp_comm.1 erase_eq_of_not_mem (ne_of_mem_of_not_mem hs.1 hs.2).symm end Down
Combinatorics\SetFamily\Compression\UV.lean
/- Copyright (c) 2021 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import Mathlib.Combinatorics.SetFamily.Shadow /-! # UV-compressions This file defines UV-compression. It is an operation on a set family that reduces its shadow. UV-compressing `a : α` along `u v : α` means replacing `a` by `(a ⊔ u) \ v` if `a` and `u` are disjoint and `v ≤ a`. In some sense, it's moving `a` from `v` to `u`. UV-compressions are immensely useful to prove the Kruskal-Katona theorem. The idea is that compressing a set family might decrease the size of its shadow, so iterated compressions hopefully minimise the shadow. ## Main declarations * `UV.compress`: `compress u v a` is `a` compressed along `u` and `v`. * `UV.compression`: `compression u v s` is the compression of the set family `s` along `u` and `v`. It is the compressions of the elements of `s` whose compression is not already in `s` along with the element whose compression is already in `s`. This way of splitting into what moves and what does not ensures the compression doesn't squash the set family, which is proved by `UV.card_compression`. * `UV.card_shadow_compression_le`: Compressing reduces the size of the shadow. This is a key fact in the proof of Kruskal-Katona. ## Notation `𝓒` (typed with `\MCC`) is notation for `UV.compression` in locale `FinsetFamily`. ## Notes Even though our emphasis is on `Finset α`, we define UV-compressions more generally in a generalized boolean algebra, so that one can use it for `Set α`. ## References * https://github.com/b-mehta/maths-notes/blob/master/iii/mich/combinatorics.pdf ## Tags compression, UV-compression, shadow -/ open Finset variable {α : Type*} /-- UV-compression is injective on the elements it moves. See `UV.compress`. -/ theorem sup_sdiff_injOn [GeneralizedBooleanAlgebra α] (u v : α) : { x | Disjoint u x ∧ v ≤ x }.InjOn fun x => (x ⊔ u) \ v := by rintro a ha b hb hab have h : ((a ⊔ u) \ v) \ u ⊔ v = ((b ⊔ u) \ v) \ u ⊔ v := by dsimp at hab rw [hab] rwa [sdiff_sdiff_comm, ha.1.symm.sup_sdiff_cancel_right, sdiff_sdiff_comm, hb.1.symm.sup_sdiff_cancel_right, sdiff_sup_cancel ha.2, sdiff_sup_cancel hb.2] at h -- The namespace is here to distinguish from other compressions. namespace UV /-! ### UV-compression in generalized boolean algebras -/ section GeneralizedBooleanAlgebra variable [GeneralizedBooleanAlgebra α] [DecidableRel (@Disjoint α _ _)] [DecidableRel ((· ≤ ·) : α → α → Prop)] {s : Finset α} {u v a b : α} /-- UV-compressing `a` means removing `v` from it and adding `u` if `a` and `u` are disjoint and `v ≤ a` (it replaces the `v` part of `a` by the `u` part). Else, UV-compressing `a` doesn't do anything. This is most useful when `u` and `v` are disjoint finsets of the same size. -/ def compress (u v a : α) : α := if Disjoint u a ∧ v ≤ a then (a ⊔ u) \ v else a theorem compress_of_disjoint_of_le (hua : Disjoint u a) (hva : v ≤ a) : compress u v a = (a ⊔ u) \ v := if_pos ⟨hua, hva⟩ theorem compress_of_disjoint_of_le' (hva : Disjoint v a) (hua : u ≤ a) : compress u v ((a ⊔ v) \ u) = a := by rw [compress_of_disjoint_of_le disjoint_sdiff_self_right (le_sdiff.2 ⟨(le_sup_right : v ≤ a ⊔ v), hva.mono_right hua⟩), sdiff_sup_cancel (le_sup_of_le_left hua), hva.symm.sup_sdiff_cancel_right] @[simp] theorem compress_self (u a : α) : compress u u a = a := by unfold compress split_ifs with h · exact h.1.symm.sup_sdiff_cancel_right · rfl /-- An element can be compressed to any other element by removing/adding the differences. -/ @[simp] theorem compress_sdiff_sdiff (a b : α) : compress (a \ b) (b \ a) b = a := by refine (compress_of_disjoint_of_le disjoint_sdiff_self_left sdiff_le).trans ?_ rw [sup_sdiff_self_right, sup_sdiff, disjoint_sdiff_self_right.sdiff_eq_left, sup_eq_right] exact sdiff_sdiff_le /-- Compressing an element is idempotent. -/ @[simp] theorem compress_idem (u v a : α) : compress u v (compress u v a) = compress u v a := by unfold compress split_ifs with h h' · rw [le_sdiff_iff.1 h'.2, sdiff_bot, sdiff_bot, sup_assoc, sup_idem] · rfl · rfl variable [DecidableEq α] /-- To UV-compress a set family, we compress each of its elements, except that we don't want to reduce the cardinality, so we keep all elements whose compression is already present. -/ def compression (u v : α) (s : Finset α) := (s.filter (compress u v · ∈ s)) ∪ (s.image <| compress u v).filter (· ∉ s) @[inherit_doc] scoped[FinsetFamily] notation "𝓒 " => UV.compression open scoped FinsetFamily /-- `IsCompressed u v s` expresses that `s` is UV-compressed. -/ def IsCompressed (u v : α) (s : Finset α) := 𝓒 u v s = s /-- UV-compression is injective on the sets that are not UV-compressed. -/ theorem compress_injOn : Set.InjOn (compress u v) ↑(s.filter (compress u v · ∉ s)) := by intro a ha b hb hab rw [mem_coe, mem_filter] at ha hb rw [compress] at ha hab split_ifs at ha hab with has · rw [compress] at hb hab split_ifs at hb hab with hbs · exact sup_sdiff_injOn u v has hbs hab · exact (hb.2 hb.1).elim · exact (ha.2 ha.1).elim /-- `a` is in the UV-compressed family iff it's in the original and its compression is in the original, or it's not in the original but it's the compression of something in the original. -/ theorem mem_compression : a ∈ 𝓒 u v s ↔ a ∈ s ∧ compress u v a ∈ s ∨ a ∉ s ∧ ∃ b ∈ s, compress u v b = a := by simp_rw [compression, mem_union, mem_filter, mem_image, and_comm] protected theorem IsCompressed.eq (h : IsCompressed u v s) : 𝓒 u v s = s := h @[simp] theorem compression_self (u : α) (s : Finset α) : 𝓒 u u s = s := by unfold compression convert union_empty s · ext a rw [mem_filter, compress_self, and_self_iff] · refine eq_empty_of_forall_not_mem fun a ha ↦ ?_ simp_rw [mem_filter, mem_image, compress_self] at ha obtain ⟨⟨b, hb, rfl⟩, hb'⟩ := ha exact hb' hb /-- Any family is compressed along two identical elements. -/ theorem isCompressed_self (u : α) (s : Finset α) : IsCompressed u u s := compression_self u s theorem compress_disjoint : Disjoint (s.filter (compress u v · ∈ s)) ((s.image <| compress u v).filter (· ∉ s)) := disjoint_left.2 fun _a ha₁ ha₂ ↦ (mem_filter.1 ha₂).2 (mem_filter.1 ha₁).1 theorem compress_mem_compression (ha : a ∈ s) : compress u v a ∈ 𝓒 u v s := by rw [mem_compression] by_cases h : compress u v a ∈ s · rw [compress_idem] exact Or.inl ⟨h, h⟩ · exact Or.inr ⟨h, a, ha, rfl⟩ -- This is a special case of `compress_mem_compression` once we have `compression_idem`. theorem compress_mem_compression_of_mem_compression (ha : a ∈ 𝓒 u v s) : compress u v a ∈ 𝓒 u v s := by rw [mem_compression] at ha ⊢ simp only [compress_idem, exists_prop] obtain ⟨_, ha⟩ | ⟨_, b, hb, rfl⟩ := ha · exact Or.inl ⟨ha, ha⟩ · exact Or.inr ⟨by rwa [compress_idem], b, hb, (compress_idem _ _ _).symm⟩ /-- Compressing a family is idempotent. -/ @[simp] theorem compression_idem (u v : α) (s : Finset α) : 𝓒 u v (𝓒 u v s) = 𝓒 u v s := by have h : filter (compress u v · ∉ 𝓒 u v s) (𝓒 u v s) = ∅ := filter_false_of_mem fun a ha h ↦ h <| compress_mem_compression_of_mem_compression ha rw [compression, filter_image, h, image_empty, ← h] exact filter_union_filter_neg_eq _ (compression u v s) /-- Compressing a family doesn't change its size. -/ @[simp] theorem card_compression (u v : α) (s : Finset α) : (𝓒 u v s).card = s.card := by rw [compression, card_union_of_disjoint compress_disjoint, filter_image, card_image_of_injOn compress_injOn, ← card_union_of_disjoint (disjoint_filter_filter_neg s _ _), filter_union_filter_neg_eq] theorem le_of_mem_compression_of_not_mem (h : a ∈ 𝓒 u v s) (ha : a ∉ s) : u ≤ a := by rw [mem_compression] at h obtain h | ⟨-, b, hb, hba⟩ := h · cases ha h.1 unfold compress at hba split_ifs at hba with h · rw [← hba, le_sdiff] exact ⟨le_sup_right, h.1.mono_right h.2⟩ · cases ne_of_mem_of_not_mem hb ha hba theorem disjoint_of_mem_compression_of_not_mem (h : a ∈ 𝓒 u v s) (ha : a ∉ s) : Disjoint v a := by rw [mem_compression] at h obtain h | ⟨-, b, hb, hba⟩ := h · cases ha h.1 unfold compress at hba split_ifs at hba · rw [← hba] exact disjoint_sdiff_self_right · cases ne_of_mem_of_not_mem hb ha hba theorem sup_sdiff_mem_of_mem_compression_of_not_mem (h : a ∈ 𝓒 u v s) (ha : a ∉ s) : (a ⊔ v) \ u ∈ s := by rw [mem_compression] at h obtain h | ⟨-, b, hb, hba⟩ := h · cases ha h.1 unfold compress at hba split_ifs at hba with h · rwa [← hba, sdiff_sup_cancel (le_sup_of_le_left h.2), sup_sdiff_right_self, h.1.symm.sdiff_eq_left] · cases ne_of_mem_of_not_mem hb ha hba /-- If `a` is in the family compression and can be compressed, then its compression is in the original family. -/ theorem sup_sdiff_mem_of_mem_compression (ha : a ∈ 𝓒 u v s) (hva : v ≤ a) (hua : Disjoint u a) : (a ⊔ u) \ v ∈ s := by rw [mem_compression, compress_of_disjoint_of_le hua hva] at ha obtain ⟨_, ha⟩ | ⟨_, b, hb, rfl⟩ := ha · exact ha have hu : u = ⊥ := by suffices Disjoint u (u \ v) by rwa [(hua.mono_right hva).sdiff_eq_left, disjoint_self] at this refine hua.mono_right ?_ rw [← compress_idem, compress_of_disjoint_of_le hua hva] exact sdiff_le_sdiff_right le_sup_right have hv : v = ⊥ := by rw [← disjoint_self] apply Disjoint.mono_right hva rw [← compress_idem, compress_of_disjoint_of_le hua hva] exact disjoint_sdiff_self_right rwa [hu, hv, compress_self, sup_bot_eq, sdiff_bot] /-- If `a` is in the `u, v`-compression but `v ≤ a`, then `a` must have been in the original family. -/ theorem mem_of_mem_compression (ha : a ∈ 𝓒 u v s) (hva : v ≤ a) (hvu : v = ⊥ → u = ⊥) : a ∈ s := by rw [mem_compression] at ha obtain ha | ⟨_, b, hb, h⟩ := ha · exact ha.1 unfold compress at h split_ifs at h · rw [← h, le_sdiff_iff] at hva rwa [← h, hvu hva, hva, sup_bot_eq, sdiff_bot] · rwa [← h] end GeneralizedBooleanAlgebra /-! ### UV-compression on finsets -/ open FinsetFamily variable [DecidableEq α] {𝒜 : Finset (Finset α)} {u v a : Finset α} {r : ℕ} /-- Compressing a finset doesn't change its size. -/ theorem card_compress (huv : u.card = v.card) (a : Finset α) : (compress u v a).card = a.card := by unfold compress split_ifs with h · rw [card_sdiff (h.2.trans le_sup_left), sup_eq_union, card_union_of_disjoint h.1.symm, huv, add_tsub_cancel_right] · rfl lemma _root_.Set.Sized.uvCompression (huv : u.card = v.card) (h𝒜 : (𝒜 : Set (Finset α)).Sized r) : (𝓒 u v 𝒜 : Set (Finset α)).Sized r := by simp_rw [Set.Sized, mem_coe, mem_compression] rintro s (hs | ⟨huvt, t, ht, rfl⟩) · exact h𝒜 hs.1 · rw [card_compress huv, h𝒜 ht] private theorem aux (huv : ∀ x ∈ u, ∃ y ∈ v, IsCompressed (u.erase x) (v.erase y) 𝒜) : v = ∅ → u = ∅ := by rintro rfl; refine eq_empty_of_forall_not_mem fun a ha ↦ ?_; obtain ⟨_, ⟨⟩, -⟩ := huv a ha /-- UV-compression reduces the size of the shadow of `𝒜` if, for all `x ∈ u` there is `y ∈ v` such that `𝒜` is `(u.erase x, v.erase y)`-compressed. This is the key fact about compression for Kruskal-Katona. -/ theorem shadow_compression_subset_compression_shadow (u v : Finset α) (huv : ∀ x ∈ u, ∃ y ∈ v, IsCompressed (u.erase x) (v.erase y) 𝒜) : ∂ (𝓒 u v 𝒜) ⊆ 𝓒 u v (∂ 𝒜) := by set 𝒜' := 𝓒 u v 𝒜 suffices H : ∀ s ∈ ∂ 𝒜', s ∉ ∂ 𝒜 → u ⊆ s ∧ Disjoint v s ∧ (s ∪ v) \ u ∈ ∂ 𝒜 ∧ (s ∪ v) \ u ∉ ∂ 𝒜' by rintro s hs' rw [mem_compression] by_cases hs : s ∈ 𝒜.shadow swap · obtain ⟨hus, hvs, h, _⟩ := H _ hs' hs exact Or.inr ⟨hs, _, h, compress_of_disjoint_of_le' hvs hus⟩ refine Or.inl ⟨hs, ?_⟩ rw [compress] split_ifs with huvs swap · exact hs rw [mem_shadow_iff] at hs' obtain ⟨t, Ht, a, hat, rfl⟩ := hs' have hav : a ∉ v := not_mem_mono huvs.2 (not_mem_erase a t) have hvt : v ≤ t := huvs.2.trans (erase_subset _ t) have ht : t ∈ 𝒜 := mem_of_mem_compression Ht hvt (aux huv) by_cases hau : a ∈ u · obtain ⟨b, hbv, Hcomp⟩ := huv a hau refine mem_shadow_iff_insert_mem.2 ⟨b, not_mem_sdiff_of_mem_right hbv, ?_⟩ rw [← Hcomp.eq] at ht have hsb := sup_sdiff_mem_of_mem_compression ht ((erase_subset _ _).trans hvt) (disjoint_erase_comm.2 huvs.1) rwa [sup_eq_union, sdiff_erase (mem_union_left _ <| hvt hbv), union_erase_of_mem hat, ← erase_union_of_mem hau] at hsb · refine mem_shadow_iff.2 ⟨(t ⊔ u) \ v, sup_sdiff_mem_of_mem_compression Ht hvt <| disjoint_of_erase_right hau huvs.1, a, ?_, ?_⟩ · rw [sup_eq_union, mem_sdiff, mem_union] exact ⟨Or.inl hat, hav⟩ · rw [← erase_sdiff_comm, sup_eq_union, erase_union_distrib, erase_eq_of_not_mem hau] intro s hs𝒜' hs𝒜 -- This is gonna be useful a couple of times so let's name it. have m : ∀ y, y ∉ s → insert y s ∉ 𝒜 := fun y h a => hs𝒜 (mem_shadow_iff_insert_mem.2 ⟨y, h, a⟩) obtain ⟨x, _, _⟩ := mem_shadow_iff_insert_mem.1 hs𝒜' have hus : u ⊆ insert x s := le_of_mem_compression_of_not_mem ‹_ ∈ 𝒜'› (m _ ‹x ∉ s›) have hvs : Disjoint v (insert x s) := disjoint_of_mem_compression_of_not_mem ‹_› (m _ ‹x ∉ s›) have : (insert x s ∪ v) \ u ∈ 𝒜 := sup_sdiff_mem_of_mem_compression_of_not_mem ‹_› (m _ ‹x ∉ s›) have hsv : Disjoint s v := hvs.symm.mono_left (subset_insert _ _) have hvu : Disjoint v u := disjoint_of_subset_right hus hvs have hxv : x ∉ v := disjoint_right.1 hvs (mem_insert_self _ _) have : v \ u = v := ‹Disjoint v u›.sdiff_eq_left -- The first key part is that `x ∉ u` have : x ∉ u := by intro hxu obtain ⟨y, hyv, hxy⟩ := huv x hxu -- If `x ∈ u`, we can get `y ∈ v` so that `𝒜` is `(u.erase x, v.erase y)`-compressed apply m y (disjoint_right.1 hsv hyv) -- and we will use this `y` to contradict `m`, so we would like to show `insert y s ∈ 𝒜`. -- We do this by showing the below have : ((insert x s ∪ v) \ u ∪ erase u x) \ erase v y ∈ 𝒜 := by refine sup_sdiff_mem_of_mem_compression (by rwa [hxy.eq]) ?_ (disjoint_of_subset_left (erase_subset _ _) disjoint_sdiff) rw [union_sdiff_distrib, ‹v \ u = v›] exact (erase_subset _ _).trans subset_union_right -- and then arguing that it's the same convert this using 1 rw [sdiff_union_erase_cancel (hus.trans subset_union_left) ‹x ∈ u›, erase_union_distrib, erase_insert ‹x ∉ s›, erase_eq_of_not_mem ‹x ∉ v›, sdiff_erase (mem_union_right _ hyv), union_sdiff_cancel_right hsv] -- Now that this is done, it's immediate that `u ⊆ s` have hus : u ⊆ s := by rwa [← erase_eq_of_not_mem ‹x ∉ u›, ← subset_insert_iff] -- and we already had that `v` and `s` are disjoint, -- so it only remains to get `(s ∪ v) \ u ∈ ∂ 𝒜 \ ∂ 𝒜'` simp_rw [mem_shadow_iff_insert_mem] refine ⟨hus, hsv.symm, ⟨x, ?_, ?_⟩, ?_⟩ -- `(s ∪ v) \ u ∈ ∂ 𝒜` is pretty direct: · exact not_mem_sdiff_of_not_mem_left (not_mem_union.2 ⟨‹x ∉ s›, ‹x ∉ v›⟩) · rwa [← insert_sdiff_of_not_mem _ ‹x ∉ u›, ← insert_union] -- For (s ∪ v) \ u ∉ ∂ 𝒜', we split up based on w ∈ u rintro ⟨w, hwB, hw𝒜'⟩ have : v ⊆ insert w ((s ∪ v) \ u) := (subset_sdiff.2 ⟨subset_union_right, hvu⟩).trans (subset_insert _ _) by_cases hwu : w ∈ u -- If `w ∈ u`, we find `z ∈ v`, and contradict `m` again · obtain ⟨z, hz, hxy⟩ := huv w hwu apply m z (disjoint_right.1 hsv hz) have : insert w ((s ∪ v) \ u) ∈ 𝒜 := mem_of_mem_compression hw𝒜' ‹_› (aux huv) have : (insert w ((s ∪ v) \ u) ∪ erase u w) \ erase v z ∈ 𝒜 := by refine sup_sdiff_mem_of_mem_compression (by rwa [hxy.eq]) ((erase_subset _ _).trans ‹_›) ?_ rw [← sdiff_erase (mem_union_left _ <| hus hwu)] exact disjoint_sdiff convert this using 1 rw [insert_union_comm, insert_erase ‹w ∈ u›, sdiff_union_of_subset (hus.trans subset_union_left), sdiff_erase (mem_union_right _ ‹z ∈ v›), union_sdiff_cancel_right hsv] -- If `w ∉ u`, we contradict `m` again rw [mem_sdiff, ← Classical.not_imp, Classical.not_not] at hwB apply m w (hwu ∘ hwB ∘ mem_union_left _) have : (insert w ((s ∪ v) \ u) ∪ u) \ v ∈ 𝒜 := sup_sdiff_mem_of_mem_compression ‹insert w ((s ∪ v) \ u) ∈ 𝒜'› ‹_› (disjoint_insert_right.2 ⟨‹_›, disjoint_sdiff⟩) convert this using 1 rw [insert_union, sdiff_union_of_subset (hus.trans subset_union_left), insert_sdiff_of_not_mem _ (hwu ∘ hwB ∘ mem_union_right _), union_sdiff_cancel_right hsv] /-- UV-compression reduces the size of the shadow of `𝒜` if, for all `x ∈ u` there is `y ∈ v` such that `𝒜` is `(u.erase x, v.erase y)`-compressed. This is the key UV-compression fact needed for Kruskal-Katona. -/ theorem card_shadow_compression_le (u v : Finset α) (huv : ∀ x ∈ u, ∃ y ∈ v, IsCompressed (u.erase x) (v.erase y) 𝒜) : (∂ (𝓒 u v 𝒜)).card ≤ (∂ 𝒜).card := (card_le_card <| shadow_compression_subset_compression_shadow _ _ huv).trans (card_compression _ _ _).le end UV
Combinatorics\SimpleGraph\Acyclic.lean
/- Copyright (c) 2022 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import Mathlib.Combinatorics.SimpleGraph.Path import Mathlib.Tactic.Linarith /-! # Acyclic graphs and trees This module introduces *acyclic graphs* (a.k.a. *forests*) and *trees*. ## Main definitions * `SimpleGraph.IsAcyclic` is a predicate for a graph having no cyclic walks * `SimpleGraph.IsTree` is a predicate for a graph being a tree (a connected acyclic graph) ## Main statements * `SimpleGraph.isAcyclic_iff_path_unique` characterizes acyclicity in terms of uniqueness of paths between pairs of vertices. * `SimpleGraph.isAcyclic_iff_forall_edge_isBridge` characterizes acyclicity in terms of every edge being a bridge edge. * `SimpleGraph.isTree_iff_existsUnique_path` characterizes trees in terms of existence and uniqueness of paths between pairs of vertices from a nonempty vertex type. ## References The structure of the proofs for `SimpleGraph.IsAcyclic` and `SimpleGraph.IsTree`, including supporting lemmas about `SimpleGraph.IsBridge`, generally follows the high-level description for these theorems for multigraphs from [Chou1994]. ## Tags acyclic graphs, trees -/ universe u v namespace SimpleGraph open Walk variable {V : Type u} (G : SimpleGraph V) /-- A graph is *acyclic* (or a *forest*) if it has no cycles. -/ def IsAcyclic : Prop := ∀ ⦃v : V⦄ (c : G.Walk v v), ¬c.IsCycle /-- A *tree* is a connected acyclic graph. -/ @[mk_iff] structure IsTree : Prop where /-- Graph is connected. -/ protected isConnected : G.Connected /-- Graph is acyclic. -/ protected IsAcyclic : G.IsAcyclic variable {G} @[simp] lemma isAcyclic_bot : IsAcyclic (⊥ : SimpleGraph V) := fun _a _w hw ↦ hw.ne_bot rfl theorem isAcyclic_iff_forall_adj_isBridge : G.IsAcyclic ↔ ∀ ⦃v w : V⦄, G.Adj v w → G.IsBridge s(v, w) := by simp_rw [isBridge_iff_adj_and_forall_cycle_not_mem] constructor · intro ha v w hvw apply And.intro hvw intro u p hp cases ha p hp · rintro hb v (_ | ⟨ha, p⟩) hp · exact hp.not_of_nil · apply (hb ha).2 _ hp rw [Walk.edges_cons] apply List.mem_cons_self theorem isAcyclic_iff_forall_edge_isBridge : G.IsAcyclic ↔ ∀ ⦃e⦄, e ∈ (G.edgeSet) → G.IsBridge e := by simp [isAcyclic_iff_forall_adj_isBridge, Sym2.forall] theorem IsAcyclic.path_unique {G : SimpleGraph V} (h : G.IsAcyclic) {v w : V} (p q : G.Path v w) : p = q := by obtain ⟨p, hp⟩ := p obtain ⟨q, hq⟩ := q rw [Subtype.mk.injEq] induction p with | nil => cases (Walk.isPath_iff_eq_nil _).mp hq rfl | cons ph p ih => rw [isAcyclic_iff_forall_adj_isBridge] at h specialize h ph rw [isBridge_iff_adj_and_forall_walk_mem_edges] at h replace h := h.2 (q.append p.reverse) simp only [Walk.edges_append, Walk.edges_reverse, List.mem_append, List.mem_reverse] at h cases' h with h h · cases q with | nil => simp [Walk.isPath_def] at hp | cons _ q => rw [Walk.cons_isPath_iff] at hp hq simp only [Walk.edges_cons, List.mem_cons, Sym2.eq_iff, true_and] at h rcases h with (⟨h, rfl⟩ | ⟨rfl, rfl⟩) | h · cases ih hp.1 q hq.1 rfl · simp at hq · exact absurd (Walk.fst_mem_support_of_mem_edges _ h) hq.2 · rw [Walk.cons_isPath_iff] at hp exact absurd (Walk.fst_mem_support_of_mem_edges _ h) hp.2 theorem isAcyclic_of_path_unique (h : ∀ (v w : V) (p q : G.Path v w), p = q) : G.IsAcyclic := by intro v c hc simp only [Walk.isCycle_def, Ne] at hc cases c with | nil => cases hc.2.1 rfl | cons ha c' => simp only [Walk.cons_isTrail_iff, Walk.support_cons, List.tail_cons, true_and_iff] at hc specialize h _ _ ⟨c', by simp only [Walk.isPath_def, hc.2]⟩ (Path.singleton ha.symm) rw [Path.singleton, Subtype.mk.injEq] at h simp [h] at hc theorem isAcyclic_iff_path_unique : G.IsAcyclic ↔ ∀ ⦃v w : V⦄ (p q : G.Path v w), p = q := ⟨IsAcyclic.path_unique, isAcyclic_of_path_unique⟩ theorem isTree_iff_existsUnique_path : G.IsTree ↔ Nonempty V ∧ ∀ v w : V, ∃! p : G.Walk v w, p.IsPath := by classical rw [isTree_iff, isAcyclic_iff_path_unique] constructor · rintro ⟨hc, hu⟩ refine ⟨hc.nonempty, ?_⟩ intro v w let q := (hc v w).some.toPath use q simp only [true_and_iff, Path.isPath] intro p hp specialize hu ⟨p, hp⟩ q exact Subtype.ext_iff.mp hu · rintro ⟨hV, h⟩ refine ⟨Connected.mk ?_, ?_⟩ · intro v w obtain ⟨p, _⟩ := h v w exact p.reachable · rintro v w ⟨p, hp⟩ ⟨q, hq⟩ simp only [ExistsUnique.unique (h v w) hp hq] lemma IsTree.existsUnique_path (hG : G.IsTree) : ∀ v w, ∃! p : G.Walk v w, p.IsPath := (isTree_iff_existsUnique_path.1 hG).2 lemma IsTree.card_edgeFinset [Fintype V] [Fintype G.edgeSet] (hG : G.IsTree) : Finset.card G.edgeFinset + 1 = Fintype.card V := by have := hG.isConnected.nonempty inhabit V classical have : Finset.card ({default} : Finset V)ᶜ + 1 = Fintype.card V := by rw [Finset.card_compl, Finset.card_singleton, Nat.sub_add_cancel Fintype.card_pos] rw [← this, add_left_inj] choose f hf hf' using (hG.existsUnique_path · default) refine Eq.symm <| Finset.card_bij (fun w hw => ((f w).firstDart <| ?notNil).edge) (fun a ha => ?memEdges) ?inj ?surj case notNil => exact not_nil_of_ne (by simpa using hw) case memEdges => simp case inj => intros a ha b hb h wlog h' : (f a).length ≤ (f b).length generalizing a b · exact Eq.symm (this _ hb _ ha h.symm (le_of_not_le h')) rw [dart_edge_eq_iff] at h obtain (h | h) := h · exact (congrArg (·.fst) h) · have h1 : ((f a).firstDart <| not_nil_of_ne (by simpa using ha)).snd = b := congrArg (·.snd) h have h3 := congrArg length (hf' _ (((f _).tail _).copy h1 rfl) ?_) · rw [length_copy, ← add_left_inj 1, length_tail_add_one] at h3 omega · simp only [ne_eq, eq_mp_eq_cast, id_eq, isPath_copy] exact (hf _).tail _ case surj => simp only [mem_edgeFinset, Finset.mem_compl, Finset.mem_singleton, Sym2.forall, mem_edgeSet] intros x y h wlog h' : (f x).length ≤ (f y).length generalizing x y · rw [Sym2.eq_swap] exact this y x h.symm (le_of_not_le h') refine ⟨y, ?_, dart_edge_eq_mk'_iff.2 <| Or.inr ?_⟩ · rintro rfl rw [← hf' _ nil IsPath.nil, length_nil, ← hf' _ (.cons h .nil) (IsPath.nil.cons <| by simpa using h.ne), length_cons, length_nil] at h' simp [Nat.le_zero, Nat.one_ne_zero] at h' rw [← hf' _ (.cons h.symm (f x)) ((cons_isPath_iff _ _).2 ⟨hf _, fun hy => ?contra⟩)] · rfl case contra => suffices (f x).takeUntil y hy = .cons h .nil by rw [← take_spec _ hy] at h' simp [this, hf' _ _ ((hf _).dropUntil hy)] at h' refine (hG.existsUnique_path _ _).unique ((hf _).takeUntil _) ?_ simp [h.ne] end SimpleGraph
Combinatorics\SimpleGraph\AdjMatrix.lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jalex Stark, Kyle Miller, Lu-Ming Zhang -/ import Mathlib.Combinatorics.SimpleGraph.Basic import Mathlib.Combinatorics.SimpleGraph.Connectivity.WalkCounting import Mathlib.LinearAlgebra.Matrix.Trace import Mathlib.LinearAlgebra.Matrix.Symmetric /-! # Adjacency Matrices This module defines the adjacency matrix of a graph, and provides theorems connecting graph properties to computational properties of the matrix. ## Main definitions * `Matrix.IsAdjMatrix`: `A : Matrix V V α` is qualified as an "adjacency matrix" if (1) every entry of `A` is `0` or `1`, (2) `A` is symmetric, (3) every diagonal entry of `A` is `0`. * `Matrix.IsAdjMatrix.to_graph`: for `A : Matrix V V α` and `h : A.IsAdjMatrix`, `h.to_graph` is the simple graph induced by `A`. * `Matrix.compl`: for `A : Matrix V V α`, `A.compl` is supposed to be the adjacency matrix of the complement graph of the graph induced by `A`. * `SimpleGraph.adjMatrix`: the adjacency matrix of a `SimpleGraph`. * `SimpleGraph.adjMatrix_pow_apply_eq_card_walk`: each entry of the `n`th power of a graph's adjacency matrix counts the number of length-`n` walks between the corresponding pair of vertices. -/ open Matrix open Finset Matrix SimpleGraph variable {V α β : Type*} namespace Matrix /-- `A : Matrix V V α` is qualified as an "adjacency matrix" if (1) every entry of `A` is `0` or `1`, (2) `A` is symmetric, (3) every diagonal entry of `A` is `0`. -/ structure IsAdjMatrix [Zero α] [One α] (A : Matrix V V α) : Prop where zero_or_one : ∀ i j, A i j = 0 ∨ A i j = 1 := by aesop symm : A.IsSymm := by aesop apply_diag : ∀ i, A i i = 0 := by aesop namespace IsAdjMatrix variable {A : Matrix V V α} @[simp] theorem apply_diag_ne [MulZeroOneClass α] [Nontrivial α] (h : IsAdjMatrix A) (i : V) : ¬A i i = 1 := by simp [h.apply_diag i] @[simp] theorem apply_ne_one_iff [MulZeroOneClass α] [Nontrivial α] (h : IsAdjMatrix A) (i j : V) : ¬A i j = 1 ↔ A i j = 0 := by obtain h | h := h.zero_or_one i j <;> simp [h] @[simp] theorem apply_ne_zero_iff [MulZeroOneClass α] [Nontrivial α] (h : IsAdjMatrix A) (i j : V) : ¬A i j = 0 ↔ A i j = 1 := by rw [← apply_ne_one_iff h, Classical.not_not] /-- For `A : Matrix V V α` and `h : IsAdjMatrix A`, `h.toGraph` is the simple graph whose adjacency matrix is `A`. -/ @[simps] def toGraph [MulZeroOneClass α] [Nontrivial α] (h : IsAdjMatrix A) : SimpleGraph V where Adj i j := A i j = 1 symm i j hij := by simp only; rwa [h.symm.apply i j] loopless i := by simp [h] instance [MulZeroOneClass α] [Nontrivial α] [DecidableEq α] (h : IsAdjMatrix A) : DecidableRel h.toGraph.Adj := by simp only [toGraph] infer_instance end IsAdjMatrix /-- For `A : Matrix V V α`, `A.compl` is supposed to be the adjacency matrix of the complement graph of the graph induced by `A.adjMatrix`. -/ def compl [Zero α] [One α] [DecidableEq α] [DecidableEq V] (A : Matrix V V α) : Matrix V V α := fun i j => ite (i = j) 0 (ite (A i j = 0) 1 0) section Compl variable [DecidableEq α] [DecidableEq V] (A : Matrix V V α) @[simp] theorem compl_apply_diag [Zero α] [One α] (i : V) : A.compl i i = 0 := by simp [compl] @[simp] theorem compl_apply [Zero α] [One α] (i j : V) : A.compl i j = 0 ∨ A.compl i j = 1 := by unfold compl split_ifs <;> simp @[simp] theorem isSymm_compl [Zero α] [One α] (h : A.IsSymm) : A.compl.IsSymm := by ext simp [compl, h.apply, eq_comm] @[simp] theorem isAdjMatrix_compl [Zero α] [One α] (h : A.IsSymm) : IsAdjMatrix A.compl := { symm := by simp [h] } namespace IsAdjMatrix variable {A} @[simp] theorem compl [Zero α] [One α] (h : IsAdjMatrix A) : IsAdjMatrix A.compl := isAdjMatrix_compl A h.symm theorem toGraph_compl_eq [MulZeroOneClass α] [Nontrivial α] (h : IsAdjMatrix A) : h.compl.toGraph = h.toGraphᶜ := by ext v w cases' h.zero_or_one v w with h h <;> by_cases hvw : v = w <;> simp [Matrix.compl, h, hvw] end IsAdjMatrix end Compl end Matrix open Matrix namespace SimpleGraph variable (G : SimpleGraph V) [DecidableRel G.Adj] variable (α) /-- `adjMatrix G α` is the matrix `A` such that `A i j = (1 : α)` if `i` and `j` are adjacent in the simple graph `G`, and otherwise `A i j = 0`. -/ def adjMatrix [Zero α] [One α] : Matrix V V α := of fun i j => if G.Adj i j then (1 : α) else 0 variable {α} -- TODO: set as an equation lemma for `adjMatrix`, see mathlib4#3024 @[simp] theorem adjMatrix_apply (v w : V) [Zero α] [One α] : G.adjMatrix α v w = if G.Adj v w then 1 else 0 := rfl @[simp] theorem transpose_adjMatrix [Zero α] [One α] : (G.adjMatrix α)ᵀ = G.adjMatrix α := by ext simp [adj_comm] @[simp] theorem isSymm_adjMatrix [Zero α] [One α] : (G.adjMatrix α).IsSymm := transpose_adjMatrix G variable (α) /-- The adjacency matrix of `G` is an adjacency matrix. -/ @[simp] theorem isAdjMatrix_adjMatrix [Zero α] [One α] : (G.adjMatrix α).IsAdjMatrix := { zero_or_one := fun i j => by by_cases h : G.Adj i j <;> simp [h] } /-- The graph induced by the adjacency matrix of `G` is `G` itself. -/ theorem toGraph_adjMatrix_eq [MulZeroOneClass α] [Nontrivial α] : (G.isAdjMatrix_adjMatrix α).toGraph = G := by ext simp only [IsAdjMatrix.toGraph_adj, adjMatrix_apply, ite_eq_left_iff, zero_ne_one] apply Classical.not_not variable {α} /-- The sum of the identity, the adjacency matrix, and its complement is the all-ones matrix. -/ theorem one_add_adjMatrix_add_compl_adjMatrix_eq_allOnes [DecidableEq V] [DecidableEq α] [NonAssocSemiring α] : 1 + G.adjMatrix α + (G.adjMatrix α).compl = Matrix.of fun _ _ ↦ 1 := by ext i j unfold Matrix.compl rw [of_apply, add_apply, adjMatrix_apply, add_apply, adjMatrix_apply, one_apply] by_cases h : G.Adj i j · aesop · split_ifs <;> simp_all variable [Fintype V] @[simp] theorem adjMatrix_dotProduct [NonAssocSemiring α] (v : V) (vec : V → α) : dotProduct (G.adjMatrix α v) vec = ∑ u ∈ G.neighborFinset v, vec u := by simp [neighborFinset_eq_filter, dotProduct, sum_filter] @[simp] theorem dotProduct_adjMatrix [NonAssocSemiring α] (v : V) (vec : V → α) : dotProduct vec (G.adjMatrix α v) = ∑ u ∈ G.neighborFinset v, vec u := by simp [neighborFinset_eq_filter, dotProduct, sum_filter, Finset.sum_apply] @[simp] theorem adjMatrix_mulVec_apply [NonAssocSemiring α] (v : V) (vec : V → α) : (G.adjMatrix α *ᵥ vec) v = ∑ u ∈ G.neighborFinset v, vec u := by rw [mulVec, adjMatrix_dotProduct] @[simp] theorem adjMatrix_vecMul_apply [NonAssocSemiring α] (v : V) (vec : V → α) : (vec ᵥ* G.adjMatrix α) v = ∑ u ∈ G.neighborFinset v, vec u := by simp only [← dotProduct_adjMatrix, vecMul] refine congr rfl ?_; ext x rw [← transpose_apply (adjMatrix α G) x v, transpose_adjMatrix] @[simp] theorem adjMatrix_mul_apply [NonAssocSemiring α] (M : Matrix V V α) (v w : V) : (G.adjMatrix α * M) v w = ∑ u ∈ G.neighborFinset v, M u w := by simp [mul_apply, neighborFinset_eq_filter, sum_filter] @[simp] theorem mul_adjMatrix_apply [NonAssocSemiring α] (M : Matrix V V α) (v w : V) : (M * G.adjMatrix α) v w = ∑ u ∈ G.neighborFinset w, M v u := by simp [mul_apply, neighborFinset_eq_filter, sum_filter, adj_comm] variable (α) @[simp] theorem trace_adjMatrix [AddCommMonoid α] [One α] : Matrix.trace (G.adjMatrix α) = 0 := by simp [Matrix.trace] variable {α} theorem adjMatrix_mul_self_apply_self [NonAssocSemiring α] (i : V) : (G.adjMatrix α * G.adjMatrix α) i i = degree G i := by simp [filter_true_of_mem] variable {G} -- @[simp] -- Porting note (#10618): simp can prove this theorem adjMatrix_mulVec_const_apply [NonAssocSemiring α] {a : α} {v : V} : (G.adjMatrix α *ᵥ Function.const _ a) v = G.degree v * a := by simp theorem adjMatrix_mulVec_const_apply_of_regular [NonAssocSemiring α] {d : ℕ} {a : α} (hd : G.IsRegularOfDegree d) {v : V} : (G.adjMatrix α *ᵥ Function.const _ a) v = d * a := by simp [hd v] theorem adjMatrix_pow_apply_eq_card_walk [DecidableEq V] [Semiring α] (n : ℕ) (u v : V) : (G.adjMatrix α ^ n) u v = Fintype.card { p : G.Walk u v | p.length = n } := by rw [card_set_walk_length_eq] induction' n with n ih generalizing u v · obtain rfl | h := eq_or_ne u v <;> simp [finsetWalkLength, *] · simp only [pow_succ', finsetWalkLength, ih, adjMatrix_mul_apply] rw [Finset.card_biUnion] · norm_cast simp only [Nat.cast_sum, card_map, neighborFinset_def] apply Finset.sum_toFinset_eq_subtype -- Disjointness for card_bUnion · rintro ⟨x, hx⟩ - ⟨y, hy⟩ - hxy rw [disjoint_iff_inf_le] intro p hp simp only [inf_eq_inter, mem_inter, mem_map, Function.Embedding.coeFn_mk, exists_prop] at hp obtain ⟨⟨px, _, rfl⟩, ⟨py, hpy, hp⟩⟩ := hp cases hp simp at hxy theorem dotProduct_mulVec_adjMatrix [NonAssocSemiring α] (x y : V → α) : x ⬝ᵥ (G.adjMatrix α).mulVec y = ∑ i : V, ∑ j : V, if G.Adj i j then x i * y j else 0 := by simp only [dotProduct, mulVec, adjMatrix_apply, ite_mul, one_mul, zero_mul, mul_sum, mul_ite, mul_zero] end SimpleGraph namespace Matrix.IsAdjMatrix variable [MulZeroOneClass α] [Nontrivial α] variable {A : Matrix V V α} (h : IsAdjMatrix A) /-- If `A` is qualified as an adjacency matrix, then the adjacency matrix of the graph induced by `A` is itself. -/ theorem adjMatrix_toGraph_eq [DecidableEq α] : h.toGraph.adjMatrix α = A := by ext i j obtain h' | h' := h.zero_or_one i j <;> simp [h'] end Matrix.IsAdjMatrix
Combinatorics\SimpleGraph\Basic.lean
/- Copyright (c) 2020 Aaron Anderson, Jalex Stark, Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jalex Stark, Kyle Miller, Alena Gusakov, Hunter Monroe -/ import Mathlib.Combinatorics.SimpleGraph.Init import Mathlib.Data.Rel import Mathlib.Data.Set.Finite import Mathlib.Data.Sym.Sym2 /-! # Simple graphs This module defines simple graphs on a vertex type `V` as an irreflexive symmetric relation. ## Main definitions * `SimpleGraph` is a structure for symmetric, irreflexive relations * `SimpleGraph.neighborSet` is the `Set` of vertices adjacent to a given vertex * `SimpleGraph.commonNeighbors` is the intersection of the neighbor sets of two given vertices * `SimpleGraph.incidenceSet` is the `Set` of edges containing a given vertex * `CompleteAtomicBooleanAlgebra` instance: Under the subgraph relation, `SimpleGraph` forms a `CompleteAtomicBooleanAlgebra`. In other words, this is the complete lattice of spanning subgraphs of the complete graph. ## TODO * This is the simplest notion of an unoriented graph. This should eventually fit into a more complete combinatorics hierarchy which includes multigraphs and directed graphs. We begin with simple graphs in order to start learning what the combinatorics hierarchy should look like. -/ -- Porting note: using `aesop` for automation -- Porting note: These attributes are needed to use `aesop` as a replacement for `obviously` attribute [aesop norm unfold (rule_sets := [SimpleGraph])] Symmetric attribute [aesop norm unfold (rule_sets := [SimpleGraph])] Irreflexive -- Porting note: a thin wrapper around `aesop` for graph lemmas, modelled on `aesop_cat` /-- A variant of the `aesop` tactic for use in the graph library. Changes relative to standard `aesop`: - We use the `SimpleGraph` rule set in addition to the default rule sets. - We instruct Aesop's `intro` rule to unfold with `default` transparency. - We instruct Aesop to fail if it can't fully solve the goal. This allows us to use `aesop_graph` for auto-params. -/ macro (name := aesop_graph) "aesop_graph" c:Aesop.tactic_clause* : tactic => `(tactic| aesop $c* (config := { introsTransparency? := some .default, terminal := true }) (rule_sets := [$(Lean.mkIdent `SimpleGraph):ident])) /-- Use `aesop_graph?` to pass along a `Try this` suggestion when using `aesop_graph` -/ macro (name := aesop_graph?) "aesop_graph?" c:Aesop.tactic_clause* : tactic => `(tactic| aesop? $c* (config := { introsTransparency? := some .default, terminal := true }) (rule_sets := [$(Lean.mkIdent `SimpleGraph):ident])) /-- A variant of `aesop_graph` which does not fail if it is unable to solve the goal. Use this only for exploration! Nonterminal Aesop is even worse than nonterminal `simp`. -/ macro (name := aesop_graph_nonterminal) "aesop_graph_nonterminal" c:Aesop.tactic_clause* : tactic => `(tactic| aesop $c* (config := { introsTransparency? := some .default, warnOnNonterminal := false }) (rule_sets := [$(Lean.mkIdent `SimpleGraph):ident])) open Finset Function universe u v w /-- A simple graph is an irreflexive symmetric relation `Adj` on a vertex type `V`. The relation describes which pairs of vertices are adjacent. There is exactly one edge for every pair of adjacent vertices; see `SimpleGraph.edgeSet` for the corresponding edge set. -/ @[ext, aesop safe constructors (rule_sets := [SimpleGraph])] structure SimpleGraph (V : Type u) where /-- The adjacency relation of a simple graph. -/ Adj : V → V → Prop symm : Symmetric Adj := by aesop_graph loopless : Irreflexive Adj := by aesop_graph -- Porting note: changed `obviously` to `aesop` in the `structure` initialize_simps_projections SimpleGraph (Adj → adj) /-- Constructor for simple graphs using a symmetric irreflexive boolean function. -/ @[simps] def SimpleGraph.mk' {V : Type u} : {adj : V → V → Bool // (∀ x y, adj x y = adj y x) ∧ (∀ x, ¬ adj x x)} ↪ SimpleGraph V where toFun x := ⟨fun v w ↦ x.1 v w, fun v w ↦ by simp [x.2.1], fun v ↦ by simp [x.2.2]⟩ inj' := by rintro ⟨adj, _⟩ ⟨adj', _⟩ simp only [mk.injEq, Subtype.mk.injEq] intro h funext v w simpa [Bool.coe_iff_coe] using congr_fun₂ h v w /-- We can enumerate simple graphs by enumerating all functions `V → V → Bool` and filtering on whether they are symmetric and irreflexive. -/ instance {V : Type u} [Fintype V] [DecidableEq V] : Fintype (SimpleGraph V) where elems := Finset.univ.map SimpleGraph.mk' complete := by classical rintro ⟨Adj, hs, hi⟩ simp only [mem_map, mem_univ, true_and, Subtype.exists, Bool.not_eq_true] refine ⟨fun v w ↦ Adj v w, ⟨?_, ?_⟩, ?_⟩ · simp [hs.iff] · intro v; simp [hi v] · ext simp /-- Construct the simple graph induced by the given relation. It symmetrizes the relation and makes it irreflexive. -/ def SimpleGraph.fromRel {V : Type u} (r : V → V → Prop) : SimpleGraph V where Adj a b := a ≠ b ∧ (r a b ∨ r b a) symm := fun _ _ ⟨hn, hr⟩ => ⟨hn.symm, hr.symm⟩ loopless := fun _ ⟨hn, _⟩ => hn rfl @[simp] theorem SimpleGraph.fromRel_adj {V : Type u} (r : V → V → Prop) (v w : V) : (SimpleGraph.fromRel r).Adj v w ↔ v ≠ w ∧ (r v w ∨ r w v) := Iff.rfl -- Porting note: attributes needed for `completeGraph` attribute [aesop safe (rule_sets := [SimpleGraph])] Ne.symm attribute [aesop safe (rule_sets := [SimpleGraph])] Ne.irrefl /-- The complete graph on a type `V` is the simple graph with all pairs of distinct vertices adjacent. In `Mathlib`, this is usually referred to as `⊤`. -/ def completeGraph (V : Type u) : SimpleGraph V where Adj := Ne /-- The graph with no edges on a given vertex type `V`. `Mathlib` prefers the notation `⊥`. -/ def emptyGraph (V : Type u) : SimpleGraph V where Adj _ _ := False /-- Two vertices are adjacent in the complete bipartite graph on two vertex types if and only if they are not from the same side. Any bipartite graph may be regarded as a subgraph of one of these. -/ @[simps] def completeBipartiteGraph (V W : Type*) : SimpleGraph (V ⊕ W) where Adj v w := v.isLeft ∧ w.isRight ∨ v.isRight ∧ w.isLeft symm v w := by cases v <;> cases w <;> simp loopless v := by cases v <;> simp namespace SimpleGraph variable {ι : Sort*} {V : Type u} (G : SimpleGraph V) {a b c u v w : V} {e : Sym2 V} @[simp] protected theorem irrefl {v : V} : ¬G.Adj v v := G.loopless v theorem adj_comm (u v : V) : G.Adj u v ↔ G.Adj v u := ⟨fun x => G.symm x, fun x => G.symm x⟩ @[symm] theorem adj_symm (h : G.Adj u v) : G.Adj v u := G.symm h theorem Adj.symm {G : SimpleGraph V} {u v : V} (h : G.Adj u v) : G.Adj v u := G.symm h theorem ne_of_adj (h : G.Adj a b) : a ≠ b := by rintro rfl exact G.irrefl h protected theorem Adj.ne {G : SimpleGraph V} {a b : V} (h : G.Adj a b) : a ≠ b := G.ne_of_adj h protected theorem Adj.ne' {G : SimpleGraph V} {a b : V} (h : G.Adj a b) : b ≠ a := h.ne.symm theorem ne_of_adj_of_not_adj {v w x : V} (h : G.Adj v x) (hn : ¬G.Adj w x) : v ≠ w := fun h' => hn (h' ▸ h) theorem adj_injective : Injective (Adj : SimpleGraph V → V → V → Prop) := fun _ _ => SimpleGraph.ext @[simp] theorem adj_inj {G H : SimpleGraph V} : G.Adj = H.Adj ↔ G = H := adj_injective.eq_iff section Order /-- The relation that one `SimpleGraph` is a subgraph of another. Note that this should be spelled `≤`. -/ def IsSubgraph (x y : SimpleGraph V) : Prop := ∀ ⦃v w : V⦄, x.Adj v w → y.Adj v w instance : LE (SimpleGraph V) := ⟨IsSubgraph⟩ @[simp] theorem isSubgraph_eq_le : (IsSubgraph : SimpleGraph V → SimpleGraph V → Prop) = (· ≤ ·) := rfl /-- The supremum of two graphs `x ⊔ y` has edges where either `x` or `y` have edges. -/ instance : Sup (SimpleGraph V) where sup x y := { Adj := x.Adj ⊔ y.Adj symm := fun v w h => by rwa [Pi.sup_apply, Pi.sup_apply, x.adj_comm, y.adj_comm] } @[simp] theorem sup_adj (x y : SimpleGraph V) (v w : V) : (x ⊔ y).Adj v w ↔ x.Adj v w ∨ y.Adj v w := Iff.rfl /-- The infimum of two graphs `x ⊓ y` has edges where both `x` and `y` have edges. -/ instance : Inf (SimpleGraph V) where inf x y := { Adj := x.Adj ⊓ y.Adj symm := fun v w h => by rwa [Pi.inf_apply, Pi.inf_apply, x.adj_comm, y.adj_comm] } @[simp] theorem inf_adj (x y : SimpleGraph V) (v w : V) : (x ⊓ y).Adj v w ↔ x.Adj v w ∧ y.Adj v w := Iff.rfl /-- We define `Gᶜ` to be the `SimpleGraph V` such that no two adjacent vertices in `G` are adjacent in the complement, and every nonadjacent pair of vertices is adjacent (still ensuring that vertices are not adjacent to themselves). -/ instance hasCompl : HasCompl (SimpleGraph V) where compl G := { Adj := fun v w => v ≠ w ∧ ¬G.Adj v w symm := fun v w ⟨hne, _⟩ => ⟨hne.symm, by rwa [adj_comm]⟩ loopless := fun v ⟨hne, _⟩ => (hne rfl).elim } @[simp] theorem compl_adj (G : SimpleGraph V) (v w : V) : Gᶜ.Adj v w ↔ v ≠ w ∧ ¬G.Adj v w := Iff.rfl /-- The difference of two graphs `x \ y` has the edges of `x` with the edges of `y` removed. -/ instance sdiff : SDiff (SimpleGraph V) where sdiff x y := { Adj := x.Adj \ y.Adj symm := fun v w h => by change x.Adj w v ∧ ¬y.Adj w v; rwa [x.adj_comm, y.adj_comm] } @[simp] theorem sdiff_adj (x y : SimpleGraph V) (v w : V) : (x \ y).Adj v w ↔ x.Adj v w ∧ ¬y.Adj v w := Iff.rfl instance supSet : SupSet (SimpleGraph V) where sSup s := { Adj := fun a b => ∃ G ∈ s, Adj G a b symm := fun a b => Exists.imp fun _ => And.imp_right Adj.symm loopless := by rintro a ⟨G, _, ha⟩ exact ha.ne rfl } instance infSet : InfSet (SimpleGraph V) where sInf s := { Adj := fun a b => (∀ ⦃G⦄, G ∈ s → Adj G a b) ∧ a ≠ b symm := fun _ _ => And.imp (forall₂_imp fun _ _ => Adj.symm) Ne.symm loopless := fun _ h => h.2 rfl } @[simp] theorem sSup_adj {s : Set (SimpleGraph V)} {a b : V} : (sSup s).Adj a b ↔ ∃ G ∈ s, Adj G a b := Iff.rfl @[simp] theorem sInf_adj {s : Set (SimpleGraph V)} : (sInf s).Adj a b ↔ (∀ G ∈ s, Adj G a b) ∧ a ≠ b := Iff.rfl @[simp] theorem iSup_adj {f : ι → SimpleGraph V} : (⨆ i, f i).Adj a b ↔ ∃ i, (f i).Adj a b := by simp [iSup] @[simp] theorem iInf_adj {f : ι → SimpleGraph V} : (⨅ i, f i).Adj a b ↔ (∀ i, (f i).Adj a b) ∧ a ≠ b := by simp [iInf] theorem sInf_adj_of_nonempty {s : Set (SimpleGraph V)} (hs : s.Nonempty) : (sInf s).Adj a b ↔ ∀ G ∈ s, Adj G a b := sInf_adj.trans <| and_iff_left_of_imp <| by obtain ⟨G, hG⟩ := hs exact fun h => (h _ hG).ne theorem iInf_adj_of_nonempty [Nonempty ι] {f : ι → SimpleGraph V} : (⨅ i, f i).Adj a b ↔ ∀ i, (f i).Adj a b := by rw [iInf, sInf_adj_of_nonempty (Set.range_nonempty _), Set.forall_mem_range] /-- For graphs `G`, `H`, `G ≤ H` iff `∀ a b, G.Adj a b → H.Adj a b`. -/ instance distribLattice : DistribLattice (SimpleGraph V) := { show DistribLattice (SimpleGraph V) from adj_injective.distribLattice _ (fun _ _ => rfl) fun _ _ => rfl with le := fun G H => ∀ ⦃a b⦄, G.Adj a b → H.Adj a b } instance completeAtomicBooleanAlgebra : CompleteAtomicBooleanAlgebra (SimpleGraph V) := { SimpleGraph.distribLattice with le := (· ≤ ·) sup := (· ⊔ ·) inf := (· ⊓ ·) compl := HasCompl.compl sdiff := (· \ ·) top := completeGraph V bot := emptyGraph V le_top := fun x v w h => x.ne_of_adj h bot_le := fun x v w h => h.elim sdiff_eq := fun x y => by ext v w refine ⟨fun h => ⟨h.1, ⟨?_, h.2⟩⟩, fun h => ⟨h.1, h.2.2⟩⟩ rintro rfl exact x.irrefl h.1 inf_compl_le_bot := fun G v w h => False.elim <| h.2.2 h.1 top_le_sup_compl := fun G v w hvw => by by_cases h : G.Adj v w · exact Or.inl h · exact Or.inr ⟨hvw, h⟩ sSup := sSup le_sSup := fun s G hG a b hab => ⟨G, hG, hab⟩ sSup_le := fun s G hG a b => by rintro ⟨H, hH, hab⟩ exact hG _ hH hab sInf := sInf sInf_le := fun s G hG a b hab => hab.1 hG le_sInf := fun s G hG a b hab => ⟨fun H hH => hG _ hH hab, hab.ne⟩ iInf_iSup_eq := fun f => by ext; simp [Classical.skolem] } @[simp] theorem top_adj (v w : V) : (⊤ : SimpleGraph V).Adj v w ↔ v ≠ w := Iff.rfl @[simp] theorem bot_adj (v w : V) : (⊥ : SimpleGraph V).Adj v w ↔ False := Iff.rfl @[simp] theorem completeGraph_eq_top (V : Type u) : completeGraph V = ⊤ := rfl @[simp] theorem emptyGraph_eq_bot (V : Type u) : emptyGraph V = ⊥ := rfl @[simps] instance (V : Type u) : Inhabited (SimpleGraph V) := ⟨⊥⟩ instance [Subsingleton V] : Unique (SimpleGraph V) where default := ⊥ uniq G := by ext a b; have := Subsingleton.elim a b; simp [this] instance [Nontrivial V] : Nontrivial (SimpleGraph V) := ⟨⟨⊥, ⊤, fun h ↦ not_subsingleton V ⟨by simpa only [← adj_inj, Function.funext_iff, bot_adj, top_adj, ne_eq, eq_iff_iff, false_iff, not_not] using h⟩⟩⟩ section Decidable variable (V) (H : SimpleGraph V) [DecidableRel G.Adj] [DecidableRel H.Adj] instance Bot.adjDecidable : DecidableRel (⊥ : SimpleGraph V).Adj := inferInstanceAs <| DecidableRel fun _ _ => False instance Sup.adjDecidable : DecidableRel (G ⊔ H).Adj := inferInstanceAs <| DecidableRel fun v w => G.Adj v w ∨ H.Adj v w instance Inf.adjDecidable : DecidableRel (G ⊓ H).Adj := inferInstanceAs <| DecidableRel fun v w => G.Adj v w ∧ H.Adj v w instance Sdiff.adjDecidable : DecidableRel (G \ H).Adj := inferInstanceAs <| DecidableRel fun v w => G.Adj v w ∧ ¬H.Adj v w variable [DecidableEq V] instance Top.adjDecidable : DecidableRel (⊤ : SimpleGraph V).Adj := inferInstanceAs <| DecidableRel fun v w => v ≠ w instance Compl.adjDecidable : DecidableRel (Gᶜ.Adj) := inferInstanceAs <| DecidableRel fun v w => v ≠ w ∧ ¬G.Adj v w end Decidable end Order /-- `G.support` is the set of vertices that form edges in `G`. -/ def support : Set V := Rel.dom G.Adj theorem mem_support {v : V} : v ∈ G.support ↔ ∃ w, G.Adj v w := Iff.rfl theorem support_mono {G G' : SimpleGraph V} (h : G ≤ G') : G.support ⊆ G'.support := Rel.dom_mono h /-- `G.neighborSet v` is the set of vertices adjacent to `v` in `G`. -/ def neighborSet (v : V) : Set V := {w | G.Adj v w} instance neighborSet.memDecidable (v : V) [DecidableRel G.Adj] : DecidablePred (· ∈ G.neighborSet v) := inferInstanceAs <| DecidablePred (Adj G v) section EdgeSet variable {G₁ G₂ : SimpleGraph V} /-- The edges of G consist of the unordered pairs of vertices related by `G.Adj`. This is the order embedding; for the edge set of a particular graph, see `SimpleGraph.edgeSet`. The way `edgeSet` is defined is such that `mem_edgeSet` is proved by `Iff.rfl`. (That is, `s(v, w) ∈ G.edgeSet` is definitionally equal to `G.Adj v w`.) -/ -- Porting note: We need a separate definition so that dot notation works. def edgeSetEmbedding (V : Type*) : SimpleGraph V ↪o Set (Sym2 V) := OrderEmbedding.ofMapLEIff (fun G => Sym2.fromRel G.symm) fun _ _ => ⟨fun h a b => @h s(a, b), fun h e => Sym2.ind @h e⟩ /-- `G.edgeSet` is the edge set for `G`. This is an abbreviation for `edgeSetEmbedding G` that permits dot notation. -/ abbrev edgeSet (G : SimpleGraph V) : Set (Sym2 V) := edgeSetEmbedding V G @[simp] theorem mem_edgeSet : s(v, w) ∈ G.edgeSet ↔ G.Adj v w := Iff.rfl theorem not_isDiag_of_mem_edgeSet : e ∈ edgeSet G → ¬e.IsDiag := Sym2.ind (fun _ _ => Adj.ne) e theorem edgeSet_inj : G₁.edgeSet = G₂.edgeSet ↔ G₁ = G₂ := (edgeSetEmbedding V).eq_iff_eq @[simp] theorem edgeSet_subset_edgeSet : edgeSet G₁ ⊆ edgeSet G₂ ↔ G₁ ≤ G₂ := (edgeSetEmbedding V).le_iff_le @[simp] theorem edgeSet_ssubset_edgeSet : edgeSet G₁ ⊂ edgeSet G₂ ↔ G₁ < G₂ := (edgeSetEmbedding V).lt_iff_lt theorem edgeSet_injective : Injective (edgeSet : SimpleGraph V → Set (Sym2 V)) := (edgeSetEmbedding V).injective alias ⟨_, edgeSet_mono⟩ := edgeSet_subset_edgeSet alias ⟨_, edgeSet_strict_mono⟩ := edgeSet_ssubset_edgeSet attribute [mono] edgeSet_mono edgeSet_strict_mono variable (G₁ G₂) @[simp] theorem edgeSet_bot : (⊥ : SimpleGraph V).edgeSet = ∅ := Sym2.fromRel_bot @[simp] theorem edgeSet_top : (⊤ : SimpleGraph V).edgeSet = {e | ¬e.IsDiag} := Sym2.fromRel_ne @[simp] theorem edgeSet_subset_setOf_not_isDiag : G.edgeSet ⊆ {e | ¬e.IsDiag} := fun _ h => (Sym2.fromRel_irreflexive (sym := G.symm)).mp G.loopless h @[simp] theorem edgeSet_sup : (G₁ ⊔ G₂).edgeSet = G₁.edgeSet ∪ G₂.edgeSet := by ext ⟨x, y⟩ rfl @[simp] theorem edgeSet_inf : (G₁ ⊓ G₂).edgeSet = G₁.edgeSet ∩ G₂.edgeSet := by ext ⟨x, y⟩ rfl @[simp] theorem edgeSet_sdiff : (G₁ \ G₂).edgeSet = G₁.edgeSet \ G₂.edgeSet := by ext ⟨x, y⟩ rfl variable {G G₁ G₂} @[simp] lemma disjoint_edgeSet : Disjoint G₁.edgeSet G₂.edgeSet ↔ Disjoint G₁ G₂ := by rw [Set.disjoint_iff, disjoint_iff_inf_le, ← edgeSet_inf, ← edgeSet_bot, ← Set.le_iff_subset, OrderEmbedding.le_iff_le] @[simp] lemma edgeSet_eq_empty : G.edgeSet = ∅ ↔ G = ⊥ := by rw [← edgeSet_bot, edgeSet_inj] @[simp] lemma edgeSet_nonempty : G.edgeSet.Nonempty ↔ G ≠ ⊥ := by rw [Set.nonempty_iff_ne_empty, edgeSet_eq_empty.ne] /-- This lemma, combined with `edgeSet_sdiff` and `edgeSet_from_edgeSet`, allows proving `(G \ from_edgeSet s).edge_set = G.edgeSet \ s` by `simp`. -/ @[simp] theorem edgeSet_sdiff_sdiff_isDiag (G : SimpleGraph V) (s : Set (Sym2 V)) : G.edgeSet \ (s \ { e | e.IsDiag }) = G.edgeSet \ s := by ext e simp only [Set.mem_diff, Set.mem_setOf_eq, not_and, not_not, and_congr_right_iff] intro h simp only [G.not_isDiag_of_mem_edgeSet h, imp_false] /-- Two vertices are adjacent iff there is an edge between them. The condition `v ≠ w` ensures they are different endpoints of the edge, which is necessary since when `v = w` the existential `∃ (e ∈ G.edgeSet), v ∈ e ∧ w ∈ e` is satisfied by every edge incident to `v`. -/ theorem adj_iff_exists_edge {v w : V} : G.Adj v w ↔ v ≠ w ∧ ∃ e ∈ G.edgeSet, v ∈ e ∧ w ∈ e := by refine ⟨fun _ => ⟨G.ne_of_adj ‹_›, s(v, w), by simpa⟩, ?_⟩ rintro ⟨hne, e, he, hv⟩ rw [Sym2.mem_and_mem_iff hne] at hv subst e rwa [mem_edgeSet] at he theorem adj_iff_exists_edge_coe : G.Adj a b ↔ ∃ e : G.edgeSet, e.val = s(a, b) := by simp only [mem_edgeSet, exists_prop, SetCoe.exists, exists_eq_right, Subtype.coe_mk] variable (G G₁ G₂) theorem edge_other_ne {e : Sym2 V} (he : e ∈ G.edgeSet) {v : V} (h : v ∈ e) : Sym2.Mem.other h ≠ v := by erw [← Sym2.other_spec h, Sym2.eq_swap] at he exact G.ne_of_adj he instance decidableMemEdgeSet [DecidableRel G.Adj] : DecidablePred (· ∈ G.edgeSet) := Sym2.fromRel.decidablePred G.symm instance fintypeEdgeSet [Fintype (Sym2 V)] [DecidableRel G.Adj] : Fintype G.edgeSet := Subtype.fintype _ instance fintypeEdgeSetBot : Fintype (⊥ : SimpleGraph V).edgeSet := by rw [edgeSet_bot] infer_instance instance fintypeEdgeSetSup [DecidableEq V] [Fintype G₁.edgeSet] [Fintype G₂.edgeSet] : Fintype (G₁ ⊔ G₂).edgeSet := by rw [edgeSet_sup] infer_instance instance fintypeEdgeSetInf [DecidableEq V] [Fintype G₁.edgeSet] [Fintype G₂.edgeSet] : Fintype (G₁ ⊓ G₂).edgeSet := by rw [edgeSet_inf] exact Set.fintypeInter _ _ instance fintypeEdgeSetSdiff [DecidableEq V] [Fintype G₁.edgeSet] [Fintype G₂.edgeSet] : Fintype (G₁ \ G₂).edgeSet := by rw [edgeSet_sdiff] exact Set.fintypeDiff _ _ end EdgeSet section FromEdgeSet variable (s : Set (Sym2 V)) /-- `fromEdgeSet` constructs a `SimpleGraph` from a set of edges, without loops. -/ def fromEdgeSet : SimpleGraph V where Adj := Sym2.ToRel s ⊓ Ne symm v w h := ⟨Sym2.toRel_symmetric s h.1, h.2.symm⟩ @[simp] theorem fromEdgeSet_adj : (fromEdgeSet s).Adj v w ↔ s(v, w) ∈ s ∧ v ≠ w := Iff.rfl -- Note: we need to make sure `fromEdgeSet_adj` and this lemma are confluent. -- In particular, both yield `s(u, v) ∈ (fromEdgeSet s).edgeSet` ==> `s(v, w) ∈ s ∧ v ≠ w`. @[simp] theorem edgeSet_fromEdgeSet : (fromEdgeSet s).edgeSet = s \ { e | e.IsDiag } := by ext e exact Sym2.ind (by simp) e @[simp] theorem fromEdgeSet_edgeSet : fromEdgeSet G.edgeSet = G := by ext v w exact ⟨fun h => h.1, fun h => ⟨h, G.ne_of_adj h⟩⟩ @[simp] theorem fromEdgeSet_empty : fromEdgeSet (∅ : Set (Sym2 V)) = ⊥ := by ext v w simp only [fromEdgeSet_adj, Set.mem_empty_iff_false, false_and_iff, bot_adj] @[simp] theorem fromEdgeSet_univ : fromEdgeSet (Set.univ : Set (Sym2 V)) = ⊤ := by ext v w simp only [fromEdgeSet_adj, Set.mem_univ, true_and_iff, top_adj] @[simp] theorem fromEdgeSet_inter (s t : Set (Sym2 V)) : fromEdgeSet (s ∩ t) = fromEdgeSet s ⊓ fromEdgeSet t := by ext v w simp only [fromEdgeSet_adj, Set.mem_inter_iff, Ne, inf_adj] tauto @[simp] theorem fromEdgeSet_union (s t : Set (Sym2 V)) : fromEdgeSet (s ∪ t) = fromEdgeSet s ⊔ fromEdgeSet t := by ext v w simp [Set.mem_union, or_and_right] @[simp] theorem fromEdgeSet_sdiff (s t : Set (Sym2 V)) : fromEdgeSet (s \ t) = fromEdgeSet s \ fromEdgeSet t := by ext v w constructor <;> simp (config := { contextual := true }) @[mono] theorem fromEdgeSet_mono {s t : Set (Sym2 V)} (h : s ⊆ t) : fromEdgeSet s ≤ fromEdgeSet t := by rintro v w simp (config := { contextual := true }) only [fromEdgeSet_adj, Ne, not_false_iff, and_true_iff, and_imp] exact fun vws _ => h vws @[simp] lemma disjoint_fromEdgeSet : Disjoint G (fromEdgeSet s) ↔ Disjoint G.edgeSet s := by conv_rhs => rw [← Set.diff_union_inter s {e : Sym2 V | e.IsDiag}] rw [← disjoint_edgeSet, edgeSet_fromEdgeSet, Set.disjoint_union_right, and_iff_left] exact Set.disjoint_left.2 fun e he he' ↦ not_isDiag_of_mem_edgeSet _ he he'.2 @[simp] lemma fromEdgeSet_disjoint : Disjoint (fromEdgeSet s) G ↔ Disjoint s G.edgeSet := by rw [disjoint_comm, disjoint_fromEdgeSet, disjoint_comm] instance [DecidableEq V] [Fintype s] : Fintype (fromEdgeSet s).edgeSet := by rw [edgeSet_fromEdgeSet s] infer_instance end FromEdgeSet /-! ### Incidence set -/ /-- Set of edges incident to a given vertex, aka incidence set. -/ def incidenceSet (v : V) : Set (Sym2 V) := { e ∈ G.edgeSet | v ∈ e } theorem incidenceSet_subset (v : V) : G.incidenceSet v ⊆ G.edgeSet := fun _ h => h.1 theorem mk'_mem_incidenceSet_iff : s(b, c) ∈ G.incidenceSet a ↔ G.Adj b c ∧ (a = b ∨ a = c) := and_congr_right' Sym2.mem_iff theorem mk'_mem_incidenceSet_left_iff : s(a, b) ∈ G.incidenceSet a ↔ G.Adj a b := and_iff_left <| Sym2.mem_mk_left _ _ theorem mk'_mem_incidenceSet_right_iff : s(a, b) ∈ G.incidenceSet b ↔ G.Adj a b := and_iff_left <| Sym2.mem_mk_right _ _ theorem edge_mem_incidenceSet_iff {e : G.edgeSet} : ↑e ∈ G.incidenceSet a ↔ a ∈ (e : Sym2 V) := and_iff_right e.2 theorem incidenceSet_inter_incidenceSet_subset (h : a ≠ b) : G.incidenceSet a ∩ G.incidenceSet b ⊆ {s(a, b)} := fun _e he => (Sym2.mem_and_mem_iff h).1 ⟨he.1.2, he.2.2⟩ theorem incidenceSet_inter_incidenceSet_of_adj (h : G.Adj a b) : G.incidenceSet a ∩ G.incidenceSet b = {s(a, b)} := by refine (G.incidenceSet_inter_incidenceSet_subset <| h.ne).antisymm ?_ rintro _ (rfl : _ = s(a, b)) exact ⟨G.mk'_mem_incidenceSet_left_iff.2 h, G.mk'_mem_incidenceSet_right_iff.2 h⟩ theorem adj_of_mem_incidenceSet (h : a ≠ b) (ha : e ∈ G.incidenceSet a) (hb : e ∈ G.incidenceSet b) : G.Adj a b := by rwa [← mk'_mem_incidenceSet_left_iff, ← Set.mem_singleton_iff.1 <| G.incidenceSet_inter_incidenceSet_subset h ⟨ha, hb⟩] theorem incidenceSet_inter_incidenceSet_of_not_adj (h : ¬G.Adj a b) (hn : a ≠ b) : G.incidenceSet a ∩ G.incidenceSet b = ∅ := by simp_rw [Set.eq_empty_iff_forall_not_mem, Set.mem_inter_iff, not_and] intro u ha hb exact h (G.adj_of_mem_incidenceSet hn ha hb) instance decidableMemIncidenceSet [DecidableEq V] [DecidableRel G.Adj] (v : V) : DecidablePred (· ∈ G.incidenceSet v) := inferInstanceAs <| DecidablePred fun e => e ∈ G.edgeSet ∧ v ∈ e @[simp] theorem mem_neighborSet (v w : V) : w ∈ G.neighborSet v ↔ G.Adj v w := Iff.rfl lemma not_mem_neighborSet_self : a ∉ G.neighborSet a := by simp @[simp] theorem mem_incidenceSet (v w : V) : s(v, w) ∈ G.incidenceSet v ↔ G.Adj v w := by simp [incidenceSet] theorem mem_incidence_iff_neighbor {v w : V} : s(v, w) ∈ G.incidenceSet v ↔ w ∈ G.neighborSet v := by simp only [mem_incidenceSet, mem_neighborSet] theorem adj_incidenceSet_inter {v : V} {e : Sym2 V} (he : e ∈ G.edgeSet) (h : v ∈ e) : G.incidenceSet v ∩ G.incidenceSet (Sym2.Mem.other h) = {e} := by ext e' simp only [incidenceSet, Set.mem_sep_iff, Set.mem_inter_iff, Set.mem_singleton_iff] refine ⟨fun h' => ?_, ?_⟩ · rw [← Sym2.other_spec h] exact (Sym2.mem_and_mem_iff (edge_other_ne G he h).symm).mp ⟨h'.1.2, h'.2.2⟩ · rintro rfl exact ⟨⟨he, h⟩, he, Sym2.other_mem _⟩ theorem compl_neighborSet_disjoint (G : SimpleGraph V) (v : V) : Disjoint (G.neighborSet v) (Gᶜ.neighborSet v) := by rw [Set.disjoint_iff] rintro w ⟨h, h'⟩ rw [mem_neighborSet, compl_adj] at h' exact h'.2 h theorem neighborSet_union_compl_neighborSet_eq (G : SimpleGraph V) (v : V) : G.neighborSet v ∪ Gᶜ.neighborSet v = {v}ᶜ := by ext w have h := @ne_of_adj _ G simp_rw [Set.mem_union, mem_neighborSet, compl_adj, Set.mem_compl_iff, Set.mem_singleton_iff] tauto theorem card_neighborSet_union_compl_neighborSet [Fintype V] (G : SimpleGraph V) (v : V) [Fintype (G.neighborSet v ∪ Gᶜ.neighborSet v : Set V)] : (Set.toFinset (G.neighborSet v ∪ Gᶜ.neighborSet v)).card = Fintype.card V - 1 := by classical simp_rw [neighborSet_union_compl_neighborSet_eq, Set.toFinset_compl, Finset.card_compl, Set.toFinset_card, Set.card_singleton] theorem neighborSet_compl (G : SimpleGraph V) (v : V) : Gᶜ.neighborSet v = (G.neighborSet v)ᶜ \ {v} := by ext w simp [and_comm, eq_comm] /-- The set of common neighbors between two vertices `v` and `w` in a graph `G` is the intersection of the neighbor sets of `v` and `w`. -/ def commonNeighbors (v w : V) : Set V := G.neighborSet v ∩ G.neighborSet w theorem commonNeighbors_eq (v w : V) : G.commonNeighbors v w = G.neighborSet v ∩ G.neighborSet w := rfl theorem mem_commonNeighbors {u v w : V} : u ∈ G.commonNeighbors v w ↔ G.Adj v u ∧ G.Adj w u := Iff.rfl theorem commonNeighbors_symm (v w : V) : G.commonNeighbors v w = G.commonNeighbors w v := Set.inter_comm _ _ theorem not_mem_commonNeighbors_left (v w : V) : v ∉ G.commonNeighbors v w := fun h => ne_of_adj G h.1 rfl theorem not_mem_commonNeighbors_right (v w : V) : w ∉ G.commonNeighbors v w := fun h => ne_of_adj G h.2 rfl theorem commonNeighbors_subset_neighborSet_left (v w : V) : G.commonNeighbors v w ⊆ G.neighborSet v := Set.inter_subset_left theorem commonNeighbors_subset_neighborSet_right (v w : V) : G.commonNeighbors v w ⊆ G.neighborSet w := Set.inter_subset_right instance decidableMemCommonNeighbors [DecidableRel G.Adj] (v w : V) : DecidablePred (· ∈ G.commonNeighbors v w) := inferInstanceAs <| DecidablePred fun u => u ∈ G.neighborSet v ∧ u ∈ G.neighborSet w theorem commonNeighbors_top_eq {v w : V} : (⊤ : SimpleGraph V).commonNeighbors v w = Set.univ \ {v, w} := by ext u simp [commonNeighbors, eq_comm, not_or] section Incidence variable [DecidableEq V] /-- Given an edge incident to a particular vertex, get the other vertex on the edge. -/ def otherVertexOfIncident {v : V} {e : Sym2 V} (h : e ∈ G.incidenceSet v) : V := Sym2.Mem.other' h.2 theorem edge_other_incident_set {v : V} {e : Sym2 V} (h : e ∈ G.incidenceSet v) : e ∈ G.incidenceSet (G.otherVertexOfIncident h) := by use h.1 simp [otherVertexOfIncident, Sym2.other_mem'] theorem incidence_other_prop {v : V} {e : Sym2 V} (h : e ∈ G.incidenceSet v) : G.otherVertexOfIncident h ∈ G.neighborSet v := by cases' h with he hv rwa [← Sym2.other_spec' hv, mem_edgeSet] at he -- Porting note: as a simp lemma this does not apply even to itself theorem incidence_other_neighbor_edge {v w : V} (h : w ∈ G.neighborSet v) : G.otherVertexOfIncident (G.mem_incidence_iff_neighbor.mpr h) = w := Sym2.congr_right.mp (Sym2.other_spec' (G.mem_incidence_iff_neighbor.mpr h).right) /-- There is an equivalence between the set of edges incident to a given vertex and the set of vertices adjacent to the vertex. -/ @[simps] def incidenceSetEquivNeighborSet (v : V) : G.incidenceSet v ≃ G.neighborSet v where toFun e := ⟨G.otherVertexOfIncident e.2, G.incidence_other_prop e.2⟩ invFun w := ⟨s(v, w.1), G.mem_incidence_iff_neighbor.mpr w.2⟩ left_inv x := by simp [otherVertexOfIncident] right_inv := fun ⟨w, hw⟩ => by simp only [mem_neighborSet, Subtype.mk.injEq] exact incidence_other_neighbor_edge _ hw end Incidence /-! ## Edge deletion -/ section deleteEdges /-- Given a set of vertex pairs, remove all of the corresponding edges from the graph's edge set, if present. See also: `SimpleGraph.Subgraph.deleteEdges`. -/ def deleteEdges (s : Set (Sym2 V)) : SimpleGraph V := G \ fromEdgeSet s variable {G} {H : SimpleGraph V} {s s₁ s₂ : Set (Sym2 V)} @[simp] lemma deleteEdges_adj : (G.deleteEdges s).Adj v w ↔ G.Adj v w ∧ ¬s(v, w) ∈ s := and_congr_right fun h ↦ (and_iff_left h.ne).not @[simp] lemma deleteEdges_edgeSet (G G' : SimpleGraph V) : G.deleteEdges G'.edgeSet = G \ G' := by ext; simp @[simp] theorem deleteEdges_deleteEdges (s s' : Set (Sym2 V)) : (G.deleteEdges s).deleteEdges s' = G.deleteEdges (s ∪ s') := by simp [deleteEdges, sdiff_sdiff] @[simp] lemma deleteEdges_empty : G.deleteEdges ∅ = G := by simp [deleteEdges] @[simp] lemma deleteEdges_univ : G.deleteEdges Set.univ = ⊥ := by simp [deleteEdges] lemma deleteEdges_le (s : Set (Sym2 V)) : G.deleteEdges s ≤ G := sdiff_le lemma deleteEdges_anti (h : s₁ ⊆ s₂) : G.deleteEdges s₂ ≤ G.deleteEdges s₁ := sdiff_le_sdiff_left $ fromEdgeSet_mono h lemma deleteEdges_mono (h : G ≤ H) : G.deleteEdges s ≤ H.deleteEdges s := sdiff_le_sdiff_right h @[simp] lemma deleteEdges_eq_self : G.deleteEdges s = G ↔ Disjoint G.edgeSet s := by rw [deleteEdges, sdiff_eq_left, disjoint_fromEdgeSet] theorem deleteEdges_eq_inter_edgeSet (s : Set (Sym2 V)) : G.deleteEdges s = G.deleteEdges (s ∩ G.edgeSet) := by ext simp (config := { contextual := true }) [imp_false] theorem deleteEdges_sdiff_eq_of_le {H : SimpleGraph V} (h : H ≤ G) : G.deleteEdges (G.edgeSet \ H.edgeSet) = H := by rw [← edgeSet_sdiff, deleteEdges_edgeSet, sdiff_sdiff_eq_self h] theorem edgeSet_deleteEdges (s : Set (Sym2 V)) : (G.deleteEdges s).edgeSet = G.edgeSet \ s := by simp [deleteEdges] end deleteEdges end SimpleGraph
Combinatorics\SimpleGraph\Circulant.lean
/- Copyright (c) 2024 Iván Renison, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Iván Renison, Bhavik Mehta -/ import Mathlib.Combinatorics.SimpleGraph.Hasse import Mathlib.Data.Set.Pointwise.Basic /-! # Definition of circulant graphs This file defines and proves several fact about circulant graphs. A circulant graph over type `G` with jumps `s : Set G` is a graph in which two vertices `u` and `v` are adjacent if and only if `u - v ∈ s` or `v - u ∈ s`. The elements of `s` are called jumps. ## Main declarations * `SimpleGraph.circulantGraph s`: the circulant graph over `G` with jumps `s`. * `SimpleGraph.cycleGraph n`: the cycle graph over `Fin n`. -/ namespace SimpleGraph /-- Circulant graph over additive group `G` with jumps `s` -/ @[simps!] def circulantGraph {G : Type*} [AddGroup G] (s : Set G) : SimpleGraph G := fromRel (· - · ∈ s) variable {G : Type*} [AddGroup G] (s : Set G) theorem circulantGraph_eq_erase_zero : circulantGraph s = circulantGraph (s \ {0}) := by ext (u v : G) simp only [circulantGraph, fromRel_adj, and_congr_right_iff] intro (h : u ≠ v) apply Iff.intro · intro h1 cases h1 with | inl h1 => exact Or.inl ⟨h1, sub_ne_zero_of_ne h⟩ | inr h1 => exact Or.inr ⟨h1, sub_ne_zero_of_ne h.symm⟩ · intro h1 cases h1 with | inl h1 => exact Or.inl h1.left | inr h1 => exact Or.inr h1.left theorem circulantGraph_eq_symm : circulantGraph s = circulantGraph (s ∪ (-s)) := by ext (u v : G) simp only [circulantGraph, fromRel_adj, Set.mem_union, Set.mem_neg, neg_sub, and_congr_right_iff, iff_self_or] intro _ h exact Or.symm h instance [DecidableEq G] [DecidablePred (· ∈ s)] : DecidableRel (circulantGraph s).Adj := fun _ _ => inferInstanceAs (Decidable (_ ∧ _)) theorem circulantGraph_adj_translate {s : Set G} {u v d : G} : (circulantGraph s).Adj (u + d) (v + d) ↔ (circulantGraph s).Adj u v := by simp /-- Cycle graph over `Fin n` -/ def cycleGraph : (n : ℕ) → SimpleGraph (Fin n) | 0 => ⊥ | _ + 1 => circulantGraph {1} instance : (n : ℕ) → DecidableRel (cycleGraph n).Adj | 0 => fun _ _ => inferInstanceAs (Decidable False) | _ + 1 => inferInstanceAs (DecidableRel (circulantGraph _).Adj) theorem cycleGraph_zero_adj {u v : Fin 0} : ¬(cycleGraph 0).Adj u v := id theorem cycleGraph_zero_eq_bot : cycleGraph 0 = ⊥ := Subsingleton.elim _ _ theorem cycleGraph_one_eq_bot : cycleGraph 1 = ⊥ := Subsingleton.elim _ _ theorem cycleGraph_zero_eq_top : cycleGraph 0 = ⊤ := Subsingleton.elim _ _ theorem cycleGraph_one_eq_top : cycleGraph 1 = ⊤ := Subsingleton.elim _ _ theorem cycleGraph_two_eq_top : cycleGraph 2 = ⊤ := by simp only [SimpleGraph.ext_iff, Function.funext_iff] decide theorem cycleGraph_three_eq_top : cycleGraph 3 = ⊤ := by simp only [SimpleGraph.ext_iff, Function.funext_iff] decide theorem cycleGraph_one_adj {u v : Fin 1} : ¬(cycleGraph 1).Adj u v := by rw [cycleGraph_one_eq_bot] exact id theorem cycleGraph_adj {n : ℕ} {u v : Fin (n + 2)} : (cycleGraph (n + 2)).Adj u v ↔ u - v = 1 ∨ v - u = 1 := by simp only [cycleGraph, circulantGraph_adj, Set.mem_singleton_iff, and_iff_right_iff_imp] intro _ _ simp_all theorem cycleGraph_adj' {n : ℕ} {u v : Fin n} : (cycleGraph n).Adj u v ↔ (u - v).val = 1 ∨ (v - u).val = 1 := by match n with | 0 => exact u.elim0 | 1 => simp [cycleGraph_one_adj] | n + 2 => simp [cycleGraph_adj, Fin.ext_iff] theorem cycleGraph_neighborSet {n : ℕ} {v : Fin (n + 2)} : (cycleGraph (n + 2)).neighborSet v = {v - 1, v + 1} := by ext w simp only [mem_neighborSet, Set.mem_insert_iff, Set.mem_singleton_iff] rw [cycleGraph_adj, sub_eq_iff_eq_add', sub_eq_iff_eq_add', eq_sub_iff_add_eq, eq_comm] theorem cycleGraph_neighborFinset {n : ℕ} {v : Fin (n + 2)} : (cycleGraph (n + 2)).neighborFinset v = {v - 1, v + 1} := by simp [neighborFinset, cycleGraph_neighborSet] theorem cycleGraph_degree_two_le {n : ℕ} {v : Fin (n + 2)} : (cycleGraph (n + 2)).degree v = Finset.card {v - 1, v + 1} := by rw [SimpleGraph.degree, cycleGraph_neighborFinset] theorem cycleGraph_degree_three_le {n : ℕ} {v : Fin (n + 3)} : (cycleGraph (n + 3)).degree v = 2 := by rw [cycleGraph_degree_two_le, Finset.card_pair] simp only [ne_eq, sub_eq_iff_eq_add, add_assoc v, self_eq_add_right] exact ne_of_beq_false rfl theorem pathGraph_le_cycleGraph {n : ℕ} : pathGraph n ≤ cycleGraph n := by match n with | 0 | 1 => simp | n + 2 => intro u v h rw [pathGraph_adj] at h rw [cycleGraph_adj'] cases h with | inl h | inr h => simp [Fin.coe_sub_iff_le.mpr (Nat.lt_of_succ_le h.le).le, Nat.eq_sub_of_add_eq' h] theorem cycleGraph_preconnected {n : ℕ} : (cycleGraph n).Preconnected := (pathGraph_preconnected n).mono pathGraph_le_cycleGraph theorem cycleGraph_connected {n : ℕ} : (cycleGraph (n + 1)).Connected := (pathGraph_connected n).mono pathGraph_le_cycleGraph end SimpleGraph
Combinatorics\SimpleGraph\Clique.lean
/- Copyright (c) 2022 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import Mathlib.Combinatorics.SimpleGraph.Path import Mathlib.Combinatorics.SimpleGraph.Operations import Mathlib.Data.Finset.Pairwise /-! # Graph cliques This file defines cliques in simple graphs. A clique is a set of vertices that are pairwise adjacent. ## Main declarations * `SimpleGraph.IsClique`: Predicate for a set of vertices to be a clique. * `SimpleGraph.IsNClique`: Predicate for a set of vertices to be an `n`-clique. * `SimpleGraph.cliqueFinset`: Finset of `n`-cliques of a graph. * `SimpleGraph.CliqueFree`: Predicate for a graph to have no `n`-cliques. ## TODO * Clique numbers * Dualise all the API to get independent sets -/ open Finset Fintype Function SimpleGraph.Walk namespace SimpleGraph variable {α β : Type*} (G H : SimpleGraph α) /-! ### Cliques -/ section Clique variable {s t : Set α} /-- A clique in a graph is a set of vertices that are pairwise adjacent. -/ abbrev IsClique (s : Set α) : Prop := s.Pairwise G.Adj theorem isClique_iff : G.IsClique s ↔ s.Pairwise G.Adj := Iff.rfl /-- A clique is a set of vertices whose induced graph is complete. -/ theorem isClique_iff_induce_eq : G.IsClique s ↔ G.induce s = ⊤ := by rw [isClique_iff] constructor · intro h ext ⟨v, hv⟩ ⟨w, hw⟩ simp only [comap_adj, Subtype.coe_mk, top_adj, Ne, Subtype.mk_eq_mk] exact ⟨Adj.ne, h hv hw⟩ · intro h v hv w hw hne have h2 : (G.induce s).Adj ⟨v, hv⟩ ⟨w, hw⟩ = _ := rfl conv_lhs at h2 => rw [h] simp only [top_adj, ne_eq, Subtype.mk.injEq, eq_iff_iff] at h2 exact h2.1 hne instance [DecidableEq α] [DecidableRel G.Adj] {s : Finset α} : Decidable (G.IsClique s) := decidable_of_iff' _ G.isClique_iff variable {G H} {a b : α} lemma isClique_empty : G.IsClique ∅ := by simp lemma isClique_singleton (a : α) : G.IsClique {a} := by simp theorem IsClique.of_subsingleton {G : SimpleGraph α} (hs : s.Subsingleton) : G.IsClique s := hs.pairwise G.Adj lemma isClique_pair : G.IsClique {a, b} ↔ a ≠ b → G.Adj a b := Set.pairwise_pair_of_symmetric G.symm @[simp] lemma isClique_insert : G.IsClique (insert a s) ↔ G.IsClique s ∧ ∀ b ∈ s, a ≠ b → G.Adj a b := Set.pairwise_insert_of_symmetric G.symm lemma isClique_insert_of_not_mem (ha : a ∉ s) : G.IsClique (insert a s) ↔ G.IsClique s ∧ ∀ b ∈ s, G.Adj a b := Set.pairwise_insert_of_symmetric_of_not_mem G.symm ha lemma IsClique.insert (hs : G.IsClique s) (h : ∀ b ∈ s, a ≠ b → G.Adj a b) : G.IsClique (insert a s) := hs.insert_of_symmetric G.symm h theorem IsClique.mono (h : G ≤ H) : G.IsClique s → H.IsClique s := Set.Pairwise.mono' h theorem IsClique.subset (h : t ⊆ s) : G.IsClique s → G.IsClique t := Set.Pairwise.mono h @[simp] theorem isClique_bot_iff : (⊥ : SimpleGraph α).IsClique s ↔ (s : Set α).Subsingleton := Set.pairwise_bot_iff alias ⟨IsClique.subsingleton, _⟩ := isClique_bot_iff protected theorem IsClique.map (h : G.IsClique s) {f : α ↪ β} : (G.map f).IsClique (f '' s) := by rintro _ ⟨a, ha, rfl⟩ _ ⟨b, hb, rfl⟩ hab exact ⟨a, b, h ha hb <| ne_of_apply_ne _ hab, rfl, rfl⟩ theorem isClique_map_iff_of_nontrivial {f : α ↪ β} {t : Set β} (ht : t.Nontrivial) : (G.map f).IsClique t ↔ ∃ (s : Set α), G.IsClique s ∧ f '' s = t := by refine ⟨fun h ↦ ⟨f ⁻¹' t, ?_, ?_⟩, by rintro ⟨x, hs, rfl⟩; exact hs.map⟩ · rintro x (hx : f x ∈ t) y (hy : f y ∈ t) hne obtain ⟨u,v, huv, hux, hvy⟩ := h hx hy (by simpa) rw [EmbeddingLike.apply_eq_iff_eq] at hux hvy rwa [← hux, ← hvy] rw [Set.image_preimage_eq_iff] intro x hxt obtain ⟨y,hyt, hyne⟩ := ht.exists_ne x obtain ⟨u,v, -, rfl, rfl⟩ := h hyt hxt hyne exact Set.mem_range_self _ theorem isClique_map_iff {f : α ↪ β} {t : Set β} : (G.map f).IsClique t ↔ t.Subsingleton ∨ ∃ (s : Set α), G.IsClique s ∧ f '' s = t := by obtain (ht | ht) := t.subsingleton_or_nontrivial · simp [IsClique.of_subsingleton, ht] simp [isClique_map_iff_of_nontrivial ht, ht.not_subsingleton] @[simp] theorem isClique_map_image_iff {f : α ↪ β} : (G.map f).IsClique (f '' s) ↔ G.IsClique s := by rw [isClique_map_iff, f.injective.subsingleton_image_iff] obtain (hs | hs) := s.subsingleton_or_nontrivial · simp [hs, IsClique.of_subsingleton] simp [or_iff_right hs.not_subsingleton, Set.image_eq_image f.injective] variable {f : α ↪ β} {t : Finset β} theorem isClique_map_finset_iff_of_nontrivial (ht : t.Nontrivial) : (G.map f).IsClique t ↔ ∃ (s : Finset α), G.IsClique s ∧ s.map f = t := by constructor · rw [isClique_map_iff_of_nontrivial (by simpa)] rintro ⟨s, hs, hst⟩ obtain ⟨s, rfl⟩ := Set.Finite.exists_finset_coe <| (show s.Finite from Set.Finite.of_finite_image (by simp [hst]) f.injective.injOn) exact ⟨s,hs, Finset.coe_inj.1 (by simpa)⟩ rintro ⟨s, hs, rfl⟩ simpa using hs.map (f := f) theorem isClique_map_finset_iff : (G.map f).IsClique t ↔ t.card ≤ 1 ∨ ∃ (s : Finset α), G.IsClique s ∧ s.map f = t := by obtain (ht | ht) := le_or_lt t.card 1 · simp only [ht, true_or, iff_true] exact IsClique.of_subsingleton <| card_le_one.1 ht rw [isClique_map_finset_iff_of_nontrivial, ← not_lt] · simp [ht, Finset.map_eq_image] exact Finset.one_lt_card_iff_nontrivial.mp ht protected theorem IsClique.finsetMap {f : α ↪ β} {s : Finset α} (h : G.IsClique s) : (G.map f).IsClique (s.map f) := by simpa end Clique /-! ### `n`-cliques -/ section NClique variable {n : ℕ} {s : Finset α} /-- An `n`-clique in a graph is a set of `n` vertices which are pairwise connected. -/ structure IsNClique (n : ℕ) (s : Finset α) : Prop where clique : G.IsClique s card_eq : s.card = n theorem isNClique_iff : G.IsNClique n s ↔ G.IsClique s ∧ s.card = n := ⟨fun h ↦ ⟨h.1, h.2⟩, fun h ↦ ⟨h.1, h.2⟩⟩ instance [DecidableEq α] [DecidableRel G.Adj] {n : ℕ} {s : Finset α} : Decidable (G.IsNClique n s) := decidable_of_iff' _ G.isNClique_iff variable {G H} {a b c : α} @[simp] lemma isNClique_empty : G.IsNClique n ∅ ↔ n = 0 := by simp [isNClique_iff, eq_comm] @[simp] lemma isNClique_singleton : G.IsNClique n {a} ↔ n = 1 := by simp [isNClique_iff, eq_comm] theorem IsNClique.mono (h : G ≤ H) : G.IsNClique n s → H.IsNClique n s := by simp_rw [isNClique_iff] exact And.imp_left (IsClique.mono h) protected theorem IsNClique.map (h : G.IsNClique n s) {f : α ↪ β} : (G.map f).IsNClique n (s.map f) := ⟨by rw [coe_map]; exact h.1.map, (card_map _).trans h.2⟩ theorem isNClique_map_iff (hn : 1 < n) {t : Finset β} {f : α ↪ β} : (G.map f).IsNClique n t ↔ ∃ s : Finset α, G.IsNClique n s ∧ s.map f = t := by rw [isNClique_iff, isClique_map_finset_iff, or_and_right, or_iff_right (by rintro ⟨h', rfl⟩; exact h'.not_lt hn)] constructor · rintro ⟨⟨s, hs, rfl⟩, rfl⟩ simp [isNClique_iff, hs] rintro ⟨s, hs, rfl⟩ simp [hs.card_eq, hs.clique] @[simp] theorem isNClique_bot_iff : (⊥ : SimpleGraph α).IsNClique n s ↔ n ≤ 1 ∧ s.card = n := by rw [isNClique_iff, isClique_bot_iff] refine and_congr_left ?_ rintro rfl exact card_le_one.symm @[simp] theorem isNClique_zero : G.IsNClique 0 s ↔ s = ∅ := by simp only [isNClique_iff, Finset.card_eq_zero, and_iff_right_iff_imp]; rintro rfl; simp @[simp] theorem isNClique_one : G.IsNClique 1 s ↔ ∃ a, s = {a} := by simp only [isNClique_iff, card_eq_one, and_iff_right_iff_imp]; rintro ⟨a, rfl⟩; simp section DecidableEq variable [DecidableEq α] theorem IsNClique.insert (hs : G.IsNClique n s) (h : ∀ b ∈ s, G.Adj a b) : G.IsNClique (n + 1) (insert a s) := by constructor · push_cast exact hs.1.insert fun b hb _ => h _ hb · rw [card_insert_of_not_mem fun ha => (h _ ha).ne rfl, hs.2] theorem is3Clique_triple_iff : G.IsNClique 3 {a, b, c} ↔ G.Adj a b ∧ G.Adj a c ∧ G.Adj b c := by simp only [isNClique_iff, isClique_iff, Set.pairwise_insert_of_symmetric G.symm, coe_insert] by_cases hab : a = b <;> by_cases hbc : b = c <;> by_cases hac : a = c <;> subst_vars <;> simp [G.ne_of_adj, and_rotate, *] theorem is3Clique_iff : G.IsNClique 3 s ↔ ∃ a b c, G.Adj a b ∧ G.Adj a c ∧ G.Adj b c ∧ s = {a, b, c} := by refine ⟨fun h ↦ ?_, ?_⟩ · obtain ⟨a, b, c, -, -, -, hs⟩ := card_eq_three.1 h.card_eq refine ⟨a, b, c, ?_⟩ rwa [hs, eq_self_iff_true, and_true, is3Clique_triple_iff.symm, ← hs] · rintro ⟨a, b, c, hab, hbc, hca, rfl⟩ exact is3Clique_triple_iff.2 ⟨hab, hbc, hca⟩ end DecidableEq theorem is3Clique_iff_exists_cycle_length_three : (∃ s : Finset α, G.IsNClique 3 s) ↔ ∃ (u : α) (w : G.Walk u u), w.IsCycle ∧ w.length = 3 := by classical simp_rw [is3Clique_iff, isCycle_def] exact ⟨(fun ⟨_, a, _, _, hab, hac, hbc, _⟩ => ⟨a, cons hab (cons hbc (cons hac.symm nil)), by aesop⟩), (fun ⟨_, .cons hab (.cons hbc (.cons hca nil)), _, _⟩ => ⟨_, _, _, _, hab, hca.symm, hbc, rfl⟩)⟩ end NClique /-! ### Graphs without cliques -/ section CliqueFree variable {m n : ℕ} /-- `G.CliqueFree n` means that `G` has no `n`-cliques. -/ def CliqueFree (n : ℕ) : Prop := ∀ t, ¬G.IsNClique n t variable {G H} {s : Finset α} theorem IsNClique.not_cliqueFree (hG : G.IsNClique n s) : ¬G.CliqueFree n := fun h ↦ h _ hG theorem not_cliqueFree_of_top_embedding {n : ℕ} (f : (⊤ : SimpleGraph (Fin n)) ↪g G) : ¬G.CliqueFree n := by simp only [CliqueFree, isNClique_iff, isClique_iff_induce_eq, not_forall, Classical.not_not] use Finset.univ.map f.toEmbedding simp only [card_map, Finset.card_fin, eq_self_iff_true, and_true_iff] ext ⟨v, hv⟩ ⟨w, hw⟩ simp only [coe_map, Set.mem_image, coe_univ, Set.mem_univ, true_and_iff] at hv hw obtain ⟨v', rfl⟩ := hv obtain ⟨w', rfl⟩ := hw simp only [coe_sort_coe, RelEmbedding.coe_toEmbedding, comap_adj, Function.Embedding.coe_subtype, f.map_adj_iff, top_adj, ne_eq, Subtype.mk.injEq, RelEmbedding.inj] -- This used to be the end of the proof before leanprover/lean4#2644 erw [Function.Embedding.coe_subtype, f.map_adj_iff] simp /-- An embedding of a complete graph that witnesses the fact that the graph is not clique-free. -/ noncomputable def topEmbeddingOfNotCliqueFree {n : ℕ} (h : ¬G.CliqueFree n) : (⊤ : SimpleGraph (Fin n)) ↪g G := by simp only [CliqueFree, isNClique_iff, isClique_iff_induce_eq, not_forall, Classical.not_not] at h obtain ⟨ha, hb⟩ := h.choose_spec have : (⊤ : SimpleGraph (Fin h.choose.card)) ≃g (⊤ : SimpleGraph h.choose) := by apply Iso.completeGraph simpa using (Fintype.equivFin h.choose).symm rw [← ha] at this convert (Embedding.induce ↑h.choose.toSet).comp this.toEmbedding exact hb.symm theorem not_cliqueFree_iff (n : ℕ) : ¬G.CliqueFree n ↔ Nonempty ((⊤ : SimpleGraph (Fin n)) ↪g G) := ⟨fun h ↦ ⟨topEmbeddingOfNotCliqueFree h⟩, fun ⟨f⟩ ↦ not_cliqueFree_of_top_embedding f⟩ theorem cliqueFree_iff {n : ℕ} : G.CliqueFree n ↔ IsEmpty ((⊤ : SimpleGraph (Fin n)) ↪g G) := by rw [← not_iff_not, not_cliqueFree_iff, not_isEmpty_iff] theorem not_cliqueFree_card_of_top_embedding [Fintype α] (f : (⊤ : SimpleGraph α) ↪g G) : ¬G.CliqueFree (card α) := by rw [not_cliqueFree_iff] exact ⟨(Iso.completeGraph (Fintype.equivFin α)).symm.toEmbedding.trans f⟩ @[simp] theorem cliqueFree_bot (h : 2 ≤ n) : (⊥ : SimpleGraph α).CliqueFree n := by intro t ht have := le_trans h (isNClique_bot_iff.1 ht).1 contradiction theorem CliqueFree.mono (h : m ≤ n) : G.CliqueFree m → G.CliqueFree n := by intro hG s hs obtain ⟨t, hts, ht⟩ := exists_subset_card_eq (h.trans hs.card_eq.ge) exact hG _ ⟨hs.clique.subset hts, ht⟩ theorem CliqueFree.anti (h : G ≤ H) : H.CliqueFree n → G.CliqueFree n := forall_imp fun _ ↦ mt <| IsNClique.mono h /-- If a graph is cliquefree, any graph that embeds into it is also cliquefree. -/ theorem CliqueFree.comap {H : SimpleGraph β} (f : H ↪g G) : G.CliqueFree n → H.CliqueFree n := by intro h; contrapose h exact not_cliqueFree_of_top_embedding <| f.comp (topEmbeddingOfNotCliqueFree h) @[simp] theorem cliqueFree_map_iff {f : α ↪ β} [Nonempty α] : (G.map f).CliqueFree n ↔ G.CliqueFree n := by obtain (hle | hlt) := le_or_lt n 1 · obtain (rfl | rfl) := Nat.le_one_iff_eq_zero_or_eq_one.1 hle · simp [CliqueFree] simp [CliqueFree, show ∃ (_ : β), True from ⟨f (Classical.arbitrary _), trivial⟩] simp [CliqueFree, isNClique_map_iff hlt] /-- See `SimpleGraph.cliqueFree_of_chromaticNumber_lt` for a tighter bound. -/ theorem cliqueFree_of_card_lt [Fintype α] (hc : card α < n) : G.CliqueFree n := by by_contra h refine Nat.lt_le_asymm hc ?_ rw [cliqueFree_iff, not_isEmpty_iff] at h simpa only [Fintype.card_fin] using Fintype.card_le_of_embedding h.some.toEmbedding /-- A complete `r`-partite graph has no `n`-cliques for `r < n`. -/ theorem cliqueFree_completeMultipartiteGraph {ι : Type*} [Fintype ι] (V : ι → Type*) (hc : card ι < n) : (completeMultipartiteGraph V).CliqueFree n := by rw [cliqueFree_iff, isEmpty_iff] intro f obtain ⟨v, w, hn, he⟩ := exists_ne_map_eq_of_card_lt (Sigma.fst ∘ f) (by simp [hc]) rw [← top_adj, ← f.map_adj_iff, comap_adj, top_adj] at hn exact absurd he hn /-- Clique-freeness is preserved by `replaceVertex`. -/ protected theorem CliqueFree.replaceVertex [DecidableEq α] (h : G.CliqueFree n) (s t : α) : (G.replaceVertex s t).CliqueFree n := by contrapose h obtain ⟨φ, hφ⟩ := topEmbeddingOfNotCliqueFree h rw [not_cliqueFree_iff] by_cases mt : t ∈ Set.range φ · obtain ⟨x, hx⟩ := mt by_cases ms : s ∈ Set.range φ · obtain ⟨y, hy⟩ := ms have e := @hφ x y simp_rw [hx, hy, adj_comm, not_adj_replaceVertex_same, top_adj, false_iff, not_ne_iff] at e rwa [← hx, e, hy, replaceVertex_self, not_cliqueFree_iff] at h · unfold replaceVertex at hφ use φ.setValue x s intro a b simp only [Embedding.coeFn_mk, Embedding.setValue, not_exists.mp ms, ite_false] rw [apply_ite (G.Adj · _), apply_ite (G.Adj _ ·), apply_ite (G.Adj _ ·)] convert @hφ a b <;> simp only [← φ.apply_eq_iff_eq, SimpleGraph.irrefl, hx] · use φ simp_rw [Set.mem_range, not_exists, ← ne_eq] at mt conv at hφ => enter [a, b]; rw [G.adj_replaceVertex_iff_of_ne _ (mt a) (mt b)] exact hφ @[simp] theorem cliqueFree_two : G.CliqueFree 2 ↔ G = ⊥ := by classical constructor · simp_rw [← edgeSet_eq_empty, Set.eq_empty_iff_forall_not_mem, Sym2.forall, mem_edgeSet] exact fun h a b hab => h _ ⟨by simpa [hab.ne], card_pair hab.ne⟩ · rintro rfl exact cliqueFree_bot le_rfl /-- Adding an edge increases the clique number by at most one. -/ protected theorem CliqueFree.sup_edge (h : G.CliqueFree n) (v w : α) : (G ⊔ edge v w).CliqueFree (n + 1) := by contrapose h obtain ⟨f, ha⟩ := topEmbeddingOfNotCliqueFree h simp only [ne_eq, top_adj] at ha rw [not_cliqueFree_iff] by_cases mw : w ∈ Set.range f · obtain ⟨x, hx⟩ := mw use ⟨f ∘ x.succAboveEmb, f.2.comp Fin.succAbove_right_injective⟩ intro a b simp_rw [Embedding.coeFn_mk, comp_apply, Fin.succAboveEmb_apply, top_adj] have hs := @ha (x.succAbove a) (x.succAbove b) have ia : w ≠ f (x.succAbove a) := (hx ▸ f.apply_eq_iff_eq x (x.succAbove a)).ne.mpr (x.succAbove_ne a).symm have ib : w ≠ f (x.succAbove b) := (hx ▸ f.apply_eq_iff_eq x (x.succAbove b)).ne.mpr (x.succAbove_ne b).symm rw [sup_adj, edge_adj] at hs simp only [ia.symm, ib.symm, and_false, false_and, or_false] at hs rw [hs, Fin.succAbove_right_inj] · use ⟨f ∘ Fin.succEmb n, (f.2.of_comp_iff _).mpr (Fin.succ_injective _)⟩ intro a b simp only [Fin.val_succEmb, Embedding.coeFn_mk, comp_apply, top_adj] have hs := @ha a.succ b.succ have ia : f a.succ ≠ w := by simp_all have ib : f b.succ ≠ w := by simp_all rw [sup_adj, edge_adj] at hs simp only [ia, ib, and_false, false_and, or_false] at hs rw [hs, Fin.succ_inj] end CliqueFree section CliqueFreeOn variable {s s₁ s₂ : Set α} {t : Finset α} {a b : α} {m n : ℕ} /-- `G.CliqueFreeOn s n` means that `G` has no `n`-cliques contained in `s`. -/ def CliqueFreeOn (G : SimpleGraph α) (s : Set α) (n : ℕ) : Prop := ∀ ⦃t⦄, ↑t ⊆ s → ¬G.IsNClique n t theorem CliqueFreeOn.subset (hs : s₁ ⊆ s₂) (h₂ : G.CliqueFreeOn s₂ n) : G.CliqueFreeOn s₁ n := fun _t hts => h₂ <| hts.trans hs theorem CliqueFreeOn.mono (hmn : m ≤ n) (hG : G.CliqueFreeOn s m) : G.CliqueFreeOn s n := by rintro t hts ht obtain ⟨u, hut, hu⟩ := exists_subset_card_eq (hmn.trans ht.card_eq.ge) exact hG ((coe_subset.2 hut).trans hts) ⟨ht.clique.subset hut, hu⟩ theorem CliqueFreeOn.anti (hGH : G ≤ H) (hH : H.CliqueFreeOn s n) : G.CliqueFreeOn s n := fun _t hts ht => hH hts <| ht.mono hGH @[simp] theorem cliqueFreeOn_empty : G.CliqueFreeOn ∅ n ↔ n ≠ 0 := by simp [CliqueFreeOn, Set.subset_empty_iff] @[simp] theorem cliqueFreeOn_singleton : G.CliqueFreeOn {a} n ↔ 1 < n := by obtain _ | _ | n := n <;> simp [CliqueFreeOn, isNClique_iff, ← subset_singleton_iff', (Nat.succ_ne_zero _).symm] @[simp] theorem cliqueFreeOn_univ : G.CliqueFreeOn Set.univ n ↔ G.CliqueFree n := by simp [CliqueFree, CliqueFreeOn] protected theorem CliqueFree.cliqueFreeOn (hG : G.CliqueFree n) : G.CliqueFreeOn s n := fun _t _ ↦ hG _ theorem cliqueFreeOn_of_card_lt {s : Finset α} (h : s.card < n) : G.CliqueFreeOn s n := fun _t hts ht => h.not_le <| ht.2.symm.trans_le <| card_mono hts -- TODO: Restate using `SimpleGraph.IndepSet` once we have it @[simp] theorem cliqueFreeOn_two : G.CliqueFreeOn s 2 ↔ s.Pairwise (G.Adjᶜ) := by classical refine ⟨fun h a ha b hb _ hab => h ?_ ⟨by simpa [hab.ne], card_pair hab.ne⟩, ?_⟩ · push_cast exact Set.insert_subset_iff.2 ⟨ha, Set.singleton_subset_iff.2 hb⟩ simp only [CliqueFreeOn, isNClique_iff, card_eq_two, coe_subset, not_and, not_exists] rintro h t hst ht a b hab rfl simp only [coe_insert, coe_singleton, Set.insert_subset_iff, Set.singleton_subset_iff] at hst refine h hst.1 hst.2 hab (ht ?_ ?_ hab) <;> simp theorem CliqueFreeOn.of_succ (hs : G.CliqueFreeOn s (n + 1)) (ha : a ∈ s) : G.CliqueFreeOn (s ∩ G.neighborSet a) n := by classical refine fun t hts ht => hs ?_ (ht.insert fun b hb => (hts hb).2) push_cast exact Set.insert_subset_iff.2 ⟨ha, hts.trans Set.inter_subset_left⟩ end CliqueFreeOn /-! ### Set of cliques -/ section CliqueSet variable {n : ℕ} {a b c : α} {s : Finset α} /-- The `n`-cliques in a graph as a set. -/ def cliqueSet (n : ℕ) : Set (Finset α) := { s | G.IsNClique n s } variable {G H} @[simp] theorem mem_cliqueSet_iff : s ∈ G.cliqueSet n ↔ G.IsNClique n s := Iff.rfl @[simp] theorem cliqueSet_eq_empty_iff : G.cliqueSet n = ∅ ↔ G.CliqueFree n := by simp_rw [CliqueFree, Set.eq_empty_iff_forall_not_mem, mem_cliqueSet_iff] protected alias ⟨_, CliqueFree.cliqueSet⟩ := cliqueSet_eq_empty_iff @[mono] theorem cliqueSet_mono (h : G ≤ H) : G.cliqueSet n ⊆ H.cliqueSet n := fun _ ↦ IsNClique.mono h theorem cliqueSet_mono' (h : G ≤ H) : G.cliqueSet ≤ H.cliqueSet := fun _ ↦ cliqueSet_mono h @[simp] theorem cliqueSet_zero (G : SimpleGraph α) : G.cliqueSet 0 = {∅} := Set.ext fun s => by simp @[simp] theorem cliqueSet_one (G : SimpleGraph α) : G.cliqueSet 1 = Set.range singleton := Set.ext fun s => by simp [eq_comm] @[simp] theorem cliqueSet_bot (hn : 1 < n) : (⊥ : SimpleGraph α).cliqueSet n = ∅ := (cliqueFree_bot hn).cliqueSet @[simp] theorem cliqueSet_map (hn : n ≠ 1) (G : SimpleGraph α) (f : α ↪ β) : (G.map f).cliqueSet n = map f '' G.cliqueSet n := by ext s constructor · rintro ⟨hs, rfl⟩ have hs' : (s.preimage f f.injective.injOn).map f = s := by classical rw [map_eq_image, image_preimage, filter_true_of_mem] rintro a ha obtain ⟨b, hb, hba⟩ := exists_mem_ne (hn.lt_of_le' <| Finset.card_pos.2 ⟨a, ha⟩) a obtain ⟨c, _, _, hc, _⟩ := hs ha hb hba.symm exact ⟨c, hc⟩ refine ⟨s.preimage f f.injective.injOn, ⟨?_, by rw [← card_map f, hs']⟩, hs'⟩ rw [coe_preimage] exact fun a ha b hb hab => map_adj_apply.1 (hs ha hb <| f.injective.ne hab) · rintro ⟨s, hs, rfl⟩ exact hs.map @[simp] theorem cliqueSet_map_of_equiv (G : SimpleGraph α) (e : α ≃ β) (n : ℕ) : (G.map e.toEmbedding).cliqueSet n = map e.toEmbedding '' G.cliqueSet n := by obtain rfl | hn := eq_or_ne n 1 · ext simp [e.exists_congr_left] · exact cliqueSet_map hn _ _ end CliqueSet /-! ### Finset of cliques -/ section CliqueFinset variable [Fintype α] [DecidableEq α] [DecidableRel G.Adj] {n : ℕ} {a b c : α} {s : Finset α} /-- The `n`-cliques in a graph as a finset. -/ def cliqueFinset (n : ℕ) : Finset (Finset α) := univ.filter <| G.IsNClique n variable {G} in @[simp] theorem mem_cliqueFinset_iff : s ∈ G.cliqueFinset n ↔ G.IsNClique n s := mem_filter.trans <| and_iff_right <| mem_univ _ @[simp, norm_cast] theorem coe_cliqueFinset (n : ℕ) : (G.cliqueFinset n : Set (Finset α)) = G.cliqueSet n := Set.ext fun _ ↦ mem_cliqueFinset_iff variable {G} @[simp] theorem cliqueFinset_eq_empty_iff : G.cliqueFinset n = ∅ ↔ G.CliqueFree n := by simp_rw [CliqueFree, eq_empty_iff_forall_not_mem, mem_cliqueFinset_iff] protected alias ⟨_, CliqueFree.cliqueFinset⟩ := cliqueFinset_eq_empty_iff theorem card_cliqueFinset_le : (G.cliqueFinset n).card ≤ (card α).choose n := by rw [← card_univ, ← card_powersetCard] refine card_mono fun s => ?_ simpa [mem_powersetCard_univ] using IsNClique.card_eq variable [DecidableRel H.Adj] @[mono] theorem cliqueFinset_mono (h : G ≤ H) : G.cliqueFinset n ⊆ H.cliqueFinset n := monotone_filter_right _ fun _ ↦ IsNClique.mono h variable [Fintype β] [DecidableEq β] (G) @[simp] theorem cliqueFinset_map (f : α ↪ β) (hn : n ≠ 1) : (G.map f).cliqueFinset n = (G.cliqueFinset n).map ⟨map f, Finset.map_injective _⟩ := coe_injective <| by simp_rw [coe_cliqueFinset, cliqueSet_map hn, coe_map, coe_cliqueFinset, Embedding.coeFn_mk] @[simp] theorem cliqueFinset_map_of_equiv (e : α ≃ β) (n : ℕ) : (G.map e.toEmbedding).cliqueFinset n = (G.cliqueFinset n).map ⟨map e.toEmbedding, Finset.map_injective _⟩ := coe_injective <| by push_cast; exact cliqueSet_map_of_equiv _ _ _ end CliqueFinset end SimpleGraph
Combinatorics\SimpleGraph\Coloring.lean
/- Copyright (c) 2021 Arthur Paulino. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Arthur Paulino, Kyle Miller -/ import Mathlib.Combinatorics.SimpleGraph.Clique import Mathlib.Data.ENat.Lattice import Mathlib.Data.Nat.Lattice import Mathlib.Data.Setoid.Partition import Mathlib.Order.Antichain import Mathlib.Data.Nat.Cast.Order.Ring /-! # Graph Coloring This module defines colorings of simple graphs (also known as proper colorings in the literature). A graph coloring is the attribution of "colors" to all of its vertices such that adjacent vertices have different colors. A coloring can be represented as a homomorphism into a complete graph, whose vertices represent the colors. ## Main definitions * `G.Coloring α` is the type of `α`-colorings of a simple graph `G`, with `α` being the set of available colors. The type is defined to be homomorphisms from `G` into the complete graph on `α`, and colorings have a coercion to `V → α`. * `G.Colorable n` is the proposition that `G` is `n`-colorable, which is whether there exists a coloring with at most *n* colors. * `G.chromaticNumber` is the minimal `n` such that `G` is `n`-colorable, or `⊤` if it cannot be colored with finitely many colors. (Cardinal-valued chromatic numbers are more niche, so we stick to `ℕ∞`.) We write `G.chromaticNumber ≠ ⊤` to mean a graph is colorable with finitely many colors. * `C.colorClass c` is the set of vertices colored by `c : α` in the coloring `C : G.Coloring α`. * `C.colorClasses` is the set containing all color classes. ## TODO * Gather material from: * https://github.com/leanprover-community/mathlib/blob/simple_graph_matching/src/combinatorics/simple_graph/coloring.lean * https://github.com/kmill/lean-graphcoloring/blob/master/src/graph.lean * Trees * Planar graphs * Chromatic polynomials * develop API for partial colorings, likely as colorings of subgraphs (`H.coe.Coloring α`) -/ open Fintype Function universe u v namespace SimpleGraph variable {V : Type u} (G : SimpleGraph V) {n : ℕ} /-- An `α`-coloring of a simple graph `G` is a homomorphism of `G` into the complete graph on `α`. This is also known as a proper coloring. -/ abbrev Coloring (α : Type v) := G →g (⊤ : SimpleGraph α) variable {G} variable {α β : Type*} (C : G.Coloring α) theorem Coloring.valid {v w : V} (h : G.Adj v w) : C v ≠ C w := C.map_rel h /-- Construct a term of `SimpleGraph.Coloring` using a function that assigns vertices to colors and a proof that it is as proper coloring. (Note: this is a definitionally the constructor for `SimpleGraph.Hom`, but with a syntactically better proper coloring hypothesis.) -/ @[match_pattern] def Coloring.mk (color : V → α) (valid : ∀ {v w : V}, G.Adj v w → color v ≠ color w) : G.Coloring α := ⟨color, @valid⟩ /-- The color class of a given color. -/ def Coloring.colorClass (c : α) : Set V := { v : V | C v = c } /-- The set containing all color classes. -/ def Coloring.colorClasses : Set (Set V) := (Setoid.ker C).classes theorem Coloring.mem_colorClass (v : V) : v ∈ C.colorClass (C v) := rfl theorem Coloring.colorClasses_isPartition : Setoid.IsPartition C.colorClasses := Setoid.isPartition_classes (Setoid.ker C) theorem Coloring.mem_colorClasses {v : V} : C.colorClass (C v) ∈ C.colorClasses := ⟨v, rfl⟩ theorem Coloring.colorClasses_finite [Finite α] : C.colorClasses.Finite := Setoid.finite_classes_ker _ theorem Coloring.card_colorClasses_le [Fintype α] [Fintype C.colorClasses] : Fintype.card C.colorClasses ≤ Fintype.card α := by simp only [colorClasses] -- Porting note: brute force instance declaration `[Fintype (Setoid.classes (Setoid.ker C))]` haveI : Fintype (Setoid.classes (Setoid.ker C)) := by assumption convert Setoid.card_classes_ker_le C theorem Coloring.not_adj_of_mem_colorClass {c : α} {v w : V} (hv : v ∈ C.colorClass c) (hw : w ∈ C.colorClass c) : ¬G.Adj v w := fun h => C.valid h (Eq.trans hv (Eq.symm hw)) theorem Coloring.color_classes_independent (c : α) : IsAntichain G.Adj (C.colorClass c) := fun _ hv _ hw _ => C.not_adj_of_mem_colorClass hv hw -- TODO make this computable noncomputable instance [Fintype V] [Fintype α] : Fintype (Coloring G α) := by classical change Fintype (RelHom G.Adj (⊤ : SimpleGraph α).Adj) apply Fintype.ofInjective _ RelHom.coe_fn_injective variable (G) /-- Whether a graph can be colored by at most `n` colors. -/ def Colorable (n : ℕ) : Prop := Nonempty (G.Coloring (Fin n)) /-- The coloring of an empty graph. -/ def coloringOfIsEmpty [IsEmpty V] : G.Coloring α := Coloring.mk isEmptyElim fun {v} => isEmptyElim v theorem colorable_of_isEmpty [IsEmpty V] (n : ℕ) : G.Colorable n := ⟨G.coloringOfIsEmpty⟩ theorem isEmpty_of_colorable_zero (h : G.Colorable 0) : IsEmpty V := by constructor intro v obtain ⟨i, hi⟩ := h.some v exact Nat.not_lt_zero _ hi /-- The "tautological" coloring of a graph, using the vertices of the graph as colors. -/ def selfColoring : G.Coloring V := Coloring.mk id fun {_ _} => G.ne_of_adj /-- The chromatic number of a graph is the minimal number of colors needed to color it. This is `⊤` (infinity) iff `G` isn't colorable with finitely many colors. If `G` is colorable, then `ENat.toNat G.chromaticNumber` is the `ℕ`-valued chromatic number. -/ noncomputable def chromaticNumber : ℕ∞ := ⨅ n ∈ setOf G.Colorable, (n : ℕ∞) lemma chromaticNumber_eq_biInf {G : SimpleGraph V} : G.chromaticNumber = ⨅ n ∈ setOf G.Colorable, (n : ℕ∞) := rfl lemma chromaticNumber_eq_iInf {G : SimpleGraph V} : G.chromaticNumber = ⨅ n : {m | G.Colorable m}, (n : ℕ∞) := by rw [chromaticNumber, iInf_subtype] lemma Colorable.chromaticNumber_eq_sInf {G : SimpleGraph V} {n} (h : G.Colorable n) : G.chromaticNumber = sInf {n' : ℕ | G.Colorable n'} := by rw [ENat.coe_sInf, chromaticNumber] exact ⟨_, h⟩ /-- Given an embedding, there is an induced embedding of colorings. -/ def recolorOfEmbedding {α β : Type*} (f : α ↪ β) : G.Coloring α ↪ G.Coloring β where toFun C := (Embedding.completeGraph f).toHom.comp C inj' := by -- this was strangely painful; seems like missing lemmas about embeddings intro C C' h dsimp only at h ext v apply (Embedding.completeGraph f).inj' change ((Embedding.completeGraph f).toHom.comp C) v = _ rw [h] rfl @[simp] lemma coe_recolorOfEmbedding (f : α ↪ β) : ⇑(G.recolorOfEmbedding f) = (Embedding.completeGraph f).toHom.comp := rfl /-- Given an equivalence, there is an induced equivalence between colorings. -/ def recolorOfEquiv {α β : Type*} (f : α ≃ β) : G.Coloring α ≃ G.Coloring β where toFun := G.recolorOfEmbedding f.toEmbedding invFun := G.recolorOfEmbedding f.symm.toEmbedding left_inv C := by ext v apply Equiv.symm_apply_apply right_inv C := by ext v apply Equiv.apply_symm_apply @[simp] lemma coe_recolorOfEquiv (f : α ≃ β) : ⇑(G.recolorOfEquiv f) = (Embedding.completeGraph f).toHom.comp := rfl /-- There is a noncomputable embedding of `α`-colorings to `β`-colorings if `β` has at least as large a cardinality as `α`. -/ noncomputable def recolorOfCardLE {α β : Type*} [Fintype α] [Fintype β] (hn : Fintype.card α ≤ Fintype.card β) : G.Coloring α ↪ G.Coloring β := G.recolorOfEmbedding <| (Function.Embedding.nonempty_of_card_le hn).some @[simp] lemma coe_recolorOfCardLE [Fintype α] [Fintype β] (hαβ : card α ≤ card β) : ⇑(G.recolorOfCardLE hαβ) = (Embedding.completeGraph (Embedding.nonempty_of_card_le hαβ).some).toHom.comp := rfl variable {G} theorem Colorable.mono {n m : ℕ} (h : n ≤ m) (hc : G.Colorable n) : G.Colorable m := ⟨G.recolorOfCardLE (by simp [h]) hc.some⟩ theorem Coloring.colorable [Fintype α] (C : G.Coloring α) : G.Colorable (Fintype.card α) := ⟨G.recolorOfCardLE (by simp) C⟩ theorem colorable_of_fintype (G : SimpleGraph V) [Fintype V] : G.Colorable (Fintype.card V) := G.selfColoring.colorable /-- Noncomputably get a coloring from colorability. -/ noncomputable def Colorable.toColoring [Fintype α] {n : ℕ} (hc : G.Colorable n) (hn : n ≤ Fintype.card α) : G.Coloring α := by rw [← Fintype.card_fin n] at hn exact G.recolorOfCardLE hn hc.some theorem Colorable.of_embedding {V' : Type*} {G' : SimpleGraph V'} (f : G ↪g G') {n : ℕ} (h : G'.Colorable n) : G.Colorable n := ⟨(h.toColoring (by simp)).comp f⟩ theorem colorable_iff_exists_bdd_nat_coloring (n : ℕ) : G.Colorable n ↔ ∃ C : G.Coloring ℕ, ∀ v, C v < n := by constructor · rintro hc have C : G.Coloring (Fin n) := hc.toColoring (by simp) let f := Embedding.completeGraph (@Fin.valEmbedding n) use f.toHom.comp C intro v cases' C with color valid exact Fin.is_lt (color v) · rintro ⟨C, Cf⟩ refine ⟨Coloring.mk ?_ ?_⟩ · exact fun v => ⟨C v, Cf v⟩ · rintro v w hvw simp only [Fin.mk_eq_mk, Ne] exact C.valid hvw theorem colorable_set_nonempty_of_colorable {n : ℕ} (hc : G.Colorable n) : { n : ℕ | G.Colorable n }.Nonempty := ⟨n, hc⟩ theorem chromaticNumber_bddBelow : BddBelow { n : ℕ | G.Colorable n } := ⟨0, fun _ _ => zero_le _⟩ theorem Colorable.chromaticNumber_le {n : ℕ} (hc : G.Colorable n) : G.chromaticNumber ≤ n := by rw [hc.chromaticNumber_eq_sInf] norm_cast apply csInf_le chromaticNumber_bddBelow exact hc theorem chromaticNumber_ne_top_iff_exists : G.chromaticNumber ≠ ⊤ ↔ ∃ n, G.Colorable n := by rw [chromaticNumber] convert_to ⨅ n : {m | G.Colorable m}, (n : ℕ∞) ≠ ⊤ ↔ _ · rw [iInf_subtype] rw [← lt_top_iff_ne_top, ENat.iInf_coe_lt_top] simp theorem chromaticNumber_le_iff_colorable {n : ℕ} : G.chromaticNumber ≤ n ↔ G.Colorable n := by refine ⟨fun h ↦ ?_, Colorable.chromaticNumber_le⟩ have : G.chromaticNumber ≠ ⊤ := (trans h (WithTop.coe_lt_top n)).ne rw [chromaticNumber_ne_top_iff_exists] at this obtain ⟨m, hm⟩ := this rw [hm.chromaticNumber_eq_sInf, Nat.cast_le] at h have := Nat.sInf_mem (⟨m, hm⟩ : {n' | G.Colorable n'}.Nonempty) rw [Set.mem_setOf_eq] at this exact this.mono h @[deprecated Colorable.chromaticNumber_le (since := "2024-03-21")] theorem chromaticNumber_le_card [Fintype α] (C : G.Coloring α) : G.chromaticNumber ≤ Fintype.card α := C.colorable.chromaticNumber_le theorem colorable_chromaticNumber {m : ℕ} (hc : G.Colorable m) : G.Colorable (ENat.toNat G.chromaticNumber) := by classical rw [hc.chromaticNumber_eq_sInf, Nat.sInf_def] · apply Nat.find_spec · exact colorable_set_nonempty_of_colorable hc theorem colorable_chromaticNumber_of_fintype (G : SimpleGraph V) [Finite V] : G.Colorable (ENat.toNat G.chromaticNumber) := by cases nonempty_fintype V exact colorable_chromaticNumber G.colorable_of_fintype theorem chromaticNumber_le_one_of_subsingleton (G : SimpleGraph V) [Subsingleton V] : G.chromaticNumber ≤ 1 := by rw [← Nat.cast_one, chromaticNumber_le_iff_colorable] refine ⟨Coloring.mk (fun _ => 0) ?_⟩ intros v w cases Subsingleton.elim v w simp theorem chromaticNumber_eq_zero_of_isempty (G : SimpleGraph V) [IsEmpty V] : G.chromaticNumber = 0 := by rw [← nonpos_iff_eq_zero, ← Nat.cast_zero, chromaticNumber_le_iff_colorable] apply colorable_of_isEmpty theorem isEmpty_of_chromaticNumber_eq_zero (G : SimpleGraph V) [Finite V] (h : G.chromaticNumber = 0) : IsEmpty V := by have h' := G.colorable_chromaticNumber_of_fintype rw [h] at h' exact G.isEmpty_of_colorable_zero h' theorem chromaticNumber_pos [Nonempty V] {n : ℕ} (hc : G.Colorable n) : 0 < G.chromaticNumber := by rw [hc.chromaticNumber_eq_sInf, Nat.cast_pos] apply le_csInf (colorable_set_nonempty_of_colorable hc) intro m hm by_contra h' simp only [not_le] at h' obtain ⟨i, hi⟩ := hm.some (Classical.arbitrary V) have h₁ : i < 0 := lt_of_lt_of_le hi (Nat.le_of_lt_succ h') exact Nat.not_lt_zero _ h₁ theorem colorable_of_chromaticNumber_ne_top (h : G.chromaticNumber ≠ ⊤) : G.Colorable (ENat.toNat G.chromaticNumber) := by rw [chromaticNumber_ne_top_iff_exists] at h obtain ⟨n, hn⟩ := h exact colorable_chromaticNumber hn theorem Colorable.mono_left {G' : SimpleGraph V} (h : G ≤ G') {n : ℕ} (hc : G'.Colorable n) : G.Colorable n := ⟨hc.some.comp (Hom.mapSpanningSubgraphs h)⟩ theorem chromaticNumber_le_of_forall_imp {V' : Type*} {G' : SimpleGraph V'} (h : ∀ n, G'.Colorable n → G.Colorable n) : G.chromaticNumber ≤ G'.chromaticNumber := by rw [chromaticNumber, chromaticNumber] simp only [Set.mem_setOf_eq, le_iInf_iff] intro m hc have := h _ hc rw [← chromaticNumber_le_iff_colorable] at this exact this theorem chromaticNumber_mono (G' : SimpleGraph V) (h : G ≤ G') : G.chromaticNumber ≤ G'.chromaticNumber := chromaticNumber_le_of_forall_imp fun _ => Colorable.mono_left h theorem chromaticNumber_mono_of_embedding {V' : Type*} {G' : SimpleGraph V'} (f : G ↪g G') : G.chromaticNumber ≤ G'.chromaticNumber := chromaticNumber_le_of_forall_imp fun _ => Colorable.of_embedding f lemma card_le_chromaticNumber_iff_forall_surjective [Fintype α] : card α ≤ G.chromaticNumber ↔ ∀ C : G.Coloring α, Surjective C := by refine ⟨fun h C ↦ ?_, fun h ↦ ?_⟩ · rw [C.colorable.chromaticNumber_eq_sInf, Nat.cast_le] at h intro i by_contra! hi let D : G.Coloring {a // a ≠ i} := ⟨fun v ↦ ⟨C v, hi v⟩, (C.valid · <| congr_arg Subtype.val ·)⟩ classical exact Nat.not_mem_of_lt_sInf ((Nat.sub_one_lt_of_lt <| card_pos_iff.2 ⟨i⟩).trans_le h) ⟨G.recolorOfEquiv (equivOfCardEq <| by simp [Nat.pred_eq_sub_one]) D⟩ · simp only [chromaticNumber, Set.mem_setOf_eq, le_iInf_iff, Nat.cast_le, exists_prop] rintro i ⟨C⟩ contrapose! h refine ⟨G.recolorOfCardLE (by simpa using h.le) C, fun hC ↦ ?_⟩ dsimp at hC simpa [h.not_le] using Fintype.card_le_of_surjective _ hC.of_comp lemma le_chromaticNumber_iff_forall_surjective : n ≤ G.chromaticNumber ↔ ∀ C : G.Coloring (Fin n), Surjective C := by simp [← card_le_chromaticNumber_iff_forall_surjective] lemma chromaticNumber_eq_card_iff_forall_surjective [Fintype α] (hG : G.Colorable (card α)) : G.chromaticNumber = card α ↔ ∀ C : G.Coloring α, Surjective C := by rw [← hG.chromaticNumber_le.ge_iff_eq, card_le_chromaticNumber_iff_forall_surjective] lemma chromaticNumber_eq_iff_forall_surjective (hG : G.Colorable n) : G.chromaticNumber = n ↔ ∀ C : G.Coloring (Fin n), Surjective C := by rw [← hG.chromaticNumber_le.ge_iff_eq, le_chromaticNumber_iff_forall_surjective] theorem chromaticNumber_bot [Nonempty V] : (⊥ : SimpleGraph V).chromaticNumber = 1 := by have : (⊥ : SimpleGraph V).Colorable 1 := ⟨.mk 0 $ by simp⟩ exact this.chromaticNumber_le.antisymm $ ENat.one_le_iff_pos.2 $ chromaticNumber_pos this @[simp] theorem chromaticNumber_top [Fintype V] : (⊤ : SimpleGraph V).chromaticNumber = Fintype.card V := by rw [chromaticNumber_eq_card_iff_forall_surjective (selfColoring _).colorable] intro C rw [← Finite.injective_iff_surjective] intro v w contrapose intro h exact C.valid h theorem chromaticNumber_top_eq_top_of_infinite (V : Type*) [Infinite V] : (⊤ : SimpleGraph V).chromaticNumber = ⊤ := by by_contra hc rw [← Ne, chromaticNumber_ne_top_iff_exists] at hc obtain ⟨n, ⟨hn⟩⟩ := hc exact not_injective_infinite_finite _ hn.injective_of_top_hom /-- The bicoloring of a complete bipartite graph using whether a vertex is on the left or on the right. -/ def CompleteBipartiteGraph.bicoloring (V W : Type*) : (completeBipartiteGraph V W).Coloring Bool := Coloring.mk (fun v => v.isRight) (by intro v w cases v <;> cases w <;> simp) theorem CompleteBipartiteGraph.chromaticNumber {V W : Type*} [Nonempty V] [Nonempty W] : (completeBipartiteGraph V W).chromaticNumber = 2 := by rw [← Nat.cast_two, chromaticNumber_eq_iff_forall_surjective (by simpa using (CompleteBipartiteGraph.bicoloring V W).colorable)] intro C b have v := Classical.arbitrary V have w := Classical.arbitrary W have h : (completeBipartiteGraph V W).Adj (Sum.inl v) (Sum.inr w) := by simp by_cases he : C (Sum.inl v) = b · exact ⟨_, he⟩ by_cases he' : C (Sum.inr w) = b · exact ⟨_, he'⟩ · simpa using two_lt_card_iff.2 ⟨_, _, _, C.valid h, he, he'⟩ /-! ### Cliques -/ theorem IsClique.card_le_of_coloring {s : Finset V} (h : G.IsClique s) [Fintype α] (C : G.Coloring α) : s.card ≤ Fintype.card α := by rw [isClique_iff_induce_eq] at h have f : G.induce ↑s ↪g G := Embedding.comap (Function.Embedding.subtype fun x => x ∈ ↑s) G rw [h] at f convert Fintype.card_le_of_injective _ (C.comp f.toHom).injective_of_top_hom using 1 simp theorem IsClique.card_le_of_colorable {s : Finset V} (h : G.IsClique s) {n : ℕ} (hc : G.Colorable n) : s.card ≤ n := by convert h.card_le_of_coloring hc.some simp theorem IsClique.card_le_chromaticNumber {s : Finset V} (h : G.IsClique s) : s.card ≤ G.chromaticNumber := by obtain (hc | hc) := eq_or_ne G.chromaticNumber ⊤ · rw [hc] exact le_top · have hc' := hc rw [chromaticNumber_ne_top_iff_exists] at hc' obtain ⟨n, c⟩ := hc' rw [← ENat.coe_toNat_eq_self] at hc rw [← hc, Nat.cast_le] exact h.card_le_of_colorable (colorable_chromaticNumber c) protected theorem Colorable.cliqueFree {n m : ℕ} (hc : G.Colorable n) (hm : n < m) : G.CliqueFree m := by by_contra h simp only [CliqueFree, isNClique_iff, not_forall, Classical.not_not] at h obtain ⟨s, h, rfl⟩ := h exact Nat.lt_le_asymm hm (h.card_le_of_colorable hc) theorem cliqueFree_of_chromaticNumber_lt {n : ℕ} (hc : G.chromaticNumber < n) : G.CliqueFree n := by have hne : G.chromaticNumber ≠ ⊤ := hc.ne_top obtain ⟨m, hc'⟩ := chromaticNumber_ne_top_iff_exists.mp hne have := colorable_chromaticNumber hc' refine this.cliqueFree ?_ rw [← ENat.coe_toNat_eq_self] at hne rw [← hne] at hc simpa using hc end SimpleGraph
Combinatorics\SimpleGraph\ConcreteColorings.lean
/- Copyright (c) 2023 Iván Renison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Iván Renison -/ import Mathlib.Combinatorics.SimpleGraph.Coloring import Mathlib.Combinatorics.SimpleGraph.Hasse import Mathlib.Logic.Equiv.Fin /-! # Concrete colorings of common graphs This file defines colorings for some common graphs ## Main declarations * `SimpleGraph.pathGraph.bicoloring`: Bicoloring of a path graph. -/ namespace SimpleGraph /-- Bicoloring of a path graph -/ def pathGraph.bicoloring (n : ℕ) : Coloring (pathGraph n) Bool := Coloring.mk (fun u ↦ u.val % 2 = 0) <| by intro u v rw [pathGraph_adj] rintro (h | h) <;> simp [← h, not_iff, Nat.succ_mod_two_eq_zero_iff] /-- Embedding of `pathGraph 2` into the first two elements of `pathGraph n` for `2 ≤ n` -/ def pathGraph_two_embedding (n : ℕ) (h : 2 ≤ n) : pathGraph 2 ↪g pathGraph n where toFun v := ⟨v, trans v.2 h⟩ inj' := by rintro v w rw [Fin.mk.injEq] exact Fin.ext map_rel_iff' := by intro v w fin_cases v <;> fin_cases w <;> simp [pathGraph, ← Fin.coe_covBy_iff] theorem chromaticNumber_pathGraph (n : ℕ) (h : 2 ≤ n) : (pathGraph n).chromaticNumber = 2 := by have hc := (pathGraph.bicoloring n).colorable apply le_antisymm · exact hc.chromaticNumber_le · simpa only [pathGraph_two_eq_top, chromaticNumber_top] using chromaticNumber_mono_of_embedding (pathGraph_two_embedding n h) theorem Coloring.even_length_iff_congr {α} {G : SimpleGraph α} (c : G.Coloring Bool) {u v : α} (p : G.Walk u v) : Even p.length ↔ (c u ↔ c v) := by induction p with | nil => simp | @cons u v w h p ih => simp only [Walk.length_cons, Nat.even_add_one] have : ¬ c u = true ↔ c v = true := by rw [← not_iff, ← Bool.eq_iff_iff] exact c.valid h tauto theorem Coloring.odd_length_iff_not_congr {α} {G : SimpleGraph α} (c : G.Coloring Bool) {u v : α} (p : G.Walk u v) : Odd p.length ↔ (¬c u ↔ c v) := by rw [Nat.odd_iff_not_even, c.even_length_iff_congr p] tauto theorem Walk.three_le_chromaticNumber_of_odd_loop {α} {G : SimpleGraph α} {u : α} (p : G.Walk u u) (hOdd : Odd p.length) : 3 ≤ G.chromaticNumber := Classical.by_contradiction <| by intro h have h' : G.chromaticNumber ≤ 2 := ENat.le_of_lt_add_one <| not_le.mp h let c : G.Coloring (Fin 2) := (chromaticNumber_le_iff_colorable.mp h').some let c' : G.Coloring Bool := recolorOfEquiv G finTwoEquiv c have : ¬c' u ↔ c' u := (c'.odd_length_iff_not_congr p).mp hOdd simp_all end SimpleGraph
Combinatorics\SimpleGraph\Dart.lean
/- Copyright (c) 2020 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import Mathlib.Combinatorics.SimpleGraph.Basic /-! # Darts in graphs A `Dart` or half-edge or bond in a graph is an ordered pair of adjacent vertices, regarded as an oriented edge. This file defines darts and proves some of their basic properties. -/ namespace SimpleGraph variable {V : Type*} (G : SimpleGraph V) /-- A `Dart` is an oriented edge, implemented as an ordered pair of adjacent vertices. This terminology comes from combinatorial maps, and they are also known as "half-edges" or "bonds." -/ structure Dart extends V × V where adj : G.Adj fst snd deriving DecidableEq initialize_simps_projections Dart (+toProd, -fst, -snd) attribute [simp] Dart.adj variable {G} theorem Dart.ext_iff (d₁ d₂ : G.Dart) : d₁ = d₂ ↔ d₁.toProd = d₂.toProd := by cases d₁; cases d₂; simp @[ext] theorem Dart.ext (d₁ d₂ : G.Dart) (h : d₁.toProd = d₂.toProd) : d₁ = d₂ := (Dart.ext_iff d₁ d₂).mpr h -- Porting note: deleted `Dart.fst` and `Dart.snd` since they are now invalid declaration names, -- even though there is not actually a `SimpleGraph.Dart.fst` or `SimpleGraph.Dart.snd`. theorem Dart.toProd_injective : Function.Injective (Dart.toProd : G.Dart → V × V) := Dart.ext instance Dart.fintype [Fintype V] [DecidableRel G.Adj] : Fintype G.Dart := Fintype.ofEquiv (Σ v, G.neighborSet v) { toFun := fun s => ⟨(s.fst, s.snd), s.snd.property⟩ invFun := fun d => ⟨d.fst, d.snd, d.adj⟩ left_inv := fun s => by ext <;> simp right_inv := fun d => by ext <;> simp } /-- The edge associated to the dart. -/ def Dart.edge (d : G.Dart) : Sym2 V := Sym2.mk d.toProd @[simp] theorem Dart.edge_mk {p : V × V} (h : G.Adj p.1 p.2) : (Dart.mk p h).edge = Sym2.mk p := rfl @[simp] theorem Dart.edge_mem (d : G.Dart) : d.edge ∈ G.edgeSet := d.adj /-- The dart with reversed orientation from a given dart. -/ @[simps] def Dart.symm (d : G.Dart) : G.Dart := ⟨d.toProd.swap, G.symm d.adj⟩ @[simp] theorem Dart.symm_mk {p : V × V} (h : G.Adj p.1 p.2) : (Dart.mk p h).symm = Dart.mk p.swap h.symm := rfl @[simp] theorem Dart.edge_symm (d : G.Dart) : d.symm.edge = d.edge := Sym2.mk_prod_swap_eq @[simp] theorem Dart.edge_comp_symm : Dart.edge ∘ Dart.symm = (Dart.edge : G.Dart → Sym2 V) := funext Dart.edge_symm @[simp] theorem Dart.symm_symm (d : G.Dart) : d.symm.symm = d := Dart.ext _ _ <| Prod.swap_swap _ @[simp] theorem Dart.symm_involutive : Function.Involutive (Dart.symm : G.Dart → G.Dart) := Dart.symm_symm theorem Dart.symm_ne (d : G.Dart) : d.symm ≠ d := ne_of_apply_ne (Prod.snd ∘ Dart.toProd) d.adj.ne theorem dart_edge_eq_iff : ∀ d₁ d₂ : G.Dart, d₁.edge = d₂.edge ↔ d₁ = d₂ ∨ d₁ = d₂.symm := by rintro ⟨p, hp⟩ ⟨q, hq⟩ simp theorem dart_edge_eq_mk'_iff : ∀ {d : G.Dart} {p : V × V}, d.edge = Sym2.mk p ↔ d.toProd = p ∨ d.toProd = p.swap := by rintro ⟨p, h⟩ apply Sym2.mk_eq_mk_iff theorem dart_edge_eq_mk'_iff' : ∀ {d : G.Dart} {u v : V}, d.edge = s(u, v) ↔ d.fst = u ∧ d.snd = v ∨ d.fst = v ∧ d.snd = u := by rintro ⟨⟨a, b⟩, h⟩ u v rw [dart_edge_eq_mk'_iff] simp variable (G) /-- Two darts are said to be adjacent if they could be consecutive darts in a walk -- that is, the first dart's second vertex is equal to the second dart's first vertex. -/ def DartAdj (d d' : G.Dart) : Prop := d.snd = d'.fst /-- For a given vertex `v`, this is the bijective map from the neighbor set at `v` to the darts `d` with `d.fst = v`. -/ @[simps] def dartOfNeighborSet (v : V) (w : G.neighborSet v) : G.Dart := ⟨(v, w), w.property⟩ theorem dartOfNeighborSet_injective (v : V) : Function.Injective (G.dartOfNeighborSet v) := fun e₁ e₂ h => Subtype.ext <| by injection h with h' convert congr_arg Prod.snd h' instance nonempty_dart_top [Nontrivial V] : Nonempty (⊤ : SimpleGraph V).Dart := by obtain ⟨v, w, h⟩ := exists_pair_ne V exact ⟨⟨(v, w), h⟩⟩ end SimpleGraph
Combinatorics\SimpleGraph\DegreeSum.lean
/- Copyright (c) 2020 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import Mathlib.Algebra.BigOperators.Ring import Mathlib.Combinatorics.SimpleGraph.Dart import Mathlib.Combinatorics.SimpleGraph.Finite import Mathlib.Data.ZMod.Parity /-! # Degree-sum formula and handshaking lemma The degree-sum formula is that the sum of the degrees of the vertices in a finite graph is equal to twice the number of edges. The handshaking lemma, a corollary, is that the number of odd-degree vertices is even. ## Main definitions - `SimpleGraph.sum_degrees_eq_twice_card_edges` is the degree-sum formula. - `SimpleGraph.even_card_odd_degree_vertices` is the handshaking lemma. - `SimpleGraph.odd_card_odd_degree_vertices_ne` is that the number of odd-degree vertices different from a given odd-degree vertex is odd. - `SimpleGraph.exists_ne_odd_degree_of_exists_odd_degree` is that the existence of an odd-degree vertex implies the existence of another one. ## Implementation notes We give a combinatorial proof by using the facts that (1) the map from darts to vertices is such that each fiber has cardinality the degree of the corresponding vertex and that (2) the map from darts to edges is 2-to-1. ## Tags simple graphs, sums, degree-sum formula, handshaking lemma -/ open Finset namespace SimpleGraph universe u variable {V : Type u} (G : SimpleGraph V) section DegreeSum variable [Fintype V] [DecidableRel G.Adj] theorem dart_fst_fiber [DecidableEq V] (v : V) : (univ.filter fun d : G.Dart => d.fst = v) = univ.image (G.dartOfNeighborSet v) := by ext d simp only [mem_image, true_and_iff, mem_filter, SetCoe.exists, mem_univ, exists_prop_of_true] constructor · rintro rfl exact ⟨_, d.adj, by ext <;> rfl⟩ · rintro ⟨e, he, rfl⟩ rfl theorem dart_fst_fiber_card_eq_degree [DecidableEq V] (v : V) : (univ.filter fun d : G.Dart => d.fst = v).card = G.degree v := by simpa only [dart_fst_fiber, Finset.card_univ, card_neighborSet_eq_degree] using card_image_of_injective univ (G.dartOfNeighborSet_injective v) theorem dart_card_eq_sum_degrees : Fintype.card G.Dart = ∑ v, G.degree v := by haveI := Classical.decEq V simp only [← card_univ, ← dart_fst_fiber_card_eq_degree] exact card_eq_sum_card_fiberwise (by simp) variable {G} theorem Dart.edge_fiber [DecidableEq V] (d : G.Dart) : (univ.filter fun d' : G.Dart => d'.edge = d.edge) = {d, d.symm} := Finset.ext fun d' => by simpa using dart_edge_eq_iff d' d variable (G) theorem dart_edge_fiber_card [DecidableEq V] (e : Sym2 V) (h : e ∈ G.edgeSet) : (univ.filter fun d : G.Dart => d.edge = e).card = 2 := by induction' e with v w let d : G.Dart := ⟨(v, w), h⟩ convert congr_arg card d.edge_fiber rw [card_insert_of_not_mem, card_singleton] rw [mem_singleton] exact d.symm_ne.symm theorem dart_card_eq_twice_card_edges : Fintype.card G.Dart = 2 * G.edgeFinset.card := by classical rw [← card_univ] rw [@card_eq_sum_card_fiberwise _ _ _ Dart.edge _ G.edgeFinset fun d _h => by rw [mem_edgeFinset]; apply Dart.edge_mem] rw [← mul_comm, sum_const_nat] intro e h apply G.dart_edge_fiber_card e rwa [← mem_edgeFinset] /-- The degree-sum formula. This is also known as the handshaking lemma, which might more specifically refer to `SimpleGraph.even_card_odd_degree_vertices`. -/ theorem sum_degrees_eq_twice_card_edges : ∑ v, G.degree v = 2 * G.edgeFinset.card := G.dart_card_eq_sum_degrees.symm.trans G.dart_card_eq_twice_card_edges lemma two_mul_card_edgeFinset : 2 * G.edgeFinset.card = (univ.filter fun (x, y) ↦ G.Adj x y).card := by rw [← dart_card_eq_twice_card_edges, ← card_univ] refine card_bij' (fun d _ ↦ (d.fst, d.snd)) (fun xy h ↦ ⟨xy, (mem_filter.1 h).2⟩) ?_ ?_ ?_ ?_ <;> simp end DegreeSum /-- The handshaking lemma. See also `SimpleGraph.sum_degrees_eq_twice_card_edges`. -/ theorem even_card_odd_degree_vertices [Fintype V] [DecidableRel G.Adj] : Even (univ.filter fun v => Odd (G.degree v)).card := by classical have h := congr_arg (fun n => ↑n : ℕ → ZMod 2) G.sum_degrees_eq_twice_card_edges simp only [ZMod.natCast_self, zero_mul, Nat.cast_mul] at h rw [Nat.cast_sum, ← sum_filter_ne_zero] at h rw [@sum_congr _ _ _ _ (fun v => (G.degree v : ZMod 2)) (fun _v => (1 : ZMod 2)) _ rfl] at h · simp only [filter_congr, mul_one, nsmul_eq_mul, sum_const, Ne] at h rw [← ZMod.eq_zero_iff_even] convert h exact ZMod.ne_zero_iff_odd.symm · intro v simp only [true_and_iff, mem_filter, mem_univ, Ne] rw [ZMod.eq_zero_iff_even, ZMod.eq_one_iff_odd, Nat.odd_iff_not_even, imp_self] trivial theorem odd_card_odd_degree_vertices_ne [Fintype V] [DecidableEq V] [DecidableRel G.Adj] (v : V) (h : Odd (G.degree v)) : Odd (univ.filter fun w => w ≠ v ∧ Odd (G.degree w)).card := by rcases G.even_card_odd_degree_vertices with ⟨k, hg⟩ have hk : 0 < k := by have hh : (filter (fun v : V => Odd (G.degree v)) univ).Nonempty := by use v simp only [true_and_iff, mem_filter, mem_univ] exact h rwa [← card_pos, hg, ← two_mul, mul_pos_iff_of_pos_left] at hh exact zero_lt_two have hc : (fun w : V => w ≠ v ∧ Odd (G.degree w)) = fun w : V => Odd (G.degree w) ∧ w ≠ v := by ext w rw [and_comm] simp only [hc, filter_congr] rw [← filter_filter, filter_ne', card_erase_of_mem] · refine ⟨k - 1, tsub_eq_of_eq_add <| hg.trans ?_⟩ rw [add_assoc, one_add_one_eq_two, ← Nat.mul_succ, ← two_mul] congr omega · simpa only [true_and_iff, mem_filter, mem_univ] theorem exists_ne_odd_degree_of_exists_odd_degree [Fintype V] [DecidableRel G.Adj] (v : V) (h : Odd (G.degree v)) : ∃ w : V, w ≠ v ∧ Odd (G.degree w) := by haveI := Classical.decEq V rcases G.odd_card_odd_degree_vertices_ne v h with ⟨k, hg⟩ have hg' : (filter (fun w : V => w ≠ v ∧ Odd (G.degree w)) univ).card > 0 := by rw [hg] apply Nat.succ_pos rcases card_pos.mp hg' with ⟨w, hw⟩ simp only [true_and_iff, mem_filter, mem_univ, Ne] at hw exact ⟨w, hw⟩ end SimpleGraph
Combinatorics\SimpleGraph\Density.lean
/- Copyright (c) 2022 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import Mathlib.Algebra.Order.Field.Basic import Mathlib.Combinatorics.SimpleGraph.Basic import Mathlib.Data.Rat.Cast.Order import Mathlib.Order.Partition.Finpartition import Mathlib.Tactic.GCongr import Mathlib.Tactic.NormNum import Mathlib.Tactic.Positivity import Mathlib.Tactic.Ring /-! # Edge density This file defines the number and density of edges of a relation/graph. ## Main declarations Between two finsets of vertices, * `Rel.interedges`: Finset of edges of a relation. * `Rel.edgeDensity`: Edge density of a relation. * `SimpleGraph.interedges`: Finset of edges of a graph. * `SimpleGraph.edgeDensity`: Edge density of a graph. -/ open Finset variable {𝕜 ι κ α β : Type*} /-! ### Density of a relation -/ namespace Rel section Asymmetric variable [LinearOrderedField 𝕜] (r : α → β → Prop) [∀ a, DecidablePred (r a)] {s s₁ s₂ : Finset α} {t t₁ t₂ : Finset β} {a : α} {b : β} {δ : 𝕜} /-- Finset of edges of a relation between two finsets of vertices. -/ def interedges (s : Finset α) (t : Finset β) : Finset (α × β) := (s ×ˢ t).filter fun e ↦ r e.1 e.2 /-- Edge density of a relation between two finsets of vertices. -/ def edgeDensity (s : Finset α) (t : Finset β) : ℚ := (interedges r s t).card / (s.card * t.card) variable {r} theorem mem_interedges_iff {x : α × β} : x ∈ interedges r s t ↔ x.1 ∈ s ∧ x.2 ∈ t ∧ r x.1 x.2 := by rw [interedges, mem_filter, Finset.mem_product, and_assoc] theorem mk_mem_interedges_iff : (a, b) ∈ interedges r s t ↔ a ∈ s ∧ b ∈ t ∧ r a b := mem_interedges_iff @[simp] theorem interedges_empty_left (t : Finset β) : interedges r ∅ t = ∅ := by rw [interedges, Finset.empty_product, filter_empty] theorem interedges_mono (hs : s₂ ⊆ s₁) (ht : t₂ ⊆ t₁) : interedges r s₂ t₂ ⊆ interedges r s₁ t₁ := fun x ↦ by simp_rw [mem_interedges_iff] exact fun h ↦ ⟨hs h.1, ht h.2.1, h.2.2⟩ variable (r) theorem card_interedges_add_card_interedges_compl (s : Finset α) (t : Finset β) : (interedges r s t).card + (interedges (fun x y ↦ ¬r x y) s t).card = s.card * t.card := by classical rw [← card_product, interedges, interedges, ← card_union_of_disjoint, filter_union_filter_neg_eq] exact disjoint_filter.2 fun _ _ ↦ Classical.not_not.2 theorem interedges_disjoint_left {s s' : Finset α} (hs : Disjoint s s') (t : Finset β) : Disjoint (interedges r s t) (interedges r s' t) := by rw [Finset.disjoint_left] at hs ⊢ intro _ hx hy rw [mem_interedges_iff] at hx hy exact hs hx.1 hy.1 theorem interedges_disjoint_right (s : Finset α) {t t' : Finset β} (ht : Disjoint t t') : Disjoint (interedges r s t) (interedges r s t') := by rw [Finset.disjoint_left] at ht ⊢ intro _ hx hy rw [mem_interedges_iff] at hx hy exact ht hx.2.1 hy.2.1 section DecidableEq variable [DecidableEq α] [DecidableEq β] lemma interedges_eq_biUnion : interedges r s t = s.biUnion (fun x ↦ (t.filter (r x)).map ⟨(x, ·), Prod.mk.inj_left x⟩) := by ext ⟨x, y⟩; simp [mem_interedges_iff] theorem interedges_biUnion_left (s : Finset ι) (t : Finset β) (f : ι → Finset α) : interedges r (s.biUnion f) t = s.biUnion fun a ↦ interedges r (f a) t := by ext simp only [mem_biUnion, mem_interedges_iff, exists_and_right, ← and_assoc] theorem interedges_biUnion_right (s : Finset α) (t : Finset ι) (f : ι → Finset β) : interedges r s (t.biUnion f) = t.biUnion fun b ↦ interedges r s (f b) := by ext a simp only [mem_interedges_iff, mem_biUnion] exact ⟨fun ⟨x₁, ⟨x₂, x₃, x₄⟩, x₅⟩ ↦ ⟨x₂, x₃, x₁, x₄, x₅⟩, fun ⟨x₂, x₃, x₁, x₄, x₅⟩ ↦ ⟨x₁, ⟨x₂, x₃, x₄⟩, x₅⟩⟩ theorem interedges_biUnion (s : Finset ι) (t : Finset κ) (f : ι → Finset α) (g : κ → Finset β) : interedges r (s.biUnion f) (t.biUnion g) = (s ×ˢ t).biUnion fun ab ↦ interedges r (f ab.1) (g ab.2) := by simp_rw [product_biUnion, interedges_biUnion_left, interedges_biUnion_right] end DecidableEq theorem card_interedges_le_mul (s : Finset α) (t : Finset β) : (interedges r s t).card ≤ s.card * t.card := (card_filter_le _ _).trans (card_product _ _).le theorem edgeDensity_nonneg (s : Finset α) (t : Finset β) : 0 ≤ edgeDensity r s t := by apply div_nonneg <;> exact mod_cast Nat.zero_le _ theorem edgeDensity_le_one (s : Finset α) (t : Finset β) : edgeDensity r s t ≤ 1 := by apply div_le_one_of_le · exact mod_cast card_interedges_le_mul r s t · exact mod_cast Nat.zero_le _ theorem edgeDensity_add_edgeDensity_compl (hs : s.Nonempty) (ht : t.Nonempty) : edgeDensity r s t + edgeDensity (fun x y ↦ ¬r x y) s t = 1 := by rw [edgeDensity, edgeDensity, div_add_div_same, div_eq_one_iff_eq] · exact mod_cast card_interedges_add_card_interedges_compl r s t · exact mod_cast (mul_pos hs.card_pos ht.card_pos).ne' @[simp] theorem edgeDensity_empty_left (t : Finset β) : edgeDensity r ∅ t = 0 := by rw [edgeDensity, Finset.card_empty, Nat.cast_zero, zero_mul, div_zero] @[simp] theorem edgeDensity_empty_right (s : Finset α) : edgeDensity r s ∅ = 0 := by rw [edgeDensity, Finset.card_empty, Nat.cast_zero, mul_zero, div_zero] theorem card_interedges_finpartition_left [DecidableEq α] (P : Finpartition s) (t : Finset β) : (interedges r s t).card = ∑ a ∈ P.parts, (interedges r a t).card := by classical simp_rw [← P.biUnion_parts, interedges_biUnion_left, id] rw [card_biUnion] exact fun x hx y hy h ↦ interedges_disjoint_left r (P.disjoint hx hy h) _ theorem card_interedges_finpartition_right [DecidableEq β] (s : Finset α) (P : Finpartition t) : (interedges r s t).card = ∑ b ∈ P.parts, (interedges r s b).card := by classical simp_rw [← P.biUnion_parts, interedges_biUnion_right, id] rw [card_biUnion] exact fun x hx y hy h ↦ interedges_disjoint_right r _ (P.disjoint hx hy h) theorem card_interedges_finpartition [DecidableEq α] [DecidableEq β] (P : Finpartition s) (Q : Finpartition t) : (interedges r s t).card = ∑ ab ∈ P.parts ×ˢ Q.parts, (interedges r ab.1 ab.2).card := by rw [card_interedges_finpartition_left _ P, sum_product] congr; ext rw [card_interedges_finpartition_right] theorem mul_edgeDensity_le_edgeDensity (hs : s₂ ⊆ s₁) (ht : t₂ ⊆ t₁) (hs₂ : s₂.Nonempty) (ht₂ : t₂.Nonempty) : (s₂.card : ℚ) / s₁.card * (t₂.card / t₁.card) * edgeDensity r s₂ t₂ ≤ edgeDensity r s₁ t₁ := by have hst : (s₂.card : ℚ) * t₂.card ≠ 0 := by simp [hs₂.ne_empty, ht₂.ne_empty] rw [edgeDensity, edgeDensity, div_mul_div_comm, mul_comm, div_mul_div_cancel _ hst] gcongr exact interedges_mono hs ht theorem edgeDensity_sub_edgeDensity_le_one_sub_mul (hs : s₂ ⊆ s₁) (ht : t₂ ⊆ t₁) (hs₂ : s₂.Nonempty) (ht₂ : t₂.Nonempty) : edgeDensity r s₂ t₂ - edgeDensity r s₁ t₁ ≤ 1 - s₂.card / s₁.card * (t₂.card / t₁.card) := by refine (sub_le_sub_left (mul_edgeDensity_le_edgeDensity r hs ht hs₂ ht₂) _).trans ?_ refine le_trans ?_ (mul_le_of_le_one_right ?_ (edgeDensity_le_one r s₂ t₂)) · rw [sub_mul, one_mul] refine sub_nonneg_of_le (mul_le_one ?_ ?_ ?_) · exact div_le_one_of_le ((@Nat.cast_le ℚ).2 (card_le_card hs)) (Nat.cast_nonneg _) · apply div_nonneg <;> exact mod_cast Nat.zero_le _ · exact div_le_one_of_le ((@Nat.cast_le ℚ).2 (card_le_card ht)) (Nat.cast_nonneg _) theorem abs_edgeDensity_sub_edgeDensity_le_one_sub_mul (hs : s₂ ⊆ s₁) (ht : t₂ ⊆ t₁) (hs₂ : s₂.Nonempty) (ht₂ : t₂.Nonempty) : |edgeDensity r s₂ t₂ - edgeDensity r s₁ t₁| ≤ 1 - s₂.card / s₁.card * (t₂.card / t₁.card) := by refine abs_sub_le_iff.2 ⟨edgeDensity_sub_edgeDensity_le_one_sub_mul r hs ht hs₂ ht₂, ?_⟩ rw [← add_sub_cancel_right (edgeDensity r s₁ t₁) (edgeDensity (fun x y ↦ ¬r x y) s₁ t₁), ← add_sub_cancel_right (edgeDensity r s₂ t₂) (edgeDensity (fun x y ↦ ¬r x y) s₂ t₂), edgeDensity_add_edgeDensity_compl _ (hs₂.mono hs) (ht₂.mono ht), edgeDensity_add_edgeDensity_compl _ hs₂ ht₂, sub_sub_sub_cancel_left] exact edgeDensity_sub_edgeDensity_le_one_sub_mul _ hs ht hs₂ ht₂ theorem abs_edgeDensity_sub_edgeDensity_le_two_mul_sub_sq (hs : s₂ ⊆ s₁) (ht : t₂ ⊆ t₁) (hδ₀ : 0 ≤ δ) (hδ₁ : δ < 1) (hs₂ : (1 - δ) * s₁.card ≤ s₂.card) (ht₂ : (1 - δ) * t₁.card ≤ t₂.card) : |(edgeDensity r s₂ t₂ : 𝕜) - edgeDensity r s₁ t₁| ≤ 2 * δ - δ ^ 2 := by have hδ' : 0 ≤ 2 * δ - δ ^ 2 := by rw [sub_nonneg, sq] gcongr exact hδ₁.le.trans (by norm_num) rw [← sub_pos] at hδ₁ obtain rfl | hs₂' := s₂.eq_empty_or_nonempty · rw [Finset.card_empty, Nat.cast_zero] at hs₂ simpa [edgeDensity, (nonpos_of_mul_nonpos_right hs₂ hδ₁).antisymm (Nat.cast_nonneg _)] using hδ' obtain rfl | ht₂' := t₂.eq_empty_or_nonempty · rw [Finset.card_empty, Nat.cast_zero] at ht₂ simpa [edgeDensity, (nonpos_of_mul_nonpos_right ht₂ hδ₁).antisymm (Nat.cast_nonneg _)] using hδ' have hr : 2 * δ - δ ^ 2 = 1 - (1 - δ) * (1 - δ) := by ring rw [hr] norm_cast refine (Rat.cast_le.2 <| abs_edgeDensity_sub_edgeDensity_le_one_sub_mul r hs ht hs₂' ht₂').trans ?_ push_cast have h₁ := hs₂'.mono hs have h₂ := ht₂'.mono ht gcongr · refine (le_div_iff ?_).2 hs₂ exact mod_cast h₁.card_pos · refine (le_div_iff ?_).2 ht₂ exact mod_cast h₂.card_pos /-- If `s₂ ⊆ s₁`, `t₂ ⊆ t₁` and they take up all but a `δ`-proportion, then the difference in edge densities is at most `2 * δ`. -/ theorem abs_edgeDensity_sub_edgeDensity_le_two_mul (hs : s₂ ⊆ s₁) (ht : t₂ ⊆ t₁) (hδ : 0 ≤ δ) (hscard : (1 - δ) * s₁.card ≤ s₂.card) (htcard : (1 - δ) * t₁.card ≤ t₂.card) : |(edgeDensity r s₂ t₂ : 𝕜) - edgeDensity r s₁ t₁| ≤ 2 * δ := by cases' lt_or_le δ 1 with h h · exact (abs_edgeDensity_sub_edgeDensity_le_two_mul_sub_sq r hs ht hδ h hscard htcard).trans ((sub_le_self_iff _).2 <| sq_nonneg δ) rw [two_mul] refine (abs_sub _ _).trans (add_le_add (le_trans ?_ h) (le_trans ?_ h)) <;> · rw [abs_of_nonneg] · exact mod_cast edgeDensity_le_one r _ _ · exact mod_cast edgeDensity_nonneg r _ _ end Asymmetric section Symmetric variable {r : α → α → Prop} [DecidableRel r] {s s₁ s₂ t t₁ t₂ : Finset α} {a b : α} @[simp] theorem swap_mem_interedges_iff (hr : Symmetric r) {x : α × α} : x.swap ∈ interedges r s t ↔ x ∈ interedges r t s := by rw [mem_interedges_iff, mem_interedges_iff, hr.iff] exact and_left_comm theorem mk_mem_interedges_comm (hr : Symmetric r) : (a, b) ∈ interedges r s t ↔ (b, a) ∈ interedges r t s := @swap_mem_interedges_iff _ _ _ _ _ hr (b, a) theorem card_interedges_comm (hr : Symmetric r) (s t : Finset α) : (interedges r s t).card = (interedges r t s).card := Finset.card_bij (fun (x : α × α) _ ↦ x.swap) (fun _ ↦ (swap_mem_interedges_iff hr).2) (fun _ _ _ _ h ↦ Prod.swap_injective h) fun x h ↦ ⟨x.swap, (swap_mem_interedges_iff hr).2 h, x.swap_swap⟩ theorem edgeDensity_comm (hr : Symmetric r) (s t : Finset α) : edgeDensity r s t = edgeDensity r t s := by rw [edgeDensity, mul_comm, card_interedges_comm hr, edgeDensity] end Symmetric end Rel open Rel /-! ### Density of a graph -/ namespace SimpleGraph variable (G : SimpleGraph α) [DecidableRel G.Adj] {s s₁ s₂ t t₁ t₂ : Finset α} {a b : α} /-- Finset of edges of a relation between two finsets of vertices. -/ def interedges (s t : Finset α) : Finset (α × α) := Rel.interedges G.Adj s t /-- Density of edges of a graph between two finsets of vertices. -/ def edgeDensity : Finset α → Finset α → ℚ := Rel.edgeDensity G.Adj theorem interedges_def (s t : Finset α) : G.interedges s t = (s ×ˢ t).filter fun e ↦ G.Adj e.1 e.2 := rfl theorem edgeDensity_def (s t : Finset α) : G.edgeDensity s t = (G.interedges s t).card / (s.card * t.card) := rfl theorem card_interedges_div_card (s t : Finset α) : ((G.interedges s t).card : ℚ) / (s.card * t.card) = G.edgeDensity s t := rfl theorem mem_interedges_iff {x : α × α} : x ∈ G.interedges s t ↔ x.1 ∈ s ∧ x.2 ∈ t ∧ G.Adj x.1 x.2 := Rel.mem_interedges_iff theorem mk_mem_interedges_iff : (a, b) ∈ G.interedges s t ↔ a ∈ s ∧ b ∈ t ∧ G.Adj a b := Rel.mk_mem_interedges_iff @[simp] theorem interedges_empty_left (t : Finset α) : G.interedges ∅ t = ∅ := Rel.interedges_empty_left _ theorem interedges_mono : s₂ ⊆ s₁ → t₂ ⊆ t₁ → G.interedges s₂ t₂ ⊆ G.interedges s₁ t₁ := Rel.interedges_mono theorem interedges_disjoint_left (hs : Disjoint s₁ s₂) (t : Finset α) : Disjoint (G.interedges s₁ t) (G.interedges s₂ t) := Rel.interedges_disjoint_left _ hs _ theorem interedges_disjoint_right (s : Finset α) (ht : Disjoint t₁ t₂) : Disjoint (G.interedges s t₁) (G.interedges s t₂) := Rel.interedges_disjoint_right _ _ ht section DecidableEq variable [DecidableEq α] theorem interedges_biUnion_left (s : Finset ι) (t : Finset α) (f : ι → Finset α) : G.interedges (s.biUnion f) t = s.biUnion fun a ↦ G.interedges (f a) t := Rel.interedges_biUnion_left _ _ _ _ theorem interedges_biUnion_right (s : Finset α) (t : Finset ι) (f : ι → Finset α) : G.interedges s (t.biUnion f) = t.biUnion fun b ↦ G.interedges s (f b) := Rel.interedges_biUnion_right _ _ _ _ theorem interedges_biUnion (s : Finset ι) (t : Finset κ) (f : ι → Finset α) (g : κ → Finset α) : G.interedges (s.biUnion f) (t.biUnion g) = (s ×ˢ t).biUnion fun ab ↦ G.interedges (f ab.1) (g ab.2) := Rel.interedges_biUnion _ _ _ _ _ theorem card_interedges_add_card_interedges_compl (h : Disjoint s t) : (G.interedges s t).card + (Gᶜ.interedges s t).card = s.card * t.card := by rw [← card_product, interedges_def, interedges_def] have : ((s ×ˢ t).filter fun e ↦ Gᶜ.Adj e.1 e.2) = (s ×ˢ t).filter fun e ↦ ¬G.Adj e.1 e.2 := by refine filter_congr fun x hx ↦ ?_ rw [mem_product] at hx rw [compl_adj, and_iff_right (h.forall_ne_finset hx.1 hx.2)] rw [this, ← card_union_of_disjoint, filter_union_filter_neg_eq] exact disjoint_filter.2 fun _ _ ↦ Classical.not_not.2 theorem edgeDensity_add_edgeDensity_compl (hs : s.Nonempty) (ht : t.Nonempty) (h : Disjoint s t) : G.edgeDensity s t + Gᶜ.edgeDensity s t = 1 := by rw [edgeDensity_def, edgeDensity_def, div_add_div_same, div_eq_one_iff_eq] · exact mod_cast card_interedges_add_card_interedges_compl _ h -- Porting note: Wrote a workaround for `positivity` tactic. · apply mul_ne_zero <;> exact mod_cast Nat.pos_iff_ne_zero.1 (Nonempty.card_pos ‹_›) end DecidableEq theorem card_interedges_le_mul (s t : Finset α) : (G.interedges s t).card ≤ s.card * t.card := Rel.card_interedges_le_mul _ _ _ theorem edgeDensity_nonneg (s t : Finset α) : 0 ≤ G.edgeDensity s t := Rel.edgeDensity_nonneg _ _ _ theorem edgeDensity_le_one (s t : Finset α) : G.edgeDensity s t ≤ 1 := Rel.edgeDensity_le_one _ _ _ @[simp] theorem edgeDensity_empty_left (t : Finset α) : G.edgeDensity ∅ t = 0 := Rel.edgeDensity_empty_left _ _ @[simp] theorem edgeDensity_empty_right (s : Finset α) : G.edgeDensity s ∅ = 0 := Rel.edgeDensity_empty_right _ _ @[simp] theorem swap_mem_interedges_iff {x : α × α} : x.swap ∈ G.interedges s t ↔ x ∈ G.interedges t s := Rel.swap_mem_interedges_iff G.symm theorem mk_mem_interedges_comm : (a, b) ∈ G.interedges s t ↔ (b, a) ∈ G.interedges t s := Rel.mk_mem_interedges_comm G.symm theorem edgeDensity_comm (s t : Finset α) : G.edgeDensity s t = G.edgeDensity t s := Rel.edgeDensity_comm G.symm s t end SimpleGraph /- Porting note: Commented out `Tactic` namespace. namespace Tactic open Positivity /-- Extension for the `positivity` tactic: `Rel.edgeDensity` and `SimpleGraph.edgeDensity` are always nonnegative. -/ @[positivity] unsafe def positivity_edge_density : expr → tactic strictness | q(Rel.edgeDensity $(r) $(s) $(t)) => nonnegative <$> mk_mapp `` Rel.edgeDensity_nonneg [none, none, r, none, s, t] | q(SimpleGraph.edgeDensity $(G) $(s) $(t)) => nonnegative <$> mk_mapp `` SimpleGraph.edgeDensity_nonneg [none, G, none, s, t] | e => pp e >>= fail ∘ format.bracket "The expression `" "` isn't of the form `Rel.edgeDensity r s t` nor `SimpleGraph.edgeDensity G s t`" end Tactic -/
Combinatorics\SimpleGraph\Finite.lean
/- Copyright (c) 2020 Aaron Anderson, Jalex Stark, Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jalex Stark, Kyle Miller, Alena Gusakov -/ import Mathlib.Algebra.Order.Ring.Defs import Mathlib.Combinatorics.SimpleGraph.Basic import Mathlib.Data.Sym.Card /-! # Definitions for finite and locally finite graphs This file defines finite versions of `edgeSet`, `neighborSet` and `incidenceSet` and proves some of their basic properties. It also defines the notion of a locally finite graph, which is one whose vertices have finite degree. The design for finiteness is that each definition takes the smallest finiteness assumption necessary. For example, `SimpleGraph.neighborFinset v` only requires that `v` have finitely many neighbors. ## Main definitions * `SimpleGraph.edgeFinset` is the `Finset` of edges in a graph, if `edgeSet` is finite * `SimpleGraph.neighborFinset` is the `Finset` of vertices adjacent to a given vertex, if `neighborSet` is finite * `SimpleGraph.incidenceFinset` is the `Finset` of edges containing a given vertex, if `incidenceSet` is finite ## Naming conventions If the vertex type of a graph is finite, we refer to its cardinality as `CardVerts` or `card_verts`. ## Implementation notes * A locally finite graph is one with instances `Π v, Fintype (G.neighborSet v)`. * Given instances `DecidableRel G.Adj` and `Fintype V`, then the graph is locally finite, too. -/ open Finset Function namespace SimpleGraph variable {V : Type*} (G : SimpleGraph V) {e : Sym2 V} section EdgeFinset variable {G₁ G₂ : SimpleGraph V} [Fintype G.edgeSet] [Fintype G₁.edgeSet] [Fintype G₂.edgeSet] /-- The `edgeSet` of the graph as a `Finset`. -/ abbrev edgeFinset : Finset (Sym2 V) := Set.toFinset G.edgeSet @[norm_cast] theorem coe_edgeFinset : (G.edgeFinset : Set (Sym2 V)) = G.edgeSet := Set.coe_toFinset _ variable {G} theorem mem_edgeFinset : e ∈ G.edgeFinset ↔ e ∈ G.edgeSet := Set.mem_toFinset theorem not_isDiag_of_mem_edgeFinset : e ∈ G.edgeFinset → ¬e.IsDiag := not_isDiag_of_mem_edgeSet _ ∘ mem_edgeFinset.1 theorem edgeFinset_inj : G₁.edgeFinset = G₂.edgeFinset ↔ G₁ = G₂ := by simp theorem edgeFinset_subset_edgeFinset : G₁.edgeFinset ⊆ G₂.edgeFinset ↔ G₁ ≤ G₂ := by simp theorem edgeFinset_ssubset_edgeFinset : G₁.edgeFinset ⊂ G₂.edgeFinset ↔ G₁ < G₂ := by simp @[gcongr] alias ⟨_, edgeFinset_mono⟩ := edgeFinset_subset_edgeFinset alias ⟨_, edgeFinset_strict_mono⟩ := edgeFinset_ssubset_edgeFinset attribute [mono] edgeFinset_mono edgeFinset_strict_mono @[simp] theorem edgeFinset_bot : (⊥ : SimpleGraph V).edgeFinset = ∅ := by simp [edgeFinset] @[simp] theorem edgeFinset_sup [Fintype (edgeSet (G₁ ⊔ G₂))] [DecidableEq V] : (G₁ ⊔ G₂).edgeFinset = G₁.edgeFinset ∪ G₂.edgeFinset := by simp [edgeFinset] @[simp] theorem edgeFinset_inf [DecidableEq V] : (G₁ ⊓ G₂).edgeFinset = G₁.edgeFinset ∩ G₂.edgeFinset := by simp [edgeFinset] @[simp] theorem edgeFinset_sdiff [DecidableEq V] : (G₁ \ G₂).edgeFinset = G₁.edgeFinset \ G₂.edgeFinset := by simp [edgeFinset] theorem edgeFinset_card : G.edgeFinset.card = Fintype.card G.edgeSet := Set.toFinset_card _ @[simp] theorem edgeSet_univ_card : (univ : Finset G.edgeSet).card = G.edgeFinset.card := Fintype.card_of_subtype G.edgeFinset fun _ => mem_edgeFinset variable [Fintype V] @[simp] theorem edgeFinset_top [DecidableEq V] : (⊤ : SimpleGraph V).edgeFinset = univ.filter fun e => ¬e.IsDiag := by rw [← coe_inj]; simp /-- The complete graph on `n` vertices has `n.choose 2` edges. -/ theorem card_edgeFinset_top_eq_card_choose_two [DecidableEq V] : (⊤ : SimpleGraph V).edgeFinset.card = (Fintype.card V).choose 2 := by simp_rw [Set.toFinset_card, edgeSet_top, Set.coe_setOf, ← Sym2.card_subtype_not_diag] /-- Any graph on `n` vertices has at most `n.choose 2` edges. -/ theorem card_edgeFinset_le_card_choose_two : G.edgeFinset.card ≤ (Fintype.card V).choose 2 := by classical rw [← card_edgeFinset_top_eq_card_choose_two] exact card_le_card (edgeFinset_mono le_top) end EdgeFinset theorem edgeFinset_deleteEdges [DecidableEq V] [Fintype G.edgeSet] (s : Finset (Sym2 V)) [Fintype (G.deleteEdges s).edgeSet] : (G.deleteEdges s).edgeFinset = G.edgeFinset \ s := by ext e simp [edgeSet_deleteEdges] section DeleteFar -- Porting note: added `Fintype (Sym2 V)` argument. variable {𝕜 : Type*} [OrderedRing 𝕜] [Fintype G.edgeSet] {p : SimpleGraph V → Prop} {r r₁ r₂ : 𝕜} /-- A graph is `r`-*delete-far* from a property `p` if we must delete at least `r` edges from it to get a graph with the property `p`. -/ def DeleteFar (p : SimpleGraph V → Prop) (r : 𝕜) : Prop := ∀ ⦃s⦄, s ⊆ G.edgeFinset → p (G.deleteEdges s) → r ≤ s.card variable {G} theorem deleteFar_iff [Fintype (Sym2 V)] : G.DeleteFar p r ↔ ∀ ⦃H : SimpleGraph _⦄ [DecidableRel H.Adj], H ≤ G → p H → r ≤ G.edgeFinset.card - H.edgeFinset.card := by classical refine ⟨fun h H _ hHG hH ↦ ?_, fun h s hs hG ↦ ?_⟩ · have := h (sdiff_subset (t := H.edgeFinset)) simp only [deleteEdges_sdiff_eq_of_le hHG, edgeFinset_mono hHG, card_sdiff, card_le_card, coe_sdiff, coe_edgeFinset, Nat.cast_sub] at this exact this hH · classical simpa [card_sdiff hs, edgeFinset_deleteEdges, -Set.toFinset_card, Nat.cast_sub, card_le_card hs] using h (G.deleteEdges_le s) hG alias ⟨DeleteFar.le_card_sub_card, _⟩ := deleteFar_iff theorem DeleteFar.mono (h : G.DeleteFar p r₂) (hr : r₁ ≤ r₂) : G.DeleteFar p r₁ := fun _ hs hG => hr.trans <| h hs hG end DeleteFar section FiniteAt /-! ## Finiteness at a vertex This section contains definitions and lemmas concerning vertices that have finitely many adjacent vertices. We denote this condition by `Fintype (G.neighborSet v)`. We define `G.neighborFinset v` to be the `Finset` version of `G.neighborSet v`. Use `neighborFinset_eq_filter` to rewrite this definition as a `Finset.filter` expression. -/ variable (v) [Fintype (G.neighborSet v)] /-- `G.neighbors v` is the `Finset` version of `G.Adj v` in case `G` is locally finite at `v`. -/ def neighborFinset : Finset V := (G.neighborSet v).toFinset theorem neighborFinset_def : G.neighborFinset v = (G.neighborSet v).toFinset := rfl @[simp] theorem mem_neighborFinset (w : V) : w ∈ G.neighborFinset v ↔ G.Adj v w := Set.mem_toFinset theorem not_mem_neighborFinset_self : v ∉ G.neighborFinset v := by simp theorem neighborFinset_disjoint_singleton : Disjoint (G.neighborFinset v) {v} := Finset.disjoint_singleton_right.mpr <| not_mem_neighborFinset_self _ _ theorem singleton_disjoint_neighborFinset : Disjoint {v} (G.neighborFinset v) := Finset.disjoint_singleton_left.mpr <| not_mem_neighborFinset_self _ _ /-- `G.degree v` is the number of vertices adjacent to `v`. -/ def degree : ℕ := (G.neighborFinset v).card -- Porting note: in Lean 3 we could do `simp [← degree]`, but that gives -- "invalid '←' modifier, 'SimpleGraph.degree' is a declaration name to be unfolded". -- In any case, having this lemma is good since there's no guarantee we won't still change -- the definition of `degree`. @[simp] theorem card_neighborFinset_eq_degree : (G.neighborFinset v).card = G.degree v := rfl @[simp] theorem card_neighborSet_eq_degree : Fintype.card (G.neighborSet v) = G.degree v := (Set.toFinset_card _).symm theorem degree_pos_iff_exists_adj : 0 < G.degree v ↔ ∃ w, G.Adj v w := by simp only [degree, card_pos, Finset.Nonempty, mem_neighborFinset] theorem degree_compl [Fintype (Gᶜ.neighborSet v)] [Fintype V] : Gᶜ.degree v = Fintype.card V - 1 - G.degree v := by classical rw [← card_neighborSet_union_compl_neighborSet G v, Set.toFinset_union] simp [card_union_of_disjoint (Set.disjoint_toFinset.mpr (compl_neighborSet_disjoint G v))] instance incidenceSetFintype [DecidableEq V] : Fintype (G.incidenceSet v) := Fintype.ofEquiv (G.neighborSet v) (G.incidenceSetEquivNeighborSet v).symm /-- This is the `Finset` version of `incidenceSet`. -/ def incidenceFinset [DecidableEq V] : Finset (Sym2 V) := (G.incidenceSet v).toFinset @[simp] theorem card_incidenceSet_eq_degree [DecidableEq V] : Fintype.card (G.incidenceSet v) = G.degree v := by rw [Fintype.card_congr (G.incidenceSetEquivNeighborSet v)] simp @[simp] theorem card_incidenceFinset_eq_degree [DecidableEq V] : (G.incidenceFinset v).card = G.degree v := by rw [← G.card_incidenceSet_eq_degree] apply Set.toFinset_card @[simp] theorem mem_incidenceFinset [DecidableEq V] (e : Sym2 V) : e ∈ G.incidenceFinset v ↔ e ∈ G.incidenceSet v := Set.mem_toFinset theorem incidenceFinset_eq_filter [DecidableEq V] [Fintype G.edgeSet] : G.incidenceFinset v = G.edgeFinset.filter (Membership.mem v) := by ext e induction e simp [mk'_mem_incidenceSet_iff] end FiniteAt section LocallyFinite /-- A graph is locally finite if every vertex has a finite neighbor set. -/ abbrev LocallyFinite := ∀ v : V, Fintype (G.neighborSet v) variable [LocallyFinite G] /-- A locally finite simple graph is regular of degree `d` if every vertex has degree `d`. -/ def IsRegularOfDegree (d : ℕ) : Prop := ∀ v : V, G.degree v = d variable {G} theorem IsRegularOfDegree.degree_eq {d : ℕ} (h : G.IsRegularOfDegree d) (v : V) : G.degree v = d := h v theorem IsRegularOfDegree.compl [Fintype V] [DecidableEq V] {G : SimpleGraph V} [DecidableRel G.Adj] {k : ℕ} (h : G.IsRegularOfDegree k) : Gᶜ.IsRegularOfDegree (Fintype.card V - 1 - k) := by intro v rw [degree_compl, h v] end LocallyFinite section Finite variable [Fintype V] instance neighborSetFintype [DecidableRel G.Adj] (v : V) : Fintype (G.neighborSet v) := @Subtype.fintype _ _ (by simp_rw [mem_neighborSet] infer_instance) _ theorem neighborFinset_eq_filter {v : V} [DecidableRel G.Adj] : G.neighborFinset v = Finset.univ.filter (G.Adj v) := by ext simp theorem neighborFinset_compl [DecidableEq V] [DecidableRel G.Adj] (v : V) : Gᶜ.neighborFinset v = (G.neighborFinset v)ᶜ \ {v} := by simp only [neighborFinset, neighborSet_compl, Set.toFinset_diff, Set.toFinset_compl, Set.toFinset_singleton] @[simp] theorem complete_graph_degree [DecidableEq V] (v : V) : (⊤ : SimpleGraph V).degree v = Fintype.card V - 1 := by erw [degree, neighborFinset_eq_filter, filter_ne, card_erase_of_mem (mem_univ v), card_univ] theorem bot_degree (v : V) : (⊥ : SimpleGraph V).degree v = 0 := by erw [degree, neighborFinset_eq_filter, filter_False] exact Finset.card_empty theorem IsRegularOfDegree.top [DecidableEq V] : (⊤ : SimpleGraph V).IsRegularOfDegree (Fintype.card V - 1) := by intro v simp /-- The minimum degree of all vertices (and `0` if there are no vertices). The key properties of this are given in `exists_minimal_degree_vertex`, `minDegree_le_degree` and `le_minDegree_of_forall_le_degree`. -/ def minDegree [DecidableRel G.Adj] : ℕ := WithTop.untop' 0 (univ.image fun v => G.degree v).min /-- There exists a vertex of minimal degree. Note the assumption of being nonempty is necessary, as the lemma implies there exists a vertex. -/ theorem exists_minimal_degree_vertex [DecidableRel G.Adj] [Nonempty V] : ∃ v, G.minDegree = G.degree v := by obtain ⟨t, ht : _ = _⟩ := min_of_nonempty (univ_nonempty.image fun v => G.degree v) obtain ⟨v, _, rfl⟩ := mem_image.mp (mem_of_min ht) exact ⟨v, by simp [minDegree, ht]⟩ /-- The minimum degree in the graph is at most the degree of any particular vertex. -/ theorem minDegree_le_degree [DecidableRel G.Adj] (v : V) : G.minDegree ≤ G.degree v := by obtain ⟨t, ht⟩ := Finset.min_of_mem (mem_image_of_mem (fun v => G.degree v) (mem_univ v)) have := Finset.min_le_of_eq (mem_image_of_mem _ (mem_univ v)) ht rwa [minDegree, ht] /-- In a nonempty graph, if `k` is at most the degree of every vertex, it is at most the minimum degree. Note the assumption that the graph is nonempty is necessary as long as `G.minDegree` is defined to be a natural. -/ theorem le_minDegree_of_forall_le_degree [DecidableRel G.Adj] [Nonempty V] (k : ℕ) (h : ∀ v, k ≤ G.degree v) : k ≤ G.minDegree := by rcases G.exists_minimal_degree_vertex with ⟨v, hv⟩ rw [hv] apply h /-- The maximum degree of all vertices (and `0` if there are no vertices). The key properties of this are given in `exists_maximal_degree_vertex`, `degree_le_maxDegree` and `maxDegree_le_of_forall_degree_le`. -/ def maxDegree [DecidableRel G.Adj] : ℕ := Option.getD (univ.image fun v => G.degree v).max 0 /-- There exists a vertex of maximal degree. Note the assumption of being nonempty is necessary, as the lemma implies there exists a vertex. -/ theorem exists_maximal_degree_vertex [DecidableRel G.Adj] [Nonempty V] : ∃ v, G.maxDegree = G.degree v := by obtain ⟨t, ht⟩ := max_of_nonempty (univ_nonempty.image fun v => G.degree v) have ht₂ := mem_of_max ht simp only [mem_image, mem_univ, exists_prop_of_true] at ht₂ rcases ht₂ with ⟨v, _, rfl⟩ refine ⟨v, ?_⟩ rw [maxDegree, ht] rfl /-- The maximum degree in the graph is at least the degree of any particular vertex. -/ theorem degree_le_maxDegree [DecidableRel G.Adj] (v : V) : G.degree v ≤ G.maxDegree := by obtain ⟨t, ht : _ = _⟩ := Finset.max_of_mem (mem_image_of_mem (fun v => G.degree v) (mem_univ v)) have := Finset.le_max_of_eq (mem_image_of_mem _ (mem_univ v)) ht rwa [maxDegree, ht] /-- In a graph, if `k` is at least the degree of every vertex, then it is at least the maximum degree. -/ theorem maxDegree_le_of_forall_degree_le [DecidableRel G.Adj] (k : ℕ) (h : ∀ v, G.degree v ≤ k) : G.maxDegree ≤ k := by by_cases hV : (univ : Finset V).Nonempty · haveI : Nonempty V := univ_nonempty_iff.mp hV obtain ⟨v, hv⟩ := G.exists_maximal_degree_vertex rw [hv] apply h · rw [not_nonempty_iff_eq_empty] at hV rw [maxDegree, hV, image_empty] exact k.zero_le theorem degree_lt_card_verts [DecidableRel G.Adj] (v : V) : G.degree v < Fintype.card V := by classical apply Finset.card_lt_card rw [Finset.ssubset_iff] exact ⟨v, by simp, Finset.subset_univ _⟩ /-- The maximum degree of a nonempty graph is less than the number of vertices. Note that the assumption that `V` is nonempty is necessary, as otherwise this would assert the existence of a natural number less than zero. -/ theorem maxDegree_lt_card_verts [DecidableRel G.Adj] [Nonempty V] : G.maxDegree < Fintype.card V := by cases' G.exists_maximal_degree_vertex with v hv rw [hv] apply G.degree_lt_card_verts v theorem card_commonNeighbors_le_degree_left [DecidableRel G.Adj] (v w : V) : Fintype.card (G.commonNeighbors v w) ≤ G.degree v := by rw [← card_neighborSet_eq_degree] exact Set.card_le_card Set.inter_subset_left theorem card_commonNeighbors_le_degree_right [DecidableRel G.Adj] (v w : V) : Fintype.card (G.commonNeighbors v w) ≤ G.degree w := by simp_rw [commonNeighbors_symm _ v w, card_commonNeighbors_le_degree_left] theorem card_commonNeighbors_lt_card_verts [DecidableRel G.Adj] (v w : V) : Fintype.card (G.commonNeighbors v w) < Fintype.card V := Nat.lt_of_le_of_lt (G.card_commonNeighbors_le_degree_left _ _) (G.degree_lt_card_verts v) /-- If the condition `G.Adj v w` fails, then `card_commonNeighbors_le_degree` is the best we can do in general. -/ theorem Adj.card_commonNeighbors_lt_degree {G : SimpleGraph V} [DecidableRel G.Adj] {v w : V} (h : G.Adj v w) : Fintype.card (G.commonNeighbors v w) < G.degree v := by classical erw [← Set.toFinset_card] apply Finset.card_lt_card rw [Finset.ssubset_iff] use w constructor · rw [Set.mem_toFinset] apply not_mem_commonNeighbors_right · rw [Finset.insert_subset_iff] constructor · simpa · rw [neighborFinset, Set.toFinset_subset_toFinset] exact G.commonNeighbors_subset_neighborSet_left _ _ theorem card_commonNeighbors_top [DecidableEq V] {v w : V} (h : v ≠ w) : Fintype.card ((⊤ : SimpleGraph V).commonNeighbors v w) = Fintype.card V - 2 := by simp only [commonNeighbors_top_eq, ← Set.toFinset_card, Set.toFinset_diff] rw [Finset.card_sdiff] · simp [Finset.card_univ, h] · simp only [Set.toFinset_subset_toFinset, Set.subset_univ] end Finite end SimpleGraph
Combinatorics\SimpleGraph\Finsubgraph.lean
/- Copyright (c) 2022 Joanna Choules. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joanna Choules -/ import Mathlib.CategoryTheory.CofilteredSystem import Mathlib.Combinatorics.SimpleGraph.Subgraph /-! # Homomorphisms from finite subgraphs This file defines the type of finite subgraphs of a `SimpleGraph` and proves a compactness result for homomorphisms to a finite codomain. ## Main statements * `SimpleGraph.nonempty_hom_of_forall_finite_subgraph_hom`: If every finite subgraph of a (possibly infinite) graph `G` has a homomorphism to some finite graph `F`, then there is also a homomorphism `G →g F`. ## Notations `→fg` is a module-local variant on `→g` where the domain is a finite subgraph of some supergraph `G`. ## Implementation notes The proof here uses compactness as formulated in `nonempty_sections_of_finite_inverse_system`. For finite subgraphs `G'' ≤ G'`, the inverse system `finsubgraphHomFunctor` restricts homomorphisms `G' →fg F` to domain `G''`. -/ open Set CategoryTheory universe u v variable {V : Type u} {W : Type v} {G : SimpleGraph V} {F : SimpleGraph W} namespace SimpleGraph /-- The subtype of `G.subgraph` comprising those subgraphs with finite vertex sets. -/ abbrev Finsubgraph (G : SimpleGraph V) := { G' : G.Subgraph // G'.verts.Finite } /-- A graph homomorphism from a finite subgraph of G to F. -/ abbrev FinsubgraphHom (G' : G.Finsubgraph) (F : SimpleGraph W) := G'.val.coe →g F local infixl:50 " →fg " => FinsubgraphHom namespace Finsubgraph instance : OrderBot G.Finsubgraph where bot := ⟨⊥, finite_empty⟩ bot_le _ := bot_le (α := G.Subgraph) instance : Sup G.Finsubgraph := ⟨fun G₁ G₂ => ⟨G₁ ⊔ G₂, G₁.2.union G₂.2⟩⟩ instance : Inf G.Finsubgraph := ⟨fun G₁ G₂ => ⟨G₁ ⊓ G₂, G₁.2.subset inter_subset_left⟩⟩ instance instSDiff : SDiff G.Finsubgraph where sdiff G₁ G₂ := ⟨G₁ \ G₂, G₁.2.subset (Subgraph.verts_mono sdiff_le)⟩ @[simp, norm_cast] lemma coe_bot : (⊥ : G.Finsubgraph) = (⊥ : G.Subgraph) := rfl @[simp, norm_cast] lemma coe_sup (G₁ G₂ : G.Finsubgraph) : ↑(G₁ ⊔ G₂) = (G₁ ⊔ G₂ : G.Subgraph) := rfl @[simp, norm_cast] lemma coe_inf (G₁ G₂ : G.Finsubgraph) : ↑(G₁ ⊓ G₂) = (G₁ ⊓ G₂ : G.Subgraph) := rfl @[simp, norm_cast] lemma coe_sdiff (G₁ G₂ : G.Finsubgraph) : ↑(G₁ \ G₂) = (G₁ \ G₂ : G.Subgraph) := rfl instance instGeneralizedCoheytingAlgebra : GeneralizedCoheytingAlgebra G.Finsubgraph := Subtype.coe_injective.generalizedCoheytingAlgebra _ coe_sup coe_inf coe_bot coe_sdiff section Finite variable [Finite V] instance instTop : Top G.Finsubgraph where top := ⟨⊤, finite_univ⟩ instance instHasCompl : HasCompl G.Finsubgraph where compl G' := ⟨G'ᶜ, Set.toFinite _⟩ instance instHNot : HNot G.Finsubgraph where hnot G' := ⟨¬G', Set.toFinite _⟩ instance instHImp : HImp G.Finsubgraph where himp G₁ G₂ := ⟨G₁ ⇨ G₂, Set.toFinite _⟩ instance instSupSet : SupSet G.Finsubgraph where sSup s := ⟨⨆ G ∈ s, ↑G, Set.toFinite _⟩ instance instInfSet : InfSet G.Finsubgraph where sInf s := ⟨⨅ G ∈ s, ↑G, Set.toFinite _⟩ @[simp, norm_cast] lemma coe_top : (⊤ : G.Finsubgraph) = (⊤ : G.Subgraph) := rfl @[simp, norm_cast] lemma coe_compl (G' : G.Finsubgraph) : ↑(G'ᶜ) = (G'ᶜ : G.Subgraph) := rfl @[simp, norm_cast] lemma coe_hnot (G' : G.Finsubgraph) : ↑(¬G') = (¬G' : G.Subgraph) := rfl @[simp, norm_cast] lemma coe_himp (G₁ G₂ : G.Finsubgraph) : ↑(G₁ ⇨ G₂) = (G₁ ⇨ G₂ : G.Subgraph) := rfl @[simp, norm_cast] lemma coe_sSup (s : Set G.Finsubgraph) : sSup s = (⨆ G ∈ s, G : G.Subgraph) := rfl @[simp, norm_cast] lemma coe_sInf (s : Set G.Finsubgraph) : sInf s = (⨅ G ∈ s, G : G.Subgraph) := rfl @[simp, norm_cast] lemma coe_iSup {ι : Sort*} (f : ι → G.Finsubgraph) : ⨆ i, f i = (⨆ i, f i : G.Subgraph) := by rw [iSup, coe_sSup, iSup_range] @[simp, norm_cast] lemma coe_iInf {ι : Sort*} (f : ι → G.Finsubgraph) : ⨅ i, f i = (⨅ i, f i : G.Subgraph) := by rw [iInf, coe_sInf, iInf_range] instance instCompletelyDistribLattice : CompletelyDistribLattice G.Finsubgraph := Subtype.coe_injective.completelyDistribLattice _ coe_sup coe_inf coe_sSup coe_sInf coe_top coe_bot coe_compl coe_himp coe_hnot coe_sdiff end Finite end Finsubgraph /-- The finite subgraph of G generated by a single vertex. -/ def singletonFinsubgraph (v : V) : G.Finsubgraph := ⟨SimpleGraph.singletonSubgraph _ v, by simp⟩ /-- The finite subgraph of G generated by a single edge. -/ def finsubgraphOfAdj {u v : V} (e : G.Adj u v) : G.Finsubgraph := ⟨SimpleGraph.subgraphOfAdj _ e, by simp⟩ -- Lemmas establishing the ordering between edge- and vertex-generated subgraphs. theorem singletonFinsubgraph_le_adj_left {u v : V} {e : G.Adj u v} : singletonFinsubgraph u ≤ finsubgraphOfAdj e := by simp [singletonFinsubgraph, finsubgraphOfAdj] theorem singletonFinsubgraph_le_adj_right {u v : V} {e : G.Adj u v} : singletonFinsubgraph v ≤ finsubgraphOfAdj e := by simp [singletonFinsubgraph, finsubgraphOfAdj] /-- Given a homomorphism from a subgraph to `F`, construct its restriction to a sub-subgraph. -/ def FinsubgraphHom.restrict {G' G'' : G.Finsubgraph} (h : G'' ≤ G') (f : G' →fg F) : G'' →fg F := by refine ⟨fun ⟨v, hv⟩ => f.toFun ⟨v, h.1 hv⟩, ?_⟩ rintro ⟨u, hu⟩ ⟨v, hv⟩ huv exact f.map_rel' (h.2 huv) /-- The inverse system of finite homomorphisms. -/ def finsubgraphHomFunctor (G : SimpleGraph V) (F : SimpleGraph W) : G.Finsubgraphᵒᵖ ⥤ Type max u v where obj G' := G'.unop →fg F map g f := f.restrict (CategoryTheory.leOfHom g.unop) /-- If every finite subgraph of a graph `G` has a homomorphism to a finite graph `F`, then there is a homomorphism from the whole of `G` to `F`. -/ theorem nonempty_hom_of_forall_finite_subgraph_hom [Finite W] (h : ∀ G' : G.Subgraph, G'.verts.Finite → G'.coe →g F) : Nonempty (G →g F) := by -- Obtain a `Fintype` instance for `W`. cases nonempty_fintype W -- Establish the required interface instances. haveI : ∀ G' : G.Finsubgraphᵒᵖ, Nonempty ((finsubgraphHomFunctor G F).obj G') := fun G' => ⟨h G'.unop G'.unop.property⟩ haveI : ∀ G' : G.Finsubgraphᵒᵖ, Fintype ((finsubgraphHomFunctor G F).obj G') := by intro G' haveI : Fintype (G'.unop.val.verts : Type u) := G'.unop.property.fintype haveI : Fintype (↥G'.unop.val.verts → W) := by classical exact Pi.fintype exact Fintype.ofInjective (fun f => f.toFun) RelHom.coe_fn_injective -- Use compactness to obtain a section. obtain ⟨u, hu⟩ := nonempty_sections_of_finite_inverse_system (finsubgraphHomFunctor G F) refine ⟨⟨fun v => ?_, ?_⟩⟩ · -- Map each vertex using the homomorphism provided for its singleton subgraph. exact (u (Opposite.op (singletonFinsubgraph v))).toFun ⟨v, by unfold singletonFinsubgraph simp⟩ · -- Prove that the above mapping preserves adjacency. intro v v' e simp only /- The homomorphism for each edge's singleton subgraph agrees with those for its source and target vertices. -/ have hv : Opposite.op (finsubgraphOfAdj e) ⟶ Opposite.op (singletonFinsubgraph v) := Quiver.Hom.op (CategoryTheory.homOfLE singletonFinsubgraph_le_adj_left) have hv' : Opposite.op (finsubgraphOfAdj e) ⟶ Opposite.op (singletonFinsubgraph v') := Quiver.Hom.op (CategoryTheory.homOfLE singletonFinsubgraph_le_adj_right) rw [← hu hv, ← hu hv'] -- Porting note: was `apply Hom.map_adj` refine Hom.map_adj (u (Opposite.op (finsubgraphOfAdj e))) ?_ -- `v` and `v'` are definitionally adjacent in `finsubgraphOfAdj e` simp [finsubgraphOfAdj] end SimpleGraph
Combinatorics\SimpleGraph\Girth.lean
/- Copyright (c) 2023 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import Mathlib.Combinatorics.SimpleGraph.Acyclic import Mathlib.Data.ENat.Lattice /-! # Girth of a simple graph This file defines the girth and the extended girth of a simple graph as the length of its smallest cycle, they give `0` or `∞` respectively if the graph is acyclic. -/ namespace SimpleGraph variable {α : Type*} {G : SimpleGraph α} section egirth /-- The extended girth of a simple graph is the length of its smallest cycle, or `∞` if the graph is acyclic. -/ noncomputable def egirth (G : SimpleGraph α) : ℕ∞ := ⨅ a, ⨅ w : G.Walk a a, ⨅ _ : w.IsCycle, w.length @[simp] lemma le_egirth {n : ℕ∞} : n ≤ G.egirth ↔ ∀ a (w : G.Walk a a), w.IsCycle → n ≤ w.length := by simp [egirth] @[simp] lemma egirth_eq_top : G.egirth = ⊤ ↔ G.IsAcyclic := by simp [egirth, IsAcyclic] protected alias ⟨_, IsAcyclic.egirth_eq_top⟩ := egirth_eq_top lemma egirth_anti : Antitone (egirth : SimpleGraph α → ℕ∞) := fun G H h ↦ iInf_mono fun a ↦ iInf₂_mono' fun w hw ↦ ⟨w.mapLe h, hw.mapLe _, by simp⟩ lemma exists_egirth_eq_length : (∃ (a : α) (w : G.Walk a a), w.IsCycle ∧ G.egirth = w.length) ↔ ¬ G.IsAcyclic := by refine ⟨?_, fun h ↦ ?_⟩ · rintro ⟨a, w, hw, _⟩ hG exact hG _ hw · simp_rw [← egirth_eq_top, ← Ne.eq_def, egirth, iInf_subtype', iInf_sigma', ENat.iInf_coe_ne_top, ← exists_prop, Subtype.exists', Sigma.exists', eq_comm] at h ⊢ exact ciInf_mem _ lemma three_le_egirth : 3 ≤ G.egirth := by by_cases h : G.IsAcyclic · rw [← egirth_eq_top] at h rw [h] apply le_top · rw [← exists_egirth_eq_length] at h have ⟨_, _, _⟩ := h simp_all only [Nat.cast_inj, Nat.ofNat_le_cast, Walk.IsCycle.three_le_length] @[simp] lemma egirth_bot : egirth (⊥ : SimpleGraph α) = ⊤ := by simp end egirth section girth /-- The girth of a simple graph is the length of its smallest cycle, or junk value `0` if the graph is acyclic. -/ noncomputable def girth (G : SimpleGraph α) : ℕ := G.egirth.toNat lemma three_le_girth (hG : ¬ G.IsAcyclic) : 3 ≤ G.girth := ENat.toNat_le_toNat three_le_egirth <| egirth_eq_top.not.mpr hG lemma girth_eq_zero : G.girth = 0 ↔ G.IsAcyclic := ⟨fun h ↦ not_not.mp <| three_le_girth.mt <| by omega, fun h ↦ by simp [girth, h]⟩ protected alias ⟨_, IsAcyclic.girth_eq_zero⟩ := girth_eq_zero lemma girth_anti {G' : SimpleGraph α} (hab : G ≤ G') (h : ¬ G.IsAcyclic) : G'.girth ≤ G.girth := ENat.toNat_le_toNat (egirth_anti hab) <| egirth_eq_top.not.mpr h lemma exists_girth_eq_length : (∃ (a : α) (w : G.Walk a a), w.IsCycle ∧ G.girth = w.length) ↔ ¬ G.IsAcyclic := by refine ⟨by tauto, fun h ↦ ?_⟩ obtain ⟨_, _, _⟩ := exists_egirth_eq_length.mpr h simp_all only [girth, ENat.toNat_coe] tauto @[simp] lemma girth_bot : girth (⊥ : SimpleGraph α) = 0 := by simp [girth] end girth end SimpleGraph
Combinatorics\SimpleGraph\Hamiltonian.lean
/- Copyright (c) 2023 Bhavik Mehta, Rishi Mehta, Linus Sommer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Rishi Mehta, Linus Sommer -/ import Mathlib.Algebra.Order.Ring.Nat import Mathlib.Combinatorics.SimpleGraph.Path /-! # Hamiltonian Graphs In this file we introduce hamiltonian paths, cycles and graphs. ## Main definitions - `SimpleGraph.Walk.IsHamiltonian`: Predicate for a walk to be hamiltonian. - `SimpleGraph.Walk.IsHamiltonianCycle`: Predicate for a walk to be a hamiltonian cycle. - `SimpleGraph.IsHamiltonian`: Predicate for a graph to be hamiltonian. -/ open Finset Function namespace SimpleGraph variable {α β : Type*} [DecidableEq α] [DecidableEq β] {G : SimpleGraph α} {a b : α} {p : G.Walk a b} namespace Walk /-- A hamiltonian path is a walk `p` that visits every vertex exactly once. Note that while this definition doesn't contain that `p` is a path, `p.isPath` gives that. -/ def IsHamiltonian (p : G.Walk a b) : Prop := ∀ a, p.support.count a = 1 lemma IsHamiltonian.map {H : SimpleGraph β} (f : G →g H) (hf : Bijective f) (hp : p.IsHamiltonian) : (p.map f).IsHamiltonian := by simp [IsHamiltonian, hf.surjective.forall, hf.injective, hp _] /-- A hamiltonian path visits every vertex. -/ @[simp] lemma IsHamiltonian.mem_support (hp : p.IsHamiltonian) (c : α) : c ∈ p.support := by simp only [← List.count_pos_iff_mem, hp _, Nat.zero_lt_one] /-- Hamiltonian paths are paths. -/ lemma IsHamiltonian.isPath (hp : p.IsHamiltonian) : p.IsPath := IsPath.mk' <| List.nodup_iff_count_le_one.2 <| (le_of_eq <| hp ·) /-- A path whose support contains every vertex is hamiltonian. -/ lemma IsPath.isHamiltonian_of_mem (hp : p.IsPath) (hp' : ∀ w, w ∈ p.support) : p.IsHamiltonian := fun _ ↦ le_antisymm (List.nodup_iff_count_le_one.1 hp.support_nodup _) (List.count_pos_iff_mem.2 (hp' _)) lemma IsPath.isHamiltonian_iff (hp : p.IsPath) : p.IsHamiltonian ↔ ∀ w, w ∈ p.support := ⟨(·.mem_support), hp.isHamiltonian_of_mem⟩ section variable [Fintype α] [Fintype β] /-- The support of a hamiltonian walk is the entire vertex set. -/ lemma IsHamiltonian.support_toFinset (hp : p.IsHamiltonian) : p.support.toFinset = Finset.univ := by simp [eq_univ_iff_forall, hp] /-- The length of a hamiltonian path is one less than the number of vertices of the graph. -/ lemma IsHamiltonian.length_eq (hp : p.IsHamiltonian) : p.length = Fintype.card α - 1 := eq_tsub_of_add_eq $ by rw [← length_support, ← List.sum_toFinset_count_eq_length, Finset.sum_congr rfl fun _ _ ↦ hp _, ← card_eq_sum_ones, hp.support_toFinset, card_univ] end /-- A hamiltonian cycle is a cycle that visits every vertex once. -/ structure IsHamiltonianCycle (p : G.Walk a a) extends p.IsCycle : Prop := isHamiltonian_tail : (p.tail toIsCycle.not_nil).IsHamiltonian variable {p : G.Walk a a} lemma IsHamiltonianCycle.isCycle (hp : p.IsHamiltonianCycle) : p.IsCycle := hp.toIsCycle lemma IsHamiltonianCycle.map {H : SimpleGraph β} (f : G →g H) (hf : Bijective f) (hp : p.IsHamiltonianCycle) : (p.map f).IsHamiltonianCycle where toIsCycle := hp.isCycle.map hf.injective isHamiltonian_tail := by simp only [IsHamiltonian, support_tail, support_map, ne_eq, List.map_eq_nil, support_ne_nil, not_false_eq_true, List.count_tail, List.head_map, beq_iff_eq, hf.surjective.forall, hf.injective, List.count_map_of_injective] intro x rcases p with (_ | ⟨y, p⟩) · cases hp.ne_nil rfl simp only [support_cons, List.count_cons, beq_iff_eq, List.head_cons, hf.injective.eq_iff, add_tsub_cancel_right] exact hp.isHamiltonian_tail _ lemma isHamiltonianCycle_isCycle_and_isHamiltonian_tail : p.IsHamiltonianCycle ↔ ∃ h : p.IsCycle, (p.tail h.not_nil).IsHamiltonian := ⟨fun ⟨h, h'⟩ ↦ ⟨h, h'⟩, fun ⟨h, h'⟩ ↦ ⟨h, h'⟩⟩ lemma isHamiltonianCycle_iff_isCycle_and_support_count_tail_eq_one : p.IsHamiltonianCycle ↔ p.IsCycle ∧ ∀ a, (support p).tail.count a = 1 := by simp only [isHamiltonianCycle_isCycle_and_isHamiltonian_tail, IsHamiltonian, support_tail, exists_prop] /-- A hamiltonian cycle visits every vertex. -/ lemma IsHamiltonianCycle.mem_support (hp : p.IsHamiltonianCycle) (b : α) : b ∈ p.support := List.mem_of_mem_tail <| support_tail p _ ▸ hp.isHamiltonian_tail.mem_support _ /-- The length of a hamiltonian cycle is the number of vertices. -/ lemma IsHamiltonianCycle.length_eq [Fintype α] (hp : p.IsHamiltonianCycle) : p.length = Fintype.card α := by rw [← length_tail_add_one hp.not_nil, hp.isHamiltonian_tail.length_eq, Nat.sub_add_cancel] rw [Nat.succ_le, Fintype.card_pos_iff] exact ⟨a⟩ lemma IsHamiltonianCycle.count_support_self (hp : p.IsHamiltonianCycle) : p.support.count a = 2 := by rw [support_eq_cons, List.count_cons_self, ← support_tail, hp.isHamiltonian_tail] lemma IsHamiltonianCycle.support_count_of_ne (hp : p.IsHamiltonianCycle) (h : a ≠ b) : p.support.count b = 1 := by rw [← cons_support_tail p, List.count_cons_of_ne h.symm, hp.isHamiltonian_tail] end Walk variable [Fintype α] /-- A hamiltonian graph is a graph that contains a hamiltonian cycle. By convention, the singleton graph is considered to be hamiltonian. -/ def IsHamiltonian (G : SimpleGraph α) : Prop := Fintype.card α ≠ 1 → ∃ a, ∃ p : G.Walk a a, p.IsHamiltonianCycle lemma IsHamiltonian.mono {H : SimpleGraph α} (hGH : G ≤ H) (hG : G.IsHamiltonian) : H.IsHamiltonian := fun hα ↦ let ⟨_, p, hp⟩ := hG hα; ⟨_, p.map $ .ofLE hGH, hp.map _ bijective_id⟩ lemma IsHamiltonian.connected (hG : G.IsHamiltonian) : G.Connected where preconnected a b := by obtain rfl | hab := eq_or_ne a b · rfl have : Nontrivial α := ⟨a, b, hab⟩ obtain ⟨_, p, hp⟩ := hG Fintype.one_lt_card.ne' have a_mem := hp.mem_support a have b_mem := hp.mem_support b exact ((p.takeUntil a a_mem).reverse.append $ p.takeUntil b b_mem).reachable nonempty := not_isEmpty_iff.1 fun _ ↦ by simpa using hG $ by simp [@Fintype.card_eq_zero] end SimpleGraph
Combinatorics\SimpleGraph\Hasse.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 Mathlib.Combinatorics.SimpleGraph.Prod import Mathlib.Data.Fin.SuccPred import Mathlib.Data.Nat.SuccPred import Mathlib.Order.SuccPred.Relation import Mathlib.Tactic.FinCases /-! # The Hasse diagram as a graph This file defines the Hasse diagram of an order (graph of `CovBy`, the covering relation) and the path graph on `n` vertices. ## Main declarations * `SimpleGraph.hasse`: Hasse diagram of an order. * `SimpleGraph.pathGraph`: Path graph on `n` vertices. -/ open Order OrderDual Relation namespace SimpleGraph variable (α β : Type*) section Preorder variable [Preorder α] [Preorder β] /-- The Hasse diagram of an order as a simple graph. The graph of the covering relation. -/ def hasse : SimpleGraph α where Adj a b := a ⋖ b ∨ b ⋖ a symm _a _b := Or.symm loopless _a h := h.elim (irrefl _) (irrefl _) variable {α β} {a b : α} @[simp] theorem hasse_adj : (hasse α).Adj a b ↔ a ⋖ b ∨ b ⋖ a := Iff.rfl /-- `αᵒᵈ` and `α` have the same Hasse diagram. -/ def hasseDualIso : hasse αᵒᵈ ≃g hasse α := { ofDual with map_rel_iff' := by simp [or_comm] } @[simp] theorem hasseDualIso_apply (a : αᵒᵈ) : hasseDualIso a = ofDual a := rfl @[simp] theorem hasseDualIso_symm_apply (a : α) : hasseDualIso.symm a = toDual a := rfl end Preorder section PartialOrder variable [PartialOrder α] [PartialOrder β] @[simp] theorem hasse_prod : hasse (α × β) = hasse α □ hasse β := by ext x y simp_rw [boxProd_adj, hasse_adj, Prod.covBy_iff, or_and_right, @eq_comm _ y.1, @eq_comm _ y.2, or_or_or_comm] end PartialOrder section LinearOrder variable [LinearOrder α] theorem hasse_preconnected_of_succ [SuccOrder α] [IsSuccArchimedean α] : (hasse α).Preconnected := fun a b => by rw [reachable_iff_reflTransGen] exact reflTransGen_of_succ _ (fun c hc => Or.inl <| covBy_succ_of_not_isMax hc.2.not_isMax) fun c hc => Or.inr <| covBy_succ_of_not_isMax hc.2.not_isMax theorem hasse_preconnected_of_pred [PredOrder α] [IsPredArchimedean α] : (hasse α).Preconnected := fun a b => by rw [reachable_iff_reflTransGen, ← reflTransGen_swap] exact reflTransGen_of_pred _ (fun c hc => Or.inl <| pred_covBy_of_not_isMin hc.1.not_isMin) fun c hc => Or.inr <| pred_covBy_of_not_isMin hc.1.not_isMin end LinearOrder /-- The path graph on `n` vertices. -/ def pathGraph (n : ℕ) : SimpleGraph (Fin n) := hasse _ theorem pathGraph_adj {n : ℕ} {u v : Fin n} : (pathGraph n).Adj u v ↔ u.val + 1 = v.val ∨ v.val + 1 = u.val := by simp only [pathGraph, hasse] simp_rw [← Fin.coe_covBy_iff, Nat.covBy_iff_succ_eq] theorem pathGraph_preconnected (n : ℕ) : (pathGraph n).Preconnected := hasse_preconnected_of_succ _ theorem pathGraph_connected (n : ℕ) : (pathGraph (n + 1)).Connected := ⟨pathGraph_preconnected _⟩ theorem pathGraph_two_eq_top : pathGraph 2 = ⊤ := by ext u v fin_cases u <;> fin_cases v <;> simp [pathGraph, ← Fin.coe_covBy_iff, Nat.covBy_iff_succ_eq] end SimpleGraph
Combinatorics\SimpleGraph\IncMatrix.lean
/- Copyright (c) 2021 Gabriel Moise. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Moise, Yaël Dillies, Kyle Miller -/ import Mathlib.Combinatorics.SimpleGraph.Finite import Mathlib.Data.Finset.Sym import Mathlib.Data.Matrix.Basic /-! # Incidence matrix of a simple graph This file defines the unoriented incidence matrix of a simple graph. ## Main definitions * `SimpleGraph.incMatrix`: `G.incMatrix R` is the incidence matrix of `G` over the ring `R`. ## Main results * `SimpleGraph.incMatrix_mul_transpose_diag`: The diagonal entries of the product of `G.incMatrix R` and its transpose are the degrees of the vertices. * `SimpleGraph.incMatrix_mul_transpose`: Gives a complete description of the product of `G.incMatrix R` and its transpose; the diagonal is the degrees of each vertex, and the off-diagonals are 1 or 0 depending on whether or not the vertices are adjacent. * `SimpleGraph.incMatrix_transpose_mul_diag`: The diagonal entries of the product of the transpose of `G.incMatrix R` and `G.inc_matrix R` are `2` or `0` depending on whether or not the unordered pair is an edge of `G`. ## Implementation notes The usual definition of an incidence matrix has one row per vertex and one column per edge. However, this definition has columns indexed by all of `Sym2 α`, where `α` is the vertex type. This appears not to change the theory, and for simple graphs it has the nice effect that every incidence matrix for each `SimpleGraph α` has the same type. ## TODO * Define the oriented incidence matrices for oriented graphs. * Define the graph Laplacian of a simple graph using the oriented incidence matrix from an arbitrary orientation of a simple graph. -/ open Finset Matrix SimpleGraph Sym2 open Matrix namespace SimpleGraph variable (R : Type*) {α : Type*} (G : SimpleGraph α) /-- `G.incMatrix R` is the `α × Sym2 α` matrix whose `(a, e)`-entry is `1` if `e` is incident to `a` and `0` otherwise. -/ noncomputable def incMatrix [Zero R] [One R] : Matrix α (Sym2 α) R := fun a => (G.incidenceSet a).indicator 1 variable {R} theorem incMatrix_apply [Zero R] [One R] {a : α} {e : Sym2 α} : G.incMatrix R a e = (G.incidenceSet a).indicator 1 e := rfl /-- Entries of the incidence matrix can be computed given additional decidable instances. -/ theorem incMatrix_apply' [Zero R] [One R] [DecidableEq α] [DecidableRel G.Adj] {a : α} {e : Sym2 α} : G.incMatrix R a e = if e ∈ G.incidenceSet a then 1 else 0 := by unfold incMatrix Set.indicator convert rfl section MulZeroOneClass variable [MulZeroOneClass R] {a b : α} {e : Sym2 α} theorem incMatrix_apply_mul_incMatrix_apply : G.incMatrix R a e * G.incMatrix R b e = (G.incidenceSet a ∩ G.incidenceSet b).indicator 1 e := by classical simp only [incMatrix, Set.indicator_apply, ite_zero_mul_ite_zero, Pi.one_apply, mul_one, Set.mem_inter_iff] theorem incMatrix_apply_mul_incMatrix_apply_of_not_adj (hab : a ≠ b) (h : ¬G.Adj a b) : G.incMatrix R a e * G.incMatrix R b e = 0 := by rw [incMatrix_apply_mul_incMatrix_apply, Set.indicator_of_not_mem] rw [G.incidenceSet_inter_incidenceSet_of_not_adj h hab] exact Set.not_mem_empty e theorem incMatrix_of_not_mem_incidenceSet (h : e ∉ G.incidenceSet a) : G.incMatrix R a e = 0 := by rw [incMatrix_apply, Set.indicator_of_not_mem h] theorem incMatrix_of_mem_incidenceSet (h : e ∈ G.incidenceSet a) : G.incMatrix R a e = 1 := by rw [incMatrix_apply, Set.indicator_of_mem h, Pi.one_apply] variable [Nontrivial R] theorem incMatrix_apply_eq_zero_iff : G.incMatrix R a e = 0 ↔ e ∉ G.incidenceSet a := by simp only [incMatrix_apply, Set.indicator_apply_eq_zero, Pi.one_apply, one_ne_zero] theorem incMatrix_apply_eq_one_iff : G.incMatrix R a e = 1 ↔ e ∈ G.incidenceSet a := by -- Porting note: was `convert one_ne_zero.ite_eq_left_iff; infer_instance` unfold incMatrix Set.indicator simp only [Pi.one_apply] apply Iff.intro <;> intro h · split at h <;> simp_all only [zero_ne_one] · simp_all only [ite_true] end MulZeroOneClass section NonAssocSemiring variable [NonAssocSemiring R] {a b : α} {e : Sym2 α} theorem sum_incMatrix_apply [Fintype (Sym2 α)] [Fintype (neighborSet G a)] : ∑ e, G.incMatrix R a e = G.degree a := by classical simp [incMatrix_apply', sum_boole, Set.filter_mem_univ_eq_toFinset] theorem incMatrix_mul_transpose_diag [Fintype (Sym2 α)] [Fintype (neighborSet G a)] : (G.incMatrix R * (G.incMatrix R)ᵀ) a a = G.degree a := by classical rw [← sum_incMatrix_apply] simp only [mul_apply, incMatrix_apply', transpose_apply, mul_ite, mul_one, mul_zero] simp_all only [ite_true, sum_boole] theorem sum_incMatrix_apply_of_mem_edgeSet [Fintype α] : e ∈ G.edgeSet → ∑ a, G.incMatrix R a e = 2 := by classical refine e.ind ?_ intro a b h rw [mem_edgeSet] at h rw [← Nat.cast_two, ← card_pair h.ne] simp only [incMatrix_apply', sum_boole, mk'_mem_incidenceSet_iff, h, true_and_iff] congr 2 ext e simp only [mem_filter, mem_univ, true_and_iff, mem_insert, mem_singleton] theorem sum_incMatrix_apply_of_not_mem_edgeSet [Fintype α] (h : e ∉ G.edgeSet) : ∑ a, G.incMatrix R a e = 0 := sum_eq_zero fun _ _ => G.incMatrix_of_not_mem_incidenceSet fun he => h he.1 theorem incMatrix_transpose_mul_diag [Fintype α] [Decidable (e ∈ G.edgeSet)] : ((G.incMatrix R)ᵀ * G.incMatrix R) e e = if e ∈ G.edgeSet then 2 else 0 := by classical simp only [Matrix.mul_apply, incMatrix_apply', transpose_apply, ite_zero_mul_ite_zero, one_mul, sum_boole, and_self_iff] split_ifs with h · revert h refine e.ind ?_ intro v w h rw [← Nat.cast_two, ← card_pair (G.ne_of_adj h)] simp only [mk'_mem_incidenceSet_iff, G.mem_edgeSet.mp h, true_and, mem_univ, forall_true_left, forall_eq_or_imp, forall_eq, and_self, mem_singleton, ne_eq] congr 2 ext u simp · revert h refine e.ind ?_ intro v w h simp [mk'_mem_incidenceSet_iff, G.mem_edgeSet.not.mp h] end NonAssocSemiring section Semiring variable [Fintype (Sym2 α)] [Semiring R] {a b : α} {e : Sym2 α} theorem incMatrix_mul_transpose_apply_of_adj (h : G.Adj a b) : (G.incMatrix R * (G.incMatrix R)ᵀ) a b = (1 : R) := by classical simp_rw [Matrix.mul_apply, Matrix.transpose_apply, incMatrix_apply_mul_incMatrix_apply, Set.indicator_apply, Pi.one_apply, sum_boole] convert @Nat.cast_one R _ convert card_singleton s(a, b) rw [← coe_eq_singleton, coe_filter_univ] exact G.incidenceSet_inter_incidenceSet_of_adj h theorem incMatrix_mul_transpose [∀ a, Fintype (neighborSet G a)] [DecidableEq α] [DecidableRel G.Adj] : G.incMatrix R * (G.incMatrix R)ᵀ = fun a b => if a = b then (G.degree a : R) else if G.Adj a b then 1 else 0 := by ext a b split_ifs with h h' · subst b exact incMatrix_mul_transpose_diag (R := R) G · exact G.incMatrix_mul_transpose_apply_of_adj h' · simp only [Matrix.mul_apply, Matrix.transpose_apply, G.incMatrix_apply_mul_incMatrix_apply_of_not_adj h h', sum_const_zero] end Semiring end SimpleGraph
Combinatorics\SimpleGraph\Init.lean
/- Copyright (c) 2023 Jannis Limperg. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jannis Limperg -/ import Aesop /-! # SimpleGraph Rule Set This module defines the `SimpleGraph` Aesop rule set which is used by the `aesop_graph` tactic. Aesop rule sets only become visible once the file in which they're declared is imported, so we must put this declaration into its own file. -/ declare_aesop_rule_sets [SimpleGraph]
Combinatorics\SimpleGraph\LapMatrix.lean
/- Copyright (c) 2023 Adrian Wüthrich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adrian Wüthrich -/ import Mathlib.Combinatorics.SimpleGraph.AdjMatrix import Mathlib.LinearAlgebra.Matrix.PosDef /-! # Laplacian Matrix This module defines the Laplacian matrix of a graph, and proves some of its elementary properties. ## Main definitions & Results * `SimpleGraph.degMatrix`: The degree matrix of a simple graph * `SimpleGraph.lapMatrix`: The Laplacian matrix of a simple graph, defined as the difference between the degree matrix and the adjacency matrix. * `isPosSemidef_lapMatrix`: The Laplacian matrix is positive semidefinite. * `rank_ker_lapMatrix_eq_card_ConnectedComponent`: The number of connected components in `G` is the dimension of the nullspace of its Laplacian matrix. -/ open Finset Matrix namespace SimpleGraph variable {V : Type*} (R : Type*) variable [Fintype V] [DecidableEq V] (G : SimpleGraph V) [DecidableRel G.Adj] /-- The diagonal matrix consisting of the degrees of the vertices in the graph. -/ def degMatrix [AddMonoidWithOne R] : Matrix V V R := Matrix.diagonal (G.degree ·) /-- The *Laplacian matrix* `lapMatrix G R` of a graph `G` is the matrix `L = D - A` where `D` is the degree and `A` the adjacency matrix of `G`. -/ def lapMatrix [AddGroupWithOne R] : Matrix V V R := G.degMatrix R - G.adjMatrix R variable {R} theorem isSymm_degMatrix [AddMonoidWithOne R] : (G.degMatrix R).IsSymm := isSymm_diagonal _ theorem isSymm_lapMatrix [AddGroupWithOne R] : (G.lapMatrix R).IsSymm := (isSymm_degMatrix _).sub (isSymm_adjMatrix _) theorem degMatrix_mulVec_apply [NonAssocSemiring R] (v : V) (vec : V → R) : (G.degMatrix R *ᵥ vec) v = G.degree v * vec v := by rw [degMatrix, mulVec_diagonal] theorem lapMatrix_mulVec_apply [NonAssocRing R] (v : V) (vec : V → R) : (G.lapMatrix R *ᵥ vec) v = G.degree v * vec v - ∑ u ∈ G.neighborFinset v, vec u := by simp_rw [lapMatrix, sub_mulVec, Pi.sub_apply, degMatrix_mulVec_apply, adjMatrix_mulVec_apply] theorem lapMatrix_mulVec_const_eq_zero [Ring R] : mulVec (G.lapMatrix R) (fun _ ↦ 1) = 0 := by ext1 i rw [lapMatrix_mulVec_apply] simp theorem dotProduct_mulVec_degMatrix [CommRing R] (x : V → R) : x ⬝ᵥ (G.degMatrix R *ᵥ x) = ∑ i : V, G.degree i * x i * x i := by simp only [dotProduct, degMatrix, mulVec_diagonal, ← mul_assoc, mul_comm] variable (R) theorem degree_eq_sum_if_adj [AddCommMonoidWithOne R] (i : V) : (G.degree i : R) = ∑ j : V, if G.Adj i j then 1 else 0 := by unfold degree neighborFinset neighborSet rw [sum_boole, Set.toFinset_setOf] /-- Let $L$ be the graph Laplacian and let $x \in \mathbb{R}$, then $$x^{\top} L x = \sum_{i \sim j} (x_{i}-x_{j})^{2}$$, where $\sim$ denotes the adjacency relation -/ theorem lapMatrix_toLinearMap₂' [Field R] [CharZero R] (x : V → R) : toLinearMap₂' R (G.lapMatrix R) x x = (∑ i : V, ∑ j : V, if G.Adj i j then (x i - x j)^2 else 0) / 2 := by simp_rw [toLinearMap₂'_apply', lapMatrix, sub_mulVec, dotProduct_sub, dotProduct_mulVec_degMatrix, dotProduct_mulVec_adjMatrix, ← sum_sub_distrib, degree_eq_sum_if_adj, sum_mul, ite_mul, one_mul, zero_mul, ← sum_sub_distrib, ite_sub_ite, sub_zero] rw [← add_self_div_two (∑ x_1 : V, ∑ x_2 : V, _)] conv_lhs => enter [1,2,2,i,2,j]; rw [if_congr (adj_comm G i j) rfl rfl] conv_lhs => enter [1,2]; rw [Finset.sum_comm] simp_rw [← sum_add_distrib, ite_add_ite] congr 2 with i congr 2 with j ring_nf /-- The Laplacian matrix is positive semidefinite -/ theorem posSemidef_lapMatrix [LinearOrderedField R] [StarRing R] [TrivialStar R] : PosSemidef (G.lapMatrix R) := by constructor · rw [IsHermitian, conjTranspose_eq_transpose_of_trivial, isSymm_lapMatrix] · intro x rw [star_trivial, ← toLinearMap₂'_apply', lapMatrix_toLinearMap₂'] positivity theorem lapMatrix_toLinearMap₂'_apply'_eq_zero_iff_forall_adj [LinearOrderedField R] (x : V → R) : Matrix.toLinearMap₂' R (G.lapMatrix R) x x = 0 ↔ ∀ i j : V, G.Adj i j → x i = x j := by simp (disch := intros; positivity) [lapMatrix_toLinearMap₂', sum_eq_zero_iff_of_nonneg, sub_eq_zero] theorem lapMatrix_toLin'_apply_eq_zero_iff_forall_adj (x : V → ℝ) : Matrix.toLin' (G.lapMatrix ℝ) x = 0 ↔ ∀ i j : V, G.Adj i j → x i = x j := by rw [← (posSemidef_lapMatrix ℝ G).toLinearMap₂'_zero_iff, star_trivial, lapMatrix_toLinearMap₂'_apply'_eq_zero_iff_forall_adj] theorem lapMatrix_toLinearMap₂'_apply'_eq_zero_iff_forall_reachable (x : V → ℝ) : Matrix.toLinearMap₂' ℝ (G.lapMatrix ℝ) x x = 0 ↔ ∀ i j : V, G.Reachable i j → x i = x j := by rw [lapMatrix_toLinearMap₂'_apply'_eq_zero_iff_forall_adj] refine ⟨?_, fun h i j hA ↦ h i j hA.reachable⟩ intro h i j ⟨w⟩ induction' w with w i j _ hA _ h' · rfl · exact (h i j hA).trans h' theorem lapMatrix_toLin'_apply_eq_zero_iff_forall_reachable (x : V → ℝ) : Matrix.toLin' (G.lapMatrix ℝ) x = 0 ↔ ∀ i j : V, G.Reachable i j → x i = x j := by rw [← (posSemidef_lapMatrix ℝ G).toLinearMap₂'_zero_iff, star_trivial, lapMatrix_toLinearMap₂'_apply'_eq_zero_iff_forall_reachable] section variable [DecidableEq G.ConnectedComponent] lemma mem_ker_toLin'_lapMatrix_of_connectedComponent {G : SimpleGraph V} [DecidableRel G.Adj] [DecidableEq G.ConnectedComponent] (c : G.ConnectedComponent) : (fun i ↦ if connectedComponentMk G i = c then 1 else 0) ∈ LinearMap.ker (toLin' (lapMatrix ℝ G)) := by rw [LinearMap.mem_ker, lapMatrix_toLin'_apply_eq_zero_iff_forall_reachable] intro i j h split_ifs with h₁ h₂ h₃ · rfl · rw [← ConnectedComponent.eq] at h exact (h₂ (h₁ ▸ h.symm)).elim · rw [← ConnectedComponent.eq] at h exact (h₁ (h₃ ▸ h)).elim · rfl /-- Given a connected component `c` of a graph `G`, `lapMatrix_ker_basis_aux c` is the map `V → ℝ` which is `1` on the vertices in `c` and `0` elsewhere. The family of these maps indexed by the connected components of `G` proves to be a basis of the kernel of `lapMatrix G R` -/ def lapMatrix_ker_basis_aux (c : G.ConnectedComponent) : LinearMap.ker (Matrix.toLin' (G.lapMatrix ℝ)) := ⟨fun i ↦ if G.connectedComponentMk i = c then (1 : ℝ) else 0, mem_ker_toLin'_lapMatrix_of_connectedComponent c⟩ lemma linearIndependent_lapMatrix_ker_basis_aux : LinearIndependent ℝ (lapMatrix_ker_basis_aux G) := by rw [Fintype.linearIndependent_iff] intro g h0 rw [Subtype.ext_iff] at h0 have h : ∑ c, g c • lapMatrix_ker_basis_aux G c = fun i ↦ g (connectedComponentMk G i) := by simp only [lapMatrix_ker_basis_aux, SetLike.mk_smul_mk, AddSubmonoid.coe_finset_sum] conv_lhs => enter [2, c, j]; rw [Pi.smul_apply, smul_eq_mul, mul_ite, mul_one, mul_zero] ext i simp only [Finset.sum_apply, sum_ite_eq, mem_univ, ite_true] rw [h] at h0 intro c obtain ⟨i, h'⟩ : ∃ i : V, G.connectedComponentMk i = c := Quot.exists_rep c exact h' ▸ congrFun h0 i lemma top_le_span_range_lapMatrix_ker_basis_aux : ⊤ ≤ Submodule.span ℝ (Set.range (lapMatrix_ker_basis_aux G)) := by intro x _ rw [mem_span_range_iff_exists_fun] use Quot.lift x.val (by rw [← lapMatrix_toLin'_apply_eq_zero_iff_forall_reachable G x, LinearMap.map_coe_ker]) ext j simp only [lapMatrix_ker_basis_aux, AddSubmonoid.coe_finset_sum, Submodule.coe_toAddSubmonoid, SetLike.val_smul, Finset.sum_apply, Pi.smul_apply, smul_eq_mul, mul_ite, mul_one, mul_zero, sum_ite_eq, mem_univ, ite_true] rfl /-- `lapMatrix_ker_basis G` is a basis of the nullspace indexed by its connected components, the basis is made up of the functions `V → ℝ` which are `1` on the vertices of the given connected component and `0` elsewhere. -/ noncomputable def lapMatrix_ker_basis := Basis.mk (linearIndependent_lapMatrix_ker_basis_aux G) (top_le_span_range_lapMatrix_ker_basis_aux G) end /-- The number of connected components in `G` is the dimension of the nullspace its Laplacian. -/ theorem card_ConnectedComponent_eq_rank_ker_lapMatrix : Fintype.card G.ConnectedComponent = FiniteDimensional.finrank ℝ (LinearMap.ker (Matrix.toLin' (G.lapMatrix ℝ))) := by classical rw [FiniteDimensional.finrank_eq_card_basis (lapMatrix_ker_basis G)] end SimpleGraph
Combinatorics\SimpleGraph\Maps.lean
/- Copyright (c) 2021 Hunter Monroe. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Hunter Monroe, Kyle Miller -/ import Mathlib.Combinatorics.SimpleGraph.Dart import Mathlib.Data.FunLike.Fintype /-! # Maps between graphs This file defines two functions and three structures relating graphs. The structures directly correspond to the classification of functions as injective, surjective and bijective, and have corresponding notation. ## Main definitions * `SimpleGraph.map`: the graph obtained by pushing the adjacency relation through an injective function between vertex types. * `SimpleGraph.comap`: the graph obtained by pulling the adjacency relation behind an arbitrary function between vertex types. * `SimpleGraph.induce`: the subgraph induced by the given vertex set, a wrapper around `comap`. * `SimpleGraph.spanningCoe`: the supergraph without any additional edges, a wrapper around `map`. * `SimpleGraph.Hom`, `G →g H`: a graph homomorphism from `G` to `H`. * `SimpleGraph.Embedding`, `G ↪g H`: a graph embedding of `G` in `H`. * `SimpleGraph.Iso`, `G ≃g H`: a graph isomorphism between `G` and `H`. Note that a graph embedding is a stronger notion than an injective graph homomorphism, since its image is an induced subgraph. ## Implementation notes Morphisms of graphs are abbreviations for `RelHom`, `RelEmbedding` and `RelIso`. To make use of pre-existing simp lemmas, definitions involving morphisms are abbreviations as well. -/ open Function namespace SimpleGraph variable {V W X : Type*} (G : SimpleGraph V) (G' : SimpleGraph W) {u v : V} /-! ## Map and comap -/ /-- Given an injective function, there is a covariant induced map on graphs by pushing forward the adjacency relation. This is injective (see `SimpleGraph.map_injective`). -/ protected def map (f : V ↪ W) (G : SimpleGraph V) : SimpleGraph W where Adj := Relation.Map G.Adj f f symm a b := by -- Porting note: `obviously` used to handle this rintro ⟨v, w, h, rfl, rfl⟩ use w, v, h.symm, rfl loopless a := by -- Porting note: `obviously` used to handle this rintro ⟨v, w, h, rfl, h'⟩ exact h.ne (f.injective h'.symm) instance instDecidableMapAdj {f : V ↪ W} {a b} [Decidable (Relation.Map G.Adj f f a b)] : Decidable ((G.map f).Adj a b) := ‹Decidable (Relation.Map G.Adj f f a b)› @[simp] theorem map_adj (f : V ↪ W) (G : SimpleGraph V) (u v : W) : (G.map f).Adj u v ↔ ∃ u' v' : V, G.Adj u' v' ∧ f u' = u ∧ f v' = v := Iff.rfl lemma map_adj_apply {G : SimpleGraph V} {f : V ↪ W} {a b : V} : (G.map f).Adj (f a) (f b) ↔ G.Adj a b := by simp theorem map_monotone (f : V ↪ W) : Monotone (SimpleGraph.map f) := by rintro G G' h _ _ ⟨u, v, ha, rfl, rfl⟩ exact ⟨_, _, h ha, rfl, rfl⟩ @[simp] lemma map_id : G.map (Function.Embedding.refl _) = G := SimpleGraph.ext <| Relation.map_id_id _ @[simp] lemma map_map (f : V ↪ W) (g : W ↪ X) : (G.map f).map g = G.map (f.trans g) := SimpleGraph.ext <| Relation.map_map _ _ _ _ _ /-- Given a function, there is a contravariant induced map on graphs by pulling back the adjacency relation. This is one of the ways of creating induced graphs. See `SimpleGraph.induce` for a wrapper. This is surjective when `f` is injective (see `SimpleGraph.comap_surjective`). -/ protected def comap (f : V → W) (G : SimpleGraph W) : SimpleGraph V where Adj u v := G.Adj (f u) (f v) symm _ _ h := h.symm loopless _ := G.loopless _ @[simp] lemma comap_adj {G : SimpleGraph W} {f : V → W} : (G.comap f).Adj u v ↔ G.Adj (f u) (f v) := Iff.rfl @[simp] lemma comap_id {G : SimpleGraph V} : G.comap id = G := SimpleGraph.ext rfl @[simp] lemma comap_comap {G : SimpleGraph X} (f : V → W) (g : W → X) : (G.comap g).comap f = G.comap (g ∘ f) := rfl instance instDecidableComapAdj (f : V → W) (G : SimpleGraph W) [DecidableRel G.Adj] : DecidableRel (G.comap f).Adj := fun _ _ ↦ ‹DecidableRel G.Adj› _ _ lemma comap_symm (G : SimpleGraph V) (e : V ≃ W) : G.comap e.symm.toEmbedding = G.map e.toEmbedding := by ext; simp only [Equiv.apply_eq_iff_eq_symm_apply, comap_adj, map_adj, Equiv.toEmbedding_apply, exists_eq_right_right, exists_eq_right] lemma map_symm (G : SimpleGraph W) (e : V ≃ W) : G.map e.symm.toEmbedding = G.comap e.toEmbedding := by rw [← comap_symm, e.symm_symm] theorem comap_monotone (f : V ↪ W) : Monotone (SimpleGraph.comap f) := by intro G G' h _ _ ha exact h ha @[simp] theorem comap_map_eq (f : V ↪ W) (G : SimpleGraph V) : (G.map f).comap f = G := by ext simp theorem leftInverse_comap_map (f : V ↪ W) : Function.LeftInverse (SimpleGraph.comap f) (SimpleGraph.map f) := comap_map_eq f theorem map_injective (f : V ↪ W) : Function.Injective (SimpleGraph.map f) := (leftInverse_comap_map f).injective theorem comap_surjective (f : V ↪ W) : Function.Surjective (SimpleGraph.comap f) := (leftInverse_comap_map f).surjective theorem map_le_iff_le_comap (f : V ↪ W) (G : SimpleGraph V) (G' : SimpleGraph W) : G.map f ≤ G' ↔ G ≤ G'.comap f := ⟨fun h u v ha => h ⟨_, _, ha, rfl, rfl⟩, by rintro h _ _ ⟨u, v, ha, rfl, rfl⟩ exact h ha⟩ theorem map_comap_le (f : V ↪ W) (G : SimpleGraph W) : (G.comap f).map f ≤ G := by rw [map_le_iff_le_comap] lemma le_comap_of_subsingleton (f : V → W) [Subsingleton V] : G ≤ G'.comap f := by intros v w; simp [Subsingleton.elim v w] lemma map_le_of_subsingleton (f : V ↪ W) [Subsingleton V] : G.map f ≤ G' := by rw [map_le_iff_le_comap]; apply le_comap_of_subsingleton /-- Given a family of vertex types indexed by `ι`, pulling back from `⊤ : SimpleGraph ι` yields the complete multipartite graph on the family. Two vertices are adjacent if and only if their indices are not equal. -/ abbrev completeMultipartiteGraph {ι : Type*} (V : ι → Type*) : SimpleGraph (Σ i, V i) := SimpleGraph.comap Sigma.fst ⊤ /-- Equivalent types have equivalent simple graphs. -/ @[simps apply] protected def _root_.Equiv.simpleGraph (e : V ≃ W) : SimpleGraph V ≃ SimpleGraph W where toFun := SimpleGraph.comap e.symm invFun := SimpleGraph.comap e left_inv _ := by simp right_inv _ := by simp @[simp] lemma _root_.Equiv.simpleGraph_refl : (Equiv.refl V).simpleGraph = Equiv.refl _ := by ext; rfl @[simp] lemma _root_.Equiv.simpleGraph_trans (e₁ : V ≃ W) (e₂ : W ≃ X) : (e₁.trans e₂).simpleGraph = e₁.simpleGraph.trans e₂.simpleGraph := rfl @[simp] lemma _root_.Equiv.symm_simpleGraph (e : V ≃ W) : e.simpleGraph.symm = e.symm.simpleGraph := rfl /-! ## Induced graphs -/ /- Given a set `s` of vertices, we can restrict a graph to those vertices by restricting its adjacency relation. This gives a map between `SimpleGraph V` and `SimpleGraph s`. There is also a notion of induced subgraphs (see `SimpleGraph.subgraph.induce`). -/ /-- Restrict a graph to the vertices in the set `s`, deleting all edges incident to vertices outside the set. This is a wrapper around `SimpleGraph.comap`. -/ abbrev induce (s : Set V) (G : SimpleGraph V) : SimpleGraph s := G.comap (Function.Embedding.subtype _) @[simp] lemma induce_singleton_eq_top (v : V) : G.induce {v} = ⊤ := by rw [eq_top_iff]; apply le_comap_of_subsingleton /-- Given a graph on a set of vertices, we can make it be a `SimpleGraph V` by adding in the remaining vertices without adding in any additional edges. This is a wrapper around `SimpleGraph.map`. -/ abbrev spanningCoe {s : Set V} (G : SimpleGraph s) : SimpleGraph V := G.map (Function.Embedding.subtype _) theorem induce_spanningCoe {s : Set V} {G : SimpleGraph s} : G.spanningCoe.induce s = G := comap_map_eq _ _ theorem spanningCoe_induce_le (s : Set V) : (G.induce s).spanningCoe ≤ G := map_comap_le _ _ /-! ## Homomorphisms, embeddings and isomorphisms -/ /-- A graph homomorphism is a map on vertex sets that respects adjacency relations. The notation `G →g G'` represents the type of graph homomorphisms. -/ abbrev Hom := RelHom G.Adj G'.Adj /-- A graph embedding is an embedding `f` such that for vertices `v w : V`, `G.Adj (f v) (f w) ↔ G.Adj v w`. Its image is an induced subgraph of G'. The notation `G ↪g G'` represents the type of graph embeddings. -/ abbrev Embedding := RelEmbedding G.Adj G'.Adj /-- A graph isomorphism is a bijective map on vertex sets that respects adjacency relations. The notation `G ≃g G'` represents the type of graph isomorphisms. -/ abbrev Iso := RelIso G.Adj G'.Adj @[inherit_doc] infixl:50 " →g " => Hom @[inherit_doc] infixl:50 " ↪g " => Embedding @[inherit_doc] infixl:50 " ≃g " => Iso namespace Hom variable {G G'} {G₁ G₂ : SimpleGraph V} {H : SimpleGraph W} (f : G →g G') /-- The identity homomorphism from a graph to itself. -/ protected abbrev id : G →g G := RelHom.id _ @[simp, norm_cast] lemma coe_id : ⇑(Hom.id : G →g G) = id := rfl instance [Subsingleton (V → W)] : Subsingleton (G →g H) := DFunLike.coe_injective.subsingleton instance [IsEmpty V] : Unique (G →g H) where default := ⟨isEmptyElim, fun {a} ↦ isEmptyElim a⟩ uniq _ := Subsingleton.elim _ _ instance [Finite V] [Finite W] : Finite (G →g H) := DFunLike.finite _ theorem map_adj {v w : V} (h : G.Adj v w) : G'.Adj (f v) (f w) := f.map_rel' h theorem map_mem_edgeSet {e : Sym2 V} (h : e ∈ G.edgeSet) : e.map f ∈ G'.edgeSet := Sym2.ind (fun _ _ => f.map_rel') e h theorem apply_mem_neighborSet {v w : V} (h : w ∈ G.neighborSet v) : f w ∈ G'.neighborSet (f v) := map_adj f h /-- The map between edge sets induced by a homomorphism. The underlying map on edges is given by `Sym2.map`. -/ @[simps] def mapEdgeSet (e : G.edgeSet) : G'.edgeSet := ⟨Sym2.map f e, f.map_mem_edgeSet e.property⟩ /-- The map between neighbor sets induced by a homomorphism. -/ @[simps] def mapNeighborSet (v : V) (w : G.neighborSet v) : G'.neighborSet (f v) := ⟨f w, f.apply_mem_neighborSet w.property⟩ /-- The map between darts induced by a homomorphism. -/ def mapDart (d : G.Dart) : G'.Dart := ⟨d.1.map f f, f.map_adj d.2⟩ @[simp] theorem mapDart_apply (d : G.Dart) : f.mapDart d = ⟨d.1.map f f, f.map_adj d.2⟩ := rfl /-- The induced map for spanning subgraphs, which is the identity on vertices. -/ @[simps] def mapSpanningSubgraphs {G G' : SimpleGraph V} (h : G ≤ G') : G →g G' where toFun x := x map_rel' ha := h ha theorem mapEdgeSet.injective (hinj : Function.Injective f) : Function.Injective f.mapEdgeSet := by rintro ⟨e₁, h₁⟩ ⟨e₂, h₂⟩ dsimp [Hom.mapEdgeSet] repeat rw [Subtype.mk_eq_mk] apply Sym2.map.injective hinj /-- Every graph homomorphism from a complete graph is injective. -/ theorem injective_of_top_hom (f : (⊤ : SimpleGraph V) →g G') : Function.Injective f := by intro v w h contrapose! h exact G'.ne_of_adj (map_adj _ ((top_adj _ _).mpr h)) /-- There is a homomorphism to a graph from a comapped graph. When the function is injective, this is an embedding (see `SimpleGraph.Embedding.comap`). -/ @[simps] protected def comap (f : V → W) (G : SimpleGraph W) : G.comap f →g G where toFun := f map_rel' := by simp variable {G'' : SimpleGraph X} /-- Composition of graph homomorphisms. -/ abbrev comp (f' : G' →g G'') (f : G →g G') : G →g G'' := RelHom.comp f' f @[simp] theorem coe_comp (f' : G' →g G'') (f : G →g G') : ⇑(f'.comp f) = f' ∘ f := rfl /-- The graph homomorphism from a smaller graph to a bigger one. -/ def ofLE (h : G₁ ≤ G₂) : G₁ →g G₂ := ⟨id, @h⟩ @[simp, norm_cast] lemma coe_ofLE (h : G₁ ≤ G₂) : ⇑(ofLE h) = id := rfl end Hom namespace Embedding variable {G G'} {H : SimpleGraph W} (f : G ↪g G') /-- The identity embedding from a graph to itself. -/ abbrev refl : G ↪g G := RelEmbedding.refl _ /-- An embedding of graphs gives rise to a homomorphism of graphs. -/ abbrev toHom : G →g G' := f.toRelHom @[simp] lemma coe_toHom (f : G ↪g H) : ⇑f.toHom = f := rfl @[simp] theorem map_adj_iff {v w : V} : G'.Adj (f v) (f w) ↔ G.Adj v w := f.map_rel_iff theorem map_mem_edgeSet_iff {e : Sym2 V} : e.map f ∈ G'.edgeSet ↔ e ∈ G.edgeSet := Sym2.ind (fun _ _ => f.map_adj_iff) e theorem apply_mem_neighborSet_iff {v w : V} : f w ∈ G'.neighborSet (f v) ↔ w ∈ G.neighborSet v := map_adj_iff f /-- A graph embedding induces an embedding of edge sets. -/ @[simps] def mapEdgeSet : G.edgeSet ↪ G'.edgeSet where toFun := Hom.mapEdgeSet f inj' := Hom.mapEdgeSet.injective f f.injective /-- A graph embedding induces an embedding of neighbor sets. -/ @[simps] def mapNeighborSet (v : V) : G.neighborSet v ↪ G'.neighborSet (f v) where toFun w := ⟨f w, f.apply_mem_neighborSet_iff.mpr w.2⟩ inj' := by rintro ⟨w₁, h₁⟩ ⟨w₂, h₂⟩ h rw [Subtype.mk_eq_mk] at h ⊢ exact f.inj' h /-- Given an injective function, there is an embedding from the comapped graph into the original graph. -/ -- Porting note: @[simps] does not work here since `f` is not a constructor application. -- `@[simps toEmbedding]` could work, but Floris suggested writing `comap_apply` for now. protected def comap (f : V ↪ W) (G : SimpleGraph W) : G.comap f ↪g G := { f with map_rel_iff' := by simp } @[simp] theorem comap_apply (f : V ↪ W) (G : SimpleGraph W) (v : V) : SimpleGraph.Embedding.comap f G v = f v := rfl /-- Given an injective function, there is an embedding from a graph into the mapped graph. -/ -- Porting note: @[simps] does not work here since `f` is not a constructor application. -- `@[simps toEmbedding]` could work, but Floris suggested writing `map_apply` for now. protected def map (f : V ↪ W) (G : SimpleGraph V) : G ↪g G.map f := { f with map_rel_iff' := by simp } @[simp] theorem map_apply (f : V ↪ W) (G : SimpleGraph V) (v : V) : SimpleGraph.Embedding.map f G v = f v := rfl /-- Induced graphs embed in the original graph. Note that if `G.induce s = ⊤` (i.e., if `s` is a clique) then this gives the embedding of a complete graph. -/ protected abbrev induce (s : Set V) : G.induce s ↪g G := SimpleGraph.Embedding.comap (Function.Embedding.subtype _) G /-- Graphs on a set of vertices embed in their `spanningCoe`. -/ protected abbrev spanningCoe {s : Set V} (G : SimpleGraph s) : G ↪g G.spanningCoe := SimpleGraph.Embedding.map (Function.Embedding.subtype _) G /-- Embeddings of types induce embeddings of complete graphs on those types. -/ protected def completeGraph {α β : Type*} (f : α ↪ β) : (⊤ : SimpleGraph α) ↪g (⊤ : SimpleGraph β) := { f with map_rel_iff' := by simp } @[simp] lemma coe_completeGraph {α β : Type*} (f : α ↪ β) : ⇑(Embedding.completeGraph f) = f := rfl variable {G'' : SimpleGraph X} /-- Composition of graph embeddings. -/ abbrev comp (f' : G' ↪g G'') (f : G ↪g G') : G ↪g G'' := f.trans f' @[simp] theorem coe_comp (f' : G' ↪g G'') (f : G ↪g G') : ⇑(f'.comp f) = f' ∘ f := rfl end Embedding section induceHom variable {G G'} {G'' : SimpleGraph X} {s : Set V} {t : Set W} {r : Set X} (φ : G →g G') (φst : Set.MapsTo φ s t) (ψ : G' →g G'') (ψtr : Set.MapsTo ψ t r) /-- The restriction of a morphism of graphs to induced subgraphs. -/ def induceHom : G.induce s →g G'.induce t where toFun := Set.MapsTo.restrict φ s t φst map_rel' := φ.map_rel' @[simp, norm_cast] lemma coe_induceHom : ⇑(induceHom φ φst) = Set.MapsTo.restrict φ s t φst := rfl @[simp] lemma induceHom_id (G : SimpleGraph V) (s) : induceHom (Hom.id : G →g G) (Set.mapsTo_id s) = Hom.id := by ext x rfl @[simp] lemma induceHom_comp : (induceHom ψ ψtr).comp (induceHom φ φst) = induceHom (ψ.comp φ) (ψtr.comp φst) := by ext x rfl lemma induceHom_injective (hi : Set.InjOn φ s) : Function.Injective (induceHom φ φst) := by erw [Set.MapsTo.restrict_inj] <;> assumption end induceHom section induceHomLE variable {s s' : Set V} (h : s ≤ s') /-- Given an inclusion of vertex subsets, the induced embedding on induced graphs. This is not an abbreviation for `induceHom` since we get an embedding in this case. -/ def induceHomOfLE (h : s ≤ s') : G.induce s ↪g G.induce s' where toEmbedding := Set.embeddingOfSubset s s' h map_rel_iff' := by simp @[simp] lemma induceHomOfLE_apply (v : s) : (G.induceHomOfLE h) v = Set.inclusion h v := rfl @[simp] lemma induceHomOfLE_toHom : (G.induceHomOfLE h).toHom = induceHom (.id : G →g G) ((Set.mapsTo_id s).mono_right h) := by ext; simp end induceHomLE namespace Iso variable {G G'} (f : G ≃g G') /-- The identity isomorphism of a graph with itself. -/ abbrev refl : G ≃g G := RelIso.refl _ /-- An isomorphism of graphs gives rise to an embedding of graphs. -/ abbrev toEmbedding : G ↪g G' := f.toRelEmbedding /-- An isomorphism of graphs gives rise to a homomorphism of graphs. -/ abbrev toHom : G →g G' := f.toEmbedding.toHom /-- The inverse of a graph isomorphism. -/ abbrev symm : G' ≃g G := RelIso.symm f theorem map_adj_iff {v w : V} : G'.Adj (f v) (f w) ↔ G.Adj v w := f.map_rel_iff theorem map_mem_edgeSet_iff {e : Sym2 V} : e.map f ∈ G'.edgeSet ↔ e ∈ G.edgeSet := Sym2.ind (fun _ _ => f.map_adj_iff) e theorem apply_mem_neighborSet_iff {v w : V} : f w ∈ G'.neighborSet (f v) ↔ w ∈ G.neighborSet v := map_adj_iff f /-- An isomorphism of graphs induces an equivalence of edge sets. -/ @[simps] def mapEdgeSet : G.edgeSet ≃ G'.edgeSet where toFun := Hom.mapEdgeSet f invFun := Hom.mapEdgeSet f.symm left_inv := by rintro ⟨e, h⟩ simp only [Hom.mapEdgeSet, RelEmbedding.toRelHom, Embedding.toFun_eq_coe, RelEmbedding.coe_toEmbedding, RelIso.coe_toRelEmbedding, Sym2.map_map, comp_apply, Subtype.mk.injEq] convert congr_fun Sym2.map_id e exact RelIso.symm_apply_apply _ _ right_inv := by rintro ⟨e, h⟩ simp only [Hom.mapEdgeSet, RelEmbedding.toRelHom, Embedding.toFun_eq_coe, RelEmbedding.coe_toEmbedding, RelIso.coe_toRelEmbedding, Sym2.map_map, comp_apply, Subtype.mk.injEq] convert congr_fun Sym2.map_id e exact RelIso.apply_symm_apply _ _ /-- A graph isomorphism induces an equivalence of neighbor sets. -/ @[simps] def mapNeighborSet (v : V) : G.neighborSet v ≃ G'.neighborSet (f v) where toFun w := ⟨f w, f.apply_mem_neighborSet_iff.mpr w.2⟩ invFun w := ⟨f.symm w, by simpa [RelIso.symm_apply_apply] using f.symm.apply_mem_neighborSet_iff.mpr w.2⟩ left_inv w := by simp right_inv w := by simp theorem card_eq [Fintype V] [Fintype W] : Fintype.card V = Fintype.card W := by rw [← Fintype.ofEquiv_card f.toEquiv] convert rfl /-- Given a bijection, there is an embedding from the comapped graph into the original graph. -/ -- Porting note: `@[simps]` does not work here anymore since `f` is not a constructor application. -- `@[simps toEmbedding]` could work, but Floris suggested writing `comap_apply` for now. protected def comap (f : V ≃ W) (G : SimpleGraph W) : G.comap f.toEmbedding ≃g G := { f with map_rel_iff' := by simp } @[simp] lemma comap_apply (f : V ≃ W) (G : SimpleGraph W) (v : V) : SimpleGraph.Iso.comap f G v = f v := rfl @[simp] lemma comap_symm_apply (f : V ≃ W) (G : SimpleGraph W) (w : W) : (SimpleGraph.Iso.comap f G).symm w = f.symm w := rfl /-- Given an injective function, there is an embedding from a graph into the mapped graph. -/ -- Porting note: `@[simps]` does not work here anymore since `f` is not a constructor application. -- `@[simps toEmbedding]` could work, but Floris suggested writing `map_apply` for now. protected def map (f : V ≃ W) (G : SimpleGraph V) : G ≃g G.map f.toEmbedding := { f with map_rel_iff' := by simp } @[simp] lemma map_apply (f : V ≃ W) (G : SimpleGraph V) (v : V) : SimpleGraph.Iso.map f G v = f v := rfl @[simp] lemma map_symm_apply (f : V ≃ W) (G : SimpleGraph V) (w : W) : (SimpleGraph.Iso.map f G).symm w = f.symm w := rfl /-- Equivalences of types induce isomorphisms of complete graphs on those types. -/ protected def completeGraph {α β : Type*} (f : α ≃ β) : (⊤ : SimpleGraph α) ≃g (⊤ : SimpleGraph β) := { f with map_rel_iff' := by simp } theorem toEmbedding_completeGraph {α β : Type*} (f : α ≃ β) : (Iso.completeGraph f).toEmbedding = Embedding.completeGraph f.toEmbedding := rfl variable {G'' : SimpleGraph X} /-- Composition of graph isomorphisms. -/ abbrev comp (f' : G' ≃g G'') (f : G ≃g G') : G ≃g G'' := f.trans f' @[simp] theorem coe_comp (f' : G' ≃g G'') (f : G ≃g G') : ⇑(f'.comp f) = f' ∘ f := rfl end Iso /-- The graph induced on `Set.univ` is isomorphic to the original graph. -/ @[simps!] def induceUnivIso (G : SimpleGraph V) : G.induce Set.univ ≃g G where toEquiv := Equiv.Set.univ V map_rel_iff' := by simp only [Equiv.Set.univ, Equiv.coe_fn_mk, comap_adj, Embedding.coe_subtype, Subtype.forall, Set.mem_univ, forall_true_left, implies_true] section Finite variable [Fintype V] {n : ℕ} /-- Given a graph over a finite vertex type `V` and a proof `hc` that `Fintype.card V = n`, `G.overFin n` is an isomorphic (as shown in `overFinIso`) graph over `Fin n`. -/ def overFin (hc : Fintype.card V = n) : SimpleGraph (Fin n) where Adj x y := G.Adj ((Fintype.equivFinOfCardEq hc).symm x) ((Fintype.equivFinOfCardEq hc).symm y) symm x y := by simp_rw [adj_comm, imp_self] /-- The isomorphism between `G` and `G.overFin hc`. -/ noncomputable def overFinIso (hc : Fintype.card V = n) : G ≃g G.overFin hc := by use Fintype.equivFinOfCardEq hc; simp [overFin] end Finite end SimpleGraph
Combinatorics\SimpleGraph\Matching.lean
/- Copyright (c) 2020 Alena Gusakov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alena Gusakov, Arthur Paulino, Kyle Miller, Pim Otte -/ import Mathlib.Combinatorics.SimpleGraph.DegreeSum import Mathlib.Combinatorics.SimpleGraph.Connectivity.WalkCounting /-! # Matchings A *matching* for a simple graph is a set of disjoint pairs of adjacent vertices, and the set of all the vertices in a matching is called its *support* (and sometimes the vertices in the support are said to be *saturated* by the matching). A *perfect matching* is a matching whose support contains every vertex of the graph. In this module, we represent a matching as a subgraph whose vertices are each incident to at most one edge, and the edges of the subgraph represent the paired vertices. ## Main definitions * `SimpleGraph.Subgraph.IsMatching`: `M.IsMatching` means that `M` is a matching of its underlying graph. * `SimpleGraph.Subgraph.IsPerfectMatching` defines when a subgraph `M` of a simple graph is a perfect matching, denoted `M.IsPerfectMatching`. ## TODO * Define an `other` function and prove useful results about it (https://leanprover.zulipchat.com/#narrow/stream/252551-graph-theory/topic/matchings/near/266205863) * Provide a bicoloring for matchings (https://leanprover.zulipchat.com/#narrow/stream/252551-graph-theory/topic/matchings/near/265495120) * Tutte's Theorem * Hall's Marriage Theorem (see `Mathlib.Combinatorics.Hall.Basic`) -/ open Function namespace SimpleGraph variable {V : Type*} {G G': SimpleGraph V} {M M' : Subgraph G} {v w : V} namespace Subgraph /-- The subgraph `M` of `G` is a matching if every vertex of `M` is incident to exactly one edge in `M`. We say that the vertices in `M.support` are *matched* or *saturated*. -/ def IsMatching (M : Subgraph G) : Prop := ∀ ⦃v⦄, v ∈ M.verts → ∃! w, M.Adj v w /-- Given a vertex, returns the unique edge of the matching it is incident to. -/ noncomputable def IsMatching.toEdge (h : M.IsMatching) (v : M.verts) : M.edgeSet := ⟨s(v, (h v.property).choose), (h v.property).choose_spec.1⟩ theorem IsMatching.toEdge_eq_of_adj (h : M.IsMatching) (hv : v ∈ M.verts) (hvw : M.Adj v w) : h.toEdge ⟨v, hv⟩ = ⟨s(v, w), hvw⟩ := by simp only [IsMatching.toEdge, Subtype.mk_eq_mk] congr exact ((h (M.edge_vert hvw)).choose_spec.2 w hvw).symm theorem IsMatching.toEdge.surjective (h : M.IsMatching) : Surjective h.toEdge := by rintro ⟨e, he⟩ induction' e with x y exact ⟨⟨x, M.edge_vert he⟩, h.toEdge_eq_of_adj _ he⟩ theorem IsMatching.toEdge_eq_toEdge_of_adj (h : M.IsMatching) (hv : v ∈ M.verts) (hw : w ∈ M.verts) (ha : M.Adj v w) : h.toEdge ⟨v, hv⟩ = h.toEdge ⟨w, hw⟩ := by rw [h.toEdge_eq_of_adj hv ha, h.toEdge_eq_of_adj hw (M.symm ha), Subtype.mk_eq_mk, Sym2.eq_swap] lemma IsMatching.map_ofLE (h : M.IsMatching) (hGG' : G ≤ G') : (M.map (Hom.ofLE hGG')).IsMatching := by intro _ hv obtain ⟨_, hv, hv'⟩ := Set.mem_image _ _ _ |>.mp hv obtain ⟨w, hw⟩ := h hv use w simpa using hv' ▸ hw lemma IsMatching.sup (hM : M.IsMatching) (hM' : M'.IsMatching) (hd : Disjoint M.support M'.support) : (M ⊔ M').IsMatching := by intro v hv have aux {N N' : Subgraph G} (hN : N.IsMatching) (hd : Disjoint N.support N'.support) (hmN: v ∈ N.verts) : ∃! w, (N ⊔ N').Adj v w := by obtain ⟨w, hw⟩ := hN hmN use w refine ⟨sup_adj.mpr (.inl hw.1), ?_⟩ intro y hy cases hy with | inl h => exact hw.2 y h | inr h => rw [Set.disjoint_left] at hd simpa [(mem_support _).mpr ⟨w, hw.1⟩, (mem_support _).mpr ⟨y, h⟩] using @hd v cases Set.mem_or_mem_of_mem_union hv with | inl hmM => exact aux hM hd hmM | inr hmM' => rw [sup_comm] exact aux hM' (Disjoint.symm hd) hmM' lemma IsMatching.iSup {ι : Sort _} {f : ι → Subgraph G} (hM : (i : ι) → (f i).IsMatching) (hd : Pairwise fun i j ↦ Disjoint (f i).support (f j).support) : (⨆ i, f i).IsMatching := by intro v hv obtain ⟨i , hi⟩ := Set.mem_iUnion.mp (verts_iSup ▸ hv) obtain ⟨w , hw⟩ := hM i hi use w refine ⟨iSup_adj.mpr ⟨i, hw.1⟩, ?_⟩ intro y hy obtain ⟨i' , hi'⟩ := iSup_adj.mp hy by_cases heq : i = i' · exact hw.2 y (heq.symm ▸ hi') · have := hd heq simp only [Set.disjoint_left] at this simpa [(mem_support _).mpr ⟨w, hw.1⟩, (mem_support _).mpr ⟨y, hi'⟩] using @this v lemma IsMatching.subgraphOfAdj (h : G.Adj v w) : (G.subgraphOfAdj h).IsMatching := by intro _ hv rw [subgraphOfAdj_verts, Set.mem_insert_iff, Set.mem_singleton_iff] at hv cases hv with | inl => use w; aesop | inr => use v; aesop lemma IsMatching.coeSubgraph {G' : Subgraph G} {M : Subgraph G'.coe} (hM : M.IsMatching) : M.coeSubgraph.IsMatching := by intro _ hv obtain ⟨w, hw⟩ := hM <| Set.mem_of_mem_image_val <| M.verts_coeSubgraph.symm ▸ hv use w refine ⟨?_, fun y hy => ?_⟩ · obtain ⟨v, hv⟩ := (Set.mem_image _ _ _).mp <| M.verts_coeSubgraph.symm ▸ hv simp only [coeSubgraph_adj, Subtype.coe_eta, Subtype.coe_prop, exists_const] exact ⟨hv.2 ▸ v.2, hw.1⟩ · obtain ⟨_, hw', hvw⟩ := (coeSubgraph_adj _ _ _).mp hy rw [← hw.2 ⟨y, hw'⟩ hvw] /-- The subgraph `M` of `G` is a perfect matching on `G` if it's a matching and every vertex `G` is matched. -/ def IsPerfectMatching (M : G.Subgraph) : Prop := M.IsMatching ∧ M.IsSpanning theorem IsMatching.support_eq_verts (h : M.IsMatching) : M.support = M.verts := by refine M.support_subset_verts.antisymm fun v hv => ?_ obtain ⟨w, hvw, -⟩ := h hv exact ⟨_, hvw⟩ theorem isMatching_iff_forall_degree [∀ v, Fintype (M.neighborSet v)] : M.IsMatching ↔ ∀ v : V, v ∈ M.verts → M.degree v = 1 := by simp only [degree_eq_one_iff_unique_adj, IsMatching] theorem IsMatching.even_card [Fintype M.verts] (h : M.IsMatching) : Even M.verts.toFinset.card := by classical rw [isMatching_iff_forall_degree] at h use M.coe.edgeFinset.card rw [← two_mul, ← M.coe.sum_degrees_eq_twice_card_edges] -- Porting note: `SimpleGraph.Subgraph.coe_degree` does not trigger because it uses -- instance arguments instead of implicit arguments for the first `Fintype` argument. -- Using a `convert_to` to swap out the `Fintype` instance to the "right" one. convert_to _ = Finset.sum Finset.univ fun v => SimpleGraph.degree (Subgraph.coe M) v using 3 simp [h, Finset.card_univ] theorem isPerfectMatching_iff : M.IsPerfectMatching ↔ ∀ v, ∃! w, M.Adj v w := by refine ⟨?_, fun hm => ⟨fun v _ => hm v, fun v => ?_⟩⟩ · rintro ⟨hm, hs⟩ v exact hm (hs v) · obtain ⟨w, hw, -⟩ := hm v exact M.edge_vert hw theorem isPerfectMatching_iff_forall_degree [∀ v, Fintype (M.neighborSet v)] : M.IsPerfectMatching ↔ ∀ v, M.degree v = 1 := by simp [degree_eq_one_iff_unique_adj, isPerfectMatching_iff] theorem IsPerfectMatching.even_card [Fintype V] (h : M.IsPerfectMatching) : Even (Fintype.card V) := by classical simpa only [h.2.card_verts] using IsMatching.even_card h.1 lemma IsMatching.induce_connectedComponent (h : M.IsMatching) (c : ConnectedComponent G) : (M.induce (M.verts ∩ c.supp)).IsMatching := by intro _ hv obtain ⟨hv, rfl⟩ := hv obtain ⟨w, hvw, hw⟩ := h hv use w simpa [hv, hvw, M.edge_vert hvw.symm, (M.adj_sub hvw).symm.reachable] using fun _ _ _ ↦ hw _ lemma IsPerfectMatching.induce_connectedComponent_isMatching (h : M.IsPerfectMatching) (c : ConnectedComponent G) : (M.induce c.supp).IsMatching := by simpa [h.2.verts_eq_univ] using h.1.induce_connectedComponent c end Subgraph namespace ConnectedComponent section Finite variable [Fintype V] lemma even_card_of_isPerfectMatching [DecidableEq V] [DecidableRel G.Adj] (c : ConnectedComponent G) (hM : M.IsPerfectMatching) : Even (Fintype.card c.supp) := by classical simpa using (hM.induce_connectedComponent_isMatching c).even_card lemma odd_matches_node_outside {u : Set V} {c : ConnectedComponent (Subgraph.deleteVerts ⊤ u).coe} (hM : M.IsPerfectMatching) (codd : Odd (Nat.card c.supp)) : ∃ᵉ (w ∈ u) (v : ((⊤ : G.Subgraph).deleteVerts u).verts), M.Adj v w ∧ v ∈ c.supp := by by_contra! h have hMmatch : (M.induce c.supp).IsMatching := by intro v hv obtain ⟨w, hw⟩ := hM.1 (hM.2 v) obtain ⟨⟨v', hv'⟩, ⟨hv , rfl⟩⟩ := hv use w have hwnu : w ∉ u := fun hw' ↦ h w hw' ⟨v', hv'⟩ (hw.1) hv refine ⟨⟨⟨⟨v', hv'⟩, hv, rfl⟩, ?_, hw.1⟩, fun _ hy ↦ hw.2 _ hy.2.2⟩ apply ConnectedComponent.mem_coe_supp_of_adj ⟨⟨v', hv'⟩, ⟨hv, rfl⟩⟩ ⟨by trivial, hwnu⟩ simp only [Subgraph.induce_verts, Subgraph.verts_top, Set.mem_diff, Set.mem_univ, true_and, Subgraph.induce_adj, hwnu, not_false_eq_true, and_self, Subgraph.top_adj, M.adj_sub hw.1, and_true] at hv' ⊢ trivial apply Nat.odd_iff_not_even.mp codd haveI : Fintype ↑(Subgraph.induce M (Subtype.val '' supp c)).verts := Fintype.ofFinite _ classical have hMeven := Subgraph.IsMatching.even_card hMmatch haveI : Fintype (c.supp) := Fintype.ofFinite _ simp only [Subgraph.induce_verts, Subgraph.verts_top, Set.toFinset_image, Nat.card_eq_fintype_card, Set.toFinset_image, Finset.card_image_of_injective _ (Subtype.val_injective), Set.toFinset_card] at hMeven ⊢ exact hMeven end Finite end ConnectedComponent end SimpleGraph
Combinatorics\SimpleGraph\Metric.lean
/- Copyright (c) 2022 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller, Vincent Beffara, Rida Hamadani -/ import Mathlib.Combinatorics.SimpleGraph.Path import Mathlib.Data.ENat.Lattice /-! # Graph metric This module defines the `SimpleGraph.edist` function, which takes pairs of vertices to the length of the shortest walk between them, or `⊤` if they are disconnected. It also defines `SimpleGraph.dist` which is the `ℕ`-valued version of `SimpleGraph.edist`. ## Main definitions - `SimpleGraph.edist` is the graph extended metric. - `SimpleGraph.dist` is the graph metric. ## TODO - Provide an additional computable version of `SimpleGraph.dist` for when `G` is connected. - When directed graphs exist, a directed notion of distance, likely `ENat`-valued. ## Tags graph metric, distance -/ namespace SimpleGraph variable {V : Type*} (G : SimpleGraph V) /-! ## Metric -/ section edist /-- The extended distance between two vertices is the length of the shortest walk between them. It is `⊤` if no such walk exists. -/ noncomputable def edist (u v : V) : ℕ∞ := ⨅ w : G.Walk u v, w.length variable {G} {u v w : V} theorem edist_eq_sInf : G.edist u v = sInf (Set.range fun w : G.Walk u v ↦ (w.length : ℕ∞)) := rfl protected theorem Reachable.exists_walk_length_eq_edist (hr : G.Reachable u v) : ∃ p : G.Walk u v, p.length = G.edist u v := csInf_mem <| Set.range_nonempty_iff_nonempty.mpr hr protected theorem Connected.exists_walk_length_eq_edist (hconn : G.Connected) (u v : V) : ∃ p : G.Walk u v, p.length = G.edist u v := (hconn u v).exists_walk_length_eq_edist theorem edist_le (p : G.Walk u v) : G.edist u v ≤ p.length := sInf_le ⟨p, rfl⟩ protected alias Walk.edist_le := edist_le @[simp] theorem edist_eq_zero_iff : G.edist u v = 0 ↔ u = v := by apply Iff.intro <;> simp [edist, ENat.iInf_eq_zero] @[simp] theorem edist_self : edist G v v = 0 := edist_eq_zero_iff.mpr rfl theorem edist_pos_of_ne (hne : u ≠ v) : 0 < G.edist u v := pos_iff_ne_zero.mpr <| edist_eq_zero_iff.ne.mpr hne lemma edist_eq_top_of_not_reachable (h : ¬G.Reachable u v) : G.edist u v = ⊤ := by simp [edist, not_reachable_iff_isEmpty_walk.mp h] theorem reachable_of_edist_ne_top (h : G.edist u v ≠ ⊤) : G.Reachable u v := not_not.mp <| edist_eq_top_of_not_reachable.mt h lemma exists_walk_of_edist_ne_top (h : G.edist u v ≠ ⊤) : ∃ p : G.Walk u v, p.length = G.edist u v := (reachable_of_edist_ne_top h).exists_walk_length_eq_edist protected theorem edist_triangle : G.edist u w ≤ G.edist u v + G.edist v w := by cases eq_or_ne (G.edist u v) ⊤ with | inl huv => simp [huv] | inr huv => cases eq_or_ne (G.edist v w) ⊤ with | inl hvw => simp [hvw] | inr hvw => obtain ⟨p, hp⟩ := exists_walk_of_edist_ne_top huv obtain ⟨q, hq⟩ := exists_walk_of_edist_ne_top hvw rw [← hp, ← hq, ← Nat.cast_add, ← Walk.length_append] exact edist_le _ theorem edist_comm : G.edist u v = G.edist v u := by rw [edist_eq_sInf, ← Set.image_univ, ← Set.image_univ_of_surjective Walk.reverse_surjective, ← Set.image_comp, Set.image_univ, Function.comp_def] simp_rw [Walk.length_reverse, ← edist_eq_sInf] lemma exists_walk_of_edist_eq_coe {k : ℕ} (h : G.edist u v = k) : ∃ p : G.Walk u v, p.length = k := have : G.edist u v ≠ ⊤ := by rw [h]; exact ENat.coe_ne_top _ have ⟨p, hp⟩ := exists_walk_of_edist_ne_top this ⟨p, Nat.cast_injective (hp.trans h)⟩ lemma edist_ne_top_iff_reachable : G.edist u v ≠ ⊤ ↔ G.Reachable u v := by refine ⟨reachable_of_edist_ne_top, fun h ↦ ?_⟩ by_contra hx simp only [edist, iInf_eq_top, ENat.coe_ne_top] at hx exact h.elim hx /-- The extended distance between vertices is equal to `1` if and only if these vertices are adjacent. -/ @[simp] theorem edist_eq_one_iff_adj : G.edist u v = 1 ↔ G.Adj u v := by refine ⟨fun h ↦ ?_, fun h ↦ ?_⟩ · obtain ⟨w, hw⟩ := exists_walk_of_edist_ne_top <| by rw [h]; simp exact w.adj_of_length_eq_one <| Nat.cast_eq_one.mp <| h ▸ hw · exact le_antisymm (edist_le h.toWalk) (ENat.one_le_iff_pos.mpr <| edist_pos_of_ne h.ne) lemma edist_bot_of_ne (h : u ≠ v) : (⊥ : SimpleGraph V).edist u v = ⊤ := by rwa [ne_eq, ← reachable_bot.not, ← edist_ne_top_iff_reachable.not, not_not] at h lemma edist_bot [DecidableEq V] : (⊥ : SimpleGraph V).edist u v = (if u = v then 0 else ⊤) := by by_cases h : u = v <;> simp [h, edist_bot_of_ne] lemma edist_top_of_ne (h : u ≠ v) : (⊤ : SimpleGraph V).edist u v = 1 := by simp [h] lemma edist_top [DecidableEq V] : (⊤ : SimpleGraph V).edist u v = (if u = v then 0 else 1) := by by_cases h : u = v <;> simp [h] /-- Supergraphs have smaller or equal extended distances to their subgraphs. -/ theorem edist_le_subgraph_edist {G' : SimpleGraph V} (h : G ≤ G') : G'.edist u v ≤ G.edist u v := by by_cases hr : G.Reachable u v · obtain ⟨_, hw⟩ := hr.exists_walk_length_eq_edist rw [← hw, ← Walk.length_map (Hom.mapSpanningSubgraphs h)] apply edist_le · exact edist_eq_top_of_not_reachable hr ▸ le_top end edist section dist /-- The distance between two vertices is the length of the shortest walk between them. If no such walk exists, this uses the junk value of `0`. -/ noncomputable def dist (u v : V) : ℕ := (G.edist u v).toNat variable {G} {u v w : V} theorem dist_eq_sInf : G.dist u v = sInf (Set.range (Walk.length : G.Walk u v → ℕ)) := ENat.iInf_toNat protected theorem Reachable.exists_walk_length_eq_dist (hr : G.Reachable u v) : ∃ p : G.Walk u v, p.length = G.dist u v := dist_eq_sInf ▸ Nat.sInf_mem (Set.range_nonempty_iff_nonempty.mpr hr) protected theorem Connected.exists_walk_length_eq_dist (hconn : G.Connected) (u v : V) : ∃ p : G.Walk u v, p.length = G.dist u v := dist_eq_sInf ▸ (hconn u v).exists_walk_length_eq_dist theorem dist_le (p : G.Walk u v) : G.dist u v ≤ p.length := dist_eq_sInf ▸ Nat.sInf_le ⟨p, rfl⟩ @[simp] theorem dist_eq_zero_iff_eq_or_not_reachable : G.dist u v = 0 ↔ u = v ∨ ¬G.Reachable u v := by simp [dist_eq_sInf, Nat.sInf_eq_zero, Reachable] theorem dist_self : dist G v v = 0 := by simp protected theorem Reachable.dist_eq_zero_iff (hr : G.Reachable u v) : G.dist u v = 0 ↔ u = v := by simp [hr] protected theorem Reachable.pos_dist_of_ne (h : G.Reachable u v) (hne : u ≠ v) : 0 < G.dist u v := Nat.pos_of_ne_zero (by simp [h, hne]) protected theorem Connected.dist_eq_zero_iff (hconn : G.Connected) : G.dist u v = 0 ↔ u = v := by simp [hconn u v] protected theorem Connected.pos_dist_of_ne (hconn : G.Connected) (hne : u ≠ v) : 0 < G.dist u v := Nat.pos_of_ne_zero fun h ↦ False.elim <| hne <| (hconn.dist_eq_zero_iff).mp h theorem dist_eq_zero_of_not_reachable (h : ¬G.Reachable u v) : G.dist u v = 0 := by simp [h] theorem nonempty_of_pos_dist (h : 0 < G.dist u v) : (Set.univ : Set (G.Walk u v)).Nonempty := by rw [dist_eq_sInf] at h simpa [Set.range_nonempty_iff_nonempty, Set.nonempty_iff_univ_nonempty] using Nat.nonempty_of_pos_sInf h protected theorem Connected.dist_triangle (hconn : G.Connected) : G.dist u w ≤ G.dist u v + G.dist v w := by obtain ⟨p, hp⟩ := hconn.exists_walk_length_eq_dist u v obtain ⟨q, hq⟩ := hconn.exists_walk_length_eq_dist v w rw [← hp, ← hq, ← Walk.length_append] apply dist_le theorem dist_comm : G.dist u v = G.dist v u := by rw [dist, dist, edist_comm] lemma dist_ne_zero_iff_ne_and_reachable : G.dist u v ≠ 0 ↔ u ≠ v ∧ G.Reachable u v := by rw [ne_eq, dist_eq_zero_iff_eq_or_not_reachable.not] push_neg; rfl lemma Reachable.of_dist_ne_zero (h : G.dist u v ≠ 0) : G.Reachable u v := (dist_ne_zero_iff_ne_and_reachable.mp h).2 lemma exists_walk_of_dist_ne_zero (h : G.dist u v ≠ 0) : ∃ p : G.Walk u v, p.length = G.dist u v := (Reachable.of_dist_ne_zero h).exists_walk_length_eq_dist /-- The distance between vertices is equal to `1` if and only if these vertices are adjacent. -/ @[simp] theorem dist_eq_one_iff_adj : G.dist u v = 1 ↔ G.Adj u v := by rw [dist, ENat.toNat_eq_iff, ENat.coe_one, edist_eq_one_iff_adj] decide theorem Walk.isPath_of_length_eq_dist (p : G.Walk u v) (hp : p.length = G.dist u v) : p.IsPath := by classical have : p.bypass = p := by apply Walk.bypass_eq_self_of_length_le calc p.length _ = G.dist u v := hp _ ≤ p.bypass.length := dist_le p.bypass rw [← this] apply Walk.bypass_isPath lemma Reachable.exists_path_of_dist (hr : G.Reachable u v) : ∃ (p : G.Walk u v), p.IsPath ∧ p.length = G.dist u v := by obtain ⟨p, h⟩ := hr.exists_walk_length_eq_dist exact ⟨p, p.isPath_of_length_eq_dist h, h⟩ lemma Connected.exists_path_of_dist (hconn : G.Connected) (u v : V) : ∃ (p : G.Walk u v), p.IsPath ∧ p.length = G.dist u v := by obtain ⟨p, h⟩ := hconn.exists_walk_length_eq_dist u v exact ⟨p, p.isPath_of_length_eq_dist h, h⟩ @[simp] lemma dist_bot : (⊥ : SimpleGraph V).dist u v = 0 := by by_cases h : u = v <;> simp [h] lemma dist_top_of_ne (h : u ≠ v) : (⊤ : SimpleGraph V).dist u v = 1 := by simp [h] lemma dist_top [DecidableEq V] : (⊤ : SimpleGraph V).dist u v = (if u = v then 0 else 1) := by by_cases h : u = v <;> simp [h] /-- Supergraphs have smaller or equal distances to their subgraphs. -/ theorem dist_le_subgraph_dist {G' : SimpleGraph V} (h : G ≤ G') (hr : G.Reachable u v) : G'.dist u v ≤ G.dist u v := by obtain ⟨_, hw⟩ := hr.exists_walk_length_eq_dist rw [← hw, ← Walk.length_map (Hom.mapSpanningSubgraphs h)] apply dist_le end dist end SimpleGraph
Combinatorics\SimpleGraph\Operations.lean
/- Copyright (c) 2023 Jeremy Tan. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Tan -/ import Mathlib.Combinatorics.SimpleGraph.Finite import Mathlib.Combinatorics.SimpleGraph.Maps /-! # Local graph operations This file defines some single-graph operations that modify a finite number of vertices and proves basic theorems about them. When the graph itself has a finite number of vertices we also prove theorems about the number of edges in the modified graphs. ## Main definitions * `G.replaceVertex s t` is `G` with `t` replaced by a copy of `s`, removing the `s-t` edge if present. * `edge s t` is the graph with a single `s-t` edge. Adding this edge to a graph `G` is then `G ⊔ edge s t`. -/ open Finset namespace SimpleGraph variable {V : Type*} (G : SimpleGraph V) (s t : V) namespace Iso variable {G} {W : Type*} {G' : SimpleGraph W} (f : G ≃g G') theorem card_edgeFinset_eq [Fintype G.edgeSet] [Fintype G'.edgeSet] : G.edgeFinset.card = G'.edgeFinset.card := by apply Finset.card_eq_of_equiv simp only [Set.mem_toFinset] exact f.mapEdgeSet end Iso section ReplaceVertex variable [DecidableEq V] /-- The graph formed by forgetting `t`'s neighbours and instead giving it those of `s`. The `s-t` edge is removed if present. -/ def replaceVertex : SimpleGraph V where Adj v w := if v = t then if w = t then False else G.Adj s w else if w = t then G.Adj v s else G.Adj v w symm v w := by dsimp only; split_ifs <;> simp [adj_comm] /-- There is never an `s-t` edge in `G.replaceVertex s t`. -/ lemma not_adj_replaceVertex_same : ¬(G.replaceVertex s t).Adj s t := by simp [replaceVertex] @[simp] lemma replaceVertex_self : G.replaceVertex s s = G := by ext; unfold replaceVertex; aesop (add simp or_iff_not_imp_left) variable {t} /-- Except possibly for `t`, the neighbours of `s` in `G.replaceVertex s t` are its neighbours in `G`. -/ lemma adj_replaceVertex_iff_of_ne_left {w : V} (hw : w ≠ t) : (G.replaceVertex s t).Adj s w ↔ G.Adj s w := by simp [replaceVertex, hw] /-- Except possibly for itself, the neighbours of `t` in `G.replaceVertex s t` are the neighbours of `s` in `G`. -/ lemma adj_replaceVertex_iff_of_ne_right {w : V} (hw : w ≠ t) : (G.replaceVertex s t).Adj t w ↔ G.Adj s w := by simp [replaceVertex, hw] /-- Adjacency in `G.replaceVertex s t` which does not involve `t` is the same as that of `G`. -/ lemma adj_replaceVertex_iff_of_ne {v w : V} (hv : v ≠ t) (hw : w ≠ t) : (G.replaceVertex s t).Adj v w ↔ G.Adj v w := by simp [replaceVertex, hv, hw] variable {s} theorem edgeSet_replaceVertex_of_not_adj (hn : ¬G.Adj s t) : (G.replaceVertex s t).edgeSet = G.edgeSet \ G.incidenceSet t ∪ (s(·, t)) '' (G.neighborSet s) := by ext e; refine e.inductionOn ?_ simp only [replaceVertex, mem_edgeSet, Set.mem_union, Set.mem_diff, mk'_mem_incidenceSet_iff] intros; split_ifs; exacts [by simp_all, by aesop, by rw [adj_comm]; aesop, by aesop] theorem edgeSet_replaceVertex_of_adj (ha : G.Adj s t) : (G.replaceVertex s t).edgeSet = (G.edgeSet \ G.incidenceSet t ∪ (s(·, t)) '' (G.neighborSet s)) \ {s(t, t)} := by ext e; refine e.inductionOn ?_ simp only [replaceVertex, mem_edgeSet, Set.mem_union, Set.mem_diff, mk'_mem_incidenceSet_iff] intros; split_ifs; exacts [by simp_all, by aesop, by rw [adj_comm]; aesop, by aesop] variable [Fintype V] [DecidableRel G.Adj] instance : DecidableRel (G.replaceVertex s t).Adj := by unfold replaceVertex; infer_instance theorem edgeFinset_replaceVertex_of_not_adj (hn : ¬G.Adj s t) : (G.replaceVertex s t).edgeFinset = G.edgeFinset \ G.incidenceFinset t ∪ (G.neighborFinset s).image (s(·, t)) := by simp only [incidenceFinset, neighborFinset, ← Set.toFinset_diff, ← Set.toFinset_image, ← Set.toFinset_union] exact Set.toFinset_congr (G.edgeSet_replaceVertex_of_not_adj hn) theorem edgeFinset_replaceVertex_of_adj (ha : G.Adj s t) : (G.replaceVertex s t).edgeFinset = (G.edgeFinset \ G.incidenceFinset t ∪ (G.neighborFinset s).image (s(·, t))) \ {s(t, t)} := by simp only [incidenceFinset, neighborFinset, ← Set.toFinset_diff, ← Set.toFinset_image, ← Set.toFinset_union, ← Set.toFinset_singleton] exact Set.toFinset_congr (G.edgeSet_replaceVertex_of_adj ha) lemma disjoint_sdiff_neighborFinset_image : Disjoint (G.edgeFinset \ G.incidenceFinset t) ((G.neighborFinset s).image (s(·, t))) := by rw [disjoint_iff_ne] intro e he have : t ∉ e := by rw [mem_sdiff, mem_incidenceFinset] at he obtain ⟨_, h⟩ := he contrapose! h simp_all [incidenceSet] aesop theorem card_edgeFinset_replaceVertex_of_not_adj (hn : ¬G.Adj s t) : (G.replaceVertex s t).edgeFinset.card = G.edgeFinset.card + G.degree s - G.degree t := by have inc : G.incidenceFinset t ⊆ G.edgeFinset := by simp [incidenceFinset, incidenceSet_subset] rw [G.edgeFinset_replaceVertex_of_not_adj hn, card_union_of_disjoint G.disjoint_sdiff_neighborFinset_image, card_sdiff inc, ← Nat.sub_add_comm <| card_le_card inc, card_incidenceFinset_eq_degree] congr 2 rw [card_image_of_injective, card_neighborFinset_eq_degree] unfold Function.Injective aesop theorem card_edgeFinset_replaceVertex_of_adj (ha : G.Adj s t) : (G.replaceVertex s t).edgeFinset.card = G.edgeFinset.card + G.degree s - G.degree t - 1 := by have inc : G.incidenceFinset t ⊆ G.edgeFinset := by simp [incidenceFinset, incidenceSet_subset] rw [G.edgeFinset_replaceVertex_of_adj ha, card_sdiff (by simp [ha]), card_union_of_disjoint G.disjoint_sdiff_neighborFinset_image, card_sdiff inc, ← Nat.sub_add_comm <| card_le_card inc, card_incidenceFinset_eq_degree] congr 2 rw [card_image_of_injective, card_neighborFinset_eq_degree] unfold Function.Injective aesop end ReplaceVertex section AddEdge /-- The graph with a single `s-t` edge. It is empty iff `s = t`. -/ def edge : SimpleGraph V := fromEdgeSet {s(s, t)} lemma edge_adj (v w : V) : (edge s t).Adj v w ↔ (v = s ∧ w = t ∨ v = t ∧ w = s) ∧ v ≠ w := by rw [edge, fromEdgeSet_adj, Set.mem_singleton_iff, Sym2.eq_iff] variable [DecidableEq V] in instance : DecidableRel (edge s t).Adj := fun _ _ ↦ by rw [edge_adj]; infer_instance lemma edge_self_eq_bot : edge s s = ⊥ := by ext; rw [edge_adj]; aesop @[simp] lemma sup_edge_self : G ⊔ edge s s = G := by rw [edge_self_eq_bot, sup_of_le_left bot_le] variable {s t} lemma edge_edgeSet_of_ne (h : s ≠ t) : (edge s t).edgeSet = {s(s, t)} := by rwa [edge, edgeSet_fromEdgeSet, sdiff_eq_left, Set.disjoint_singleton_left, Set.mem_setOf_eq, Sym2.isDiag_iff_proj_eq] lemma sup_edge_of_adj (h : G.Adj s t) : G ⊔ edge s t = G := by rwa [sup_eq_left, ← edgeSet_subset_edgeSet, edge_edgeSet_of_ne h.ne, Set.singleton_subset_iff, mem_edgeSet] variable [Fintype V] [DecidableRel G.Adj] variable [DecidableEq V] in instance : Fintype (edge s t).edgeSet := by rw [edge]; infer_instance theorem edgeFinset_sup_edge [Fintype (edgeSet (G ⊔ edge s t))] (hn : ¬G.Adj s t) (h : s ≠ t) : (G ⊔ edge s t).edgeFinset = G.edgeFinset.cons s(s, t) (by simp_all) := by letI := Classical.decEq V rw [edgeFinset_sup, cons_eq_insert, insert_eq, union_comm] simp_rw [edgeFinset, edge_edgeSet_of_ne h]; rfl theorem card_edgeFinset_sup_edge [Fintype (edgeSet (G ⊔ edge s t))] (hn : ¬G.Adj s t) (h : s ≠ t) : (G ⊔ edge s t).edgeFinset.card = G.edgeFinset.card + 1 := by rw [G.edgeFinset_sup_edge hn h, card_cons] end AddEdge end SimpleGraph
Combinatorics\SimpleGraph\Partition.lean
/- Copyright (c) 2021 Arthur Paulino. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Arthur Paulino, Kyle Miller -/ import Mathlib.Combinatorics.SimpleGraph.Coloring /-! # Graph partitions This module provides an interface for dealing with partitions on simple graphs. A partition of a graph `G`, with vertices `V`, is a set `P` of disjoint nonempty subsets of `V` such that: * The union of the subsets in `P` is `V`. * Each element of `P` is an independent set. (Each subset contains no pair of adjacent vertices.) Graph partitions are graph colorings that do not name their colors. They are adjoint in the following sense. Given a graph coloring, there is an associated partition from the set of color classes, and given a partition, there is an associated graph coloring from using the partition's subsets as colors. Going from graph colorings to partitions and back makes a coloring "canonical": all colors are given a canonical name and unused colors are removed. Going from partitions to graph colorings and back is the identity. ## Main definitions * `SimpleGraph.Partition` is a structure to represent a partition of a simple graph * `SimpleGraph.Partition.PartsCardLe` is whether a given partition is an `n`-partition. (a partition with at most `n` parts). * `SimpleGraph.Partitionable n` is whether a given graph is `n`-partite * `SimpleGraph.Partition.toColoring` creates colorings from partitions * `SimpleGraph.Coloring.toPartition` creates partitions from colorings ## Main statements * `SimpleGraph.partitionable_iff_colorable` is that `n`-partitionability and `n`-colorability are equivalent. -/ universe u v namespace SimpleGraph variable {V : Type u} (G : SimpleGraph V) /-- A `Partition` of a simple graph `G` is a structure constituted by * `parts`: a set of subsets of the vertices `V` of `G` * `isPartition`: a proof that `parts` is a proper partition of `V` * `independent`: a proof that each element of `parts` doesn't have a pair of adjacent vertices -/ structure Partition where /-- `parts`: a set of subsets of the vertices `V` of `G`. -/ parts : Set (Set V) /-- `isPartition`: a proof that `parts` is a proper partition of `V`. -/ isPartition : Setoid.IsPartition parts /-- `independent`: a proof that each element of `parts` doesn't have a pair of adjacent vertices. -/ independent : ∀ s ∈ parts, IsAntichain G.Adj s /-- Whether a partition `P` has at most `n` parts. A graph with a partition satisfying this predicate called `n`-partite. (See `SimpleGraph.Partitionable`.) -/ def Partition.PartsCardLe {G : SimpleGraph V} (P : G.Partition) (n : ℕ) : Prop := ∃ h : P.parts.Finite, h.toFinset.card ≤ n /-- Whether a graph is `n`-partite, which is whether its vertex set can be partitioned in at most `n` independent sets. -/ def Partitionable (n : ℕ) : Prop := ∃ P : G.Partition, P.PartsCardLe n namespace Partition variable {G} variable (P : G.Partition) /-- The part in the partition that `v` belongs to -/ def partOfVertex (v : V) : Set V := Classical.choose (P.isPartition.2 v) theorem partOfVertex_mem (v : V) : P.partOfVertex v ∈ P.parts := by obtain ⟨h, -⟩ := (P.isPartition.2 v).choose_spec.1 exact h theorem mem_partOfVertex (v : V) : v ∈ P.partOfVertex v := by obtain ⟨⟨_, h⟩, _⟩ := (P.isPartition.2 v).choose_spec exact h theorem partOfVertex_ne_of_adj {v w : V} (h : G.Adj v w) : P.partOfVertex v ≠ P.partOfVertex w := by intro hn have hw := P.mem_partOfVertex w rw [← hn] at hw exact P.independent _ (P.partOfVertex_mem v) (P.mem_partOfVertex v) hw (G.ne_of_adj h) h /-- Create a coloring using the parts themselves as the colors. Each vertex is colored by the part it's contained in. -/ def toColoring : G.Coloring P.parts := Coloring.mk (fun v ↦ ⟨P.partOfVertex v, P.partOfVertex_mem v⟩) fun hvw ↦ by rw [Ne, Subtype.mk_eq_mk] exact P.partOfVertex_ne_of_adj hvw /-- Like `SimpleGraph.Partition.toColoring` but uses `Set V` as the coloring type. -/ def toColoring' : G.Coloring (Set V) := Coloring.mk P.partOfVertex fun hvw ↦ P.partOfVertex_ne_of_adj hvw theorem colorable [Fintype P.parts] : G.Colorable (Fintype.card P.parts) := P.toColoring.colorable end Partition variable {G} /-- Creates a partition from a coloring. -/ @[simps] def Coloring.toPartition {α : Type v} (C : G.Coloring α) : G.Partition where parts := C.colorClasses isPartition := C.colorClasses_isPartition independent := by rintro s ⟨c, rfl⟩ apply C.color_classes_independent /-- The partition where every vertex is in its own part. -/ @[simps] instance : Inhabited (Partition G) := ⟨G.selfColoring.toPartition⟩ theorem partitionable_iff_colorable {n : ℕ} : G.Partitionable n ↔ G.Colorable n := by constructor · rintro ⟨P, hf, hc⟩ have : Fintype P.parts := hf.fintype rw [Set.Finite.card_toFinset hf] at hc apply P.colorable.mono hc · rintro ⟨C⟩ refine ⟨C.toPartition, C.colorClasses_finite, le_trans ?_ (Fintype.card_fin n).le⟩ generalize_proofs h change Set.Finite (Coloring.colorClasses C) at h have : Fintype C.colorClasses := C.colorClasses_finite.fintype rw [h.card_toFinset] exact C.card_colorClasses_le end SimpleGraph
Combinatorics\SimpleGraph\Path.lean
/- Copyright (c) 2021 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import Mathlib.Combinatorics.SimpleGraph.Walk import Mathlib.Combinatorics.SimpleGraph.Subgraph /-! # Trail, Path, and Cycle In a simple graph, * A *trail* is a walk whose edges each appear no more than once. * A *path* is a trail whose vertices appear no more than once. * A *cycle* is a nonempty trail whose first and last vertices are the same and whose vertices except for the first appear no more than once. **Warning:** graph theorists mean something different by "path" than do homotopy theorists. A "walk" in graph theory is a "path" in homotopy theory. Another warning: some graph theorists use "path" and "simple path" for "walk" and "path." Some definitions and theorems have inspiration from multigraph counterparts in [Chou1994]. ## Main definitions * `SimpleGraph.Walk.IsTrail`, `SimpleGraph.Walk.IsPath`, and `SimpleGraph.Walk.IsCycle`. * `SimpleGraph.Path` * `SimpleGraph.Path.map` for the induced map on paths, given an (injective) graph homomorphism. * `SimpleGraph.Reachable` for the relation of whether there exists a walk between a given pair of vertices * `SimpleGraph.Preconnected` and `SimpleGraph.Connected` are predicates on simple graphs for whether every vertex can be reached from every other, and in the latter case, whether the vertex type is nonempty. * `SimpleGraph.ConnectedComponent` is the type of connected components of a given graph. * `SimpleGraph.IsBridge` for whether an edge is a bridge edge ## Main statements * `SimpleGraph.isBridge_iff_mem_and_forall_cycle_not_mem` characterizes bridge edges in terms of there being no cycle containing them. ## Tags trails, paths, circuits, cycles, bridge edges -/ open Function universe u v w namespace SimpleGraph variable {V : Type u} {V' : Type v} {V'' : Type w} variable (G : SimpleGraph V) (G' : SimpleGraph V') (G'' : SimpleGraph V'') namespace Walk variable {G} {u v w : V} /-! ### Trails, paths, circuits, cycles -/ /-- A *trail* is a walk with no repeating edges. -/ @[mk_iff isTrail_def] structure IsTrail {u v : V} (p : G.Walk u v) : Prop where edges_nodup : p.edges.Nodup /-- A *path* is a walk with no repeating vertices. Use `SimpleGraph.Walk.IsPath.mk'` for a simpler constructor. -/ structure IsPath {u v : V} (p : G.Walk u v) extends IsTrail p : Prop where support_nodup : p.support.Nodup -- Porting note: used to use `extends to_trail : is_trail p` in structure protected lemma IsPath.isTrail {p : Walk G u v}(h : IsPath p) : IsTrail p := h.toIsTrail /-- A *circuit* at `u : V` is a nonempty trail beginning and ending at `u`. -/ @[mk_iff isCircuit_def] structure IsCircuit {u : V} (p : G.Walk u u) extends IsTrail p : Prop where ne_nil : p ≠ nil -- Porting note: used to use `extends to_trail : is_trail p` in structure protected lemma IsCircuit.isTrail {p : Walk G u u} (h : IsCircuit p) : IsTrail p := h.toIsTrail /-- A *cycle* at `u : V` is a circuit at `u` whose only repeating vertex is `u` (which appears exactly twice). -/ structure IsCycle {u : V} (p : G.Walk u u) extends IsCircuit p : Prop where support_nodup : p.support.tail.Nodup -- Porting note: used to use `extends to_circuit : is_circuit p` in structure protected lemma IsCycle.isCircuit {p : Walk G u u} (h : IsCycle p) : IsCircuit p := h.toIsCircuit @[simp] theorem isTrail_copy {u v u' v'} (p : G.Walk u v) (hu : u = u') (hv : v = v') : (p.copy hu hv).IsTrail ↔ p.IsTrail := by subst_vars rfl theorem IsPath.mk' {u v : V} {p : G.Walk u v} (h : p.support.Nodup) : p.IsPath := ⟨⟨edges_nodup_of_support_nodup h⟩, h⟩ theorem isPath_def {u v : V} (p : G.Walk u v) : p.IsPath ↔ p.support.Nodup := ⟨IsPath.support_nodup, IsPath.mk'⟩ @[simp] theorem isPath_copy {u v u' v'} (p : G.Walk u v) (hu : u = u') (hv : v = v') : (p.copy hu hv).IsPath ↔ p.IsPath := by subst_vars rfl @[simp] theorem isCircuit_copy {u u'} (p : G.Walk u u) (hu : u = u') : (p.copy hu hu).IsCircuit ↔ p.IsCircuit := by subst_vars rfl lemma IsCircuit.not_nil {p : G.Walk v v} (hp : IsCircuit p) : ¬ p.Nil := (hp.ne_nil ·.eq_nil) theorem isCycle_def {u : V} (p : G.Walk u u) : p.IsCycle ↔ p.IsTrail ∧ p ≠ nil ∧ p.support.tail.Nodup := Iff.intro (fun h => ⟨h.1.1, h.1.2, h.2⟩) fun h => ⟨⟨h.1, h.2.1⟩, h.2.2⟩ @[simp] theorem isCycle_copy {u u'} (p : G.Walk u u) (hu : u = u') : (p.copy hu hu).IsCycle ↔ p.IsCycle := by subst_vars rfl lemma IsCycle.not_nil {p : G.Walk v v} (hp : IsCycle p) : ¬ p.Nil := (hp.ne_nil ·.eq_nil) @[simp] theorem IsTrail.nil {u : V} : (nil : G.Walk u u).IsTrail := ⟨by simp [edges]⟩ theorem IsTrail.of_cons {u v w : V} {h : G.Adj u v} {p : G.Walk v w} : (cons h p).IsTrail → p.IsTrail := by simp [isTrail_def] @[simp] theorem cons_isTrail_iff {u v w : V} (h : G.Adj u v) (p : G.Walk v w) : (cons h p).IsTrail ↔ p.IsTrail ∧ s(u, v) ∉ p.edges := by simp [isTrail_def, and_comm] theorem IsTrail.reverse {u v : V} (p : G.Walk u v) (h : p.IsTrail) : p.reverse.IsTrail := by simpa [isTrail_def] using h @[simp] theorem reverse_isTrail_iff {u v : V} (p : G.Walk u v) : p.reverse.IsTrail ↔ p.IsTrail := by constructor <;> · intro h convert h.reverse _ try rw [reverse_reverse] theorem IsTrail.of_append_left {u v w : V} {p : G.Walk u v} {q : G.Walk v w} (h : (p.append q).IsTrail) : p.IsTrail := by rw [isTrail_def, edges_append, List.nodup_append] at h exact ⟨h.1⟩ theorem IsTrail.of_append_right {u v w : V} {p : G.Walk u v} {q : G.Walk v w} (h : (p.append q).IsTrail) : q.IsTrail := by rw [isTrail_def, edges_append, List.nodup_append] at h exact ⟨h.2.1⟩ theorem IsTrail.count_edges_le_one [DecidableEq V] {u v : V} {p : G.Walk u v} (h : p.IsTrail) (e : Sym2 V) : p.edges.count e ≤ 1 := List.nodup_iff_count_le_one.mp h.edges_nodup e theorem IsTrail.count_edges_eq_one [DecidableEq V] {u v : V} {p : G.Walk u v} (h : p.IsTrail) {e : Sym2 V} (he : e ∈ p.edges) : p.edges.count e = 1 := List.count_eq_one_of_mem h.edges_nodup he theorem IsPath.nil {u : V} : (nil : G.Walk u u).IsPath := by constructor <;> simp theorem IsPath.of_cons {u v w : V} {h : G.Adj u v} {p : G.Walk v w} : (cons h p).IsPath → p.IsPath := by simp [isPath_def] @[simp] theorem cons_isPath_iff {u v w : V} (h : G.Adj u v) (p : G.Walk v w) : (cons h p).IsPath ↔ p.IsPath ∧ u ∉ p.support := by constructor <;> simp (config := { contextual := true }) [isPath_def] protected lemma IsPath.cons {p : Walk G v w} (hp : p.IsPath) (hu : u ∉ p.support) {h : G.Adj u v} : (cons h p).IsPath := (cons_isPath_iff _ _).2 ⟨hp, hu⟩ @[simp] theorem isPath_iff_eq_nil {u : V} (p : G.Walk u u) : p.IsPath ↔ p = nil := by cases p <;> simp [IsPath.nil] theorem IsPath.reverse {u v : V} {p : G.Walk u v} (h : p.IsPath) : p.reverse.IsPath := by simpa [isPath_def] using h @[simp] theorem isPath_reverse_iff {u v : V} (p : G.Walk u v) : p.reverse.IsPath ↔ p.IsPath := by constructor <;> intro h <;> convert h.reverse; simp theorem IsPath.of_append_left {u v w : V} {p : G.Walk u v} {q : G.Walk v w} : (p.append q).IsPath → p.IsPath := by simp only [isPath_def, support_append] exact List.Nodup.of_append_left theorem IsPath.of_append_right {u v w : V} {p : G.Walk u v} {q : G.Walk v w} (h : (p.append q).IsPath) : q.IsPath := by rw [← isPath_reverse_iff] at h ⊢ rw [reverse_append] at h apply h.of_append_left @[simp] theorem IsCycle.not_of_nil {u : V} : ¬(nil : G.Walk u u).IsCycle := fun h => h.ne_nil rfl lemma IsCycle.ne_bot : ∀ {p : G.Walk u u}, p.IsCycle → G ≠ ⊥ | nil, hp => by cases hp.ne_nil rfl | cons h _, hp => by rintro rfl; exact h lemma IsCycle.three_le_length {v : V} {p : G.Walk v v} (hp : p.IsCycle) : 3 ≤ p.length := by have ⟨⟨hp, hp'⟩, _⟩ := hp match p with | .nil => simp at hp' | .cons h .nil => simp at h | .cons _ (.cons _ .nil) => simp at hp | .cons _ (.cons _ (.cons _ _)) => simp_rw [SimpleGraph.Walk.length_cons]; omega theorem cons_isCycle_iff {u v : V} (p : G.Walk v u) (h : G.Adj u v) : (Walk.cons h p).IsCycle ↔ p.IsPath ∧ ¬s(u, v) ∈ p.edges := by simp only [Walk.isCycle_def, Walk.isPath_def, Walk.isTrail_def, edges_cons, List.nodup_cons, support_cons, List.tail_cons] have : p.support.Nodup → p.edges.Nodup := edges_nodup_of_support_nodup tauto lemma IsPath.tail {p : G.Walk u v} (hp : p.IsPath) (hp' : ¬ p.Nil) : (p.tail hp').IsPath := by rw [Walk.isPath_def] at hp ⊢ rw [← cons_support_tail _ hp', List.nodup_cons] at hp exact hp.2 /-! ### About paths -/ instance [DecidableEq V] {u v : V} (p : G.Walk u v) : Decidable p.IsPath := by rw [isPath_def] infer_instance theorem IsPath.length_lt [Fintype V] {u v : V} {p : G.Walk u v} (hp : p.IsPath) : p.length < Fintype.card V := by rw [Nat.lt_iff_add_one_le, ← length_support] exact hp.support_nodup.length_le_card /-! ### Walk decompositions -/ section WalkDecomp variable [DecidableEq V] protected theorem IsTrail.takeUntil {u v w : V} {p : G.Walk v w} (hc : p.IsTrail) (h : u ∈ p.support) : (p.takeUntil u h).IsTrail := IsTrail.of_append_left (q := p.dropUntil u h) (by rwa [← take_spec _ h] at hc) protected theorem IsTrail.dropUntil {u v w : V} {p : G.Walk v w} (hc : p.IsTrail) (h : u ∈ p.support) : (p.dropUntil u h).IsTrail := IsTrail.of_append_right (q := p.dropUntil u h) (by rwa [← take_spec _ h] at hc) protected theorem IsPath.takeUntil {u v w : V} {p : G.Walk v w} (hc : p.IsPath) (h : u ∈ p.support) : (p.takeUntil u h).IsPath := IsPath.of_append_left (q := p.dropUntil u h) (by rwa [← take_spec _ h] at hc) -- Porting note: p was previously accidentally an explicit argument protected theorem IsPath.dropUntil {u v w : V} {p : G.Walk v w} (hc : p.IsPath) (h : u ∈ p.support) : (p.dropUntil u h).IsPath := IsPath.of_append_right (q := p.dropUntil u h) (by rwa [← take_spec _ h] at hc) protected theorem IsTrail.rotate {u v : V} {c : G.Walk v v} (hc : c.IsTrail) (h : u ∈ c.support) : (c.rotate h).IsTrail := by rw [isTrail_def, (c.rotate_edges h).perm.nodup_iff] exact hc.edges_nodup protected theorem IsCircuit.rotate {u v : V} {c : G.Walk v v} (hc : c.IsCircuit) (h : u ∈ c.support) : (c.rotate h).IsCircuit := by refine ⟨hc.isTrail.rotate _, ?_⟩ cases c · exact (hc.ne_nil rfl).elim · intro hn have hn' := congr_arg length hn rw [rotate, length_append, add_comm, ← length_append, take_spec] at hn' simp at hn' protected theorem IsCycle.rotate {u v : V} {c : G.Walk v v} (hc : c.IsCycle) (h : u ∈ c.support) : (c.rotate h).IsCycle := by refine ⟨hc.isCircuit.rotate _, ?_⟩ rw [List.IsRotated.nodup_iff (support_rotate _ _)] exact hc.support_nodup end WalkDecomp end Walk /-! ### Type of paths -/ /-- The type for paths between two vertices. -/ abbrev Path (u v : V) := { p : G.Walk u v // p.IsPath } namespace Path variable {G G'} @[simp] protected theorem isPath {u v : V} (p : G.Path u v) : (p : G.Walk u v).IsPath := p.property @[simp] protected theorem isTrail {u v : V} (p : G.Path u v) : (p : G.Walk u v).IsTrail := p.property.isTrail /-- The length-0 path at a vertex. -/ @[refl, simps] protected def nil {u : V} : G.Path u u := ⟨Walk.nil, Walk.IsPath.nil⟩ /-- The length-1 path between a pair of adjacent vertices. -/ @[simps] def singleton {u v : V} (h : G.Adj u v) : G.Path u v := ⟨Walk.cons h Walk.nil, by simp [h.ne]⟩ theorem mk'_mem_edges_singleton {u v : V} (h : G.Adj u v) : s(u, v) ∈ (singleton h : G.Walk u v).edges := by simp [singleton] /-- The reverse of a path is another path. See also `SimpleGraph.Walk.reverse`. -/ @[symm, simps] def reverse {u v : V} (p : G.Path u v) : G.Path v u := ⟨Walk.reverse p, p.property.reverse⟩ theorem count_support_eq_one [DecidableEq V] {u v w : V} {p : G.Path u v} (hw : w ∈ (p : G.Walk u v).support) : (p : G.Walk u v).support.count w = 1 := List.count_eq_one_of_mem p.property.support_nodup hw theorem count_edges_eq_one [DecidableEq V] {u v : V} {p : G.Path u v} (e : Sym2 V) (hw : e ∈ (p : G.Walk u v).edges) : (p : G.Walk u v).edges.count e = 1 := List.count_eq_one_of_mem p.property.isTrail.edges_nodup hw @[simp] theorem nodup_support {u v : V} (p : G.Path u v) : (p : G.Walk u v).support.Nodup := (Walk.isPath_def _).mp p.property theorem loop_eq {v : V} (p : G.Path v v) : p = Path.nil := by obtain ⟨_ | _, h⟩ := p · rfl · simp at h theorem not_mem_edges_of_loop {v : V} {e : Sym2 V} {p : G.Path v v} : ¬e ∈ (p : G.Walk v v).edges := by simp [p.loop_eq] theorem cons_isCycle {u v : V} (p : G.Path v u) (h : G.Adj u v) (he : ¬s(u, v) ∈ (p : G.Walk v u).edges) : (Walk.cons h ↑p).IsCycle := by simp [Walk.isCycle_def, Walk.cons_isTrail_iff, he] end Path /-! ### Walks to paths -/ namespace Walk variable {G} [DecidableEq V] /-- Given a walk, produces a walk from it by bypassing subwalks between repeated vertices. The result is a path, as shown in `SimpleGraph.Walk.bypass_isPath`. This is packaged up in `SimpleGraph.Walk.toPath`. -/ def bypass {u v : V} : G.Walk u v → G.Walk u v | nil => nil | cons ha p => let p' := p.bypass if hs : u ∈ p'.support then p'.dropUntil u hs else cons ha p' @[simp] theorem bypass_copy {u v u' v'} (p : G.Walk u v) (hu : u = u') (hv : v = v') : (p.copy hu hv).bypass = p.bypass.copy hu hv := by subst_vars rfl theorem bypass_isPath {u v : V} (p : G.Walk u v) : p.bypass.IsPath := by induction p with | nil => simp! | cons _ p' ih => simp only [bypass] split_ifs with hs · exact ih.dropUntil hs · simp [*, cons_isPath_iff] theorem length_bypass_le {u v : V} (p : G.Walk u v) : p.bypass.length ≤ p.length := by induction p with | nil => rfl | cons _ _ ih => simp only [bypass] split_ifs · trans · apply length_dropUntil_le rw [length_cons] omega · rw [length_cons, length_cons] exact Nat.add_le_add_right ih 1 lemma bypass_eq_self_of_length_le {u v : V} (p : G.Walk u v) (h : p.length ≤ p.bypass.length) : p.bypass = p := by induction p with | nil => rfl | cons h p ih => simp only [Walk.bypass] split_ifs with hb · exfalso simp only [hb, Walk.bypass, Walk.length_cons, dif_pos] at h apply Nat.not_succ_le_self p.length calc p.length + 1 _ ≤ (p.bypass.dropUntil _ _).length := h _ ≤ p.bypass.length := Walk.length_dropUntil_le p.bypass hb _ ≤ p.length := Walk.length_bypass_le _ · simp only [hb, Walk.bypass, Walk.length_cons, not_false_iff, dif_neg, Nat.add_le_add_iff_right] at h rw [ih h] /-- Given a walk, produces a path with the same endpoints using `SimpleGraph.Walk.bypass`. -/ def toPath {u v : V} (p : G.Walk u v) : G.Path u v := ⟨p.bypass, p.bypass_isPath⟩ theorem support_bypass_subset {u v : V} (p : G.Walk u v) : p.bypass.support ⊆ p.support := by induction p with | nil => simp! | cons _ _ ih => simp! only split_ifs · apply List.Subset.trans (support_dropUntil_subset _ _) apply List.subset_cons_of_subset assumption · rw [support_cons] apply List.cons_subset_cons assumption theorem support_toPath_subset {u v : V} (p : G.Walk u v) : (p.toPath : G.Walk u v).support ⊆ p.support := support_bypass_subset _ theorem darts_bypass_subset {u v : V} (p : G.Walk u v) : p.bypass.darts ⊆ p.darts := by induction p with | nil => simp! | cons _ _ ih => simp! only split_ifs · apply List.Subset.trans (darts_dropUntil_subset _ _) apply List.subset_cons_of_subset _ ih · rw [darts_cons] exact List.cons_subset_cons _ ih theorem edges_bypass_subset {u v : V} (p : G.Walk u v) : p.bypass.edges ⊆ p.edges := List.map_subset _ p.darts_bypass_subset theorem darts_toPath_subset {u v : V} (p : G.Walk u v) : (p.toPath : G.Walk u v).darts ⊆ p.darts := darts_bypass_subset _ theorem edges_toPath_subset {u v : V} (p : G.Walk u v) : (p.toPath : G.Walk u v).edges ⊆ p.edges := edges_bypass_subset _ end Walk /-! ### Mapping paths -/ namespace Walk variable {G G' G''} variable (f : G →g G') (f' : G' →g G'') {u v u' v' : V} (p : G.Walk u v) variable {p f} theorem map_isPath_of_injective (hinj : Function.Injective f) (hp : p.IsPath) : (p.map f).IsPath := by induction p with | nil => simp | cons _ _ ih => rw [Walk.cons_isPath_iff] at hp simp only [map_cons, cons_isPath_iff, ih hp.1, support_map, List.mem_map, not_exists, not_and, true_and] intro x hx hf cases hinj hf exact hp.2 hx protected theorem IsPath.of_map {f : G →g G'} (hp : (p.map f).IsPath) : p.IsPath := by induction p with | nil => simp | cons _ _ ih => rw [map_cons, Walk.cons_isPath_iff, support_map] at hp rw [Walk.cons_isPath_iff] cases' hp with hp1 hp2 refine ⟨ih hp1, ?_⟩ contrapose! hp2 exact List.mem_map_of_mem f hp2 theorem map_isPath_iff_of_injective (hinj : Function.Injective f) : (p.map f).IsPath ↔ p.IsPath := ⟨IsPath.of_map, map_isPath_of_injective hinj⟩ theorem map_isTrail_iff_of_injective (hinj : Function.Injective f) : (p.map f).IsTrail ↔ p.IsTrail := by induction p with | nil => simp | cons _ _ ih => rw [map_cons, cons_isTrail_iff, ih, cons_isTrail_iff] apply and_congr_right' rw [← Sym2.map_pair_eq, edges_map, ← List.mem_map_of_injective (Sym2.map.injective hinj)] alias ⟨_, map_isTrail_of_injective⟩ := map_isTrail_iff_of_injective theorem map_isCycle_iff_of_injective {p : G.Walk u u} (hinj : Function.Injective f) : (p.map f).IsCycle ↔ p.IsCycle := by rw [isCycle_def, isCycle_def, map_isTrail_iff_of_injective hinj, Ne, map_eq_nil_iff, support_map, ← List.map_tail, List.nodup_map_iff hinj] alias ⟨_, IsCycle.map⟩ := map_isCycle_iff_of_injective @[simp] theorem mapLe_isTrail {G G' : SimpleGraph V} (h : G ≤ G') {u v : V} {p : G.Walk u v} : (p.mapLe h).IsTrail ↔ p.IsTrail := map_isTrail_iff_of_injective Function.injective_id alias ⟨IsTrail.of_mapLe, IsTrail.mapLe⟩ := mapLe_isTrail @[simp] theorem mapLe_isPath {G G' : SimpleGraph V} (h : G ≤ G') {u v : V} {p : G.Walk u v} : (p.mapLe h).IsPath ↔ p.IsPath := map_isPath_iff_of_injective Function.injective_id alias ⟨IsPath.of_mapLe, IsPath.mapLe⟩ := mapLe_isPath @[simp] theorem mapLe_isCycle {G G' : SimpleGraph V} (h : G ≤ G') {u : V} {p : G.Walk u u} : (p.mapLe h).IsCycle ↔ p.IsCycle := map_isCycle_iff_of_injective Function.injective_id alias ⟨IsCycle.of_mapLe, IsCycle.mapLe⟩ := mapLe_isCycle end Walk namespace Path variable {G G'} /-- Given an injective graph homomorphism, map paths to paths. -/ @[simps] protected def map (f : G →g G') (hinj : Function.Injective f) {u v : V} (p : G.Path u v) : G'.Path (f u) (f v) := ⟨Walk.map f p, Walk.map_isPath_of_injective hinj p.2⟩ theorem map_injective {f : G →g G'} (hinj : Function.Injective f) (u v : V) : Function.Injective (Path.map f hinj : G.Path u v → G'.Path (f u) (f v)) := by rintro ⟨p, hp⟩ ⟨p', hp'⟩ h simp only [Path.map, Subtype.coe_mk, Subtype.mk.injEq] at h simp [Walk.map_injective_of_injective hinj u v h] /-- Given a graph embedding, map paths to paths. -/ @[simps!] protected def mapEmbedding (f : G ↪g G') {u v : V} (p : G.Path u v) : G'.Path (f u) (f v) := Path.map f.toHom f.injective p theorem mapEmbedding_injective (f : G ↪g G') (u v : V) : Function.Injective (Path.mapEmbedding f : G.Path u v → G'.Path (f u) (f v)) := map_injective f.injective u v end Path /-! ### Transferring between graphs -/ namespace Walk variable {G} {p} {u v : V} {H : SimpleGraph V} variable (p : G.Walk u v) protected theorem IsPath.transfer (hp) (pp : p.IsPath) : (p.transfer H hp).IsPath := by induction p with | nil => simp | cons _ _ ih => simp only [Walk.transfer, cons_isPath_iff, support_transfer _ ] at pp ⊢ exact ⟨ih _ pp.1, pp.2⟩ protected theorem IsCycle.transfer {q : G.Walk u u} (qc : q.IsCycle) (hq) : (q.transfer H hq).IsCycle := by cases q with | nil => simp at qc | cons _ q => simp only [edges_cons, List.find?, List.mem_cons, forall_eq_or_imp, mem_edgeSet] at hq simp only [Walk.transfer, cons_isCycle_iff, edges_transfer q hq.2] at qc ⊢ exact ⟨qc.1.transfer hq.2, qc.2⟩ end Walk /-! ## Deleting edges -/ namespace Walk variable {v w : V} protected theorem IsPath.toDeleteEdges (s : Set (Sym2 V)) {p : G.Walk v w} (h : p.IsPath) (hp) : (p.toDeleteEdges s hp).IsPath := h.transfer _ protected theorem IsCycle.toDeleteEdges (s : Set (Sym2 V)) {p : G.Walk v v} (h : p.IsCycle) (hp) : (p.toDeleteEdges s hp).IsCycle := h.transfer _ @[simp] theorem toDeleteEdges_copy {v u u' v' : V} (s : Set (Sym2 V)) (p : G.Walk u v) (hu : u = u') (hv : v = v') (h) : (p.copy hu hv).toDeleteEdges s h = (p.toDeleteEdges s (by subst_vars; exact h)).copy hu hv := by subst_vars rfl end Walk /-! ## `Reachable` and `Connected` -/ /-- Two vertices are *reachable* if there is a walk between them. This is equivalent to `Relation.ReflTransGen` of `G.Adj`. See `SimpleGraph.reachable_iff_reflTransGen`. -/ def Reachable (u v : V) : Prop := Nonempty (G.Walk u v) variable {G} theorem reachable_iff_nonempty_univ {u v : V} : G.Reachable u v ↔ (Set.univ : Set (G.Walk u v)).Nonempty := Set.nonempty_iff_univ_nonempty lemma not_reachable_iff_isEmpty_walk {u v : V} : ¬G.Reachable u v ↔ IsEmpty (G.Walk u v) := not_nonempty_iff protected theorem Reachable.elim {p : Prop} {u v : V} (h : G.Reachable u v) (hp : G.Walk u v → p) : p := Nonempty.elim h hp protected theorem Reachable.elim_path {p : Prop} {u v : V} (h : G.Reachable u v) (hp : G.Path u v → p) : p := by classical exact h.elim fun q => hp q.toPath protected theorem Walk.reachable {G : SimpleGraph V} {u v : V} (p : G.Walk u v) : G.Reachable u v := ⟨p⟩ protected theorem Adj.reachable {u v : V} (h : G.Adj u v) : G.Reachable u v := h.toWalk.reachable @[refl] protected theorem Reachable.refl (u : V) : G.Reachable u u := ⟨Walk.nil⟩ protected theorem Reachable.rfl {u : V} : G.Reachable u u := Reachable.refl _ @[symm] protected theorem Reachable.symm {u v : V} (huv : G.Reachable u v) : G.Reachable v u := huv.elim fun p => ⟨p.reverse⟩ theorem reachable_comm {u v : V} : G.Reachable u v ↔ G.Reachable v u := ⟨Reachable.symm, Reachable.symm⟩ @[trans] protected theorem Reachable.trans {u v w : V} (huv : G.Reachable u v) (hvw : G.Reachable v w) : G.Reachable u w := huv.elim fun puv => hvw.elim fun pvw => ⟨puv.append pvw⟩ theorem reachable_iff_reflTransGen (u v : V) : G.Reachable u v ↔ Relation.ReflTransGen G.Adj u v := by constructor · rintro ⟨h⟩ induction h with | nil => rfl | cons h' _ ih => exact (Relation.ReflTransGen.single h').trans ih · intro h induction h with | refl => rfl | tail _ ha hr => exact Reachable.trans hr ⟨Walk.cons ha Walk.nil⟩ protected theorem Reachable.map {u v : V} {G : SimpleGraph V} {G' : SimpleGraph V'} (f : G →g G') (h : G.Reachable u v) : G'.Reachable (f u) (f v) := h.elim fun p => ⟨p.map f⟩ @[mono] protected lemma Reachable.mono {u v : V} {G G' : SimpleGraph V} (h : G ≤ G') (Guv : G.Reachable u v) : G'.Reachable u v := Guv.map (SimpleGraph.Hom.mapSpanningSubgraphs h) theorem Iso.reachable_iff {G : SimpleGraph V} {G' : SimpleGraph V'} {φ : G ≃g G'} {u v : V} : G'.Reachable (φ u) (φ v) ↔ G.Reachable u v := ⟨fun r => φ.left_inv u ▸ φ.left_inv v ▸ r.map φ.symm.toHom, Reachable.map φ.toHom⟩ theorem Iso.symm_apply_reachable {G : SimpleGraph V} {G' : SimpleGraph V'} {φ : G ≃g G'} {u : V} {v : V'} : G.Reachable (φ.symm v) u ↔ G'.Reachable v (φ u) := by rw [← Iso.reachable_iff, RelIso.apply_symm_apply] variable (G) theorem reachable_is_equivalence : Equivalence G.Reachable := Equivalence.mk (@Reachable.refl _ G) (@Reachable.symm _ G) (@Reachable.trans _ G) /-- Distinct vertices are not reachable in the empty graph. -/ @[simp] lemma reachable_bot {u v : V} : (⊥ : SimpleGraph V).Reachable u v ↔ u = v := ⟨fun h ↦ h.elim fun p ↦ match p with | .nil => rfl, fun h ↦ h ▸ .rfl⟩ /-- The equivalence relation on vertices given by `SimpleGraph.Reachable`. -/ def reachableSetoid : Setoid V := Setoid.mk _ G.reachable_is_equivalence /-- A graph is preconnected if every pair of vertices is reachable from one another. -/ def Preconnected : Prop := ∀ u v : V, G.Reachable u v theorem Preconnected.map {G : SimpleGraph V} {H : SimpleGraph V'} (f : G →g H) (hf : Surjective f) (hG : G.Preconnected) : H.Preconnected := hf.forall₂.2 fun _ _ => Nonempty.map (Walk.map _) <| hG _ _ @[mono] protected lemma Preconnected.mono {G G' : SimpleGraph V} (h : G ≤ G') (hG : G.Preconnected) : G'.Preconnected := fun u v => (hG u v).mono h lemma top_preconnected : (⊤ : SimpleGraph V).Preconnected := fun x y => by if h : x = y then rw [h] else exact Adj.reachable h theorem Iso.preconnected_iff {G : SimpleGraph V} {H : SimpleGraph V'} (e : G ≃g H) : G.Preconnected ↔ H.Preconnected := ⟨Preconnected.map e.toHom e.toEquiv.surjective, Preconnected.map e.symm.toHom e.symm.toEquiv.surjective⟩ /-- A graph is connected if it's preconnected and contains at least one vertex. This follows the convention observed by mathlib that something is connected iff it has exactly one connected component. There is a `CoeFun` instance so that `h u v` can be used instead of `h.Preconnected u v`. -/ @[mk_iff] structure Connected : Prop where protected preconnected : G.Preconnected protected [nonempty : Nonempty V] lemma connected_iff_exists_forall_reachable : G.Connected ↔ ∃ v, ∀ w, G.Reachable v w := by rw [connected_iff] constructor · rintro ⟨hp, ⟨v⟩⟩ exact ⟨v, fun w => hp v w⟩ · rintro ⟨v, h⟩ exact ⟨fun u w => (h u).symm.trans (h w), ⟨v⟩⟩ instance : CoeFun G.Connected fun _ => ∀ u v : V, G.Reachable u v := ⟨fun h => h.preconnected⟩ theorem Connected.map {G : SimpleGraph V} {H : SimpleGraph V'} (f : G →g H) (hf : Surjective f) (hG : G.Connected) : H.Connected := haveI := hG.nonempty.map f ⟨hG.preconnected.map f hf⟩ @[mono] protected lemma Connected.mono {G G' : SimpleGraph V} (h : G ≤ G') (hG : G.Connected) : G'.Connected where preconnected := hG.preconnected.mono h nonempty := hG.nonempty lemma top_connected [Nonempty V] : (⊤ : SimpleGraph V).Connected where preconnected := top_preconnected theorem Iso.connected_iff {G : SimpleGraph V} {H : SimpleGraph V'} (e : G ≃g H) : G.Connected ↔ H.Connected := ⟨Connected.map e.toHom e.toEquiv.surjective, Connected.map e.symm.toHom e.symm.toEquiv.surjective⟩ /-- The quotient of `V` by the `SimpleGraph.Reachable` relation gives the connected components of a graph. -/ def ConnectedComponent := Quot G.Reachable /-- Gives the connected component containing a particular vertex. -/ def connectedComponentMk (v : V) : G.ConnectedComponent := Quot.mk G.Reachable v variable {G G' G''} namespace ConnectedComponent @[simps] instance inhabited [Inhabited V] : Inhabited G.ConnectedComponent := ⟨G.connectedComponentMk default⟩ @[elab_as_elim] protected theorem ind {β : G.ConnectedComponent → Prop} (h : ∀ v : V, β (G.connectedComponentMk v)) (c : G.ConnectedComponent) : β c := Quot.ind h c @[elab_as_elim] protected theorem ind₂ {β : G.ConnectedComponent → G.ConnectedComponent → Prop} (h : ∀ v w : V, β (G.connectedComponentMk v) (G.connectedComponentMk w)) (c d : G.ConnectedComponent) : β c d := Quot.induction_on₂ c d h protected theorem sound {v w : V} : G.Reachable v w → G.connectedComponentMk v = G.connectedComponentMk w := Quot.sound protected theorem exact {v w : V} : G.connectedComponentMk v = G.connectedComponentMk w → G.Reachable v w := @Quotient.exact _ G.reachableSetoid _ _ @[simp] protected theorem eq {v w : V} : G.connectedComponentMk v = G.connectedComponentMk w ↔ G.Reachable v w := @Quotient.eq' _ G.reachableSetoid _ _ theorem connectedComponentMk_eq_of_adj {v w : V} (a : G.Adj v w) : G.connectedComponentMk v = G.connectedComponentMk w := ConnectedComponent.sound a.reachable /-- The `ConnectedComponent` specialization of `Quot.lift`. Provides the stronger assumption that the vertices are connected by a path. -/ protected def lift {β : Sort*} (f : V → β) (h : ∀ (v w : V) (p : G.Walk v w), p.IsPath → f v = f w) : G.ConnectedComponent → β := Quot.lift f fun v w (h' : G.Reachable v w) => h'.elim_path fun hp => h v w hp hp.2 @[simp] protected theorem lift_mk {β : Sort*} {f : V → β} {h : ∀ (v w : V) (p : G.Walk v w), p.IsPath → f v = f w} {v : V} : ConnectedComponent.lift f h (G.connectedComponentMk v) = f v := rfl protected theorem «exists» {p : G.ConnectedComponent → Prop} : (∃ c : G.ConnectedComponent, p c) ↔ ∃ v, p (G.connectedComponentMk v) := (surjective_quot_mk G.Reachable).exists protected theorem «forall» {p : G.ConnectedComponent → Prop} : (∀ c : G.ConnectedComponent, p c) ↔ ∀ v, p (G.connectedComponentMk v) := (surjective_quot_mk G.Reachable).forall theorem _root_.SimpleGraph.Preconnected.subsingleton_connectedComponent (h : G.Preconnected) : Subsingleton G.ConnectedComponent := ⟨ConnectedComponent.ind₂ fun v w => ConnectedComponent.sound (h v w)⟩ /-- This is `Quot.recOn` specialized to connected components. For convenience, it strengthens the assumptions in the hypothesis to provide a path between the vertices. -/ @[elab_as_elim] def recOn {motive : G.ConnectedComponent → Sort*} (c : G.ConnectedComponent) (f : (v : V) → motive (G.connectedComponentMk v)) (h : ∀ (u v : V) (p : G.Walk u v) (_ : p.IsPath), ConnectedComponent.sound p.reachable ▸ f u = f v) : motive c := Quot.recOn c f fun u v r => r.elim_path fun p => h u v p p.2 /-- The map on connected components induced by a graph homomorphism. -/ def map (φ : G →g G') (C : G.ConnectedComponent) : G'.ConnectedComponent := C.lift (fun v => G'.connectedComponentMk (φ v)) fun _ _ p _ => ConnectedComponent.eq.mpr (p.map φ).reachable @[simp] theorem map_mk (φ : G →g G') (v : V) : (G.connectedComponentMk v).map φ = G'.connectedComponentMk (φ v) := rfl @[simp] theorem map_id (C : ConnectedComponent G) : C.map Hom.id = C := by refine C.ind ?_ exact fun _ => rfl @[simp] theorem map_comp (C : G.ConnectedComponent) (φ : G →g G') (ψ : G' →g G'') : (C.map φ).map ψ = C.map (ψ.comp φ) := by refine C.ind ?_ exact fun _ => rfl variable {φ : G ≃g G'} {v : V} {v' : V'} @[simp] theorem iso_image_comp_eq_map_iff_eq_comp {C : G.ConnectedComponent} : G'.connectedComponentMk (φ v) = C.map ↑(↑φ : G ↪g G') ↔ G.connectedComponentMk v = C := by refine C.ind fun u => ?_ simp only [Iso.reachable_iff, ConnectedComponent.map_mk, RelEmbedding.coe_toRelHom, RelIso.coe_toRelEmbedding, ConnectedComponent.eq] @[simp] theorem iso_inv_image_comp_eq_iff_eq_map {C : G.ConnectedComponent} : G.connectedComponentMk (φ.symm v') = C ↔ G'.connectedComponentMk v' = C.map φ := by refine C.ind fun u => ?_ simp only [Iso.symm_apply_reachable, ConnectedComponent.eq, ConnectedComponent.map_mk, RelEmbedding.coe_toRelHom, RelIso.coe_toRelEmbedding] end ConnectedComponent namespace Iso /-- An isomorphism of graphs induces a bijection of connected components. -/ @[simps] def connectedComponentEquiv (φ : G ≃g G') : G.ConnectedComponent ≃ G'.ConnectedComponent where toFun := ConnectedComponent.map φ invFun := ConnectedComponent.map φ.symm left_inv C := ConnectedComponent.ind (fun v => congr_arg G.connectedComponentMk (Equiv.left_inv φ.toEquiv v)) C right_inv C := ConnectedComponent.ind (fun v => congr_arg G'.connectedComponentMk (Equiv.right_inv φ.toEquiv v)) C @[simp] theorem connectedComponentEquiv_refl : (Iso.refl : G ≃g G).connectedComponentEquiv = Equiv.refl _ := by ext ⟨v⟩ rfl @[simp] theorem connectedComponentEquiv_symm (φ : G ≃g G') : φ.symm.connectedComponentEquiv = φ.connectedComponentEquiv.symm := by ext ⟨_⟩ rfl @[simp] theorem connectedComponentEquiv_trans (φ : G ≃g G') (φ' : G' ≃g G'') : connectedComponentEquiv (φ.trans φ') = φ.connectedComponentEquiv.trans φ'.connectedComponentEquiv := by ext ⟨_⟩ rfl end Iso namespace ConnectedComponent /-- The set of vertices in a connected component of a graph. -/ def supp (C : G.ConnectedComponent) := { v | G.connectedComponentMk v = C } @[ext] theorem supp_injective : Function.Injective (ConnectedComponent.supp : G.ConnectedComponent → Set V) := by refine ConnectedComponent.ind₂ ?_ intro v w simp only [ConnectedComponent.supp, Set.ext_iff, ConnectedComponent.eq, Set.mem_setOf_eq] intro h rw [reachable_comm, h] @[simp] theorem supp_inj {C D : G.ConnectedComponent} : C.supp = D.supp ↔ C = D := ConnectedComponent.supp_injective.eq_iff instance : SetLike G.ConnectedComponent V where coe := ConnectedComponent.supp coe_injective' := ConnectedComponent.supp_injective @[simp] theorem mem_supp_iff (C : G.ConnectedComponent) (v : V) : v ∈ C.supp ↔ G.connectedComponentMk v = C := Iff.rfl theorem connectedComponentMk_mem {v : V} : v ∈ G.connectedComponentMk v := rfl /-- The equivalence between connected components, induced by an isomorphism of graphs, itself defines an equivalence on the supports of each connected component. -/ def isoEquivSupp (φ : G ≃g G') (C : G.ConnectedComponent) : C.supp ≃ (φ.connectedComponentEquiv C).supp where toFun v := ⟨φ v, ConnectedComponent.iso_image_comp_eq_map_iff_eq_comp.mpr v.prop⟩ invFun v' := ⟨φ.symm v', ConnectedComponent.iso_inv_image_comp_eq_iff_eq_map.mpr v'.prop⟩ left_inv v := Subtype.ext_val (φ.toEquiv.left_inv ↑v) right_inv v := Subtype.ext_val (φ.toEquiv.right_inv ↑v) lemma mem_coe_supp_of_adj {v w : V} {H : Subgraph G} {c : ConnectedComponent H.coe} (hv : v ∈ (↑) '' (c : Set H.verts)) (hw : w ∈ H.verts) (hadj : H.Adj v w) : w ∈ (↑) '' (c : Set H.verts):= by obtain ⟨_, h⟩ := hv use ⟨w, hw⟩ rw [← (mem_supp_iff _ _).mp h.1] exact ⟨connectedComponentMk_eq_of_adj <| Subgraph.Adj.coe <| h.2 ▸ hadj.symm, rfl⟩ end ConnectedComponent -- TODO: Extract as lemma about general equivalence relation lemma pairwise_disjoint_supp_connectedComponent (G : SimpleGraph V) : Pairwise fun c c' : ConnectedComponent G ↦ Disjoint c.supp c'.supp := by simp_rw [Set.disjoint_left] intro _ _ h a hsx hsy rw [ConnectedComponent.mem_supp_iff] at hsx hsy rw [hsx] at hsy exact h hsy -- TODO: Extract as lemma about general equivalence relation lemma iUnion_connectedComponentSupp (G : SimpleGraph V) : ⋃ c : G.ConnectedComponent, c.supp = Set.univ := by refine Set.eq_univ_of_forall fun v ↦ ⟨G.connectedComponentMk v, ?_⟩ simp only [Set.mem_range, SetLike.mem_coe] exact ⟨by use G.connectedComponentMk v; exact rfl, rfl⟩ theorem Preconnected.set_univ_walk_nonempty (hconn : G.Preconnected) (u v : V) : (Set.univ : Set (G.Walk u v)).Nonempty := by rw [← Set.nonempty_iff_univ_nonempty] exact hconn u v theorem Connected.set_univ_walk_nonempty (hconn : G.Connected) (u v : V) : (Set.univ : Set (G.Walk u v)).Nonempty := hconn.preconnected.set_univ_walk_nonempty u v /-! ### Bridge edges -/ section BridgeEdges /-- An edge of a graph is a *bridge* if, after removing it, its incident vertices are no longer reachable from one another. -/ def IsBridge (G : SimpleGraph V) (e : Sym2 V) : Prop := e ∈ G.edgeSet ∧ Sym2.lift ⟨fun v w => ¬(G \ fromEdgeSet {e}).Reachable v w, by simp [reachable_comm]⟩ e theorem isBridge_iff {u v : V} : G.IsBridge s(u, v) ↔ G.Adj u v ∧ ¬(G \ fromEdgeSet {s(u, v)}).Reachable u v := Iff.rfl theorem reachable_delete_edges_iff_exists_walk {v w : V} : (G \ fromEdgeSet {s(v, w)}).Reachable v w ↔ ∃ p : G.Walk v w, ¬s(v, w) ∈ p.edges := by constructor · rintro ⟨p⟩ use p.map (Hom.mapSpanningSubgraphs (by simp)) simp_rw [Walk.edges_map, List.mem_map, Hom.mapSpanningSubgraphs_apply, Sym2.map_id', id] rintro ⟨e, h, rfl⟩ simpa using p.edges_subset_edgeSet h · rintro ⟨p, h⟩ refine ⟨p.transfer _ fun e ep => ?_⟩ simp only [edgeSet_sdiff, edgeSet_fromEdgeSet, edgeSet_sdiff_sdiff_isDiag, Set.mem_diff, Set.mem_singleton_iff] exact ⟨p.edges_subset_edgeSet ep, fun h' => h (h' ▸ ep)⟩ theorem isBridge_iff_adj_and_forall_walk_mem_edges {v w : V} : G.IsBridge s(v, w) ↔ G.Adj v w ∧ ∀ p : G.Walk v w, s(v, w) ∈ p.edges := by rw [isBridge_iff, and_congr_right'] rw [reachable_delete_edges_iff_exists_walk, not_exists_not] theorem reachable_deleteEdges_iff_exists_cycle.aux [DecidableEq V] {u v w : V} (hb : ∀ p : G.Walk v w, s(v, w) ∈ p.edges) (c : G.Walk u u) (hc : c.IsTrail) (he : s(v, w) ∈ c.edges) (hw : w ∈ (c.takeUntil v (c.fst_mem_support_of_mem_edges he)).support) : False := by have hv := c.fst_mem_support_of_mem_edges he -- decompose c into -- puw pwv pvu -- u ----> w ----> v ----> u let puw := (c.takeUntil v hv).takeUntil w hw let pwv := (c.takeUntil v hv).dropUntil w hw let pvu := c.dropUntil v hv have : c = (puw.append pwv).append pvu := by simp [puw, pwv, pvu] -- We have two walks from v to w -- pvu puw -- v ----> u ----> w -- | ^ -- `-------------' -- pwv.reverse -- so they both contain the edge s(v, w), but that's a contradiction since c is a trail. have hbq := hb (pvu.append puw) have hpq' := hb pwv.reverse rw [Walk.edges_reverse, List.mem_reverse] at hpq' rw [Walk.isTrail_def, this, Walk.edges_append, Walk.edges_append, List.nodup_append_comm, ← List.append_assoc, ← Walk.edges_append] at hc exact List.disjoint_of_nodup_append hc hbq hpq' -- Porting note: the unused variable checker helped eliminate a good amount of this proof (!) theorem adj_and_reachable_delete_edges_iff_exists_cycle {v w : V} : G.Adj v w ∧ (G \ fromEdgeSet {s(v, w)}).Reachable v w ↔ ∃ (u : V) (p : G.Walk u u), p.IsCycle ∧ s(v, w) ∈ p.edges := by classical rw [reachable_delete_edges_iff_exists_walk] constructor · rintro ⟨h, p, hp⟩ refine ⟨w, Walk.cons h.symm p.toPath, ?_, ?_⟩ · apply Path.cons_isCycle rw [Sym2.eq_swap] intro h cases hp (Walk.edges_toPath_subset p h) · simp only [Sym2.eq_swap, Walk.edges_cons, List.mem_cons, eq_self_iff_true, true_or_iff] · rintro ⟨u, c, hc, he⟩ refine ⟨c.adj_of_mem_edges he, ?_⟩ by_contra! hb have hb' : ∀ p : G.Walk w v, s(w, v) ∈ p.edges := by intro p simpa [Sym2.eq_swap] using hb p.reverse have hvc : v ∈ c.support := Walk.fst_mem_support_of_mem_edges c he refine reachable_deleteEdges_iff_exists_cycle.aux hb' (c.rotate hvc) (hc.isTrail.rotate hvc) ?_ (Walk.start_mem_support _) rwa [(Walk.rotate_edges c hvc).mem_iff, Sym2.eq_swap] theorem isBridge_iff_adj_and_forall_cycle_not_mem {v w : V} : G.IsBridge s(v, w) ↔ G.Adj v w ∧ ∀ ⦃u : V⦄ (p : G.Walk u u), p.IsCycle → s(v, w) ∉ p.edges := by rw [isBridge_iff, and_congr_right_iff] intro h rw [← not_iff_not] push_neg rw [← adj_and_reachable_delete_edges_iff_exists_cycle] simp only [h, true_and_iff] theorem isBridge_iff_mem_and_forall_cycle_not_mem {e : Sym2 V} : G.IsBridge e ↔ e ∈ G.edgeSet ∧ ∀ ⦃u : V⦄ (p : G.Walk u u), p.IsCycle → e ∉ p.edges := Sym2.ind (fun _ _ => isBridge_iff_adj_and_forall_cycle_not_mem) e end BridgeEdges end SimpleGraph
Combinatorics\SimpleGraph\Prod.lean
/- Copyright (c) 2022 George Peter Banyard, Yaël Dillies, Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: George Peter Banyard, Yaël Dillies, Kyle Miller -/ import Mathlib.Combinatorics.SimpleGraph.Path /-! # Graph products This file defines the box product of graphs and other product constructions. The box product of `G` and `H` is the graph on the product of the vertices such that `x` and `y` are related iff they agree on one component and the other one is related via either `G` or `H`. For example, the box product of two edges is a square. ## Main declarations * `SimpleGraph.boxProd`: The box product. ## Notation * `G □ H`: The box product of `G` and `H`. ## TODO Define all other graph products! -/ variable {α β γ : Type*} namespace SimpleGraph -- Porting note: pruned variables to keep things out of local contexts, which -- can impact how generalization works, or what aesop does. variable {G : SimpleGraph α} {H : SimpleGraph β} /-- Box product of simple graphs. It relates `(a₁, b)` and `(a₂, b)` if `G` relates `a₁` and `a₂`, and `(a, b₁)` and `(a, b₂)` if `H` relates `b₁` and `b₂`. -/ def boxProd (G : SimpleGraph α) (H : SimpleGraph β) : SimpleGraph (α × β) where Adj x y := G.Adj x.1 y.1 ∧ x.2 = y.2 ∨ H.Adj x.2 y.2 ∧ x.1 = y.1 symm x y := by simp [and_comm, or_comm, eq_comm, adj_comm] loopless x := by simp /-- Box product of simple graphs. It relates `(a₁, b)` and `(a₂, b)` if `G` relates `a₁` and `a₂`, and `(a, b₁)` and `(a, b₂)` if `H` relates `b₁` and `b₂`. -/ infixl:70 " □ " => boxProd @[simp] theorem boxProd_adj {x y : α × β} : (G □ H).Adj x y ↔ G.Adj x.1 y.1 ∧ x.2 = y.2 ∨ H.Adj x.2 y.2 ∧ x.1 = y.1 := Iff.rfl --@[simp] Porting note (#10618): `simp` can prove theorem boxProd_adj_left {a₁ : α} {b : β} {a₂ : α} : (G □ H).Adj (a₁, b) (a₂, b) ↔ G.Adj a₁ a₂ := by simp only [boxProd_adj, and_true, SimpleGraph.irrefl, false_and, or_false] --@[simp] Porting note (#10618): `simp` can prove theorem boxProd_adj_right {a : α} {b₁ b₂ : β} : (G □ H).Adj (a, b₁) (a, b₂) ↔ H.Adj b₁ b₂ := by simp only [boxProd_adj, SimpleGraph.irrefl, false_and, and_true, false_or] theorem boxProd_neighborSet (x : α × β) : (G □ H).neighborSet x = G.neighborSet x.1 ×ˢ {x.2} ∪ {x.1} ×ˢ H.neighborSet x.2 := by ext ⟨a', b'⟩ simp only [mem_neighborSet, Set.mem_union, boxProd_adj, Set.mem_prod, Set.mem_singleton_iff] simp only [eq_comm, and_comm] variable (G H) /-- The box product is commutative up to isomorphism. `Equiv.prodComm` as a graph isomorphism. -/ @[simps!] def boxProdComm : G □ H ≃g H □ G := ⟨Equiv.prodComm _ _, or_comm⟩ /-- The box product is associative up to isomorphism. `Equiv.prodAssoc` as a graph isomorphism. -/ @[simps!] def boxProdAssoc (I : SimpleGraph γ) : G □ H □ I ≃g G □ (H □ I) := ⟨Equiv.prodAssoc _ _ _, fun {x y} => by simp only [boxProd_adj, Equiv.prodAssoc_apply, or_and_right, or_assoc, Prod.ext_iff, and_assoc, @and_comm (x.fst.fst = _)]⟩ /-- The embedding of `G` into `G □ H` given by `b`. -/ @[simps] def boxProdLeft (b : β) : G ↪g G □ H where toFun a := (a, b) inj' _ _ := congr_arg Prod.fst map_rel_iff' {_ _} := boxProd_adj_left /-- The embedding of `H` into `G □ H` given by `a`. -/ @[simps] def boxProdRight (a : α) : H ↪g G □ H where toFun := Prod.mk a inj' _ _ := congr_arg Prod.snd map_rel_iff' {_ _} := boxProd_adj_right namespace Walk variable {G} /-- Turn a walk on `G` into a walk on `G □ H`. -/ protected def boxProdLeft {a₁ a₂ : α} (b : β) : G.Walk a₁ a₂ → (G □ H).Walk (a₁, b) (a₂, b) := Walk.map (G.boxProdLeft H b).toHom variable (G) {H} /-- Turn a walk on `H` into a walk on `G □ H`. -/ protected def boxProdRight {b₁ b₂ : β} (a : α) : H.Walk b₁ b₂ → (G □ H).Walk (a, b₁) (a, b₂) := Walk.map (G.boxProdRight H a).toHom variable {G} /-- Project a walk on `G □ H` to a walk on `G` by discarding the moves in the direction of `H`. -/ def ofBoxProdLeft [DecidableEq β] [DecidableRel G.Adj] {x y : α × β} : (G □ H).Walk x y → G.Walk x.1 y.1 | nil => nil | cons h w => Or.by_cases h (fun hG => w.ofBoxProdLeft.cons hG.1) (fun hH => hH.2 ▸ w.ofBoxProdLeft) /-- Project a walk on `G □ H` to a walk on `H` by discarding the moves in the direction of `G`. -/ def ofBoxProdRight [DecidableEq α] [DecidableRel H.Adj] {x y : α × β} : (G □ H).Walk x y → H.Walk x.2 y.2 | nil => nil | cons h w => (Or.symm h).by_cases (fun hH => w.ofBoxProdRight.cons hH.1) (fun hG => hG.2 ▸ w.ofBoxProdRight) @[simp] theorem ofBoxProdLeft_boxProdLeft [DecidableEq β] [DecidableRel G.Adj] {a₁ a₂ : α} {b : β} : ∀ (w : G.Walk a₁ a₂), (w.boxProdLeft H b).ofBoxProdLeft = w | nil => rfl | cons' x y z h w => by rw [Walk.boxProdLeft, map_cons, ofBoxProdLeft, Or.by_cases, dif_pos, ← Walk.boxProdLeft] · simp [ofBoxProdLeft_boxProdLeft] · exact ⟨h, rfl⟩ @[simp] theorem ofBoxProdLeft_boxProdRight [DecidableEq α] [DecidableRel G.Adj] {a b₁ b₂ : α} : ∀ (w : G.Walk b₁ b₂), (w.boxProdRight G a).ofBoxProdRight = w | nil => rfl | cons' x y z h w => by rw [Walk.boxProdRight, map_cons, ofBoxProdRight, Or.by_cases, dif_pos, ← Walk.boxProdRight] · simp [ofBoxProdLeft_boxProdRight] · exact ⟨h, rfl⟩ end Walk variable {G H} protected theorem Preconnected.boxProd (hG : G.Preconnected) (hH : H.Preconnected) : (G □ H).Preconnected := by rintro x y obtain ⟨w₁⟩ := hG x.1 y.1 obtain ⟨w₂⟩ := hH x.2 y.2 exact ⟨(w₁.boxProdLeft _ _).append (w₂.boxProdRight _ _)⟩ protected theorem Preconnected.ofBoxProdLeft [Nonempty β] (h : (G □ H).Preconnected) : G.Preconnected := by classical rintro a₁ a₂ obtain ⟨w⟩ := h (a₁, Classical.arbitrary _) (a₂, Classical.arbitrary _) exact ⟨w.ofBoxProdLeft⟩ protected theorem Preconnected.ofBoxProdRight [Nonempty α] (h : (G □ H).Preconnected) : H.Preconnected := by classical rintro b₁ b₂ obtain ⟨w⟩ := h (Classical.arbitrary _, b₁) (Classical.arbitrary _, b₂) exact ⟨w.ofBoxProdRight⟩ protected theorem Connected.boxProd (hG : G.Connected) (hH : H.Connected) : (G □ H).Connected := by haveI := hG.nonempty haveI := hH.nonempty exact ⟨hG.preconnected.boxProd hH.preconnected⟩ protected theorem Connected.ofBoxProdLeft (h : (G □ H).Connected) : G.Connected := by haveI := (nonempty_prod.1 h.nonempty).1 haveI := (nonempty_prod.1 h.nonempty).2 exact ⟨h.preconnected.ofBoxProdLeft⟩ protected theorem Connected.ofBoxProdRight (h : (G □ H).Connected) : H.Connected := by haveI := (nonempty_prod.1 h.nonempty).1 haveI := (nonempty_prod.1 h.nonempty).2 exact ⟨h.preconnected.ofBoxProdRight⟩ @[simp] theorem boxProd_connected : (G □ H).Connected ↔ G.Connected ∧ H.Connected := ⟨fun h => ⟨h.ofBoxProdLeft, h.ofBoxProdRight⟩, fun h => h.1.boxProd h.2⟩ instance boxProdFintypeNeighborSet (x : α × β) [Fintype (G.neighborSet x.1)] [Fintype (H.neighborSet x.2)] : Fintype ((G □ H).neighborSet x) := Fintype.ofEquiv ((G.neighborFinset x.1 ×ˢ {x.2}).disjUnion ({x.1} ×ˢ H.neighborFinset x.2) <| Finset.disjoint_product.mpr <| Or.inl <| neighborFinset_disjoint_singleton _ _) ((Equiv.refl _).subtypeEquiv fun y => by simp_rw [Finset.mem_disjUnion, Finset.mem_product, Finset.mem_singleton, mem_neighborFinset, mem_neighborSet, Equiv.refl_apply, boxProd_adj] simp only [eq_comm, and_comm]) theorem boxProd_neighborFinset (x : α × β) [Fintype (G.neighborSet x.1)] [Fintype (H.neighborSet x.2)] [Fintype ((G □ H).neighborSet x)] : (G □ H).neighborFinset x = (G.neighborFinset x.1 ×ˢ {x.2}).disjUnion ({x.1} ×ˢ H.neighborFinset x.2) (Finset.disjoint_product.mpr <| Or.inl <| neighborFinset_disjoint_singleton _ _) := by -- swap out the fintype instance for the canonical one letI : Fintype ((G □ H).neighborSet x) := SimpleGraph.boxProdFintypeNeighborSet _ convert_to (G □ H).neighborFinset x = _ using 2 exact Eq.trans (Finset.map_map _ _ _) Finset.attach_map_val theorem boxProd_degree (x : α × β) [Fintype (G.neighborSet x.1)] [Fintype (H.neighborSet x.2)] [Fintype ((G □ H).neighborSet x)] : (G □ H).degree x = G.degree x.1 + H.degree x.2 := by rw [degree, degree, degree, boxProd_neighborFinset, Finset.card_disjUnion] simp_rw [Finset.card_product, Finset.card_singleton, mul_one, one_mul] end SimpleGraph
Combinatorics\SimpleGraph\StronglyRegular.lean
/- Copyright (c) 2021 Alena Gusakov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alena Gusakov, Jeremy Tan -/ import Mathlib.Combinatorics.Enumerative.DoubleCounting import Mathlib.Combinatorics.SimpleGraph.AdjMatrix import Mathlib.Combinatorics.SimpleGraph.Basic import Mathlib.Data.Set.Finite /-! # Strongly regular graphs ## Main definitions * `G.IsSRGWith n k ℓ μ` (see `SimpleGraph.IsSRGWith`) is a structure for a `SimpleGraph` satisfying the following conditions: * The cardinality of the vertex set is `n` * `G` is a regular graph with degree `k` * The number of common neighbors between any two adjacent vertices in `G` is `ℓ` * The number of common neighbors between any two nonadjacent vertices in `G` is `μ` ## Main theorems * `IsSRGWith.compl`: the complement of a strongly regular graph is strongly regular. * `IsSRGWith.param_eq`: `k * (k - ℓ - 1) = (n - k - 1) * μ` when `0 < n`. * `IsSRGWith.matrix_eq`: let `A` and `C` be `G`'s and `Gᶜ`'s adjacency matrices respectively and `I` be the identity matrix, then `A ^ 2 = k • I + ℓ • A + μ • C`. -/ open Finset universe u namespace SimpleGraph variable {V : Type u} [Fintype V] variable (G : SimpleGraph V) [DecidableRel G.Adj] /-- A graph is strongly regular with parameters `n k ℓ μ` if * its vertex set has cardinality `n` * it is regular with degree `k` * every pair of adjacent vertices has `ℓ` common neighbors * every pair of nonadjacent vertices has `μ` common neighbors -/ structure IsSRGWith (n k ℓ μ : ℕ) : Prop where card : Fintype.card V = n regular : G.IsRegularOfDegree k of_adj : ∀ v w : V, G.Adj v w → Fintype.card (G.commonNeighbors v w) = ℓ of_not_adj : Pairwise fun v w => ¬G.Adj v w → Fintype.card (G.commonNeighbors v w) = μ variable {G} {n k ℓ μ : ℕ} /-- Empty graphs are strongly regular. Note that `ℓ` can take any value for empty graphs, since there are no pairs of adjacent vertices. -/ theorem bot_strongly_regular : (⊥ : SimpleGraph V).IsSRGWith (Fintype.card V) 0 ℓ 0 where card := rfl regular := bot_degree of_adj := fun v w h => h.elim of_not_adj := fun v w _h => by simp only [card_eq_zero, Fintype.card_ofFinset, forall_true_left, not_false_iff, bot_adj] ext simp [mem_commonNeighbors] variable [DecidableEq V] /-- Complete graphs are strongly regular. Note that `μ` can take any value for complete graphs, since there are no distinct pairs of non-adjacent vertices. -/ theorem IsSRGWith.top : (⊤ : SimpleGraph V).IsSRGWith (Fintype.card V) (Fintype.card V - 1) (Fintype.card V - 2) μ where card := rfl regular := IsRegularOfDegree.top of_adj := fun v w h => by rw [card_commonNeighbors_top] exact h of_not_adj := fun v w h h' => False.elim (h' ((top_adj v w).2 h)) theorem IsSRGWith.card_neighborFinset_union_eq {v w : V} (h : G.IsSRGWith n k ℓ μ) : (G.neighborFinset v ∪ G.neighborFinset w).card = 2 * k - Fintype.card (G.commonNeighbors v w) := by apply Nat.add_right_cancel (m := Fintype.card (G.commonNeighbors v w)) rw [Nat.sub_add_cancel, ← Set.toFinset_card] -- Porting note: Set.toFinset_inter needs workaround to use unification to solve for one of the -- instance arguments: · simp [commonNeighbors, @Set.toFinset_inter _ _ _ _ _ _ (_), ← neighborFinset_def, Finset.card_union_add_card_inter, card_neighborFinset_eq_degree, h.regular.degree_eq, two_mul] · apply le_trans (card_commonNeighbors_le_degree_left _ _ _) simp [h.regular.degree_eq, two_mul] /-- Assuming `G` is strongly regular, `2*(k + 1) - m` in `G` is the number of vertices that are adjacent to either `v` or `w` when `¬G.Adj v w`. So it's the cardinality of `G.neighborSet v ∪ G.neighborSet w`. -/ theorem IsSRGWith.card_neighborFinset_union_of_not_adj {v w : V} (h : G.IsSRGWith n k ℓ μ) (hne : v ≠ w) (ha : ¬G.Adj v w) : (G.neighborFinset v ∪ G.neighborFinset w).card = 2 * k - μ := by rw [← h.of_not_adj hne ha] apply h.card_neighborFinset_union_eq theorem IsSRGWith.card_neighborFinset_union_of_adj {v w : V} (h : G.IsSRGWith n k ℓ μ) (ha : G.Adj v w) : (G.neighborFinset v ∪ G.neighborFinset w).card = 2 * k - ℓ := by rw [← h.of_adj v w ha] apply h.card_neighborFinset_union_eq theorem compl_neighborFinset_sdiff_inter_eq {v w : V} : (G.neighborFinset v)ᶜ \ {v} ∩ ((G.neighborFinset w)ᶜ \ {w}) = ((G.neighborFinset v)ᶜ ∩ (G.neighborFinset w)ᶜ) \ ({w} ∪ {v}) := by ext rw [← not_iff_not] simp [imp_iff_not_or, or_assoc, or_comm, or_left_comm] theorem sdiff_compl_neighborFinset_inter_eq {v w : V} (h : G.Adj v w) : ((G.neighborFinset v)ᶜ ∩ (G.neighborFinset w)ᶜ) \ ({w} ∪ {v}) = (G.neighborFinset v)ᶜ ∩ (G.neighborFinset w)ᶜ := by ext simp only [and_imp, mem_union, mem_sdiff, mem_compl, and_iff_left_iff_imp, mem_neighborFinset, mem_inter, mem_singleton] rintro hnv hnw (rfl | rfl) · exact hnv h · apply hnw rwa [adj_comm] theorem IsSRGWith.compl_is_regular (h : G.IsSRGWith n k ℓ μ) : Gᶜ.IsRegularOfDegree (n - k - 1) := by rw [← h.card, Nat.sub_sub, add_comm, ← Nat.sub_sub] exact h.regular.compl theorem IsSRGWith.card_commonNeighbors_eq_of_adj_compl (h : G.IsSRGWith n k ℓ μ) {v w : V} (ha : Gᶜ.Adj v w) : Fintype.card (Gᶜ.commonNeighbors v w) = n - (2 * k - μ) - 2 := by simp only [← Set.toFinset_card, commonNeighbors, Set.toFinset_inter, neighborSet_compl, Set.toFinset_diff, Set.toFinset_singleton, Set.toFinset_compl, ← neighborFinset_def] simp_rw [compl_neighborFinset_sdiff_inter_eq] have hne : v ≠ w := ne_of_adj _ ha rw [compl_adj] at ha rw [card_sdiff, ← insert_eq, card_insert_of_not_mem, card_singleton, ← Finset.compl_union] · rw [card_compl, h.card_neighborFinset_union_of_not_adj hne ha.2, ← h.card] · simp only [hne.symm, not_false_iff, mem_singleton] · intro u simp only [mem_union, mem_compl, mem_neighborFinset, mem_inter, mem_singleton] rintro (rfl | rfl) <;> simpa [adj_comm] using ha.2 theorem IsSRGWith.card_commonNeighbors_eq_of_not_adj_compl (h : G.IsSRGWith n k ℓ μ) {v w : V} (hn : v ≠ w) (hna : ¬Gᶜ.Adj v w) : Fintype.card (Gᶜ.commonNeighbors v w) = n - (2 * k - ℓ) := by simp only [← Set.toFinset_card, commonNeighbors, Set.toFinset_inter, neighborSet_compl, Set.toFinset_diff, Set.toFinset_singleton, Set.toFinset_compl, ← neighborFinset_def] simp only [not_and, Classical.not_not, compl_adj] at hna have h2' := hna hn simp_rw [compl_neighborFinset_sdiff_inter_eq, sdiff_compl_neighborFinset_inter_eq h2'] rwa [← Finset.compl_union, card_compl, h.card_neighborFinset_union_of_adj, ← h.card] /-- The complement of a strongly regular graph is strongly regular. -/ theorem IsSRGWith.compl (h : G.IsSRGWith n k ℓ μ) : Gᶜ.IsSRGWith n (n - k - 1) (n - (2 * k - μ) - 2) (n - (2 * k - ℓ)) where card := h.card regular := h.compl_is_regular of_adj := fun _v _w ha => h.card_commonNeighbors_eq_of_adj_compl ha of_not_adj := fun _v _w hn hna => h.card_commonNeighbors_eq_of_not_adj_compl hn hna /-- The parameters of a strongly regular graph with at least one vertex satisfy `k * (k - ℓ - 1) = (n - k - 1) * μ`. -/ theorem IsSRGWith.param_eq {V : Type u} [Fintype V] (G : SimpleGraph V) [DecidableRel G.Adj] (h : G.IsSRGWith n k ℓ μ) (hn : 0 < n) : k * (k - ℓ - 1) = (n - k - 1) * μ := by letI := Classical.decEq V rw [← h.card, Fintype.card_pos_iff] at hn obtain ⟨v⟩ := hn convert card_mul_eq_card_mul G.Adj (s := G.neighborFinset v) (t := Gᶜ.neighborFinset v) _ _ · simp [h.regular v] · simp [h.compl.regular v] · intro w hw rw [mem_neighborFinset] at hw simp_rw [bipartiteAbove] -- This used to be part of the enclosing `simp_rw` chain, -- but after leanprover/lean4#3124 it caused a maximum recursion depth error. change Finset.card (filter (fun a => Adj G w a) _) = _ simp_rw [← mem_neighborFinset, filter_mem_eq_inter] have s : {v} ⊆ G.neighborFinset w \ G.neighborFinset v := by rw [singleton_subset_iff, mem_sdiff, mem_neighborFinset] exact ⟨hw.symm, G.not_mem_neighborFinset_self v⟩ rw [inter_comm, neighborFinset_compl, ← inter_sdiff_assoc, ← sdiff_eq_inter_compl, card_sdiff s, card_singleton, ← sdiff_inter_self_left, card_sdiff (by apply inter_subset_left)] congr · simp [h.regular w] · simp_rw [inter_comm, neighborFinset_def, ← Set.toFinset_inter, ← h.of_adj v w hw, ← Set.toFinset_card] congr! · intro w hw simp_rw [neighborFinset_compl, mem_sdiff, mem_compl, mem_singleton, mem_neighborFinset, ← Ne.eq_def] at hw simp_rw [bipartiteBelow, adj_comm, ← mem_neighborFinset, filter_mem_eq_inter, neighborFinset_def, ← Set.toFinset_inter, ← h.of_not_adj hw.2.symm hw.1, ← Set.toFinset_card] congr! /-- Let `A` and `C` be the adjacency matrices of a strongly regular graph with parameters `n k ℓ μ` and its complement respectively and `I` be the identity matrix, then `A ^ 2 = k • I + ℓ • A + μ • C`. `C` is equivalent to the expression `J - I - A` more often found in the literature, where `J` is the all-ones matrix. -/ theorem IsSRGWith.matrix_eq {α : Type*} [Semiring α] (h : G.IsSRGWith n k ℓ μ) : G.adjMatrix α ^ 2 = k • (1 : Matrix V V α) + ℓ • G.adjMatrix α + μ • Gᶜ.adjMatrix α := by ext v w simp only [adjMatrix_pow_apply_eq_card_walk, Set.coe_setOf, Matrix.add_apply, Matrix.smul_apply, adjMatrix_apply, compl_adj] rw [Fintype.card_congr (G.walkLengthTwoEquivCommonNeighbors v w)] obtain rfl | hn := eq_or_ne v w · rw [← Set.toFinset_card] simp [commonNeighbors, ← neighborFinset_def, h.regular v] · simp only [Matrix.one_apply_ne' hn.symm, ne_eq, hn] by_cases ha : G.Adj v w <;> simp only [ha, ite_true, ite_false, add_zero, zero_add, nsmul_eq_mul, smul_zero, mul_one, not_true_eq_false, not_false_eq_true, and_false, and_self] · rw [h.of_adj v w ha] · rw [h.of_not_adj hn ha] end SimpleGraph
Combinatorics\SimpleGraph\Subgraph.lean
/- Copyright (c) 2021 Hunter Monroe. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Hunter Monroe, Kyle Miller, Alena Gusakov -/ import Mathlib.Combinatorics.SimpleGraph.Finite import Mathlib.Combinatorics.SimpleGraph.Maps /-! # Subgraphs of a simple graph A subgraph of a simple graph consists of subsets of the graph's vertices and edges such that the endpoints of each edge are present in the vertex subset. The edge subset is formalized as a sub-relation of the adjacency relation of the simple graph. ## Main definitions * `Subgraph G` is the type of subgraphs of a `G : SimpleGraph V`. * `Subgraph.neighborSet`, `Subgraph.incidenceSet`, and `Subgraph.degree` are like their `SimpleGraph` counterparts, but they refer to vertices from `G` to avoid subtype coercions. * `Subgraph.coe` is the coercion from a `G' : Subgraph G` to a `SimpleGraph G'.verts`. (In Lean 3 this could not be a `Coe` instance since the destination type depends on `G'`.) * `Subgraph.IsSpanning` for whether a subgraph is a spanning subgraph and `Subgraph.IsInduced` for whether a subgraph is an induced subgraph. * Instances for `Lattice (Subgraph G)` and `BoundedOrder (Subgraph G)`. * `SimpleGraph.toSubgraph`: If a `SimpleGraph` is a subgraph of another, then you can turn it into a member of the larger graph's `SimpleGraph.Subgraph` type. * Graph homomorphisms from a subgraph to a graph (`Subgraph.map_top`) and between subgraphs (`Subgraph.map`). ## Implementation notes * Recall that subgraphs are not determined by their vertex sets, so `SetLike` does not apply to this kind of subobject. ## TODO * Images of graph homomorphisms as subgraphs. -/ universe u v namespace SimpleGraph /-- A subgraph of a `SimpleGraph` is a subset of vertices along with a restriction of the adjacency relation that is symmetric and is supported by the vertex subset. They also form a bounded lattice. Thinking of `V → V → Prop` as `Set (V × V)`, a set of darts (i.e., half-edges), then `Subgraph.adj_sub` is that the darts of a subgraph are a subset of the darts of `G`. -/ @[ext] structure Subgraph {V : Type u} (G : SimpleGraph V) where verts : Set V Adj : V → V → Prop adj_sub : ∀ {v w : V}, Adj v w → G.Adj v w edge_vert : ∀ {v w : V}, Adj v w → v ∈ verts symm : Symmetric Adj := by aesop_graph -- Porting note: Originally `by obviously` initialize_simps_projections SimpleGraph.Subgraph (Adj → adj) variable {ι : Sort*} {V : Type u} {W : Type v} /-- The one-vertex subgraph. -/ @[simps] protected def singletonSubgraph (G : SimpleGraph V) (v : V) : G.Subgraph where verts := {v} Adj := ⊥ adj_sub := False.elim edge_vert := False.elim symm _ _ := False.elim /-- The one-edge subgraph. -/ @[simps] def subgraphOfAdj (G : SimpleGraph V) {v w : V} (hvw : G.Adj v w) : G.Subgraph where verts := {v, w} Adj a b := s(v, w) = s(a, b) adj_sub h := by rw [← G.mem_edgeSet, ← h] exact hvw edge_vert {a b} h := by apply_fun fun e ↦ a ∈ e at h simp only [Sym2.mem_iff, true_or, eq_iff_iff, iff_true] at h exact h namespace Subgraph variable {G : SimpleGraph V} {G₁ G₂ : G.Subgraph} {a b : V} protected theorem loopless (G' : Subgraph G) : Irreflexive G'.Adj := fun v h ↦ G.loopless v (G'.adj_sub h) theorem adj_comm (G' : Subgraph G) (v w : V) : G'.Adj v w ↔ G'.Adj w v := ⟨fun x ↦ G'.symm x, fun x ↦ G'.symm x⟩ @[symm] theorem adj_symm (G' : Subgraph G) {u v : V} (h : G'.Adj u v) : G'.Adj v u := G'.symm h protected theorem Adj.symm {G' : Subgraph G} {u v : V} (h : G'.Adj u v) : G'.Adj v u := G'.symm h protected theorem Adj.adj_sub {H : G.Subgraph} {u v : V} (h : H.Adj u v) : G.Adj u v := H.adj_sub h protected theorem Adj.fst_mem {H : G.Subgraph} {u v : V} (h : H.Adj u v) : u ∈ H.verts := H.edge_vert h protected theorem Adj.snd_mem {H : G.Subgraph} {u v : V} (h : H.Adj u v) : v ∈ H.verts := h.symm.fst_mem protected theorem Adj.ne {H : G.Subgraph} {u v : V} (h : H.Adj u v) : u ≠ v := h.adj_sub.ne /-- Coercion from `G' : Subgraph G` to a `SimpleGraph G'.verts`. -/ @[simps] protected def coe (G' : Subgraph G) : SimpleGraph G'.verts where Adj v w := G'.Adj v w symm _ _ h := G'.symm h loopless v h := loopless G v (G'.adj_sub h) @[simp] theorem coe_adj_sub (G' : Subgraph G) (u v : G'.verts) (h : G'.coe.Adj u v) : G.Adj u v := G'.adj_sub h -- Given `h : H.Adj u v`, then `h.coe : H.coe.Adj ⟨u, _⟩ ⟨v, _⟩`. protected theorem Adj.coe {H : G.Subgraph} {u v : V} (h : H.Adj u v) : H.coe.Adj ⟨u, H.edge_vert h⟩ ⟨v, H.edge_vert h.symm⟩ := h /-- A subgraph is called a *spanning subgraph* if it contains all the vertices of `G`. -/ def IsSpanning (G' : Subgraph G) : Prop := ∀ v : V, v ∈ G'.verts theorem isSpanning_iff {G' : Subgraph G} : G'.IsSpanning ↔ G'.verts = Set.univ := Set.eq_univ_iff_forall.symm protected alias ⟨IsSpanning.verts_eq_univ, _⟩ := isSpanning_iff /-- Coercion from `Subgraph G` to `SimpleGraph V`. If `G'` is a spanning subgraph, then `G'.spanningCoe` yields an isomorphic graph. In general, this adds in all vertices from `V` as isolated vertices. -/ @[simps] protected def spanningCoe (G' : Subgraph G) : SimpleGraph V where Adj := G'.Adj symm := G'.symm loopless v hv := G.loopless v (G'.adj_sub hv) @[simp] theorem Adj.of_spanningCoe {G' : Subgraph G} {u v : G'.verts} (h : G'.spanningCoe.Adj u v) : G.Adj u v := G'.adj_sub h theorem spanningCoe_inj : G₁.spanningCoe = G₂.spanningCoe ↔ G₁.Adj = G₂.Adj := by simp [Subgraph.spanningCoe] /-- `spanningCoe` is equivalent to `coe` for a subgraph that `IsSpanning`. -/ @[simps] def spanningCoeEquivCoeOfSpanning (G' : Subgraph G) (h : G'.IsSpanning) : G'.spanningCoe ≃g G'.coe where toFun v := ⟨v, h v⟩ invFun v := v left_inv _ := rfl right_inv _ := rfl map_rel_iff' := Iff.rfl /-- A subgraph is called an *induced subgraph* if vertices of `G'` are adjacent if they are adjacent in `G`. -/ def IsInduced (G' : Subgraph G) : Prop := ∀ {v w : V}, v ∈ G'.verts → w ∈ G'.verts → G.Adj v w → G'.Adj v w /-- `H.support` is the set of vertices that form edges in the subgraph `H`. -/ def support (H : Subgraph G) : Set V := Rel.dom H.Adj theorem mem_support (H : Subgraph G) {v : V} : v ∈ H.support ↔ ∃ w, H.Adj v w := Iff.rfl theorem support_subset_verts (H : Subgraph G) : H.support ⊆ H.verts := fun _ ⟨_, h⟩ ↦ H.edge_vert h /-- `G'.neighborSet v` is the set of vertices adjacent to `v` in `G'`. -/ def neighborSet (G' : Subgraph G) (v : V) : Set V := {w | G'.Adj v w} theorem neighborSet_subset (G' : Subgraph G) (v : V) : G'.neighborSet v ⊆ G.neighborSet v := fun _ ↦ G'.adj_sub theorem neighborSet_subset_verts (G' : Subgraph G) (v : V) : G'.neighborSet v ⊆ G'.verts := fun _ h ↦ G'.edge_vert (adj_symm G' h) @[simp] theorem mem_neighborSet (G' : Subgraph G) (v w : V) : w ∈ G'.neighborSet v ↔ G'.Adj v w := Iff.rfl /-- A subgraph as a graph has equivalent neighbor sets. -/ def coeNeighborSetEquiv {G' : Subgraph G} (v : G'.verts) : G'.coe.neighborSet v ≃ G'.neighborSet v where toFun w := ⟨w, w.2⟩ invFun w := ⟨⟨w, G'.edge_vert (G'.adj_symm w.2)⟩, w.2⟩ left_inv _ := rfl right_inv _ := rfl /-- The edge set of `G'` consists of a subset of edges of `G`. -/ def edgeSet (G' : Subgraph G) : Set (Sym2 V) := Sym2.fromRel G'.symm theorem edgeSet_subset (G' : Subgraph G) : G'.edgeSet ⊆ G.edgeSet := Sym2.ind (fun _ _ ↦ G'.adj_sub) @[simp] theorem mem_edgeSet {G' : Subgraph G} {v w : V} : s(v, w) ∈ G'.edgeSet ↔ G'.Adj v w := Iff.rfl theorem mem_verts_if_mem_edge {G' : Subgraph G} {e : Sym2 V} {v : V} (he : e ∈ G'.edgeSet) (hv : v ∈ e) : v ∈ G'.verts := by induction e rcases Sym2.mem_iff.mp hv with (rfl | rfl) · exact G'.edge_vert he · exact G'.edge_vert (G'.symm he) /-- The `incidenceSet` is the set of edges incident to a given vertex. -/ def incidenceSet (G' : Subgraph G) (v : V) : Set (Sym2 V) := {e ∈ G'.edgeSet | v ∈ e} theorem incidenceSet_subset_incidenceSet (G' : Subgraph G) (v : V) : G'.incidenceSet v ⊆ G.incidenceSet v := fun _ h ↦ ⟨G'.edgeSet_subset h.1, h.2⟩ theorem incidenceSet_subset (G' : Subgraph G) (v : V) : G'.incidenceSet v ⊆ G'.edgeSet := fun _ h ↦ h.1 /-- Give a vertex as an element of the subgraph's vertex type. -/ abbrev vert (G' : Subgraph G) (v : V) (h : v ∈ G'.verts) : G'.verts := ⟨v, h⟩ /-- Create an equal copy of a subgraph (see `copy_eq`) with possibly different definitional equalities. See Note [range copy pattern]. -/ def copy (G' : Subgraph G) (V'' : Set V) (hV : V'' = G'.verts) (adj' : V → V → Prop) (hadj : adj' = G'.Adj) : Subgraph G where verts := V'' Adj := adj' adj_sub := hadj.symm ▸ G'.adj_sub edge_vert := hV.symm ▸ hadj.symm ▸ G'.edge_vert symm := hadj.symm ▸ G'.symm theorem copy_eq (G' : Subgraph G) (V'' : Set V) (hV : V'' = G'.verts) (adj' : V → V → Prop) (hadj : adj' = G'.Adj) : G'.copy V'' hV adj' hadj = G' := Subgraph.ext hV hadj /-- The union of two subgraphs. -/ instance : Sup G.Subgraph where sup G₁ G₂ := { verts := G₁.verts ∪ G₂.verts Adj := G₁.Adj ⊔ G₂.Adj adj_sub := fun hab => Or.elim hab (fun h => G₁.adj_sub h) fun h => G₂.adj_sub h edge_vert := Or.imp (fun h => G₁.edge_vert h) fun h => G₂.edge_vert h symm := fun _ _ => Or.imp G₁.adj_symm G₂.adj_symm } /-- The intersection of two subgraphs. -/ instance : Inf G.Subgraph where inf G₁ G₂ := { verts := G₁.verts ∩ G₂.verts Adj := G₁.Adj ⊓ G₂.Adj adj_sub := fun hab => G₁.adj_sub hab.1 edge_vert := And.imp (fun h => G₁.edge_vert h) fun h => G₂.edge_vert h symm := fun _ _ => And.imp G₁.adj_symm G₂.adj_symm } /-- The `top` subgraph is `G` as a subgraph of itself. -/ instance : Top G.Subgraph where top := { verts := Set.univ Adj := G.Adj adj_sub := id edge_vert := @fun v _ _ => Set.mem_univ v symm := G.symm } /-- The `bot` subgraph is the subgraph with no vertices or edges. -/ instance : Bot G.Subgraph where bot := { verts := ∅ Adj := ⊥ adj_sub := False.elim edge_vert := False.elim symm := fun _ _ => id } instance : SupSet G.Subgraph where sSup s := { verts := ⋃ G' ∈ s, verts G' Adj := fun a b => ∃ G' ∈ s, Adj G' a b adj_sub := by rintro a b ⟨G', -, hab⟩ exact G'.adj_sub hab edge_vert := by rintro a b ⟨G', hG', hab⟩ exact Set.mem_iUnion₂_of_mem hG' (G'.edge_vert hab) symm := fun a b h => by simpa [adj_comm] using h } instance : InfSet G.Subgraph where sInf s := { verts := ⋂ G' ∈ s, verts G' Adj := fun a b => (∀ ⦃G'⦄, G' ∈ s → Adj G' a b) ∧ G.Adj a b adj_sub := And.right edge_vert := fun hab => Set.mem_iInter₂_of_mem fun G' hG' => G'.edge_vert <| hab.1 hG' symm := fun _ _ => And.imp (forall₂_imp fun _ _ => Adj.symm) G.adj_symm } @[simp] theorem sup_adj : (G₁ ⊔ G₂).Adj a b ↔ G₁.Adj a b ∨ G₂.Adj a b := Iff.rfl @[simp] theorem inf_adj : (G₁ ⊓ G₂).Adj a b ↔ G₁.Adj a b ∧ G₂.Adj a b := Iff.rfl @[simp] theorem top_adj : (⊤ : Subgraph G).Adj a b ↔ G.Adj a b := Iff.rfl @[simp] theorem not_bot_adj : ¬ (⊥ : Subgraph G).Adj a b := not_false @[simp] theorem verts_sup (G₁ G₂ : G.Subgraph) : (G₁ ⊔ G₂).verts = G₁.verts ∪ G₂.verts := rfl @[simp] theorem verts_inf (G₁ G₂ : G.Subgraph) : (G₁ ⊓ G₂).verts = G₁.verts ∩ G₂.verts := rfl @[simp] theorem verts_top : (⊤ : G.Subgraph).verts = Set.univ := rfl @[simp] theorem verts_bot : (⊥ : G.Subgraph).verts = ∅ := rfl @[simp] theorem sSup_adj {s : Set G.Subgraph} : (sSup s).Adj a b ↔ ∃ G ∈ s, Adj G a b := Iff.rfl @[simp] theorem sInf_adj {s : Set G.Subgraph} : (sInf s).Adj a b ↔ (∀ G' ∈ s, Adj G' a b) ∧ G.Adj a b := Iff.rfl @[simp] theorem iSup_adj {f : ι → G.Subgraph} : (⨆ i, f i).Adj a b ↔ ∃ i, (f i).Adj a b := by simp [iSup] @[simp] theorem iInf_adj {f : ι → G.Subgraph} : (⨅ i, f i).Adj a b ↔ (∀ i, (f i).Adj a b) ∧ G.Adj a b := by simp [iInf] theorem sInf_adj_of_nonempty {s : Set G.Subgraph} (hs : s.Nonempty) : (sInf s).Adj a b ↔ ∀ G' ∈ s, Adj G' a b := sInf_adj.trans <| and_iff_left_of_imp <| by obtain ⟨G', hG'⟩ := hs exact fun h => G'.adj_sub (h _ hG') theorem iInf_adj_of_nonempty [Nonempty ι] {f : ι → G.Subgraph} : (⨅ i, f i).Adj a b ↔ ∀ i, (f i).Adj a b := by rw [iInf, sInf_adj_of_nonempty (Set.range_nonempty _)] simp @[simp] theorem verts_sSup (s : Set G.Subgraph) : (sSup s).verts = ⋃ G' ∈ s, verts G' := rfl @[simp] theorem verts_sInf (s : Set G.Subgraph) : (sInf s).verts = ⋂ G' ∈ s, verts G' := rfl @[simp] theorem verts_iSup {f : ι → G.Subgraph} : (⨆ i, f i).verts = ⋃ i, (f i).verts := by simp [iSup] @[simp] theorem verts_iInf {f : ι → G.Subgraph} : (⨅ i, f i).verts = ⋂ i, (f i).verts := by simp [iInf] theorem verts_spanningCoe_injective : (fun G' : Subgraph G => (G'.verts, G'.spanningCoe)).Injective := by intro G₁ G₂ h rw [Prod.ext_iff] at h exact Subgraph.ext h.1 (spanningCoe_inj.1 h.2) /-- For subgraphs `G₁`, `G₂`, `G₁ ≤ G₂` iff `G₁.verts ⊆ G₂.verts` and `∀ a b, G₁.adj a b → G₂.adj a b`. -/ instance distribLattice : DistribLattice G.Subgraph := { show DistribLattice G.Subgraph from verts_spanningCoe_injective.distribLattice _ (fun _ _ => rfl) fun _ _ => rfl with le := fun x y => x.verts ⊆ y.verts ∧ ∀ ⦃v w : V⦄, x.Adj v w → y.Adj v w } instance : BoundedOrder (Subgraph G) where top := ⊤ bot := ⊥ le_top x := ⟨Set.subset_univ _, fun _ _ => x.adj_sub⟩ bot_le _ := ⟨Set.empty_subset _, fun _ _ => False.elim⟩ /-- Note that subgraphs do not form a Boolean algebra, because of `verts`. -/ def completelyDistribLatticeMinimalAxioms : CompletelyDistribLattice.MinimalAxioms G.Subgraph := { Subgraph.distribLattice with le := (· ≤ ·) sup := (· ⊔ ·) inf := (· ⊓ ·) top := ⊤ bot := ⊥ le_top := fun G' => ⟨Set.subset_univ _, fun a b => G'.adj_sub⟩ bot_le := fun G' => ⟨Set.empty_subset _, fun a b => False.elim⟩ sSup := sSup -- Porting note: needed `apply` here to modify elaboration; previously the term itself was fine. le_sSup := fun s G' hG' => ⟨by apply Set.subset_iUnion₂ G' hG', fun a b hab => ⟨G', hG', hab⟩⟩ sSup_le := fun s G' hG' => ⟨Set.iUnion₂_subset fun H hH => (hG' _ hH).1, by rintro a b ⟨H, hH, hab⟩ exact (hG' _ hH).2 hab⟩ sInf := sInf sInf_le := fun s G' hG' => ⟨Set.iInter₂_subset G' hG', fun a b hab => hab.1 hG'⟩ le_sInf := fun s G' hG' => ⟨Set.subset_iInter₂ fun H hH => (hG' _ hH).1, fun a b hab => ⟨fun H hH => (hG' _ hH).2 hab, G'.adj_sub hab⟩⟩ iInf_iSup_eq := fun f => Subgraph.ext (by simpa using iInf_iSup_eq) (by ext; simp [Classical.skolem]) } instance : CompletelyDistribLattice G.Subgraph := .ofMinimalAxioms completelyDistribLatticeMinimalAxioms @[gcongr] lemma verts_mono {H H' : G.Subgraph} (h : H ≤ H') : H.verts ⊆ H'.verts := h.1 lemma verts_monotone : Monotone (verts : G.Subgraph → Set V) := fun _ _ h ↦ h.1 @[simps] instance subgraphInhabited : Inhabited (Subgraph G) := ⟨⊥⟩ @[simp] theorem neighborSet_sup {H H' : G.Subgraph} (v : V) : (H ⊔ H').neighborSet v = H.neighborSet v ∪ H'.neighborSet v := rfl @[simp] theorem neighborSet_inf {H H' : G.Subgraph} (v : V) : (H ⊓ H').neighborSet v = H.neighborSet v ∩ H'.neighborSet v := rfl @[simp] theorem neighborSet_top (v : V) : (⊤ : G.Subgraph).neighborSet v = G.neighborSet v := rfl @[simp] theorem neighborSet_bot (v : V) : (⊥ : G.Subgraph).neighborSet v = ∅ := rfl @[simp] theorem neighborSet_sSup (s : Set G.Subgraph) (v : V) : (sSup s).neighborSet v = ⋃ G' ∈ s, neighborSet G' v := by ext simp @[simp] theorem neighborSet_sInf (s : Set G.Subgraph) (v : V) : (sInf s).neighborSet v = (⋂ G' ∈ s, neighborSet G' v) ∩ G.neighborSet v := by ext simp @[simp] theorem neighborSet_iSup (f : ι → G.Subgraph) (v : V) : (⨆ i, f i).neighborSet v = ⋃ i, (f i).neighborSet v := by simp [iSup] @[simp] theorem neighborSet_iInf (f : ι → G.Subgraph) (v : V) : (⨅ i, f i).neighborSet v = (⋂ i, (f i).neighborSet v) ∩ G.neighborSet v := by simp [iInf] @[simp] theorem edgeSet_top : (⊤ : Subgraph G).edgeSet = G.edgeSet := rfl @[simp] theorem edgeSet_bot : (⊥ : Subgraph G).edgeSet = ∅ := Set.ext <| Sym2.ind (by simp) @[simp] theorem edgeSet_inf {H₁ H₂ : Subgraph G} : (H₁ ⊓ H₂).edgeSet = H₁.edgeSet ∩ H₂.edgeSet := Set.ext <| Sym2.ind (by simp) @[simp] theorem edgeSet_sup {H₁ H₂ : Subgraph G} : (H₁ ⊔ H₂).edgeSet = H₁.edgeSet ∪ H₂.edgeSet := Set.ext <| Sym2.ind (by simp) @[simp] theorem edgeSet_sSup (s : Set G.Subgraph) : (sSup s).edgeSet = ⋃ G' ∈ s, edgeSet G' := by ext e induction e simp @[simp] theorem edgeSet_sInf (s : Set G.Subgraph) : (sInf s).edgeSet = (⋂ G' ∈ s, edgeSet G') ∩ G.edgeSet := by ext e induction e simp @[simp] theorem edgeSet_iSup (f : ι → G.Subgraph) : (⨆ i, f i).edgeSet = ⋃ i, (f i).edgeSet := by simp [iSup] @[simp] theorem edgeSet_iInf (f : ι → G.Subgraph) : (⨅ i, f i).edgeSet = (⋂ i, (f i).edgeSet) ∩ G.edgeSet := by simp [iInf] @[simp] theorem spanningCoe_top : (⊤ : Subgraph G).spanningCoe = G := rfl @[simp] theorem spanningCoe_bot : (⊥ : Subgraph G).spanningCoe = ⊥ := rfl /-- Turn a subgraph of a `SimpleGraph` into a member of its subgraph type. -/ @[simps] def _root_.SimpleGraph.toSubgraph (H : SimpleGraph V) (h : H ≤ G) : G.Subgraph where verts := Set.univ Adj := H.Adj adj_sub e := h e edge_vert _ := Set.mem_univ _ symm := H.symm theorem support_mono {H H' : Subgraph G} (h : H ≤ H') : H.support ⊆ H'.support := Rel.dom_mono h.2 theorem _root_.SimpleGraph.toSubgraph.isSpanning (H : SimpleGraph V) (h : H ≤ G) : (toSubgraph H h).IsSpanning := Set.mem_univ theorem spanningCoe_le_of_le {H H' : Subgraph G} (h : H ≤ H') : H.spanningCoe ≤ H'.spanningCoe := h.2 /-- The top of the `Subgraph G` lattice is equivalent to the graph itself. -/ def topEquiv : (⊤ : Subgraph G).coe ≃g G where toFun v := ↑v invFun v := ⟨v, trivial⟩ left_inv _ := rfl right_inv _ := rfl map_rel_iff' := Iff.rfl /-- The bottom of the `Subgraph G` lattice is equivalent to the empty graph on the empty vertex type. -/ def botEquiv : (⊥ : Subgraph G).coe ≃g (⊥ : SimpleGraph Empty) where toFun v := v.property.elim invFun v := v.elim left_inv := fun ⟨_, h⟩ ↦ h.elim right_inv v := v.elim map_rel_iff' := Iff.rfl theorem edgeSet_mono {H₁ H₂ : Subgraph G} (h : H₁ ≤ H₂) : H₁.edgeSet ≤ H₂.edgeSet := Sym2.ind h.2 theorem _root_.Disjoint.edgeSet {H₁ H₂ : Subgraph G} (h : Disjoint H₁ H₂) : Disjoint H₁.edgeSet H₂.edgeSet := disjoint_iff_inf_le.mpr <| by simpa using edgeSet_mono h.le_bot /-- Graph homomorphisms induce a covariant function on subgraphs. -/ @[simps] protected def map {G' : SimpleGraph W} (f : G →g G') (H : G.Subgraph) : G'.Subgraph where verts := f '' H.verts Adj := Relation.Map H.Adj f f adj_sub := by rintro _ _ ⟨u, v, h, rfl, rfl⟩ exact f.map_rel (H.adj_sub h) edge_vert := by rintro _ _ ⟨u, v, h, rfl, rfl⟩ exact Set.mem_image_of_mem _ (H.edge_vert h) symm := by rintro _ _ ⟨u, v, h, rfl, rfl⟩ exact ⟨v, u, H.symm h, rfl, rfl⟩ theorem map_monotone {G' : SimpleGraph W} (f : G →g G') : Monotone (Subgraph.map f) := by intro H H' h constructor · intro simp only [map_verts, Set.mem_image, forall_exists_index, and_imp] rintro v hv rfl exact ⟨_, h.1 hv, rfl⟩ · rintro _ _ ⟨u, v, ha, rfl, rfl⟩ exact ⟨_, _, h.2 ha, rfl, rfl⟩ theorem map_sup {G : SimpleGraph V} {G' : SimpleGraph W} (f : G →g G') {H H' : G.Subgraph} : (H ⊔ H').map f = H.map f ⊔ H'.map f := by ext1 · simp only [Set.image_union, map_verts, verts_sup] · ext simp only [Relation.Map, map_adj, sup_adj] constructor · rintro ⟨a, b, h | h, rfl, rfl⟩ · exact Or.inl ⟨_, _, h, rfl, rfl⟩ · exact Or.inr ⟨_, _, h, rfl, rfl⟩ · rintro (⟨a, b, h, rfl, rfl⟩ | ⟨a, b, h, rfl, rfl⟩) · exact ⟨_, _, Or.inl h, rfl, rfl⟩ · exact ⟨_, _, Or.inr h, rfl, rfl⟩ /-- Graph homomorphisms induce a contravariant function on subgraphs. -/ @[simps] protected def comap {G' : SimpleGraph W} (f : G →g G') (H : G'.Subgraph) : G.Subgraph where verts := f ⁻¹' H.verts Adj u v := G.Adj u v ∧ H.Adj (f u) (f v) adj_sub h := h.1 edge_vert h := Set.mem_preimage.1 (H.edge_vert h.2) symm _ _ h := ⟨G.symm h.1, H.symm h.2⟩ theorem comap_monotone {G' : SimpleGraph W} (f : G →g G') : Monotone (Subgraph.comap f) := by intro H H' h constructor · intro simp only [comap_verts, Set.mem_preimage] apply h.1 · intro v w simp (config := { contextual := true }) only [comap_adj, and_imp, true_and_iff] intro apply h.2 theorem map_le_iff_le_comap {G' : SimpleGraph W} (f : G →g G') (H : G.Subgraph) (H' : G'.Subgraph) : H.map f ≤ H' ↔ H ≤ H'.comap f := by refine ⟨fun h ↦ ⟨fun v hv ↦ ?_, fun v w hvw ↦ ?_⟩, fun h ↦ ⟨fun v ↦ ?_, fun v w ↦ ?_⟩⟩ · simp only [comap_verts, Set.mem_preimage] exact h.1 ⟨v, hv, rfl⟩ · simp only [H.adj_sub hvw, comap_adj, true_and_iff] exact h.2 ⟨v, w, hvw, rfl, rfl⟩ · simp only [map_verts, Set.mem_image, forall_exists_index, and_imp] rintro w hw rfl exact h.1 hw · simp only [Relation.Map, map_adj, forall_exists_index, and_imp] rintro u u' hu rfl rfl exact (h.2 hu).2 /-- Given two subgraphs, one a subgraph of the other, there is an induced injective homomorphism of the subgraphs as graphs. -/ @[simps] def inclusion {x y : Subgraph G} (h : x ≤ y) : x.coe →g y.coe where toFun v := ⟨↑v, And.left h v.property⟩ map_rel' hvw := h.2 hvw theorem inclusion.injective {x y : Subgraph G} (h : x ≤ y) : Function.Injective (inclusion h) := by intro v w h rw [inclusion, DFunLike.coe, Subtype.mk_eq_mk] at h exact Subtype.ext h /-- There is an induced injective homomorphism of a subgraph of `G` into `G`. -/ @[simps] protected def hom (x : Subgraph G) : x.coe →g G where toFun v := v map_rel' := x.adj_sub @[simp] lemma coe_hom (x : Subgraph G) : (x.hom : x.verts → V) = (fun (v : x.verts) => (v : V)) := rfl theorem hom.injective {x : Subgraph G} : Function.Injective x.hom := fun _ _ ↦ Subtype.ext /-- There is an induced injective homomorphism of a subgraph of `G` as a spanning subgraph into `G`. -/ @[simps] def spanningHom (x : Subgraph G) : x.spanningCoe →g G where toFun := id map_rel' := x.adj_sub theorem spanningHom.injective {x : Subgraph G} : Function.Injective x.spanningHom := fun _ _ ↦ id theorem neighborSet_subset_of_subgraph {x y : Subgraph G} (h : x ≤ y) (v : V) : x.neighborSet v ⊆ y.neighborSet v := fun _ h' ↦ h.2 h' instance neighborSet.decidablePred (G' : Subgraph G) [h : DecidableRel G'.Adj] (v : V) : DecidablePred (· ∈ G'.neighborSet v) := h v /-- If a graph is locally finite at a vertex, then so is a subgraph of that graph. -/ instance finiteAt {G' : Subgraph G} (v : G'.verts) [DecidableRel G'.Adj] [Fintype (G.neighborSet v)] : Fintype (G'.neighborSet v) := Set.fintypeSubset (G.neighborSet v) (G'.neighborSet_subset v) /-- If a subgraph is locally finite at a vertex, then so are subgraphs of that subgraph. This is not an instance because `G''` cannot be inferred. -/ def finiteAtOfSubgraph {G' G'' : Subgraph G} [DecidableRel G'.Adj] (h : G' ≤ G'') (v : G'.verts) [Fintype (G''.neighborSet v)] : Fintype (G'.neighborSet v) := Set.fintypeSubset (G''.neighborSet v) (neighborSet_subset_of_subgraph h v) instance (G' : Subgraph G) [Fintype G'.verts] (v : V) [DecidablePred (· ∈ G'.neighborSet v)] : Fintype (G'.neighborSet v) := Set.fintypeSubset G'.verts (neighborSet_subset_verts G' v) instance coeFiniteAt {G' : Subgraph G} (v : G'.verts) [Fintype (G'.neighborSet v)] : Fintype (G'.coe.neighborSet v) := Fintype.ofEquiv _ (coeNeighborSetEquiv v).symm theorem IsSpanning.card_verts [Fintype V] {G' : Subgraph G} [Fintype G'.verts] (h : G'.IsSpanning) : G'.verts.toFinset.card = Fintype.card V := by simp only [isSpanning_iff.1 h, Set.toFinset_univ] congr /-- The degree of a vertex in a subgraph. It's zero for vertices outside the subgraph. -/ def degree (G' : Subgraph G) (v : V) [Fintype (G'.neighborSet v)] : ℕ := Fintype.card (G'.neighborSet v) theorem finset_card_neighborSet_eq_degree {G' : Subgraph G} {v : V} [Fintype (G'.neighborSet v)] : (G'.neighborSet v).toFinset.card = G'.degree v := by rw [degree, Set.toFinset_card] theorem degree_le (G' : Subgraph G) (v : V) [Fintype (G'.neighborSet v)] [Fintype (G.neighborSet v)] : G'.degree v ≤ G.degree v := by rw [← card_neighborSet_eq_degree] exact Set.card_le_card (G'.neighborSet_subset v) theorem degree_le' (G' G'' : Subgraph G) (h : G' ≤ G'') (v : V) [Fintype (G'.neighborSet v)] [Fintype (G''.neighborSet v)] : G'.degree v ≤ G''.degree v := Set.card_le_card (neighborSet_subset_of_subgraph h v) @[simp] theorem coe_degree (G' : Subgraph G) (v : G'.verts) [Fintype (G'.coe.neighborSet v)] [Fintype (G'.neighborSet v)] : G'.coe.degree v = G'.degree v := by rw [← card_neighborSet_eq_degree] exact Fintype.card_congr (coeNeighborSetEquiv v) @[simp] theorem degree_spanningCoe {G' : G.Subgraph} (v : V) [Fintype (G'.neighborSet v)] [Fintype (G'.spanningCoe.neighborSet v)] : G'.spanningCoe.degree v = G'.degree v := by rw [← card_neighborSet_eq_degree, Subgraph.degree] congr! theorem degree_eq_one_iff_unique_adj {G' : Subgraph G} {v : V} [Fintype (G'.neighborSet v)] : G'.degree v = 1 ↔ ∃! w : V, G'.Adj v w := by rw [← finset_card_neighborSet_eq_degree, Finset.card_eq_one, Finset.singleton_iff_unique_mem] simp only [Set.mem_toFinset, mem_neighborSet] end Subgraph section MkProperties /-! ### Properties of `singletonSubgraph` and `subgraphOfAdj` -/ variable {G : SimpleGraph V} {G' : SimpleGraph W} instance nonempty_singletonSubgraph_verts (v : V) : Nonempty (G.singletonSubgraph v).verts := ⟨⟨v, Set.mem_singleton v⟩⟩ @[simp] theorem singletonSubgraph_le_iff (v : V) (H : G.Subgraph) : G.singletonSubgraph v ≤ H ↔ v ∈ H.verts := by refine ⟨fun h ↦ h.1 (Set.mem_singleton v), ?_⟩ intro h constructor · rwa [singletonSubgraph_verts, Set.singleton_subset_iff] · exact fun _ _ ↦ False.elim @[simp] theorem map_singletonSubgraph (f : G →g G') {v : V} : Subgraph.map f (G.singletonSubgraph v) = G'.singletonSubgraph (f v) := by ext <;> simp only [Relation.Map, Subgraph.map_adj, singletonSubgraph_adj, Pi.bot_apply, exists_and_left, and_iff_left_iff_imp, IsEmpty.forall_iff, Subgraph.map_verts, singletonSubgraph_verts, Set.image_singleton] exact False.elim @[simp] theorem neighborSet_singletonSubgraph (v w : V) : (G.singletonSubgraph v).neighborSet w = ∅ := rfl @[simp] theorem edgeSet_singletonSubgraph (v : V) : (G.singletonSubgraph v).edgeSet = ∅ := Sym2.fromRel_bot theorem eq_singletonSubgraph_iff_verts_eq (H : G.Subgraph) {v : V} : H = G.singletonSubgraph v ↔ H.verts = {v} := by refine ⟨fun h ↦ by rw [h, singletonSubgraph_verts], fun h ↦ ?_⟩ ext · rw [h, singletonSubgraph_verts] · simp only [Prop.bot_eq_false, singletonSubgraph_adj, Pi.bot_apply, iff_false_iff] intro ha have ha1 := ha.fst_mem have ha2 := ha.snd_mem rw [h, Set.mem_singleton_iff] at ha1 ha2 subst_vars exact ha.ne rfl instance nonempty_subgraphOfAdj_verts {v w : V} (hvw : G.Adj v w) : Nonempty (G.subgraphOfAdj hvw).verts := ⟨⟨v, by simp⟩⟩ @[simp] theorem edgeSet_subgraphOfAdj {v w : V} (hvw : G.Adj v w) : (G.subgraphOfAdj hvw).edgeSet = {s(v, w)} := by ext e refine e.ind ?_ simp only [eq_comm, Set.mem_singleton_iff, Subgraph.mem_edgeSet, subgraphOfAdj_adj, iff_self_iff, forall₂_true_iff] lemma subgraphOfAdj_le_of_adj {v w : V} (H : G.Subgraph) (h : H.Adj v w) : G.subgraphOfAdj (H.adj_sub h) ≤ H := by constructor · intro x rintro (rfl | rfl) <;> simp [H.edge_vert h, H.edge_vert h.symm] · simp only [subgraphOfAdj_adj, Sym2.eq, Sym2.rel_iff] rintro _ _ (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩) <;> simp [h, h.symm] theorem subgraphOfAdj_symm {v w : V} (hvw : G.Adj v w) : G.subgraphOfAdj hvw.symm = G.subgraphOfAdj hvw := by ext <;> simp [or_comm, and_comm] @[simp] theorem map_subgraphOfAdj (f : G →g G') {v w : V} (hvw : G.Adj v w) : Subgraph.map f (G.subgraphOfAdj hvw) = G'.subgraphOfAdj (f.map_adj hvw) := by ext · simp only [Subgraph.map_verts, subgraphOfAdj_verts, Set.mem_image, Set.mem_insert_iff, Set.mem_singleton_iff] constructor · rintro ⟨u, rfl | rfl, rfl⟩ <;> simp · rintro (rfl | rfl) · use v simp · use w simp · simp only [Relation.Map, Subgraph.map_adj, subgraphOfAdj_adj, Sym2.eq, Sym2.rel_iff] constructor · rintro ⟨a, b, ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, rfl, rfl⟩ <;> simp · rintro (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩) · use v, w simp · use w, v simp theorem neighborSet_subgraphOfAdj_subset {u v w : V} (hvw : G.Adj v w) : (G.subgraphOfAdj hvw).neighborSet u ⊆ {v, w} := (G.subgraphOfAdj hvw).neighborSet_subset_verts _ @[simp] theorem neighborSet_fst_subgraphOfAdj {v w : V} (hvw : G.Adj v w) : (G.subgraphOfAdj hvw).neighborSet v = {w} := by ext u suffices w = u ↔ u = w by simpa [hvw.ne.symm] using this rw [eq_comm] @[simp] theorem neighborSet_snd_subgraphOfAdj {v w : V} (hvw : G.Adj v w) : (G.subgraphOfAdj hvw).neighborSet w = {v} := by rw [subgraphOfAdj_symm hvw.symm] exact neighborSet_fst_subgraphOfAdj hvw.symm @[simp] theorem neighborSet_subgraphOfAdj_of_ne_of_ne {u v w : V} (hvw : G.Adj v w) (hv : u ≠ v) (hw : u ≠ w) : (G.subgraphOfAdj hvw).neighborSet u = ∅ := by ext simp [hv.symm, hw.symm] theorem neighborSet_subgraphOfAdj [DecidableEq V] {u v w : V} (hvw : G.Adj v w) : (G.subgraphOfAdj hvw).neighborSet u = (if u = v then {w} else ∅) ∪ if u = w then {v} else ∅ := by split_ifs <;> subst_vars <;> simp [*] theorem singletonSubgraph_fst_le_subgraphOfAdj {u v : V} {h : G.Adj u v} : G.singletonSubgraph u ≤ G.subgraphOfAdj h := by simp theorem singletonSubgraph_snd_le_subgraphOfAdj {u v : V} {h : G.Adj u v} : G.singletonSubgraph v ≤ G.subgraphOfAdj h := by simp @[simp] lemma support_subgraphOfAdj {u v : V} (h : G.Adj u v) : (G.subgraphOfAdj h).support = {u , v} := by ext rw [Subgraph.mem_support] simp only [subgraphOfAdj_adj, Sym2.eq, Sym2.rel_iff', Prod.mk.injEq, Prod.swap_prod_mk] refine ⟨?_, fun h ↦ h.elim (fun hl ↦ ⟨v, .inl ⟨hl.symm, rfl⟩⟩) fun hr ↦ ⟨u, .inr ⟨rfl, hr.symm⟩⟩⟩ rintro ⟨_, hw⟩ exact hw.elim (fun h1 ↦ .inl h1.1.symm) fun hr ↦ .inr hr.2.symm end MkProperties namespace Subgraph variable {G : SimpleGraph V} /-! ### Subgraphs of subgraphs -/ /-- Given a subgraph of a subgraph of `G`, construct a subgraph of `G`. -/ protected abbrev coeSubgraph {G' : G.Subgraph} : G'.coe.Subgraph → G.Subgraph := Subgraph.map G'.hom /-- Given a subgraph of `G`, restrict it to being a subgraph of another subgraph `G'` by taking the portion of `G` that intersects `G'`. -/ protected abbrev restrict {G' : G.Subgraph} : G.Subgraph → G'.coe.Subgraph := Subgraph.comap G'.hom @[simp] lemma verts_coeSubgraph {G' : Subgraph G} (G'' : Subgraph G'.coe) : G''.coeSubgraph.verts = (G''.verts : Set V) := rfl lemma coeSubgraph_adj {G' : G.Subgraph} (G'' : G'.coe.Subgraph) (v w : V) : (G'.coeSubgraph G'').Adj v w ↔ ∃ (hv : v ∈ G'.verts) (hw : w ∈ G'.verts), G''.Adj ⟨v, hv⟩ ⟨w, hw⟩ := by simp [Relation.Map] lemma restrict_adj {G' G'' : G.Subgraph} (v w : G'.verts) : (G'.restrict G'').Adj v w ↔ G'.Adj v w ∧ G''.Adj v w := Iff.rfl theorem restrict_coeSubgraph {G' : G.Subgraph} (G'' : G'.coe.Subgraph) : Subgraph.restrict (Subgraph.coeSubgraph G'') = G'' := by ext · simp · rw [restrict_adj, coeSubgraph_adj] simpa using G''.adj_sub theorem coeSubgraph_injective (G' : G.Subgraph) : Function.Injective (Subgraph.coeSubgraph : G'.coe.Subgraph → G.Subgraph) := Function.LeftInverse.injective restrict_coeSubgraph lemma coeSubgraph_le {H : G.Subgraph} (H' : H.coe.Subgraph) : Subgraph.coeSubgraph H' ≤ H := by constructor · simp · rintro v w ⟨_, _, h, rfl, rfl⟩ exact H'.adj_sub h lemma coeSubgraph_restrict_eq {H : G.Subgraph} (H' : G.Subgraph) : Subgraph.coeSubgraph (H.restrict H') = H ⊓ H' := by ext · simp [and_comm] · simp_rw [coeSubgraph_adj, restrict_adj] simp only [exists_and_left, exists_prop, inf_adj, and_congr_right_iff] intro h simp [H.edge_vert h, H.edge_vert h.symm] /-! ### Edge deletion -/ /-- Given a subgraph `G'` and a set of vertex pairs, remove all of the corresponding edges from its edge set, if present. See also: `SimpleGraph.deleteEdges`. -/ def deleteEdges (G' : G.Subgraph) (s : Set (Sym2 V)) : G.Subgraph where verts := G'.verts Adj := G'.Adj \ Sym2.ToRel s adj_sub h' := G'.adj_sub h'.1 edge_vert h' := G'.edge_vert h'.1 symm a b := by simp [G'.adj_comm, Sym2.eq_swap] section DeleteEdges variable {G' : G.Subgraph} (s : Set (Sym2 V)) @[simp] theorem deleteEdges_verts : (G'.deleteEdges s).verts = G'.verts := rfl @[simp] theorem deleteEdges_adj (v w : V) : (G'.deleteEdges s).Adj v w ↔ G'.Adj v w ∧ ¬s(v, w) ∈ s := Iff.rfl @[simp] theorem deleteEdges_deleteEdges (s s' : Set (Sym2 V)) : (G'.deleteEdges s).deleteEdges s' = G'.deleteEdges (s ∪ s') := by ext <;> simp [and_assoc, not_or] @[simp] theorem deleteEdges_empty_eq : G'.deleteEdges ∅ = G' := by ext <;> simp @[simp] theorem deleteEdges_spanningCoe_eq : G'.spanningCoe.deleteEdges s = (G'.deleteEdges s).spanningCoe := by ext simp theorem deleteEdges_coe_eq (s : Set (Sym2 G'.verts)) : G'.coe.deleteEdges s = (G'.deleteEdges (Sym2.map (↑) '' s)).coe := by ext ⟨v, hv⟩ ⟨w, hw⟩ simp only [SimpleGraph.deleteEdges_adj, coe_adj, deleteEdges_adj, Set.mem_image, not_exists, not_and, and_congr_right_iff] intro constructor · intro hs refine Sym2.ind ?_ rintro ⟨v', hv'⟩ ⟨w', hw'⟩ simp only [Sym2.map_pair_eq, Sym2.eq] contrapose! rintro (_ | _) <;> simpa only [Sym2.eq_swap] · intro h' hs exact h' _ hs rfl theorem coe_deleteEdges_eq (s : Set (Sym2 V)) : (G'.deleteEdges s).coe = G'.coe.deleteEdges (Sym2.map (↑) ⁻¹' s) := by ext ⟨v, hv⟩ ⟨w, hw⟩ simp theorem deleteEdges_le : G'.deleteEdges s ≤ G' := by constructor <;> simp (config := { contextual := true }) [subset_rfl] theorem deleteEdges_le_of_le {s s' : Set (Sym2 V)} (h : s ⊆ s') : G'.deleteEdges s' ≤ G'.deleteEdges s := by constructor <;> simp (config := { contextual := true }) only [deleteEdges_verts, deleteEdges_adj, true_and_iff, and_imp, subset_rfl] exact fun _ _ _ hs' hs ↦ hs' (h hs) @[simp] theorem deleteEdges_inter_edgeSet_left_eq : G'.deleteEdges (G'.edgeSet ∩ s) = G'.deleteEdges s := by ext <;> simp (config := { contextual := true }) [imp_false] @[simp] theorem deleteEdges_inter_edgeSet_right_eq : G'.deleteEdges (s ∩ G'.edgeSet) = G'.deleteEdges s := by ext <;> simp (config := { contextual := true }) [imp_false] theorem coe_deleteEdges_le : (G'.deleteEdges s).coe ≤ (G'.coe : SimpleGraph G'.verts) := by intro v w simp (config := { contextual := true }) theorem spanningCoe_deleteEdges_le (G' : G.Subgraph) (s : Set (Sym2 V)) : (G'.deleteEdges s).spanningCoe ≤ G'.spanningCoe := spanningCoe_le_of_le (deleteEdges_le s) end DeleteEdges /-! ### Induced subgraphs -/ /- Given a subgraph, we can change its vertex set while removing any invalid edges, which gives induced subgraphs. See also `SimpleGraph.induce` for the `SimpleGraph` version, which, unlike for subgraphs, results in a graph with a different vertex type. -/ /-- The induced subgraph of a subgraph. The expectation is that `s ⊆ G'.verts` for the usual notion of an induced subgraph, but, in general, `s` is taken to be the new vertex set and edges are induced from the subgraph `G'`. -/ @[simps] def induce (G' : G.Subgraph) (s : Set V) : G.Subgraph where verts := s Adj u v := u ∈ s ∧ v ∈ s ∧ G'.Adj u v adj_sub h := G'.adj_sub h.2.2 edge_vert h := h.1 symm _ _ h := ⟨h.2.1, h.1, G'.symm h.2.2⟩ theorem _root_.SimpleGraph.induce_eq_coe_induce_top (s : Set V) : G.induce s = ((⊤ : G.Subgraph).induce s).coe := by ext simp section Induce variable {G' G'' : G.Subgraph} {s s' : Set V} theorem induce_mono (hg : G' ≤ G'') (hs : s ⊆ s') : G'.induce s ≤ G''.induce s' := by constructor · simp [hs] · simp (config := { contextual := true }) only [induce_adj, true_and_iff, and_imp] intro v w hv hw ha exact ⟨hs hv, hs hw, hg.2 ha⟩ @[mono] theorem induce_mono_left (hg : G' ≤ G'') : G'.induce s ≤ G''.induce s := induce_mono hg subset_rfl @[mono] theorem induce_mono_right (hs : s ⊆ s') : G'.induce s ≤ G'.induce s' := induce_mono le_rfl hs @[simp] theorem induce_empty : G'.induce ∅ = ⊥ := by ext <;> simp @[simp] theorem induce_self_verts : G'.induce G'.verts = G' := by ext · simp · constructor <;> simp (config := { contextual := true }) only [induce_adj, imp_true_iff, and_true_iff] exact fun ha ↦ ⟨G'.edge_vert ha, G'.edge_vert ha.symm⟩ lemma le_induce_top_verts : G' ≤ (⊤ : G.Subgraph).induce G'.verts := calc G' = G'.induce G'.verts := Subgraph.induce_self_verts.symm _ ≤ (⊤ : G.Subgraph).induce G'.verts := Subgraph.induce_mono_left le_top lemma le_induce_union : G'.induce s ⊔ G'.induce s' ≤ G'.induce (s ∪ s') := by constructor · simp only [verts_sup, induce_verts, Set.Subset.rfl] · simp only [sup_adj, induce_adj, Set.mem_union] rintro v w (h | h) <;> simp [h] lemma le_induce_union_left : G'.induce s ≤ G'.induce (s ∪ s') := by exact (sup_le_iff.mp le_induce_union).1 lemma le_induce_union_right : G'.induce s' ≤ G'.induce (s ∪ s') := by exact (sup_le_iff.mp le_induce_union).2 theorem singletonSubgraph_eq_induce {v : V} : G.singletonSubgraph v = (⊤ : G.Subgraph).induce {v} := by ext <;> simp (config := { contextual := true }) [-Set.bot_eq_empty, Prop.bot_eq_false] theorem subgraphOfAdj_eq_induce {v w : V} (hvw : G.Adj v w) : G.subgraphOfAdj hvw = (⊤ : G.Subgraph).induce {v, w} := by ext · simp · constructor · intro h simp only [subgraphOfAdj_adj, Sym2.eq, Sym2.rel_iff] at h obtain ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩ := h <;> simp [hvw, hvw.symm] · intro h simp only [induce_adj, Set.mem_insert_iff, Set.mem_singleton_iff, top_adj] at h obtain ⟨rfl | rfl, rfl | rfl, ha⟩ := h <;> first |exact (ha.ne rfl).elim|simp end Induce /-- Given a subgraph and a set of vertices, delete all the vertices from the subgraph, if present. Any edges incident to the deleted vertices are deleted as well. -/ abbrev deleteVerts (G' : G.Subgraph) (s : Set V) : G.Subgraph := G'.induce (G'.verts \ s) section DeleteVerts variable {G' : G.Subgraph} {s : Set V} theorem deleteVerts_verts : (G'.deleteVerts s).verts = G'.verts \ s := rfl theorem deleteVerts_adj {u v : V} : (G'.deleteVerts s).Adj u v ↔ u ∈ G'.verts ∧ ¬u ∈ s ∧ v ∈ G'.verts ∧ ¬v ∈ s ∧ G'.Adj u v := by simp [and_assoc] @[simp] theorem deleteVerts_deleteVerts (s s' : Set V) : (G'.deleteVerts s).deleteVerts s' = G'.deleteVerts (s ∪ s') := by ext <;> simp (config := { contextual := true }) [not_or, and_assoc] @[simp] theorem deleteVerts_empty : G'.deleteVerts ∅ = G' := by simp [deleteVerts] theorem deleteVerts_le : G'.deleteVerts s ≤ G' := by constructor <;> simp [Set.diff_subset] @[mono] theorem deleteVerts_mono {G' G'' : G.Subgraph} (h : G' ≤ G'') : G'.deleteVerts s ≤ G''.deleteVerts s := induce_mono h (Set.diff_subset_diff_left h.1) @[mono] theorem deleteVerts_anti {s s' : Set V} (h : s ⊆ s') : G'.deleteVerts s' ≤ G'.deleteVerts s := induce_mono (le_refl _) (Set.diff_subset_diff_right h) @[simp] theorem deleteVerts_inter_verts_left_eq : G'.deleteVerts (G'.verts ∩ s) = G'.deleteVerts s := by ext <;> simp (config := { contextual := true }) [imp_false] @[simp] theorem deleteVerts_inter_verts_set_right_eq : G'.deleteVerts (s ∩ G'.verts) = G'.deleteVerts s := by ext <;> simp (config := { contextual := true }) [imp_false] end DeleteVerts end Subgraph end SimpleGraph
Combinatorics\SimpleGraph\Trails.lean
/- Copyright (c) 2022 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import Mathlib.Algebra.Ring.Parity import Mathlib.Combinatorics.SimpleGraph.Path /-! # Trails and Eulerian trails This module contains additional theory about trails, including Eulerian trails (also known as Eulerian circuits). ## Main definitions * `SimpleGraph.Walk.IsEulerian` is the predicate that a trail is an Eulerian trail. * `SimpleGraph.Walk.IsTrail.even_countP_edges_iff` gives a condition on the number of edges in a trail that can be incident to a given vertex. * `SimpleGraph.Walk.IsEulerian.even_degree_iff` gives a condition on the degrees of vertices when there exists an Eulerian trail. * `SimpleGraph.Walk.IsEulerian.card_odd_degree` gives the possible numbers of odd-degree vertices when there exists an Eulerian trail. ## TODO * Prove that there exists an Eulerian trail when the conclusion to `SimpleGraph.Walk.IsEulerian.card_odd_degree` holds. ## Tags Eulerian trails -/ namespace SimpleGraph variable {V : Type*} {G : SimpleGraph V} namespace Walk /-- The edges of a trail as a finset, since each edge in a trail appears exactly once. -/ abbrev IsTrail.edgesFinset {u v : V} {p : G.Walk u v} (h : p.IsTrail) : Finset (Sym2 V) := ⟨p.edges, h.edges_nodup⟩ variable [DecidableEq V] theorem IsTrail.even_countP_edges_iff {u v : V} {p : G.Walk u v} (ht : p.IsTrail) (x : V) : Even (p.edges.countP fun e => x ∈ e) ↔ u ≠ v → x ≠ u ∧ x ≠ v := by induction' p with u u v w huv p ih · simp · rw [cons_isTrail_iff] at ht specialize ih ht.1 simp only [List.countP_cons, Ne, edges_cons, Sym2.mem_iff] split_ifs with h · rw [decide_eq_true_eq] at h obtain (rfl | rfl) := h · rw [Nat.even_add_one, ih] simp only [huv.ne, imp_false, Ne, not_false_iff, true_and_iff, not_forall, Classical.not_not, exists_prop, eq_self_iff_true, not_true, false_and_iff, and_iff_right_iff_imp] rintro rfl rfl exact G.loopless _ huv · rw [Nat.even_add_one, ih, ← not_iff_not] simp only [huv.ne.symm, Ne, eq_self_iff_true, not_true, false_and_iff, not_forall, not_false_iff, exists_prop, and_true_iff, Classical.not_not, true_and_iff, iff_and_self] rintro rfl exact huv.ne · rw [decide_eq_true_eq, not_or] at h simp only [h.1, h.2, not_false_iff, true_and_iff, add_zero, Ne] at ih ⊢ rw [ih] constructor <;> · rintro h' h'' rfl simp only [imp_false, eq_self_iff_true, not_true, Classical.not_not] at h' cases h' simp only [not_true, and_false, false_and] at h /-- An *Eulerian trail* (also known as an "Eulerian path") is a walk `p` that visits every edge exactly once. The lemma `SimpleGraph.Walk.IsEulerian.IsTrail` shows that these are trails. Combine with `p.IsCircuit` to get an Eulerian circuit (also known as an "Eulerian cycle"). -/ def IsEulerian {u v : V} (p : G.Walk u v) : Prop := ∀ e, e ∈ G.edgeSet → p.edges.count e = 1 theorem IsEulerian.isTrail {u v : V} {p : G.Walk u v} (h : p.IsEulerian) : p.IsTrail := by rw [isTrail_def, List.nodup_iff_count_le_one] intro e by_cases he : e ∈ p.edges · exact (h e (edges_subset_edgeSet _ he)).le · simp [List.count_eq_zero_of_not_mem he] theorem IsEulerian.mem_edges_iff {u v : V} {p : G.Walk u v} (h : p.IsEulerian) {e : Sym2 V} : e ∈ p.edges ↔ e ∈ G.edgeSet := ⟨ fun h => p.edges_subset_edgeSet h , fun he => by simpa [Nat.succ_le] using (h e he).ge ⟩ /-- The edge set of an Eulerian graph is finite. -/ def IsEulerian.fintypeEdgeSet {u v : V} {p : G.Walk u v} (h : p.IsEulerian) : Fintype G.edgeSet := Fintype.ofFinset h.isTrail.edgesFinset fun e => by simp only [Finset.mem_mk, Multiset.mem_coe, h.mem_edges_iff] theorem IsTrail.isEulerian_of_forall_mem {u v : V} {p : G.Walk u v} (h : p.IsTrail) (hc : ∀ e, e ∈ G.edgeSet → e ∈ p.edges) : p.IsEulerian := fun e he => List.count_eq_one_of_mem h.edges_nodup (hc e he) theorem isEulerian_iff {u v : V} (p : G.Walk u v) : p.IsEulerian ↔ p.IsTrail ∧ ∀ e, e ∈ G.edgeSet → e ∈ p.edges := by constructor · intro h exact ⟨h.isTrail, fun _ => h.mem_edges_iff.mpr⟩ · rintro ⟨h, hl⟩ exact h.isEulerian_of_forall_mem hl theorem IsEulerian.edgesFinset_eq [Fintype G.edgeSet] {u v : V} {p : G.Walk u v} (h : p.IsEulerian) : h.isTrail.edgesFinset = G.edgeFinset := by ext e simp [h.mem_edges_iff] theorem IsEulerian.even_degree_iff {x u v : V} {p : G.Walk u v} (ht : p.IsEulerian) [Fintype V] [DecidableRel G.Adj] : Even (G.degree x) ↔ u ≠ v → x ≠ u ∧ x ≠ v := by convert ht.isTrail.even_countP_edges_iff x rw [← Multiset.coe_countP, Multiset.countP_eq_card_filter, ← card_incidenceFinset_eq_degree] change Multiset.card _ = _ congr 1 convert_to _ = (ht.isTrail.edgesFinset.filter (Membership.mem x)).val have : Fintype G.edgeSet := fintypeEdgeSet ht rw [ht.edgesFinset_eq, G.incidenceFinset_eq_filter x] theorem IsEulerian.card_filter_odd_degree [Fintype V] [DecidableRel G.Adj] {u v : V} {p : G.Walk u v} (ht : p.IsEulerian) {s} (h : s = (Finset.univ : Finset V).filter fun v => Odd (G.degree v)) : s.card = 0 ∨ s.card = 2 := by subst s simp only [Nat.odd_iff_not_even, Finset.card_eq_zero] simp only [ht.even_degree_iff, Ne, not_forall, not_and, Classical.not_not, exists_prop] obtain rfl | hn := eq_or_ne u v · left simp · right convert_to _ = ({u, v} : Finset V).card · simp [hn] · congr ext x simp [hn, imp_iff_not_or] theorem IsEulerian.card_odd_degree [Fintype V] [DecidableRel G.Adj] {u v : V} {p : G.Walk u v} (ht : p.IsEulerian) : Fintype.card { v : V | Odd (G.degree v) } = 0 ∨ Fintype.card { v : V | Odd (G.degree v) } = 2 := by rw [← Set.toFinset_card] apply IsEulerian.card_filter_odd_degree ht ext v simp end Walk end SimpleGraph
Combinatorics\SimpleGraph\Turan.lean
/- Copyright (c) 2024 Jeremy Tan. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Tan -/ import Mathlib.Combinatorics.SimpleGraph.Clique import Mathlib.Order.Partition.Equipartition /-! # Turán's theorem In this file we prove Turán's theorem, the first important result of extremal graph theory, which states that the `r + 1`-cliquefree graph on `n` vertices with the most edges is the complete `r`-partite graph with part sizes as equal as possible (`turanGraph n r`). The forward direction of the proof performs "Zykov symmetrisation", which first shows constructively that non-adjacency is an equivalence relation in a maximal graph, so it must be complete multipartite with the parts being the equivalence classes. Then basic manipulations show that the graph is isomorphic to the Turán graph for the given parameters. For the reverse direction we first show that a Turán-maximal graph exists, then transfer the property through `turanGraph n r` using the isomorphism provided by the forward direction. ## Main declarations * `SimpleGraph.IsTuranMaximal`: `G.IsTuranMaximal r` means that `G` has the most number of edges for its number of vertices while still being `r + 1`-cliquefree. * `SimpleGraph.turanGraph n r`: The canonical `r + 1`-cliquefree Turán graph on `n` vertices. * `SimpleGraph.IsTuranMaximal.finpartition`: The result of Zykov symmetrisation, a finpartition of the vertices such that two vertices are in the same part iff they are non-adjacent. * `SimpleGraph.IsTuranMaximal.nonempty_iso_turanGraph`: The forward direction, an isomorphism between `G` satisfying `G.IsTuranMaximal r` and `turanGraph n r`. * `isTuranMaximal_of_iso`: the reverse direction, `G.IsTuranMaximal r` given the isomorphism. * `isTuranMaximal_iff_nonempty_iso_turanGraph`: Turán's theorem in full. ## References * https://en.wikipedia.org/wiki/Turán%27s_theorem -/ open Finset namespace SimpleGraph variable {V : Type*} [Fintype V] {G : SimpleGraph V} [DecidableRel G.Adj] {n r : ℕ} variable (G) in /-- An `r + 1`-cliquefree graph is `r`-Turán-maximal if any other `r + 1`-cliquefree graph on the same vertex set has the same or fewer number of edges. -/ def IsTuranMaximal (r : ℕ) : Prop := G.CliqueFree (r + 1) ∧ ∀ (H : SimpleGraph V) [DecidableRel H.Adj], H.CliqueFree (r + 1) → H.edgeFinset.card ≤ G.edgeFinset.card section Defs variable {H : SimpleGraph V} lemma IsTuranMaximal.le_iff_eq (hG : G.IsTuranMaximal r) (hH : H.CliqueFree (r + 1)) : G ≤ H ↔ G = H := by classical exact ⟨fun hGH ↦ edgeFinset_inj.1 <| eq_of_subset_of_card_le (edgeFinset_subset_edgeFinset.2 hGH) (hG.2 _ hH), le_of_eq⟩ /-- The canonical `r + 1`-cliquefree Turán graph on `n` vertices. -/ def turanGraph (n r : ℕ) : SimpleGraph (Fin n) where Adj v w := v % r ≠ w % r instance turanGraph.instDecidableRelAdj : DecidableRel (turanGraph n r).Adj := by dsimp only [turanGraph]; infer_instance @[simp] lemma turanGraph_zero : turanGraph n 0 = ⊤ := by ext a b; simp_rw [turanGraph, top_adj, Nat.mod_zero, not_iff_not, Fin.val_inj] @[simp] theorem turanGraph_eq_top : turanGraph n r = ⊤ ↔ r = 0 ∨ n ≤ r := by simp_rw [SimpleGraph.ext_iff, Function.funext_iff, turanGraph, top_adj, eq_iff_iff, not_iff_not] refine ⟨fun h ↦ ?_, ?_⟩ · contrapose! h use ⟨0, (Nat.pos_of_ne_zero h.1).trans h.2⟩, ⟨r, h.2⟩ simp [h.1.symm] · rintro (rfl | h) a b · simp [Fin.val_inj] · rw [Nat.mod_eq_of_lt (a.2.trans_le h), Nat.mod_eq_of_lt (b.2.trans_le h), Fin.val_inj] variable (hr : 0 < r) theorem turanGraph_cliqueFree : (turanGraph n r).CliqueFree (r + 1) := by rw [cliqueFree_iff] by_contra h rw [not_isEmpty_iff] at h obtain ⟨f, ha⟩ := h simp only [turanGraph, top_adj] at ha obtain ⟨x, y, d, c⟩ := Fintype.exists_ne_map_eq_of_card_lt (fun x ↦ (⟨(f x).1 % r, Nat.mod_lt _ hr⟩ : Fin r)) (by simp) simp only [Fin.mk.injEq] at c exact absurd c ((@ha x y).mpr d) /-- An `r + 1`-cliquefree Turán-maximal graph is _not_ `r`-cliquefree if it can accommodate such a clique. -/ theorem not_cliqueFree_of_isTuranMaximal (hn : r ≤ Fintype.card V) (hG : G.IsTuranMaximal r) : ¬G.CliqueFree r := by rintro h obtain ⟨K, _, rfl⟩ := exists_subset_card_eq hn obtain ⟨a, -, b, -, hab, hGab⟩ : ∃ a ∈ K, ∃ b ∈ K, a ≠ b ∧ ¬ G.Adj a b := by simpa only [isNClique_iff, IsClique, Set.Pairwise, mem_coe, ne_eq, and_true, not_forall, exists_prop, exists_and_right] using h K exact hGab <| le_sup_right.trans_eq ((hG.le_iff_eq <| h.sup_edge _ _).1 le_sup_left).symm <| (edge_adj ..).2 ⟨Or.inl ⟨rfl, rfl⟩, hab⟩ lemma exists_isTuranMaximal : ∃ H : SimpleGraph V, ∃ _ : DecidableRel H.Adj, H.IsTuranMaximal r := by classical let c := {H : SimpleGraph V | H.CliqueFree (r + 1)} have cn : c.toFinset.Nonempty := ⟨⊥, by simp only [Set.toFinset_setOf, mem_filter, mem_univ, true_and, c] exact cliqueFree_bot (by omega)⟩ obtain ⟨S, Sm, Sl⟩ := exists_max_image c.toFinset (·.edgeFinset.card) cn use S, inferInstance rw [Set.mem_toFinset] at Sm refine ⟨Sm, fun I _ cf ↦ ?_⟩ by_cases Im : I ∈ c.toFinset · convert Sl I Im · rw [Set.mem_toFinset] at Im contradiction end Defs namespace IsTuranMaximal variable {s t u : V} /-- In a Turán-maximal graph, non-adjacent vertices have the same degree. -/ lemma degree_eq_of_not_adj (h : G.IsTuranMaximal r) (hn : ¬G.Adj s t) : G.degree s = G.degree t := by rw [IsTuranMaximal] at h; contrapose! h; intro cf wlog hd : G.degree t < G.degree s generalizing G t s · replace hd : G.degree s < G.degree t := lt_of_le_of_ne (le_of_not_lt hd) h exact this (by rwa [adj_comm] at hn) hd.ne' cf hd classical use G.replaceVertex s t, inferInstance, cf.replaceVertex s t have := G.card_edgeFinset_replaceVertex_of_not_adj hn omega /-- In a Turán-maximal graph, non-adjacency is transitive. -/ lemma not_adj_trans (h : G.IsTuranMaximal r) (hts : ¬G.Adj t s) (hsu : ¬G.Adj s u) : ¬G.Adj t u := by have hst : ¬G.Adj s t := fun a ↦ hts a.symm have dst := h.degree_eq_of_not_adj hst have dsu := h.degree_eq_of_not_adj hsu rw [IsTuranMaximal] at h; contrapose! h; intro cf classical use (G.replaceVertex s t).replaceVertex s u, inferInstance, (cf.replaceVertex s t).replaceVertex s u have nst : s ≠ t := fun a ↦ hsu (a ▸ h) have ntu : t ≠ u := G.ne_of_adj h have := (G.adj_replaceVertex_iff_of_ne s nst ntu.symm).not.mpr hsu rw [card_edgeFinset_replaceVertex_of_not_adj _ this, card_edgeFinset_replaceVertex_of_not_adj _ hst, dst, Nat.add_sub_cancel] have l1 : (G.replaceVertex s t).degree s = G.degree s := by unfold degree; congr 1; ext v simp only [mem_neighborFinset, SimpleGraph.irrefl, ite_self] by_cases eq : v = t · simpa only [eq, not_adj_replaceVertex_same, false_iff] · rw [G.adj_replaceVertex_iff_of_ne s nst eq] have l2 : (G.replaceVertex s t).degree u = G.degree u - 1 := by rw [degree, degree, ← card_singleton t, ← card_sdiff (by simp [h.symm])] congr 1; ext v simp only [mem_neighborFinset, mem_sdiff, mem_singleton, replaceVertex] split_ifs <;> simp_all [adj_comm] have l3 : 0 < G.degree u := by rw [G.degree_pos_iff_exists_adj u]; use t, h.symm omega variable (h : G.IsTuranMaximal r) /-- In a Turán-maximal graph, non-adjacency is an equivalence relation. -/ theorem equivalence_not_adj : Equivalence (¬G.Adj · ·) where refl := by simp symm := by simp [adj_comm] trans := h.not_adj_trans /-- The non-adjacency setoid over the vertices of a Turán-maximal graph induced by `equivalence_not_adj`. -/ def setoid : Setoid V := ⟨_, h.equivalence_not_adj⟩ instance : DecidableRel h.setoid.r := inferInstanceAs <| DecidableRel (¬G.Adj · ·) /-- The finpartition derived from `h.setoid`. -/ def finpartition [DecidableEq V] : Finpartition (univ : Finset V) := Finpartition.ofSetoid h.setoid variable [DecidableEq V] lemma not_adj_iff_part_eq : ¬G.Adj s t ↔ h.finpartition.part s = h.finpartition.part t := by change h.setoid.r s t ↔ _ rw [← Finpartition.mem_part_ofSetoid_iff_rel] let fp := h.finpartition change t ∈ fp.part s ↔ fp.part s = fp.part t rw [fp.mem_part_iff_part_eq_part (mem_univ t) (mem_univ s), eq_comm] lemma degree_eq_card_sub_part_card : G.degree s = Fintype.card V - (h.finpartition.part s).card := calc _ = (univ.filter (G.Adj s)).card := by simp [← card_neighborFinset_eq_degree, neighborFinset] _ = Fintype.card V - (univ.filter (¬G.Adj s ·)).card := eq_tsub_of_add_eq (filter_card_add_filter_neg_card_eq_card _) _ = _ := by congr; ext; rw [mem_filter] convert Finpartition.mem_part_ofSetoid_iff_rel.symm simp [setoid] /-- The parts of a Turán-maximal graph form an equipartition. -/ theorem isEquipartition : h.finpartition.IsEquipartition := by set fp := h.finpartition by_contra hn rw [Finpartition.not_isEquipartition] at hn obtain ⟨large, hl, small, hs, ineq⟩ := hn obtain ⟨w, hw⟩ := fp.nonempty_of_mem_parts hl obtain ⟨v, hv⟩ := fp.nonempty_of_mem_parts hs apply absurd h rw [IsTuranMaximal]; push_neg; intro cf use G.replaceVertex v w, inferInstance, cf.replaceVertex v w have large_eq := fp.part_eq_of_mem hl hw have small_eq := fp.part_eq_of_mem hs hv have ha : G.Adj v w := by by_contra hn; rw [h.not_adj_iff_part_eq, small_eq, large_eq] at hn rw [hn] at ineq; omega rw [G.card_edgeFinset_replaceVertex_of_adj ha, degree_eq_card_sub_part_card h, small_eq, degree_eq_card_sub_part_card h, large_eq] have : large.card ≤ Fintype.card V := by simpa using card_le_card large.subset_univ omega lemma card_parts_le : h.finpartition.parts.card ≤ r := by by_contra! l obtain ⟨z, -, hz⟩ := h.finpartition.exists_subset_part_bijOn have ncf : ¬G.CliqueFree z.card := by refine IsNClique.not_cliqueFree ⟨fun v hv w hw hn ↦ ?_, rfl⟩ contrapose! hn exact hz.injOn hv hw (by rwa [← h.not_adj_iff_part_eq]) rw [Finset.card_eq_of_equiv hz.equiv] at ncf exact absurd (h.1.mono (Nat.succ_le_of_lt l)) ncf /-- There are `min n r` parts in a graph on `n` vertices satisfying `G.IsTuranMaximal r`. `min` handles the `n < r` case, when `G` is complete but still `r + 1`-cliquefree for having insufficiently many vertices. -/ theorem card_parts : h.finpartition.parts.card = min (Fintype.card V) r := by set fp := h.finpartition apply le_antisymm (le_min fp.card_parts_le_card h.card_parts_le) by_contra! l rw [lt_min_iff] at l obtain ⟨x, -, y, -, hn, he⟩ := exists_ne_map_eq_of_card_lt_of_maps_to l.1 fun a _ ↦ fp.part_mem (mem_univ a) apply absurd h rw [IsTuranMaximal]; push_neg; rintro - have cf : G.CliqueFree r := by simp_rw [← cliqueFinset_eq_empty_iff, cliqueFinset, filter_eq_empty_iff, mem_univ, forall_true_left, isNClique_iff, and_comm, not_and, isClique_iff, Set.Pairwise] intro z zc; push_neg; simp_rw [h.not_adj_iff_part_eq] exact exists_ne_map_eq_of_card_lt_of_maps_to (zc.symm ▸ l.2) fun a _ ↦ fp.part_mem (mem_univ a) use G ⊔ edge x y, inferInstance, cf.sup_edge x y convert Nat.lt.base G.edgeFinset.card convert G.card_edgeFinset_sup_edge _ hn rwa [h.not_adj_iff_part_eq] /-- **Turán's theorem**, forward direction. Any `r + 1`-cliquefree Turán-maximal graph on `n` vertices is isomorphic to `turanGraph n r`. -/ theorem nonempty_iso_turanGraph (h : G.IsTuranMaximal r) : Nonempty (G ≃g turanGraph (Fintype.card V) r) := by classical obtain ⟨zm, zp⟩ := h.isEquipartition.exists_partPreservingEquiv use (Equiv.subtypeUnivEquiv mem_univ).symm.trans zm intro a b simp_rw [turanGraph, Equiv.trans_apply, Equiv.subtypeUnivEquiv_symm_apply] have := zp ⟨a, mem_univ a⟩ ⟨b, mem_univ b⟩ rw [← h.not_adj_iff_part_eq] at this rw [← not_iff_not, not_ne_iff, this, card_parts] rcases le_or_lt r (Fintype.card V) with c | c · rw [min_eq_right c]; rfl · have lc : ∀ x, zm ⟨x, _⟩ < Fintype.card V := fun x ↦ (zm ⟨x, mem_univ x⟩).2 rw [min_eq_left c.le, Nat.mod_eq_of_lt (lc a), Nat.mod_eq_of_lt (lc b), ← Nat.mod_eq_of_lt ((lc a).trans c), ← Nat.mod_eq_of_lt ((lc b).trans c)]; rfl end IsTuranMaximal variable [DecidableEq V] /-- **Turán's theorem**, reverse direction. Any graph isomorphic to `turanGraph n r` is itself Turán-maximal if `0 < r`. -/ theorem isTuranMaximal_of_iso (f : G ≃g turanGraph n r) (hr : 0 < r) : G.IsTuranMaximal r := by obtain ⟨J, _, j⟩ := exists_isTuranMaximal (V := V) hr obtain ⟨g⟩ := j.nonempty_iso_turanGraph rw [f.card_eq, Fintype.card_fin] at g use (turanGraph_cliqueFree (n := n) hr).comap f, fun H _ cf ↦ (f.symm.comp g).card_edgeFinset_eq ▸ j.2 H cf /-- Turán-maximality with `0 < r` transfers across graph isomorphisms. -/ theorem IsTuranMaximal.iso {W : Type*} [DecidableEq W] [Fintype W] {H : SimpleGraph W} [DecidableRel H.Adj] (h : G.IsTuranMaximal r) (f : G ≃g H) (hr : 0 < r) : H.IsTuranMaximal r := isTuranMaximal_of_iso (h.nonempty_iso_turanGraph.some.comp f.symm) hr /-- For `0 < r`, `turanGraph n r` is Turán-maximal. -/ theorem isTuranMaximal_turanGraph (hr : 0 < r) : (turanGraph n r).IsTuranMaximal r := isTuranMaximal_of_iso Iso.refl hr /-- **Turán's theorem**. `turanGraph n r` is, up to isomorphism, the unique `r + 1`-cliquefree Turán-maximal graph on `n` vertices. -/ theorem isTuranMaximal_iff_nonempty_iso_turanGraph (hr : 0 < r) : G.IsTuranMaximal r ↔ Nonempty (G ≃g turanGraph (Fintype.card V) r) := ⟨fun h ↦ h.nonempty_iso_turanGraph, fun h ↦ isTuranMaximal_of_iso h.some hr⟩ end SimpleGraph
Combinatorics\SimpleGraph\Walk.lean
/- Copyright (c) 2021 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import Mathlib.Combinatorics.SimpleGraph.Maps /-! # Walk In a simple graph, a *walk* is a finite sequence of adjacent vertices, and can be thought of equally well as a sequence of directed edges. **Warning:** graph theorists mean something different by "path" than do homotopy theorists. A "walk" in graph theory is a "path" in homotopy theory. Another warning: some graph theorists use "path" and "simple path" for "walk" and "path." Some definitions and theorems have inspiration from multigraph counterparts in [Chou1994]. ## Main definitions * `SimpleGraph.Walk` (with accompanying pattern definitions `SimpleGraph.Walk.nil'` and `SimpleGraph.Walk.cons'`) * `SimpleGraph.Walk.map` for the induced map on walks, given an (injective) graph homomorphism. ## Tags walks -/ open Function universe u v w namespace SimpleGraph variable {V : Type u} {V' : Type v} {V'' : Type w} variable (G : SimpleGraph V) (G' : SimpleGraph V') (G'' : SimpleGraph V'') /-- A walk is a sequence of adjacent vertices. For vertices `u v : V`, the type `walk u v` consists of all walks starting at `u` and ending at `v`. We say that a walk *visits* the vertices it contains. The set of vertices a walk visits is `SimpleGraph.Walk.support`. See `SimpleGraph.Walk.nil'` and `SimpleGraph.Walk.cons'` for patterns that can be useful in definitions since they make the vertices explicit. -/ inductive Walk : V → V → Type u | nil {u : V} : Walk u u | cons {u v w : V} (h : G.Adj u v) (p : Walk v w) : Walk u w deriving DecidableEq attribute [refl] Walk.nil @[simps] instance Walk.instInhabited (v : V) : Inhabited (G.Walk v v) := ⟨Walk.nil⟩ /-- The one-edge walk associated to a pair of adjacent vertices. -/ @[match_pattern, reducible] def Adj.toWalk {G : SimpleGraph V} {u v : V} (h : G.Adj u v) : G.Walk u v := Walk.cons h Walk.nil namespace Walk variable {G} /-- Pattern to get `Walk.nil` with the vertex as an explicit argument. -/ @[match_pattern] abbrev nil' (u : V) : G.Walk u u := Walk.nil /-- Pattern to get `Walk.cons` with the vertices as explicit arguments. -/ @[match_pattern] abbrev cons' (u v w : V) (h : G.Adj u v) (p : G.Walk v w) : G.Walk u w := Walk.cons h p /-- Change the endpoints of a walk using equalities. This is helpful for relaxing definitional equality constraints and to be able to state otherwise difficult-to-state lemmas. While this is a simple wrapper around `Eq.rec`, it gives a canonical way to write it. The simp-normal form is for the `copy` to be pushed outward. That way calculations can occur within the "copy context." -/ protected def copy {u v u' v'} (p : G.Walk u v) (hu : u = u') (hv : v = v') : G.Walk u' v' := hu ▸ hv ▸ p @[simp] theorem copy_rfl_rfl {u v} (p : G.Walk u v) : p.copy rfl rfl = p := rfl @[simp] theorem copy_copy {u v u' v' u'' v''} (p : G.Walk u v) (hu : u = u') (hv : v = v') (hu' : u' = u'') (hv' : v' = v'') : (p.copy hu hv).copy hu' hv' = p.copy (hu.trans hu') (hv.trans hv') := by subst_vars rfl @[simp] theorem copy_nil {u u'} (hu : u = u') : (Walk.nil : G.Walk u u).copy hu hu = Walk.nil := by subst_vars rfl theorem copy_cons {u v w u' w'} (h : G.Adj u v) (p : G.Walk v w) (hu : u = u') (hw : w = w') : (Walk.cons h p).copy hu hw = Walk.cons (hu ▸ h) (p.copy rfl hw) := by subst_vars rfl @[simp] theorem cons_copy {u v w v' w'} (h : G.Adj u v) (p : G.Walk v' w') (hv : v' = v) (hw : w' = w) : Walk.cons h (p.copy hv hw) = (Walk.cons (hv ▸ h) p).copy rfl hw := by subst_vars rfl theorem exists_eq_cons_of_ne {u v : V} (hne : u ≠ v) : ∀ (p : G.Walk u v), ∃ (w : V) (h : G.Adj u w) (p' : G.Walk w v), p = cons h p' | nil => (hne rfl).elim | cons h p' => ⟨_, h, p', rfl⟩ /-- The length of a walk is the number of edges/darts along it. -/ def length {u v : V} : G.Walk u v → ℕ | nil => 0 | cons _ q => q.length.succ /-- The concatenation of two compatible walks. -/ @[trans] def append {u v w : V} : G.Walk u v → G.Walk v w → G.Walk u w | nil, q => q | cons h p, q => cons h (p.append q) /-- The reversed version of `SimpleGraph.Walk.cons`, concatenating an edge to the end of a walk. -/ def concat {u v w : V} (p : G.Walk u v) (h : G.Adj v w) : G.Walk u w := p.append (cons h nil) theorem concat_eq_append {u v w : V} (p : G.Walk u v) (h : G.Adj v w) : p.concat h = p.append (cons h nil) := rfl /-- The concatenation of the reverse of the first walk with the second walk. -/ protected def reverseAux {u v w : V} : G.Walk u v → G.Walk u w → G.Walk v w | nil, q => q | cons h p, q => Walk.reverseAux p (cons (G.symm h) q) /-- The walk in reverse. -/ @[symm] def reverse {u v : V} (w : G.Walk u v) : G.Walk v u := w.reverseAux nil /-- Get the `n`th vertex from a walk, where `n` is generally expected to be between `0` and `p.length`, inclusive. If `n` is greater than or equal to `p.length`, the result is the path's endpoint. -/ def getVert {u v : V} : G.Walk u v → ℕ → V | nil, _ => u | cons _ _, 0 => u | cons _ q, n + 1 => q.getVert n @[simp] theorem getVert_zero {u v} (w : G.Walk u v) : w.getVert 0 = u := by cases w <;> rfl theorem getVert_of_length_le {u v} (w : G.Walk u v) {i : ℕ} (hi : w.length ≤ i) : w.getVert i = v := by induction w generalizing i with | nil => rfl | cons _ _ ih => cases i · cases hi · exact ih (Nat.succ_le_succ_iff.1 hi) @[simp] theorem getVert_length {u v} (w : G.Walk u v) : w.getVert w.length = v := w.getVert_of_length_le rfl.le theorem adj_getVert_succ {u v} (w : G.Walk u v) {i : ℕ} (hi : i < w.length) : G.Adj (w.getVert i) (w.getVert (i + 1)) := by induction w generalizing i with | nil => cases hi | cons hxy _ ih => cases i · simp [getVert, hxy] · exact ih (Nat.succ_lt_succ_iff.1 hi) @[simp] lemma cons_getVert_succ {u v w n} (p : G.Walk v w) (h : G.Adj u v) : (p.cons h).getVert (n + 1) = p.getVert n := rfl lemma cons_getVert {u v w n} (p : G.Walk v w) (h : G.Adj u v) (hn : n ≠ 0) : (p.cons h).getVert n = p.getVert (n - 1) := by obtain ⟨i, hi⟩ : ∃ (i : ℕ), i.succ = n := by use n - 1; exact Nat.succ_pred_eq_of_ne_zero hn rw [← hi] simp only [Nat.succ_eq_add_one, cons_getVert_succ, Nat.add_sub_cancel] @[simp] theorem cons_append {u v w x : V} (h : G.Adj u v) (p : G.Walk v w) (q : G.Walk w x) : (cons h p).append q = cons h (p.append q) := rfl @[simp] theorem cons_nil_append {u v w : V} (h : G.Adj u v) (p : G.Walk v w) : (cons h nil).append p = cons h p := rfl @[simp] theorem append_nil {u v : V} (p : G.Walk u v) : p.append nil = p := by induction p with | nil => rfl | cons _ _ ih => rw [cons_append, ih] @[simp] theorem nil_append {u v : V} (p : G.Walk u v) : nil.append p = p := rfl theorem append_assoc {u v w x : V} (p : G.Walk u v) (q : G.Walk v w) (r : G.Walk w x) : p.append (q.append r) = (p.append q).append r := by induction p with | nil => rfl | cons h p' ih => dsimp only [append] rw [ih] @[simp] theorem append_copy_copy {u v w u' v' w'} (p : G.Walk u v) (q : G.Walk v w) (hu : u = u') (hv : v = v') (hw : w = w') : (p.copy hu hv).append (q.copy hv hw) = (p.append q).copy hu hw := by subst_vars rfl theorem concat_nil {u v : V} (h : G.Adj u v) : nil.concat h = cons h nil := rfl @[simp] theorem concat_cons {u v w x : V} (h : G.Adj u v) (p : G.Walk v w) (h' : G.Adj w x) : (cons h p).concat h' = cons h (p.concat h') := rfl theorem append_concat {u v w x : V} (p : G.Walk u v) (q : G.Walk v w) (h : G.Adj w x) : p.append (q.concat h) = (p.append q).concat h := append_assoc _ _ _ theorem concat_append {u v w x : V} (p : G.Walk u v) (h : G.Adj v w) (q : G.Walk w x) : (p.concat h).append q = p.append (cons h q) := by rw [concat_eq_append, ← append_assoc, cons_nil_append] /-- A non-trivial `cons` walk is representable as a `concat` walk. -/ theorem exists_cons_eq_concat {u v w : V} (h : G.Adj u v) (p : G.Walk v w) : ∃ (x : V) (q : G.Walk u x) (h' : G.Adj x w), cons h p = q.concat h' := by induction p generalizing u with | nil => exact ⟨_, nil, h, rfl⟩ | cons h' p ih => obtain ⟨y, q, h'', hc⟩ := ih h' refine ⟨y, cons h q, h'', ?_⟩ rw [concat_cons, hc] /-- A non-trivial `concat` walk is representable as a `cons` walk. -/ theorem exists_concat_eq_cons {u v w : V} : ∀ (p : G.Walk u v) (h : G.Adj v w), ∃ (x : V) (h' : G.Adj u x) (q : G.Walk x w), p.concat h = cons h' q | nil, h => ⟨_, h, nil, rfl⟩ | cons h' p, h => ⟨_, h', Walk.concat p h, concat_cons _ _ _⟩ @[simp] theorem reverse_nil {u : V} : (nil : G.Walk u u).reverse = nil := rfl theorem reverse_singleton {u v : V} (h : G.Adj u v) : (cons h nil).reverse = cons (G.symm h) nil := rfl @[simp] theorem cons_reverseAux {u v w x : V} (p : G.Walk u v) (q : G.Walk w x) (h : G.Adj w u) : (cons h p).reverseAux q = p.reverseAux (cons (G.symm h) q) := rfl @[simp] protected theorem append_reverseAux {u v w x : V} (p : G.Walk u v) (q : G.Walk v w) (r : G.Walk u x) : (p.append q).reverseAux r = q.reverseAux (p.reverseAux r) := by induction p with | nil => rfl | cons h _ ih => exact ih q (cons (G.symm h) r) @[simp] protected theorem reverseAux_append {u v w x : V} (p : G.Walk u v) (q : G.Walk u w) (r : G.Walk w x) : (p.reverseAux q).append r = p.reverseAux (q.append r) := by induction p with | nil => rfl | cons h _ ih => simp [ih (cons (G.symm h) q)] protected theorem reverseAux_eq_reverse_append {u v w : V} (p : G.Walk u v) (q : G.Walk u w) : p.reverseAux q = p.reverse.append q := by simp [reverse] @[simp] theorem reverse_cons {u v w : V} (h : G.Adj u v) (p : G.Walk v w) : (cons h p).reverse = p.reverse.append (cons (G.symm h) nil) := by simp [reverse] @[simp] theorem reverse_copy {u v u' v'} (p : G.Walk u v) (hu : u = u') (hv : v = v') : (p.copy hu hv).reverse = p.reverse.copy hv hu := by subst_vars rfl @[simp] theorem reverse_append {u v w : V} (p : G.Walk u v) (q : G.Walk v w) : (p.append q).reverse = q.reverse.append p.reverse := by simp [reverse] @[simp] theorem reverse_concat {u v w : V} (p : G.Walk u v) (h : G.Adj v w) : (p.concat h).reverse = cons (G.symm h) p.reverse := by simp [concat_eq_append] @[simp] theorem reverse_reverse {u v : V} (p : G.Walk u v) : p.reverse.reverse = p := by induction p with | nil => rfl | cons _ _ ih => simp [ih] theorem reverse_surjective {u v : V} : Function.Surjective (reverse : G.Walk u v → _) := RightInverse.surjective reverse_reverse theorem reverse_injective {u v : V} : Function.Injective (reverse : G.Walk u v → _) := RightInverse.injective reverse_reverse theorem reverse_bijective {u v : V} : Function.Bijective (reverse : G.Walk u v → _) := And.intro reverse_injective reverse_surjective @[simp] theorem length_nil {u : V} : (nil : G.Walk u u).length = 0 := rfl @[simp] theorem length_cons {u v w : V} (h : G.Adj u v) (p : G.Walk v w) : (cons h p).length = p.length + 1 := rfl @[simp] theorem length_copy {u v u' v'} (p : G.Walk u v) (hu : u = u') (hv : v = v') : (p.copy hu hv).length = p.length := by subst_vars rfl @[simp] theorem length_append {u v w : V} (p : G.Walk u v) (q : G.Walk v w) : (p.append q).length = p.length + q.length := by induction p with | nil => simp | cons _ _ ih => simp [ih, add_comm, add_left_comm, add_assoc] @[simp] theorem length_concat {u v w : V} (p : G.Walk u v) (h : G.Adj v w) : (p.concat h).length = p.length + 1 := length_append _ _ @[simp] protected theorem length_reverseAux {u v w : V} (p : G.Walk u v) (q : G.Walk u w) : (p.reverseAux q).length = p.length + q.length := by induction p with | nil => simp! | cons _ _ ih => simp [ih, Nat.succ_add, Nat.add_assoc] @[simp] theorem length_reverse {u v : V} (p : G.Walk u v) : p.reverse.length = p.length := by simp [reverse] theorem eq_of_length_eq_zero {u v : V} : ∀ {p : G.Walk u v}, p.length = 0 → u = v | nil, _ => rfl theorem adj_of_length_eq_one {u v : V} : ∀ {p : G.Walk u v}, p.length = 1 → G.Adj u v | cons h nil, _ => h @[simp] theorem exists_length_eq_zero_iff {u v : V} : (∃ p : G.Walk u v, p.length = 0) ↔ u = v := by constructor · rintro ⟨p, hp⟩ exact eq_of_length_eq_zero hp · rintro rfl exact ⟨nil, rfl⟩ @[simp] theorem length_eq_zero_iff {u : V} {p : G.Walk u u} : p.length = 0 ↔ p = nil := by cases p <;> simp theorem getVert_append {u v w : V} (p : G.Walk u v) (q : G.Walk v w) (i : ℕ) : (p.append q).getVert i = if i < p.length then p.getVert i else q.getVert (i - p.length) := by induction p generalizing i with | nil => simp | cons h p ih => cases i <;> simp [getVert, ih, Nat.succ_lt_succ_iff] theorem getVert_reverse {u v : V} (p : G.Walk u v) (i : ℕ) : p.reverse.getVert i = p.getVert (p.length - i) := by induction p with | nil => rfl | cons h p ih => simp only [reverse_cons, getVert_append, length_reverse, ih, length_cons] split_ifs next hi => rw [Nat.succ_sub hi.le] simp [getVert] next hi => obtain rfl | hi' := Nat.eq_or_lt_of_not_lt hi · simp [getVert] · rw [Nat.eq_add_of_sub_eq (Nat.sub_pos_of_lt hi') rfl, Nat.sub_eq_zero_of_le hi'] simp [getVert] section ConcatRec variable {motive : ∀ u v : V, G.Walk u v → Sort*} (Hnil : ∀ {u : V}, motive u u nil) (Hconcat : ∀ {u v w : V} (p : G.Walk u v) (h : G.Adj v w), motive u v p → motive u w (p.concat h)) /-- Auxiliary definition for `SimpleGraph.Walk.concatRec` -/ def concatRecAux {u v : V} : (p : G.Walk u v) → motive v u p.reverse | nil => Hnil | cons h p => reverse_cons h p ▸ Hconcat p.reverse h.symm (concatRecAux p) /-- Recursor on walks by inducting on `SimpleGraph.Walk.concat`. This is inducting from the opposite end of the walk compared to `SimpleGraph.Walk.rec`, which inducts on `SimpleGraph.Walk.cons`. -/ @[elab_as_elim] def concatRec {u v : V} (p : G.Walk u v) : motive u v p := reverse_reverse p ▸ concatRecAux @Hnil @Hconcat p.reverse @[simp] theorem concatRec_nil (u : V) : @concatRec _ _ motive @Hnil @Hconcat _ _ (nil : G.Walk u u) = Hnil := rfl @[simp] theorem concatRec_concat {u v w : V} (p : G.Walk u v) (h : G.Adj v w) : @concatRec _ _ motive @Hnil @Hconcat _ _ (p.concat h) = Hconcat p h (concatRec @Hnil @Hconcat p) := by simp only [concatRec] apply eq_of_heq apply rec_heq_of_heq trans concatRecAux @Hnil @Hconcat (cons h.symm p.reverse) · congr simp · rw [concatRecAux, rec_heq_iff_heq] congr <;> simp [heq_rec_iff_heq] end ConcatRec theorem concat_ne_nil {u v : V} (p : G.Walk u v) (h : G.Adj v u) : p.concat h ≠ nil := by cases p <;> simp [concat] theorem concat_inj {u v v' w : V} {p : G.Walk u v} {h : G.Adj v w} {p' : G.Walk u v'} {h' : G.Adj v' w} (he : p.concat h = p'.concat h') : ∃ hv : v = v', p.copy rfl hv = p' := by induction p with | nil => cases p' · exact ⟨rfl, rfl⟩ · exfalso simp only [concat_nil, concat_cons, cons.injEq] at he obtain ⟨rfl, he⟩ := he simp only [heq_iff_eq] at he exact concat_ne_nil _ _ he.symm | cons _ _ ih => rw [concat_cons] at he cases p' · exfalso simp only [concat_nil, cons.injEq] at he obtain ⟨rfl, he⟩ := he rw [heq_iff_eq] at he exact concat_ne_nil _ _ he · rw [concat_cons, cons.injEq] at he obtain ⟨rfl, he⟩ := he rw [heq_iff_eq] at he obtain ⟨rfl, rfl⟩ := ih he exact ⟨rfl, rfl⟩ /-- The `support` of a walk is the list of vertices it visits in order. -/ def support {u v : V} : G.Walk u v → List V | nil => [u] | cons _ p => u :: p.support /-- The `darts` of a walk is the list of darts it visits in order. -/ def darts {u v : V} : G.Walk u v → List G.Dart | nil => [] | cons h p => ⟨(u, _), h⟩ :: p.darts /-- The `edges` of a walk is the list of edges it visits in order. This is defined to be the list of edges underlying `SimpleGraph.Walk.darts`. -/ def edges {u v : V} (p : G.Walk u v) : List (Sym2 V) := p.darts.map Dart.edge @[simp] theorem support_nil {u : V} : (nil : G.Walk u u).support = [u] := rfl @[simp] theorem support_cons {u v w : V} (h : G.Adj u v) (p : G.Walk v w) : (cons h p).support = u :: p.support := rfl @[simp] theorem support_concat {u v w : V} (p : G.Walk u v) (h : G.Adj v w) : (p.concat h).support = p.support.concat w := by induction p <;> simp [*, concat_nil] @[simp] theorem support_copy {u v u' v'} (p : G.Walk u v) (hu : u = u') (hv : v = v') : (p.copy hu hv).support = p.support := by subst_vars rfl theorem support_append {u v w : V} (p : G.Walk u v) (p' : G.Walk v w) : (p.append p').support = p.support ++ p'.support.tail := by induction p <;> cases p' <;> simp [*] @[simp] theorem support_reverse {u v : V} (p : G.Walk u v) : p.reverse.support = p.support.reverse := by induction p <;> simp [support_append, *] @[simp] theorem support_ne_nil {u v : V} (p : G.Walk u v) : p.support ≠ [] := by cases p <;> simp theorem tail_support_append {u v w : V} (p : G.Walk u v) (p' : G.Walk v w) : (p.append p').support.tail = p.support.tail ++ p'.support.tail := by rw [support_append, List.tail_append_of_ne_nil _ _ (support_ne_nil _)] theorem support_eq_cons {u v : V} (p : G.Walk u v) : p.support = u :: p.support.tail := by cases p <;> simp @[simp] theorem start_mem_support {u v : V} (p : G.Walk u v) : u ∈ p.support := by cases p <;> simp @[simp] theorem end_mem_support {u v : V} (p : G.Walk u v) : v ∈ p.support := by induction p <;> simp [*] @[simp] theorem support_nonempty {u v : V} (p : G.Walk u v) : { w | w ∈ p.support }.Nonempty := ⟨u, by simp⟩ theorem mem_support_iff {u v w : V} (p : G.Walk u v) : w ∈ p.support ↔ w = u ∨ w ∈ p.support.tail := by cases p <;> simp theorem mem_support_nil_iff {u v : V} : u ∈ (nil : G.Walk v v).support ↔ u = v := by simp @[simp] theorem mem_tail_support_append_iff {t u v w : V} (p : G.Walk u v) (p' : G.Walk v w) : t ∈ (p.append p').support.tail ↔ t ∈ p.support.tail ∨ t ∈ p'.support.tail := by rw [tail_support_append, List.mem_append] @[simp] theorem end_mem_tail_support_of_ne {u v : V} (h : u ≠ v) (p : G.Walk u v) : v ∈ p.support.tail := by obtain ⟨_, _, _, rfl⟩ := exists_eq_cons_of_ne h p simp @[simp, nolint unusedHavesSuffices] theorem mem_support_append_iff {t u v w : V} (p : G.Walk u v) (p' : G.Walk v w) : t ∈ (p.append p').support ↔ t ∈ p.support ∨ t ∈ p'.support := by simp only [mem_support_iff, mem_tail_support_append_iff] obtain rfl | h := eq_or_ne t v <;> obtain rfl | h' := eq_or_ne t u <;> -- this `have` triggers the unusedHavesSuffices linter: (try have := h'.symm) <;> simp [*] @[simp] theorem subset_support_append_left {V : Type u} {G : SimpleGraph V} {u v w : V} (p : G.Walk u v) (q : G.Walk v w) : p.support ⊆ (p.append q).support := by simp only [Walk.support_append, List.subset_append_left] @[simp] theorem subset_support_append_right {V : Type u} {G : SimpleGraph V} {u v w : V} (p : G.Walk u v) (q : G.Walk v w) : q.support ⊆ (p.append q).support := by intro h simp (config := { contextual := true }) only [mem_support_append_iff, or_true_iff, imp_true_iff] theorem coe_support {u v : V} (p : G.Walk u v) : (p.support : Multiset V) = {u} + p.support.tail := by cases p <;> rfl theorem coe_support_append {u v w : V} (p : G.Walk u v) (p' : G.Walk v w) : ((p.append p').support : Multiset V) = {u} + p.support.tail + p'.support.tail := by rw [support_append, ← Multiset.coe_add, coe_support] theorem coe_support_append' [DecidableEq V] {u v w : V} (p : G.Walk u v) (p' : G.Walk v w) : ((p.append p').support : Multiset V) = p.support + p'.support - {v} := by rw [support_append, ← Multiset.coe_add] simp only [coe_support] rw [add_comm ({v} : Multiset V)] simp only [← add_assoc, add_tsub_cancel_right] theorem chain_adj_support {u v w : V} (h : G.Adj u v) : ∀ (p : G.Walk v w), List.Chain G.Adj u p.support | nil => List.Chain.cons h List.Chain.nil | cons h' p => List.Chain.cons h (chain_adj_support h' p) theorem chain'_adj_support {u v : V} : ∀ (p : G.Walk u v), List.Chain' G.Adj p.support | nil => List.Chain.nil | cons h p => chain_adj_support h p theorem chain_dartAdj_darts {d : G.Dart} {v w : V} (h : d.snd = v) (p : G.Walk v w) : List.Chain G.DartAdj d p.darts := by induction p generalizing d with | nil => exact List.Chain.nil -- Porting note: needed to defer `h` and `rfl` to help elaboration | cons h' p ih => exact List.Chain.cons (by exact h) (ih (by rfl)) theorem chain'_dartAdj_darts {u v : V} : ∀ (p : G.Walk u v), List.Chain' G.DartAdj p.darts | nil => trivial -- Porting note: needed to defer `rfl` to help elaboration | cons h p => chain_dartAdj_darts (by rfl) p /-- Every edge in a walk's edge list is an edge of the graph. It is written in this form (rather than using `⊆`) to avoid unsightly coercions. -/ theorem edges_subset_edgeSet {u v : V} : ∀ (p : G.Walk u v) ⦃e : Sym2 V⦄, e ∈ p.edges → e ∈ G.edgeSet | cons h' p', e, h => by cases h · exact h' next h' => exact edges_subset_edgeSet p' h' theorem adj_of_mem_edges {u v x y : V} (p : G.Walk u v) (h : s(x, y) ∈ p.edges) : G.Adj x y := edges_subset_edgeSet p h @[simp] theorem darts_nil {u : V} : (nil : G.Walk u u).darts = [] := rfl @[simp] theorem darts_cons {u v w : V} (h : G.Adj u v) (p : G.Walk v w) : (cons h p).darts = ⟨(u, v), h⟩ :: p.darts := rfl @[simp] theorem darts_concat {u v w : V} (p : G.Walk u v) (h : G.Adj v w) : (p.concat h).darts = p.darts.concat ⟨(v, w), h⟩ := by induction p <;> simp [*, concat_nil] @[simp] theorem darts_copy {u v u' v'} (p : G.Walk u v) (hu : u = u') (hv : v = v') : (p.copy hu hv).darts = p.darts := by subst_vars rfl @[simp] theorem darts_append {u v w : V} (p : G.Walk u v) (p' : G.Walk v w) : (p.append p').darts = p.darts ++ p'.darts := by induction p <;> simp [*] @[simp] theorem darts_reverse {u v : V} (p : G.Walk u v) : p.reverse.darts = (p.darts.map Dart.symm).reverse := by induction p <;> simp [*, Sym2.eq_swap] theorem mem_darts_reverse {u v : V} {d : G.Dart} {p : G.Walk u v} : d ∈ p.reverse.darts ↔ d.symm ∈ p.darts := by simp theorem cons_map_snd_darts {u v : V} (p : G.Walk u v) : (u :: p.darts.map (·.snd)) = p.support := by induction p <;> simp! [*] theorem map_snd_darts {u v : V} (p : G.Walk u v) : p.darts.map (·.snd) = p.support.tail := by simpa using congr_arg List.tail (cons_map_snd_darts p) theorem map_fst_darts_append {u v : V} (p : G.Walk u v) : p.darts.map (·.fst) ++ [v] = p.support := by induction p <;> simp! [*] theorem map_fst_darts {u v : V} (p : G.Walk u v) : p.darts.map (·.fst) = p.support.dropLast := by simpa! using congr_arg List.dropLast (map_fst_darts_append p) @[simp] theorem edges_nil {u : V} : (nil : G.Walk u u).edges = [] := rfl @[simp] theorem edges_cons {u v w : V} (h : G.Adj u v) (p : G.Walk v w) : (cons h p).edges = s(u, v) :: p.edges := rfl @[simp] theorem edges_concat {u v w : V} (p : G.Walk u v) (h : G.Adj v w) : (p.concat h).edges = p.edges.concat s(v, w) := by simp [edges] @[simp] theorem edges_copy {u v u' v'} (p : G.Walk u v) (hu : u = u') (hv : v = v') : (p.copy hu hv).edges = p.edges := by subst_vars rfl @[simp] theorem edges_append {u v w : V} (p : G.Walk u v) (p' : G.Walk v w) : (p.append p').edges = p.edges ++ p'.edges := by simp [edges] @[simp] theorem edges_reverse {u v : V} (p : G.Walk u v) : p.reverse.edges = p.edges.reverse := by simp [edges, List.map_reverse] @[simp] theorem length_support {u v : V} (p : G.Walk u v) : p.support.length = p.length + 1 := by induction p <;> simp [*] @[simp] theorem length_darts {u v : V} (p : G.Walk u v) : p.darts.length = p.length := by induction p <;> simp [*] @[simp] theorem length_edges {u v : V} (p : G.Walk u v) : p.edges.length = p.length := by simp [edges] theorem dart_fst_mem_support_of_mem_darts {u v : V} : ∀ (p : G.Walk u v) {d : G.Dart}, d ∈ p.darts → d.fst ∈ p.support | cons h p', d, hd => by simp only [support_cons, darts_cons, List.mem_cons] at hd ⊢ rcases hd with (rfl | hd) · exact Or.inl rfl · exact Or.inr (dart_fst_mem_support_of_mem_darts _ hd) theorem dart_snd_mem_support_of_mem_darts {u v : V} (p : G.Walk u v) {d : G.Dart} (h : d ∈ p.darts) : d.snd ∈ p.support := by simpa using p.reverse.dart_fst_mem_support_of_mem_darts (by simp [h] : d.symm ∈ p.reverse.darts) theorem fst_mem_support_of_mem_edges {t u v w : V} (p : G.Walk v w) (he : s(t, u) ∈ p.edges) : t ∈ p.support := by obtain ⟨d, hd, he⟩ := List.mem_map.mp he rw [dart_edge_eq_mk'_iff'] at he rcases he with (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩) · exact dart_fst_mem_support_of_mem_darts _ hd · exact dart_snd_mem_support_of_mem_darts _ hd theorem snd_mem_support_of_mem_edges {t u v w : V} (p : G.Walk v w) (he : s(t, u) ∈ p.edges) : u ∈ p.support := by rw [Sym2.eq_swap] at he exact p.fst_mem_support_of_mem_edges he theorem darts_nodup_of_support_nodup {u v : V} {p : G.Walk u v} (h : p.support.Nodup) : p.darts.Nodup := by induction p with | nil => simp | cons _ p' ih => simp only [darts_cons, support_cons, List.nodup_cons] at h ⊢ exact ⟨fun h' => h.1 (dart_fst_mem_support_of_mem_darts p' h'), ih h.2⟩ theorem edges_nodup_of_support_nodup {u v : V} {p : G.Walk u v} (h : p.support.Nodup) : p.edges.Nodup := by induction p with | nil => simp | cons _ p' ih => simp only [edges_cons, support_cons, List.nodup_cons] at h ⊢ exact ⟨fun h' => h.1 (fst_mem_support_of_mem_edges p' h'), ih h.2⟩ /-- Predicate for the empty walk. Solves the dependent type problem where `p = G.Walk.nil` typechecks only if `p` has defeq endpoints. -/ inductive Nil : {v w : V} → G.Walk v w → Prop | nil {u : V} : Nil (nil : G.Walk u u) variable {u v w : V} @[simp] lemma nil_nil : (nil : G.Walk u u).Nil := Nil.nil @[simp] lemma not_nil_cons {h : G.Adj u v} {p : G.Walk v w} : ¬ (cons h p).Nil := nofun instance (p : G.Walk v w) : Decidable p.Nil := match p with | nil => isTrue .nil | cons _ _ => isFalse nofun protected lemma Nil.eq {p : G.Walk v w} : p.Nil → v = w | .nil => rfl lemma not_nil_of_ne {p : G.Walk v w} : v ≠ w → ¬ p.Nil := mt Nil.eq lemma nil_iff_support_eq {p : G.Walk v w} : p.Nil ↔ p.support = [v] := by cases p <;> simp lemma nil_iff_length_eq {p : G.Walk v w} : p.Nil ↔ p.length = 0 := by cases p <;> simp lemma not_nil_iff {p : G.Walk v w} : ¬ p.Nil ↔ ∃ (u : V) (h : G.Adj v u) (q : G.Walk u w), p = cons h q := by cases p <;> simp [*] /-- A walk with its endpoints defeq is `Nil` if and only if it is equal to `nil`. -/ lemma nil_iff_eq_nil : ∀ {p : G.Walk v v}, p.Nil ↔ p = nil | .nil | .cons _ _ => by simp alias ⟨Nil.eq_nil, _⟩ := nil_iff_eq_nil @[elab_as_elim] def notNilRec {motive : {u w : V} → (p : G.Walk u w) → (h : ¬ p.Nil) → Sort*} (cons : {u v w : V} → (h : G.Adj u v) → (q : G.Walk v w) → motive (cons h q) not_nil_cons) (p : G.Walk u w) : (hp : ¬ p.Nil) → motive p hp := match p with | nil => fun hp => absurd .nil hp | .cons h q => fun _ => cons h q @[simp] lemma notNilRec_cons {motive : {u w : V} → (p : G.Walk u w) → ¬ p.Nil → Sort*} (cons : {u v w : V} → (h : G.Adj u v) → (q : G.Walk v w) → motive (q.cons h) Walk.not_nil_cons) (h' : G.Adj u v) (q' : G.Walk v w) : @Walk.notNilRec _ _ _ _ _ cons _ _ = cons h' q' := by rfl /-- The second vertex along a non-nil walk. -/ def sndOfNotNil (p : G.Walk v w) (hp : ¬ p.Nil) : V := p.notNilRec (@fun _ u _ _ _ => u) hp @[simp] lemma adj_sndOfNotNil {p : G.Walk v w} (hp : ¬ p.Nil) : G.Adj v (p.sndOfNotNil hp) := p.notNilRec (fun h _ => h) hp /-- The walk obtained by removing the first dart of a non-nil walk. -/ def tail (p : G.Walk u v) (hp : ¬ p.Nil) : G.Walk (p.sndOfNotNil hp) v := p.notNilRec (fun _ q => q) hp /-- The first dart of a walk. -/ @[simps] def firstDart (p : G.Walk v w) (hp : ¬ p.Nil) : G.Dart where fst := v snd := p.sndOfNotNil hp adj := p.adj_sndOfNotNil hp lemma edge_firstDart (p : G.Walk v w) (hp : ¬ p.Nil) : (p.firstDart hp).edge = s(v, p.sndOfNotNil hp) := rfl variable {x y : V} -- TODO: rename to u, v, w instead? @[simp] lemma cons_tail_eq (p : G.Walk x y) (hp : ¬ p.Nil) : cons (p.adj_sndOfNotNil hp) (p.tail hp) = p := p.notNilRec (fun _ _ => rfl) hp @[simp] lemma cons_support_tail (p : G.Walk x y) (hp : ¬p.Nil) : x :: (p.tail hp).support = p.support := by rw [← support_cons, cons_tail_eq] @[simp] lemma length_tail_add_one {p : G.Walk x y} (hp : ¬ p.Nil) : (p.tail hp).length + 1 = p.length := by rw [← length_cons, cons_tail_eq] @[simp] lemma nil_copy {x' y' : V} {p : G.Walk x y} (hx : x = x') (hy : y = y') : (p.copy hx hy).Nil = p.Nil := by subst_vars; rfl @[simp] lemma support_tail (p : G.Walk v v) (hp) : (p.tail hp).support = p.support.tail := by rw [← cons_support_tail p hp, List.tail_cons] @[simp] lemma tail_cons {t u v} (p : G.Walk u v) (h : G.Adj t u) : (p.cons h).tail not_nil_cons = p := by unfold Walk.tail; simp only [notNilRec_cons] lemma tail_support_eq_support_tail (p : G.Walk u v) (hnp : ¬p.Nil) : (p.tail hnp).support = p.support.tail := p.notNilRec (by intro u v w huv q unfold Walk.tail simp only [notNilRec_cons, Walk.support_cons, List.tail_cons]) hnp /-! ### Walk decompositions -/ section WalkDecomp variable [DecidableEq V] /-- Given a vertex in the support of a path, give the path up until (and including) that vertex. -/ def takeUntil {v w : V} : ∀ (p : G.Walk v w) (u : V), u ∈ p.support → G.Walk v u | nil, u, h => by rw [mem_support_nil_iff.mp h] | cons r p, u, h => if hx : v = u then by subst u; exact Walk.nil else cons r (takeUntil p u <| by cases h · exact (hx rfl).elim · assumption) /-- Given a vertex in the support of a path, give the path from (and including) that vertex to the end. In other words, drop vertices from the front of a path until (and not including) that vertex. -/ def dropUntil {v w : V} : ∀ (p : G.Walk v w) (u : V), u ∈ p.support → G.Walk u w | nil, u, h => by rw [mem_support_nil_iff.mp h] | cons r p, u, h => if hx : v = u then by subst u exact cons r p else dropUntil p u <| by cases h · exact (hx rfl).elim · assumption /-- The `takeUntil` and `dropUntil` functions split a walk into two pieces. The lemma `SimpleGraph.Walk.count_support_takeUntil_eq_one` specifies where this split occurs. -/ @[simp] theorem take_spec {u v w : V} (p : G.Walk v w) (h : u ∈ p.support) : (p.takeUntil u h).append (p.dropUntil u h) = p := by induction p · rw [mem_support_nil_iff] at h subst u rfl · cases h · simp! · simp! only split_ifs with h' <;> subst_vars <;> simp [*] theorem mem_support_iff_exists_append {V : Type u} {G : SimpleGraph V} {u v w : V} {p : G.Walk u v} : w ∈ p.support ↔ ∃ (q : G.Walk u w) (r : G.Walk w v), p = q.append r := by classical constructor · exact fun h => ⟨_, _, (p.take_spec h).symm⟩ · rintro ⟨q, r, rfl⟩ simp only [mem_support_append_iff, end_mem_support, start_mem_support, or_self_iff] @[simp] theorem count_support_takeUntil_eq_one {u v w : V} (p : G.Walk v w) (h : u ∈ p.support) : (p.takeUntil u h).support.count u = 1 := by induction p · rw [mem_support_nil_iff] at h subst u simp! · cases h · simp! · simp! only split_ifs with h' <;> rw [eq_comm] at h' <;> subst_vars <;> simp! [*, List.count_cons] theorem count_edges_takeUntil_le_one {u v w : V} (p : G.Walk v w) (h : u ∈ p.support) (x : V) : (p.takeUntil u h).edges.count s(u, x) ≤ 1 := by induction' p with u' u' v' w' ha p' ih · rw [mem_support_nil_iff] at h subst u simp! · cases h · simp! · simp! only split_ifs with h' · subst h' simp · rw [edges_cons, List.count_cons] split_ifs with h'' · simp only [beq_iff_eq, Sym2.eq, Sym2.rel_iff', Prod.mk.injEq, Prod.swap_prod_mk] at h'' obtain ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩ := h'' · exact (h' rfl).elim · cases p' <;> simp! · apply ih @[simp] theorem takeUntil_copy {u v w v' w'} (p : G.Walk v w) (hv : v = v') (hw : w = w') (h : u ∈ (p.copy hv hw).support) : (p.copy hv hw).takeUntil u h = (p.takeUntil u (by subst_vars; exact h)).copy hv rfl := by subst_vars rfl @[simp] theorem dropUntil_copy {u v w v' w'} (p : G.Walk v w) (hv : v = v') (hw : w = w') (h : u ∈ (p.copy hv hw).support) : (p.copy hv hw).dropUntil u h = (p.dropUntil u (by subst_vars; exact h)).copy rfl hw := by subst_vars rfl theorem support_takeUntil_subset {u v w : V} (p : G.Walk v w) (h : u ∈ p.support) : (p.takeUntil u h).support ⊆ p.support := fun x hx => by rw [← take_spec p h, mem_support_append_iff] exact Or.inl hx theorem support_dropUntil_subset {u v w : V} (p : G.Walk v w) (h : u ∈ p.support) : (p.dropUntil u h).support ⊆ p.support := fun x hx => by rw [← take_spec p h, mem_support_append_iff] exact Or.inr hx theorem darts_takeUntil_subset {u v w : V} (p : G.Walk v w) (h : u ∈ p.support) : (p.takeUntil u h).darts ⊆ p.darts := fun x hx => by rw [← take_spec p h, darts_append, List.mem_append] exact Or.inl hx theorem darts_dropUntil_subset {u v w : V} (p : G.Walk v w) (h : u ∈ p.support) : (p.dropUntil u h).darts ⊆ p.darts := fun x hx => by rw [← take_spec p h, darts_append, List.mem_append] exact Or.inr hx theorem edges_takeUntil_subset {u v w : V} (p : G.Walk v w) (h : u ∈ p.support) : (p.takeUntil u h).edges ⊆ p.edges := List.map_subset _ (p.darts_takeUntil_subset h) theorem edges_dropUntil_subset {u v w : V} (p : G.Walk v w) (h : u ∈ p.support) : (p.dropUntil u h).edges ⊆ p.edges := List.map_subset _ (p.darts_dropUntil_subset h) theorem length_takeUntil_le {u v w : V} (p : G.Walk v w) (h : u ∈ p.support) : (p.takeUntil u h).length ≤ p.length := by have := congr_arg Walk.length (p.take_spec h) rw [length_append] at this exact Nat.le.intro this theorem length_dropUntil_le {u v w : V} (p : G.Walk v w) (h : u ∈ p.support) : (p.dropUntil u h).length ≤ p.length := by have := congr_arg Walk.length (p.take_spec h) rw [length_append, add_comm] at this exact Nat.le.intro this /-- Rotate a loop walk such that it is centered at the given vertex. -/ def rotate {u v : V} (c : G.Walk v v) (h : u ∈ c.support) : G.Walk u u := (c.dropUntil u h).append (c.takeUntil u h) @[simp] theorem support_rotate {u v : V} (c : G.Walk v v) (h : u ∈ c.support) : (c.rotate h).support.tail ~r c.support.tail := by simp only [rotate, tail_support_append] apply List.IsRotated.trans List.isRotated_append rw [← tail_support_append, take_spec] theorem rotate_darts {u v : V} (c : G.Walk v v) (h : u ∈ c.support) : (c.rotate h).darts ~r c.darts := by simp only [rotate, darts_append] apply List.IsRotated.trans List.isRotated_append rw [← darts_append, take_spec] theorem rotate_edges {u v : V} (c : G.Walk v v) (h : u ∈ c.support) : (c.rotate h).edges ~r c.edges := (rotate_darts c h).map _ end WalkDecomp /-- Given a set `S` and a walk `w` from `u` to `v` such that `u ∈ S` but `v ∉ S`, there exists a dart in the walk whose start is in `S` but whose end is not. -/ theorem exists_boundary_dart {u v : V} (p : G.Walk u v) (S : Set V) (uS : u ∈ S) (vS : v ∉ S) : ∃ d : G.Dart, d ∈ p.darts ∧ d.fst ∈ S ∧ d.snd ∉ S := by induction' p with _ x y w a p' ih · cases vS uS · by_cases h : y ∈ S · obtain ⟨d, hd, hcd⟩ := ih h vS exact ⟨d, List.Mem.tail _ hd, hcd⟩ · exact ⟨⟨(x, y), a⟩, List.Mem.head _, uS, h⟩ lemma getVert_tail {u v n} (p : G.Walk u v) (hnp: ¬ p.Nil) : (p.tail hnp).getVert n = p.getVert (n + 1) := p.notNilRec (fun _ _ ↦ by simp only [tail_cons, cons_getVert_succ]) hnp @[simp] lemma cons_sndOfNotNil (q : G.Walk v w) (hadj : G.Adj u v) : (q.cons hadj).sndOfNotNil not_nil_cons = v := by unfold sndOfNotNil; simp only [notNilRec_cons] lemma getVert_one (p : G.Walk u v) (hnp : ¬ p.Nil) : p.getVert 1 = p.sndOfNotNil hnp := p.notNilRec (fun _ _ ↦ by simp only [cons_getVert_succ, getVert_zero, cons_sndOfNotNil]) hnp /-- Given a walk `w` and a node in the support, there exists a natural `n`, such that given node is the `n`-th node (zero-indexed) in the walk. In addition, `n` is at most the length of the path. Due to the definition of `getVert` it would otherwise be legal to return a larger `n` for the last node. -/ theorem mem_support_iff_exists_getVert {u v w : V} {p : G.Walk v w} : u ∈ p.support ↔ ∃ n, p.getVert n = u ∧ n ≤ p.length := by constructor · intro h obtain ⟨q, r, hqr⟩ := SimpleGraph.Walk.mem_support_iff_exists_append.mp h use q.length rw [hqr] rw [Walk.getVert_append] simp only [lt_self_iff_false, ↓reduceIte, Nat.sub_self, getVert_zero, length_append, Nat.le_add_right, and_self] · rintro ⟨n, hn⟩ rw [SimpleGraph.Walk.mem_support_iff] by_cases h0 : n = 0 · rw [h0, getVert_zero] at hn left exact hn.1.symm · right have hnp : ¬ p.Nil := by rw [@nil_iff_length_eq] have : 1 ≤ p.length := by omega exact Nat.not_eq_zero_of_lt this rw [← tail_support_eq_support_tail _ hnp] rw [mem_support_iff_exists_getVert] use n - 1 simp only [Nat.sub_le_iff_le_add, length_tail_add_one, getVert_tail] have : n - 1 + 1 = n := by omega rwa [this] termination_by p.length end Walk /-! ### Mapping walks -/ namespace Walk variable {G G' G''} /-- Given a graph homomorphism, map walks to walks. -/ protected def map (f : G →g G') {u v : V} : G.Walk u v → G'.Walk (f u) (f v) | nil => nil | cons h p => cons (f.map_adj h) (p.map f) variable (f : G →g G') (f' : G' →g G'') {u v u' v' : V} (p : G.Walk u v) @[simp] theorem map_nil : (nil : G.Walk u u).map f = nil := rfl @[simp] theorem map_cons {w : V} (h : G.Adj w u) : (cons h p).map f = cons (f.map_adj h) (p.map f) := rfl @[simp] theorem map_copy (hu : u = u') (hv : v = v') : (p.copy hu hv).map f = (p.map f).copy (hu ▸ rfl) (hv ▸ rfl) := by subst_vars rfl @[simp] theorem map_id (p : G.Walk u v) : p.map Hom.id = p := by induction p with | nil => rfl | cons _ p' ih => simp [ih p'] @[simp] theorem map_map : (p.map f).map f' = p.map (f'.comp f) := by induction p with | nil => rfl | cons _ _ ih => simp [ih] /-- Unlike categories, for graphs vertex equality is an important notion, so needing to be able to work with equality of graph homomorphisms is a necessary evil. -/ theorem map_eq_of_eq {f : G →g G'} (f' : G →g G') (h : f = f') : p.map f = (p.map f').copy (h ▸ rfl) (h ▸ rfl) := by subst_vars rfl @[simp] theorem map_eq_nil_iff {p : G.Walk u u} : p.map f = nil ↔ p = nil := by cases p <;> simp @[simp] theorem length_map : (p.map f).length = p.length := by induction p <;> simp [*] theorem map_append {u v w : V} (p : G.Walk u v) (q : G.Walk v w) : (p.append q).map f = (p.map f).append (q.map f) := by induction p <;> simp [*] @[simp] theorem reverse_map : (p.map f).reverse = p.reverse.map f := by induction p <;> simp [map_append, *] @[simp] theorem support_map : (p.map f).support = p.support.map f := by induction p <;> simp [*] @[simp] theorem darts_map : (p.map f).darts = p.darts.map f.mapDart := by induction p <;> simp [*] @[simp] theorem edges_map : (p.map f).edges = p.edges.map (Sym2.map f) := by induction p with | nil => rfl | cons _ _ ih => simp only [Walk.map_cons, edges_cons, List.map_cons, Sym2.map_pair_eq, List.cons.injEq, true_and, ih] theorem map_injective_of_injective {f : G →g G'} (hinj : Function.Injective f) (u v : V) : Function.Injective (Walk.map f : G.Walk u v → G'.Walk (f u) (f v)) := by intro p p' h induction p with | nil => cases p' · rfl · simp at h | cons _ _ ih => cases p' with | nil => simp at h | cons _ _ => simp only [map_cons, cons.injEq] at h cases hinj h.1 simp only [cons.injEq, heq_iff_eq, true_and_iff] apply ih simpa using h.2 /-- The specialization of `SimpleGraph.Walk.map` for mapping walks to supergraphs. -/ abbrev mapLe {G G' : SimpleGraph V} (h : G ≤ G') {u v : V} (p : G.Walk u v) : G'.Walk u v := p.map (Hom.mapSpanningSubgraphs h) /-! ### Transferring between graphs -/ /-- The walk `p` transferred to lie in `H`, given that `H` contains its edges. -/ @[simp] protected def transfer {u v : V} (p : G.Walk u v) (H : SimpleGraph V) (h : ∀ e, e ∈ p.edges → e ∈ H.edgeSet) : H.Walk u v := match p with | nil => nil | cons' u v w _ p => cons (h s(u, v) (by simp)) (p.transfer H fun e he => h e (by simp [he])) variable {u v : V} (p : G.Walk u v) theorem transfer_self : p.transfer G p.edges_subset_edgeSet = p := by induction p <;> simp [*] variable {H : SimpleGraph V} theorem transfer_eq_map_of_le (hp) (GH : G ≤ H) : p.transfer H hp = p.map (SimpleGraph.Hom.mapSpanningSubgraphs GH) := by induction p <;> simp [*] @[simp] theorem edges_transfer (hp) : (p.transfer H hp).edges = p.edges := by induction p <;> simp [*] @[simp] theorem support_transfer (hp) : (p.transfer H hp).support = p.support := by induction p <;> simp [*] @[simp] theorem length_transfer (hp) : (p.transfer H hp).length = p.length := by induction p <;> simp [*] -- Porting note: this failed the simpNF linter since it was originally of the form -- `(p.transfer H hp).transfer K hp' = p.transfer K hp''` with `hp'` a function of `hp` and `hp'`. -- This was a mistake and it's corrected here. @[simp] theorem transfer_transfer (hp) {K : SimpleGraph V} (hp') : (p.transfer H hp).transfer K hp' = p.transfer K (p.edges_transfer hp ▸ hp') := by induction p with | nil => simp | cons _ _ ih => simp only [Walk.transfer, cons.injEq, heq_eq_eq, true_and] apply ih @[simp] theorem transfer_append {w : V} (q : G.Walk v w) (hpq) : (p.append q).transfer H hpq = (p.transfer H fun e he => hpq _ (by simp [he])).append (q.transfer H fun e he => hpq _ (by simp [he])) := by induction p with | nil => simp | cons _ _ ih => simp only [Walk.transfer, cons_append, cons.injEq, heq_eq_eq, true_and, ih] @[simp] theorem reverse_transfer (hp) : (p.transfer H hp).reverse = p.reverse.transfer H (by simp only [edges_reverse, List.mem_reverse]; exact hp) := by induction p with | nil => simp | cons _ _ ih => simp only [transfer_append, Walk.transfer, reverse_nil, reverse_cons, ih] end Walk /-! ## Deleting edges -/ namespace Walk variable {G} /-- Given a walk that avoids a set of edges, produce a walk in the graph with those edges deleted. -/ abbrev toDeleteEdges (s : Set (Sym2 V)) {v w : V} (p : G.Walk v w) (hp : ∀ e, e ∈ p.edges → ¬e ∈ s) : (G.deleteEdges s).Walk v w := p.transfer _ <| by simp only [edgeSet_deleteEdges, Set.mem_diff] exact fun e ep => ⟨edges_subset_edgeSet p ep, hp e ep⟩ @[simp] theorem toDeleteEdges_nil (s : Set (Sym2 V)) {v : V} (hp) : (Walk.nil : G.Walk v v).toDeleteEdges s hp = Walk.nil := rfl @[simp] theorem toDeleteEdges_cons (s : Set (Sym2 V)) {u v w : V} (h : G.Adj u v) (p : G.Walk v w) (hp) : (Walk.cons h p).toDeleteEdges s hp = Walk.cons (deleteEdges_adj.mpr ⟨h, hp _ (List.Mem.head _)⟩) (p.toDeleteEdges s fun _ he => hp _ <| List.Mem.tail _ he) := rfl variable {v w : V} /-- Given a walk that avoids an edge, create a walk in the subgraph with that edge deleted. This is an abbreviation for `SimpleGraph.Walk.toDeleteEdges`. -/ abbrev toDeleteEdge (e : Sym2 V) (p : G.Walk v w) (hp : e ∉ p.edges) : (G.deleteEdges {e}).Walk v w := p.toDeleteEdges {e} (fun e' => by contrapose!; simp (config := { contextual := true }) [hp]) @[simp] theorem map_toDeleteEdges_eq (s : Set (Sym2 V)) {p : G.Walk v w} (hp) : Walk.map (Hom.mapSpanningSubgraphs (G.deleteEdges_le s)) (p.toDeleteEdges s hp) = p := by rw [← transfer_eq_map_of_le, transfer_transfer, transfer_self] intros e rw [edges_transfer] apply edges_subset_edgeSet p end Walk end SimpleGraph
Combinatorics\SimpleGraph\Connectivity\Subgraph.lean
/- Copyright (c) 2023 Kyle Miller, Rémi Bottinelli. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller, Rémi Bottinelli -/ import Mathlib.Combinatorics.SimpleGraph.Path /-! # Connectivity of subgraphs and induced graphs ## Main definitions * `SimpleGraph.Subgraph.Preconnected` and `SimpleGraph.Subgraph.Connected` give subgraphs connectivity predicates via `SimpleGraph.subgraph.coe`. -/ namespace SimpleGraph universe u v variable {V : Type u} {V' : Type v} {G : SimpleGraph V} {G' : SimpleGraph V'} namespace Subgraph /-- A subgraph is preconnected if it is preconnected when coerced to be a simple graph. Note: This is a structure to make it so one can be precise about how dot notation resolves. -/ protected structure Preconnected (H : G.Subgraph) : Prop where protected coe : H.coe.Preconnected instance {H : G.Subgraph} : Coe H.Preconnected H.coe.Preconnected := ⟨Preconnected.coe⟩ instance {H : G.Subgraph} : CoeFun H.Preconnected (fun _ => ∀ u v : H.verts, H.coe.Reachable u v) := ⟨fun h => h.coe⟩ protected lemma preconnected_iff {H : G.Subgraph} : H.Preconnected ↔ H.coe.Preconnected := ⟨fun ⟨h⟩ => h, .mk⟩ /-- A subgraph is connected if it is connected when coerced to be a simple graph. Note: This is a structure to make it so one can be precise about how dot notation resolves. -/ protected structure Connected (H : G.Subgraph) : Prop where protected coe : H.coe.Connected instance {H : G.Subgraph} : Coe H.Connected H.coe.Connected := ⟨Connected.coe⟩ instance {H : G.Subgraph} : CoeFun H.Connected (fun _ => ∀ u v : H.verts, H.coe.Reachable u v) := ⟨fun h => h.coe⟩ protected lemma connected_iff' {H : G.Subgraph} : H.Connected ↔ H.coe.Connected := ⟨fun ⟨h⟩ => h, .mk⟩ protected lemma connected_iff {H : G.Subgraph} : H.Connected ↔ H.Preconnected ∧ H.verts.Nonempty := by rw [H.connected_iff', connected_iff, H.preconnected_iff, Set.nonempty_coe_sort] protected lemma Connected.preconnected {H : G.Subgraph} (h : H.Connected) : H.Preconnected := by rw [H.connected_iff] at h; exact h.1 protected lemma Connected.nonempty {H : G.Subgraph} (h : H.Connected) : H.verts.Nonempty := by rw [H.connected_iff] at h; exact h.2 theorem singletonSubgraph_connected {v : V} : (G.singletonSubgraph v).Connected := by refine ⟨⟨?_⟩⟩ rintro ⟨a, ha⟩ ⟨b, hb⟩ simp only [singletonSubgraph_verts, Set.mem_singleton_iff] at ha hb subst_vars rfl @[simp] theorem subgraphOfAdj_connected {v w : V} (hvw : G.Adj v w) : (G.subgraphOfAdj hvw).Connected := by refine ⟨⟨?_⟩⟩ rintro ⟨a, ha⟩ ⟨b, hb⟩ simp only [subgraphOfAdj_verts, Set.mem_insert_iff, Set.mem_singleton_iff] at ha hb obtain rfl | rfl := ha <;> obtain rfl | rfl := hb <;> first | rfl | (apply Adj.reachable; simp) lemma top_induce_pair_connected_of_adj {u v : V} (huv : G.Adj u v) : ((⊤ : G.Subgraph).induce {u, v}).Connected := by rw [← subgraphOfAdj_eq_induce huv] exact subgraphOfAdj_connected huv @[mono] protected lemma Connected.mono {H H' : G.Subgraph} (hle : H ≤ H') (hv : H.verts = H'.verts) (h : H.Connected) : H'.Connected := by rw [← Subgraph.copy_eq H' H.verts hv H'.Adj rfl] refine ⟨h.coe.mono ?_⟩ rintro ⟨v, hv⟩ ⟨w, hw⟩ hvw exact hle.2 hvw protected lemma Connected.mono' {H H' : G.Subgraph} (hle : ∀ v w, H.Adj v w → H'.Adj v w) (hv : H.verts = H'.verts) (h : H.Connected) : H'.Connected := by exact h.mono ⟨hv.le, hle⟩ hv protected lemma Connected.sup {H K : G.Subgraph} (hH : H.Connected) (hK : K.Connected) (hn : (H ⊓ K).verts.Nonempty) : (H ⊔ K).Connected := by rw [Subgraph.connected_iff', connected_iff_exists_forall_reachable] obtain ⟨u, hu, hu'⟩ := hn exists ⟨u, Or.inl hu⟩ rintro ⟨v, (hv|hv)⟩ · exact Reachable.map (Subgraph.inclusion (le_sup_left : H ≤ H ⊔ K)) (hH ⟨u, hu⟩ ⟨v, hv⟩) · exact Reachable.map (Subgraph.inclusion (le_sup_right : K ≤ H ⊔ K)) (hK ⟨u, hu'⟩ ⟨v, hv⟩) end Subgraph /-! ### Walks as subgraphs -/ namespace Walk variable {u v w : V} /-- The subgraph consisting of the vertices and edges of the walk. -/ @[simp] protected def toSubgraph {u v : V} : G.Walk u v → G.Subgraph | nil => G.singletonSubgraph u | cons h p => G.subgraphOfAdj h ⊔ p.toSubgraph theorem toSubgraph_cons_nil_eq_subgraphOfAdj (h : G.Adj u v) : (cons h nil).toSubgraph = G.subgraphOfAdj h := by simp theorem mem_verts_toSubgraph (p : G.Walk u v) : w ∈ p.toSubgraph.verts ↔ w ∈ p.support := by induction' p with _ x y z h p' ih · simp · have : w = y ∨ w ∈ p'.support ↔ w ∈ p'.support := ⟨by rintro (rfl | h) <;> simp [*], by simp (config := { contextual := true })⟩ simp [ih, or_assoc, this] lemma start_mem_verts_toSubgraph (p : G.Walk u v) : u ∈ p.toSubgraph.verts := by simp [mem_verts_toSubgraph] lemma end_mem_verts_toSubgraph (p : G.Walk u v) : v ∈ p.toSubgraph.verts := by simp [mem_verts_toSubgraph] @[simp] theorem verts_toSubgraph (p : G.Walk u v) : p.toSubgraph.verts = { w | w ∈ p.support } := Set.ext fun _ => p.mem_verts_toSubgraph theorem mem_edges_toSubgraph (p : G.Walk u v) {e : Sym2 V} : e ∈ p.toSubgraph.edgeSet ↔ e ∈ p.edges := by induction p <;> simp [*] @[simp] theorem edgeSet_toSubgraph (p : G.Walk u v) : p.toSubgraph.edgeSet = { e | e ∈ p.edges } := Set.ext fun _ => p.mem_edges_toSubgraph @[simp] theorem toSubgraph_append (p : G.Walk u v) (q : G.Walk v w) : (p.append q).toSubgraph = p.toSubgraph ⊔ q.toSubgraph := by induction p <;> simp [*, sup_assoc] @[simp] theorem toSubgraph_reverse (p : G.Walk u v) : p.reverse.toSubgraph = p.toSubgraph := by induction p with | nil => simp | cons _ _ _ => simp only [*, Walk.toSubgraph, reverse_cons, toSubgraph_append, subgraphOfAdj_symm] rw [sup_comm] congr ext <;> simp [-Set.bot_eq_empty] @[simp] theorem toSubgraph_rotate [DecidableEq V] (c : G.Walk v v) (h : u ∈ c.support) : (c.rotate h).toSubgraph = c.toSubgraph := by rw [rotate, toSubgraph_append, sup_comm, ← toSubgraph_append, take_spec] @[simp] theorem toSubgraph_map (f : G →g G') (p : G.Walk u v) : (p.map f).toSubgraph = p.toSubgraph.map f := by induction p <;> simp [*, Subgraph.map_sup] @[simp] theorem finite_neighborSet_toSubgraph (p : G.Walk u v) : (p.toSubgraph.neighborSet w).Finite := by induction p with | nil => rw [Walk.toSubgraph, neighborSet_singletonSubgraph] apply Set.toFinite | cons ha _ ih => rw [Walk.toSubgraph, Subgraph.neighborSet_sup] refine Set.Finite.union ?_ ih refine Set.Finite.subset ?_ (neighborSet_subgraphOfAdj_subset ha) apply Set.toFinite lemma toSubgraph_le_induce_support (p : G.Walk u v) : p.toSubgraph ≤ (⊤ : G.Subgraph).induce {v | v ∈ p.support} := by convert Subgraph.le_induce_top_verts exact p.verts_toSubgraph.symm theorem toSubgraph_adj_getVert {u v} (w : G.Walk u v) {i : ℕ} (hi : i < w.length) : w.toSubgraph.Adj (w.getVert i) (w.getVert (i + 1)) := by induction w generalizing i with | nil => cases hi | cons hxy i' ih => cases i · simp only [Walk.toSubgraph, Walk.getVert_zero, zero_add, cons_getVert_succ, Subgraph.sup_adj, subgraphOfAdj_adj, true_or] · simp only [Walk.toSubgraph, cons_getVert_succ, Subgraph.sup_adj, subgraphOfAdj_adj, Sym2.eq, Sym2.rel_iff', Prod.mk.injEq, Prod.swap_prod_mk] right exact ih (Nat.succ_lt_succ_iff.mp hi) theorem toSubgraph_adj_iff {u v u' v'} (w : G.Walk u v) : w.toSubgraph.Adj u' v' ↔ ∃ i, s(w.getVert i, w.getVert (i + 1)) = s(u', v') ∧ i < w.length := by constructor · intro hadj unfold Walk.toSubgraph at hadj match w with | .nil => simp only [singletonSubgraph_adj, Pi.bot_apply, Prop.bot_eq_false] at hadj | .cons h p => simp only [Subgraph.sup_adj, subgraphOfAdj_adj, Sym2.eq, Sym2.rel_iff', Prod.mk.injEq, Prod.swap_prod_mk] at hadj cases hadj with | inl hl => use 0 simp only [Walk.getVert_zero, zero_add, cons_getVert_succ] refine ⟨?_, by simp only [length_cons, Nat.zero_lt_succ]⟩ simp only [Sym2.eq, Sym2.rel_iff', Prod.mk.injEq, Prod.swap_prod_mk] cases hl with | inl h1 => left; exact ⟨h1.1, h1.2⟩ | inr h2 => right; exact ⟨h2.1, h2.2⟩ | inr hr => obtain ⟨i, hi⟩ := (toSubgraph_adj_iff _).mp hr use i + 1 simp only [cons_getVert_succ] constructor · exact hi.1 · simp only [Walk.length_cons, add_lt_add_iff_right, Nat.add_lt_add_right hi.2 1] · rintro ⟨i, hi⟩ rw [← Subgraph.mem_edgeSet, ← hi.1, Subgraph.mem_edgeSet] exact toSubgraph_adj_getVert _ hi.2 end Walk namespace Subgraph lemma _root_.SimpleGraph.Walk.toSubgraph_connected {u v : V} (p : G.Walk u v) : p.toSubgraph.Connected := by induction p with | nil => apply singletonSubgraph_connected | @cons _ w _ h p ih => apply (subgraphOfAdj_connected h).sup ih exists w simp lemma induce_union_connected {H : G.Subgraph} {s t : Set V} (sconn : (H.induce s).Connected) (tconn : (H.induce t).Connected) (sintert : (s ⊓ t).Nonempty) : (H.induce (s ∪ t)).Connected := by refine (sconn.sup tconn sintert).mono ?_ ?_ · apply le_induce_union · simp lemma Connected.adj_union {H K : G.Subgraph} (Hconn : H.Connected) (Kconn : K.Connected) {u v : V} (uH : u ∈ H.verts) (vK : v ∈ K.verts) (huv : G.Adj u v) : ((⊤ : G.Subgraph).induce {u, v} ⊔ H ⊔ K).Connected := by refine ((top_induce_pair_connected_of_adj huv).sup Hconn ?_).sup Kconn ?_ · exact ⟨u, by simp [uH]⟩ · exact ⟨v, by simp [vK]⟩ lemma preconnected_iff_forall_exists_walk_subgraph (H : G.Subgraph) : H.Preconnected ↔ ∀ {u v}, u ∈ H.verts → v ∈ H.verts → ∃ p : G.Walk u v, p.toSubgraph ≤ H := by constructor · intro hc u v hu hv refine (hc ⟨_, hu⟩ ⟨_, hv⟩).elim fun p => ?_ exists p.map (Subgraph.hom _) simp [coeSubgraph_le] · intro hw rw [Subgraph.preconnected_iff] rintro ⟨u, hu⟩ ⟨v, hv⟩ obtain ⟨p, h⟩ := hw hu hv exact Reachable.map (Subgraph.inclusion h) (p.toSubgraph_connected ⟨_, p.start_mem_verts_toSubgraph⟩ ⟨_, p.end_mem_verts_toSubgraph⟩) lemma connected_iff_forall_exists_walk_subgraph (H : G.Subgraph) : H.Connected ↔ H.verts.Nonempty ∧ ∀ {u v}, u ∈ H.verts → v ∈ H.verts → ∃ p : G.Walk u v, p.toSubgraph ≤ H := by rw [H.connected_iff, preconnected_iff_forall_exists_walk_subgraph, and_comm] end Subgraph section induced_subgraphs lemma connected_induce_iff {s : Set V} : (G.induce s).Connected ↔ ((⊤ : G.Subgraph).induce s).Connected := by rw [induce_eq_coe_induce_top, ← Subgraph.connected_iff'] lemma induce_union_connected {s t : Set V} (sconn : (G.induce s).Connected) (tconn : (G.induce t).Connected) (sintert : (s ∩ t).Nonempty) : (G.induce (s ∪ t)).Connected := by rw [connected_induce_iff] at sconn tconn ⊢ exact Subgraph.induce_union_connected sconn tconn sintert lemma induce_pair_connected_of_adj {u v : V} (huv : G.Adj u v) : (G.induce {u, v}).Connected := by rw [connected_induce_iff] exact Subgraph.top_induce_pair_connected_of_adj huv lemma Subgraph.Connected.induce_verts {H : G.Subgraph} (h : H.Connected) : (G.induce H.verts).Connected := by rw [connected_induce_iff] exact h.mono le_induce_top_verts (by exact rfl) lemma Walk.connected_induce_support {u v : V} (p : G.Walk u v) : (G.induce {v | v ∈ p.support}).Connected := by rw [← p.verts_toSubgraph] exact p.toSubgraph_connected.induce_verts lemma induce_connected_adj_union {v w : V} {s t : Set V} (sconn : (G.induce s).Connected) (tconn : (G.induce t).Connected) (hv : v ∈ s) (hw : w ∈ t) (ha : G.Adj v w) : (G.induce (s ∪ t)).Connected := by rw [connected_induce_iff] at sconn tconn ⊢ apply (sconn.adj_union tconn hv hw ha).mono · simp only [Set.mem_singleton_iff, sup_le_iff, Subgraph.le_induce_union_left, Subgraph.le_induce_union_right, and_true, ← Subgraph.subgraphOfAdj_eq_induce ha] apply subgraphOfAdj_le_of_adj simp [hv, hw, ha] · simp only [Set.mem_singleton_iff, sup_le_iff, Subgraph.verts_sup, Subgraph.induce_verts] rw [Set.union_assoc] simp [Set.insert_subset_iff, Set.singleton_subset_iff, hv, hw] lemma induce_connected_of_patches {s : Set V} (u : V) (hu : u ∈ s) (patches : ∀ {v}, v ∈ s → ∃ s' ⊆ s, ∃ (hu' : u ∈ s') (hv' : v ∈ s'), (G.induce s').Reachable ⟨u, hu'⟩ ⟨v, hv'⟩) : (G.induce s).Connected := by rw [connected_iff_exists_forall_reachable] refine ⟨⟨u, hu⟩, ?_⟩ rintro ⟨v, hv⟩ obtain ⟨sv, svs, hu', hv', uv⟩ := patches hv exact uv.map (induceHomOfLE _ svs).toHom lemma induce_sUnion_connected_of_pairwise_not_disjoint {S : Set (Set V)} (Sn : S.Nonempty) (Snd : ∀ {s t}, s ∈ S → t ∈ S → (s ∩ t).Nonempty) (Sc : ∀ {s}, s ∈ S → (G.induce s).Connected) : (G.induce (⋃₀ S)).Connected := by obtain ⟨s, sS⟩ := Sn obtain ⟨v, vs⟩ := (Sc sS).nonempty apply G.induce_connected_of_patches _ (Set.subset_sUnion_of_mem sS vs) rintro w hw simp only [Set.mem_sUnion, exists_prop] at hw obtain ⟨t, tS, wt⟩ := hw refine ⟨s ∪ t, Set.union_subset (Set.subset_sUnion_of_mem sS) (Set.subset_sUnion_of_mem tS), Or.inl vs, Or.inr wt, induce_union_connected (Sc sS) (Sc tS) (Snd sS tS) _ _⟩ lemma extend_finset_to_connected (Gpc : G.Preconnected) {t : Finset V} (tn : t.Nonempty) : ∃ (t' : Finset V), t ⊆ t' ∧ (G.induce (t' : Set V)).Connected := by classical obtain ⟨u, ut⟩ := tn refine ⟨t.biUnion (fun v => (Gpc u v).some.support.toFinset), fun v vt => ?_, ?_⟩ · simp only [Finset.mem_biUnion, List.mem_toFinset, exists_prop] exact ⟨v, vt, Walk.end_mem_support _⟩ · apply G.induce_connected_of_patches u · simp only [Finset.coe_biUnion, Finset.mem_coe, List.coe_toFinset, Set.mem_iUnion, Set.mem_setOf_eq, Walk.start_mem_support, exists_prop, and_true] exact ⟨u, ut⟩ intros v hv simp only [Finset.mem_coe, Finset.mem_biUnion, List.mem_toFinset, exists_prop] at hv obtain ⟨w, wt, hw⟩ := hv refine ⟨{x | x ∈ (Gpc u w).some.support}, ?_, ?_⟩ · simp only [Finset.coe_biUnion, Finset.mem_coe, List.coe_toFinset] exact fun x xw => Set.mem_iUnion₂.mpr ⟨w,wt,xw⟩ · simp only [Set.mem_setOf_eq, Walk.start_mem_support, exists_true_left] refine ⟨hw, Walk.connected_induce_support _ _ _⟩ end induced_subgraphs end SimpleGraph
Combinatorics\SimpleGraph\Connectivity\WalkCounting.lean
/- Copyright (c) 2021 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import Mathlib.Algebra.BigOperators.Ring.Nat import Mathlib.Combinatorics.SimpleGraph.Path import Mathlib.Combinatorics.SimpleGraph.Subgraph import Mathlib.SetTheory.Cardinal.Finite /-! # Counting walks of a given length ## Main definitions - `walkLengthTwoEquivCommonNeighbors`: bijective correspondence between walks of length two from `u` to `v` and common neighbours of `u` and `v`. Note that `u` and `v` may be the same. - `finsetWalkLength`: the `Finset` of length-`n` walks from `u` to `v`. This is used to give `{p : G.walk u v | p.length = n}` a `Fintype` instance, and it can also be useful as a recursive description of this set when `V` is finite. TODO: should this be extended further? -/ open Function universe u v w namespace SimpleGraph variable {V : Type u} {V' : Type v} {V'' : Type w} variable (G : SimpleGraph V) (G' : SimpleGraph V') (G'' : SimpleGraph V'') /-! ### Walks of a given length -/ section WalkCounting theorem set_walk_self_length_zero_eq (u : V) : {p : G.Walk u u | p.length = 0} = {Walk.nil} := by ext p simp theorem set_walk_length_zero_eq_of_ne {u v : V} (h : u ≠ v) : {p : G.Walk u v | p.length = 0} = ∅ := by ext p simp only [Set.mem_setOf_eq, Set.mem_empty_iff_false, iff_false_iff] exact fun h' => absurd (Walk.eq_of_length_eq_zero h') h theorem set_walk_length_succ_eq (u v : V) (n : ℕ) : {p : G.Walk u v | p.length = n.succ} = ⋃ (w : V) (h : G.Adj u w), Walk.cons h '' {p' : G.Walk w v | p'.length = n} := by ext p cases' p with _ _ w _ huw pwv · simp [eq_comm] · simp only [Nat.succ_eq_add_one, Set.mem_setOf_eq, Walk.length_cons, add_left_inj, Set.mem_iUnion, Set.mem_image, exists_prop] constructor · rintro rfl exact ⟨w, huw, pwv, rfl, rfl⟩ · rintro ⟨w, huw, pwv, rfl, rfl, rfl⟩ rfl variable [DecidableEq V] /-- Walks of length two from `u` to `v` correspond bijectively to common neighbours of `u` and `v`. Note that `u` and `v` may be the same. -/ @[simps] def walkLengthTwoEquivCommonNeighbors (u v : V) : {p : G.Walk u v // p.length = 2} ≃ G.commonNeighbors u v where toFun p := ⟨p.val.getVert 1, match p with | ⟨.cons _ (.cons _ .nil), hp⟩ => ⟨‹G.Adj u _›, ‹G.Adj _ v›.symm⟩⟩ invFun w := ⟨w.prop.1.toWalk.concat w.prop.2.symm, rfl⟩ left_inv | ⟨.cons _ (.cons _ .nil), hp⟩ => by rfl right_inv _ := rfl section LocallyFinite variable [LocallyFinite G] /-- The `Finset` of length-`n` walks from `u` to `v`. This is used to give `{p : G.walk u v | p.length = n}` a `Fintype` instance, and it can also be useful as a recursive description of this set when `V` is finite. See `SimpleGraph.coe_finsetWalkLength_eq` for the relationship between this `Finset` and the set of length-`n` walks. -/ def finsetWalkLength (n : ℕ) (u v : V) : Finset (G.Walk u v) := match n with | 0 => if h : u = v then by subst u exact {Walk.nil} else ∅ | n + 1 => Finset.univ.biUnion fun (w : G.neighborSet u) => (finsetWalkLength n w v).map ⟨fun p => Walk.cons w.property p, fun _ _ => by simp⟩ theorem coe_finsetWalkLength_eq (n : ℕ) (u v : V) : (G.finsetWalkLength n u v : Set (G.Walk u v)) = {p : G.Walk u v | p.length = n} := by induction' n with n ih generalizing u v · obtain rfl | huv := eq_or_ne u v <;> simp [finsetWalkLength, set_walk_length_zero_eq_of_ne, *] · simp only [finsetWalkLength, set_walk_length_succ_eq, Finset.coe_biUnion, Finset.mem_coe, Finset.mem_univ, Set.iUnion_true] ext p simp only [mem_neighborSet, Finset.coe_map, Embedding.coeFn_mk, Set.iUnion_coe_set, Set.mem_iUnion, Set.mem_image, Finset.mem_coe, Set.mem_setOf_eq] congr! rename_i w _ q have := Set.ext_iff.mp (ih w v) q simp only [Finset.mem_coe, Set.mem_setOf_eq] at this rw [← this] variable {G} theorem Walk.mem_finsetWalkLength_iff_length_eq {n : ℕ} {u v : V} (p : G.Walk u v) : p ∈ G.finsetWalkLength n u v ↔ p.length = n := Set.ext_iff.mp (G.coe_finsetWalkLength_eq n u v) p variable (G) instance fintypeSetWalkLength (u v : V) (n : ℕ) : Fintype {p : G.Walk u v | p.length = n} := Fintype.ofFinset (G.finsetWalkLength n u v) fun p => by rw [← Finset.mem_coe, coe_finsetWalkLength_eq] instance fintypeSubtypeWalkLength (u v : V) (n : ℕ) : Fintype {p : G.Walk u v // p.length = n} := fintypeSetWalkLength G u v n theorem set_walk_length_toFinset_eq (n : ℕ) (u v : V) : {p : G.Walk u v | p.length = n}.toFinset = G.finsetWalkLength n u v := by ext p simp [← coe_finsetWalkLength_eq] /- See `SimpleGraph.adjMatrix_pow_apply_eq_card_walk` for the cardinality in terms of the `n`th power of the adjacency matrix. -/ theorem card_set_walk_length_eq (u v : V) (n : ℕ) : Fintype.card {p : G.Walk u v | p.length = n} = (G.finsetWalkLength n u v).card := Fintype.card_ofFinset (G.finsetWalkLength n u v) fun p => by rw [← Finset.mem_coe, coe_finsetWalkLength_eq] instance fintypeSetPathLength (u v : V) (n : ℕ) : Fintype {p : G.Walk u v | p.IsPath ∧ p.length = n} := Fintype.ofFinset ((G.finsetWalkLength n u v).filter Walk.IsPath) <| by simp [Walk.mem_finsetWalkLength_iff_length_eq, and_comm] end LocallyFinite section Finite variable [Fintype V] [DecidableRel G.Adj] theorem reachable_iff_exists_finsetWalkLength_nonempty (u v : V) : G.Reachable u v ↔ ∃ n : Fin (Fintype.card V), (G.finsetWalkLength n u v).Nonempty := by constructor · intro r refine r.elim_path fun p => ?_ refine ⟨⟨_, p.isPath.length_lt⟩, p, ?_⟩ simp [Walk.mem_finsetWalkLength_iff_length_eq] · rintro ⟨_, p, _⟩ exact ⟨p⟩ instance : DecidableRel G.Reachable := fun u v => decidable_of_iff' _ (reachable_iff_exists_finsetWalkLength_nonempty G u v) instance : Fintype G.ConnectedComponent := @Quotient.fintype _ _ G.reachableSetoid (inferInstance : DecidableRel G.Reachable) instance : Decidable G.Preconnected := inferInstanceAs <| Decidable (∀ u v, G.Reachable u v) instance : Decidable G.Connected := by rw [connected_iff, ← Finset.univ_nonempty_iff] infer_instance instance instDecidableMemSupp (c : G.ConnectedComponent) (v : V) : Decidable (v ∈ c.supp) := c.recOn (fun w ↦ decidable_of_iff (G.Reachable v w) $ by simp) (fun _ _ _ _ ↦ Subsingleton.elim _ _) lemma odd_card_iff_odd_components : Odd (Nat.card V) ↔ Odd (Nat.card ({(c : ConnectedComponent G) | Odd (Nat.card c.supp)})) := by rw [Nat.card_eq_fintype_card] simp only [← (set_fintype_card_eq_univ_iff _).mpr G.iUnion_connectedComponentSupp, ConnectedComponent.mem_supp_iff, Fintype.card_subtype_compl, ← Set.toFinset_card, Set.toFinset_iUnion ConnectedComponent.supp] rw [Finset.card_biUnion (fun x _ y _ hxy ↦ Set.disjoint_toFinset.mpr (pairwise_disjoint_supp_connectedComponent _ hxy))] simp_rw [Set.toFinset_card, ← Nat.card_eq_fintype_card] rw [Nat.card_eq_fintype_card, Fintype.card_ofFinset] exact (Finset.odd_sum_iff_odd_card_odd (fun x : G.ConnectedComponent ↦ Nat.card x.supp)) end Finite end WalkCounting end SimpleGraph
Combinatorics\SimpleGraph\Ends\Defs.lean
/- Copyright (c) 2022 Anand Rao, Rémi Bottinelli. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anand Rao, Rémi Bottinelli -/ import Mathlib.CategoryTheory.CofilteredSystem import Mathlib.Combinatorics.SimpleGraph.Path import Mathlib.Data.Finite.Set /-! # Ends This file contains a definition of the ends of a simple graph, as sections of the inverse system assigning, to each finite set of vertices, the connected components of its complement. -/ universe u variable {V : Type u} (G : SimpleGraph V) (K L L' M : Set V) namespace SimpleGraph /-- The components outside a given set of vertices `K` -/ abbrev ComponentCompl := (G.induce Kᶜ).ConnectedComponent variable {G} {K L M} /-- The connected component of `v` in `G.induce Kᶜ`. -/ abbrev componentComplMk (G : SimpleGraph V) {v : V} (vK : v ∉ K) : G.ComponentCompl K := connectedComponentMk (G.induce Kᶜ) ⟨v, vK⟩ /-- The set of vertices of `G` making up the connected component `C` -/ def ComponentCompl.supp (C : G.ComponentCompl K) : Set V := { v : V | ∃ h : v ∉ K, G.componentComplMk h = C } @[ext] theorem ComponentCompl.supp_injective : Function.Injective (ComponentCompl.supp : G.ComponentCompl K → Set V) := by refine ConnectedComponent.ind₂ ?_ rintro ⟨v, hv⟩ ⟨w, hw⟩ h simp only [Set.ext_iff, ConnectedComponent.eq, Set.mem_setOf_eq, ComponentCompl.supp] at h ⊢ exact ((h v).mp ⟨hv, Reachable.refl _⟩).choose_spec theorem ComponentCompl.supp_inj {C D : G.ComponentCompl K} : C.supp = D.supp ↔ C = D := ComponentCompl.supp_injective.eq_iff instance ComponentCompl.setLike : SetLike (G.ComponentCompl K) V where coe := ComponentCompl.supp coe_injective' _ _ := ComponentCompl.supp_inj.mp @[simp] theorem ComponentCompl.mem_supp_iff {v : V} {C : ComponentCompl G K} : v ∈ C ↔ ∃ vK : v ∉ K, G.componentComplMk vK = C := Iff.rfl theorem componentComplMk_mem (G : SimpleGraph V) {v : V} (vK : v ∉ K) : v ∈ G.componentComplMk vK := ⟨vK, rfl⟩ theorem componentComplMk_eq_of_adj (G : SimpleGraph V) {v w : V} (vK : v ∉ K) (wK : w ∉ K) (a : G.Adj v w) : G.componentComplMk vK = G.componentComplMk wK := by rw [ConnectedComponent.eq] apply Adj.reachable exact a /-- In an infinite graph, the set of components out of a finite set is nonempty. -/ instance componentCompl_nonempty_of_infinite (G : SimpleGraph V) [Infinite V] (K : Finset V) : Nonempty (G.ComponentCompl K) := let ⟨_, kK⟩ := K.finite_toSet.infinite_compl.nonempty ⟨componentComplMk _ kK⟩ namespace ComponentCompl /-- A `ComponentCompl` specialization of `Quot.lift`, where soundness has to be proved only for adjacent vertices. -/ protected def lift {β : Sort*} (f : ∀ ⦃v⦄ (_ : v ∉ K), β) (h : ∀ ⦃v w⦄ (hv : v ∉ K) (hw : w ∉ K), G.Adj v w → f hv = f hw) : G.ComponentCompl K → β := ConnectedComponent.lift (fun vv => f vv.prop) fun v w p => by induction' p with _ u v w a q ih · rintro _ rfl · rintro h' exact (h u.prop v.prop a).trans (ih h'.of_cons) @[elab_as_elim] -- Porting note: added protected theorem ind {β : G.ComponentCompl K → Prop} (f : ∀ ⦃v⦄ (hv : v ∉ K), β (G.componentComplMk hv)) : ∀ C : G.ComponentCompl K, β C := by apply ConnectedComponent.ind exact fun ⟨v, vnK⟩ => f vnK /-- The induced graph on the vertices `C`. -/ protected abbrev coeGraph (C : ComponentCompl G K) : SimpleGraph C := G.induce (C : Set V) theorem coe_inj {C D : G.ComponentCompl K} : (C : Set V) = (D : Set V) ↔ C = D := SetLike.coe_set_eq @[simp] protected theorem nonempty (C : G.ComponentCompl K) : (C : Set V).Nonempty := C.ind fun v vnK => ⟨v, vnK, rfl⟩ protected theorem exists_eq_mk (C : G.ComponentCompl K) : ∃ (v : _) (h : v ∉ K), G.componentComplMk h = C := C.nonempty protected theorem disjoint_right (C : G.ComponentCompl K) : Disjoint K C := by rw [Set.disjoint_iff] exact fun v ⟨vK, vC⟩ => vC.choose vK theorem not_mem_of_mem {C : G.ComponentCompl K} {c : V} (cC : c ∈ C) : c ∉ K := fun cK => Set.disjoint_iff.mp C.disjoint_right ⟨cK, cC⟩ protected theorem pairwise_disjoint : Pairwise fun C D : G.ComponentCompl K => Disjoint (C : Set V) (D : Set V) := by rintro C D ne rw [Set.disjoint_iff] exact fun u ⟨uC, uD⟩ => ne (uC.choose_spec.symm.trans uD.choose_spec) /-- Any vertex adjacent to a vertex of `C` and not lying in `K` must lie in `C`. -/ theorem mem_of_adj : ∀ {C : G.ComponentCompl K} (c d : V), c ∈ C → d ∉ K → G.Adj c d → d ∈ C := fun {C} c d ⟨cnK, h⟩ dnK cd => ⟨dnK, by rw [← h, ConnectedComponent.eq] exact Adj.reachable cd.symm⟩ /-- Assuming `G` is preconnected and `K` not empty, given any connected component `C` outside of `K`, there exists a vertex `k ∈ K` adjacent to a vertex `v ∈ C`. -/ theorem exists_adj_boundary_pair (Gc : G.Preconnected) (hK : K.Nonempty) : ∀ C : G.ComponentCompl K, ∃ ck : V × V, ck.1 ∈ C ∧ ck.2 ∈ K ∧ G.Adj ck.1 ck.2 := by refine ComponentCompl.ind fun v vnK => ?_ let C : G.ComponentCompl K := G.componentComplMk vnK let dis := Set.disjoint_iff.mp C.disjoint_right by_contra! h suffices Set.univ = (C : Set V) by exact dis ⟨hK.choose_spec, this ▸ Set.mem_univ hK.some⟩ symm rw [Set.eq_univ_iff_forall] rintro u by_contra unC obtain ⟨p⟩ := Gc v u obtain ⟨⟨⟨x, y⟩, xy⟩, -, xC, ynC⟩ := p.exists_boundary_dart (C : Set V) (G.componentComplMk_mem vnK) unC exact ynC (mem_of_adj x y xC (fun yK : y ∈ K => h ⟨x, y⟩ xC yK xy) xy) /-- If `K ⊆ L`, the components outside of `L` are all contained in a single component outside of `K`. -/ abbrev hom (h : K ⊆ L) (C : G.ComponentCompl L) : G.ComponentCompl K := C.map <| induceHom Hom.id <| Set.compl_subset_compl.2 h theorem subset_hom (C : G.ComponentCompl L) (h : K ⊆ L) : (C : Set V) ⊆ (C.hom h : Set V) := by rintro c ⟨cL, rfl⟩ exact ⟨fun h' => cL (h h'), rfl⟩ theorem _root_.SimpleGraph.componentComplMk_mem_hom (G : SimpleGraph V) {v : V} (vK : v ∉ K) (h : L ⊆ K) : v ∈ (G.componentComplMk vK).hom h := subset_hom (G.componentComplMk vK) h (G.componentComplMk_mem vK) theorem hom_eq_iff_le (C : G.ComponentCompl L) (h : K ⊆ L) (D : G.ComponentCompl K) : C.hom h = D ↔ (C : Set V) ⊆ (D : Set V) := ⟨fun h' => h' ▸ C.subset_hom h, C.ind fun _ vnL vD => (vD ⟨vnL, rfl⟩).choose_spec⟩ theorem hom_eq_iff_not_disjoint (C : G.ComponentCompl L) (h : K ⊆ L) (D : G.ComponentCompl K) : C.hom h = D ↔ ¬Disjoint (C : Set V) (D : Set V) := by rw [Set.not_disjoint_iff] constructor · rintro rfl refine C.ind fun x xnL => ?_ exact ⟨x, ⟨xnL, rfl⟩, ⟨fun xK => xnL (h xK), rfl⟩⟩ · refine C.ind fun x xnL => ?_ rintro ⟨x, ⟨_, e₁⟩, _, rfl⟩ rw [← e₁] rfl theorem hom_refl (C : G.ComponentCompl L) : C.hom (subset_refl L) = C := by change C.map _ = C erw [induceHom_id G Lᶜ, ConnectedComponent.map_id] theorem hom_trans (C : G.ComponentCompl L) (h : K ⊆ L) (h' : M ⊆ K) : C.hom (h'.trans h) = (C.hom h).hom h' := by change C.map _ = (C.map _).map _ erw [ConnectedComponent.map_comp, induceHom_comp] rfl theorem hom_mk {v : V} (vnL : v ∉ L) (h : K ⊆ L) : (G.componentComplMk vnL).hom h = G.componentComplMk (Set.not_mem_subset h vnL) := rfl theorem hom_infinite (C : G.ComponentCompl L) (h : K ⊆ L) (Cinf : (C : Set V).Infinite) : (C.hom h : Set V).Infinite := Set.Infinite.mono (C.subset_hom h) Cinf theorem infinite_iff_in_all_ranges {K : Finset V} (C : G.ComponentCompl K) : C.supp.Infinite ↔ ∀ (L) (h : K ⊆ L), ∃ D : G.ComponentCompl L, D.hom h = C := by classical constructor · rintro Cinf L h obtain ⟨v, ⟨vK, rfl⟩, vL⟩ := Set.Infinite.nonempty (Set.Infinite.diff Cinf L.finite_toSet) exact ⟨componentComplMk _ vL, rfl⟩ · rintro h Cfin obtain ⟨D, e⟩ := h (K ∪ Cfin.toFinset) Finset.subset_union_left obtain ⟨v, vD⟩ := D.nonempty let Ddis := D.disjoint_right simp_rw [Finset.coe_union, Set.Finite.coe_toFinset, Set.disjoint_union_left, Set.disjoint_iff] at Ddis exact Ddis.right ⟨(ComponentCompl.hom_eq_iff_le _ _ _).mp e vD, vD⟩ end ComponentCompl /-- For a locally finite preconnected graph, the number of components outside of any finite set is finite. -/ instance componentCompl_finite [LocallyFinite G] [Gpc : Fact G.Preconnected] (K : Finset V) : Finite (G.ComponentCompl K) := by classical rcases K.eq_empty_or_nonempty with rfl | h -- If K is empty, then removing K doesn't change the graph, which is connected, hence has a -- single connected component · dsimp [ComponentCompl] rw [Finset.coe_empty, Set.compl_empty] have := Gpc.out.subsingleton_connectedComponent exact Finite.of_equiv _ (induceUnivIso G).connectedComponentEquiv.symm -- Otherwise, we consider the function `touch` mapping a connected component to one of its -- vertices adjacent to `K`. · let touch (C : G.ComponentCompl K) : {v : V | ∃ k : V, k ∈ K ∧ G.Adj k v} := let p := C.exists_adj_boundary_pair Gpc.out h ⟨p.choose.1, p.choose.2, p.choose_spec.2.1, p.choose_spec.2.2.symm⟩ -- `touch` is injective have touch_inj : touch.Injective := fun C D h' => ComponentCompl.pairwise_disjoint.eq (Set.not_disjoint_iff.mpr ⟨touch C, (C.exists_adj_boundary_pair Gpc.out h).choose_spec.1, h'.symm ▸ (D.exists_adj_boundary_pair Gpc.out h).choose_spec.1⟩) -- `touch` has finite range have : Finite (Set.range touch) := by refine @Subtype.finite _ (Set.Finite.to_subtype ?_) _ apply Set.Finite.ofFinset (K.biUnion (fun v => G.neighborFinset v)) simp only [Finset.mem_biUnion, mem_neighborFinset, Set.mem_setOf_eq, implies_true] -- hence `touch` has a finite domain apply Finite.of_injective_finite_range touch_inj section Ends variable (G) open CategoryTheory /-- The functor assigning, to a finite set in `V`, the set of connected components in its complement. -/ @[simps] def componentComplFunctor : (Finset V)ᵒᵖ ⥤ Type u where obj K := G.ComponentCompl K.unop map f := ComponentCompl.hom (le_of_op_hom f) map_id _ := funext fun C => C.hom_refl map_comp h h' := funext fun C => C.hom_trans (le_of_op_hom h) (le_of_op_hom h') /-- The end of a graph, defined as the sections of the functor `component_compl_functor` . -/ protected def «end» := (componentComplFunctor G).sections theorem end_hom_mk_of_mk {s} (sec : s ∈ G.end) {K L : (Finset V)ᵒᵖ} (h : L ⟶ K) {v : V} (vnL : v ∉ L.unop) (hs : s L = G.componentComplMk vnL) : s K = G.componentComplMk (Set.not_mem_subset (le_of_op_hom h : _ ⊆ _) vnL) := by rw [← sec h, hs] apply ComponentCompl.hom_mk _ (le_of_op_hom h : _ ⊆ _) theorem infinite_iff_in_eventualRange {K : (Finset V)ᵒᵖ} (C : G.componentComplFunctor.obj K) : C.supp.Infinite ↔ C ∈ G.componentComplFunctor.eventualRange K := by simp only [C.infinite_iff_in_all_ranges, CategoryTheory.Functor.eventualRange, Set.mem_iInter, Set.mem_range, componentComplFunctor_map] exact ⟨fun h Lop KL => h Lop.unop (le_of_op_hom KL), fun h L KL => h (Opposite.op L) (opHomOfLE KL)⟩ end Ends end SimpleGraph
Combinatorics\SimpleGraph\Ends\Properties.lean
/- Copyright (c) 2022 Anand Rao, Rémi Bottinelli. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anand Rao, Rémi Bottinelli -/ import Mathlib.Combinatorics.SimpleGraph.Ends.Defs import Mathlib.CategoryTheory.CofilteredSystem /-! # Properties of the ends of graphs This file is meant to contain results about the ends of (locally finite connected) graphs. -/ variable {V : Type} (G : SimpleGraph V) namespace SimpleGraph instance [Finite V] : IsEmpty G.end where false := by rintro ⟨s, _⟩ cases nonempty_fintype V obtain ⟨v, h⟩ := (s <| Opposite.op Finset.univ).nonempty exact Set.disjoint_iff.mp (s _).disjoint_right ⟨by simp only [Opposite.unop_op, Finset.coe_univ, Set.mem_univ], h⟩ /-- The `componentCompl`s chosen by an end are all infinite. -/ lemma end_componentCompl_infinite (e : G.end) (K : (Finset V)ᵒᵖ) : ((e : (j : (Finset V)ᵒᵖ) → G.componentComplFunctor.obj j) K).supp.Infinite := by refine (e.val K).infinite_iff_in_all_ranges.mpr (fun L h => ?_) change Opposite.unop K ⊆ Opposite.unop (Opposite.op L) at h exact ⟨e.val (Opposite.op L), (e.prop (CategoryTheory.opHomOfLE h))⟩ instance compononentComplFunctor_nonempty_of_infinite [Infinite V] (K : (Finset V)ᵒᵖ) : Nonempty (G.componentComplFunctor.obj K) := G.componentCompl_nonempty_of_infinite K.unop instance componentComplFunctor_finite [LocallyFinite G] [Fact G.Preconnected] (K : (Finset V)ᵒᵖ) : Finite (G.componentComplFunctor.obj K) := G.componentCompl_finite K.unop /-- A locally finite preconnected infinite graph has at least one end. -/ lemma nonempty_ends_of_infinite [LocallyFinite G] [Fact G.Preconnected] [Infinite V] : G.end.Nonempty := by classical apply nonempty_sections_of_finite_inverse_system G.componentComplFunctor end SimpleGraph
Combinatorics\SimpleGraph\Regularity\Bound.lean
/- Copyright (c) 2022 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import Mathlib.Algebra.Order.Chebyshev import Mathlib.Analysis.SpecialFunctions.Pow.Real import Mathlib.Order.Partition.Equipartition /-! # Numerical bounds for Szemerédi Regularity Lemma This file gathers the numerical facts required by the proof of Szemerédi's regularity lemma. This entire file is internal to the proof of Szemerédi Regularity Lemma. ## Main declarations * `SzemerediRegularity.stepBound`: During the inductive step, a partition of size `n` is blown to size at most `stepBound n`. * `SzemerediRegularity.initialBound`: The size of the partition we start the induction with. * `SzemerediRegularity.bound`: The upper bound on the size of the partition produced by our version of Szemerédi's regularity lemma. ## References [Yaël Dillies, Bhavik Mehta, *Formalising Szemerédi’s Regularity Lemma in Lean*][srl_itp] -/ open Finset Fintype Function Real namespace SzemerediRegularity /-- Auxiliary function for Szemerédi's regularity lemma. Blowing up a partition of size `n` during the induction results in a partition of size at most `stepBound n`. -/ def stepBound (n : ℕ) : ℕ := n * 4 ^ n theorem le_stepBound : id ≤ stepBound := fun n => Nat.le_mul_of_pos_right _ <| pow_pos (by norm_num) n theorem stepBound_mono : Monotone stepBound := fun a b h => Nat.mul_le_mul h <| Nat.pow_le_pow_of_le_right (by norm_num) h theorem stepBound_pos_iff {n : ℕ} : 0 < stepBound n ↔ 0 < n := mul_pos_iff_of_pos_right <| by positivity alias ⟨_, stepBound_pos⟩ := stepBound_pos_iff @[norm_cast] lemma coe_stepBound {α : Type*} [Semiring α] (n : ℕ) : (stepBound n : α) = n * 4 ^ n := by unfold stepBound; norm_cast end SzemerediRegularity open SzemerediRegularity variable {α : Type*} [DecidableEq α] [Fintype α] {P : Finpartition (univ : Finset α)} {u : Finset α} {ε : ℝ} local notation3 "m" => (card α / stepBound P.parts.card : ℕ) local notation3 "a" => (card α / P.parts.card - m * 4 ^ P.parts.card : ℕ) namespace SzemerediRegularity.Positivity private theorem eps_pos {ε : ℝ} {n : ℕ} (h : 100 ≤ (4 : ℝ) ^ n * ε ^ 5) : 0 < ε := (Odd.pow_pos_iff (by decide)).mp (pos_of_mul_pos_right ((show 0 < (100 : ℝ) by norm_num).trans_le h) (by positivity)) private theorem m_pos [Nonempty α] (hPα : P.parts.card * 16 ^ P.parts.card ≤ card α) : 0 < m := Nat.div_pos ((Nat.mul_le_mul_left _ <| Nat.pow_le_pow_left (by norm_num) _).trans hPα) <| stepBound_pos (P.parts_nonempty <| univ_nonempty.ne_empty).card_pos /-- Local extension for the `positivity` tactic: A few facts that are needed many times for the proof of Szemerédi's regularity lemma. -/ -- Porting note: positivity extensions must now be global, and this did not seem like a good -- match for positivity anymore, so I wrote a new tactic (kmill) scoped macro "sz_positivity" : tactic => `(tactic| { try have := m_pos ‹_› try have := eps_pos ‹_› positivity }) -- Original meta code /- meta def positivity_szemeredi_regularity : expr → tactic strictness | `(%%n / step_bound (finpartition.parts %%P).card) := do p ← to_expr ``((finpartition.parts %%P).card * 16^(finpartition.parts %%P).card ≤ %%n) >>= find_assumption, positive <$> mk_app ``m_pos [p] | ε := do typ ← infer_type ε, unify typ `(ℝ), p ← to_expr ``(100 ≤ 4 ^ _ * %%ε ^ 5) >>= find_assumption, positive <$> mk_app ``eps_pos [p] -/ end SzemerediRegularity.Positivity namespace SzemerediRegularity open scoped SzemerediRegularity.Positivity theorem m_pos [Nonempty α] (hPα : P.parts.card * 16 ^ P.parts.card ≤ card α) : 0 < m := by sz_positivity theorem coe_m_add_one_pos : 0 < (m : ℝ) + 1 := by positivity theorem one_le_m_coe [Nonempty α] (hPα : P.parts.card * 16 ^ P.parts.card ≤ card α) : (1 : ℝ) ≤ m := Nat.one_le_cast.2 <| m_pos hPα theorem eps_pow_five_pos (hPε : 100 ≤ (4 : ℝ) ^ P.parts.card * ε ^ 5) : ↑0 < ε ^ 5 := pos_of_mul_pos_right ((by norm_num : (0 : ℝ) < 100).trans_le hPε) <| pow_nonneg (by norm_num) _ theorem eps_pos (hPε : 100 ≤ (4 : ℝ) ^ P.parts.card * ε ^ 5) : 0 < ε := (Odd.pow_pos_iff (by decide)).mp (eps_pow_five_pos hPε) theorem hundred_div_ε_pow_five_le_m [Nonempty α] (hPα : P.parts.card * 16 ^ P.parts.card ≤ card α) (hPε : 100 ≤ (4 : ℝ) ^ P.parts.card * ε ^ 5) : 100 / ε ^ 5 ≤ m := (div_le_of_nonneg_of_le_mul (eps_pow_five_pos hPε).le (by positivity) hPε).trans <| by norm_cast rwa [Nat.le_div_iff_mul_le' (stepBound_pos (P.parts_nonempty <| univ_nonempty.ne_empty).card_pos), stepBound, mul_left_comm, ← mul_pow] theorem hundred_le_m [Nonempty α] (hPα : P.parts.card * 16 ^ P.parts.card ≤ card α) (hPε : 100 ≤ (4 : ℝ) ^ P.parts.card * ε ^ 5) (hε : ε ≤ 1) : 100 ≤ m := mod_cast (hundred_div_ε_pow_five_le_m hPα hPε).trans' (le_div_self (by norm_num) (by sz_positivity) <| pow_le_one _ (by sz_positivity) hε) theorem a_add_one_le_four_pow_parts_card : a + 1 ≤ 4 ^ P.parts.card := by have h : 1 ≤ 4 ^ P.parts.card := one_le_pow_of_one_le (by norm_num) _ rw [stepBound, ← Nat.div_div_eq_div_mul] conv_rhs => rw [← Nat.sub_add_cancel h] rw [add_le_add_iff_right, tsub_le_iff_left, ← Nat.add_sub_assoc h] exact Nat.le_sub_one_of_lt (Nat.lt_div_mul_add h) theorem card_aux₁ (hucard : u.card = m * 4 ^ P.parts.card + a) : (4 ^ P.parts.card - a) * m + a * (m + 1) = u.card := by rw [hucard, mul_add, mul_one, ← add_assoc, ← add_mul, Nat.sub_add_cancel ((Nat.le_succ _).trans a_add_one_le_four_pow_parts_card), mul_comm] theorem card_aux₂ (hP : P.IsEquipartition) (hu : u ∈ P.parts) (hucard : ¬u.card = m * 4 ^ P.parts.card + a) : (4 ^ P.parts.card - (a + 1)) * m + (a + 1) * (m + 1) = u.card := by have : m * 4 ^ P.parts.card ≤ card α / P.parts.card := by rw [stepBound, ← Nat.div_div_eq_div_mul] exact Nat.div_mul_le_self _ _ rw [Nat.add_sub_of_le this] at hucard rw [(hP.card_parts_eq_average hu).resolve_left hucard, mul_add, mul_one, ← add_assoc, ← add_mul, Nat.sub_add_cancel a_add_one_le_four_pow_parts_card, ← add_assoc, mul_comm, Nat.add_sub_of_le this, card_univ] theorem pow_mul_m_le_card_part (hP : P.IsEquipartition) (hu : u ∈ P.parts) : (4 : ℝ) ^ P.parts.card * m ≤ u.card := by norm_cast rw [stepBound, ← Nat.div_div_eq_div_mul] exact (Nat.mul_div_le _ _).trans (hP.average_le_card_part hu) variable (P ε) (l : ℕ) /-- Auxiliary function for Szemerédi's regularity lemma. The size of the partition by which we start blowing. -/ noncomputable def initialBound : ℕ := max 7 <| max l <| ⌊log (100 / ε ^ 5) / log 4⌋₊ + 1 theorem le_initialBound : l ≤ initialBound ε l := (le_max_left _ _).trans <| le_max_right _ _ theorem seven_le_initialBound : 7 ≤ initialBound ε l := le_max_left _ _ theorem initialBound_pos : 0 < initialBound ε l := Nat.succ_pos'.trans_le <| seven_le_initialBound _ _ theorem hundred_lt_pow_initialBound_mul {ε : ℝ} (hε : 0 < ε) (l : ℕ) : 100 < ↑4 ^ initialBound ε l * ε ^ 5 := by rw [← rpow_natCast 4, ← div_lt_iff (pow_pos hε 5), lt_rpow_iff_log_lt _ zero_lt_four, ← div_lt_iff, initialBound, Nat.cast_max, Nat.cast_max] · push_cast exact lt_max_of_lt_right (lt_max_of_lt_right <| Nat.lt_floor_add_one _) · exact log_pos (by norm_num) · exact div_pos (by norm_num) (pow_pos hε 5) /-- An explicit bound on the size of the equipartition whose existence is given by Szemerédi's regularity lemma. -/ noncomputable def bound : ℕ := (stepBound^[⌊4 / ε ^ 5⌋₊] <| initialBound ε l) * 16 ^ (stepBound^[⌊4 / ε ^ 5⌋₊] <| initialBound ε l) theorem initialBound_le_bound : initialBound ε l ≤ bound ε l := (id_le_iterate_of_id_le le_stepBound _ _).trans <| Nat.le_mul_of_pos_right _ <| by positivity theorem le_bound : l ≤ bound ε l := (le_initialBound ε l).trans <| initialBound_le_bound ε l theorem bound_pos : 0 < bound ε l := (initialBound_pos ε l).trans_le <| initialBound_le_bound ε l variable {ι 𝕜 : Type*} [LinearOrderedField 𝕜] (r : ι → ι → Prop) [DecidableRel r] {s t : Finset ι} {x : 𝕜} theorem mul_sq_le_sum_sq (hst : s ⊆ t) (f : ι → 𝕜) (hs : x ^ 2 ≤ ((∑ i ∈ s, f i) / s.card) ^ 2) (hs' : (s.card : 𝕜) ≠ 0) : (s.card : 𝕜) * x ^ 2 ≤ ∑ i ∈ t, f i ^ 2 := (mul_le_mul_of_nonneg_left (hs.trans sum_div_card_sq_le_sum_sq_div_card) <| Nat.cast_nonneg _).trans <| (mul_div_cancel₀ _ hs').le.trans <| sum_le_sum_of_subset_of_nonneg hst fun _ _ _ => sq_nonneg _ theorem add_div_le_sum_sq_div_card (hst : s ⊆ t) (f : ι → 𝕜) (d : 𝕜) (hx : 0 ≤ x) (hs : x ≤ |(∑ i ∈ s, f i) / s.card - (∑ i ∈ t, f i) / t.card|) (ht : d ≤ ((∑ i ∈ t, f i) / t.card) ^ 2) : d + s.card / t.card * x ^ 2 ≤ (∑ i ∈ t, f i ^ 2) / t.card := by obtain hscard | hscard := (s.card.cast_nonneg : (0 : 𝕜) ≤ s.card).eq_or_lt · simpa [← hscard] using ht.trans sum_div_card_sq_le_sum_sq_div_card have htcard : (0 : 𝕜) < t.card := hscard.trans_le (Nat.cast_le.2 (card_le_card hst)) have h₁ : x ^ 2 ≤ ((∑ i ∈ s, f i) / s.card - (∑ i ∈ t, f i) / t.card) ^ 2 := sq_le_sq.2 (by rwa [abs_of_nonneg hx]) have h₂ : x ^ 2 ≤ ((∑ i ∈ s, (f i - (∑ j ∈ t, f j) / t.card)) / s.card) ^ 2 := by apply h₁.trans rw [sum_sub_distrib, sum_const, nsmul_eq_mul, sub_div, mul_div_cancel_left₀ _ hscard.ne'] apply (add_le_add_right ht _).trans rw [← mul_div_right_comm, le_div_iff htcard, add_mul, div_mul_cancel₀ _ htcard.ne'] have h₃ := mul_sq_le_sum_sq hst (fun i => (f i - (∑ j ∈ t, f j) / t.card)) h₂ hscard.ne' apply (add_le_add_left h₃ _).trans -- Porting note: was -- `simp [← mul_div_right_comm _ (t.card : 𝕜), sub_div' _ _ _ htcard.ne', ← sum_div, ← add_div,` -- ` mul_pow, div_le_iff (sq_pos_of_ne_zero htcard.ne'), sub_sq, sum_add_distrib, ← sum_mul,` -- ` ← mul_sum]` simp_rw [sub_div' _ _ _ htcard.ne'] conv_lhs => enter [2, 2, x]; rw [div_pow] rw [div_pow, ← sum_div, ← mul_div_right_comm _ (t.card : 𝕜), ← add_div, div_le_iff (sq_pos_of_ne_zero htcard.ne')] simp_rw [sub_sq, sum_add_distrib, sum_const, nsmul_eq_mul, sum_sub_distrib, mul_pow, ← sum_mul, ← mul_sum, ← sum_mul] ring_nf; rfl end SzemerediRegularity namespace Mathlib.Meta.Positivity open Lean.Meta Qq /-- Extension for the `positivity` tactic: `SzemerediRegularity.initialBound` is always positive. -/ @[positivity SzemerediRegularity.initialBound _ _] def evalInitialBound : PositivityExt where eval {u α} _ _ e := do match u, α, e with | 0, ~q(ℕ), ~q(SzemerediRegularity.initialBound $ε $l) => assertInstancesCommute pure (.positive q(SzemerediRegularity.initialBound_pos $ε $l)) | _, _, _ => throwError "not initialBound" example (ε : ℝ) (l : ℕ) : 0 < SzemerediRegularity.initialBound ε l := by positivity /-- Extension for the `positivity` tactic: `SzemerediRegularity.bound` is always positive. -/ @[positivity SzemerediRegularity.bound _ _] def evalBound : PositivityExt where eval {u α} _ _ e := do match u, α, e with | 0, ~q(ℕ), ~q(SzemerediRegularity.bound $ε $l) => assertInstancesCommute pure (.positive q(SzemerediRegularity.bound_pos $ε $l)) | _, _, _ => throwError "not bound" example (ε : ℝ) (l : ℕ) : 0 < SzemerediRegularity.bound ε l := by positivity end Mathlib.Meta.Positivity
Combinatorics\SimpleGraph\Regularity\Chunk.lean
/- Copyright (c) 2022 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import Mathlib.Combinatorics.SimpleGraph.Regularity.Bound import Mathlib.Combinatorics.SimpleGraph.Regularity.Equitabilise import Mathlib.Combinatorics.SimpleGraph.Regularity.Uniform /-! # Chunk of the increment partition for Szemerédi Regularity Lemma In the proof of Szemerédi Regularity Lemma, we need to partition each part of a starting partition to increase the energy. This file defines those partitions of parts and shows that they locally increase the energy. This entire file is internal to the proof of Szemerédi Regularity Lemma. ## Main declarations * `SzemerediRegularity.chunk`: The partition of a part of the starting partition. * `SzemerediRegularity.edgeDensity_chunk_uniform`: `chunk` does not locally decrease the edge density between uniform parts too much. * `SzemerediRegularity.edgeDensity_chunk_not_uniform`: `chunk` locally increases the edge density between non-uniform parts. ## TODO Once ported to mathlib4, this file will be a great golfing ground for Heather's new tactic `gcongr`. ## References [Yaël Dillies, Bhavik Mehta, *Formalising Szemerédi’s Regularity Lemma in Lean*][srl_itp] -/ open Finpartition Finset Fintype Rel Nat open scoped SzemerediRegularity.Positivity namespace SzemerediRegularity variable {α : Type*} [Fintype α] [DecidableEq α] {P : Finpartition (univ : Finset α)} (hP : P.IsEquipartition) (G : SimpleGraph α) [DecidableRel G.Adj] (ε : ℝ) {U : Finset α} (hU : U ∈ P.parts) (V : Finset α) local notation3 "m" => (card α / stepBound P.parts.card : ℕ) /-! ### Definitions We define `chunk`, the partition of a part, and `star`, the sets of parts of `chunk` that are contained in the corresponding witness of non-uniformity. -/ /-- The portion of `SzemerediRegularity.increment` which partitions `U`. -/ noncomputable def chunk : Finpartition U := if hUcard : U.card = m * 4 ^ P.parts.card + (card α / P.parts.card - m * 4 ^ P.parts.card) then (atomise U <| P.nonuniformWitnesses G ε U).equitabilise <| card_aux₁ hUcard else (atomise U <| P.nonuniformWitnesses G ε U).equitabilise <| card_aux₂ hP hU hUcard -- `hP` and `hU` are used to get that `U` has size -- `m * 4 ^ P.parts.card + a or m * 4 ^ P.parts.card + a + 1` /-- The portion of `SzemerediRegularity.chunk` which is contained in the witness of non-uniformity of `U` and `V`. -/ noncomputable def star (V : Finset α) : Finset (Finset α) := (chunk hP G ε hU).parts.filter (· ⊆ G.nonuniformWitness ε U V) /-! ### Density estimates We estimate the density between parts of `chunk`. -/ theorem biUnion_star_subset_nonuniformWitness : (star hP G ε hU V).biUnion id ⊆ G.nonuniformWitness ε U V := biUnion_subset_iff_forall_subset.2 fun _ hA => (mem_filter.1 hA).2 variable {hP G ε hU V} {𝒜 : Finset (Finset α)} {s : Finset α} theorem star_subset_chunk : star hP G ε hU V ⊆ (chunk hP G ε hU).parts := filter_subset _ _ private theorem card_nonuniformWitness_sdiff_biUnion_star (hV : V ∈ P.parts) (hUV : U ≠ V) (h₂ : ¬G.IsUniform ε U V) : (G.nonuniformWitness ε U V \ (star hP G ε hU V).biUnion id).card ≤ 2 ^ (P.parts.card - 1) * m := by have hX : G.nonuniformWitness ε U V ∈ P.nonuniformWitnesses G ε U := nonuniformWitness_mem_nonuniformWitnesses h₂ hV hUV have q : G.nonuniformWitness ε U V \ (star hP G ε hU V).biUnion id ⊆ ((atomise U <| P.nonuniformWitnesses G ε U).parts.filter fun B => B ⊆ G.nonuniformWitness ε U V ∧ B.Nonempty).biUnion fun B => B \ ((chunk hP G ε hU).parts.filter (· ⊆ B)).biUnion id := by intro x hx rw [← biUnion_filter_atomise hX (G.nonuniformWitness_subset h₂), star, mem_sdiff, mem_biUnion] at hx simp only [not_exists, mem_biUnion, and_imp, exists_prop, mem_filter, not_and, mem_sdiff, id, mem_sdiff] at hx ⊢ obtain ⟨⟨B, hB₁, hB₂⟩, hx⟩ := hx exact ⟨B, hB₁, hB₂, fun A hA AB => hx A hA <| AB.trans hB₁.2.1⟩ apply (card_le_card q).trans (card_biUnion_le.trans _) trans ∑ _i in (atomise U <| P.nonuniformWitnesses G ε U).parts.filter fun B => B ⊆ G.nonuniformWitness ε U V ∧ B.Nonempty, m · suffices ∀ B ∈ (atomise U <| P.nonuniformWitnesses G ε U).parts, (B \ ((chunk hP G ε hU).parts.filter (· ⊆ B)).biUnion id).card ≤ m by exact sum_le_sum fun B hB => this B <| filter_subset _ _ hB intro B hB unfold chunk split_ifs with h₁ · convert card_parts_equitabilise_subset_le _ (card_aux₁ h₁) hB · convert card_parts_equitabilise_subset_le _ (card_aux₂ hP hU h₁) hB rw [sum_const] refine mul_le_mul_right' ?_ _ have t := card_filter_atomise_le_two_pow (s := U) hX refine t.trans (pow_le_pow_right (by norm_num) <| tsub_le_tsub_right ?_ _) exact card_image_le.trans (card_le_card <| filter_subset _ _) private theorem one_sub_eps_mul_card_nonuniformWitness_le_card_star (hV : V ∈ P.parts) (hUV : U ≠ V) (hunif : ¬G.IsUniform ε U V) (hPε : ↑100 ≤ ↑4 ^ P.parts.card * ε ^ 5) (hε₁ : ε ≤ 1) : (1 - ε / 10) * (G.nonuniformWitness ε U V).card ≤ ((star hP G ε hU V).biUnion id).card := by have hP₁ : 0 < P.parts.card := Finset.card_pos.2 ⟨_, hU⟩ have : (↑2 ^ P.parts.card : ℝ) * m / (U.card * ε) ≤ ε / 10 := by rw [← div_div, div_le_iff'] swap · sz_positivity refine le_of_mul_le_mul_left ?_ (pow_pos zero_lt_two P.parts.card) calc ↑2 ^ P.parts.card * ((↑2 ^ P.parts.card * m : ℝ) / U.card) = ((2 : ℝ) * 2) ^ P.parts.card * m / U.card := by rw [mul_pow, ← mul_div_assoc, mul_assoc] _ = ↑4 ^ P.parts.card * m / U.card := by norm_num _ ≤ 1 := div_le_one_of_le (pow_mul_m_le_card_part hP hU) (cast_nonneg _) _ ≤ ↑2 ^ P.parts.card * ε ^ 2 / 10 := by refine (one_le_sq_iff <| by positivity).1 ?_ rw [div_pow, mul_pow, pow_right_comm, ← pow_mul ε, one_le_div (sq_pos_of_ne_zero <| by norm_num)] calc (↑10 ^ 2) = 100 := by norm_num _ ≤ ↑4 ^ P.parts.card * ε ^ 5 := hPε _ ≤ ↑4 ^ P.parts.card * ε ^ 4 := (mul_le_mul_of_nonneg_left (pow_le_pow_of_le_one (by sz_positivity) hε₁ <| le_succ _) (by positivity)) _ = (↑2 ^ 2) ^ P.parts.card * ε ^ (2 * 2) := by norm_num _ = ↑2 ^ P.parts.card * (ε * (ε / 10)) := by rw [mul_div_assoc, sq, mul_div_assoc] calc (↑1 - ε / 10) * (G.nonuniformWitness ε U V).card ≤ (↑1 - ↑2 ^ P.parts.card * m / (U.card * ε)) * (G.nonuniformWitness ε U V).card := mul_le_mul_of_nonneg_right (sub_le_sub_left this _) (cast_nonneg _) _ = (G.nonuniformWitness ε U V).card - ↑2 ^ P.parts.card * m / (U.card * ε) * (G.nonuniformWitness ε U V).card := by rw [sub_mul, one_mul] _ ≤ (G.nonuniformWitness ε U V).card - ↑2 ^ (P.parts.card - 1) * m := by refine sub_le_sub_left ?_ _ have : (2 : ℝ) ^ P.parts.card = ↑2 ^ (P.parts.card - 1) * 2 := by rw [← _root_.pow_succ, tsub_add_cancel_of_le (succ_le_iff.2 hP₁)] rw [← mul_div_right_comm, this, mul_right_comm _ (2 : ℝ), mul_assoc, le_div_iff] · refine mul_le_mul_of_nonneg_left ?_ (by positivity) exact (G.le_card_nonuniformWitness hunif).trans (le_mul_of_one_le_left (cast_nonneg _) one_le_two) have := Finset.card_pos.mpr (P.nonempty_of_mem_parts hU) sz_positivity _ ≤ ((star hP G ε hU V).biUnion id).card := by rw [sub_le_comm, ← cast_sub (card_le_card <| biUnion_star_subset_nonuniformWitness hP G ε hU V), ← card_sdiff (biUnion_star_subset_nonuniformWitness hP G ε hU V)] exact mod_cast card_nonuniformWitness_sdiff_biUnion_star hV hUV hunif /-! ### `chunk` -/ theorem card_chunk (hm : m ≠ 0) : (chunk hP G ε hU).parts.card = 4 ^ P.parts.card := by unfold chunk split_ifs · rw [card_parts_equitabilise _ _ hm, tsub_add_cancel_of_le] exact le_of_lt a_add_one_le_four_pow_parts_card · rw [card_parts_equitabilise _ _ hm, tsub_add_cancel_of_le a_add_one_le_four_pow_parts_card] theorem card_eq_of_mem_parts_chunk (hs : s ∈ (chunk hP G ε hU).parts) : s.card = m ∨ s.card = m + 1 := by unfold chunk at hs split_ifs at hs <;> exact card_eq_of_mem_parts_equitabilise hs theorem m_le_card_of_mem_chunk_parts (hs : s ∈ (chunk hP G ε hU).parts) : m ≤ s.card := (card_eq_of_mem_parts_chunk hs).elim ge_of_eq fun i => by simp [i] theorem card_le_m_add_one_of_mem_chunk_parts (hs : s ∈ (chunk hP G ε hU).parts) : s.card ≤ m + 1 := (card_eq_of_mem_parts_chunk hs).elim (fun i => by simp [i]) fun i => i.le theorem card_biUnion_star_le_m_add_one_card_star_mul : (((star hP G ε hU V).biUnion id).card : ℝ) ≤ (star hP G ε hU V).card * (m + 1) := mod_cast card_biUnion_le_card_mul _ _ _ fun _ hs => card_le_m_add_one_of_mem_chunk_parts <| star_subset_chunk hs private theorem le_sum_card_subset_chunk_parts (h𝒜 : 𝒜 ⊆ (chunk hP G ε hU).parts) (hs : s ∈ 𝒜) : (𝒜.card : ℝ) * s.card * (m / (m + 1)) ≤ (𝒜.sup id).card := by rw [mul_div_assoc', div_le_iff coe_m_add_one_pos, mul_right_comm] refine mul_le_mul ?_ ?_ (cast_nonneg _) (cast_nonneg _) · rw [← (ofSubset _ h𝒜 rfl).sum_card_parts, ofSubset_parts, ← cast_mul, cast_le] exact card_nsmul_le_sum _ _ _ fun x hx => m_le_card_of_mem_chunk_parts <| h𝒜 hx · exact mod_cast card_le_m_add_one_of_mem_chunk_parts (h𝒜 hs) private theorem sum_card_subset_chunk_parts_le (m_pos : (0 : ℝ) < m) (h𝒜 : 𝒜 ⊆ (chunk hP G ε hU).parts) (hs : s ∈ 𝒜) : ((𝒜.sup id).card : ℝ) ≤ 𝒜.card * s.card * ((m + 1) / m) := by rw [sup_eq_biUnion, mul_div_assoc', le_div_iff m_pos, mul_right_comm] refine mul_le_mul ?_ ?_ (cast_nonneg _) (by positivity) · norm_cast refine card_biUnion_le_card_mul _ _ _ fun x hx => ?_ apply card_le_m_add_one_of_mem_chunk_parts (h𝒜 hx) · exact mod_cast m_le_card_of_mem_chunk_parts (h𝒜 hs) private theorem one_sub_le_m_div_m_add_one_sq [Nonempty α] (hPα : P.parts.card * 16 ^ P.parts.card ≤ card α) (hPε : ↑100 ≤ ↑4 ^ P.parts.card * ε ^ 5) : ↑1 - ε ^ 5 / ↑50 ≤ (m / (m + 1 : ℝ)) ^ 2 := by have : (m : ℝ) / (m + 1) = 1 - 1 / (m + 1) := by rw [one_sub_div coe_m_add_one_pos.ne', add_sub_cancel_right] rw [this, sub_sq, one_pow, mul_one] refine le_trans ?_ (le_add_of_nonneg_right <| sq_nonneg _) rw [sub_le_sub_iff_left, ← le_div_iff' (show (0 : ℝ) < 2 by norm_num), div_div, one_div_le coe_m_add_one_pos, one_div_div] · refine le_trans ?_ (le_add_of_nonneg_right zero_le_one) norm_num apply hundred_div_ε_pow_five_le_m hPα hPε sz_positivity private theorem m_add_one_div_m_le_one_add [Nonempty α] (hPα : P.parts.card * 16 ^ P.parts.card ≤ card α) (hPε : ↑100 ≤ ↑4 ^ P.parts.card * ε ^ 5) (hε₁ : ε ≤ 1) : ((m + 1 : ℝ) / m) ^ 2 ≤ ↑1 + ε ^ 5 / 49 := by rw [same_add_div] swap; · sz_positivity have : ↑1 + ↑1 / (m : ℝ) ≤ ↑1 + ε ^ 5 / 100 := by rw [add_le_add_iff_left, ← one_div_div (100 : ℝ)] exact one_div_le_one_div_of_le (by sz_positivity) (hundred_div_ε_pow_five_le_m hPα hPε) refine (pow_le_pow_left ?_ this 2).trans ?_ · positivity rw [add_sq, one_pow, add_assoc, add_le_add_iff_left, mul_one, ← le_sub_iff_add_le', div_eq_mul_one_div _ (49 : ℝ), mul_div_left_comm (2 : ℝ), ← mul_sub_left_distrib, div_pow, div_le_iff (show (0 : ℝ) < ↑100 ^ 2 by norm_num), mul_assoc, sq] refine mul_le_mul_of_nonneg_left ?_ (by sz_positivity) exact (pow_le_one 5 (by sz_positivity) hε₁).trans (by norm_num) private theorem density_sub_eps_le_sum_density_div_card [Nonempty α] (hPα : P.parts.card * 16 ^ P.parts.card ≤ card α) (hPε : ↑100 ≤ ↑4 ^ P.parts.card * ε ^ 5) {hU : U ∈ P.parts} {hV : V ∈ P.parts} {A B : Finset (Finset α)} (hA : A ⊆ (chunk hP G ε hU).parts) (hB : B ⊆ (chunk hP G ε hV).parts) : (G.edgeDensity (A.biUnion id) (B.biUnion id)) - ε ^ 5 / 50 ≤ (∑ ab ∈ A.product B, (G.edgeDensity ab.1 ab.2 : ℝ)) / (A.card * B.card) := by have : ↑(G.edgeDensity (A.biUnion id) (B.biUnion id)) - ε ^ 5 / ↑50 ≤ (↑1 - ε ^ 5 / 50) * G.edgeDensity (A.biUnion id) (B.biUnion id) := by rw [sub_mul, one_mul, sub_le_sub_iff_left] refine mul_le_of_le_one_right (by sz_positivity) ?_ exact mod_cast G.edgeDensity_le_one _ _ refine this.trans ?_ conv_rhs => -- Porting note: LHS and RHS need separate treatment to get the desired form simp only [SimpleGraph.edgeDensity_def, sum_div, Rat.cast_div, div_div] conv_lhs => rw [SimpleGraph.edgeDensity_def, SimpleGraph.interedges, ← sup_eq_biUnion, ← sup_eq_biUnion, Rel.card_interedges_finpartition _ (ofSubset _ hA rfl) (ofSubset _ hB rfl), ofSubset_parts, ofSubset_parts] simp only [cast_sum, sum_div, mul_sum, Rat.cast_sum, Rat.cast_div, mul_div_left_comm ((1 : ℝ) - _)] push_cast apply sum_le_sum simp only [and_imp, Prod.forall, mem_product] rintro x y hx hy rw [mul_mul_mul_comm, mul_comm (x.card : ℝ), mul_comm (y.card : ℝ), le_div_iff, mul_assoc] · refine mul_le_of_le_one_right (cast_nonneg _) ?_ rw [div_mul_eq_mul_div, ← mul_assoc, mul_assoc] refine div_le_one_of_le ?_ (by positivity) refine (mul_le_mul_of_nonneg_right (one_sub_le_m_div_m_add_one_sq hPα hPε) ?_).trans ?_ · exact mod_cast _root_.zero_le _ rw [sq, mul_mul_mul_comm, mul_comm ((m : ℝ) / _), mul_comm ((m : ℝ) / _)] refine mul_le_mul ?_ ?_ ?_ (cast_nonneg _) · apply le_sum_card_subset_chunk_parts hA hx · apply le_sum_card_subset_chunk_parts hB hy · positivity refine mul_pos (mul_pos ?_ ?_) (mul_pos ?_ ?_) <;> rw [cast_pos, Finset.card_pos] exacts [⟨_, hx⟩, nonempty_of_mem_parts _ (hA hx), ⟨_, hy⟩, nonempty_of_mem_parts _ (hB hy)] private theorem sum_density_div_card_le_density_add_eps [Nonempty α] (hPα : P.parts.card * 16 ^ P.parts.card ≤ card α) (hPε : ↑100 ≤ ↑4 ^ P.parts.card * ε ^ 5) (hε₁ : ε ≤ 1) {hU : U ∈ P.parts} {hV : V ∈ P.parts} {A B : Finset (Finset α)} (hA : A ⊆ (chunk hP G ε hU).parts) (hB : B ⊆ (chunk hP G ε hV).parts) : (∑ ab ∈ A.product B, G.edgeDensity ab.1 ab.2 : ℝ) / (A.card * B.card) ≤ G.edgeDensity (A.biUnion id) (B.biUnion id) + ε ^ 5 / 49 := by have : (↑1 + ε ^ 5 / ↑49) * G.edgeDensity (A.biUnion id) (B.biUnion id) ≤ G.edgeDensity (A.biUnion id) (B.biUnion id) + ε ^ 5 / 49 := by rw [add_mul, one_mul, add_le_add_iff_left] refine mul_le_of_le_one_right (by sz_positivity) ?_ exact mod_cast G.edgeDensity_le_one _ _ refine le_trans ?_ this conv_lhs => -- Porting note: LHS and RHS need separate treatment to get the desired form simp only [SimpleGraph.edgeDensity, edgeDensity, sum_div, Rat.cast_div, div_div] conv_rhs => rw [SimpleGraph.edgeDensity, edgeDensity, ← sup_eq_biUnion, ← sup_eq_biUnion, Rel.card_interedges_finpartition _ (ofSubset _ hA rfl) (ofSubset _ hB rfl)] simp only [cast_sum, mul_sum, sum_div, Rat.cast_sum, Rat.cast_div, mul_div_left_comm ((1 : ℝ) + _)] push_cast apply sum_le_sum simp only [and_imp, Prod.forall, mem_product, show A.product B = A ×ˢ B by rfl] intro x y hx hy rw [mul_mul_mul_comm, mul_comm (x.card : ℝ), mul_comm (y.card : ℝ), div_le_iff, mul_assoc] · refine le_mul_of_one_le_right (cast_nonneg _) ?_ rw [div_mul_eq_mul_div, one_le_div] · refine le_trans ?_ (mul_le_mul_of_nonneg_right (m_add_one_div_m_le_one_add hPα hPε hε₁) ?_) · rw [sq, mul_mul_mul_comm, mul_comm (_ / (m : ℝ)), mul_comm (_ / (m : ℝ))] exact mul_le_mul (sum_card_subset_chunk_parts_le (by sz_positivity) hA hx) (sum_card_subset_chunk_parts_le (by sz_positivity) hB hy) (by positivity) (by positivity) · exact mod_cast _root_.zero_le _ rw [← cast_mul, cast_pos] apply mul_pos <;> rw [Finset.card_pos, sup_eq_biUnion, biUnion_nonempty] · exact ⟨_, hx, nonempty_of_mem_parts _ (hA hx)⟩ · exact ⟨_, hy, nonempty_of_mem_parts _ (hB hy)⟩ refine mul_pos (mul_pos ?_ ?_) (mul_pos ?_ ?_) <;> rw [cast_pos, Finset.card_pos] exacts [⟨_, hx⟩, nonempty_of_mem_parts _ (hA hx), ⟨_, hy⟩, nonempty_of_mem_parts _ (hB hy)] private theorem average_density_near_total_density [Nonempty α] (hPα : P.parts.card * 16 ^ P.parts.card ≤ card α) (hPε : ↑100 ≤ ↑4 ^ P.parts.card * ε ^ 5) (hε₁ : ε ≤ 1) {hU : U ∈ P.parts} {hV : V ∈ P.parts} {A B : Finset (Finset α)} (hA : A ⊆ (chunk hP G ε hU).parts) (hB : B ⊆ (chunk hP G ε hV).parts) : |(∑ ab ∈ A.product B, G.edgeDensity ab.1 ab.2 : ℝ) / (A.card * B.card) - G.edgeDensity (A.biUnion id) (B.biUnion id)| ≤ ε ^ 5 / 49 := by rw [abs_sub_le_iff] constructor · rw [sub_le_iff_le_add'] exact sum_density_div_card_le_density_add_eps hPα hPε hε₁ hA hB suffices (G.edgeDensity (A.biUnion id) (B.biUnion id) : ℝ) - (∑ ab ∈ A.product B, (G.edgeDensity ab.1 ab.2 : ℝ)) / (A.card * B.card) ≤ ε ^ 5 / 50 by apply this.trans gcongr <;> [sz_positivity; norm_num] rw [sub_le_iff_le_add, ← sub_le_iff_le_add'] apply density_sub_eps_le_sum_density_div_card hPα hPε hA hB private theorem edgeDensity_chunk_aux [Nonempty α] (hPα : P.parts.card * 16 ^ P.parts.card ≤ card α) (hPε : ↑100 ≤ ↑4 ^ P.parts.card * ε ^ 5) (hU : U ∈ P.parts) (hV : V ∈ P.parts) : (G.edgeDensity U V : ℝ) ^ 2 - ε ^ 5 / ↑25 ≤ ((∑ ab ∈ (chunk hP G ε hU).parts.product (chunk hP G ε hV).parts, (G.edgeDensity ab.1 ab.2 : ℝ)) / ↑16 ^ P.parts.card) ^ 2 := by obtain hGε | hGε := le_total (G.edgeDensity U V : ℝ) (ε ^ 5 / 50) · refine (sub_nonpos_of_le <| (sq_le ?_ ?_).trans <| hGε.trans ?_).trans (sq_nonneg _) · exact mod_cast G.edgeDensity_nonneg _ _ · exact mod_cast G.edgeDensity_le_one _ _ · exact div_le_div_of_nonneg_left (by sz_positivity) (by norm_num) (by norm_num) rw [← sub_nonneg] at hGε have : ↑(G.edgeDensity U V) - ε ^ 5 / ↑50 ≤ (∑ ab ∈ (chunk hP G ε hU).parts.product (chunk hP G ε hV).parts, (G.edgeDensity ab.1 ab.2 : ℝ)) / ↑16 ^ P.parts.card := by have rflU := Set.Subset.refl (chunk hP G ε hU).parts.toSet have rflV := Set.Subset.refl (chunk hP G ε hV).parts.toSet refine (le_trans ?_ <| density_sub_eps_le_sum_density_div_card hPα hPε rflU rflV).trans ?_ · rw [biUnion_parts, biUnion_parts] · rw [card_chunk (m_pos hPα).ne', card_chunk (m_pos hPα).ne', ← cast_mul, ← mul_pow, cast_pow] norm_cast refine le_trans ?_ (pow_le_pow_left hGε this 2) rw [sub_sq, sub_add, sub_le_sub_iff_left] refine (sub_le_self _ <| sq_nonneg <| ε ^ 5 / 50).trans ?_ rw [mul_right_comm, mul_div_left_comm, div_eq_mul_inv (ε ^ 5), show (2 : ℝ) / 50 = 25⁻¹ by norm_num] exact mul_le_of_le_one_right (by sz_positivity) (mod_cast G.edgeDensity_le_one _ _) private theorem abs_density_star_sub_density_le_eps (hPε : ↑100 ≤ ↑4 ^ P.parts.card * ε ^ 5) (hε₁ : ε ≤ 1) {hU : U ∈ P.parts} {hV : V ∈ P.parts} (hUV' : U ≠ V) (hUV : ¬G.IsUniform ε U V) : |(G.edgeDensity ((star hP G ε hU V).biUnion id) ((star hP G ε hV U).biUnion id) : ℝ) - G.edgeDensity (G.nonuniformWitness ε U V) (G.nonuniformWitness ε V U)| ≤ ε / 5 := by convert abs_edgeDensity_sub_edgeDensity_le_two_mul G.Adj (biUnion_star_subset_nonuniformWitness hP G ε hU V) (biUnion_star_subset_nonuniformWitness hP G ε hV U) (by sz_positivity) (one_sub_eps_mul_card_nonuniformWitness_le_card_star hV hUV' hUV hPε hε₁) (one_sub_eps_mul_card_nonuniformWitness_le_card_star hU hUV'.symm (fun hVU => hUV hVU.symm) hPε hε₁) using 1 linarith private theorem eps_le_card_star_div [Nonempty α] (hPα : P.parts.card * 16 ^ P.parts.card ≤ card α) (hPε : ↑100 ≤ ↑4 ^ P.parts.card * ε ^ 5) (hε₁ : ε ≤ 1) (hU : U ∈ P.parts) (hV : V ∈ P.parts) (hUV : U ≠ V) (hunif : ¬G.IsUniform ε U V) : ↑4 / ↑5 * ε ≤ (star hP G ε hU V).card / ↑4 ^ P.parts.card := by have hm : (0 : ℝ) ≤ 1 - (↑m)⁻¹ := sub_nonneg_of_le (inv_le_one <| one_le_m_coe hPα) have hε : 0 ≤ 1 - ε / 10 := sub_nonneg_of_le (div_le_one_of_le (hε₁.trans <| by norm_num) <| by norm_num) have hε₀ : 0 < ε := by sz_positivity calc 4 / 5 * ε = (1 - 1 / 10) * (1 - 9⁻¹) * ε := by norm_num _ ≤ (1 - ε / 10) * (1 - (↑m)⁻¹) * ((G.nonuniformWitness ε U V).card / U.card) := by gcongr exacts [mod_cast (show 9 ≤ 100 by norm_num).trans (hundred_le_m hPα hPε hε₁), (le_div_iff' <| cast_pos.2 (P.nonempty_of_mem_parts hU).card_pos).2 <| G.le_card_nonuniformWitness hunif] _ = (1 - ε / 10) * (G.nonuniformWitness ε U V).card * ((1 - (↑m)⁻¹) / U.card) := by rw [mul_assoc, mul_assoc, mul_div_left_comm] _ ≤ ((star hP G ε hU V).biUnion id).card * ((1 - (↑m)⁻¹) / U.card) := (mul_le_mul_of_nonneg_right (one_sub_eps_mul_card_nonuniformWitness_le_card_star hV hUV hunif hPε hε₁) (by positivity)) _ ≤ (star hP G ε hU V).card * (m + 1) * ((1 - (↑m)⁻¹) / U.card) := (mul_le_mul_of_nonneg_right card_biUnion_star_le_m_add_one_card_star_mul (by positivity)) _ ≤ (star hP G ε hU V).card * (m + ↑1) * ((↑1 - (↑m)⁻¹) / (↑4 ^ P.parts.card * m)) := (mul_le_mul_of_nonneg_left (div_le_div_of_nonneg_left hm (by sz_positivity) <| pow_mul_m_le_card_part hP hU) (by positivity)) _ ≤ (star hP G ε hU V).card / ↑4 ^ P.parts.card := by rw [mul_assoc, mul_comm ((4 : ℝ) ^ P.parts.card), ← div_div, ← mul_div_assoc, ← mul_comm_div] refine mul_le_of_le_one_right (by positivity) ?_ have hm : (0 : ℝ) < m := by sz_positivity rw [mul_div_assoc', div_le_one hm, ← one_div, one_sub_div hm.ne', mul_div_assoc', div_le_iff hm] linarith /-! ### Final bounds Those inequalities are the end result of all this hard work. -/ /-- Lower bound on the edge densities between non-uniform parts of `SzemerediRegularity.star`. -/ private theorem edgeDensity_star_not_uniform [Nonempty α] (hPα : P.parts.card * 16 ^ P.parts.card ≤ card α) (hPε : ↑100 ≤ ↑4 ^ P.parts.card * ε ^ 5) (hε₁ : ε ≤ 1) {hU : U ∈ P.parts} {hV : V ∈ P.parts} (hUVne : U ≠ V) (hUV : ¬G.IsUniform ε U V) : ↑3 / ↑4 * ε ≤ |(∑ ab ∈ (star hP G ε hU V).product (star hP G ε hV U), (G.edgeDensity ab.1 ab.2 : ℝ)) / ((star hP G ε hU V).card * (star hP G ε hV U).card) - (∑ ab ∈ (chunk hP G ε hU).parts.product (chunk hP G ε hV).parts, (G.edgeDensity ab.1 ab.2 : ℝ)) / (16 : ℝ) ^ P.parts.card| := by rw [show (16 : ℝ) = ↑4 ^ 2 by norm_num, pow_right_comm, sq ((4 : ℝ) ^ _)] set p : ℝ := (∑ ab ∈ (star hP G ε hU V).product (star hP G ε hV U), (G.edgeDensity ab.1 ab.2 : ℝ)) / ((star hP G ε hU V).card * (star hP G ε hV U).card) set q : ℝ := (∑ ab ∈ (chunk hP G ε hU).parts.product (chunk hP G ε hV).parts, (G.edgeDensity ab.1 ab.2 : ℝ)) / (↑4 ^ P.parts.card * ↑4 ^ P.parts.card) change _ ≤ |p - q| set r : ℝ := ↑(G.edgeDensity ((star hP G ε hU V).biUnion id) ((star hP G ε hV U).biUnion id)) set s : ℝ := ↑(G.edgeDensity (G.nonuniformWitness ε U V) (G.nonuniformWitness ε V U)) set t : ℝ := ↑(G.edgeDensity U V) have hrs : |r - s| ≤ ε / 5 := abs_density_star_sub_density_le_eps hPε hε₁ hUVne hUV have hst : ε ≤ |s - t| := by -- After leanprover/lean4#2734, we need to do the zeta reduction before `mod_cast`. unfold_let s t exact mod_cast G.nonuniformWitness_spec hUVne hUV have hpr : |p - r| ≤ ε ^ 5 / 49 := average_density_near_total_density hPα hPε hε₁ star_subset_chunk star_subset_chunk have hqt : |q - t| ≤ ε ^ 5 / 49 := by have := average_density_near_total_density hPα hPε hε₁ (Subset.refl (chunk hP G ε hU).parts) (Subset.refl (chunk hP G ε hV).parts) simp_rw [← sup_eq_biUnion, sup_parts, card_chunk (m_pos hPα).ne', cast_pow] at this norm_num at this exact this have hε' : ε ^ 5 ≤ ε := by simpa using pow_le_pow_of_le_one (by sz_positivity) hε₁ (show 1 ≤ 5 by norm_num) rw [abs_sub_le_iff] at hrs hpr hqt rw [le_abs] at hst ⊢ cases hst · left; linarith · right; linarith set_option tactic.skipAssignedInstances false in /-- Lower bound on the edge densities between non-uniform parts of `SzemerediRegularity.increment`. -/ theorem edgeDensity_chunk_not_uniform [Nonempty α] (hPα : P.parts.card * 16 ^ P.parts.card ≤ card α) (hPε : ↑100 ≤ ↑4 ^ P.parts.card * ε ^ 5) (hε₁ : ε ≤ 1) {hU : U ∈ P.parts} {hV : V ∈ P.parts} (hUVne : U ≠ V) (hUV : ¬G.IsUniform ε U V) : (G.edgeDensity U V : ℝ) ^ 2 - ε ^ 5 / ↑25 + ε ^ 4 / ↑3 ≤ (∑ ab ∈ (chunk hP G ε hU).parts.product (chunk hP G ε hV).parts, (G.edgeDensity ab.1 ab.2 : ℝ) ^ 2) / ↑16 ^ P.parts.card := calc ↑(G.edgeDensity U V) ^ 2 - ε ^ 5 / 25 + ε ^ 4 / ↑3 ≤ ↑(G.edgeDensity U V) ^ 2 - ε ^ 5 / ↑25 + (star hP G ε hU V).card * (star hP G ε hV U).card / ↑16 ^ P.parts.card * (↑9 / ↑16) * ε ^ 2 := by apply add_le_add_left have Ul : 4 / 5 * ε ≤ (star hP G ε hU V).card / _ := eps_le_card_star_div hPα hPε hε₁ hU hV hUVne hUV have Vl : 4 / 5 * ε ≤ (star hP G ε hV U).card / _ := eps_le_card_star_div hPα hPε hε₁ hV hU hUVne.symm fun h => hUV h.symm rw [show (16 : ℝ) = ↑4 ^ 2 by norm_num, pow_right_comm, sq ((4 : ℝ) ^ _), ← _root_.div_mul_div_comm, mul_assoc] have : 0 < ε := by sz_positivity have UVl := mul_le_mul Ul Vl (by positivity) ?_ swap · -- This seems faster than `exact div_nonneg (by positivity) (by positivity)` and *much* -- (tens of seconds) faster than `positivity` on its own. apply div_nonneg <;> positivity refine le_trans ?_ (mul_le_mul_of_nonneg_right UVl ?_) · norm_num nlinarith · norm_num positivity _ ≤ (∑ ab ∈ (chunk hP G ε hU).parts.product (chunk hP G ε hV).parts, (G.edgeDensity ab.1 ab.2 : ℝ) ^ 2) / ↑16 ^ P.parts.card := by have t : (star hP G ε hU V).product (star hP G ε hV U) ⊆ (chunk hP G ε hU).parts.product (chunk hP G ε hV).parts := product_subset_product star_subset_chunk star_subset_chunk have hε : 0 ≤ ε := by sz_positivity have sp : ∀ (a b : Finset (Finset α)), a.product b = a ×ˢ b := fun a b => rfl have := add_div_le_sum_sq_div_card t (fun x => (G.edgeDensity x.1 x.2 : ℝ)) ((G.edgeDensity U V : ℝ) ^ 2 - ε ^ 5 / ↑25) (show 0 ≤ 3 / 4 * ε by linarith) ?_ ?_ · simp_rw [sp, card_product, card_chunk (m_pos hPα).ne', ← mul_pow, cast_pow, mul_pow, div_pow, ← mul_assoc] at this norm_num at this exact this · simp_rw [sp, card_product, card_chunk (m_pos hPα).ne', ← mul_pow] norm_num exact edgeDensity_star_not_uniform hPα hPε hε₁ hUVne hUV · rw [sp, card_product] apply (edgeDensity_chunk_aux hPα hPε hU hV).trans · rw [card_chunk (m_pos hPα).ne', card_chunk (m_pos hPα).ne', ← mul_pow] · norm_num rfl /-- Lower bound on the edge densities between parts of `SzemerediRegularity.increment`. This is the blanket lower bound used the uniform parts. -/ theorem edgeDensity_chunk_uniform [Nonempty α] (hPα : P.parts.card * 16 ^ P.parts.card ≤ card α) (hPε : ↑100 ≤ ↑4 ^ P.parts.card * ε ^ 5) (hU : U ∈ P.parts) (hV : V ∈ P.parts) : (G.edgeDensity U V : ℝ) ^ 2 - ε ^ 5 / ↑25 ≤ (∑ ab ∈ (chunk hP G ε hU).parts.product (chunk hP G ε hV).parts, (G.edgeDensity ab.1 ab.2 : ℝ) ^ 2) / ↑16 ^ P.parts.card := by apply (edgeDensity_chunk_aux (hP := hP) hPα hPε hU hV).trans have key : ↑16 ^ P.parts.card = (((chunk hP G ε hU).parts ×ˢ (chunk hP G ε hV).parts).card : ℝ) := by rw [card_product, cast_mul, card_chunk (m_pos hPα).ne', card_chunk (m_pos hPα).ne', ← cast_mul, ← mul_pow]; norm_cast simp_rw [key] convert sum_div_card_sq_le_sum_sq_div_card (α := ℝ) end SzemerediRegularity
Combinatorics\SimpleGraph\Regularity\Energy.lean
/- Copyright (c) 2022 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import Mathlib.Algebra.Module.Defs import Mathlib.Algebra.Order.BigOperators.Group.Finset import Mathlib.Algebra.Order.Ring.Basic import Mathlib.Combinatorics.SimpleGraph.Density import Mathlib.Data.Rat.BigOperators /-! # Energy of a partition This file defines the energy of a partition. The energy is the auxiliary quantity that drives the induction process in the proof of Szemerédi's Regularity Lemma. As long as we do not have a suitable equipartition, we will find a new one that has an energy greater than the previous one plus some fixed constant. ## References [Yaël Dillies, Bhavik Mehta, *Formalising Szemerédi’s Regularity Lemma in Lean*][srl_itp] -/ open Finset variable {α : Type*} [DecidableEq α] {s : Finset α} (P : Finpartition s) (G : SimpleGraph α) [DecidableRel G.Adj] namespace Finpartition /-- The energy of a partition, also known as index. Auxiliary quantity for Szemerédi's regularity lemma. -/ def energy : ℚ := ((∑ uv ∈ P.parts.offDiag, G.edgeDensity uv.1 uv.2 ^ 2) : ℚ) / (P.parts.card : ℚ) ^ 2 theorem energy_nonneg : 0 ≤ P.energy G := by exact div_nonneg (Finset.sum_nonneg fun _ _ => sq_nonneg _) <| sq_nonneg _ theorem energy_le_one : P.energy G ≤ 1 := div_le_of_nonneg_of_le_mul (sq_nonneg _) zero_le_one <| calc ∑ uv ∈ P.parts.offDiag, G.edgeDensity uv.1 uv.2 ^ 2 ≤ P.parts.offDiag.card • (1 : ℚ) := sum_le_card_nsmul _ _ 1 fun uv _ => (sq_le_one_iff <| G.edgeDensity_nonneg _ _).2 <| G.edgeDensity_le_one _ _ _ = P.parts.offDiag.card := Nat.smul_one_eq_cast _ _ ≤ _ := by rw [offDiag_card, one_mul] norm_cast rw [sq] exact tsub_le_self @[simp, norm_cast] theorem coe_energy {𝕜 : Type*} [LinearOrderedField 𝕜] : (P.energy G : 𝕜) = (∑ uv ∈ P.parts.offDiag, (G.edgeDensity uv.1 uv.2 : 𝕜) ^ 2) / (P.parts.card : 𝕜) ^ 2 := by rw [energy]; norm_cast end Finpartition
Combinatorics\SimpleGraph\Regularity\Equitabilise.lean
/- Copyright (c) 2022 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import Mathlib.Order.Partition.Equipartition /-! # Equitabilising a partition This file allows to blow partitions up into parts of controlled size. Given a partition `P` and `a b m : ℕ`, we want to find a partition `Q` with `a` parts of size `m` and `b` parts of size `m + 1` such that all parts of `P` are "as close as possible" to unions of parts of `Q`. By "as close as possible", we mean that each part of `P` can be written as the union of some parts of `Q` along with at most `m` other elements. ## Main declarations * `Finpartition.equitabilise`: `P.equitabilise h` where `h : a * m + b * (m + 1)` is a partition with `a` parts of size `m` and `b` parts of size `m + 1` which almost refines `P`. * `Finpartition.exists_equipartition_card_eq`: We can find equipartitions of arbitrary size. ## References [Yaël Dillies, Bhavik Mehta, *Formalising Szemerédi’s Regularity Lemma in Lean*][srl_itp] -/ open Finset Nat namespace Finpartition variable {α : Type*} [DecidableEq α] {s t : Finset α} {m n a b : ℕ} {P : Finpartition s} /-- Given a partition `P` of `s`, as well as a proof that `a * m + b * (m + 1) = s.card`, we can find a new partition `Q` of `s` where each part has size `m` or `m + 1`, every part of `P` is the union of parts of `Q` plus at most `m` extra elements, there are `b` parts of size `m + 1` and (provided `m > 0`, because a partition does not have parts of size `0`) there are `a` parts of size `m` and hence `a + b` parts in total. -/ theorem equitabilise_aux (hs : a * m + b * (m + 1) = s.card) : ∃ Q : Finpartition s, (∀ x : Finset α, x ∈ Q.parts → x.card = m ∨ x.card = m + 1) ∧ (∀ x, x ∈ P.parts → (x \ (Q.parts.filter fun y => y ⊆ x).biUnion id).card ≤ m) ∧ (Q.parts.filter fun i => card i = m + 1).card = b := by -- Get rid of the easy case `m = 0` obtain rfl | m_pos := m.eq_zero_or_pos · refine ⟨⊥, by simp, ?_, by simpa [Finset.filter_true_of_mem] using hs.symm⟩ simp only [le_zero_iff, card_eq_zero, mem_biUnion, exists_prop, mem_filter, id, and_assoc, sdiff_eq_empty_iff_subset, subset_iff] exact fun x hx a ha => ⟨{a}, mem_map_of_mem _ (P.le hx ha), singleton_subset_iff.2 ha, mem_singleton_self _⟩ -- Prove the case `m > 0` by strong induction on `s` induction' s using Finset.strongInduction with s ih generalizing a b -- If `a = b = 0`, then `s = ∅` and we can partition into zero parts by_cases hab : a = 0 ∧ b = 0 · simp only [hab.1, hab.2, add_zero, zero_mul, eq_comm, card_eq_zero, Finset.bot_eq_empty] at hs subst hs -- Porting note: to synthesize `Finpartition ∅`, `have` is required have : P = Finpartition.empty _ := Unique.eq_default (α := Finpartition ⊥) P exact ⟨Finpartition.empty _, by simp, by simp [this], by simp [hab.2]⟩ simp_rw [not_and_or, ← Ne.eq_def, ← pos_iff_ne_zero] at hab -- `n` will be the size of the smallest part set n := if 0 < a then m else m + 1 with hn -- Some easy facts about it obtain ⟨hn₀, hn₁, hn₂, hn₃⟩ : 0 < n ∧ n ≤ m + 1 ∧ n ≤ a * m + b * (m + 1) ∧ ite (0 < a) (a - 1) a * m + ite (0 < a) b (b - 1) * (m + 1) = s.card - n := by rw [hn, ← hs] split_ifs with h <;> rw [tsub_mul, one_mul] · refine ⟨m_pos, le_succ _, le_add_right (Nat.le_mul_of_pos_left _ ‹0 < a›), ?_⟩ rw [tsub_add_eq_add_tsub (Nat.le_mul_of_pos_left _ h)] · refine ⟨succ_pos', le_rfl, le_add_left (Nat.le_mul_of_pos_left _ <| hab.resolve_left ‹¬0 < a›), ?_⟩ rw [← add_tsub_assoc_of_le (Nat.le_mul_of_pos_left _ <| hab.resolve_left ‹¬0 < a›)] /- We will call the inductive hypothesis on a partition of `s \ t` for a carefully chosen `t ⊆ s`. To decide which, however, we must distinguish the case where all parts of `P` have size `m` (in which case we take `t` to be an arbitrary subset of `s` of size `n`) from the case where at least one part `u` of `P` has size `m + 1` (in which case we take `t` to be an arbitrary subset of `u` of size `n`). The rest of each branch is just tedious calculations to satisfy the induction hypothesis. -/ by_cases h : ∀ u ∈ P.parts, card u < m + 1 · obtain ⟨t, hts, htn⟩ := exists_subset_card_eq (hn₂.trans_eq hs) have ht : t.Nonempty := by rwa [← card_pos, htn] have hcard : ite (0 < a) (a - 1) a * m + ite (0 < a) b (b - 1) * (m + 1) = (s \ t).card := by rw [card_sdiff ‹t ⊆ s›, htn, hn₃] obtain ⟨R, hR₁, _, hR₃⟩ := @ih (s \ t) (sdiff_ssubset hts ‹t.Nonempty›) (if 0 < a then a - 1 else a) (if 0 < a then b else b - 1) (P.avoid t) hcard refine ⟨R.extend ht.ne_empty sdiff_disjoint (sdiff_sup_cancel hts), ?_, ?_, ?_⟩ · simp only [extend_parts, mem_insert, forall_eq_or_imp, and_iff_left hR₁, htn, hn] exact ite_eq_or_eq _ _ _ · exact fun x hx => (card_le_card sdiff_subset).trans (Nat.lt_succ_iff.1 <| h _ hx) simp_rw [extend_parts, filter_insert, htn, m.succ_ne_self.symm.ite_eq_right_iff] split_ifs with ha · rw [hR₃, if_pos ha] rw [card_insert_of_not_mem, hR₃, if_neg ha, tsub_add_cancel_of_le] · exact hab.resolve_left ha · intro H; exact ht.ne_empty (le_sdiff_iff.1 <| R.le <| filter_subset _ _ H) push_neg at h obtain ⟨u, hu₁, hu₂⟩ := h obtain ⟨t, htu, htn⟩ := exists_subset_card_eq (hn₁.trans hu₂) have ht : t.Nonempty := by rwa [← card_pos, htn] have hcard : ite (0 < a) (a - 1) a * m + ite (0 < a) b (b - 1) * (m + 1) = (s \ t).card := by rw [card_sdiff (htu.trans <| P.le hu₁), htn, hn₃] obtain ⟨R, hR₁, hR₂, hR₃⟩ := @ih (s \ t) (sdiff_ssubset (htu.trans <| P.le hu₁) ht) (if 0 < a then a - 1 else a) (if 0 < a then b else b - 1) (P.avoid t) hcard refine ⟨R.extend ht.ne_empty sdiff_disjoint (sdiff_sup_cancel <| htu.trans <| P.le hu₁), ?_, ?_, ?_⟩ · simp only [mem_insert, forall_eq_or_imp, extend_parts, and_iff_left hR₁, htn, hn] exact ite_eq_or_eq _ _ _ · conv in _ ∈ _ => rw [← insert_erase hu₁] simp only [and_imp, mem_insert, forall_eq_or_imp, Ne, extend_parts] refine ⟨?_, fun x hx => (card_le_card ?_).trans <| hR₂ x ?_⟩ · simp only [filter_insert, if_pos htu, biUnion_insert, mem_erase, id] obtain rfl | hut := eq_or_ne u t · rw [sdiff_eq_empty_iff_subset.2 subset_union_left] exact bot_le refine (card_le_card fun i => ?_).trans (hR₂ (u \ t) <| P.mem_avoid.2 ⟨u, hu₁, fun i => hut <| i.antisymm htu, rfl⟩) -- Porting note: `not_and` required because `∃ x ∈ s, p x` is defined differently simp only [not_exists, not_and, mem_biUnion, and_imp, mem_union, mem_filter, mem_sdiff, id, not_or] exact fun hi₁ hi₂ hi₃ => ⟨⟨hi₁, hi₂⟩, fun x hx hx' => hi₃ _ hx <| hx'.trans sdiff_subset⟩ · apply sdiff_subset_sdiff Subset.rfl (biUnion_subset_biUnion_of_subset_left _ _) exact filter_subset_filter _ (subset_insert _ _) simp only [avoid, ofErase, mem_erase, mem_image, bot_eq_empty] exact ⟨(nonempty_of_mem_parts _ <| mem_of_mem_erase hx).ne_empty, _, mem_of_mem_erase hx, (disjoint_of_subset_right htu <| P.disjoint (mem_of_mem_erase hx) hu₁ <| ne_of_mem_erase hx).sdiff_eq_left⟩ simp only [extend_parts, filter_insert, htn, hn, m.succ_ne_self.symm.ite_eq_right_iff] split_ifs with h · rw [hR₃, if_pos h] · rw [card_insert_of_not_mem, hR₃, if_neg h, Nat.sub_add_cancel (hab.resolve_left h)] intro H; exact ht.ne_empty (le_sdiff_iff.1 <| R.le <| filter_subset _ _ H) variable (h : a * m + b * (m + 1) = s.card) /-- Given a partition `P` of `s`, as well as a proof that `a * m + b * (m + 1) = s.card`, build a new partition `Q` of `s` where each part has size `m` or `m + 1`, every part of `P` is the union of parts of `Q` plus at most `m` extra elements, there are `b` parts of size `m + 1` and (provided `m > 0`, because a partition does not have parts of size `0`) there are `a` parts of size `m` and hence `a + b` parts in total. -/ noncomputable def equitabilise : Finpartition s := (P.equitabilise_aux h).choose variable {h} theorem card_eq_of_mem_parts_equitabilise : t ∈ (P.equitabilise h).parts → t.card = m ∨ t.card = m + 1 := (P.equitabilise_aux h).choose_spec.1 _ theorem equitabilise_isEquipartition : (P.equitabilise h).IsEquipartition := Set.equitableOn_iff_exists_eq_eq_add_one.2 ⟨m, fun _ => card_eq_of_mem_parts_equitabilise⟩ variable (P h) theorem card_filter_equitabilise_big : ((P.equitabilise h).parts.filter fun u : Finset α => u.card = m + 1).card = b := (P.equitabilise_aux h).choose_spec.2.2 theorem card_filter_equitabilise_small (hm : m ≠ 0) : ((P.equitabilise h).parts.filter fun u : Finset α => u.card = m).card = a := by refine (mul_eq_mul_right_iff.1 <| (add_left_inj (b * (m + 1))).1 ?_).resolve_right hm rw [h, ← (P.equitabilise h).sum_card_parts] have hunion : (P.equitabilise h).parts = ((P.equitabilise h).parts.filter fun u => u.card = m) ∪ (P.equitabilise h).parts.filter fun u => u.card = m + 1 := by rw [← filter_or, filter_true_of_mem] exact fun x => card_eq_of_mem_parts_equitabilise nth_rw 2 [hunion] rw [sum_union, sum_const_nat fun x hx => (mem_filter.1 hx).2, sum_const_nat fun x hx => (mem_filter.1 hx).2, P.card_filter_equitabilise_big] refine disjoint_filter_filter' _ _ ?_ intro x ha hb i h apply succ_ne_self m _ exact (hb i h).symm.trans (ha i h) theorem card_parts_equitabilise (hm : m ≠ 0) : (P.equitabilise h).parts.card = a + b := by rw [← filter_true_of_mem fun x => card_eq_of_mem_parts_equitabilise, filter_or, card_union_of_disjoint, P.card_filter_equitabilise_small _ hm, P.card_filter_equitabilise_big] -- Porting note (#11187): was `infer_instance` exact disjoint_filter.2 fun x _ h₀ h₁ => Nat.succ_ne_self m <| h₁.symm.trans h₀ theorem card_parts_equitabilise_subset_le : t ∈ P.parts → (t \ ((P.equitabilise h).parts.filter fun u => u ⊆ t).biUnion id).card ≤ m := (Classical.choose_spec <| P.equitabilise_aux h).2.1 t variable (s) /-- We can find equipartitions of arbitrary size. -/ theorem exists_equipartition_card_eq (hn : n ≠ 0) (hs : n ≤ s.card) : ∃ P : Finpartition s, P.IsEquipartition ∧ P.parts.card = n := by rw [← pos_iff_ne_zero] at hn have : (n - s.card % n) * (s.card / n) + s.card % n * (s.card / n + 1) = s.card := by rw [tsub_mul, mul_add, ← add_assoc, tsub_add_cancel_of_le (Nat.mul_le_mul_right _ (mod_lt _ hn).le), mul_one, add_comm, mod_add_div] refine ⟨(indiscrete (card_pos.1 <| hn.trans_le hs).ne_empty).equitabilise this, equitabilise_isEquipartition, ?_⟩ rw [card_parts_equitabilise _ _ (Nat.div_pos hs hn).ne', tsub_add_cancel_of_le (mod_lt _ hn).le] end Finpartition
Combinatorics\SimpleGraph\Regularity\Increment.lean
/- Copyright (c) 2022 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import Mathlib.Combinatorics.SimpleGraph.Regularity.Chunk import Mathlib.Combinatorics.SimpleGraph.Regularity.Energy /-! # Increment partition for Szemerédi Regularity Lemma In the proof of Szemerédi Regularity Lemma, we need to partition each part of a starting partition to increase the energy. This file defines the partition obtained by gluing the parts partitions together (the *increment partition*) and shows that the energy globally increases. This entire file is internal to the proof of Szemerédi Regularity Lemma. ## Main declarations * `SzemerediRegularity.increment`: The increment partition. * `SzemerediRegularity.card_increment`: The increment partition is much bigger than the original, but by a controlled amount. * `SzemerediRegularity.energy_increment`: The increment partition has energy greater than the original by a known (small) fixed amount. ## TODO Once ported to mathlib4, this file will be a great golfing ground for Heather's new tactic `gcongr`. ## References [Yaël Dillies, Bhavik Mehta, *Formalising Szemerédi’s Regularity Lemma in Lean*][srl_itp] -/ open Finset Fintype SimpleGraph SzemerediRegularity open scoped SzemerediRegularity.Positivity variable {α : Type*} [Fintype α] [DecidableEq α] {P : Finpartition (univ : Finset α)} (hP : P.IsEquipartition) (G : SimpleGraph α) [DecidableRel G.Adj] (ε : ℝ) local notation3 "m" => (card α / stepBound P.parts.card : ℕ) namespace SzemerediRegularity /-- The **increment partition** in Szemerédi's Regularity Lemma. If an equipartition is *not* uniform, then the increment partition is a (much bigger) equipartition with a slightly higher energy. This is helpful since the energy is bounded by a constant (see `Finpartition.energy_le_one`), so this process eventually terminates and yields a not-too-big uniform equipartition. -/ noncomputable def increment : Finpartition (univ : Finset α) := P.bind fun _ => chunk hP G ε open Finpartition Finpartition.IsEquipartition variable {hP G ε} /-- The increment partition has a prescribed (very big) size in terms of the original partition. -/ theorem card_increment (hPα : P.parts.card * 16 ^ P.parts.card ≤ card α) (hPG : ¬P.IsUniform G ε) : (increment hP G ε).parts.card = stepBound P.parts.card := by have hPα' : stepBound P.parts.card ≤ card α := (mul_le_mul_left' (pow_le_pow_left' (by norm_num) _) _).trans hPα have hPpos : 0 < stepBound P.parts.card := stepBound_pos (nonempty_of_not_uniform hPG).card_pos rw [increment, card_bind] simp_rw [chunk, apply_dite Finpartition.parts, apply_dite card, sum_dite] rw [sum_const_nat, sum_const_nat, card_attach, card_attach]; rotate_left any_goals exact fun x hx => card_parts_equitabilise _ _ (Nat.div_pos hPα' hPpos).ne' rw [Nat.sub_add_cancel a_add_one_le_four_pow_parts_card, Nat.sub_add_cancel ((Nat.le_succ _).trans a_add_one_le_four_pow_parts_card), ← add_mul] congr rw [filter_card_add_filter_neg_card_eq_card, card_attach] variable (hP G ε) theorem increment_isEquipartition : (increment hP G ε).IsEquipartition := by simp_rw [IsEquipartition, Set.equitableOn_iff_exists_eq_eq_add_one] refine ⟨m, fun A hA => ?_⟩ rw [mem_coe, increment, mem_bind] at hA obtain ⟨U, hU, hA⟩ := hA exact card_eq_of_mem_parts_chunk hA /-- The contribution to `Finpartition.energy` of a pair of distinct parts of a `Finpartition`. -/ private noncomputable def distinctPairs (x : {x // x ∈ P.parts.offDiag}) : Finset (Finset α × Finset α) := (chunk hP G ε (mem_offDiag.1 x.2).1).parts ×ˢ (chunk hP G ε (mem_offDiag.1 x.2).2.1).parts variable {hP G ε} private theorem distinctPairs_increment : P.parts.offDiag.attach.biUnion (distinctPairs hP G ε) ⊆ (increment hP G ε).parts.offDiag := by rintro ⟨Ui, Vj⟩ simp only [distinctPairs, increment, mem_offDiag, bind_parts, mem_biUnion, Prod.exists, exists_and_left, exists_prop, mem_product, mem_attach, true_and_iff, Subtype.exists, and_imp, mem_offDiag, forall_exists_index, exists₂_imp, Ne] refine fun U V hUV hUi hVj => ⟨⟨_, hUV.1, hUi⟩, ⟨_, hUV.2.1, hVj⟩, ?_⟩ rintro rfl obtain ⟨i, hi⟩ := nonempty_of_mem_parts _ hUi exact hUV.2.2 (P.disjoint.elim_finset hUV.1 hUV.2.1 i (Finpartition.le _ hUi hi) <| Finpartition.le _ hVj hi) private lemma pairwiseDisjoint_distinctPairs : (P.parts.offDiag.attach : Set {x // x ∈ P.parts.offDiag}).PairwiseDisjoint (distinctPairs hP G ε) := by simp (config := { unfoldPartialApp := true }) only [distinctPairs, Set.PairwiseDisjoint, Function.onFun, disjoint_left, inf_eq_inter, mem_inter, mem_product] rintro ⟨⟨s₁, s₂⟩, hs⟩ _ ⟨⟨t₁, t₂⟩, ht⟩ _ hst ⟨u, v⟩ huv₁ huv₂ rw [mem_offDiag] at hs ht obtain ⟨a, ha⟩ := Finpartition.nonempty_of_mem_parts _ huv₁.1 obtain ⟨b, hb⟩ := Finpartition.nonempty_of_mem_parts _ huv₁.2 exact hst <| Subtype.ext_val <| Prod.ext (P.disjoint.elim_finset hs.1 ht.1 a (Finpartition.le _ huv₁.1 ha) <| Finpartition.le _ huv₂.1 ha) <| P.disjoint.elim_finset hs.2.1 ht.2.1 b (Finpartition.le _ huv₁.2 hb) <| Finpartition.le _ huv₂.2 hb variable [Nonempty α] lemma le_sum_distinctPairs_edgeDensity_sq (x : {i // i ∈ P.parts.offDiag}) (hε₁ : ε ≤ 1) (hPα : P.parts.card * 16 ^ P.parts.card ≤ card α) (hPε : ↑100 ≤ ↑4 ^ P.parts.card * ε ^ 5) : (G.edgeDensity x.1.1 x.1.2 : ℝ) ^ 2 + ((if G.IsUniform ε x.1.1 x.1.2 then 0 else ε ^ 4 / 3) - ε ^ 5 / 25) ≤ (∑ i ∈ distinctPairs hP G ε x, G.edgeDensity i.1 i.2 ^ 2 : ℝ) / 16 ^ P.parts.card := by rw [distinctPairs, ← add_sub_assoc, add_sub_right_comm] split_ifs with h · rw [add_zero] exact edgeDensity_chunk_uniform hPα hPε _ _ · exact edgeDensity_chunk_not_uniform hPα hPε hε₁ (mem_offDiag.1 x.2).2.2 h /-- The increment partition has energy greater than the original one by a known fixed amount. -/ theorem energy_increment (hP : P.IsEquipartition) (hP₇ : 7 ≤ P.parts.card) (hPε : 100 ≤ 4 ^ P.parts.card * ε ^ 5) (hPα : P.parts.card * 16 ^ P.parts.card ≤ card α) (hPG : ¬P.IsUniform G ε) (hε₀ : 0 ≤ ε) (hε₁ : ε ≤ 1) : ↑(P.energy G) + ε ^ 5 / 4 ≤ (increment hP G ε).energy G := by calc _ = (∑ x ∈ P.parts.offDiag, (G.edgeDensity x.1 x.2 : ℝ) ^ 2 + P.parts.card ^ 2 * (ε ^ 5 / 4) : ℝ) / P.parts.card ^ 2 := by rw [coe_energy, add_div, mul_div_cancel_left₀]; positivity _ ≤ (∑ x ∈ P.parts.offDiag.attach, (∑ i ∈ distinctPairs hP G ε x, G.edgeDensity i.1 i.2 ^ 2 : ℝ) / 16 ^ P.parts.card) / P.parts.card ^ 2 := ?_ _ = (∑ x ∈ P.parts.offDiag.attach, ∑ i ∈ distinctPairs hP G ε x, G.edgeDensity i.1 i.2 ^ 2 : ℝ) / (increment hP G ε).parts.card ^ 2 := by rw [card_increment hPα hPG, coe_stepBound, mul_pow, pow_right_comm, div_mul_eq_div_div_swap, ← sum_div]; norm_num _ ≤ _ := by rw [coe_energy] gcongr rw [← sum_biUnion pairwiseDisjoint_distinctPairs] exact sum_le_sum_of_subset_of_nonneg distinctPairs_increment fun i _ _ ↦ sq_nonneg _ gcongr rw [Finpartition.IsUniform, not_le, mul_tsub, mul_one, ← offDiag_card] at hPG calc _ ≤ ∑ x ∈ P.parts.offDiag, (edgeDensity G x.1 x.2 : ℝ) ^ 2 + ((nonUniforms P G ε).card * (ε ^ 4 / 3) - P.parts.offDiag.card * (ε ^ 5 / 25)) := add_le_add_left ?_ _ _ = ∑ x ∈ P.parts.offDiag, ((G.edgeDensity x.1 x.2 : ℝ) ^ 2 + ((if G.IsUniform ε x.1 x.2 then (0 : ℝ) else ε ^ 4 / 3) - ε ^ 5 / 25) : ℝ) := by rw [sum_add_distrib, sum_sub_distrib, sum_const, nsmul_eq_mul, sum_ite, sum_const_zero, zero_add, sum_const, nsmul_eq_mul, ← Finpartition.nonUniforms, ← add_sub_assoc, add_sub_right_comm] _ = _ := (sum_attach ..).symm _ ≤ _ := sum_le_sum fun i _ ↦ le_sum_distinctPairs_edgeDensity_sq i hε₁ hPα hPε calc _ = (6/7 * P.parts.card ^ 2) * ε ^ 5 * (7 / 24) := by ring _ ≤ P.parts.offDiag.card * ε ^ 5 * (22 / 75) := by gcongr ?_ * _ * ?_ · rw [← mul_div_right_comm, div_le_iff (by norm_num), offDiag_card] norm_cast rw [tsub_mul] refine le_tsub_of_add_le_left ?_ nlinarith · norm_num _ = (P.parts.offDiag.card * ε * (ε ^ 4 / 3) - P.parts.offDiag.card * (ε ^ 5 / 25)) := by ring _ ≤ ((nonUniforms P G ε).card * (ε ^ 4 / 3) - P.parts.offDiag.card * (ε ^ 5 / 25)) := by gcongr end SzemerediRegularity
Combinatorics\SimpleGraph\Regularity\Lemma.lean
/- Copyright (c) 2021 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import Mathlib.Combinatorics.SimpleGraph.Regularity.Increment /-! # Szemerédi's Regularity Lemma In this file, we prove Szemerédi's Regularity Lemma (aka SRL). This is a landmark result in combinatorics roughly stating that any sufficiently big graph behaves like a random graph. This is useful because random graphs are well-behaved in many aspects. More precisely, SRL states that for any `ε > 0` and integer `l` there exists a bound `M` such that any graph on at least `l` vertices can be partitioned into at least `l` parts and at most `M` parts such that the resulting partitioned graph is `ε`-uniform. This statement is very robust to tweaking and many different versions exist. Here, we prove the version where the resulting partition is equitable (aka an *equipartition*), namely all parts have the same size up to a difference of `1`. The proof we formalise goes as follows: 1. Define an auxiliary measure of edge density, the *energy* of a partition. 2. Start with an arbitrary equipartition of size `l`. 3. Repeatedly break up the parts of the current equipartition in a big but controlled number of parts. The key point is to break along the witnesses of non-uniformity, so that a lesser portion of the pairs of parts are non-`ε`-uniform. 4. Check that this results in an equipartition with an energy greater than the energy of the current partition, plus some constant. 5. Since the energy is between zero and one, we can't run this process forever. Check that when the process stops we have an `ε`-uniform equipartition. This file only contains the final result. The supporting material is spread across the `Combinatorics/SimpleGraph/Regularity` folder: * `Combinatorics/SimpleGraph/Regularity/Bound`: Definition of the bound on the number of parts. Numerical inequalities involving the lemma constants. * `Combinatorics/SimpleGraph/Regularity/Energy`: Definition of the energy of a simple graph along a partition. * `Combinatorics/SimpleGraph/Regularity/Uniform`: Definition of uniformity of a simple graph along a pair of parts and along a partition. * `Combinatorics/SimpleGraph/Regularity/Equitabilise`: Construction of an equipartition with a prescribed number of parts of each size and almost refining a given partition. * `Combinatorics/SimpleGraph/Regularity/Chunk`: Break up one part of the current equipartition. Check that density between non-uniform parts increases, and that density between uniform parts doesn't decrease too much. * `Combinatorics/SimpleGraph/Regularity/Increment`: Gather all those broken up parts into the new equipartition (aka *increment partition*). Check that energy increases by at least a fixed amount. * `Combinatorics/SimpleGraph/Regularity/Lemma`: Wrap everything up into an induction on the energy. ## TODO We currently only prove the equipartition version of SRL. * Prove the diagonal version. * Prove the degree version. * Define the regularity of a partition and prove the corresponding version. ## References [Yaël Dillies, Bhavik Mehta, *Formalising Szemerédi’s Regularity Lemma in Lean*][srl_itp] -/ open Finpartition Finset Fintype Function SzemerediRegularity variable {α : Type*} [DecidableEq α] [Fintype α] (G : SimpleGraph α) [DecidableRel G.Adj] {ε : ℝ} {l : ℕ} /-- Effective **Szemerédi Regularity Lemma**: For any sufficiently large graph, there is an `ε`-uniform equipartition of bounded size (where the bound does not depend on the graph). -/ theorem szemeredi_regularity (hε : 0 < ε) (hl : l ≤ card α) : ∃ P : Finpartition univ, P.IsEquipartition ∧ l ≤ P.parts.card ∧ P.parts.card ≤ bound ε l ∧ P.IsUniform G ε := by obtain hα | hα := le_total (card α) (bound ε l) -- If `card α ≤ bound ε l`, then the partition into singletons is acceptable. · refine ⟨⊥, bot_isEquipartition _, ?_⟩ rw [card_bot, card_univ] exact ⟨hl, hα, bot_isUniform _ hε⟩ -- Else, let's start from a dummy equipartition of size `initialBound ε l`. let t := initialBound ε l have htα : t ≤ (univ : Finset α).card := (initialBound_le_bound _ _).trans (by rwa [Finset.card_univ]) obtain ⟨dum, hdum₁, hdum₂⟩ := exists_equipartition_card_eq (univ : Finset α) (initialBound_pos _ _).ne' htα obtain hε₁ | hε₁ := le_total 1 ε -- If `ε ≥ 1`, then this dummy equipartition is `ε`-uniform, so we're done. · exact ⟨dum, hdum₁, (le_initialBound ε l).trans hdum₂.ge, hdum₂.le.trans (initialBound_le_bound ε l), (dum.isUniform_one G).mono hε₁⟩ -- Else, set up the induction on energy. We phrase it through the existence for each `i` of an -- equipartition of size bounded by `stepBound^[i] (initialBound ε l)` and which is either -- `ε`-uniform or has energy at least `ε ^ 5 / 4 * i`. have : Nonempty α := by rw [← Fintype.card_pos_iff] exact (bound_pos _ _).trans_le hα suffices h : ∀ i, ∃ P : Finpartition (univ : Finset α), P.IsEquipartition ∧ t ≤ P.parts.card ∧ P.parts.card ≤ stepBound^[i] t ∧ (P.IsUniform G ε ∨ ε ^ 5 / 4 * i ≤ P.energy G) by -- For `i > 4 / ε ^ 5` we know that the partition we get can't have energy `≥ ε ^ 5 / 4 * i > 1`, -- so it must instead be `ε`-uniform and we won. obtain ⟨P, hP₁, hP₂, hP₃, hP₄⟩ := h (⌊4 / ε ^ 5⌋₊ + 1) refine ⟨P, hP₁, (le_initialBound _ _).trans hP₂, hP₃.trans ?_, hP₄.resolve_right fun hPenergy => lt_irrefl (1 : ℝ) ?_⟩ · rw [iterate_succ_apply'] exact mul_le_mul_left' (pow_le_pow_left (by norm_num) (by norm_num) _) _ calc (1 : ℝ) = ε ^ 5 / ↑4 * (↑4 / ε ^ 5) := by rw [mul_comm, div_mul_div_cancel 4 (pow_pos hε 5).ne']; norm_num _ < ε ^ 5 / 4 * (⌊4 / ε ^ 5⌋₊ + 1) := ((mul_lt_mul_left <| by positivity).2 (Nat.lt_floor_add_one _)) _ ≤ (P.energy G : ℝ) := by rwa [← Nat.cast_add_one] _ ≤ 1 := mod_cast P.energy_le_one G -- Let's do the actual induction. intro i induction' i with i ih -- For `i = 0`, the dummy equipartition is enough. · refine ⟨dum, hdum₁, hdum₂.ge, hdum₂.le, Or.inr ?_⟩ rw [Nat.cast_zero, mul_zero] exact mod_cast dum.energy_nonneg G -- For the induction step at `i + 1`, find `P` the equipartition at `i`. obtain ⟨P, hP₁, hP₂, hP₃, hP₄⟩ := ih by_cases huniform : P.IsUniform G ε -- If `P` is already uniform, then no need to break it up further. We can just return `P` again. · refine ⟨P, hP₁, hP₂, ?_, Or.inl huniform⟩ rw [iterate_succ_apply'] exact hP₃.trans (le_stepBound _) -- Else, `P` must instead have energy at least `ε ^ 5 / 4 * i`. replace hP₄ := hP₄.resolve_left huniform -- We gather a few numerical facts. have hεl' : 100 ≤ 4 ^ P.parts.card * ε ^ 5 := (hundred_lt_pow_initialBound_mul hε l).le.trans (mul_le_mul_of_nonneg_right (pow_le_pow_right (by norm_num) hP₂) <| by positivity) have hi : (i : ℝ) ≤ 4 / ε ^ 5 := by have hi : ε ^ 5 / 4 * ↑i ≤ 1 := hP₄.trans (mod_cast P.energy_le_one G) rw [div_mul_eq_mul_div, div_le_iff (show (0 : ℝ) < 4 by norm_num)] at hi norm_num at hi rwa [le_div_iff' (pow_pos hε _)] have hsize : P.parts.card ≤ stepBound^[⌊4 / ε ^ 5⌋₊] t := hP₃.trans (monotone_iterate_of_id_le le_stepBound (Nat.le_floor hi) _) have hPα : P.parts.card * 16 ^ P.parts.card ≤ card α := (Nat.mul_le_mul hsize (Nat.pow_le_pow_of_le_right (by norm_num) hsize)).trans hα -- We return the increment equipartition of `P`, which has energy `≥ ε ^ 5 / 4 * (i + 1)`. refine ⟨increment hP₁ G ε, increment_isEquipartition hP₁ G ε, ?_, ?_, Or.inr <| le_trans ?_ <| energy_increment hP₁ ((seven_le_initialBound ε l).trans hP₂) hεl' hPα huniform hε.le hε₁⟩ · rw [card_increment hPα huniform] exact hP₂.trans (le_stepBound _) · rw [card_increment hPα huniform, iterate_succ_apply'] exact stepBound_mono hP₃ · rw [Nat.cast_succ, mul_add, mul_one] exact add_le_add_right hP₄ _
Combinatorics\SimpleGraph\Regularity\Uniform.lean
/- Copyright (c) 2022 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import Mathlib.Algebra.BigOperators.Ring import Mathlib.Combinatorics.SimpleGraph.Density import Mathlib.Data.Nat.Cast.Order.Field import Mathlib.Order.Partition.Equipartition import Mathlib.SetTheory.Ordinal.Basic /-! # Graph uniformity and uniform partitions In this file we define uniformity of a pair of vertices in a graph and uniformity of a partition of vertices of a graph. Both are also known as ε-regularity. Finsets of vertices `s` and `t` are `ε`-uniform in a graph `G` if their edge density is at most `ε`-far from the density of any big enough `s'` and `t'` where `s' ⊆ s`, `t' ⊆ t`. The definition is pretty technical, but it amounts to the edges between `s` and `t` being "random" The literature contains several definitions which are equivalent up to scaling `ε` by some constant when the partition is equitable. A partition `P` of the vertices is `ε`-uniform if the proportion of non `ε`-uniform pairs of parts is less than `ε`. ## Main declarations * `SimpleGraph.IsUniform`: Graph uniformity of a pair of finsets of vertices. * `SimpleGraph.nonuniformWitness`: `G.nonuniformWitness ε s t` and `G.nonuniformWitness ε t s` together witness the non-uniformity of `s` and `t`. * `Finpartition.nonUniforms`: Non uniform pairs of parts of a partition. * `Finpartition.IsUniform`: Uniformity of a partition. * `Finpartition.nonuniformWitnesses`: For each non-uniform pair of parts of a partition, pick witnesses of non-uniformity and dump them all together. ## References [Yaël Dillies, Bhavik Mehta, *Formalising Szemerédi’s Regularity Lemma in Lean*][srl_itp] -/ open Finset variable {α 𝕜 : Type*} [LinearOrderedField 𝕜] /-! ### Graph uniformity -/ namespace SimpleGraph variable (G : SimpleGraph α) [DecidableRel G.Adj] (ε : 𝕜) {s t : Finset α} {a b : α} /-- A pair of finsets of vertices is `ε`-uniform (aka `ε`-regular) iff their edge density is close to the density of any big enough pair of subsets. Intuitively, the edges between them are random-like. -/ def IsUniform (s t : Finset α) : Prop := ∀ ⦃s'⦄, s' ⊆ s → ∀ ⦃t'⦄, t' ⊆ t → (s.card : 𝕜) * ε ≤ s'.card → (t.card : 𝕜) * ε ≤ t'.card → |(G.edgeDensity s' t' : 𝕜) - (G.edgeDensity s t : 𝕜)| < ε variable {G ε} instance IsUniform.instDecidableRel : DecidableRel (G.IsUniform ε) := by unfold IsUniform; infer_instance theorem IsUniform.mono {ε' : 𝕜} (h : ε ≤ ε') (hε : IsUniform G ε s t) : IsUniform G ε' s t := fun s' hs' t' ht' hs ht => by refine (hε hs' ht' (le_trans ?_ hs) (le_trans ?_ ht)).trans_le h <;> gcongr theorem IsUniform.symm : Symmetric (IsUniform G ε) := fun s t h t' ht' s' hs' ht hs => by rw [edgeDensity_comm _ t', edgeDensity_comm _ t] exact h hs' ht' hs ht variable (G) theorem isUniform_comm : IsUniform G ε s t ↔ IsUniform G ε t s := ⟨fun h => h.symm, fun h => h.symm⟩ lemma isUniform_one : G.IsUniform (1 : 𝕜) s t := by intro s' hs' t' ht' hs ht rw [mul_one] at hs ht rw [eq_of_subset_of_card_le hs' (Nat.cast_le.1 hs), eq_of_subset_of_card_le ht' (Nat.cast_le.1 ht), sub_self, abs_zero] exact zero_lt_one variable {G} lemma IsUniform.pos (hG : G.IsUniform ε s t) : 0 < ε := not_le.1 fun hε ↦ (hε.trans $ abs_nonneg _).not_lt $ hG (empty_subset _) (empty_subset _) (by simpa using mul_nonpos_of_nonneg_of_nonpos (Nat.cast_nonneg _) hε) (by simpa using mul_nonpos_of_nonneg_of_nonpos (Nat.cast_nonneg _) hε) @[simp] lemma isUniform_singleton : G.IsUniform ε {a} {b} ↔ 0 < ε := by refine ⟨IsUniform.pos, fun hε s' hs' t' ht' hs ht ↦ ?_⟩ rw [card_singleton, Nat.cast_one, one_mul] at hs ht obtain rfl | rfl := Finset.subset_singleton_iff.1 hs' · replace hs : ε ≤ 0 := by simpa using hs exact (hε.not_le hs).elim obtain rfl | rfl := Finset.subset_singleton_iff.1 ht' · replace ht : ε ≤ 0 := by simpa using ht exact (hε.not_le ht).elim · rwa [sub_self, abs_zero] theorem not_isUniform_zero : ¬G.IsUniform (0 : 𝕜) s t := fun h => (abs_nonneg _).not_lt <| h (empty_subset _) (empty_subset _) (by simp) (by simp) theorem not_isUniform_iff : ¬G.IsUniform ε s t ↔ ∃ s', s' ⊆ s ∧ ∃ t', t' ⊆ t ∧ ↑s.card * ε ≤ s'.card ∧ ↑t.card * ε ≤ t'.card ∧ ε ≤ |G.edgeDensity s' t' - G.edgeDensity s t| := by unfold IsUniform simp only [not_forall, not_lt, exists_prop, exists_and_left, Rat.cast_abs, Rat.cast_sub] open scoped Classical variable (G) /-- An arbitrary pair of subsets witnessing the non-uniformity of `(s, t)`. If `(s, t)` is uniform, returns `(s, t)`. Witnesses for `(s, t)` and `(t, s)` don't necessarily match. See `SimpleGraph.nonuniformWitness`. -/ noncomputable def nonuniformWitnesses (ε : 𝕜) (s t : Finset α) : Finset α × Finset α := if h : ¬G.IsUniform ε s t then ((not_isUniform_iff.1 h).choose, (not_isUniform_iff.1 h).choose_spec.2.choose) else (s, t) theorem left_nonuniformWitnesses_subset (h : ¬G.IsUniform ε s t) : (G.nonuniformWitnesses ε s t).1 ⊆ s := by rw [nonuniformWitnesses, dif_pos h] exact (not_isUniform_iff.1 h).choose_spec.1 theorem left_nonuniformWitnesses_card (h : ¬G.IsUniform ε s t) : (s.card : 𝕜) * ε ≤ (G.nonuniformWitnesses ε s t).1.card := by rw [nonuniformWitnesses, dif_pos h] exact (not_isUniform_iff.1 h).choose_spec.2.choose_spec.2.1 theorem right_nonuniformWitnesses_subset (h : ¬G.IsUniform ε s t) : (G.nonuniformWitnesses ε s t).2 ⊆ t := by rw [nonuniformWitnesses, dif_pos h] exact (not_isUniform_iff.1 h).choose_spec.2.choose_spec.1 theorem right_nonuniformWitnesses_card (h : ¬G.IsUniform ε s t) : (t.card : 𝕜) * ε ≤ (G.nonuniformWitnesses ε s t).2.card := by rw [nonuniformWitnesses, dif_pos h] exact (not_isUniform_iff.1 h).choose_spec.2.choose_spec.2.2.1 theorem nonuniformWitnesses_spec (h : ¬G.IsUniform ε s t) : ε ≤ |G.edgeDensity (G.nonuniformWitnesses ε s t).1 (G.nonuniformWitnesses ε s t).2 - G.edgeDensity s t| := by rw [nonuniformWitnesses, dif_pos h] exact (not_isUniform_iff.1 h).choose_spec.2.choose_spec.2.2.2 /-- Arbitrary witness of non-uniformity. `G.nonuniformWitness ε s t` and `G.nonuniformWitness ε t s` form a pair of subsets witnessing the non-uniformity of `(s, t)`. If `(s, t)` is uniform, returns `s`. -/ noncomputable def nonuniformWitness (ε : 𝕜) (s t : Finset α) : Finset α := if WellOrderingRel s t then (G.nonuniformWitnesses ε s t).1 else (G.nonuniformWitnesses ε t s).2 theorem nonuniformWitness_subset (h : ¬G.IsUniform ε s t) : G.nonuniformWitness ε s t ⊆ s := by unfold nonuniformWitness split_ifs · exact G.left_nonuniformWitnesses_subset h · exact G.right_nonuniformWitnesses_subset fun i => h i.symm theorem le_card_nonuniformWitness (h : ¬G.IsUniform ε s t) : (s.card : 𝕜) * ε ≤ (G.nonuniformWitness ε s t).card := by unfold nonuniformWitness split_ifs · exact G.left_nonuniformWitnesses_card h · exact G.right_nonuniformWitnesses_card fun i => h i.symm theorem nonuniformWitness_spec (h₁ : s ≠ t) (h₂ : ¬G.IsUniform ε s t) : ε ≤ |G.edgeDensity (G.nonuniformWitness ε s t) (G.nonuniformWitness ε t s) - G.edgeDensity s t| := by unfold nonuniformWitness rcases trichotomous_of WellOrderingRel s t with (lt | rfl | gt) · rw [if_pos lt, if_neg (asymm lt)] exact G.nonuniformWitnesses_spec h₂ · cases h₁ rfl · rw [if_neg (asymm gt), if_pos gt, edgeDensity_comm, edgeDensity_comm _ s] apply G.nonuniformWitnesses_spec fun i => h₂ i.symm end SimpleGraph /-! ### Uniform partitions -/ variable [DecidableEq α] {A : Finset α} (P : Finpartition A) (G : SimpleGraph α) [DecidableRel G.Adj] {ε δ : 𝕜} {u v : Finset α} namespace Finpartition /-- The pairs of parts of a partition `P` which are not `ε`-dense in a graph `G`. Note that we dismiss the diagonal. We do not care whether `s` is `ε`-dense with itself. -/ def sparsePairs (ε : 𝕜) : Finset (Finset α × Finset α) := P.parts.offDiag.filter fun (u, v) ↦ G.edgeDensity u v < ε @[simp] lemma mk_mem_sparsePairs (u v : Finset α) (ε : 𝕜) : (u, v) ∈ P.sparsePairs G ε ↔ u ∈ P.parts ∧ v ∈ P.parts ∧ u ≠ v ∧ G.edgeDensity u v < ε := by rw [sparsePairs, mem_filter, mem_offDiag, and_assoc, and_assoc] lemma sparsePairs_mono {ε ε' : 𝕜} (h : ε ≤ ε') : P.sparsePairs G ε ⊆ P.sparsePairs G ε' := monotone_filter_right _ fun _ ↦ h.trans_lt' /-- The pairs of parts of a partition `P` which are not `ε`-uniform in a graph `G`. Note that we dismiss the diagonal. We do not care whether `s` is `ε`-uniform with itself. -/ def nonUniforms (ε : 𝕜) : Finset (Finset α × Finset α) := P.parts.offDiag.filter fun (u, v) ↦ ¬G.IsUniform ε u v @[simp] lemma mk_mem_nonUniforms : (u, v) ∈ P.nonUniforms G ε ↔ u ∈ P.parts ∧ v ∈ P.parts ∧ u ≠ v ∧ ¬G.IsUniform ε u v := by rw [nonUniforms, mem_filter, mem_offDiag, and_assoc, and_assoc] theorem nonUniforms_mono {ε ε' : 𝕜} (h : ε ≤ ε') : P.nonUniforms G ε' ⊆ P.nonUniforms G ε := monotone_filter_right _ fun _ => mt <| SimpleGraph.IsUniform.mono h theorem nonUniforms_bot (hε : 0 < ε) : (⊥ : Finpartition A).nonUniforms G ε = ∅ := by rw [eq_empty_iff_forall_not_mem] rintro ⟨u, v⟩ simp only [mk_mem_nonUniforms, parts_bot, mem_map, not_and, Classical.not_not, exists_imp]; dsimp rintro x ⟨_, rfl⟩ y ⟨_,rfl⟩ _ rwa [SimpleGraph.isUniform_singleton] /-- A finpartition of a graph's vertex set is `ε`-uniform (aka `ε`-regular) iff the proportion of its pairs of parts that are not `ε`-uniform is at most `ε`. -/ def IsUniform (ε : 𝕜) : Prop := ((P.nonUniforms G ε).card : 𝕜) ≤ (P.parts.card * (P.parts.card - 1) : ℕ) * ε lemma bot_isUniform (hε : 0 < ε) : (⊥ : Finpartition A).IsUniform G ε := by rw [Finpartition.IsUniform, Finpartition.card_bot, nonUniforms_bot _ hε, Finset.card_empty, Nat.cast_zero] exact mul_nonneg (Nat.cast_nonneg _) hε.le lemma isUniform_one : P.IsUniform G (1 : 𝕜) := by rw [IsUniform, mul_one, Nat.cast_le] refine (card_filter_le _ (fun uv => ¬SimpleGraph.IsUniform G 1 (Prod.fst uv) (Prod.snd uv))).trans ?_ rw [offDiag_card, Nat.mul_sub_left_distrib, mul_one] variable {P G} theorem IsUniform.mono {ε ε' : 𝕜} (hP : P.IsUniform G ε) (h : ε ≤ ε') : P.IsUniform G ε' := ((Nat.cast_le.2 <| card_le_card <| P.nonUniforms_mono G h).trans hP).trans <| by gcongr theorem isUniformOfEmpty (hP : P.parts = ∅) : P.IsUniform G ε := by simp [IsUniform, hP, nonUniforms] theorem nonempty_of_not_uniform (h : ¬P.IsUniform G ε) : P.parts.Nonempty := nonempty_of_ne_empty fun h₁ => h <| isUniformOfEmpty h₁ variable (P G ε) (s : Finset α) /-- A choice of witnesses of non-uniformity among the parts of a finpartition. -/ noncomputable def nonuniformWitnesses : Finset (Finset α) := (P.parts.filter fun t => s ≠ t ∧ ¬G.IsUniform ε s t).image (G.nonuniformWitness ε s) variable {P G ε s} {t : Finset α} theorem nonuniformWitness_mem_nonuniformWitnesses (h : ¬G.IsUniform ε s t) (ht : t ∈ P.parts) (hst : s ≠ t) : G.nonuniformWitness ε s t ∈ P.nonuniformWitnesses G ε s := mem_image_of_mem _ <| mem_filter.2 ⟨ht, hst, h⟩ /-! ### Equipartitions -/ open SimpleGraph in lemma IsEquipartition.card_interedges_sparsePairs_le' (hP : P.IsEquipartition) (hε : 0 ≤ ε) : ((P.sparsePairs G ε).biUnion fun (U, V) ↦ G.interedges U V).card ≤ ε * (A.card + P.parts.card) ^ 2 := by calc _ ≤ ∑ UV ∈ P.sparsePairs G ε, ((G.interedges UV.1 UV.2).card : 𝕜) := mod_cast card_biUnion_le _ ≤ ∑ UV ∈ P.sparsePairs G ε, ε * (UV.1.card * UV.2.card) := ?_ _ ≤ _ := sum_le_sum_of_subset_of_nonneg (filter_subset _ _) fun i _ _ ↦ by positivity _ = _ := (mul_sum _ _ _).symm _ ≤ _ := mul_le_mul_of_nonneg_left ?_ hε · gcongr with UV hUV obtain ⟨U, V⟩ := UV simp [mk_mem_sparsePairs, ← card_interedges_div_card] at hUV refine ((div_lt_iff ?_).1 hUV.2.2.2).le exact mul_pos (Nat.cast_pos.2 (P.nonempty_of_mem_parts hUV.1).card_pos) (Nat.cast_pos.2 (P.nonempty_of_mem_parts hUV.2.1).card_pos) norm_cast calc (_ : ℕ) ≤ _ := sum_le_card_nsmul P.parts.offDiag (fun i ↦ i.1.card * i.2.card) ((A.card / P.parts.card + 1)^2 : ℕ) ?_ _ ≤ (P.parts.card * (A.card / P.parts.card) + P.parts.card) ^ 2 := ?_ _ ≤ _ := Nat.pow_le_pow_of_le_left (add_le_add_right (Nat.mul_div_le _ _) _) _ · simp only [Prod.forall, Finpartition.mk_mem_nonUniforms, and_imp, mem_offDiag, sq] rintro U V hU hV - exact_mod_cast Nat.mul_le_mul (hP.card_part_le_average_add_one hU) (hP.card_part_le_average_add_one hV) · rw [smul_eq_mul, offDiag_card, Nat.mul_sub_right_distrib, ← sq, ← mul_pow, mul_add_one (α := ℕ)] exact Nat.sub_le _ _ lemma IsEquipartition.card_interedges_sparsePairs_le (hP : P.IsEquipartition) (hε : 0 ≤ ε) : ((P.sparsePairs G ε).biUnion fun (U, V) ↦ G.interedges U V).card ≤ 4 * ε * A.card ^ 2 := by calc _ ≤ _ := hP.card_interedges_sparsePairs_le' hε _ ≤ ε * (A.card + A.card)^2 := by gcongr; exact P.card_parts_le_card _ = _ := by ring private lemma aux {i j : ℕ} (hj : 0 < j) : j * (j - 1) * (i / j + 1) ^ 2 < (i + j) ^ 2 := by have : j * (j - 1) < j ^ 2 := by rw [sq]; exact Nat.mul_lt_mul_of_pos_left (Nat.sub_lt hj zero_lt_one) hj apply (Nat.mul_lt_mul_of_pos_right this $ pow_pos Nat.succ_pos' _).trans_le rw [← mul_pow] exact Nat.pow_le_pow_of_le_left (add_le_add_right (Nat.mul_div_le i j) _) _ lemma IsEquipartition.card_biUnion_offDiag_le' (hP : P.IsEquipartition) : ((P.parts.biUnion offDiag).card : 𝕜) ≤ A.card * (A.card + P.parts.card) / P.parts.card := by obtain h | h := P.parts.eq_empty_or_nonempty · simp [h] calc _ ≤ (P.parts.card : 𝕜) * (↑(A.card / P.parts.card) * ↑(A.card / P.parts.card + 1)) := mod_cast card_biUnion_le_card_mul _ _ _ fun U hU ↦ ?_ _ = P.parts.card * ↑(A.card / P.parts.card) * ↑(A.card / P.parts.card + 1) := by rw [mul_assoc] _ ≤ A.card * (A.card / P.parts.card + 1) := mul_le_mul (mod_cast Nat.mul_div_le _ _) ?_ (by positivity) (by positivity) _ = _ := by rw [← div_add_same (mod_cast h.card_pos.ne'), mul_div_assoc] · simpa using Nat.cast_div_le suffices (U.card - 1) * U.card ≤ A.card / P.parts.card * (A.card / P.parts.card + 1) by rwa [Nat.mul_sub_right_distrib, one_mul, ← offDiag_card] at this have := hP.card_part_le_average_add_one hU refine Nat.mul_le_mul ((Nat.sub_le_sub_right this 1).trans ?_) this simp only [Nat.add_succ_sub_one, add_zero, card_univ, le_rfl] lemma IsEquipartition.card_biUnion_offDiag_le (hε : 0 < ε) (hP : P.IsEquipartition) (hP' : 4 / ε ≤ P.parts.card) : (P.parts.biUnion offDiag).card ≤ ε / 2 * A.card ^ 2 := by obtain rfl | hA : A = ⊥ ∨ _ := A.eq_empty_or_nonempty · simp [Subsingleton.elim P ⊥] apply hP.card_biUnion_offDiag_le'.trans rw [div_le_iff (Nat.cast_pos.2 (P.parts_nonempty hA.ne_empty).card_pos)] have : (A.card : 𝕜) + P.parts.card ≤ 2 * A.card := by rw [two_mul]; exact add_le_add_left (Nat.cast_le.2 P.card_parts_le_card) _ refine (mul_le_mul_of_nonneg_left this $ by positivity).trans ?_ suffices 1 ≤ ε/4 * P.parts.card by rw [mul_left_comm, ← sq] convert mul_le_mul_of_nonneg_left this (mul_nonneg zero_le_two $ sq_nonneg (A.card : 𝕜)) using 1 <;> ring rwa [← div_le_iff', one_div_div] positivity lemma IsEquipartition.sum_nonUniforms_lt' (hA : A.Nonempty) (hε : 0 < ε) (hP : P.IsEquipartition) (hG : P.IsUniform G ε) : ∑ i ∈ P.nonUniforms G ε, (i.1.card * i.2.card : 𝕜) < ε * (A.card + P.parts.card) ^ 2 := by calc _ ≤ (P.nonUniforms G ε).card • (↑(A.card / P.parts.card + 1) : 𝕜) ^ 2 := sum_le_card_nsmul _ _ _ ?_ _ = _ := nsmul_eq_mul _ _ _ ≤ _ := mul_le_mul_of_nonneg_right hG $ by positivity _ < _ := ?_ · simp only [Prod.forall, Finpartition.mk_mem_nonUniforms, and_imp] rintro U V hU hV - - rw [sq, ← Nat.cast_mul, ← Nat.cast_mul, Nat.cast_le] exact Nat.mul_le_mul (hP.card_part_le_average_add_one hU) (hP.card_part_le_average_add_one hV) · rw [mul_right_comm _ ε, mul_comm ε] apply mul_lt_mul_of_pos_right _ hε norm_cast exact aux (P.parts_nonempty hA.ne_empty).card_pos lemma IsEquipartition.sum_nonUniforms_lt (hA : A.Nonempty) (hε : 0 < ε) (hP : P.IsEquipartition) (hG : P.IsUniform G ε) : ((P.nonUniforms G ε).biUnion fun (U, V) ↦ U ×ˢ V).card < 4 * ε * A.card ^ 2 := by calc _ ≤ ∑ i ∈ P.nonUniforms G ε, (i.1.card * i.2.card : 𝕜) := by norm_cast; simp_rw [← card_product]; exact card_biUnion_le _ < _ := hP.sum_nonUniforms_lt' hA hε hG _ ≤ ε * (A.card + A.card) ^ 2 := by gcongr; exact P.card_parts_le_card _ = _ := by ring end Finpartition /-! ### Reduced graph -/ namespace SimpleGraph /-- The reduction of the graph `G` along partition `P` has edges between `ε`-uniform pairs of parts that have edge density at least `δ`. -/ @[simps] def regularityReduced (ε δ : 𝕜) : SimpleGraph α where Adj a b := G.Adj a b ∧ ∃ U ∈ P.parts, ∃ V ∈ P.parts, a ∈ U ∧ b ∈ V ∧ U ≠ V ∧ G.IsUniform ε U V ∧ δ ≤ G.edgeDensity U V symm a b := by rintro ⟨ab, U, UP, V, VP, xU, yV, UV, GUV, εUV⟩ refine ⟨G.symm ab, V, VP, U, UP, yV, xU, UV.symm, GUV.symm, ?_⟩ rwa [edgeDensity_comm] loopless a h := G.loopless a h.1 instance regularityReduced.instDecidableRel_adj : DecidableRel (G.regularityReduced P ε δ).Adj := by unfold regularityReduced; infer_instance variable {G P} lemma regularityReduced_le : G.regularityReduced P ε δ ≤ G := fun _ _ ↦ And.left lemma regularityReduced_mono {ε₁ ε₂ : 𝕜} (hε : ε₁ ≤ ε₂) : G.regularityReduced P ε₁ δ ≤ G.regularityReduced P ε₂ δ := fun _a _b ⟨hab, U, hU, V, hV, ha, hb, hUV, hGε, hGδ⟩ ↦ ⟨hab, U, hU, V, hV, ha, hb, hUV, hGε.mono hε, hGδ⟩ lemma regularityReduced_anti {δ₁ δ₂ : 𝕜} (hδ : δ₁ ≤ δ₂) : G.regularityReduced P ε δ₂ ≤ G.regularityReduced P ε δ₁ := fun _a _b ⟨hab, U, hU, V, hV, ha, hb, hUV, hUVε, hUVδ⟩ ↦ ⟨hab, U, hU, V, hV, ha, hb, hUV, hUVε, hδ.trans hUVδ⟩ lemma unreduced_edges_subset : (A ×ˢ A).filter (fun (x, y) ↦ G.Adj x y ∧ ¬ (G.regularityReduced P (ε/8) (ε/4)).Adj x y) ⊆ (P.nonUniforms G (ε/8)).biUnion (fun (U, V) ↦ U ×ˢ V) ∪ P.parts.biUnion offDiag ∪ (P.sparsePairs G (ε/4)).biUnion fun (U, V) ↦ G.interedges U V := by rintro ⟨x, y⟩ simp only [mem_sdiff, mem_filter, mem_univ, true_and, regularityReduced_adj, not_and, not_exists, not_le, mem_biUnion, mem_union, exists_prop, mem_product, Prod.exists, mem_offDiag, and_imp, or_assoc, and_assoc, P.mk_mem_nonUniforms, Finpartition.mk_mem_sparsePairs, mem_interedges_iff] intros hx hy h h' replace h' := h' h obtain ⟨U, hU, hx⟩ := P.exists_mem hx obtain ⟨V, hV, hy⟩ := P.exists_mem hy obtain rfl | hUV := eq_or_ne U V · exact Or.inr (Or.inl ⟨U, hU, hx, hy, G.ne_of_adj h⟩) by_cases h₂ : G.IsUniform (ε/8) U V · exact Or.inr $ Or.inr ⟨U, V, hU, hV, hUV, h' _ hU _ hV hx hy hUV h₂, hx, hy, h⟩ · exact Or.inl ⟨U, V, hU, hV, hUV, h₂, hx, hy⟩ end SimpleGraph
Combinatorics\SimpleGraph\Triangle\Basic.lean
/- Copyright (c) 2022 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import Mathlib.Algebra.Order.Field.Basic import Mathlib.Algebra.Order.Ring.Abs import Mathlib.Combinatorics.Enumerative.DoubleCounting import Mathlib.Combinatorics.SimpleGraph.Clique import Mathlib.Data.Finset.Sym import Mathlib.Tactic.GCongr import Mathlib.Tactic.Positivity import Mathlib.Tactic.Positivity.Finset /-! # Triangles in graphs A *triangle* in a simple graph is a `3`-clique, namely a set of three vertices that are pairwise adjacent. This module defines and proves properties about triangles in simple graphs. ## Main declarations * `SimpleGraph.FarFromTriangleFree`: Predicate for a graph such that one must remove a lot of edges from it for it to become triangle-free. This is the crux of the Triangle Removal Lemma. ## TODO * Generalise `FarFromTriangleFree` to other graphs, to state and prove the Graph Removal Lemma. -/ open Finset Nat open Fintype (card) namespace SimpleGraph variable {α β 𝕜 : Type*} [LinearOrderedField 𝕜] {G H : SimpleGraph α} {ε δ : 𝕜} {n : ℕ} {s : Finset α} section LocallyLinear /-- A graph has edge-disjoint triangles if each edge belongs to at most one triangle. -/ def EdgeDisjointTriangles (G : SimpleGraph α) : Prop := (G.cliqueSet 3).Pairwise fun x y ↦ (x ∩ y : Set α).Subsingleton /-- A graph is locally linear if each edge belongs to exactly one triangle. -/ def LocallyLinear (G : SimpleGraph α) : Prop := G.EdgeDisjointTriangles ∧ ∀ ⦃x y⦄, G.Adj x y → ∃ s, G.IsNClique 3 s ∧ x ∈ s ∧ y ∈ s protected lemma LocallyLinear.edgeDisjointTriangles : G.LocallyLinear → G.EdgeDisjointTriangles := And.left nonrec lemma EdgeDisjointTriangles.mono (h : G ≤ H) (hH : H.EdgeDisjointTriangles) : G.EdgeDisjointTriangles := hH.mono $ cliqueSet_mono h @[simp] lemma edgeDisjointTriangles_bot : (⊥ : SimpleGraph α).EdgeDisjointTriangles := by simp [EdgeDisjointTriangles] @[simp] lemma locallyLinear_bot : (⊥ : SimpleGraph α).LocallyLinear := by simp [LocallyLinear] lemma EdgeDisjointTriangles.map (f : α ↪ β) (hG : G.EdgeDisjointTriangles) : (G.map f).EdgeDisjointTriangles := by rw [EdgeDisjointTriangles, cliqueSet_map (by norm_num : 3 ≠ 1), (Finset.map_injective f).injOn.pairwise_image] classical rintro s hs t ht hst dsimp [Function.onFun] rw [← coe_inter, ← map_inter, coe_map, coe_inter] exact (hG hs ht hst).image _ lemma LocallyLinear.map (f : α ↪ β) (hG : G.LocallyLinear) : (G.map f).LocallyLinear := by refine ⟨hG.1.map _, ?_⟩ rintro _ _ ⟨a, b, h, rfl, rfl⟩ obtain ⟨s, hs, ha, hb⟩ := hG.2 h exact ⟨s.map f, hs.map, mem_map_of_mem _ ha, mem_map_of_mem _ hb⟩ @[simp] lemma locallyLinear_comap {G : SimpleGraph β} {e : α ≃ β} : (G.comap e).LocallyLinear ↔ G.LocallyLinear := by refine ⟨fun h ↦ ?_, ?_⟩ · rw [← comap_map_eq e.symm.toEmbedding G, comap_symm, map_symm] exact h.map _ · rw [← Equiv.coe_toEmbedding, ← map_symm] exact LocallyLinear.map _ lemma edgeDisjointTriangles_iff_mem_sym2_subsingleton : G.EdgeDisjointTriangles ↔ ∀ ⦃e : Sym2 α⦄, ¬ e.IsDiag → {s ∈ G.cliqueSet 3 | e ∈ (s : Finset α).sym2}.Subsingleton := by classical have (a b) (hab : a ≠ b) : {s ∈ (G.cliqueSet 3 : Set (Finset α)) | s(a, b) ∈ (s : Finset α).sym2} = {s | G.Adj a b ∧ ∃ c, G.Adj a c ∧ G.Adj b c ∧ s = {a, b, c}} := by ext s simp only [mem_sym2_iff, Sym2.mem_iff, forall_eq_or_imp, forall_eq, Set.sep_and, Set.mem_inter_iff, Set.mem_sep_iff, mem_cliqueSet_iff, Set.mem_setOf_eq, and_and_and_comm (b := _ ∈ _), and_self, is3Clique_iff] constructor · rintro ⟨⟨c, d, e, hcd, hce, hde, rfl⟩, hab⟩ simp only [mem_insert, mem_singleton] at hab obtain ⟨rfl | rfl | rfl, rfl | rfl | rfl⟩ := hab any_goals simp only [*, adj_comm, true_and, Ne, eq_self_iff_true, not_true] at * any_goals first | exact ⟨c, by aesop⟩ | exact ⟨d, by aesop⟩ | exact ⟨e, by aesop⟩ | simp only [*, adj_comm, true_and, Ne, eq_self_iff_true, not_true] at * exact ⟨c, by aesop⟩ | simp only [*, adj_comm, true_and, Ne, eq_self_iff_true, not_true] at * exact ⟨d, by aesop⟩ | simp only [*, adj_comm, true_and, Ne, eq_self_iff_true, not_true] at * exact ⟨e, by aesop⟩ · rintro ⟨hab, c, hac, hbc, rfl⟩ refine ⟨⟨a, b, c, ?_⟩, ?_⟩ <;> simp [*] constructor · rw [Sym2.forall] rintro hG a b hab simp only [Sym2.isDiag_iff_proj_eq] at hab rw [this _ _ (Sym2.mk_isDiag_iff.not.2 hab)] rintro _ ⟨hab, c, hac, hbc, rfl⟩ _ ⟨-, d, had, hbd, rfl⟩ refine hG.eq ?_ ?_ (Set.Nontrivial.not_subsingleton ⟨a, ?_, b, ?_, hab.ne⟩) <;> simp [is3Clique_triple_iff, *] · simp only [EdgeDisjointTriangles, is3Clique_iff, Set.Pairwise, mem_cliqueSet_iff, Ne, forall_exists_index, and_imp, ← Set.not_nontrivial_iff (s := _ ∩ _), not_imp_not, Set.Nontrivial, Set.mem_inter_iff, mem_coe] rintro hG _ a b c hab hac hbc rfl _ d e f hde hdf hef rfl g hg₁ hg₂ h hh₁ hh₂ hgh refine hG (Sym2.mk_isDiag_iff.not.2 hgh) ⟨⟨a, b, c, ?_⟩, by simpa using And.intro hg₁ hh₁⟩ ⟨⟨d, e, f, ?_⟩, by simpa using And.intro hg₂ hh₂⟩ <;> simp [is3Clique_triple_iff, *] alias ⟨EdgeDisjointTriangles.mem_sym2_subsingleton, _⟩ := edgeDisjointTriangles_iff_mem_sym2_subsingleton variable [DecidableEq α] [Fintype α] [DecidableRel G.Adj] instance EdgeDisjointTriangles.instDecidable : Decidable G.EdgeDisjointTriangles := decidable_of_iff ((G.cliqueFinset 3 : Set (Finset α)).Pairwise fun x y ↦ ((x ∩ y).card ≤ 1)) $ by simp only [coe_cliqueFinset, EdgeDisjointTriangles, Finset.card_le_one, ← coe_inter]; rfl instance LocallyLinear.instDecidable : Decidable G.LocallyLinear := And.decidable lemma EdgeDisjointTriangles.card_edgeFinset_le (hG : G.EdgeDisjointTriangles) : 3 * (G.cliqueFinset 3).card ≤ G.edgeFinset.card := by rw [mul_comm, ← mul_one G.edgeFinset.card] refine card_mul_le_card_mul (fun s e ↦ e ∈ s.sym2) ?_ (fun e he ↦ ?_) · simp only [is3Clique_iff, mem_cliqueFinset_iff, mem_sym2_iff, forall_exists_index, and_imp] rintro _ a b c hab hac hbc rfl have : Finset.card ({s(a, b), s(a, c), s(b, c)} : Finset (Sym2 α)) = 3 := by refine card_eq_three.2 ⟨_, _, _, ?_, ?_, ?_, rfl⟩ <;> simp [hab.ne, hac.ne, hbc.ne] rw [← this] refine card_mono ?_ simp [insert_subset, *] · simpa only [card_le_one, mem_bipartiteBelow, and_imp, Set.Subsingleton, Set.mem_setOf_eq, mem_cliqueFinset_iff, mem_cliqueSet_iff] using hG.mem_sym2_subsingleton (G.not_isDiag_of_mem_edgeSet $ mem_edgeFinset.1 he) lemma LocallyLinear.card_edgeFinset (hG : G.LocallyLinear) : G.edgeFinset.card = 3 * (G.cliqueFinset 3).card := by refine hG.edgeDisjointTriangles.card_edgeFinset_le.antisymm' ?_ rw [← mul_comm, ← mul_one (Finset.card _)] refine card_mul_le_card_mul (fun e s ↦ e ∈ s.sym2) ?_ ?_ · simpa [Sym2.forall, Nat.one_le_iff_ne_zero, -Finset.card_eq_zero, Finset.card_ne_zero, Finset.Nonempty] using hG.2 simp only [mem_cliqueFinset_iff, is3Clique_iff, forall_exists_index, and_imp] rintro _ a b c hab hac hbc rfl calc _ ≤ ({s(a, b), s(a, c), s(b, c)} : Finset _).card := card_le_card ?_ _ ≤ 3 := (card_insert_le _ _).trans (succ_le_succ $ (card_insert_le _ _).trans_eq $ by rw [card_singleton]) simp only [subset_iff, Sym2.forall, mem_sym2_iff, le_eq_subset, mem_bipartiteBelow, mem_insert, mem_edgeFinset, mem_singleton, and_imp, mem_edgeSet, Sym2.mem_iff, forall_eq_or_imp, forall_eq, Quotient.eq, Sym2.rel_iff] rintro d e hde (rfl | rfl | rfl) (rfl | rfl | rfl) <;> simp [*] at * end LocallyLinear variable (G ε) variable [Fintype α] [DecidableRel G.Adj] [DecidableRel H.Adj] /-- A simple graph is *`ε`-far from triangle-free* if one must remove at least `ε * (card α) ^ 2` edges to make it triangle-free. -/ def FarFromTriangleFree : Prop := G.DeleteFar (fun H ↦ H.CliqueFree 3) <| ε * (card α ^ 2 : ℕ) variable {G ε} theorem farFromTriangleFree_iff : G.FarFromTriangleFree ε ↔ ∀ ⦃H : SimpleGraph α⦄, [DecidableRel H.Adj] → H ≤ G → H.CliqueFree 3 → ε * (card α ^ 2 : ℕ) ≤ G.edgeFinset.card - H.edgeFinset.card := deleteFar_iff alias ⟨farFromTriangleFree.le_card_sub_card, _⟩ := farFromTriangleFree_iff nonrec theorem FarFromTriangleFree.mono (hε : G.FarFromTriangleFree ε) (h : δ ≤ ε) : G.FarFromTriangleFree δ := hε.mono <| by gcongr section DecidableEq variable [DecidableEq α] theorem FarFromTriangleFree.cliqueFinset_nonempty' (hH : H ≤ G) (hG : G.FarFromTriangleFree ε) (hcard : G.edgeFinset.card - H.edgeFinset.card < ε * (card α ^ 2 : ℕ)) : (H.cliqueFinset 3).Nonempty := nonempty_of_ne_empty <| cliqueFinset_eq_empty_iff.not.2 fun hH' => (hG.le_card_sub_card hH hH').not_lt hcard private lemma farFromTriangleFree_of_disjoint_triangles_aux {tris : Finset (Finset α)} (htris : tris ⊆ G.cliqueFinset 3) (pd : (tris : Set (Finset α)).Pairwise fun x y ↦ (x ∩ y : Set α).Subsingleton) (hHG : H ≤ G) (hH : H.CliqueFree 3) : tris.card ≤ G.edgeFinset.card - H.edgeFinset.card := by rw [← card_sdiff (edgeFinset_mono hHG), ← card_attach] by_contra! hG have ⦃t⦄ (ht : t ∈ tris) : ∃ x y, x ∈ t ∧ y ∈ t ∧ x ≠ y ∧ s(x, y) ∈ G.edgeFinset \ H.edgeFinset := by by_contra! h refine hH t ?_ simp only [not_and, mem_sdiff, not_not, mem_edgeFinset, mem_edgeSet] at h obtain ⟨x, y, z, xy, xz, yz, rfl⟩ := is3Clique_iff.1 (mem_cliqueFinset_iff.1 $ htris ht) rw [is3Clique_triple_iff] refine ⟨h _ _ ?_ ?_ xy.ne xy, h _ _ ?_ ?_ xz.ne xz, h _ _ ?_ ?_ yz.ne yz⟩ <;> simp choose fx fy hfx hfy hfne fmem using this let f (t : {x // x ∈ tris}) : Sym2 α := s(fx t.2, fy t.2) have hf (x) (_ : x ∈ tris.attach) : f x ∈ G.edgeFinset \ H.edgeFinset := fmem _ obtain ⟨⟨t₁, ht₁⟩, -, ⟨t₂, ht₂⟩, -, tne, t : s(_, _) = s(_, _)⟩ := exists_ne_map_eq_of_card_lt_of_maps_to hG hf dsimp at t have i := pd ht₁ ht₂ (Subtype.val_injective.ne tne) rw [Sym2.eq_iff] at t obtain t | t := t · exact hfne _ (i ⟨hfx ht₁, t.1.symm ▸ hfx ht₂⟩ ⟨hfy ht₁, t.2.symm ▸ hfy ht₂⟩) · exact hfne _ (i ⟨hfx ht₁, t.1.symm ▸ hfy ht₂⟩ ⟨hfy ht₁, t.2.symm ▸ hfx ht₂⟩) /-- If there are `ε * (card α)^2` disjoint triangles, then the graph is `ε`-far from being triangle-free. -/ lemma farFromTriangleFree_of_disjoint_triangles (tris : Finset (Finset α)) (htris : tris ⊆ G.cliqueFinset 3) (pd : (tris : Set (Finset α)).Pairwise fun x y ↦ (x ∩ y : Set α).Subsingleton) (tris_big : ε * (card α ^ 2 : ℕ) ≤ tris.card) : G.FarFromTriangleFree ε := by rw [farFromTriangleFree_iff] intros H _ hG hH rw [← Nat.cast_sub (card_le_card $ edgeFinset_mono hG)] exact tris_big.trans (Nat.cast_le.2 $ farFromTriangleFree_of_disjoint_triangles_aux htris pd hG hH) protected lemma EdgeDisjointTriangles.farFromTriangleFree (hG : G.EdgeDisjointTriangles) (tris_big : ε * (card α ^ 2 : ℕ) ≤ (G.cliqueFinset 3).card) : G.FarFromTriangleFree ε := farFromTriangleFree_of_disjoint_triangles _ Subset.rfl (by simpa using hG) tris_big end DecidableEq variable [Nonempty α] lemma FarFromTriangleFree.lt_half (hG : G.FarFromTriangleFree ε) : ε < 2⁻¹ := by classical by_contra! hε refine lt_irrefl (ε * card α ^ 2) ?_ have hε₀ : 0 < ε := hε.trans_lt' (by norm_num) rw [inv_pos_le_iff_one_le_mul (zero_lt_two' 𝕜)] at hε calc _ ≤ (G.edgeFinset.card : 𝕜) := by simpa using hG.le_card_sub_card bot_le (cliqueFree_bot (le_succ _)) _ ≤ ε * 2 * (edgeFinset G).card := le_mul_of_one_le_left (by positivity) (by assumption) _ < ε * card α ^ 2 := ?_ rw [mul_assoc, mul_lt_mul_left hε₀] norm_cast calc _ ≤ 2 * (⊤ : SimpleGraph α).edgeFinset.card := by gcongr; exact le_top _ < card α ^ 2 := ?_ rw [edgeFinset_top, filter_not, card_sdiff (subset_univ _), card_univ, Sym2.card,] simp_rw [choose_two_right, Nat.add_sub_cancel, Nat.mul_comm _ (card α), funext (propext <| Sym2.isDiag_iff_mem_range_diag ·), univ_filter_mem_range, mul_tsub, Nat.mul_div_cancel' (card α).even_mul_succ_self.two_dvd] rw [card_image_of_injective _ Sym2.diag_injective, card_univ, mul_add_one (α := ℕ), two_mul, sq, add_tsub_add_eq_tsub_right] apply tsub_lt_self <;> positivity lemma FarFromTriangleFree.lt_one (hG : G.FarFromTriangleFree ε) : ε < 1 := hG.lt_half.trans $ inv_lt_one one_lt_two theorem FarFromTriangleFree.nonpos (h₀ : G.FarFromTriangleFree ε) (h₁ : G.CliqueFree 3) : ε ≤ 0 := by have := h₀ (empty_subset _) rw [coe_empty, Finset.card_empty, cast_zero, deleteEdges_empty] at this exact nonpos_of_mul_nonpos_left (this h₁) (cast_pos.2 <| sq_pos_of_pos Fintype.card_pos) theorem CliqueFree.not_farFromTriangleFree (hG : G.CliqueFree 3) (hε : 0 < ε) : ¬G.FarFromTriangleFree ε := fun h => (h.nonpos hG).not_lt hε theorem FarFromTriangleFree.not_cliqueFree (hG : G.FarFromTriangleFree ε) (hε : 0 < ε) : ¬G.CliqueFree 3 := fun h => (hG.nonpos h).not_lt hε theorem FarFromTriangleFree.cliqueFinset_nonempty [DecidableEq α] (hG : G.FarFromTriangleFree ε) (hε : 0 < ε) : (G.cliqueFinset 3).Nonempty := nonempty_of_ne_empty <| cliqueFinset_eq_empty_iff.not.2 <| hG.not_cliqueFree hε end SimpleGraph
Combinatorics\SimpleGraph\Triangle\Counting.lean
/- Copyright (c) 2022 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import Mathlib.Combinatorics.SimpleGraph.Clique import Mathlib.Combinatorics.SimpleGraph.Regularity.Uniform import Mathlib.Data.Real.Basic import Mathlib.Tactic.Linarith /-! # Triangle counting lemma In this file, we prove the triangle counting lemma. ## References [Yaël Dillies, Bhavik Mehta, *Formalising Szemerédi’s Regularity Lemma in Lean*][srl_itp] -/ -- TODO: This instance is bad because it creates data out of a Prop attribute [-instance] decidableEq_of_subsingleton open Finset Fintype variable {α : Type*} (G G' : SimpleGraph α) [DecidableRel G.Adj] {ε : ℝ} {s t u : Finset α} namespace SimpleGraph /-- The vertices of `s` whose density in `t` is `ε` less than expected. -/ private noncomputable def badVertices (ε : ℝ) (s t : Finset α) : Finset α := s.filter fun x ↦ (t.filter $ G.Adj x).card < (G.edgeDensity s t - ε) * t.card private lemma card_interedges_badVertices_le : (Rel.interedges G.Adj (badVertices G ε s t) t).card ≤ (badVertices G ε s t).card * t.card * (G.edgeDensity s t - ε) := by classical refine (Nat.cast_le.2 $ (card_le_card $ subset_of_eq (Rel.interedges_eq_biUnion _)).trans card_biUnion_le).trans ?_ simp_rw [Nat.cast_sum, card_map, ← nsmul_eq_mul, smul_mul_assoc, mul_comm (t.card : ℝ)] exact sum_le_card_nsmul _ _ _ fun x hx ↦ (mem_filter.1 hx).2.le private lemma edgeDensity_badVertices_le (hε : 0 ≤ ε) (dst : 2 * ε ≤ G.edgeDensity s t) : G.edgeDensity (badVertices G ε s t) t ≤ G.edgeDensity s t - ε := by rw [edgeDensity_def] push_cast refine div_le_of_nonneg_of_le_mul (by positivity) (sub_nonneg_of_le $ by linarith) ?_ rw [mul_comm] exact G.card_interedges_badVertices_le private lemma card_badVertices_le (dst : 2 * ε ≤ G.edgeDensity s t) (hst : G.IsUniform ε s t) : (badVertices G ε s t).card ≤ s.card * ε := by have hε : ε ≤ 1 := (le_mul_of_one_le_of_le_of_nonneg (by norm_num) le_rfl hst.pos.le).trans (dst.trans $ by exact_mod_cast edgeDensity_le_one _ _ _) by_contra! h have : |(G.edgeDensity (badVertices G ε s t) t - G.edgeDensity s t : ℝ)| < ε := hst (filter_subset _ _) Subset.rfl h.le (mul_le_of_le_one_right (Nat.cast_nonneg _) hε) rw [abs_sub_lt_iff] at this linarith [G.edgeDensity_badVertices_le hst.pos.le dst] /-- A subset of the triangles constructed in a weird way to make them easy to count. -/ private lemma triangle_split_helper [DecidableEq α] : (s \ (badVertices G ε s t ∪ badVertices G ε s u)).biUnion (fun x ↦ (G.interedges (t.filter $ G.Adj x) (u.filter $ G.Adj x)).image (x, ·)) ⊆ (s ×ˢ t ×ˢ u).filter (fun (x, y, z) ↦ G.Adj x y ∧ G.Adj x z ∧ G.Adj y z) := by rintro ⟨x, y, z⟩ simp only [mem_filter, mem_product, mem_biUnion, mem_sdiff, exists_prop, mem_union, mem_image, Prod.exists, and_assoc, exists_imp, and_imp, Prod.mk.inj_iff, mem_interedges_iff] rintro x hx - y z hy xy hz xz yz rfl rfl rfl exact ⟨hx, hy, hz, xy, xz, yz⟩ private lemma good_vertices_triangle_card [DecidableEq α] (dst : 2 * ε ≤ G.edgeDensity s t) (dsu : 2 * ε ≤ G.edgeDensity s u) (dtu : 2 * ε ≤ G.edgeDensity t u) (utu : G.IsUniform ε t u) (x : α) (hx : x ∈ s \ (badVertices G ε s t ∪ badVertices G ε s u)) : ε ^ 3 * t.card * u.card ≤ (((t.filter (G.Adj x) ×ˢ u.filter (G.Adj x)).filter fun (y, z) ↦ G.Adj y z).image (x, ·)).card := by simp only [mem_sdiff, badVertices, mem_union, not_or, mem_filter, not_and_or, not_lt] at hx rw [← or_and_left, and_or_left] at hx simp only [false_or, and_not_self, mul_comm (_ - _)] at hx obtain ⟨-, hxY, hsu⟩ := hx have hY : t.card * ε ≤ (filter (G.Adj x) t).card := (mul_le_mul_of_nonneg_left (by linarith) (Nat.cast_nonneg _)).trans hxY have hZ : u.card * ε ≤ (filter (G.Adj x) u).card := (mul_le_mul_of_nonneg_left (by linarith) (Nat.cast_nonneg _)).trans hsu rw [card_image_of_injective _ (Prod.mk.inj_left _)] have := utu (filter_subset (G.Adj x) _) (filter_subset (G.Adj x) _) hY hZ have : ε ≤ G.edgeDensity (filter (G.Adj x) t) (filter (G.Adj x) u) := by rw [abs_sub_lt_iff] at this; linarith rw [edgeDensity_def] at this push_cast at this have hε := utu.pos.le refine le_trans ?_ (mul_le_of_nonneg_of_le_div (Nat.cast_nonneg _) (by positivity) this) refine Eq.trans_le ?_ (mul_le_mul_of_nonneg_left (mul_le_mul hY hZ (by positivity) (by positivity)) hε) ring /-- The **Triangle Counting Lemma**. If `G` is a graph and `s`, `t`, `u` are sets of vertices such that each pair is `ε`-uniform and `2 * ε`-dense, then a proportion of at least `(1 - 2 * ε) * ε ^ 3` of the triples `(a, b, c) ∈ s × t × u` are triangles. -/ lemma triangle_counting' (dst : 2 * ε ≤ G.edgeDensity s t) (hst : G.IsUniform ε s t) (dsu : 2 * ε ≤ G.edgeDensity s u) (usu : G.IsUniform ε s u) (dtu : 2 * ε ≤ G.edgeDensity t u) (utu : G.IsUniform ε t u) : (1 - 2 * ε) * ε ^ 3 * s.card * t.card * u.card ≤ ((s ×ˢ t ×ˢ u).filter fun (a, b, c) ↦ G.Adj a b ∧ G.Adj a c ∧ G.Adj b c).card := by classical have h₁ : (badVertices G ε s t).card ≤ s.card * ε := G.card_badVertices_le dst hst have h₂ : (badVertices G ε s u).card ≤ s.card * ε := G.card_badVertices_le dsu usu let X' := s \ (badVertices G ε s t ∪ badVertices G ε s u) have : X'.biUnion _ ⊆ (s ×ˢ t ×ˢ u).filter fun (a, b, c) ↦ G.Adj a b ∧ G.Adj a c ∧ G.Adj b c := triangle_split_helper _ refine le_trans ?_ (Nat.cast_le.2 $ card_le_card this) rw [card_biUnion, Nat.cast_sum] · apply le_trans _ (card_nsmul_le_sum X' _ _ $ G.good_vertices_triangle_card dst dsu dtu utu) rw [nsmul_eq_mul] have := hst.pos.le suffices hX' : (1 - 2 * ε) * s.card ≤ X'.card by exact Eq.trans_le (by ring) (mul_le_mul_of_nonneg_right hX' $ by positivity) have i : badVertices G ε s t ∪ badVertices G ε s u ⊆ s := union_subset (filter_subset _ _) (filter_subset _ _) rw [sub_mul, one_mul, card_sdiff i, Nat.cast_sub (card_le_card i), sub_le_sub_iff_left, mul_assoc, mul_comm ε, two_mul] refine (Nat.cast_le.2 $ card_union_le _ _).trans ?_ rw [Nat.cast_add] exact add_le_add h₁ h₂ rintro a _ b _ t rw [disjoint_left] simp only [Prod.forall, mem_image, not_exists, exists_prop, mem_filter, Prod.mk.inj_iff, exists_imp, and_imp, not_and, mem_product, or_assoc] aesop variable [DecidableEq α] private lemma triple_eq_triple_of_mem (hst : Disjoint s t) (hsu : Disjoint s u) (htu : Disjoint t u) {x₁ x₂ y₁ y₂ z₁ z₂ : α} (h : ({x₁, y₁, z₁} : Finset α) = {x₂, y₂, z₂}) (hx₁ : x₁ ∈ s) (hx₂ : x₂ ∈ s) (hy₁ : y₁ ∈ t) (hy₂ : y₂ ∈ t) (hz₁ : z₁ ∈ u) (hz₂ : z₂ ∈ u) : (x₁, y₁, z₁) = (x₂, y₂, z₂) := by simp only [Finset.Subset.antisymm_iff, subset_iff, mem_insert, mem_singleton, forall_eq_or_imp, forall_eq] at h rw [disjoint_left] at hst hsu htu rw [Prod.mk.inj_iff, Prod.mk.inj_iff] simp only [and_assoc, @or_left_comm _ (y₁ = y₂), @or_comm _ (z₁ = z₂), @or_left_comm _ (z₁ = z₂)] at h refine ⟨h.1.resolve_right (not_or_intro ?_ ?_), h.2.1.resolve_right (not_or_intro ?_ ?_), h.2.2.1.resolve_right (not_or_intro ?_ ?_)⟩ <;> · rintro rfl solve_by_elim variable [Fintype α] {P : Finpartition (univ : Finset α)} /-- The **Triangle Counting Lemma**. If `G` is a graph and `s`, `t`, `u` are disjoint sets of vertices such that each pair is `ε`-uniform and `2 * ε`-dense, then `G` contains at least `(1 - 2 * ε) * ε ^ 3 * |s| * |t| * |u|` triangles. -/ lemma triangle_counting (dst : 2 * ε ≤ G.edgeDensity s t) (ust : G.IsUniform ε s t) (hst : Disjoint s t) (dsu : 2 * ε ≤ G.edgeDensity s u) (usu : G.IsUniform ε s u) (hsu : Disjoint s u) (dtu : 2 * ε ≤ G.edgeDensity t u) (utu : G.IsUniform ε t u) (htu : Disjoint t u) : (1 - 2 * ε) * ε ^ 3 * s.card * t.card * u.card ≤ (G.cliqueFinset 3).card := by apply (G.triangle_counting' dst ust dsu usu dtu utu).trans _ rw [Nat.cast_le] refine card_le_card_of_injOn (fun (x, y, z) ↦ {x, y, z}) ?_ ?_ · rintro ⟨x, y, z⟩ simp only [and_imp, mem_filter, mem_product, mem_cliqueFinset_iff, is3Clique_triple_iff] exact fun _ _ _ hxy hxz hyz ↦ ⟨hxy, hxz, hyz⟩ rintro ⟨x₁, y₁, z₁⟩ h₁ ⟨x₂, y₂, z₂⟩ h₂ t simp only [mem_coe, mem_filter, mem_product] at h₁ h₂ apply triple_eq_triple_of_mem hst hsu htu t <;> tauto end SimpleGraph
Combinatorics\SimpleGraph\Triangle\Removal.lean
/- Copyright (c) 2022 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import Mathlib.Combinatorics.SimpleGraph.DegreeSum import Mathlib.Combinatorics.SimpleGraph.Regularity.Lemma import Mathlib.Combinatorics.SimpleGraph.Triangle.Basic import Mathlib.Combinatorics.SimpleGraph.Triangle.Counting /-! # Triangle removal lemma In this file, we prove the triangle removal lemma. ## References [Yaël Dillies, Bhavik Mehta, *Formalising Szemerédi’s Regularity Lemma in Lean*][srl_itp] -/ open Finset Fintype Nat SzemerediRegularity variable {α : Type*} [DecidableEq α] [Fintype α] {G : SimpleGraph α} [DecidableRel G.Adj] {s t : Finset α} {P : Finpartition (univ : Finset α)} {ε : ℝ} namespace SimpleGraph /-- An explicit form for the constant in the triangle removal lemma. Note that this depends on `SzemerediRegularity.bound`, which is a tower-type exponential. This means `triangleRemovalBound` is in practice absolutely tiny. -/ noncomputable def triangleRemovalBound (ε : ℝ) : ℝ := min (2 * ⌈4/ε⌉₊^3)⁻¹ ((1 - ε/4) * (ε/(16 * bound (ε/8) ⌈4/ε⌉₊))^3) lemma triangleRemovalBound_pos (hε : 0 < ε) (hε₁ : ε ≤ 1) : 0 < triangleRemovalBound ε := by have : 0 < 1 - ε / 4 := by linarith unfold triangleRemovalBound positivity lemma triangleRemovalBound_nonpos (hε : ε ≤ 0) : triangleRemovalBound ε ≤ 0 := by rw [triangleRemovalBound, ceil_eq_zero.2 (div_nonpos_of_nonneg_of_nonpos _ hε)] <;> simp lemma triangleRemovalBound_mul_cube_lt (hε : 0 < ε) : triangleRemovalBound ε * ⌈4 / ε⌉₊ ^ 3 < 1 := by calc _ ≤ (2 * ⌈4 / ε⌉₊ ^ 3 : ℝ)⁻¹ * ↑⌈4 / ε⌉₊ ^ 3 := by gcongr; exact min_le_left _ _ _ = 2⁻¹ := by rw [mul_inv, inv_mul_cancel_right₀]; positivity _ < 1 := by norm_num private lemma aux {n k : ℕ} (hk : 0 < k) (hn : k ≤ n) : n < 2 * k * (n / k) := by rw [mul_assoc, two_mul, ← add_lt_add_iff_right (n % k), add_right_comm, add_assoc, mod_add_div n k, add_comm, add_lt_add_iff_right] apply (mod_lt n hk).trans_le simpa using Nat.mul_le_mul_left k ((Nat.one_le_div_iff hk).2 hn) private lemma card_bound (hP₁ : P.IsEquipartition) (hP₃ : P.parts.card ≤ bound (ε / 8) ⌈4/ε⌉₊) (hX : s ∈ P.parts) : card α / (2 * bound (ε / 8) ⌈4 / ε⌉₊ : ℝ) ≤ s.card := by cases isEmpty_or_nonempty α · simp [Fintype.card_eq_zero] have := Finset.Nonempty.card_pos ⟨_, hX⟩ calc _ ≤ card α / (2 * P.parts.card : ℝ) := by gcongr _ ≤ ↑(card α / P.parts.card) := (div_le_iff' (by positivity)).2 $ mod_cast (aux ‹_› P.card_parts_le_card).le _ ≤ (s.card : ℝ) := mod_cast hP₁.average_le_card_part hX private lemma triangle_removal_aux (hε : 0 < ε) (hP₁ : P.IsEquipartition) (hP₃ : P.parts.card ≤ bound (ε / 8) ⌈4/ε⌉₊) (ht : t ∈ (G.regularityReduced P (ε/8) (ε/4)).cliqueFinset 3) : triangleRemovalBound ε * card α ^ 3 ≤ (G.cliqueFinset 3).card := by rw [mem_cliqueFinset_iff, is3Clique_iff] at ht obtain ⟨x, y, z, ⟨-, s, hX, Y, hY, xX, yY, nXY, uXY, dXY⟩, ⟨-, X', hX', Z, hZ, xX', zZ, nXZ, uXZ, dXZ⟩, ⟨-, Y', hY', Z', hZ', yY', zZ', nYZ, uYZ, dYZ⟩, rfl⟩ := ht cases P.disjoint.elim hX hX' (not_disjoint_iff.2 ⟨x, xX, xX'⟩) cases P.disjoint.elim hY hY' (not_disjoint_iff.2 ⟨y, yY, yY'⟩) cases P.disjoint.elim hZ hZ' (not_disjoint_iff.2 ⟨z, zZ, zZ'⟩) have dXY := P.disjoint hX hY nXY have dXZ := P.disjoint hX hZ nXZ have dYZ := P.disjoint hY hZ nYZ have that : 2 * (ε/8) = ε/4 := by ring have : 0 ≤ 1 - 2 * (ε / 8) := by have : ε / 4 ≤ 1 := ‹ε / 4 ≤ _›.trans (by exact mod_cast G.edgeDensity_le_one _ _); linarith calc _ ≤ (1 - ε/4) * (ε/(16 * bound (ε/8) ⌈4/ε⌉₊))^3 * card α ^ 3 := by gcongr; exact min_le_right _ _ _ = (1 - 2 * (ε / 8)) * (ε / 8) ^ 3 * (card α / (2 * bound (ε / 8) ⌈4 / ε⌉₊)) * (card α / (2 * bound (ε / 8) ⌈4 / ε⌉₊)) * (card α / (2 * bound (ε / 8) ⌈4 / ε⌉₊)) := by ring _ ≤ (1 - 2 * (ε / 8)) * (ε / 8) ^ 3 * s.card * Y.card * Z.card := by gcongr <;> exact card_bound hP₁ hP₃ ‹_› _ ≤ _ := triangle_counting G (by rwa [that]) uXY dXY (by rwa [that]) uXZ dXZ (by rwa [that]) uYZ dYZ lemma regularityReduced_edges_card_aux [Nonempty α] (hε : 0 < ε) (hP : P.IsEquipartition) (hPε : P.IsUniform G (ε/8)) (hP' : 4 / ε ≤ P.parts.card) : 2 * (G.edgeFinset.card - (G.regularityReduced P (ε/8) (ε/4)).edgeFinset.card : ℝ) < 2 * ε * (card α ^ 2 : ℕ) := by let A := (P.nonUniforms G (ε/8)).biUnion fun (U, V) ↦ U ×ˢ V let B := P.parts.biUnion offDiag let C := (P.sparsePairs G (ε/4)).biUnion fun (U, V) ↦ G.interedges U V calc _ = ↑((univ ×ˢ univ).filter fun (x, y) ↦ G.Adj x y ∧ ¬(G.regularityReduced P (ε / 8) (ε /4)).Adj x y).card := by rw [univ_product_univ, mul_sub, filter_and_not, cast_card_sdiff] · norm_cast rw [two_mul_card_edgeFinset, two_mul_card_edgeFinset] · exact monotone_filter_right _ fun xy hxy ↦ regularityReduced_le hxy _ ≤ ((A ∪ B ∪ C).card : ℝ) := by gcongr; exact unreduced_edges_subset _ ≤ ((A ∪ B).card + C.card : ℝ) := mod_cast (card_union_le _ _) _ ≤ (A.card + B.card + C.card : ℝ) := by gcongr; exact mod_cast card_union_le _ _ _ < 4 * (ε / 8) * card α ^ 2 + _ + _ := by gcongr; exact hP.sum_nonUniforms_lt univ_nonempty (by positivity) hPε _ ≤ _ + ε / 2 * card α ^ 2 + 4 * (ε / 4) * card α ^ 2 := by gcongr · exact hP.card_biUnion_offDiag_le hε hP' · exact hP.card_interedges_sparsePairs_le (G := G) (ε := ε / 4) (by positivity) _ = 2 * ε * (card α ^ 2 : ℕ) := by norm_cast; ring /-- **Triangle Removal Lemma**. If not all triangles can be removed by removing few edges (on the order of `(card α)^2`), then there were many triangles to start with (on the order of `(card α)^3`). -/ lemma FarFromTriangleFree.le_card_cliqueFinset (hG : G.FarFromTriangleFree ε) : triangleRemovalBound ε * card α ^ 3 ≤ (G.cliqueFinset 3).card := by cases isEmpty_or_nonempty α · simp [Fintype.card_eq_zero] obtain hε | hε := le_or_lt ε 0 · apply (mul_nonpos_of_nonpos_of_nonneg (triangleRemovalBound_nonpos hε) _).trans <;> positivity let l : ℕ := ⌈4 / ε⌉₊ have hl : 4/ε ≤ l := le_ceil (4/ε) cases' le_total (card α) l with hl' hl' · calc _ ≤ triangleRemovalBound ε * ↑l ^ 3 := by gcongr; exact (triangleRemovalBound_pos hε hG.lt_one.le).le _ ≤ (1 : ℝ) := (triangleRemovalBound_mul_cube_lt hε).le _ ≤ _ := by simpa [one_le_iff_ne_zero] using (hG.cliqueFinset_nonempty hε).card_pos.ne' obtain ⟨P, hP₁, hP₂, hP₃, hP₄⟩ := szemeredi_regularity G (by positivity : 0 < ε / 8) hl' have : 4/ε ≤ P.parts.card := hl.trans (cast_le.2 hP₂) have k := regularityReduced_edges_card_aux hε hP₁ hP₄ this rw [mul_assoc] at k replace k := lt_of_mul_lt_mul_left k zero_le_two obtain ⟨t, ht⟩ := hG.cliqueFinset_nonempty' regularityReduced_le k exact triangle_removal_aux hε hP₁ hP₃ ht /-- **Triangle Removal Lemma**. If there are not too many triangles (on the order of `(card α)^3`) then they can all be removed by removing a few edges (on the order of `(card α)^2`). -/ lemma triangle_removal (hG : (G.cliqueFinset 3).card < triangleRemovalBound ε * card α ^ 3) : ∃ G' ≤ G, ∃ _ : DecidableRel G'.Adj, (G.edgeFinset.card - G'.edgeFinset.card : ℝ) < ε * (card α^2 : ℕ) ∧ G'.CliqueFree 3 := by by_contra! h refine hG.not_le (farFromTriangleFree_iff.2 ?_).le_card_cliqueFinset intros G' _ hG hG' exact le_of_not_lt fun i ↦ h G' hG _ i hG' end SimpleGraph namespace Mathlib.Meta.Positivity open Lean.Meta Qq SimpleGraph /-- Extension for the `positivity` tactic: `SimpleGraph.triangleRemovalBound ε` is positive if `0 < ε ≤ 1`. Note this looks for `ε ≤ 1` in the context. -/ @[positivity triangleRemovalBound _] def evalTriangleRemovalBound : PositivityExt where eval {u α} _zα _pα e := do match u, α, e with | 0, ~q(ℝ), ~q(triangleRemovalBound $ε) => let some fvarId ← findLocalDeclWithType? q($ε ≤ 1) | throwError "`ε ≤ 1` is not available in the local context" let hε₁ : Q($ε ≤ 1) := .fvar fvarId let .positive hε ← core q(inferInstance) q(inferInstance) ε | failure assertInstancesCommute pure (.positive q(triangleRemovalBound_pos $hε $hε₁)) | _, _, _ => throwError "failed to match on Int.ceil application" example (ε : ℝ) (hε₀ : 0 < ε) (hε₁ : ε ≤ 1) : 0 < triangleRemovalBound ε := by positivity end Mathlib.Meta.Positivity
Combinatorics\SimpleGraph\Triangle\Tripartite.lean
/- Copyright (c) 2023 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import Mathlib.Combinatorics.SimpleGraph.Triangle.Basic /-! # Construct a tripartite graph from its triangles This file contains the construction of a simple graph on `α ⊕ β ⊕ γ` from a list of triangles `(a, b, c)` (with `a` in the first component, `b` in the second, `c` in the third). We call * `t : Finset (α × β × γ)` the set of *triangle indices* (its elements are not triangles within the graph but instead index them). * *explicit* a triangle of the constructed graph coming from a triangle index. * *accidental* a triangle of the constructed graph not coming from a triangle index. The two important properties of this construction are: * `SimpleGraph.TripartiteFromTriangles.ExplicitDisjoint`: Whether the explicit triangles are edge-disjoint. * `SimpleGraph.TripartiteFromTriangles.NoAccidental`: Whether all triangles are explicit. This construction shows up unrelatedly twice in the theory of Roth numbers: * The lower bound of the Ruzsa-Szemerédi problem: From a set `s` in a finite abelian group `G` of odd order, we construct a tripartite graph on `G ⊕ G ⊕ G`. The triangle indices are `(x, x + a, x + 2 * a)` for `x` any element and `a ∈ s`. The explicit triangles are always edge-disjoint and there is no accidental triangle if `s` is 3AP-free. * The proof of the corners theorem from the triangle removal lemma: For a set `s` in a finite abelian group `G`, we construct a tripartite graph on `G ⊕ G ⊕ G`, whose vertices correspond to the horizontal, vertical and diagonal lines in `G × G`. The explicit triangles are `(h, v, d)` where `h`, `v`, `d` are horizontal, vertical, diagonal lines that intersect in an element of `s`. The explicit triangles are always edge-disjoint and there is no accidental triangle if `s` is corner-free. -/ open Finset Function Sum3 variable {α β γ 𝕜 : Type*} [LinearOrderedField 𝕜] {t : Finset (α × β × γ)} {a a' : α} {b b' : β} {c c' : γ} {x : α × β × γ} {ε : 𝕜} namespace SimpleGraph namespace TripartiteFromTriangles /-- The underlying relation of the tripartite-from-triangles graph. Two vertices are related iff there exists a triangle index containing them both. -/ @[mk_iff] inductive Rel (t : Finset (α × β × γ)) : α ⊕ β ⊕ γ → α ⊕ β ⊕ γ → Prop | in₀₁ ⦃a b c⦄ : (a, b, c) ∈ t → Rel t (in₀ a) (in₁ b) | in₁₀ ⦃a b c⦄ : (a, b, c) ∈ t → Rel t (in₁ b) (in₀ a) | in₀₂ ⦃a b c⦄ : (a, b, c) ∈ t → Rel t (in₀ a) (in₂ c) | in₂₀ ⦃a b c⦄ : (a, b, c) ∈ t → Rel t (in₂ c) (in₀ a) | in₁₂ ⦃a b c⦄ : (a, b, c) ∈ t → Rel t (in₁ b) (in₂ c) | in₂₁ ⦃a b c⦄ : (a, b, c) ∈ t → Rel t (in₂ c) (in₁ b) open Rel lemma rel_irrefl : ∀ x, ¬ Rel t x x := fun _x hx ↦ nomatch hx lemma rel_symm : Symmetric (Rel t) := fun x y h ↦ by cases h <;> constructor <;> assumption /-- The tripartite-from-triangles graph. Two vertices are related iff there exists a triangle index containing them both. -/ def graph (t : Finset (α × β × γ)) : SimpleGraph (α ⊕ β ⊕ γ) := ⟨Rel t, rel_symm, rel_irrefl⟩ namespace Graph @[simp] lemma not_in₀₀ : ¬ (graph t).Adj (in₀ a) (in₀ a') := fun h ↦ nomatch h @[simp] lemma not_in₁₁ : ¬ (graph t).Adj (in₁ b) (in₁ b') := fun h ↦ nomatch h @[simp] lemma not_in₂₂ : ¬ (graph t).Adj (in₂ c) (in₂ c') := fun h ↦ nomatch h @[simp] lemma in₀₁_iff : (graph t).Adj (in₀ a) (in₁ b) ↔ ∃ c, (a, b, c) ∈ t := ⟨by rintro ⟨⟩; exact ⟨_, ‹_›⟩, fun ⟨_, h⟩ ↦ in₀₁ h⟩ @[simp] lemma in₁₀_iff : (graph t).Adj (in₁ b) (in₀ a) ↔ ∃ c, (a, b, c) ∈ t := ⟨by rintro ⟨⟩; exact ⟨_, ‹_›⟩, fun ⟨_, h⟩ ↦ in₁₀ h⟩ @[simp] lemma in₀₂_iff : (graph t).Adj (in₀ a) (in₂ c) ↔ ∃ b, (a, b, c) ∈ t := ⟨by rintro ⟨⟩; exact ⟨_, ‹_›⟩, fun ⟨_, h⟩ ↦ in₀₂ h⟩ @[simp] lemma in₂₀_iff : (graph t).Adj (in₂ c) (in₀ a) ↔ ∃ b, (a, b, c) ∈ t := ⟨by rintro ⟨⟩; exact ⟨_, ‹_›⟩, fun ⟨_, h⟩ ↦ in₂₀ h⟩ @[simp] lemma in₁₂_iff : (graph t).Adj (in₁ b) (in₂ c) ↔ ∃ a, (a, b, c) ∈ t := ⟨by rintro ⟨⟩; exact ⟨_, ‹_›⟩, fun ⟨_, h⟩ ↦ in₁₂ h⟩ @[simp] lemma in₂₁_iff : (graph t).Adj (in₂ c) (in₁ b) ↔ ∃ a, (a, b, c) ∈ t := ⟨by rintro ⟨⟩; exact ⟨_, ‹_›⟩, fun ⟨_, h⟩ ↦ in₂₁ h⟩ lemma in₀₁_iff' : (graph t).Adj (in₀ a) (in₁ b) ↔ ∃ x : α × β × γ, x ∈ t ∧ x.1 = a ∧ x.2.1 = b where mp := by rintro ⟨⟩; exact ⟨_, ‹_›, by simp⟩ mpr := by rintro ⟨⟨a, b, c⟩, h, rfl, rfl⟩; constructor; assumption lemma in₁₀_iff' : (graph t).Adj (in₁ b) (in₀ a) ↔ ∃ x : α × β × γ, x ∈ t ∧ x.2.1 = b ∧ x.1 = a where mp := by rintro ⟨⟩; exact ⟨_, ‹_›, by simp⟩ mpr := by rintro ⟨⟨a, b, c⟩, h, rfl, rfl⟩; constructor; assumption lemma in₀₂_iff' : (graph t).Adj (in₀ a) (in₂ c) ↔ ∃ x : α × β × γ, x ∈ t ∧ x.1 = a ∧ x.2.2 = c where mp := by rintro ⟨⟩; exact ⟨_, ‹_›, by simp⟩ mpr := by rintro ⟨⟨a, b, c⟩, h, rfl, rfl⟩; constructor; assumption lemma in₂₀_iff' : (graph t).Adj (in₂ c) (in₀ a) ↔ ∃ x : α × β × γ, x ∈ t ∧ x.2.2 = c ∧ x.1 = a where mp := by rintro ⟨⟩; exact ⟨_, ‹_›, by simp⟩ mpr := by rintro ⟨⟨a, b, c⟩, h, rfl, rfl⟩; constructor; assumption lemma in₁₂_iff' : (graph t).Adj (in₁ b) (in₂ c) ↔ ∃ x : α × β × γ, x ∈ t ∧ x.2.1 = b ∧ x.2.2 = c where mp := by rintro ⟨⟩; exact ⟨_, ‹_›, by simp⟩ mpr := by rintro ⟨⟨a, b, c⟩, h, rfl, rfl⟩; constructor; assumption lemma in₂₁_iff' : (graph t).Adj (in₂ c) (in₁ b) ↔ ∃ x : α × β × γ, x ∈ t ∧ x.2.2 = c ∧ x.2.1 = b where mp := by rintro ⟨⟩; exact ⟨_, ‹_›, by simp⟩ mpr := by rintro ⟨⟨a, b, c⟩, h, rfl, rfl⟩; constructor; assumption end Graph open Graph /-- Predicate on the triangle indices for the explicit triangles to be edge-disjoint. -/ class ExplicitDisjoint (t : Finset (α × β × γ)) : Prop where inj₀ : ∀ ⦃a b c a'⦄, (a, b, c) ∈ t → (a', b, c) ∈ t → a = a' inj₁ : ∀ ⦃a b c b'⦄, (a, b, c) ∈ t → (a, b', c) ∈ t → b = b' inj₂ : ∀ ⦃a b c c'⦄, (a, b, c) ∈ t → (a, b, c') ∈ t → c = c' /-- Predicate on the triangle indices for there to be no accidental triangle. Note that we cheat a bit, since the exact translation of this informal description would have `(a', b', c') ∈ t` as a conclusion rather than `a = a' ∨ b = b' ∨ c = c'`. Those conditions are equivalent when the explicit triangles are edge-disjoint (which is the case we care about). -/ class NoAccidental (t : Finset (α × β × γ)) : Prop where eq_or_eq_or_eq : ∀ ⦃a a' b b' c c'⦄, (a', b, c) ∈ t → (a, b', c) ∈ t → (a, b, c') ∈ t → a = a' ∨ b = b' ∨ c = c' section DecidableEq variable [DecidableEq α] [DecidableEq β] [DecidableEq γ] instance graph.instDecidableRelAdj : DecidableRel (graph t).Adj | in₀ _a, in₀ _a' => Decidable.isFalse not_in₀₀ | in₀ _a, in₁ _b' => decidable_of_iff' _ in₀₁_iff' | in₀ _a, in₂ _c' => decidable_of_iff' _ in₀₂_iff' | in₁ _b, in₀ _a' => decidable_of_iff' _ in₁₀_iff' | in₁ _b, in₁ _b' => Decidable.isFalse not_in₁₁ | in₁ _b, in₂ _b' => decidable_of_iff' _ in₁₂_iff' | in₂ _c, in₀ _a' => decidable_of_iff' _ in₂₀_iff' | in₂ _c, in₁ _b' => decidable_of_iff' _ in₂₁_iff' | in₂ _c, in₂ _b' => Decidable.isFalse not_in₂₂ /-- This lemma reorders the elements of a triangle in the tripartite graph. It turns a triangle `{x, y, z}` into a triangle `{a, b, c}` where `a : α `, `b : β`, `c : γ`. -/ lemma graph_triple ⦃x y z⦄ : (graph t).Adj x y → (graph t).Adj x z → (graph t).Adj y z → ∃ a b c, ({in₀ a, in₁ b, in₂ c} : Finset (α ⊕ β ⊕ γ)) = {x, y, z} ∧ (graph t).Adj (in₀ a) (in₁ b) ∧ (graph t).Adj (in₀ a) (in₂ c) ∧ (graph t).Adj (in₁ b) (in₂ c) := by rintro (_ | _ | _) (_ | _ | _) (_ | _ | _) <;> refine ⟨_, _, _, by ext; simp only [Finset.mem_insert, Finset.mem_singleton]; try tauto, ?_, ?_, ?_⟩ <;> constructor <;> assumption /-- The map that turns a triangle index into an explicit triangle. -/ @[simps] def toTriangle : α × β × γ ↪ Finset (α ⊕ β ⊕ γ) where toFun x := {in₀ x.1, in₁ x.2.1, in₂ x.2.2} inj' := fun ⟨a, b, c⟩ ⟨a', b', c'⟩ ↦ by simpa only [Finset.Subset.antisymm_iff, Finset.subset_iff, mem_insert, mem_singleton, forall_eq_or_imp, forall_eq, Prod.mk.inj_iff, or_false, false_or, in₀, in₁, in₂, Sum.inl.inj_iff, Sum.inr.inj_iff] using And.left lemma toTriangle_is3Clique (hx : x ∈ t) : (graph t).IsNClique 3 (toTriangle x) := by simp only [toTriangle_apply, is3Clique_triple_iff, in₀₁_iff, in₀₂_iff, in₁₂_iff] exact ⟨⟨_, hx⟩, ⟨_, hx⟩, _, hx⟩ lemma exists_mem_toTriangle {x y : α ⊕ β ⊕ γ} (hxy : (graph t).Adj x y) : ∃ z ∈ t, x ∈ toTriangle z ∧ y ∈ toTriangle z := by cases hxy <;> exact ⟨_, ‹_›, by simp⟩ nonrec lemma is3Clique_iff [NoAccidental t] {s : Finset (α ⊕ β ⊕ γ)} : (graph t).IsNClique 3 s ↔ ∃ x, x ∈ t ∧ toTriangle x = s := by refine ⟨fun h ↦ ?_, ?_⟩ · rw [is3Clique_iff] at h obtain ⟨x, y, z, hxy, hxz, hyz, rfl⟩ := h obtain ⟨a, b, c, habc, hab, hac, hbc⟩ := graph_triple hxy hxz hyz refine ⟨(a, b, c), ?_, habc⟩ obtain ⟨c', hc'⟩ := in₀₁_iff.1 hab obtain ⟨b', hb'⟩ := in₀₂_iff.1 hac obtain ⟨a', ha'⟩ := in₁₂_iff.1 hbc obtain rfl | rfl | rfl := NoAccidental.eq_or_eq_or_eq ha' hb' hc' <;> assumption · rintro ⟨x, hx, rfl⟩ exact toTriangle_is3Clique hx lemma toTriangle_surjOn [NoAccidental t] : (t : Set (α × β × γ)).SurjOn toTriangle ((graph t).cliqueSet 3) := fun _ ↦ is3Clique_iff.1 variable (t) lemma map_toTriangle_disjoint [ExplicitDisjoint t] : (t.map toTriangle : Set (Finset (α ⊕ β ⊕ γ))).Pairwise fun x y ↦ (x ∩ y : Set (α ⊕ β ⊕ γ)).Subsingleton := by clear x intro simp only [Finset.coe_map, Set.mem_image, Finset.mem_coe, Prod.exists, Ne, forall_exists_index, and_imp] rintro a b c habc rfl e x y z hxyz rfl h' have := ne_of_apply_ne _ h' simp only [Ne, Prod.mk.inj_iff, not_and] at this simp only [toTriangle_apply, in₀, in₁, in₂, Set.mem_inter_iff, mem_insert, mem_singleton, mem_coe, and_imp, Sum.forall, or_false, forall_eq, false_or, eq_self_iff_true, imp_true_iff, true_and, and_true, Set.Subsingleton] suffices ¬ (a = x ∧ b = y) ∧ ¬ (a = x ∧ c = z) ∧ ¬ (b = y ∧ c = z) by aesop refine ⟨?_, ?_, ?_⟩ · rintro ⟨rfl, rfl⟩ exact this rfl rfl (ExplicitDisjoint.inj₂ habc hxyz) · rintro ⟨rfl, rfl⟩ exact this rfl (ExplicitDisjoint.inj₁ habc hxyz) rfl · rintro ⟨rfl, rfl⟩ exact this (ExplicitDisjoint.inj₀ habc hxyz) rfl rfl lemma cliqueSet_eq_image [NoAccidental t] : (graph t).cliqueSet 3 = toTriangle '' t := by ext; exact is3Clique_iff section Fintype variable [Fintype α] [Fintype β] [Fintype γ] lemma cliqueFinset_eq_image [NoAccidental t] : (graph t).cliqueFinset 3 = t.image toTriangle := coe_injective $ by push_cast; exact cliqueSet_eq_image _ lemma cliqueFinset_eq_map [NoAccidental t] : (graph t).cliqueFinset 3 = t.map toTriangle := by simp [cliqueFinset_eq_image, map_eq_image] @[simp] lemma card_triangles [NoAccidental t] : ((graph t).cliqueFinset 3).card = t.card := by rw [cliqueFinset_eq_map, card_map] lemma farFromTriangleFree [ExplicitDisjoint t] {ε : 𝕜} (ht : ε * ((Fintype.card α + Fintype.card β + Fintype.card γ) ^ 2 : ℕ) ≤ t.card) : (graph t).FarFromTriangleFree ε := farFromTriangleFree_of_disjoint_triangles (t.map toTriangle) (map_subset_iff_subset_preimage.2 fun x hx ↦ by simpa using toTriangle_is3Clique hx) (map_toTriangle_disjoint t) $ by simpa [add_assoc] using ht end Fintype end DecidableEq variable (t) lemma locallyLinear [ExplicitDisjoint t] [NoAccidental t] : (graph t).LocallyLinear := by classical refine ⟨?_, fun x y hxy ↦ ?_⟩ · unfold EdgeDisjointTriangles convert map_toTriangle_disjoint t rw [cliqueSet_eq_image, coe_map] · obtain ⟨z, hz, hxy⟩ := exists_mem_toTriangle hxy exact ⟨_, toTriangle_is3Clique hz, hxy⟩ end TripartiteFromTriangles end SimpleGraph
Combinatorics\Young\SemistandardTableau.lean
/- Copyright (c) 2022 Jake Levinson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jake Levinson -/ import Mathlib.Combinatorics.Young.YoungDiagram /-! # Semistandard Young tableaux A semistandard Young tableau is a filling of a Young diagram by natural numbers, such that the entries are weakly increasing left-to-right along rows (i.e. for fixed `i`), and strictly-increasing top-to-bottom along columns (i.e. for fixed `j`). An example of an SSYT of shape `μ = [4, 2, 1]` is: ```text 0 0 0 2 1 1 2 ``` We represent a semistandard Young tableau as a function `ℕ → ℕ → ℕ`, which is required to be zero for all pairs `(i, j) ∉ μ` and to satisfy the row-weak and column-strict conditions on `μ`. ## Main definitions - `SemistandardYoungTableau (μ : YoungDiagram)`: semistandard Young tableaux of shape `μ`. There is a `coe` instance such that `T i j` is value of the `(i, j)` entry of the semistandard Young tableau `T`. - `Ssyt.highestWeight (μ : YoungDiagram)`: the semistandard Young tableau whose `i`th row consists entirely of `i`s, for each `i`. ## Tags Semistandard Young tableau ## References <https://en.wikipedia.org/wiki/Young_tableau> -/ /-- A semistandard Young tableau is a filling of the cells of a Young diagram by natural numbers, such that the entries in each row are weakly increasing (left to right), and the entries in each column are strictly increasing (top to bottom). Here, a semistandard Young tableau is represented as an unrestricted function `ℕ → ℕ → ℕ` that, for reasons of extensionality, is required to vanish outside `μ`. -/ structure SemistandardYoungTableau (μ : YoungDiagram) where /-- `entry i j` is value of the `(i, j)` entry of the SSYT `μ`. -/ entry : ℕ → ℕ → ℕ /-- The entries in each row are weakly increasing (left to right). -/ row_weak' : ∀ {i j1 j2 : ℕ}, j1 < j2 → (i, j2) ∈ μ → entry i j1 ≤ entry i j2 /-- The entries in each column are strictly increasing (top to bottom). -/ col_strict' : ∀ {i1 i2 j : ℕ}, i1 < i2 → (i2, j) ∈ μ → entry i1 j < entry i2 j /-- `entry` is required to be zero for all pairs `(i, j) ∉ μ`. -/ zeros' : ∀ {i j}, (i, j) ∉ μ → entry i j = 0 namespace SemistandardYoungTableau instance instFunLike {μ : YoungDiagram} : FunLike (SemistandardYoungTableau μ) ℕ (ℕ → ℕ) where coe := SemistandardYoungTableau.entry coe_injective' T T' h := by cases T cases T' congr /-- Helper instance for when there's too many metavariables to apply `CoeFun.coe` directly. -/ instance {μ : YoungDiagram} : CoeFun (SemistandardYoungTableau μ) fun _ ↦ ℕ → ℕ → ℕ := inferInstance @[simp] theorem to_fun_eq_coe {μ : YoungDiagram} {T : SemistandardYoungTableau μ} : T.entry = (T : ℕ → ℕ → ℕ) := rfl @[ext] theorem ext {μ : YoungDiagram} {T T' : SemistandardYoungTableau μ} (h : ∀ i j, T i j = T' i j) : T = T' := DFunLike.ext T T' fun _ ↦ by funext apply h /-- Copy of an `SemistandardYoungTableau μ` with a new `entry` equal to the old one. Useful to fix definitional equalities. -/ protected def copy {μ : YoungDiagram} (T : SemistandardYoungTableau μ) (entry' : ℕ → ℕ → ℕ) (h : entry' = T) : SemistandardYoungTableau μ where entry := entry' row_weak' := h.symm ▸ T.row_weak' col_strict' := h.symm ▸ T.col_strict' zeros' := h.symm ▸ T.zeros' @[simp] theorem coe_copy {μ : YoungDiagram} (T : SemistandardYoungTableau μ) (entry' : ℕ → ℕ → ℕ) (h : entry' = T) : ⇑(T.copy entry' h) = entry' := rfl theorem copy_eq {μ : YoungDiagram} (T : SemistandardYoungTableau μ) (entry' : ℕ → ℕ → ℕ) (h : entry' = T) : T.copy entry' h = T := DFunLike.ext' h theorem row_weak {μ : YoungDiagram} (T : SemistandardYoungTableau μ) {i j1 j2 : ℕ} (hj : j1 < j2) (hcell : (i, j2) ∈ μ) : T i j1 ≤ T i j2 := T.row_weak' hj hcell theorem col_strict {μ : YoungDiagram} (T : SemistandardYoungTableau μ) {i1 i2 j : ℕ} (hi : i1 < i2) (hcell : (i2, j) ∈ μ) : T i1 j < T i2 j := T.col_strict' hi hcell theorem zeros {μ : YoungDiagram} (T : SemistandardYoungTableau μ) {i j : ℕ} (not_cell : (i, j) ∉ μ) : T i j = 0 := T.zeros' not_cell theorem row_weak_of_le {μ : YoungDiagram} (T : SemistandardYoungTableau μ) {i j1 j2 : ℕ} (hj : j1 ≤ j2) (cell : (i, j2) ∈ μ) : T i j1 ≤ T i j2 := by cases' eq_or_lt_of_le hj with h h · rw [h] · exact T.row_weak h cell theorem col_weak {μ : YoungDiagram} (T : SemistandardYoungTableau μ) {i1 i2 j : ℕ} (hi : i1 ≤ i2) (cell : (i2, j) ∈ μ) : T i1 j ≤ T i2 j := by cases' eq_or_lt_of_le hi with h h · rw [h] · exact le_of_lt (T.col_strict h cell) /-- The "highest weight" SSYT of a given shape has all i's in row i, for each i. -/ def highestWeight (μ : YoungDiagram) : SemistandardYoungTableau μ where entry i j := if (i, j) ∈ μ then i else 0 row_weak' hj hcell := by simp only rw [if_pos hcell, if_pos (μ.up_left_mem (by rfl) (le_of_lt hj) hcell)] col_strict' hi hcell := by simp only rwa [if_pos hcell, if_pos (μ.up_left_mem (le_of_lt hi) (by rfl) hcell)] zeros' not_cell := if_neg not_cell @[simp] theorem highestWeight_apply {μ : YoungDiagram} {i j : ℕ} : highestWeight μ i j = if (i, j) ∈ μ then i else 0 := rfl instance {μ : YoungDiagram} : Inhabited (SemistandardYoungTableau μ) := ⟨highestWeight μ⟩ end SemistandardYoungTableau
Combinatorics\Young\YoungDiagram.lean
/- Copyright (c) 2022 Jake Levinson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jake Levinson -/ import Mathlib.Order.UpperLower.Basic import Mathlib.Data.Finset.Preimage /-! # Young diagrams A Young diagram is a finite set of up-left justified boxes: ```text □□□□□ □□□ □□□ □ ``` This Young diagram corresponds to the [5, 3, 3, 1] partition of 12. We represent it as a lower set in `ℕ × ℕ` in the product partial order. We write `(i, j) ∈ μ` to say that `(i, j)` (in matrix coordinates) is in the Young diagram `μ`. ## Main definitions - `YoungDiagram` : Young diagrams - `YoungDiagram.card` : the number of cells in a Young diagram (its *cardinality*) - `YoungDiagram.instDistribLatticeYoungDiagram` : a distributive lattice instance for Young diagrams ordered by containment, with `(⊥ : YoungDiagram)` the empty diagram. - `YoungDiagram.row` and `YoungDiagram.rowLen`: rows of a Young diagram and their lengths - `YoungDiagram.col` and `YoungDiagram.colLen`: columns of a Young diagram and their lengths ## Notation In "English notation", a Young diagram is drawn so that (i1, j1) ≤ (i2, j2) means (i1, j1) is weakly up-and-left of (i2, j2). This terminology is used below, e.g. in `YoungDiagram.up_left_mem`. ## Tags Young diagram ## References <https://en.wikipedia.org/wiki/Young_tableau> -/ open Function /-- A Young diagram is a finite collection of cells on the `ℕ × ℕ` grid such that whenever a cell is present, so are all the ones above and to the left of it. Like matrices, an `(i, j)` cell is a cell in row `i` and column `j`, where rows are enumerated downward and columns rightward. Young diagrams are modeled as finite sets in `ℕ × ℕ` that are lower sets with respect to the standard order on products. -/ @[ext] structure YoungDiagram where /-- A finite set which represents a finite collection of cells on the `ℕ × ℕ` grid. -/ cells : Finset (ℕ × ℕ) /-- Cells are up-left justified, witnessed by the fact that `cells` is a lower set in `ℕ × ℕ`. -/ isLowerSet : IsLowerSet (cells : Set (ℕ × ℕ)) namespace YoungDiagram instance : SetLike YoungDiagram (ℕ × ℕ) where -- Porting note (#11215): TODO: figure out how to do this correctly coe := fun y => y.cells coe_injective' μ ν h := by rwa [YoungDiagram.ext_iff, ← Finset.coe_inj] @[simp] theorem mem_cells {μ : YoungDiagram} (c : ℕ × ℕ) : c ∈ μ.cells ↔ c ∈ μ := Iff.rfl @[simp] theorem mem_mk (c : ℕ × ℕ) (cells) (isLowerSet) : c ∈ YoungDiagram.mk cells isLowerSet ↔ c ∈ cells := Iff.rfl instance decidableMem (μ : YoungDiagram) : DecidablePred (· ∈ μ) := inferInstanceAs (DecidablePred (· ∈ μ.cells)) /-- In "English notation", a Young diagram is drawn so that (i1, j1) ≤ (i2, j2) means (i1, j1) is weakly up-and-left of (i2, j2). -/ theorem up_left_mem (μ : YoungDiagram) {i1 i2 j1 j2 : ℕ} (hi : i1 ≤ i2) (hj : j1 ≤ j2) (hcell : (i2, j2) ∈ μ) : (i1, j1) ∈ μ := μ.isLowerSet (Prod.mk_le_mk.mpr ⟨hi, hj⟩) hcell section DistribLattice @[simp] theorem cells_subset_iff {μ ν : YoungDiagram} : μ.cells ⊆ ν.cells ↔ μ ≤ ν := Iff.rfl @[simp] theorem cells_ssubset_iff {μ ν : YoungDiagram} : μ.cells ⊂ ν.cells ↔ μ < ν := Iff.rfl instance : Sup YoungDiagram where sup μ ν := { cells := μ.cells ∪ ν.cells isLowerSet := by rw [Finset.coe_union] exact μ.isLowerSet.union ν.isLowerSet } @[simp] theorem cells_sup (μ ν : YoungDiagram) : (μ ⊔ ν).cells = μ.cells ∪ ν.cells := rfl @[simp, norm_cast] theorem coe_sup (μ ν : YoungDiagram) : ↑(μ ⊔ ν) = (μ ∪ ν : Set (ℕ × ℕ)) := Finset.coe_union _ _ @[simp] theorem mem_sup {μ ν : YoungDiagram} {x : ℕ × ℕ} : x ∈ μ ⊔ ν ↔ x ∈ μ ∨ x ∈ ν := Finset.mem_union instance : Inf YoungDiagram where inf μ ν := { cells := μ.cells ∩ ν.cells isLowerSet := by rw [Finset.coe_inter] exact μ.isLowerSet.inter ν.isLowerSet } @[simp] theorem cells_inf (μ ν : YoungDiagram) : (μ ⊓ ν).cells = μ.cells ∩ ν.cells := rfl @[simp, norm_cast] theorem coe_inf (μ ν : YoungDiagram) : ↑(μ ⊓ ν) = (μ ∩ ν : Set (ℕ × ℕ)) := Finset.coe_inter _ _ @[simp] theorem mem_inf {μ ν : YoungDiagram} {x : ℕ × ℕ} : x ∈ μ ⊓ ν ↔ x ∈ μ ∧ x ∈ ν := Finset.mem_inter /-- The empty Young diagram is (⊥ : young_diagram). -/ instance : OrderBot YoungDiagram where bot := { cells := ∅ isLowerSet := by intros a b _ h simp only [Finset.coe_empty, Set.mem_empty_iff_false] simp only [Finset.coe_empty, Set.mem_empty_iff_false] at h } bot_le _ _ := by intro y simp only [mem_mk, Finset.not_mem_empty] at y @[simp] theorem cells_bot : (⊥ : YoungDiagram).cells = ∅ := rfl -- Porting note: removed `↑`, added `.cells` and changed proof -- @[simp] -- Porting note (#10618): simp can prove this @[norm_cast] theorem coe_bot : (⊥ : YoungDiagram).cells = (∅ : Set (ℕ × ℕ)) := by refine Set.eq_of_subset_of_subset ?_ ?_ · intros x h simp? [mem_mk, Finset.coe_empty, Set.mem_empty_iff_false] at h says simp only [cells_bot, Finset.coe_empty, Set.mem_empty_iff_false] at h · simp only [cells_bot, Finset.coe_empty, Set.empty_subset] @[simp] theorem not_mem_bot (x : ℕ × ℕ) : x ∉ (⊥ : YoungDiagram) := Finset.not_mem_empty x instance : Inhabited YoungDiagram := ⟨⊥⟩ instance : DistribLattice YoungDiagram := Function.Injective.distribLattice YoungDiagram.cells (fun μ ν h => by rwa [YoungDiagram.ext_iff]) (fun _ _ => rfl) fun _ _ => rfl end DistribLattice /-- Cardinality of a Young diagram -/ protected abbrev card (μ : YoungDiagram) : ℕ := μ.cells.card section Transpose /-- The `transpose` of a Young diagram is obtained by swapping i's with j's. -/ def transpose (μ : YoungDiagram) : YoungDiagram where cells := (Equiv.prodComm _ _).finsetCongr μ.cells isLowerSet _ _ h := by simp only [Finset.mem_coe, Equiv.finsetCongr_apply, Finset.mem_map_equiv] intro hcell apply μ.isLowerSet _ hcell simp [h] @[simp] theorem mem_transpose {μ : YoungDiagram} {c : ℕ × ℕ} : c ∈ μ.transpose ↔ c.swap ∈ μ := by simp [transpose] @[simp] theorem transpose_transpose (μ : YoungDiagram) : μ.transpose.transpose = μ := by ext x simp theorem transpose_eq_iff_eq_transpose {μ ν : YoungDiagram} : μ.transpose = ν ↔ μ = ν.transpose := by constructor <;> · rintro rfl simp @[simp] theorem transpose_eq_iff {μ ν : YoungDiagram} : μ.transpose = ν.transpose ↔ μ = ν := by rw [transpose_eq_iff_eq_transpose] simp -- This is effectively both directions of `transpose_le_iff` below. protected theorem le_of_transpose_le {μ ν : YoungDiagram} (h_le : μ.transpose ≤ ν) : μ ≤ ν.transpose := fun c hc => by simp only [mem_cells, mem_transpose] apply h_le simpa @[simp] theorem transpose_le_iff {μ ν : YoungDiagram} : μ.transpose ≤ ν.transpose ↔ μ ≤ ν := ⟨fun h => by convert YoungDiagram.le_of_transpose_le h simp, fun h => by rw [← transpose_transpose μ] at h exact YoungDiagram.le_of_transpose_le h ⟩ @[mono] protected theorem transpose_mono {μ ν : YoungDiagram} (h_le : μ ≤ ν) : μ.transpose ≤ ν.transpose := transpose_le_iff.mpr h_le /-- Transposing Young diagrams is an `OrderIso`. -/ @[simps] def transposeOrderIso : YoungDiagram ≃o YoungDiagram := ⟨⟨transpose, transpose, fun _ => by simp, fun _ => by simp⟩, by simp⟩ end Transpose section Rows /-! ### Rows and row lengths of Young diagrams. This section defines `μ.row` and `μ.rowLen`, with the following API: 1. `(i, j) ∈ μ ↔ j < μ.rowLen i` 2. `μ.row i = {i} ×ˢ (Finset.range (μ.rowLen i))` 3. `μ.rowLen i = (μ.row i).card` 4. `∀ {i1 i2}, i1 ≤ i2 → μ.rowLen i2 ≤ μ.rowLen i1` Note: #3 is not convenient for defining `μ.rowLen`; instead, `μ.rowLen` is defined as the smallest `j` such that `(i, j) ∉ μ`. -/ /-- The `i`-th row of a Young diagram consists of the cells whose first coordinate is `i`. -/ def row (μ : YoungDiagram) (i : ℕ) : Finset (ℕ × ℕ) := μ.cells.filter fun c => c.fst = i theorem mem_row_iff {μ : YoungDiagram} {i : ℕ} {c : ℕ × ℕ} : c ∈ μ.row i ↔ c ∈ μ ∧ c.fst = i := by simp [row] theorem mk_mem_row_iff {μ : YoungDiagram} {i j : ℕ} : (i, j) ∈ μ.row i ↔ (i, j) ∈ μ := by simp [row] protected theorem exists_not_mem_row (μ : YoungDiagram) (i : ℕ) : ∃ j, (i, j) ∉ μ := by obtain ⟨j, hj⟩ := Infinite.exists_not_mem_finset (μ.cells.preimage (Prod.mk i) fun _ _ _ _ h => by cases h rfl) rw [Finset.mem_preimage] at hj exact ⟨j, hj⟩ /-- Length of a row of a Young diagram -/ def rowLen (μ : YoungDiagram) (i : ℕ) : ℕ := Nat.find <| μ.exists_not_mem_row i theorem mem_iff_lt_rowLen {μ : YoungDiagram} {i j : ℕ} : (i, j) ∈ μ ↔ j < μ.rowLen i := by rw [rowLen, Nat.lt_find_iff] push_neg exact ⟨fun h _ hmj => μ.up_left_mem (by rfl) hmj h, fun h => h _ (by rfl)⟩ theorem row_eq_prod {μ : YoungDiagram} {i : ℕ} : μ.row i = {i} ×ˢ Finset.range (μ.rowLen i) := by ext ⟨a, b⟩ simp only [Finset.mem_product, Finset.mem_singleton, Finset.mem_range, mem_row_iff, mem_iff_lt_rowLen, and_comm, and_congr_right_iff] rintro rfl rfl theorem rowLen_eq_card (μ : YoungDiagram) {i : ℕ} : μ.rowLen i = (μ.row i).card := by simp [row_eq_prod] @[mono] theorem rowLen_anti (μ : YoungDiagram) (i1 i2 : ℕ) (hi : i1 ≤ i2) : μ.rowLen i2 ≤ μ.rowLen i1 := by by_contra! h_lt rw [← lt_self_iff_false (μ.rowLen i1)] rw [← mem_iff_lt_rowLen] at h_lt ⊢ exact μ.up_left_mem hi (by rfl) h_lt end Rows section Columns /-! ### Columns and column lengths of Young diagrams. This section has an identical API to the rows section. -/ /-- The `j`-th column of a Young diagram consists of the cells whose second coordinate is `j`. -/ def col (μ : YoungDiagram) (j : ℕ) : Finset (ℕ × ℕ) := μ.cells.filter fun c => c.snd = j theorem mem_col_iff {μ : YoungDiagram} {j : ℕ} {c : ℕ × ℕ} : c ∈ μ.col j ↔ c ∈ μ ∧ c.snd = j := by simp [col] theorem mk_mem_col_iff {μ : YoungDiagram} {i j : ℕ} : (i, j) ∈ μ.col j ↔ (i, j) ∈ μ := by simp [col] protected theorem exists_not_mem_col (μ : YoungDiagram) (j : ℕ) : ∃ i, (i, j) ∉ μ.cells := by convert μ.transpose.exists_not_mem_row j using 1 simp /-- Length of a column of a Young diagram -/ def colLen (μ : YoungDiagram) (j : ℕ) : ℕ := Nat.find <| μ.exists_not_mem_col j @[simp] theorem colLen_transpose (μ : YoungDiagram) (j : ℕ) : μ.transpose.colLen j = μ.rowLen j := by simp [rowLen, colLen] @[simp] theorem rowLen_transpose (μ : YoungDiagram) (i : ℕ) : μ.transpose.rowLen i = μ.colLen i := by simp [rowLen, colLen] theorem mem_iff_lt_colLen {μ : YoungDiagram} {i j : ℕ} : (i, j) ∈ μ ↔ i < μ.colLen j := by rw [← rowLen_transpose, ← mem_iff_lt_rowLen] simp theorem col_eq_prod {μ : YoungDiagram} {j : ℕ} : μ.col j = Finset.range (μ.colLen j) ×ˢ {j} := by ext ⟨a, b⟩ simp only [Finset.mem_product, Finset.mem_singleton, Finset.mem_range, mem_col_iff, mem_iff_lt_colLen, and_comm, and_congr_right_iff] rintro rfl rfl theorem colLen_eq_card (μ : YoungDiagram) {j : ℕ} : μ.colLen j = (μ.col j).card := by simp [col_eq_prod] @[mono] theorem colLen_anti (μ : YoungDiagram) (j1 j2 : ℕ) (hj : j1 ≤ j2) : μ.colLen j2 ≤ μ.colLen j1 := by convert μ.transpose.rowLen_anti j1 j2 hj using 1 <;> simp end Columns section RowLens /-! ### The list of row lengths of a Young diagram This section defines `μ.rowLens : List ℕ`, the list of row lengths of a Young diagram `μ`. 1. `YoungDiagram.rowLens_sorted` : It is weakly decreasing (`List.Sorted (· ≥ ·)`). 2. `YoungDiagram.rowLens_pos` : It is strictly positive. -/ /-- List of row lengths of a Young diagram -/ def rowLens (μ : YoungDiagram) : List ℕ := (List.range <| μ.colLen 0).map μ.rowLen @[simp] theorem get_rowLens {μ : YoungDiagram} {i : Nat} {h : i < μ.rowLens.length} : μ.rowLens[i] = μ.rowLen i := by simp only [rowLens, List.getElem_range, List.getElem_map] @[simp] theorem length_rowLens {μ : YoungDiagram} : μ.rowLens.length = μ.colLen 0 := by simp only [rowLens, List.length_map, List.length_range] theorem rowLens_sorted (μ : YoungDiagram) : μ.rowLens.Sorted (· ≥ ·) := (List.pairwise_le_range _).map _ μ.rowLen_anti theorem pos_of_mem_rowLens (μ : YoungDiagram) (x : ℕ) (hx : x ∈ μ.rowLens) : 0 < x := by rw [rowLens, List.mem_map] at hx obtain ⟨i, hi, rfl : μ.rowLen i = x⟩ := hx rwa [List.mem_range, ← mem_iff_lt_colLen, mem_iff_lt_rowLen] at hi end RowLens section EquivListRowLens /-! ### Equivalence between Young diagrams and lists of natural numbers This section defines the equivalence between Young diagrams `μ` and weakly decreasing lists `w` of positive natural numbers, corresponding to row lengths of the diagram: `YoungDiagram.equivListRowLens :` `YoungDiagram ≃ {w : List ℕ // w.Sorted (· ≥ ·) ∧ ∀ x ∈ w, 0 < x}` The two directions are `YoungDiagram.rowLens` (defined above) and `YoungDiagram.ofRowLens`. -/ /-- The cells making up a `YoungDiagram` from a list of row lengths -/ protected def cellsOfRowLens : List ℕ → Finset (ℕ × ℕ) | [] => ∅ | w::ws => ({0} : Finset ℕ) ×ˢ Finset.range w ∪ (YoungDiagram.cellsOfRowLens ws).map (Embedding.prodMap ⟨_, Nat.succ_injective⟩ (Embedding.refl ℕ)) protected theorem mem_cellsOfRowLens {w : List ℕ} {c : ℕ × ℕ} : c ∈ YoungDiagram.cellsOfRowLens w ↔ ∃ h : c.fst < w.length, c.snd < w.get ⟨c.fst, h⟩ := by induction' w with w_hd w_tl w_ih generalizing c <;> rw [YoungDiagram.cellsOfRowLens] · simp [YoungDiagram.cellsOfRowLens] · rcases c with ⟨⟨_, _⟩, _⟩ · simp -- Porting note: was `simpa` · simp [w_ih, -Finset.singleton_product, Nat.succ_lt_succ_iff] /-- Young diagram from a sorted list -/ def ofRowLens (w : List ℕ) (hw : w.Sorted (· ≥ ·)) : YoungDiagram where cells := YoungDiagram.cellsOfRowLens w isLowerSet := by rintro ⟨i2, j2⟩ ⟨i1, j1⟩ ⟨hi : i1 ≤ i2, hj : j1 ≤ j2⟩ hcell rw [Finset.mem_coe, YoungDiagram.mem_cellsOfRowLens] at hcell ⊢ obtain ⟨h1, h2⟩ := hcell refine ⟨hi.trans_lt h1, ?_⟩ calc j1 ≤ j2 := hj _ < w.get ⟨i2, _⟩ := h2 _ ≤ w.get ⟨i1, _⟩ := by obtain rfl | h := eq_or_lt_of_le hi · convert le_refl (w.get ⟨i1, h1⟩) · exact List.pairwise_iff_get.mp hw _ _ h theorem mem_ofRowLens {w : List ℕ} {hw : w.Sorted (· ≥ ·)} {c : ℕ × ℕ} : c ∈ ofRowLens w hw ↔ ∃ h : c.fst < w.length, c.snd < w.get ⟨c.fst, h⟩ := YoungDiagram.mem_cellsOfRowLens /-- The number of rows in `ofRowLens w hw` is the length of `w` -/ theorem rowLens_length_ofRowLens {w : List ℕ} {hw : w.Sorted (· ≥ ·)} (hpos : ∀ x ∈ w, 0 < x) : (ofRowLens w hw).rowLens.length = w.length := by simp only [length_rowLens, colLen, Nat.find_eq_iff, mem_cells, mem_ofRowLens, lt_self_iff_false, IsEmpty.exists_iff, Classical.not_not] exact ⟨not_false, fun n hn => ⟨hn, hpos _ (List.get_mem _ _ hn)⟩⟩ /-- The length of the `i`th row in `ofRowLens w hw` is the `i`th entry of `w` -/ theorem rowLen_ofRowLens {w : List ℕ} {hw : w.Sorted (· ≥ ·)} (i : Fin w.length) : (ofRowLens w hw).rowLen i = w.get i := by simp [rowLen, Nat.find_eq_iff, mem_ofRowLens] /-- The left_inv direction of the equivalence -/ theorem ofRowLens_to_rowLens_eq_self {μ : YoungDiagram} : ofRowLens _ (rowLens_sorted μ) = μ := by ext ⟨i, j⟩ simp only [mem_cells, mem_ofRowLens, length_rowLens, get_rowLens] simpa [← mem_iff_lt_colLen, mem_iff_lt_rowLen] using j.zero_le.trans_lt /-- The right_inv direction of the equivalence -/ theorem rowLens_ofRowLens_eq_self {w : List ℕ} {hw : w.Sorted (· ≥ ·)} (hpos : ∀ x ∈ w, 0 < x) : (ofRowLens w hw).rowLens = w := List.ext_get (rowLens_length_ofRowLens hpos) fun i h₁ h₂ => (get_rowLens (h := h₁)).trans <| rowLen_ofRowLens ⟨i, h₂⟩ /-- Equivalence between Young diagrams and weakly decreasing lists of positive natural numbers. A Young diagram `μ` is equivalent to a list of row lengths. -/ @[simps] def equivListRowLens : YoungDiagram ≃ { w : List ℕ // w.Sorted (· ≥ ·) ∧ ∀ x ∈ w, 0 < x } where toFun μ := ⟨μ.rowLens, μ.rowLens_sorted, μ.pos_of_mem_rowLens⟩ invFun ww := ofRowLens ww.1 ww.2.1 left_inv _ := ofRowLens_to_rowLens_eq_self right_inv := fun ⟨_, hw⟩ => Subtype.mk_eq_mk.mpr (rowLens_ofRowLens_eq_self hw.2) end EquivListRowLens end YoungDiagram
Computability\Ackermann.lean
/- Copyright (c) 2022 Violeta Hernández Palacios. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Violeta Hernández Palacios -/ import Mathlib.Algebra.Order.Ring.Basic import Mathlib.Computability.Primrec import Mathlib.Tactic.Ring import Mathlib.Tactic.Linarith /-! # Ackermann function In this file, we define the two-argument Ackermann function `ack`. Despite having a recursive definition, we show that this isn't a primitive recursive function. ## Main results - `exists_lt_ack_of_nat_primrec`: any primitive recursive function is pointwise bounded above by `ack m` for some `m`. - `not_primrec₂_ack`: the two-argument Ackermann function is not primitive recursive. ## Proof approach We very broadly adapt the proof idea from https://www.planetmath.org/ackermannfunctionisnotprimitiverecursive. Namely, we prove that for any primitive recursive `f : ℕ → ℕ`, there exists `m` such that `f n < ack m n` for all `n`. This then implies that `fun n => ack n n` can't be primitive recursive, and so neither can `ack`. We aren't able to use the same bounds as in that proof though, since our approach of using pairing functions differs from their approach of using multivariate functions. The important bounds we show during the main inductive proof (`exists_lt_ack_of_nat_primrec`) are the following. Assuming `∀ n, f n < ack a n` and `∀ n, g n < ack b n`, we have: - `∀ n, pair (f n) (g n) < ack (max a b + 3) n`. - `∀ n, g (f n) < ack (max a b + 2) n`. - `∀ n, Nat.rec (f n.unpair.1) (fun (y IH : ℕ) => g (pair n.unpair.1 (pair y IH))) n.unpair.2 < ack (max a b + 9) n`. The last one is evidently the hardest. Using `unpair_add_le`, we reduce it to the more manageable - `∀ m n, rec (f m) (fun (y IH : ℕ) => g (pair m (pair y IH))) n < ack (max a b + 9) (m + n)`. We then prove this by induction on `n`. Our proof crucially depends on `ack_pair_lt`, which is applied twice, giving us a constant of `4 + 4`. The rest of the proof consists of simpler bounds which bump up our constant to `9`. -/ open Nat /-- The two-argument Ackermann function, defined so that - `ack 0 n = n + 1` - `ack (m + 1) 0 = ack m 1` - `ack (m + 1) (n + 1) = ack m (ack (m + 1) n)`. This is of interest as both a fast-growing function, and as an example of a recursive function that isn't primitive recursive. -/ def ack : ℕ → ℕ → ℕ | 0, n => n + 1 | m + 1, 0 => ack m 1 | m + 1, n + 1 => ack m (ack (m + 1) n) @[simp] theorem ack_zero (n : ℕ) : ack 0 n = n + 1 := by rw [ack] @[simp] theorem ack_succ_zero (m : ℕ) : ack (m + 1) 0 = ack m 1 := by rw [ack] @[simp] theorem ack_succ_succ (m n : ℕ) : ack (m + 1) (n + 1) = ack m (ack (m + 1) n) := by rw [ack] @[simp] theorem ack_one (n : ℕ) : ack 1 n = n + 2 := by induction' n with n IH · rfl · simp [IH] @[simp] theorem ack_two (n : ℕ) : ack 2 n = 2 * n + 3 := by induction' n with n IH · rfl · simpa [mul_succ] -- Porting note: re-written to get rid of ack_three_aux @[simp] theorem ack_three (n : ℕ) : ack 3 n = 2 ^ (n + 3) - 3 := by induction' n with n IH · rfl · rw [ack_succ_succ, IH, ack_two, Nat.succ_add, Nat.pow_succ 2 (n + 3), mul_comm _ 2, Nat.mul_sub_left_distrib, ← Nat.sub_add_comm, two_mul 3, Nat.add_sub_add_right] have H : 2 * 3 ≤ 2 * 2 ^ 3 := by norm_num apply H.trans rw [_root_.mul_le_mul_left two_pos] exact pow_le_pow_right one_le_two (Nat.le_add_left 3 n) theorem ack_pos : ∀ m n, 0 < ack m n | 0, n => by simp | m + 1, 0 => by rw [ack_succ_zero] apply ack_pos | m + 1, n + 1 => by rw [ack_succ_succ] apply ack_pos theorem one_lt_ack_succ_left : ∀ m n, 1 < ack (m + 1) n | 0, n => by simp | m + 1, 0 => by rw [ack_succ_zero] apply one_lt_ack_succ_left | m + 1, n + 1 => by rw [ack_succ_succ] apply one_lt_ack_succ_left theorem one_lt_ack_succ_right : ∀ m n, 1 < ack m (n + 1) | 0, n => by simp | m + 1, n => by rw [ack_succ_succ] cases' exists_eq_succ_of_ne_zero (ack_pos (m + 1) n).ne' with h h rw [h] apply one_lt_ack_succ_right theorem ack_strictMono_right : ∀ m, StrictMono (ack m) | 0, n₁, n₂, h => by simpa using h | m + 1, 0, n + 1, _h => by rw [ack_succ_zero, ack_succ_succ] exact ack_strictMono_right _ (one_lt_ack_succ_left m n) | m + 1, n₁ + 1, n₂ + 1, h => by rw [ack_succ_succ, ack_succ_succ] apply ack_strictMono_right _ (ack_strictMono_right _ _) rwa [add_lt_add_iff_right] at h theorem ack_mono_right (m : ℕ) : Monotone (ack m) := (ack_strictMono_right m).monotone theorem ack_injective_right (m : ℕ) : Function.Injective (ack m) := (ack_strictMono_right m).injective @[simp] theorem ack_lt_iff_right {m n₁ n₂ : ℕ} : ack m n₁ < ack m n₂ ↔ n₁ < n₂ := (ack_strictMono_right m).lt_iff_lt @[simp] theorem ack_le_iff_right {m n₁ n₂ : ℕ} : ack m n₁ ≤ ack m n₂ ↔ n₁ ≤ n₂ := (ack_strictMono_right m).le_iff_le @[simp] theorem ack_inj_right {m n₁ n₂ : ℕ} : ack m n₁ = ack m n₂ ↔ n₁ = n₂ := (ack_injective_right m).eq_iff theorem max_ack_right (m n₁ n₂ : ℕ) : ack m (max n₁ n₂) = max (ack m n₁) (ack m n₂) := (ack_mono_right m).map_max theorem add_lt_ack : ∀ m n, m + n < ack m n | 0, n => by simp | m + 1, 0 => by simpa using add_lt_ack m 1 | m + 1, n + 1 => calc m + 1 + n + 1 ≤ m + (m + n + 2) := by omega _ < ack m (m + n + 2) := add_lt_ack _ _ _ ≤ ack m (ack (m + 1) n) := ack_mono_right m <| le_of_eq_of_le (by rw [succ_eq_add_one]; ring_nf) <| succ_le_of_lt <| add_lt_ack (m + 1) n _ = ack (m + 1) (n + 1) := (ack_succ_succ m n).symm theorem add_add_one_le_ack (m n : ℕ) : m + n + 1 ≤ ack m n := succ_le_of_lt (add_lt_ack m n) theorem lt_ack_left (m n : ℕ) : m < ack m n := (self_le_add_right m n).trans_lt <| add_lt_ack m n theorem lt_ack_right (m n : ℕ) : n < ack m n := (self_le_add_left n m).trans_lt <| add_lt_ack m n -- we reorder the arguments to appease the equation compiler private theorem ack_strict_mono_left' : ∀ {m₁ m₂} (n), m₁ < m₂ → ack m₁ n < ack m₂ n | m, 0, n => fun h => (not_lt_zero m h).elim | 0, m + 1, 0 => fun _h => by simpa using one_lt_ack_succ_right m 0 | 0, m + 1, n + 1 => fun h => by rw [ack_zero, ack_succ_succ] apply lt_of_le_of_lt (le_trans _ <| add_le_add_left (add_add_one_le_ack _ _) m) (add_lt_ack _ _) omega | m₁ + 1, m₂ + 1, 0 => fun h => by simpa using ack_strict_mono_left' 1 ((add_lt_add_iff_right 1).1 h) | m₁ + 1, m₂ + 1, n + 1 => fun h => by rw [ack_succ_succ, ack_succ_succ] exact (ack_strict_mono_left' _ <| (add_lt_add_iff_right 1).1 h).trans (ack_strictMono_right _ <| ack_strict_mono_left' n h) theorem ack_strictMono_left (n : ℕ) : StrictMono fun m => ack m n := fun _m₁ _m₂ => ack_strict_mono_left' n theorem ack_mono_left (n : ℕ) : Monotone fun m => ack m n := (ack_strictMono_left n).monotone theorem ack_injective_left (n : ℕ) : Function.Injective fun m => ack m n := (ack_strictMono_left n).injective @[simp] theorem ack_lt_iff_left {m₁ m₂ n : ℕ} : ack m₁ n < ack m₂ n ↔ m₁ < m₂ := (ack_strictMono_left n).lt_iff_lt @[simp] theorem ack_le_iff_left {m₁ m₂ n : ℕ} : ack m₁ n ≤ ack m₂ n ↔ m₁ ≤ m₂ := (ack_strictMono_left n).le_iff_le @[simp] theorem ack_inj_left {m₁ m₂ n : ℕ} : ack m₁ n = ack m₂ n ↔ m₁ = m₂ := (ack_injective_left n).eq_iff theorem max_ack_left (m₁ m₂ n : ℕ) : ack (max m₁ m₂) n = max (ack m₁ n) (ack m₂ n) := (ack_mono_left n).map_max theorem ack_le_ack {m₁ m₂ n₁ n₂ : ℕ} (hm : m₁ ≤ m₂) (hn : n₁ ≤ n₂) : ack m₁ n₁ ≤ ack m₂ n₂ := (ack_mono_left n₁ hm).trans <| ack_mono_right m₂ hn theorem ack_succ_right_le_ack_succ_left (m n : ℕ) : ack m (n + 1) ≤ ack (m + 1) n := by cases' n with n n · simp · rw [ack_succ_succ] apply ack_mono_right m (le_trans _ <| add_add_one_le_ack _ n) omega -- All the inequalities from this point onwards are specific to the main proof. private theorem sq_le_two_pow_add_one_minus_three (n : ℕ) : n ^ 2 ≤ 2 ^ (n + 1) - 3 := by induction' n with k hk · norm_num · cases' k with k k · norm_num · rw [add_sq, Nat.pow_succ 2, mul_comm _ 2, two_mul (2 ^ _), add_tsub_assoc_of_le, add_comm (2 ^ _), add_assoc] · apply Nat.add_le_add hk norm_num apply succ_le_of_lt rw [Nat.pow_succ, mul_comm _ 2, mul_lt_mul_left (zero_lt_two' ℕ)] apply lt_two_pow · rw [Nat.pow_succ, Nat.pow_succ] linarith [one_le_pow k 2 zero_lt_two] theorem ack_add_one_sq_lt_ack_add_three : ∀ m n, (ack m n + 1) ^ 2 ≤ ack (m + 3) n | 0, n => by simpa using sq_le_two_pow_add_one_minus_three (n + 2) | m + 1, 0 => by rw [ack_succ_zero, ack_succ_zero] apply ack_add_one_sq_lt_ack_add_three | m + 1, n + 1 => by rw [ack_succ_succ, ack_succ_succ] apply (ack_add_one_sq_lt_ack_add_three _ _).trans (ack_mono_right _ <| ack_mono_left _ _) omega theorem ack_ack_lt_ack_max_add_two (m n k : ℕ) : ack m (ack n k) < ack (max m n + 2) k := calc ack m (ack n k) ≤ ack (max m n) (ack n k) := ack_mono_left _ (le_max_left _ _) _ < ack (max m n) (ack (max m n + 1) k) := ack_strictMono_right _ <| ack_strictMono_left k <| lt_succ_of_le <| le_max_right m n _ = ack (max m n + 1) (k + 1) := (ack_succ_succ _ _).symm _ ≤ ack (max m n + 2) k := ack_succ_right_le_ack_succ_left _ _ theorem ack_add_one_sq_lt_ack_add_four (m n : ℕ) : ack m ((n + 1) ^ 2) < ack (m + 4) n := calc ack m ((n + 1) ^ 2) < ack m ((ack m n + 1) ^ 2) := ack_strictMono_right m <| Nat.pow_lt_pow_left (succ_lt_succ <| lt_ack_right m n) two_ne_zero _ ≤ ack m (ack (m + 3) n) := ack_mono_right m <| ack_add_one_sq_lt_ack_add_three m n _ ≤ ack (m + 2) (ack (m + 3) n) := ack_mono_left _ <| by omega _ = ack (m + 3) (n + 1) := (ack_succ_succ _ n).symm _ ≤ ack (m + 4) n := ack_succ_right_le_ack_succ_left _ n theorem ack_pair_lt (m n k : ℕ) : ack m (pair n k) < ack (m + 4) (max n k) := (ack_strictMono_right m <| pair_lt_max_add_one_sq n k).trans <| ack_add_one_sq_lt_ack_add_four _ _ /-- If `f` is primitive recursive, there exists `m` such that `f n < ack m n` for all `n`. -/ theorem exists_lt_ack_of_nat_primrec {f : ℕ → ℕ} (hf : Nat.Primrec f) : ∃ m, ∀ n, f n < ack m n := by induction' hf with f g hf hg IHf IHg f g hf hg IHf IHg f g hf hg IHf IHg -- Zero function: · exact ⟨0, ack_pos 0⟩ -- Successor function: · refine ⟨1, fun n => ?_⟩ rw [succ_eq_one_add] apply add_lt_ack -- Left projection: · refine ⟨0, fun n => ?_⟩ rw [ack_zero, Nat.lt_succ_iff] exact unpair_left_le n -- Right projection: · refine ⟨0, fun n => ?_⟩ rw [ack_zero, Nat.lt_succ_iff] exact unpair_right_le n all_goals cases' IHf with a ha; cases' IHg with b hb -- Pairing: · refine ⟨max a b + 3, fun n => (pair_lt_max_add_one_sq _ _).trans_le <| (Nat.pow_le_pow_left (add_le_add_right ?_ _) 2).trans <| ack_add_one_sq_lt_ack_add_three _ _⟩ rw [max_ack_left] exact max_le_max (ha n).le (hb n).le -- Composition: · exact ⟨max a b + 2, fun n => (ha _).trans <| (ack_strictMono_right a <| hb n).trans <| ack_ack_lt_ack_max_add_two a b n⟩ -- Primitive recursion operator: · -- We prove this simpler inequality first. have : ∀ {m n}, rec (f m) (fun y IH => g <| pair m <| pair y IH) n < ack (max a b + 9) (m + n) := by intro m n -- We induct on n. induction' n with n IH -- The base case is easy. · apply (ha m).trans (ack_strictMono_left m <| (le_max_left a b).trans_lt _) omega · -- We get rid of the first `pair`. simp only apply (hb _).trans ((ack_pair_lt _ _ _).trans_le _) -- If m is the maximum, we get a very weak inequality. cases' lt_or_le _ m with h₁ h₁ · rw [max_eq_left h₁.le] exact ack_le_ack (Nat.add_le_add (le_max_right a b) <| by norm_num) (self_le_add_right m _) rw [max_eq_right h₁] -- We get rid of the second `pair`. apply (ack_pair_lt _ _ _).le.trans -- If n is the maximum, we get a very weak inequality. cases' lt_or_le _ n with h₂ h₂ · rw [max_eq_left h₂.le, add_assoc] exact ack_le_ack (Nat.add_le_add (le_max_right a b) <| by norm_num) ((le_succ n).trans <| self_le_add_left _ _) rw [max_eq_right h₂] -- We now use the inductive hypothesis, and some simple algebraic manipulation. apply (ack_strictMono_right _ IH).le.trans rw [add_succ m, add_succ _ 8, succ_eq_add_one, succ_eq_add_one, ack_succ_succ (_ + 8), add_assoc] exact ack_mono_left _ (Nat.add_le_add (le_max_right a b) le_rfl) -- The proof is now simple. exact ⟨max a b + 9, fun n => this.trans_le <| ack_mono_right _ <| unpair_add_le n⟩ theorem not_nat_primrec_ack_self : ¬Nat.Primrec fun n => ack n n := fun h => by cases' exists_lt_ack_of_nat_primrec h with m hm exact (hm m).false theorem not_primrec_ack_self : ¬Primrec fun n => ack n n := by rw [Primrec.nat_iff] exact not_nat_primrec_ack_self /-- The Ackermann function is not primitive recursive. -/ theorem not_primrec₂_ack : ¬Primrec₂ ack := fun h => not_primrec_ack_self <| h.comp Primrec.id Primrec.id
Computability\ContextFreeGrammar.lean
/- Copyright (c) 2023 Martin Dvorak. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Martin Dvorak -/ import Mathlib.Computability.Language /-! # Context-Free Grammars This file contains the definition of a context-free grammar, which is a grammar that has a single nonterminal symbol on the left-hand side of each rule. ## Main definitions * `ContextFreeGrammar`: A context-free grammar. * `ContextFreeGrammar.language`: A language generated by a given context-free grammar. ## Main theorems * `Language.IsContextFree.reverse`: The class of context-free languages is closed under reversal. -/ universe uT uN in /-- Rule that rewrites a single nonterminal to any string (a list of symbols). -/ structure ContextFreeRule (T : Type uT) (N : Type uN) where /-- Input nonterminal a.k.a. left-hand side. -/ input : N /-- Output string a.k.a. right-hand side. -/ output : List (Symbol T N) /-- Context-free grammar that generates words over the alphabet `T` (a type of terminals). -/ structure ContextFreeGrammar.{uN,uT} (T : Type uT) where /-- Type of nonterminals. -/ NT : Type uN /-- Initial nonterminal. -/ initial : NT /-- Rewrite rules. -/ rules : List (ContextFreeRule T NT) universe uT uN variable {T : Type uT} namespace ContextFreeRule variable {N : Type uN} /-- Inductive definition of a single application of a given context-free rule `r` to a string `u`; `r.Rewrites u v` means that the `r` sends `u` to `v` (there may be multiple such strings `v`). -/ inductive Rewrites (r : ContextFreeRule T N) : List (Symbol T N) → List (Symbol T N) → Prop /-- The replacement is at the start of the remaining string. -/ | head (s : List (Symbol T N)) : r.Rewrites (Symbol.nonterminal r.input :: s) (r.output ++ s) /-- There is a replacement later in the string. -/ | cons (x : Symbol T N) {s₁ s₂ : List (Symbol T N)} (hrs : Rewrites r s₁ s₂) : r.Rewrites (x :: s₁) (x :: s₂) lemma Rewrites.exists_parts {r : ContextFreeRule T N} {u v : List (Symbol T N)} (hyp : r.Rewrites u v) : ∃ p q : List (Symbol T N), u = p ++ [Symbol.nonterminal r.input] ++ q ∧ v = p ++ r.output ++ q := by induction hyp with | head s => use [], s simp | cons x _ ih => rcases ih with ⟨p', q', rfl, rfl⟩ use x :: p', q' simp lemma rewrites_of_exists_parts (r : ContextFreeRule T N) (p q : List (Symbol T N)) : r.Rewrites (p ++ [Symbol.nonterminal r.input] ++ q) (p ++ r.output ++ q) := by induction p with | nil => exact Rewrites.head q | cons d l ih => exact Rewrites.cons d ih /-- Rule `r` rewrites string `u` is to string `v` iff they share both a prefix `p` and postfix `q` such that the remaining middle part of `u` is the input of `r` and the remaining middle part of `u` is the output of `r`. -/ theorem rewrites_iff {r : ContextFreeRule T N} (u v : List (Symbol T N)) : r.Rewrites u v ↔ ∃ p q : List (Symbol T N), u = p ++ [Symbol.nonterminal r.input] ++ q ∧ v = p ++ r.output ++ q := ⟨Rewrites.exists_parts, by rintro ⟨p, q, rfl, rfl⟩; apply rewrites_of_exists_parts⟩ /-- Add extra prefix to context-free rewriting. -/ lemma Rewrites.append_left {r : ContextFreeRule T N} {v w : List (Symbol T N)} (hvw : r.Rewrites v w) (p : List (Symbol T N)) : r.Rewrites (p ++ v) (p ++ w) := by rw [rewrites_iff] at * rcases hvw with ⟨x, y, hxy⟩ use p ++ x, y simp_all /-- Add extra postfix to context-free rewriting. -/ lemma Rewrites.append_right {r : ContextFreeRule T N} {v w : List (Symbol T N)} (hvw : r.Rewrites v w) (p : List (Symbol T N)) : r.Rewrites (v ++ p) (w ++ p) := by rw [rewrites_iff] at * rcases hvw with ⟨x, y, hxy⟩ use x, y ++ p simp_all end ContextFreeRule namespace ContextFreeGrammar /-- Given a context-free grammar `g` and strings `u` and `v` `g.Produces u v` means that one step of a context-free transformation by a rule from `g` sends `u` to `v`. -/ def Produces (g : ContextFreeGrammar.{uN} T) (u v : List (Symbol T g.NT)) : Prop := ∃ r ∈ g.rules, r.Rewrites u v /-- Given a context-free grammar `g` and strings `u` and `v` `g.Derives u v` means that `g` can transform `u` to `v` in some number of rewriting steps. -/ abbrev Derives (g : ContextFreeGrammar.{uN} T) : List (Symbol T g.NT) → List (Symbol T g.NT) → Prop := Relation.ReflTransGen g.Produces /-- Given a context-free grammar `g` and a string `s` `g.Generates s` means that `g` can transform its initial nonterminal to `s` in some number of rewriting steps. -/ def Generates (g : ContextFreeGrammar.{uN} T) (s : List (Symbol T g.NT)) : Prop := g.Derives [Symbol.nonterminal g.initial] s /-- The language (set of words) that can be generated by a given context-free grammar `g`. -/ def language (g : ContextFreeGrammar.{uN} T) : Language T := { w | g.Generates (List.map Symbol.terminal w) } /-- A given word `w` belongs to the language generated by a given context-free grammar `g` iff `g` can derive the word `w` (wrapped as a string) from the initial nonterminal of `g` in some number of steps. -/ @[simp] lemma mem_language_iff (g : ContextFreeGrammar.{uN} T) (w : List T) : w ∈ g.language ↔ g.Derives [Symbol.nonterminal g.initial] (List.map Symbol.terminal w) := by rfl variable {g : ContextFreeGrammar.{uN} T} @[refl] lemma Derives.refl (w : List (Symbol T g.NT)) : g.Derives w w := Relation.ReflTransGen.refl lemma Produces.single {v w : List (Symbol T g.NT)} (hvw : g.Produces v w) : g.Derives v w := Relation.ReflTransGen.single hvw @[trans] lemma Derives.trans {u v w : List (Symbol T g.NT)} (huv : g.Derives u v) (hvw : g.Derives v w) : g.Derives u w := Relation.ReflTransGen.trans huv hvw lemma Derives.trans_produces {u v w : List (Symbol T g.NT)} (huv : g.Derives u v) (hvw : g.Produces v w) : g.Derives u w := huv.trans hvw.single lemma Produces.trans_derives {u v w : List (Symbol T g.NT)} (huv : g.Produces u v) (hvw : g.Derives v w) : g.Derives u w := huv.single.trans hvw lemma Derives.eq_or_head {u w : List (Symbol T g.NT)} (huw : g.Derives u w) : u = w ∨ ∃ v : List (Symbol T g.NT), g.Produces u v ∧ g.Derives v w := Relation.ReflTransGen.cases_head huw lemma Derives.eq_or_tail {u w : List (Symbol T g.NT)} (huw : g.Derives u w) : u = w ∨ ∃ v : List (Symbol T g.NT), g.Derives u v ∧ g.Produces v w := (Relation.ReflTransGen.cases_tail huw).casesOn (Or.inl ∘ Eq.symm) Or.inr /-- Add extra prefix to context-free producing. -/ lemma Produces.append_left {v w : List (Symbol T g.NT)} (hvw : g.Produces v w) (p : List (Symbol T g.NT)) : g.Produces (p ++ v) (p ++ w) := match hvw with | ⟨r, hrmem, hrvw⟩ => ⟨r, hrmem, hrvw.append_left p⟩ /-- Add extra postfix to context-free producing. -/ lemma Produces.append_right {v w : List (Symbol T g.NT)} (hvw : g.Produces v w) (p : List (Symbol T g.NT)) : g.Produces (v ++ p) (w ++ p) := match hvw with | ⟨r, hrmem, hrvw⟩ => ⟨r, hrmem, hrvw.append_right p⟩ /-- Add extra prefix to context-free deriving. -/ lemma Derives.append_left {v w : List (Symbol T g.NT)} (hvw : g.Derives v w) (p : List (Symbol T g.NT)) : g.Derives (p ++ v) (p ++ w) := by induction hvw with | refl => rfl | tail _ last ih => exact ih.trans_produces <| last.append_left p /-- Add extra prefix to context-free deriving. -/ lemma Derives.append_right {v w : List (Symbol T g.NT)} (hvw : g.Derives v w) (p : List (Symbol T g.NT)) : g.Derives (v ++ p) (w ++ p) := by induction hvw with | refl => rfl | tail _ last ih => exact ih.trans_produces <| last.append_right p end ContextFreeGrammar /-- Context-free languages are defined by context-free grammars. -/ def Language.IsContextFree (L : Language T) : Prop := ∃ g : ContextFreeGrammar.{uT} T, g.language = L section closure_reversal /-- Rules for a grammar for a reversed language. -/ def ContextFreeRule.reverse {N : Type uN} (r : ContextFreeRule T N) : ContextFreeRule T N := ⟨r.input, r.output.reverse⟩ /-- Grammar for a reversed language. -/ def ContextFreeGrammar.reverse (g : ContextFreeGrammar T) : ContextFreeGrammar T := ⟨g.NT, g.initial, g.rules.map .reverse⟩ lemma ContextFreeRule.reverse_involutive {N : Type uN} : Function.Involutive (@ContextFreeRule.reverse T N) := by intro x simp [ContextFreeRule.reverse] lemma ContextFreeGrammar.reverse_involutive : Function.Involutive (@ContextFreeGrammar.reverse T) := by intro x simp [ContextFreeGrammar.reverse, ContextFreeRule.reverse_involutive] lemma ContextFreeGrammar.reverse_derives (g : ContextFreeGrammar T) {s : List (Symbol T g.NT)} (hgs : g.reverse.Derives [Symbol.nonterminal g.reverse.initial] s) : g.Derives [Symbol.nonterminal g.initial] s.reverse := by induction hgs with | refl => rw [List.reverse_singleton] apply ContextFreeGrammar.Derives.refl | tail _ orig ih => apply ContextFreeGrammar.Derives.trans_produces ih obtain ⟨r, rin, rewr⟩ := orig simp only [ContextFreeGrammar.reverse, List.mem_map] at rin obtain ⟨r₀, rin₀, rfl⟩ := rin refine ⟨r₀, rin₀, ?_⟩ rw [ContextFreeRule.rewrites_iff] at rewr ⊢ rcases rewr with ⟨p, q, rfl, rfl⟩ use q.reverse, p.reverse simp [ContextFreeRule.reverse] lemma ContextFreeGrammar.reverse_mem_language_of_mem_reverse_language (g : ContextFreeGrammar T) {w : List T} (hgw : w ∈ g.reverse.language) : w.reverse ∈ g.language := by convert g.reverse_derives hgw simp [List.map_reverse] lemma ContextFreeGrammar.mem_reverse_language_iff_reverse_mem_language (g : ContextFreeGrammar T) (w : List T) : w ∈ g.reverse.language ↔ w.reverse ∈ g.language := by refine ⟨reverse_mem_language_of_mem_reverse_language _, fun hw => ?_⟩ rw [← ContextFreeGrammar.reverse_involutive g] at hw rw [← List.reverse_reverse w] exact g.reverse.reverse_mem_language_of_mem_reverse_language hw /-- The class of context-free languages is closed under reversal. -/ theorem Language.IsContextFree.reverse (L : Language T) : L.IsContextFree → L.reverse.IsContextFree := fun ⟨g, hg⟩ => ⟨g.reverse, hg ▸ Set.ext g.mem_reverse_language_iff_reverse_mem_language⟩ end closure_reversal
Computability\DFA.lean
/- Copyright (c) 2020 Fox Thomson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Fox Thomson, Chris Wong -/ import Mathlib.Computability.Language import Mathlib.Data.Fintype.Card import Mathlib.Data.List.Indexes import Mathlib.Tactic.NormNum /-! # Deterministic Finite Automata This file contains the definition of a Deterministic Finite Automaton (DFA), a state machine which determines whether a string (implemented as a list over an arbitrary alphabet) is in a regular set in linear time. Note that this definition allows for Automaton with infinite states, a `Fintype` instance must be supplied for true DFA's. ## Implementation notes Currently, there are two disjoint sets of simp lemmas: one for `DFA.eval`, and another for `DFA.evalFrom`. You can switch from the former to the latter using `simp [eval]`. ## TODO - Should we unify these simp sets, such that `eval` is rewritten to `evalFrom` automatically? - Should `mem_accepts` and `mem_acceptsFrom` be marked `@[simp]`? -/ open Computability universe u v /-- A DFA is a set of states (`σ`), a transition function from state to state labelled by the alphabet (`step`), a starting state (`start`) and a set of acceptance states (`accept`). -/ structure DFA (α : Type u) (σ : Type v) where /-- A transition function from state to state labelled by the alphabet. -/ step : σ → α → σ /-- Starting state. -/ start : σ /-- Set of acceptance states. -/ accept : Set σ namespace DFA variable {α : Type u} {σ : Type v} (M : DFA α σ) instance [Inhabited σ] : Inhabited (DFA α σ) := ⟨DFA.mk (fun _ _ => default) default ∅⟩ /-- `M.evalFrom s x` evaluates `M` with input `x` starting from the state `s`. -/ def evalFrom (s : σ) : List α → σ := List.foldl M.step s @[simp] theorem evalFrom_nil (s : σ) : M.evalFrom s [] = s := rfl @[simp] theorem evalFrom_singleton (s : σ) (a : α) : M.evalFrom s [a] = M.step s a := rfl @[simp] theorem evalFrom_append_singleton (s : σ) (x : List α) (a : α) : M.evalFrom s (x ++ [a]) = M.step (M.evalFrom s x) a := by simp only [evalFrom, List.foldl_append, List.foldl_cons, List.foldl_nil] /-- `M.eval x` evaluates `M` with input `x` starting from the state `M.start`. -/ def eval : List α → σ := M.evalFrom M.start @[simp] theorem eval_nil : M.eval [] = M.start := rfl @[simp] theorem eval_singleton (a : α) : M.eval [a] = M.step M.start a := rfl @[simp] theorem eval_append_singleton (x : List α) (a : α) : M.eval (x ++ [a]) = M.step (M.eval x) a := evalFrom_append_singleton _ _ _ _ theorem evalFrom_of_append (start : σ) (x y : List α) : M.evalFrom start (x ++ y) = M.evalFrom (M.evalFrom start x) y := x.foldl_append _ _ y /-- `M.acceptsFrom s` is the language of `x` such that `M.evalFrom s x` is an accept state. -/ def acceptsFrom (s : σ) : Language α := {x | M.evalFrom s x ∈ M.accept} theorem mem_acceptsFrom {s : σ} {x : List α} : x ∈ M.acceptsFrom s ↔ M.evalFrom s x ∈ M.accept := by rfl /-- `M.accepts` is the language of `x` such that `M.eval x` is an accept state. -/ def accepts : Language α := M.acceptsFrom M.start theorem mem_accepts {x : List α} : x ∈ M.accepts ↔ M.eval x ∈ M.accept := by rfl theorem evalFrom_split [Fintype σ] {x : List α} {s t : σ} (hlen : Fintype.card σ ≤ x.length) (hx : M.evalFrom s x = t) : ∃ q a b c, x = a ++ b ++ c ∧ a.length + b.length ≤ Fintype.card σ ∧ b ≠ [] ∧ M.evalFrom s a = q ∧ M.evalFrom q b = q ∧ M.evalFrom q c = t := by obtain ⟨n, m, hneq, heq⟩ := Fintype.exists_ne_map_eq_of_card_lt (fun n : Fin (Fintype.card σ + 1) => M.evalFrom s (x.take n)) (by norm_num) wlog hle : (n : ℕ) ≤ m generalizing n m · exact this m n hneq.symm heq.symm (le_of_not_le hle) have hm : (m : ℕ) ≤ Fintype.card σ := Fin.is_le m refine ⟨M.evalFrom s ((x.take m).take n), (x.take m).take n, (x.take m).drop n, x.drop m, ?_, ?_, ?_, by rfl, ?_⟩ · rw [List.take_append_drop, List.take_append_drop] · simp only [List.length_drop, List.length_take] rw [min_eq_left (hm.trans hlen), min_eq_left hle, add_tsub_cancel_of_le hle] exact hm · intro h have hlen' := congr_arg List.length h simp only [List.length_drop, List.length, List.length_take] at hlen' rw [min_eq_left, tsub_eq_zero_iff_le] at hlen' · apply hneq apply le_antisymm assumption' exact hm.trans hlen have hq : M.evalFrom (M.evalFrom s ((x.take m).take n)) ((x.take m).drop n) = M.evalFrom s ((x.take m).take n) := by rw [List.take_take, min_eq_left hle, ← evalFrom_of_append, heq, ← min_eq_left hle, ← List.take_take, min_eq_left hle, List.take_append_drop] use hq rwa [← hq, ← evalFrom_of_append, ← evalFrom_of_append, ← List.append_assoc, List.take_append_drop, List.take_append_drop] theorem evalFrom_of_pow {x y : List α} {s : σ} (hx : M.evalFrom s x = s) (hy : y ∈ ({x} : Language α)∗) : M.evalFrom s y = s := by rw [Language.mem_kstar] at hy rcases hy with ⟨S, rfl, hS⟩ induction' S with a S ih · rfl · have ha := hS a (List.mem_cons_self _ _) rw [Set.mem_singleton_iff] at ha rw [List.join, evalFrom_of_append, ha, hx] apply ih intro z hz exact hS z (List.mem_cons_of_mem a hz) theorem pumping_lemma [Fintype σ] {x : List α} (hx : x ∈ M.accepts) (hlen : Fintype.card σ ≤ List.length x) : ∃ a b c, x = a ++ b ++ c ∧ a.length + b.length ≤ Fintype.card σ ∧ b ≠ [] ∧ {a} * {b}∗ * {c} ≤ M.accepts := by obtain ⟨_, a, b, c, hx, hlen, hnil, rfl, hb, hc⟩ := M.evalFrom_split (s := M.start) hlen rfl use a, b, c, hx, hlen, hnil intro y hy rw [Language.mem_mul] at hy rcases hy with ⟨ab, hab, c', hc', rfl⟩ rw [Language.mem_mul] at hab rcases hab with ⟨a', ha', b', hb', rfl⟩ rw [Set.mem_singleton_iff] at ha' hc' substs ha' hc' have h := M.evalFrom_of_pow hb hb' rwa [mem_accepts, eval, evalFrom_of_append, evalFrom_of_append, h, hc] section Maps variable {α' σ' : Type*} /-- `M.comap f` pulls back the alphabet of `M` along `f`. In other words, it applies `f` to the input before passing it to `M`. -/ @[simps] def comap (f : α' → α) (M : DFA α σ) : DFA α' σ where step s a := M.step s (f a) start := M.start accept := M.accept @[simp] theorem comap_id : M.comap id = M := rfl @[simp] theorem evalFrom_comap (f : α' → α) (s : σ) (x : List α') : (M.comap f).evalFrom s x = M.evalFrom s (x.map f) := by induction x using List.list_reverse_induction with | base => simp | ind x a ih => simp [ih] @[simp] theorem eval_comap (f : α' → α) (x : List α') : (M.comap f).eval x = M.eval (x.map f) := by simp [eval] @[simp] theorem accepts_comap (f : α' → α) : (M.comap f).accepts = List.map f ⁻¹' M.accepts := by ext x conv => rhs rw [Set.mem_preimage, mem_accepts] simp [mem_accepts] /-- Lifts an equivalence on states to an equivalence on DFAs. -/ @[simps apply_step apply_start apply_accept] def reindex (g : σ ≃ σ') : DFA α σ ≃ DFA α σ' where toFun M := { step := fun s a => g (M.step (g.symm s) a) start := g M.start accept := g.symm ⁻¹' M.accept } invFun M := { step := fun s a => g.symm (M.step (g s) a) start := g.symm M.start accept := g ⁻¹' M.accept } left_inv M := by simp right_inv M := by simp @[simp] theorem reindex_refl : reindex (Equiv.refl σ) M = M := rfl @[simp] theorem symm_reindex (g : σ ≃ σ') : (reindex (α := α) g).symm = reindex g.symm := rfl @[simp] theorem evalFrom_reindex (g : σ ≃ σ') (s : σ') (x : List α) : (reindex g M).evalFrom s x = g (M.evalFrom (g.symm s) x) := by induction x using List.list_reverse_induction with | base => simp | ind x a ih => simp [ih] @[simp] theorem eval_reindex (g : σ ≃ σ') (x : List α) : (reindex g M).eval x = g (M.eval x) := by simp [eval] @[simp] theorem accepts_reindex (g : σ ≃ σ') : (reindex g M).accepts = M.accepts := by ext x simp [mem_accepts] theorem comap_reindex (f : α' → α) (g : σ ≃ σ') : (reindex g M).comap f = reindex g (M.comap f) := by simp [comap, reindex] end Maps end DFA
Computability\Encoding.lean
/- Copyright (c) 2020 Pim Spelier, Daan van Gent. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Pim Spelier, Daan van Gent -/ import Mathlib.Data.Fintype.Basic import Mathlib.Data.Num.Lemmas import Mathlib.Data.Option.Basic import Mathlib.SetTheory.Cardinal.Basic /-! # Encodings This file contains the definition of a (finite) encoding, a map from a type to strings in an alphabet, used in defining computability by Turing machines. It also contains several examples: ## Examples - `finEncodingNatBool` : a binary encoding of ℕ in a simple alphabet. - `finEncodingNatΓ'` : a binary encoding of ℕ in the alphabet used for TM's. - `unaryFinEncodingNat` : a unary encoding of ℕ - `finEncodingBoolBool` : an encoding of bool. -/ universe u v open Cardinal namespace Computability /-- An encoding of a type in a certain alphabet, together with a decoding. -/ structure Encoding (α : Type u) where Γ : Type v encode : α → List Γ decode : List Γ → Option α decode_encode : ∀ x, decode (encode x) = some x theorem Encoding.encode_injective {α : Type u} (e : Encoding α) : Function.Injective e.encode := by refine fun _ _ h => Option.some_injective _ ?_ rw [← e.decode_encode, ← e.decode_encode, h] /-- An encoding plus a guarantee of finiteness of the alphabet. -/ structure FinEncoding (α : Type u) extends Encoding.{u, 0} α where ΓFin : Fintype Γ instance Γ.fintype {α : Type u} (e : FinEncoding α) : Fintype e.toEncoding.Γ := e.ΓFin /-- A standard Turing machine alphabet, consisting of blank,bit0,bit1,bra,ket,comma. -/ inductive Γ' | blank | bit (b : Bool) | bra | ket | comma deriving DecidableEq -- Porting note: A handler for `Fintype` had not been implemented yet. instance Γ'.fintype : Fintype Γ' := ⟨⟨{.blank, .bit true, .bit false, .bra, .ket, .comma}, by decide⟩, by intro; cases_type* Γ' Bool <;> decide⟩ instance inhabitedΓ' : Inhabited Γ' := ⟨Γ'.blank⟩ /-- The natural inclusion of bool in Γ'. -/ def inclusionBoolΓ' : Bool → Γ' := Γ'.bit /-- An arbitrary section of the natural inclusion of bool in Γ'. -/ def sectionΓ'Bool : Γ' → Bool | Γ'.bit b => b | _ => Inhabited.default theorem leftInverse_section_inclusion : Function.LeftInverse sectionΓ'Bool inclusionBoolΓ' := fun x => Bool.casesOn x rfl rfl theorem inclusionBoolΓ'_injective : Function.Injective inclusionBoolΓ' := Function.HasLeftInverse.injective (Exists.intro sectionΓ'Bool leftInverse_section_inclusion) /-- An encoding function of the positive binary numbers in bool. -/ def encodePosNum : PosNum → List Bool | PosNum.one => [true] | PosNum.bit0 n => false :: encodePosNum n | PosNum.bit1 n => true :: encodePosNum n /-- An encoding function of the binary numbers in bool. -/ def encodeNum : Num → List Bool | Num.zero => [] | Num.pos n => encodePosNum n /-- An encoding function of ℕ in bool. -/ def encodeNat (n : ℕ) : List Bool := encodeNum n /-- A decoding function from `List Bool` to the positive binary numbers. -/ def decodePosNum : List Bool → PosNum | false :: l => PosNum.bit0 (decodePosNum l) | true :: l => ite (l = []) PosNum.one (PosNum.bit1 (decodePosNum l)) | _ => PosNum.one /-- A decoding function from `List Bool` to the binary numbers. -/ def decodeNum : List Bool → Num := fun l => ite (l = []) Num.zero <| decodePosNum l /-- A decoding function from `List Bool` to ℕ. -/ def decodeNat : List Bool → Nat := fun l => decodeNum l theorem encodePosNum_nonempty (n : PosNum) : encodePosNum n ≠ [] := PosNum.casesOn n (List.cons_ne_nil _ _) (fun _m => List.cons_ne_nil _ _) fun _m => List.cons_ne_nil _ _ theorem decode_encodePosNum : ∀ n, decodePosNum (encodePosNum n) = n := by intro n induction' n with m hm m hm <;> unfold encodePosNum decodePosNum · rfl · rw [hm] exact if_neg (encodePosNum_nonempty m) · exact congr_arg PosNum.bit0 hm theorem decode_encodeNum : ∀ n, decodeNum (encodeNum n) = n := by intro n cases' n with n <;> unfold encodeNum decodeNum · rfl rw [decode_encodePosNum n] rw [PosNum.cast_to_num] exact if_neg (encodePosNum_nonempty n) theorem decode_encodeNat : ∀ n, decodeNat (encodeNat n) = n := by intro n conv_rhs => rw [← Num.to_of_nat n] exact congr_arg ((↑) : Num → ℕ) (decode_encodeNum n) /-- A binary encoding of ℕ in bool. -/ def encodingNatBool : Encoding ℕ where Γ := Bool encode := encodeNat decode n := some (decodeNat n) decode_encode n := congr_arg _ (decode_encodeNat n) /-- A binary fin_encoding of ℕ in bool. -/ def finEncodingNatBool : FinEncoding ℕ := ⟨encodingNatBool, Bool.fintype⟩ /-- A binary encoding of ℕ in Γ'. -/ def encodingNatΓ' : Encoding ℕ where Γ := Γ' encode x := List.map inclusionBoolΓ' (encodeNat x) decode x := some (decodeNat (List.map sectionΓ'Bool x)) decode_encode x := congr_arg _ <| by -- Porting note: `rw` can't unify `g ∘ f` with `fun x => g (f x)`, used `LeftInverse.id` -- instead. rw [List.map_map, leftInverse_section_inclusion.id, List.map_id, decode_encodeNat] /-- A binary fin_encoding of ℕ in Γ'. -/ def finEncodingNatΓ' : FinEncoding ℕ := ⟨encodingNatΓ', Γ'.fintype⟩ /-- A unary encoding function of ℕ in bool. -/ def unaryEncodeNat : Nat → List Bool | 0 => [] | n + 1 => true :: unaryEncodeNat n /-- A unary decoding function from `List Bool` to ℕ. -/ def unaryDecodeNat : List Bool → Nat := List.length theorem unary_decode_encode_nat : ∀ n, unaryDecodeNat (unaryEncodeNat n) = n := fun n => Nat.rec rfl (fun (_m : ℕ) hm => (congr_arg Nat.succ hm.symm).symm) n /-- A unary fin_encoding of ℕ. -/ def unaryFinEncodingNat : FinEncoding ℕ where Γ := Bool encode := unaryEncodeNat decode n := some (unaryDecodeNat n) decode_encode n := congr_arg _ (unary_decode_encode_nat n) ΓFin := Bool.fintype /-- An encoding function of bool in bool. -/ def encodeBool : Bool → List Bool := pure /-- A decoding function from `List Bool` to bool. -/ def decodeBool : List Bool → Bool | b :: _ => b | _ => Inhabited.default theorem decode_encodeBool (b : Bool) : decodeBool (encodeBool b) = b := rfl /-- A fin_encoding of bool in bool. -/ def finEncodingBoolBool : FinEncoding Bool where Γ := Bool encode := encodeBool decode x := some (decodeBool x) decode_encode x := congr_arg _ (decode_encodeBool x) ΓFin := Bool.fintype instance inhabitedFinEncoding : Inhabited (FinEncoding Bool) := ⟨finEncodingBoolBool⟩ instance inhabitedEncoding : Inhabited (Encoding Bool) := ⟨finEncodingBoolBool.toEncoding⟩ theorem Encoding.card_le_card_list {α : Type u} (e : Encoding.{u, v} α) : Cardinal.lift.{v} #α ≤ Cardinal.lift.{u} #(List e.Γ) := Cardinal.lift_mk_le'.2 ⟨⟨e.encode, e.encode_injective⟩⟩ theorem Encoding.card_le_aleph0 {α : Type u} (e : Encoding.{u, v} α) [Countable e.Γ] : #α ≤ ℵ₀ := haveI : Countable α := e.encode_injective.countable Cardinal.mk_le_aleph0 theorem FinEncoding.card_le_aleph0 {α : Type u} (e : FinEncoding α) : #α ≤ ℵ₀ := e.toEncoding.card_le_aleph0 end Computability
Computability\EpsilonNFA.lean
/- Copyright (c) 2021 Fox Thomson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Fox Thomson, Yaël Dillies -/ import Mathlib.Computability.NFA /-! # Epsilon Nondeterministic Finite Automata This file contains the definition of an epsilon Nondeterministic Finite Automaton (`εNFA`), a state machine which determines whether a string (implemented as a list over an arbitrary alphabet) is in a regular set by evaluating the string over every possible path, also having access to ε-transitions, which can be followed without reading a character. Since this definition allows for automata with infinite states, a `Fintype` instance must be supplied for true `εNFA`'s. -/ open Set open Computability -- "ε_NFA" universe u v /-- An `εNFA` is a set of states (`σ`), a transition function from state to state labelled by the alphabet (`step`), a starting state (`start`) and a set of acceptance states (`accept`). Note the transition function sends a state to a `Set` of states and can make ε-transitions by inputing `none`. Since this definition allows for Automata with infinite states, a `Fintype` instance must be supplied for true `εNFA`'s. -/ structure εNFA (α : Type u) (σ : Type v) where /-- Transition function. The automaton is rendered non-deterministic by this transition function returning `Set σ` (rather than `σ`), and ε-transitions are made possible by taking `Option α` (rather than `α`). -/ step : σ → Option α → Set σ /-- Starting states. -/ start : Set σ /-- Set of acceptance states. -/ accept : Set σ variable {α : Type u} {σ σ' : Type v} (M : εNFA α σ) {S : Set σ} {x : List α} {s : σ} {a : α} namespace εNFA /-- The `εClosure` of a set is the set of states which can be reached by taking a finite string of ε-transitions from an element of the set. -/ inductive εClosure (S : Set σ) : Set σ | base : ∀ s ∈ S, εClosure S s | step : ∀ (s), ∀ t ∈ M.step s none, εClosure S s → εClosure S t @[simp] theorem subset_εClosure (S : Set σ) : S ⊆ M.εClosure S := εClosure.base @[simp] theorem εClosure_empty : M.εClosure ∅ = ∅ := eq_empty_of_forall_not_mem fun s hs ↦ by induction hs <;> assumption @[simp] theorem εClosure_univ : M.εClosure univ = univ := eq_univ_of_univ_subset <| subset_εClosure _ _ /-- `M.stepSet S a` is the union of the ε-closure of `M.step s a` for all `s ∈ S`. -/ def stepSet (S : Set σ) (a : α) : Set σ := ⋃ s ∈ S, M.εClosure (M.step s a) variable {M} @[simp] theorem mem_stepSet_iff : s ∈ M.stepSet S a ↔ ∃ t ∈ S, s ∈ M.εClosure (M.step t a) := by simp_rw [stepSet, mem_iUnion₂, exists_prop] @[simp] theorem stepSet_empty (a : α) : M.stepSet ∅ a = ∅ := by simp_rw [stepSet, mem_empty_iff_false, iUnion_false, iUnion_empty] variable (M) /-- `M.evalFrom S x` computes all possible paths through `M` with input `x` starting at an element of `S`. -/ def evalFrom (start : Set σ) : List α → Set σ := List.foldl M.stepSet (M.εClosure start) @[simp] theorem evalFrom_nil (S : Set σ) : M.evalFrom S [] = M.εClosure S := rfl @[simp] theorem evalFrom_singleton (S : Set σ) (a : α) : M.evalFrom S [a] = M.stepSet (M.εClosure S) a := rfl @[simp] theorem evalFrom_append_singleton (S : Set σ) (x : List α) (a : α) : M.evalFrom S (x ++ [a]) = M.stepSet (M.evalFrom S x) a := by rw [evalFrom, List.foldl_append, List.foldl_cons, List.foldl_nil] @[simp] theorem evalFrom_empty (x : List α) : M.evalFrom ∅ x = ∅ := by induction' x using List.reverseRecOn with x a ih · rw [evalFrom_nil, εClosure_empty] · rw [evalFrom_append_singleton, ih, stepSet_empty] /-- `M.eval x` computes all possible paths through `M` with input `x` starting at an element of `M.start`. -/ def eval := M.evalFrom M.start @[simp] theorem eval_nil : M.eval [] = M.εClosure M.start := rfl @[simp] theorem eval_singleton (a : α) : M.eval [a] = M.stepSet (M.εClosure M.start) a := rfl @[simp] theorem eval_append_singleton (x : List α) (a : α) : M.eval (x ++ [a]) = M.stepSet (M.eval x) a := evalFrom_append_singleton _ _ _ _ /-- `M.accepts` is the language of `x` such that there is an accept state in `M.eval x`. -/ def accepts : Language α := { x | ∃ S ∈ M.accept, S ∈ M.eval x } /-! ### Conversions between `εNFA` and `NFA` -/ /-- `M.toNFA` is an `NFA` constructed from an `εNFA` `M`. -/ def toNFA : NFA α σ where step S a := M.εClosure (M.step S a) start := M.εClosure M.start accept := M.accept @[simp] theorem toNFA_evalFrom_match (start : Set σ) : M.toNFA.evalFrom (M.εClosure start) = M.evalFrom start := rfl @[simp] theorem toNFA_correct : M.toNFA.accepts = M.accepts := rfl theorem pumping_lemma [Fintype σ] {x : List α} (hx : x ∈ M.accepts) (hlen : Fintype.card (Set σ) ≤ List.length x) : ∃ a b c, x = a ++ b ++ c ∧ a.length + b.length ≤ Fintype.card (Set σ) ∧ b ≠ [] ∧ {a} * {b}∗ * {c} ≤ M.accepts := M.toNFA.pumping_lemma hx hlen end εNFA namespace NFA /-- `M.toεNFA` is an `εNFA` constructed from an `NFA` `M` by using the same start and accept states and transition functions. -/ def toεNFA (M : NFA α σ) : εNFA α σ where step s a := a.casesOn' ∅ fun a ↦ M.step s a start := M.start accept := M.accept @[simp] theorem toεNFA_εClosure (M : NFA α σ) (S : Set σ) : M.toεNFA.εClosure S = S := by ext a refine ⟨?_, εNFA.εClosure.base _⟩ rintro (⟨_, h⟩ | ⟨_, _, h, _⟩) · exact h · cases h @[simp] theorem toεNFA_evalFrom_match (M : NFA α σ) (start : Set σ) : M.toεNFA.evalFrom start = M.evalFrom start := by rw [evalFrom, εNFA.evalFrom, toεNFA_εClosure] suffices εNFA.stepSet (toεNFA M) = stepSet M by rw [this] ext S s simp only [stepSet, εNFA.stepSet, exists_prop, Set.mem_iUnion] apply exists_congr simp only [and_congr_right_iff] intro _ _ rw [M.toεNFA_εClosure] rfl @[simp] theorem toεNFA_correct (M : NFA α σ) : M.toεNFA.accepts = M.accepts := by rw [εNFA.accepts, εNFA.eval, toεNFA_evalFrom_match] rfl end NFA /-! ### Regex-like operations -/ namespace εNFA instance : Zero (εNFA α σ) := ⟨⟨fun _ _ ↦ ∅, ∅, ∅⟩⟩ instance : One (εNFA α σ) := ⟨⟨fun _ _ ↦ ∅, univ, univ⟩⟩ instance : Inhabited (εNFA α σ) := ⟨0⟩ variable (P : εNFA α σ) (Q : εNFA α σ') @[simp] theorem step_zero (s a) : (0 : εNFA α σ).step s a = ∅ := rfl @[simp] theorem step_one (s a) : (1 : εNFA α σ).step s a = ∅ := rfl @[simp] theorem start_zero : (0 : εNFA α σ).start = ∅ := rfl @[simp] theorem start_one : (1 : εNFA α σ).start = univ := rfl @[simp] theorem accept_zero : (0 : εNFA α σ).accept = ∅ := rfl @[simp] theorem accept_one : (1 : εNFA α σ).accept = univ := rfl end εNFA
Computability\Halting.lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Computability.PartrecCode import Mathlib.Data.Set.Subsingleton /-! # Computability theory and the halting problem A universal partial recursive function, Rice's theorem, and the halting problem. ## References * [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019] -/ open Mathlib (Vector) open Encodable Denumerable namespace Nat.Partrec open Computable Part theorem merge' {f g} (hf : Nat.Partrec f) (hg : Nat.Partrec g) : ∃ h, Nat.Partrec h ∧ ∀ a, (∀ x ∈ h a, x ∈ f a ∨ x ∈ g a) ∧ ((h a).Dom ↔ (f a).Dom ∨ (g a).Dom) := by obtain ⟨cf, rfl⟩ := Code.exists_code.1 hf obtain ⟨cg, rfl⟩ := Code.exists_code.1 hg have : Nat.Partrec fun n => Nat.rfindOpt fun k => cf.evaln k n <|> cg.evaln k n := Partrec.nat_iff.1 (Partrec.rfindOpt <| Primrec.option_orElse.to_comp.comp (Code.evaln_prim.to_comp.comp <| (snd.pair (const cf)).pair fst) (Code.evaln_prim.to_comp.comp <| (snd.pair (const cg)).pair fst)) refine ⟨_, this, fun n => ?_⟩ have : ∀ x ∈ rfindOpt fun k ↦ HOrElse.hOrElse (Code.evaln k cf n) fun _x ↦ Code.evaln k cg n, x ∈ Code.eval cf n ∨ x ∈ Code.eval cg n := by intro x h obtain ⟨k, e⟩ := Nat.rfindOpt_spec h revert e simp only [Option.mem_def] cases' e' : cf.evaln k n with y <;> simp <;> intro e · exact Or.inr (Code.evaln_sound e) · subst y exact Or.inl (Code.evaln_sound e') refine ⟨this, ⟨fun h => (this _ ⟨h, rfl⟩).imp Exists.fst Exists.fst, ?_⟩⟩ intro h rw [Nat.rfindOpt_dom] simp only [dom_iff_mem, Code.evaln_complete, Option.mem_def] at h obtain ⟨x, k, e⟩ | ⟨x, k, e⟩ := h · refine ⟨k, x, ?_⟩ simp only [e, Option.some_orElse, Option.mem_def] · refine ⟨k, ?_⟩ cases' cf.evaln k n with y · exact ⟨x, by simp only [e, Option.mem_def, Option.none_orElse]⟩ · exact ⟨y, by simp only [Option.some_orElse, Option.mem_def]⟩ end Nat.Partrec namespace Partrec variable {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variable [Primcodable α] [Primcodable β] [Primcodable γ] [Primcodable σ] open Computable Part open Nat.Partrec (Code) open Nat.Partrec.Code theorem merge' {f g : α →. σ} (hf : Partrec f) (hg : Partrec g) : ∃ k : α →. σ, Partrec k ∧ ∀ a, (∀ x ∈ k a, x ∈ f a ∨ x ∈ g a) ∧ ((k a).Dom ↔ (f a).Dom ∨ (g a).Dom) := by let ⟨k, hk, H⟩ := Nat.Partrec.merge' (bind_decode₂_iff.1 hf) (bind_decode₂_iff.1 hg) let k' (a : α) := (k (encode a)).bind fun n => (decode (α := σ) n : Part σ) refine ⟨k', ((nat_iff.2 hk).comp Computable.encode).bind (Computable.decode.ofOption.comp snd).to₂, fun a => ?_⟩ have : ∀ x ∈ k' a, x ∈ f a ∨ x ∈ g a := by intro x h' simp only [k', exists_prop, mem_coe, mem_bind_iff, Option.mem_def] at h' obtain ⟨n, hn, hx⟩ := h' have := (H _).1 _ hn simp only [decode₂_encode, coe_some, bind_some, mem_map_iff] at this obtain ⟨a', ha, rfl⟩ | ⟨a', ha, rfl⟩ := this <;> simp only [encodek, Option.some_inj] at hx <;> rw [hx] at ha · exact Or.inl ha · exact Or.inr ha refine ⟨this, ⟨fun h => (this _ ⟨h, rfl⟩).imp Exists.fst Exists.fst, ?_⟩⟩ intro h rw [bind_dom] have hk : (k (encode a)).Dom := (H _).2.2 (by simpa only [encodek₂, bind_some, coe_some] using h) exists hk simp only [exists_prop, mem_map_iff, mem_coe, mem_bind_iff, Option.mem_def] at H obtain ⟨a', _, y, _, e⟩ | ⟨a', _, y, _, e⟩ := (H _).1 _ ⟨hk, rfl⟩ <;> simp only [e.symm, encodek, coe_some, some_dom] theorem merge {f g : α →. σ} (hf : Partrec f) (hg : Partrec g) (H : ∀ (a), ∀ x ∈ f a, ∀ y ∈ g a, x = y) : ∃ k : α →. σ, Partrec k ∧ ∀ a x, x ∈ k a ↔ x ∈ f a ∨ x ∈ g a := let ⟨k, hk, K⟩ := merge' hf hg ⟨k, hk, fun a x => ⟨(K _).1 _, fun h => by have : (k a).Dom := (K _).2.2 (h.imp Exists.fst Exists.fst) refine ⟨this, ?_⟩ cases' h with h h <;> cases' (K _).1 _ ⟨this, rfl⟩ with h' h' · exact mem_unique h' h · exact (H _ _ h _ h').symm · exact H _ _ h' _ h · exact mem_unique h' h⟩⟩ theorem cond {c : α → Bool} {f : α →. σ} {g : α →. σ} (hc : Computable c) (hf : Partrec f) (hg : Partrec g) : Partrec fun a => cond (c a) (f a) (g a) := let ⟨cf, ef⟩ := exists_code.1 hf let ⟨cg, eg⟩ := exists_code.1 hg ((eval_part.comp (Computable.cond hc (const cf) (const cg)) Computable.encode).bind ((@Computable.decode σ _).comp snd).ofOption.to₂).of_eq fun a => by cases c a <;> simp [ef, eg, encodek] nonrec theorem sum_casesOn {f : α → β ⊕ γ} {g : α → β →. σ} {h : α → γ →. σ} (hf : Computable f) (hg : Partrec₂ g) (hh : Partrec₂ h) : @Partrec _ σ _ _ fun a => Sum.casesOn (f a) (g a) (h a) := option_some_iff.1 <| (cond (sum_casesOn hf (const true).to₂ (const false).to₂) (sum_casesOn_left hf (option_some_iff.2 hg).to₂ (const Option.none).to₂) (sum_casesOn_right hf (const Option.none).to₂ (option_some_iff.2 hh).to₂)).of_eq fun a => by cases f a <;> simp only [Bool.cond_true, Bool.cond_false] end Partrec /-- A computable predicate is one whose indicator function is computable. -/ def ComputablePred {α} [Primcodable α] (p : α → Prop) := ∃ _ : DecidablePred p, Computable fun a => decide (p a) /-- A recursively enumerable predicate is one which is the domain of a computable partial function. -/ def RePred {α} [Primcodable α] (p : α → Prop) := Partrec fun a => Part.assert (p a) fun _ => Part.some () theorem RePred.of_eq {α} [Primcodable α] {p q : α → Prop} (hp : RePred p) (H : ∀ a, p a ↔ q a) : RePred q := (funext fun a => propext (H a) : p = q) ▸ hp theorem Partrec.dom_re {α β} [Primcodable α] [Primcodable β] {f : α →. β} (h : Partrec f) : RePred fun a => (f a).Dom := (h.map (Computable.const ()).to₂).of_eq fun n => Part.ext fun _ => by simp [Part.dom_iff_mem] theorem ComputablePred.of_eq {α} [Primcodable α] {p q : α → Prop} (hp : ComputablePred p) (H : ∀ a, p a ↔ q a) : ComputablePred q := (funext fun a => propext (H a) : p = q) ▸ hp namespace ComputablePred variable {α : Type*} {σ : Type*} variable [Primcodable α] [Primcodable σ] open Nat.Partrec (Code) open Nat.Partrec.Code Computable theorem computable_iff {p : α → Prop} : ComputablePred p ↔ ∃ f : α → Bool, Computable f ∧ p = fun a => (f a : Prop) := ⟨fun ⟨D, h⟩ => ⟨_, h, funext fun a => propext (Bool.decide_iff _).symm⟩, by rintro ⟨f, h, rfl⟩; exact ⟨by infer_instance, by simpa using h⟩⟩ protected theorem not {p : α → Prop} (hp : ComputablePred p) : ComputablePred fun a => ¬p a := by obtain ⟨f, hf, rfl⟩ := computable_iff.1 hp exact ⟨by infer_instance, (cond hf (const false) (const true)).of_eq fun n => by simp only [Bool.not_eq_true] cases f n <;> rfl⟩ theorem to_re {p : α → Prop} (hp : ComputablePred p) : RePred p := by obtain ⟨f, hf, rfl⟩ := computable_iff.1 hp unfold RePred dsimp only [] refine (Partrec.cond hf (Decidable.Partrec.const' (Part.some ())) Partrec.none).of_eq fun n => Part.ext fun a => ?_ cases a; cases f n <;> simp /-- **Rice's Theorem** -/ theorem rice (C : Set (ℕ →. ℕ)) (h : ComputablePred fun c => eval c ∈ C) {f g} (hf : Nat.Partrec f) (hg : Nat.Partrec g) (fC : f ∈ C) : g ∈ C := by cases' h with _ h obtain ⟨c, e⟩ := fixed_point₂ (Partrec.cond (h.comp fst) ((Partrec.nat_iff.2 hg).comp snd).to₂ ((Partrec.nat_iff.2 hf).comp snd).to₂).to₂ simp only [Bool.cond_decide] at e by_cases H : eval c ∈ C · simp only [H, if_true] at e change (fun b => g b) ∈ C rwa [← e] · simp only [H, if_false] at e rw [e] at H contradiction theorem rice₂ (C : Set Code) (H : ∀ cf cg, eval cf = eval cg → (cf ∈ C ↔ cg ∈ C)) : (ComputablePred fun c => c ∈ C) ↔ C = ∅ ∨ C = Set.univ := by classical exact have hC : ∀ f, f ∈ C ↔ eval f ∈ eval '' C := fun f => ⟨Set.mem_image_of_mem _, fun ⟨g, hg, e⟩ => (H _ _ e).1 hg⟩ ⟨fun h => or_iff_not_imp_left.2 fun C0 => Set.eq_univ_of_forall fun cg => let ⟨cf, fC⟩ := Set.nonempty_iff_ne_empty.2 C0 (hC _).2 <| rice (eval '' C) (h.of_eq hC) (Partrec.nat_iff.1 <| eval_part.comp (const cf) Computable.id) (Partrec.nat_iff.1 <| eval_part.comp (const cg) Computable.id) ((hC _).1 fC), fun h => by { obtain rfl | rfl := h <;> simpa [ComputablePred, Set.mem_empty_iff_false] using ⟨by infer_instance, Computable.const _⟩ }⟩ /-- The Halting problem is recursively enumerable -/ theorem halting_problem_re (n) : RePred fun c => (eval c n).Dom := (eval_part.comp Computable.id (Computable.const _)).dom_re /-- The **Halting problem** is not computable -/ theorem halting_problem (n) : ¬ComputablePred fun c => (eval c n).Dom | h => rice { f | (f n).Dom } h Nat.Partrec.zero Nat.Partrec.none trivial -- Post's theorem on the equivalence of r.e., co-r.e. sets and -- computable sets. The assumption that p is decidable is required -- unless we assume Markov's principle or LEM. -- @[nolint decidable_classical] theorem computable_iff_re_compl_re {p : α → Prop} [DecidablePred p] : ComputablePred p ↔ RePred p ∧ RePred fun a => ¬p a := ⟨fun h => ⟨h.to_re, h.not.to_re⟩, fun ⟨h₁, h₂⟩ => ⟨‹_›, by obtain ⟨k, pk, hk⟩ := Partrec.merge (h₁.map (Computable.const true).to₂) (h₂.map (Computable.const false).to₂) (by intro a x hx y hy simp only [Part.mem_map_iff, Part.mem_assert_iff, Part.mem_some_iff, exists_prop, and_true, exists_const] at hx hy cases hy.1 hx.1) refine Partrec.of_eq pk fun n => Part.eq_some_iff.2 ?_ rw [hk] simp only [Part.mem_map_iff, Part.mem_assert_iff, Part.mem_some_iff, exists_prop, and_true, true_eq_decide_iff, and_self, exists_const, false_eq_decide_iff] apply Decidable.em⟩⟩ theorem computable_iff_re_compl_re' {p : α → Prop} : ComputablePred p ↔ RePred p ∧ RePred fun a => ¬p a := by classical exact computable_iff_re_compl_re theorem halting_problem_not_re (n) : ¬RePred fun c => ¬(eval c n).Dom | h => halting_problem _ <| computable_iff_re_compl_re'.2 ⟨halting_problem_re _, h⟩ end ComputablePred namespace Nat open Vector Part /-- A simplified basis for `Partrec`. -/ inductive Partrec' : ∀ {n}, (Vector ℕ n →. ℕ) → Prop | prim {n f} : @Primrec' n f → @Partrec' n f | comp {m n f} (g : Fin n → Vector ℕ m →. ℕ) : Partrec' f → (∀ i, Partrec' (g i)) → Partrec' fun v => (Vector.mOfFn fun i => g i v) >>= f | rfind {n} {f : Vector ℕ (n + 1) → ℕ} : @Partrec' (n + 1) f → Partrec' fun v => rfind fun n => some (f (n ::ᵥ v) = 0) end Nat namespace Nat.Partrec' open Mathlib.Vector Partrec Computable open Nat (Partrec') open Nat.Partrec' theorem to_part {n f} (pf : @Partrec' n f) : _root_.Partrec f := by induction pf with | prim hf => exact hf.to_prim.to_comp | comp _ _ _ hf hg => exact (Partrec.vector_mOfFn hg).bind (hf.comp snd) | rfind _ hf => have := hf.comp (vector_cons.comp snd fst) have := ((Primrec.eq.comp _root_.Primrec.id (_root_.Primrec.const 0)).to_comp.comp this).to₂.partrec₂ exact _root_.Partrec.rfind this theorem of_eq {n} {f g : Vector ℕ n →. ℕ} (hf : Partrec' f) (H : ∀ i, f i = g i) : Partrec' g := (funext H : f = g) ▸ hf theorem of_prim {n} {f : Vector ℕ n → ℕ} (hf : Primrec f) : @Partrec' n f := prim (Nat.Primrec'.of_prim hf) theorem head {n : ℕ} : @Partrec' n.succ (@head ℕ n) := prim Nat.Primrec'.head theorem tail {n f} (hf : @Partrec' n f) : @Partrec' n.succ fun v => f v.tail := (hf.comp _ fun i => @prim _ _ <| Nat.Primrec'.get i.succ).of_eq fun v => by simp; rw [← ofFn_get v.tail]; congr; funext i; simp protected theorem bind {n f g} (hf : @Partrec' n f) (hg : @Partrec' (n + 1) g) : @Partrec' n fun v => (f v).bind fun a => g (a ::ᵥ v) := (@comp n (n + 1) g (fun i => Fin.cases f (fun i v => some (v.get i)) i) hg fun i => by refine Fin.cases ?_ (fun i => ?_) i <;> simp [*] exact prim (Nat.Primrec'.get _)).of_eq fun v => by simp [mOfFn, Part.bind_assoc, pure] protected theorem map {n f} {g : Vector ℕ (n + 1) → ℕ} (hf : @Partrec' n f) (hg : @Partrec' (n + 1) g) : @Partrec' n fun v => (f v).map fun a => g (a ::ᵥ v) := by simpa [(Part.bind_some_eq_map _ _).symm] using hf.bind hg /-- Analogous to `Nat.Partrec'` for `ℕ`-valued functions, a predicate for partial recursive vector-valued functions. -/ def Vec {n m} (f : Vector ℕ n → Vector ℕ m) := ∀ i, Partrec' fun v => (f v).get i nonrec theorem Vec.prim {n m f} (hf : @Nat.Primrec'.Vec n m f) : Vec f := fun i => prim <| hf i protected theorem nil {n} : @Vec n 0 fun _ => nil := fun i => i.elim0 protected theorem cons {n m} {f : Vector ℕ n → ℕ} {g} (hf : @Partrec' n f) (hg : @Vec n m g) : Vec fun v => f v ::ᵥ g v := fun i => Fin.cases (by simpa using hf) (fun i => by simp only [hg i, get_cons_succ]) i theorem idv {n} : @Vec n n id := Vec.prim Nat.Primrec'.idv theorem comp' {n m f g} (hf : @Partrec' m f) (hg : @Vec n m g) : Partrec' fun v => f (g v) := (hf.comp _ hg).of_eq fun v => by simp theorem comp₁ {n} (f : ℕ →. ℕ) {g : Vector ℕ n → ℕ} (hf : @Partrec' 1 fun v => f v.head) (hg : @Partrec' n g) : @Partrec' n fun v => f (g v) := by simpa using hf.comp' (Partrec'.cons hg Partrec'.nil) theorem rfindOpt {n} {f : Vector ℕ (n + 1) → ℕ} (hf : @Partrec' (n + 1) f) : @Partrec' n fun v => Nat.rfindOpt fun a => ofNat (Option ℕ) (f (a ::ᵥ v)) := ((rfind <| (of_prim (Primrec.nat_sub.comp (_root_.Primrec.const 1) Primrec.vector_head)).comp₁ (fun n => Part.some (1 - n)) hf).bind ((prim Nat.Primrec'.pred).comp₁ Nat.pred hf)).of_eq fun v => Part.ext fun b => by simp only [Nat.rfindOpt, exists_prop, tsub_eq_zero_iff_le, PFun.coe_val, Part.mem_bind_iff, Part.mem_some_iff, Option.mem_def, Part.mem_coe] refine exists_congr fun a => (and_congr (iff_of_eq ?_) Iff.rfl).trans (and_congr_right fun h => ?_) · congr funext n cases f (n ::ᵥ v) <;> simp [Nat.succ_le_succ] <;> rfl · have := Nat.rfind_spec h simp only [Part.coe_some, Part.mem_some_iff] at this revert this; cases' f (a ::ᵥ v) with c <;> intro this · cases this rw [← Option.some_inj, eq_comm] rfl open Nat.Partrec.Code theorem of_part : ∀ {n f}, _root_.Partrec f → @Partrec' n f := @(suffices ∀ f, Nat.Partrec f → @Partrec' 1 fun v => f v.head from fun {n f} hf => by let g := fun n₁ => (Part.ofOption (decode (α := Vector ℕ n) n₁)).bind (fun a => Part.map encode (f a)) exact (comp₁ g (this g hf) (prim Nat.Primrec'.encode)).of_eq fun i => by dsimp only [g]; simp [encodek, Part.map_id'] fun f hf => by obtain ⟨c, rfl⟩ := exists_code.1 hf simpa [eval_eq_rfindOpt] using rfindOpt <| of_prim <| Primrec.encode_iff.2 <| evaln_prim.comp <| (Primrec.vector_head.pair (_root_.Primrec.const c)).pair <| Primrec.vector_head.comp Primrec.vector_tail) theorem part_iff {n f} : @Partrec' n f ↔ _root_.Partrec f := ⟨to_part, of_part⟩ theorem part_iff₁ {f : ℕ →. ℕ} : (@Partrec' 1 fun v => f v.head) ↔ _root_.Partrec f := part_iff.trans ⟨fun h => (h.comp <| (Primrec.vector_ofFn fun _ => _root_.Primrec.id).to_comp).of_eq fun v => by simp only [id, head_ofFn], fun h => h.comp vector_head⟩ theorem part_iff₂ {f : ℕ → ℕ →. ℕ} : (@Partrec' 2 fun v => f v.head v.tail.head) ↔ Partrec₂ f := part_iff.trans ⟨fun h => (h.comp <| vector_cons.comp fst <| vector_cons.comp snd (const nil)).of_eq fun v => by simp only [head_cons, tail_cons], fun h => h.comp vector_head (vector_head.comp vector_tail)⟩ theorem vec_iff {m n f} : @Vec m n f ↔ Computable f := ⟨fun h => by simpa only [ofFn_get] using vector_ofFn fun i => to_part (h i), fun h i => of_part <| vector_get.comp h (const i)⟩ end Nat.Partrec'
Computability\Language.lean
/- Copyright (c) 2020 Fox Thomson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Fox Thomson, Martin Dvorak -/ import Mathlib.Algebra.Order.Kleene import Mathlib.Algebra.Ring.Hom.Defs import Mathlib.Data.List.Join import Mathlib.Data.Set.Lattice import Mathlib.Tactic.DeriveFintype /-! # Languages This file contains the definition and operations on formal languages over an alphabet. Note that "strings" are implemented as lists over the alphabet. Union and concatenation define a [Kleene algebra](https://en.wikipedia.org/wiki/Kleene_algebra) over the languages. In addition to that, we define a reversal of a language and prove that it behaves well with respect to other language operations. -/ open List Set Computability universe v variable {α β γ : Type*} /-- A language is a set of strings over an alphabet. -/ def Language (α) := Set (List α) instance : Membership (List α) (Language α) := ⟨Set.Mem⟩ instance : Singleton (List α) (Language α) := ⟨Set.singleton⟩ instance : Insert (List α) (Language α) := ⟨Set.insert⟩ instance : CompleteAtomicBooleanAlgebra (Language α) := Set.completeAtomicBooleanAlgebra namespace Language variable {l m : Language α} {a b x : List α} -- Porting note: `reducible` attribute cannot be local. -- attribute [local reducible] Language /-- Zero language has no elements. -/ instance : Zero (Language α) := ⟨(∅ : Set _)⟩ /-- `1 : Language α` contains only one element `[]`. -/ instance : One (Language α) := ⟨{[]}⟩ instance : Inhabited (Language α) := ⟨(∅ : Set _)⟩ /-- The sum of two languages is their union. -/ instance : Add (Language α) := ⟨((· ∪ ·) : Set (List α) → Set (List α) → Set (List α))⟩ /-- The product of two languages `l` and `m` is the language made of the strings `x ++ y` where `x ∈ l` and `y ∈ m`. -/ instance : Mul (Language α) := ⟨image2 (· ++ ·)⟩ theorem zero_def : (0 : Language α) = (∅ : Set _) := rfl theorem one_def : (1 : Language α) = ({[]} : Set (List α)) := rfl theorem add_def (l m : Language α) : l + m = (l ∪ m : Set (List α)) := rfl theorem mul_def (l m : Language α) : l * m = image2 (· ++ ·) l m := rfl /-- The Kleene star of a language `L` is the set of all strings which can be written by concatenating strings from `L`. -/ instance : KStar (Language α) := ⟨fun l ↦ {x | ∃ L : List (List α), x = L.join ∧ ∀ y ∈ L, y ∈ l}⟩ lemma kstar_def (l : Language α) : l∗ = {x | ∃ L : List (List α), x = L.join ∧ ∀ y ∈ L, y ∈ l} := rfl -- Porting note: `reducible` attribute cannot be local, -- so this new theorem is required in place of `Set.ext`. @[ext] theorem ext {l m : Language α} (h : ∀ (x : List α), x ∈ l ↔ x ∈ m) : l = m := Set.ext h @[simp] theorem not_mem_zero (x : List α) : x ∉ (0 : Language α) := id @[simp] theorem mem_one (x : List α) : x ∈ (1 : Language α) ↔ x = [] := by rfl theorem nil_mem_one : [] ∈ (1 : Language α) := Set.mem_singleton _ theorem mem_add (l m : Language α) (x : List α) : x ∈ l + m ↔ x ∈ l ∨ x ∈ m := Iff.rfl theorem mem_mul : x ∈ l * m ↔ ∃ a ∈ l, ∃ b ∈ m, a ++ b = x := mem_image2 theorem append_mem_mul : a ∈ l → b ∈ m → a ++ b ∈ l * m := mem_image2_of_mem theorem mem_kstar : x ∈ l∗ ↔ ∃ L : List (List α), x = L.join ∧ ∀ y ∈ L, y ∈ l := Iff.rfl theorem join_mem_kstar {L : List (List α)} (h : ∀ y ∈ L, y ∈ l) : L.join ∈ l∗ := ⟨L, rfl, h⟩ theorem nil_mem_kstar (l : Language α) : [] ∈ l∗ := ⟨[], rfl, fun _ h ↦ by contradiction⟩ instance instSemiring : Semiring (Language α) where add := (· + ·) add_assoc := union_assoc zero := 0 zero_add := empty_union add_zero := union_empty add_comm := union_comm mul := (· * ·) mul_assoc _ _ _ := image2_assoc append_assoc zero_mul _ := image2_empty_left mul_zero _ := image2_empty_right one := 1 one_mul l := by simp [mul_def, one_def] mul_one l := by simp [mul_def, one_def] natCast n := if n = 0 then 0 else 1 natCast_zero := rfl natCast_succ n := by cases n <;> simp [Nat.cast, add_def, zero_def] left_distrib _ _ _ := image2_union_right right_distrib _ _ _ := image2_union_left nsmul := nsmulRec @[simp] theorem add_self (l : Language α) : l + l = l := sup_idem _ /-- Maps the alphabet of a language. -/ def map (f : α → β) : Language α →+* Language β where toFun := image (List.map f) map_zero' := image_empty _ map_one' := image_singleton map_add' := image_union _ map_mul' _ _ := image_image2_distrib <| map_append _ @[simp] theorem map_id (l : Language α) : map id l = l := by simp [map] @[simp] theorem map_map (g : β → γ) (f : α → β) (l : Language α) : map g (map f l) = map (g ∘ f) l := by simp [map, image_image] lemma mem_kstar_iff_exists_nonempty {x : List α} : x ∈ l∗ ↔ ∃ S : List (List α), x = S.join ∧ ∀ y ∈ S, y ∈ l ∧ y ≠ [] := by constructor · rintro ⟨S, rfl, h⟩ refine ⟨S.filter fun l ↦ !List.isEmpty l, by simp, fun y hy ↦ ?_⟩ -- Porting note: The previous code was: -- rw [mem_filter, empty_iff_eq_nil] at hy rw [mem_filter, Bool.not_eq_true', ← Bool.bool_iff_false, isEmpty_iff_eq_nil] at hy exact ⟨h y hy.1, hy.2⟩ · rintro ⟨S, hx, h⟩ exact ⟨S, hx, fun y hy ↦ (h y hy).1⟩ theorem kstar_def_nonempty (l : Language α) : l∗ = { x | ∃ S : List (List α), x = S.join ∧ ∀ y ∈ S, y ∈ l ∧ y ≠ [] } := by ext x; apply mem_kstar_iff_exists_nonempty theorem le_iff (l m : Language α) : l ≤ m ↔ l + m = m := sup_eq_right.symm theorem le_mul_congr {l₁ l₂ m₁ m₂ : Language α} : l₁ ≤ m₁ → l₂ ≤ m₂ → l₁ * l₂ ≤ m₁ * m₂ := by intro h₁ h₂ x hx simp only [mul_def, exists_and_left, mem_image2, image_prod] at hx ⊢ tauto theorem le_add_congr {l₁ l₂ m₁ m₂ : Language α} : l₁ ≤ m₁ → l₂ ≤ m₂ → l₁ + l₂ ≤ m₁ + m₂ := sup_le_sup theorem mem_iSup {ι : Sort v} {l : ι → Language α} {x : List α} : (x ∈ ⨆ i, l i) ↔ ∃ i, x ∈ l i := mem_iUnion theorem iSup_mul {ι : Sort v} (l : ι → Language α) (m : Language α) : (⨆ i, l i) * m = ⨆ i, l i * m := image2_iUnion_left _ _ _ theorem mul_iSup {ι : Sort v} (l : ι → Language α) (m : Language α) : (m * ⨆ i, l i) = ⨆ i, m * l i := image2_iUnion_right _ _ _ theorem iSup_add {ι : Sort v} [Nonempty ι] (l : ι → Language α) (m : Language α) : (⨆ i, l i) + m = ⨆ i, l i + m := iSup_sup theorem add_iSup {ι : Sort v} [Nonempty ι] (l : ι → Language α) (m : Language α) : (m + ⨆ i, l i) = ⨆ i, m + l i := sup_iSup theorem mem_pow {l : Language α} {x : List α} {n : ℕ} : x ∈ l ^ n ↔ ∃ S : List (List α), x = S.join ∧ S.length = n ∧ ∀ y ∈ S, y ∈ l := by induction' n with n ihn generalizing x · simp only [mem_one, pow_zero, length_eq_zero] constructor · rintro rfl exact ⟨[], rfl, rfl, fun _ h ↦ by contradiction⟩ · rintro ⟨_, rfl, rfl, _⟩ rfl · simp only [pow_succ', mem_mul, ihn] constructor · rintro ⟨a, ha, b, ⟨S, rfl, rfl, hS⟩, rfl⟩ exact ⟨a :: S, rfl, rfl, forall_mem_cons.2 ⟨ha, hS⟩⟩ · rintro ⟨_ | ⟨a, S⟩, rfl, hn, hS⟩ <;> cases hn rw [forall_mem_cons] at hS exact ⟨a, hS.1, _, ⟨S, rfl, rfl, hS.2⟩, rfl⟩ theorem kstar_eq_iSup_pow (l : Language α) : l∗ = ⨆ i : ℕ, l ^ i := by ext x simp only [mem_kstar, mem_iSup, mem_pow] constructor · rintro ⟨S, rfl, hS⟩ exact ⟨_, S, rfl, rfl, hS⟩ · rintro ⟨_, S, rfl, rfl, hS⟩ exact ⟨S, rfl, hS⟩ @[simp] theorem map_kstar (f : α → β) (l : Language α) : map f l∗ = (map f l)∗ := by rw [kstar_eq_iSup_pow, kstar_eq_iSup_pow] simp_rw [← map_pow] exact image_iUnion theorem mul_self_kstar_comm (l : Language α) : l∗ * l = l * l∗ := by simp only [kstar_eq_iSup_pow, mul_iSup, iSup_mul, ← pow_succ, ← pow_succ'] @[simp] theorem one_add_self_mul_kstar_eq_kstar (l : Language α) : 1 + l * l∗ = l∗ := by simp only [kstar_eq_iSup_pow, mul_iSup, ← pow_succ', ← pow_zero l] exact sup_iSup_nat_succ _ @[simp] theorem one_add_kstar_mul_self_eq_kstar (l : Language α) : 1 + l∗ * l = l∗ := by rw [mul_self_kstar_comm, one_add_self_mul_kstar_eq_kstar] instance : KleeneAlgebra (Language α) := { Language.instSemiring, Set.completeAtomicBooleanAlgebra with kstar := fun L ↦ L∗, one_le_kstar := fun a l hl ↦ ⟨[], hl, by simp⟩, mul_kstar_le_kstar := fun a ↦ (one_add_self_mul_kstar_eq_kstar a).le.trans' le_sup_right, kstar_mul_le_kstar := fun a ↦ (one_add_kstar_mul_self_eq_kstar a).le.trans' le_sup_right, kstar_mul_le_self := fun l m h ↦ by rw [kstar_eq_iSup_pow, iSup_mul] refine iSup_le (fun n ↦ ?_) induction' n with n ih · simp rw [pow_succ, mul_assoc (l^n) l m] exact le_trans (le_mul_congr le_rfl h) ih, mul_kstar_le_self := fun l m h ↦ by rw [kstar_eq_iSup_pow, mul_iSup] refine iSup_le (fun n ↦ ?_) induction' n with n ih · simp rw [pow_succ, ← mul_assoc m (l^n) l] exact le_trans (le_mul_congr ih le_rfl) h } /-- Language `l.reverse` is defined as the set of words from `l` backwards. -/ def reverse (l : Language α) : Language α := { w : List α | w.reverse ∈ l } @[simp] lemma mem_reverse : a ∈ l.reverse ↔ a.reverse ∈ l := Iff.rfl lemma reverse_mem_reverse : a.reverse ∈ l.reverse ↔ a ∈ l := by rw [mem_reverse, List.reverse_reverse] lemma reverse_eq_image (l : Language α) : l.reverse = List.reverse '' l := ((List.reverse_involutive.toPerm _).image_eq_preimage _).symm @[simp] lemma reverse_zero : (0 : Language α).reverse = 0 := rfl @[simp] lemma reverse_one : (1 : Language α).reverse = 1 := by simp [reverse, ← one_def] lemma reverse_involutive : Function.Involutive (reverse : Language α → _) := List.reverse_involutive.preimage lemma reverse_bijective : Function.Bijective (reverse : Language α → _) := reverse_involutive.bijective lemma reverse_injective : Function.Injective (reverse : Language α → _) := reverse_involutive.injective lemma reverse_surjective : Function.Surjective (reverse : Language α → _) := reverse_involutive.surjective @[simp] lemma reverse_reverse (l : Language α) : l.reverse.reverse = l := reverse_involutive l @[simp] lemma reverse_add (l m : Language α) : (l + m).reverse = l.reverse + m.reverse := rfl @[simp] lemma reverse_mul (l m : Language α) : (l * m).reverse = m.reverse * l.reverse := by simp only [mul_def, reverse_eq_image, image2_image_left, image2_image_right, image_image2, List.reverse_append] apply image2_swap @[simp] lemma reverse_iSup {ι : Sort*} (l : ι → Language α) : (⨆ i, l i).reverse = ⨆ i, (l i).reverse := preimage_iUnion @[simp] lemma reverse_iInf {ι : Sort*} (l : ι → Language α) : (⨅ i, l i).reverse = ⨅ i, (l i).reverse := preimage_iInter variable (α) in /-- `Language.reverse` as a ring isomorphism to the opposite ring. -/ @[simps] def reverseIso : Language α ≃+* (Language α)ᵐᵒᵖ where toFun l := .op l.reverse invFun l' := l'.unop.reverse left_inv := reverse_reverse right_inv l' := MulOpposite.unop_injective <| reverse_reverse l'.unop map_mul' l₁ l₂ := MulOpposite.unop_injective <| reverse_mul l₁ l₂ map_add' l₁ l₂ := MulOpposite.unop_injective <| reverse_add l₁ l₂ @[simp] lemma reverse_pow (l : Language α) (n : ℕ) : (l ^ n).reverse = l.reverse ^ n := MulOpposite.op_injective (map_pow (reverseIso α) l n) @[simp] lemma reverse_kstar (l : Language α) : l∗.reverse = l.reverse∗ := by simp only [kstar_eq_iSup_pow, reverse_iSup, reverse_pow] end Language /-- Symbols for use by all kinds of grammars. -/ inductive Symbol (T N : Type*) /-- Terminal symbols (of the same type as the language) -/ | terminal (t : T) : Symbol T N /-- Nonterminal symbols (must not be present at the end of word being generated) -/ | nonterminal (n : N) : Symbol T N deriving DecidableEq, Repr, Fintype attribute [nolint docBlame] Symbol.proxyType Symbol.proxyTypeEquiv
Computability\NFA.lean
/- Copyright (c) 2020 Fox Thomson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Fox Thomson -/ import Mathlib.Computability.DFA import Mathlib.Data.Fintype.Powerset /-! # Nondeterministic Finite Automata This file contains the definition of a Nondeterministic Finite Automaton (NFA), a state machine which determines whether a string (implemented as a list over an arbitrary alphabet) is in a regular set by evaluating the string over every possible path. We show that DFA's are equivalent to NFA's however the construction from NFA to DFA uses an exponential number of states. Note that this definition allows for Automaton with infinite states; a `Fintype` instance must be supplied for true NFA's. -/ open Set open Computability universe u v /-- An NFA is a set of states (`σ`), a transition function from state to state labelled by the alphabet (`step`), a set of starting states (`start`) and a set of acceptance states (`accept`). Note the transition function sends a state to a `Set` of states. These are the states that it may be sent to. -/ structure NFA (α : Type u) (σ : Type v) where step : σ → α → Set σ start : Set σ accept : Set σ variable {α : Type u} {σ σ' : Type v} (M : NFA α σ) namespace NFA instance : Inhabited (NFA α σ) := ⟨NFA.mk (fun _ _ => ∅) ∅ ∅⟩ /-- `M.stepSet S a` is the union of `M.step s a` for all `s ∈ S`. -/ def stepSet (S : Set σ) (a : α) : Set σ := ⋃ s ∈ S, M.step s a theorem mem_stepSet (s : σ) (S : Set σ) (a : α) : s ∈ M.stepSet S a ↔ ∃ t ∈ S, s ∈ M.step t a := by simp [stepSet] @[simp] theorem stepSet_empty (a : α) : M.stepSet ∅ a = ∅ := by simp [stepSet] /-- `M.evalFrom S x` computes all possible paths though `M` with input `x` starting at an element of `S`. -/ def evalFrom (start : Set σ) : List α → Set σ := List.foldl M.stepSet start @[simp] theorem evalFrom_nil (S : Set σ) : M.evalFrom S [] = S := rfl @[simp] theorem evalFrom_singleton (S : Set σ) (a : α) : M.evalFrom S [a] = M.stepSet S a := rfl @[simp] theorem evalFrom_append_singleton (S : Set σ) (x : List α) (a : α) : M.evalFrom S (x ++ [a]) = M.stepSet (M.evalFrom S x) a := by simp only [evalFrom, List.foldl_append, List.foldl_cons, List.foldl_nil] /-- `M.eval x` computes all possible paths though `M` with input `x` starting at an element of `M.start`. -/ def eval : List α → Set σ := M.evalFrom M.start @[simp] theorem eval_nil : M.eval [] = M.start := rfl @[simp] theorem eval_singleton (a : α) : M.eval [a] = M.stepSet M.start a := rfl @[simp] theorem eval_append_singleton (x : List α) (a : α) : M.eval (x ++ [a]) = M.stepSet (M.eval x) a := evalFrom_append_singleton _ _ _ _ /-- `M.accepts` is the language of `x` such that there is an accept state in `M.eval x`. -/ def accepts : Language α := {x | ∃ S ∈ M.accept, S ∈ M.eval x} theorem mem_accepts {x : List α} : x ∈ M.accepts ↔ ∃ S ∈ M.accept, S ∈ M.evalFrom M.start x := by rfl /-- `M.toDFA` is a `DFA` constructed from an `NFA` `M` using the subset construction. The states is the type of `Set`s of `M.state` and the step function is `M.stepSet`. -/ def toDFA : DFA α (Set σ) where step := M.stepSet start := M.start accept := { S | ∃ s ∈ S, s ∈ M.accept } @[simp] theorem toDFA_correct : M.toDFA.accepts = M.accepts := by ext x rw [mem_accepts, DFA.mem_accepts] constructor <;> · exact fun ⟨w, h2, h3⟩ => ⟨w, h3, h2⟩ theorem pumping_lemma [Fintype σ] {x : List α} (hx : x ∈ M.accepts) (hlen : Fintype.card (Set σ) ≤ List.length x) : ∃ a b c, x = a ++ b ++ c ∧ a.length + b.length ≤ Fintype.card (Set σ) ∧ b ≠ [] ∧ {a} * {b}∗ * {c} ≤ M.accepts := by rw [← toDFA_correct] at hx ⊢ exact M.toDFA.pumping_lemma hx hlen end NFA namespace DFA /-- `M.toNFA` is an `NFA` constructed from a `DFA` `M` by using the same start and accept states and a transition function which sends `s` with input `a` to the singleton `M.step s a`. -/ @[simps] def toNFA (M : DFA α σ') : NFA α σ' where step s a := {M.step s a} start := {M.start} accept := M.accept @[simp] theorem toNFA_evalFrom_match (M : DFA α σ) (start : σ) (s : List α) : M.toNFA.evalFrom {start} s = {M.evalFrom start s} := by change List.foldl M.toNFA.stepSet {start} s = {List.foldl M.step start s} induction' s with a s ih generalizing start · tauto · rw [List.foldl, List.foldl, show M.toNFA.stepSet {start} a = {M.step start a} by simp [NFA.stepSet] ] tauto @[simp] theorem toNFA_correct (M : DFA α σ) : M.toNFA.accepts = M.accepts := by ext x rw [NFA.mem_accepts, toNFA_start, toNFA_evalFrom_match] constructor · rintro ⟨S, hS₁, hS₂⟩ rwa [Set.mem_singleton_iff.mp hS₂] at hS₁ · exact fun h => ⟨M.eval x, h, rfl⟩ end DFA
Computability\Partrec.lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Computability.Primrec import Mathlib.Data.Nat.PSub import Mathlib.Data.PFun /-! # The partial recursive functions The partial recursive functions are defined similarly to the primitive recursive functions, but now all functions are partial, implemented using the `Part` monad, and there is an additional operation, called μ-recursion, which performs unbounded minimization. ## References * [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019] -/ open Mathlib (Vector) open Encodable Denumerable Part attribute [-simp] not_forall namespace Nat section Rfind variable (p : ℕ →. Bool) private def lbp (m n : ℕ) : Prop := m = n + 1 ∧ ∀ k ≤ n, false ∈ p k private def wf_lbp (H : ∃ n, true ∈ p n ∧ ∀ k < n, (p k).Dom) : WellFounded (lbp p) := ⟨by let ⟨n, pn⟩ := H suffices ∀ m k, n ≤ k + m → Acc (lbp p) k by exact fun a => this _ _ (Nat.le_add_left _ _) intro m k kn induction' m with m IH generalizing k <;> refine ⟨_, fun y r => ?_⟩ <;> rcases r with ⟨rfl, a⟩ · injection mem_unique pn.1 (a _ kn) · exact IH _ (by rw [Nat.add_right_comm]; exact kn)⟩ variable (H : ∃ n, true ∈ p n ∧ ∀ k < n, (p k).Dom) def rfindX : { n // true ∈ p n ∧ ∀ m < n, false ∈ p m } := suffices ∀ k, (∀ n < k, false ∈ p n) → { n // true ∈ p n ∧ ∀ m < n, false ∈ p m } from this 0 fun n => (Nat.not_lt_zero _).elim @WellFounded.fix _ _ (lbp p) (wf_lbp p H) (by intro m IH al have pm : (p m).Dom := by rcases H with ⟨n, h₁, h₂⟩ rcases lt_trichotomy m n with (h₃ | h₃ | h₃) · exact h₂ _ h₃ · rw [h₃] exact h₁.fst · injection mem_unique h₁ (al _ h₃) cases e : (p m).get pm · suffices ∀ᵉ k ≤ m, false ∈ p k from IH _ ⟨rfl, this⟩ fun n h => this _ (le_of_lt_succ h) intro n h cases' h.lt_or_eq_dec with h h · exact al _ h · rw [h] exact ⟨_, e⟩ · exact ⟨m, ⟨_, e⟩, al⟩) end Rfind def rfind (p : ℕ →. Bool) : Part ℕ := ⟨_, fun h => (rfindX p h).1⟩ theorem rfind_spec {p : ℕ →. Bool} {n : ℕ} (h : n ∈ rfind p) : true ∈ p n := h.snd ▸ (rfindX p h.fst).2.1 theorem rfind_min {p : ℕ →. Bool} {n : ℕ} (h : n ∈ rfind p) : ∀ {m : ℕ}, m < n → false ∈ p m := @(h.snd ▸ @((rfindX p h.fst).2.2)) @[simp] theorem rfind_dom {p : ℕ →. Bool} : (rfind p).Dom ↔ ∃ n, true ∈ p n ∧ ∀ {m : ℕ}, m < n → (p m).Dom := Iff.rfl theorem rfind_dom' {p : ℕ →. Bool} : (rfind p).Dom ↔ ∃ n, true ∈ p n ∧ ∀ {m : ℕ}, m ≤ n → (p m).Dom := exists_congr fun _ => and_congr_right fun pn => ⟨fun H _ h => (Decidable.eq_or_lt_of_le h).elim (fun e => e.symm ▸ pn.fst) (H _), fun H _ h => H (le_of_lt h)⟩ @[simp] theorem mem_rfind {p : ℕ →. Bool} {n : ℕ} : n ∈ rfind p ↔ true ∈ p n ∧ ∀ {m : ℕ}, m < n → false ∈ p m := ⟨fun h => ⟨rfind_spec h, @rfind_min _ _ h⟩, fun ⟨h₁, h₂⟩ => by let ⟨m, hm⟩ := dom_iff_mem.1 <| (@rfind_dom p).2 ⟨_, h₁, fun {m} mn => (h₂ mn).fst⟩ rcases lt_trichotomy m n with (h | h | h) · injection mem_unique (h₂ h) (rfind_spec hm) · rwa [← h] · injection mem_unique h₁ (rfind_min hm h)⟩ theorem rfind_min' {p : ℕ → Bool} {m : ℕ} (pm : p m) : ∃ n ∈ rfind p, n ≤ m := have : true ∈ (p : ℕ →. Bool) m := ⟨trivial, pm⟩ let ⟨n, hn⟩ := dom_iff_mem.1 <| (@rfind_dom p).2 ⟨m, this, fun {k} _ => ⟨⟩⟩ ⟨n, hn, not_lt.1 fun h => by injection mem_unique this (rfind_min hn h)⟩ theorem rfind_zero_none (p : ℕ →. Bool) (p0 : p 0 = Part.none) : rfind p = Part.none := eq_none_iff.2 fun _ h => let ⟨_, _, h₂⟩ := rfind_dom'.1 h.fst (p0 ▸ h₂ (zero_le _) : (@Part.none Bool).Dom) def rfindOpt {α} (f : ℕ → Option α) : Part α := (rfind fun n => (f n).isSome).bind fun n => f n theorem rfindOpt_spec {α} {f : ℕ → Option α} {a} (h : a ∈ rfindOpt f) : ∃ n, a ∈ f n := let ⟨n, _, h₂⟩ := mem_bind_iff.1 h ⟨n, mem_coe.1 h₂⟩ theorem rfindOpt_dom {α} {f : ℕ → Option α} : (rfindOpt f).Dom ↔ ∃ n a, a ∈ f n := ⟨fun h => (rfindOpt_spec ⟨h, rfl⟩).imp fun n h => ⟨_, h⟩, fun h => by have h' : ∃ n, (f n).isSome := h.imp fun n => Option.isSome_iff_exists.2 have s := Nat.find_spec h' have fd : (rfind fun n => (f n).isSome).Dom := ⟨Nat.find h', by simpa using s.symm, fun _ _ => trivial⟩ refine ⟨fd, ?_⟩ have := rfind_spec (get_mem fd) simpa using this⟩ theorem rfindOpt_mono {α} {f : ℕ → Option α} (H : ∀ {a m n}, m ≤ n → a ∈ f m → a ∈ f n) {a} : a ∈ rfindOpt f ↔ ∃ n, a ∈ f n := ⟨rfindOpt_spec, fun ⟨n, h⟩ => by have h' := rfindOpt_dom.2 ⟨_, _, h⟩ cases' rfindOpt_spec ⟨h', rfl⟩ with k hk have := (H (le_max_left _ _) h).symm.trans (H (le_max_right _ _) hk) simp at this; simp [this, get_mem]⟩ /-- `PartRec f` means that the partial function `f : ℕ → ℕ` is partially recursive. -/ inductive Partrec : (ℕ →. ℕ) → Prop | zero : Partrec (pure 0) | succ : Partrec succ | left : Partrec ↑fun n : ℕ => n.unpair.1 | right : Partrec ↑fun n : ℕ => n.unpair.2 | pair {f g} : Partrec f → Partrec g → Partrec fun n => pair <$> f n <*> g n | comp {f g} : Partrec f → Partrec g → Partrec fun n => g n >>= f | prec {f g} : Partrec f → Partrec g → Partrec (unpaired fun a n => n.rec (f a) fun y IH => do let i ← IH; g (pair a (pair y i))) | rfind {f} : Partrec f → Partrec fun a => rfind fun n => (fun m => m = 0) <$> f (pair a n) namespace Partrec theorem of_eq {f g : ℕ →. ℕ} (hf : Partrec f) (H : ∀ n, f n = g n) : Partrec g := (funext H : f = g) ▸ hf theorem of_eq_tot {f : ℕ →. ℕ} {g : ℕ → ℕ} (hf : Partrec f) (H : ∀ n, g n ∈ f n) : Partrec g := hf.of_eq fun n => eq_some_iff.2 (H n) theorem of_primrec {f : ℕ → ℕ} (hf : Nat.Primrec f) : Partrec f := by induction hf with | zero => exact zero | succ => exact succ | left => exact left | right => exact right | pair _ _ pf pg => refine (pf.pair pg).of_eq_tot fun n => ?_ simp [Seq.seq] | comp _ _ pf pg => refine (pf.comp pg).of_eq_tot fun n => (by simp) | prec _ _ pf pg => refine (pf.prec pg).of_eq_tot fun n => ?_ simp only [unpaired, PFun.coe_val, bind_eq_bind] induction n.unpair.2 with | zero => simp | succ m IH => simp only [mem_bind_iff, mem_some_iff] exact ⟨_, IH, rfl⟩ protected theorem some : Partrec some := of_primrec Primrec.id theorem none : Partrec fun _ => none := (of_primrec (Nat.Primrec.const 1)).rfind.of_eq fun n => eq_none_iff.2 fun a ⟨h, _⟩ => by simp at h theorem prec' {f g h} (hf : Partrec f) (hg : Partrec g) (hh : Partrec h) : Partrec fun a => (f a).bind fun n => n.rec (g a) fun y IH => do {let i ← IH; h (Nat.pair a (Nat.pair y i))} := ((prec hg hh).comp (pair Partrec.some hf)).of_eq fun a => ext fun s => by simp [Seq.seq] theorem ppred : Partrec fun n => ppred n := have : Primrec₂ fun n m => if n = Nat.succ m then 0 else 1 := (Primrec.ite (@PrimrecRel.comp _ _ _ _ _ _ _ _ _ _ Primrec.eq Primrec.fst (_root_.Primrec.succ.comp Primrec.snd)) (_root_.Primrec.const 0) (_root_.Primrec.const 1)).to₂ (of_primrec (Primrec₂.unpaired'.2 this)).rfind.of_eq fun n => by cases n <;> simp · exact eq_none_iff.2 fun a ⟨⟨m, h, _⟩, _⟩ => by simp [show 0 ≠ m.succ by intro h; injection h] at h · refine eq_some_iff.2 ?_ simp only [mem_rfind, not_true, IsEmpty.forall_iff, decide_True, mem_some_iff, false_eq_decide_iff, true_and] intro m h simp [ne_of_gt h] end Partrec end Nat /-- Partially recursive partial functions `α → σ` between `Primcodable` types -/ def Partrec {α σ} [Primcodable α] [Primcodable σ] (f : α →. σ) := Nat.Partrec fun n => Part.bind (decode (α := α) n) fun a => (f a).map encode /-- Partially recursive partial functions `α → β → σ` between `Primcodable` types -/ def Partrec₂ {α β σ} [Primcodable α] [Primcodable β] [Primcodable σ] (f : α → β →. σ) := Partrec fun p : α × β => f p.1 p.2 /-- Computable functions `α → σ` between `Primcodable` types: a function is computable if and only if it is partially recursive (as a partial function) -/ def Computable {α σ} [Primcodable α] [Primcodable σ] (f : α → σ) := Partrec (f : α →. σ) /-- Computable functions `α → β → σ` between `Primcodable` types -/ def Computable₂ {α β σ} [Primcodable α] [Primcodable β] [Primcodable σ] (f : α → β → σ) := Computable fun p : α × β => f p.1 p.2 theorem Primrec.to_comp {α σ} [Primcodable α] [Primcodable σ] {f : α → σ} (hf : Primrec f) : Computable f := (Nat.Partrec.ppred.comp (Nat.Partrec.of_primrec hf)).of_eq fun n => by simp; cases decode (α := α) n <;> simp nonrec theorem Primrec₂.to_comp {α β σ} [Primcodable α] [Primcodable β] [Primcodable σ] {f : α → β → σ} (hf : Primrec₂ f) : Computable₂ f := hf.to_comp protected theorem Computable.partrec {α σ} [Primcodable α] [Primcodable σ] {f : α → σ} (hf : Computable f) : Partrec (f : α →. σ) := hf protected theorem Computable₂.partrec₂ {α β σ} [Primcodable α] [Primcodable β] [Primcodable σ] {f : α → β → σ} (hf : Computable₂ f) : Partrec₂ fun a => (f a : β →. σ) := hf namespace Computable variable {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variable [Primcodable α] [Primcodable β] [Primcodable γ] [Primcodable σ] theorem of_eq {f g : α → σ} (hf : Computable f) (H : ∀ n, f n = g n) : Computable g := (funext H : f = g) ▸ hf theorem const (s : σ) : Computable fun _ : α => s := (Primrec.const _).to_comp theorem ofOption {f : α → Option β} (hf : Computable f) : Partrec fun a => (f a : Part β) := (Nat.Partrec.ppred.comp hf).of_eq fun n => by cases' decode (α := α) n with a <;> simp cases' f a with b <;> simp theorem to₂ {f : α × β → σ} (hf : Computable f) : Computable₂ fun a b => f (a, b) := hf.of_eq fun ⟨_, _⟩ => rfl protected theorem id : Computable (@id α) := Primrec.id.to_comp theorem fst : Computable (@Prod.fst α β) := Primrec.fst.to_comp theorem snd : Computable (@Prod.snd α β) := Primrec.snd.to_comp nonrec theorem pair {f : α → β} {g : α → γ} (hf : Computable f) (hg : Computable g) : Computable fun a => (f a, g a) := (hf.pair hg).of_eq fun n => by cases decode (α := α) n <;> simp [Seq.seq] theorem unpair : Computable Nat.unpair := Primrec.unpair.to_comp theorem succ : Computable Nat.succ := Primrec.succ.to_comp theorem pred : Computable Nat.pred := Primrec.pred.to_comp theorem nat_bodd : Computable Nat.bodd := Primrec.nat_bodd.to_comp theorem nat_div2 : Computable Nat.div2 := Primrec.nat_div2.to_comp theorem sum_inl : Computable (@Sum.inl α β) := Primrec.sum_inl.to_comp theorem sum_inr : Computable (@Sum.inr α β) := Primrec.sum_inr.to_comp theorem list_cons : Computable₂ (@List.cons α) := Primrec.list_cons.to_comp theorem list_reverse : Computable (@List.reverse α) := Primrec.list_reverse.to_comp theorem list_get? : Computable₂ (@List.get? α) := Primrec.list_get?.to_comp theorem list_append : Computable₂ ((· ++ ·) : List α → List α → List α) := Primrec.list_append.to_comp theorem list_concat : Computable₂ fun l (a : α) => l ++ [a] := Primrec.list_concat.to_comp theorem list_length : Computable (@List.length α) := Primrec.list_length.to_comp theorem vector_cons {n} : Computable₂ (@Vector.cons α n) := Primrec.vector_cons.to_comp theorem vector_toList {n} : Computable (@Vector.toList α n) := Primrec.vector_toList.to_comp theorem vector_length {n} : Computable (@Vector.length α n) := Primrec.vector_length.to_comp theorem vector_head {n} : Computable (@Vector.head α n) := Primrec.vector_head.to_comp theorem vector_tail {n} : Computable (@Vector.tail α n) := Primrec.vector_tail.to_comp theorem vector_get {n} : Computable₂ (@Vector.get α n) := Primrec.vector_get.to_comp theorem vector_ofFn' {n} : Computable (@Vector.ofFn α n) := Primrec.vector_ofFn'.to_comp theorem fin_app {n} : Computable₂ (@id (Fin n → σ)) := Primrec.fin_app.to_comp protected theorem encode : Computable (@encode α _) := Primrec.encode.to_comp protected theorem decode : Computable (decode (α := α)) := Primrec.decode.to_comp protected theorem ofNat (α) [Denumerable α] : Computable (ofNat α) := (Primrec.ofNat _).to_comp theorem encode_iff {f : α → σ} : (Computable fun a => encode (f a)) ↔ Computable f := Iff.rfl theorem option_some : Computable (@Option.some α) := Primrec.option_some.to_comp end Computable namespace Partrec variable {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variable [Primcodable α] [Primcodable β] [Primcodable γ] [Primcodable σ] open Computable theorem of_eq {f g : α →. σ} (hf : Partrec f) (H : ∀ n, f n = g n) : Partrec g := (funext H : f = g) ▸ hf theorem of_eq_tot {f : α →. σ} {g : α → σ} (hf : Partrec f) (H : ∀ n, g n ∈ f n) : Computable g := hf.of_eq fun a => eq_some_iff.2 (H a) theorem none : Partrec fun _ : α => @Part.none σ := Nat.Partrec.none.of_eq fun n => by cases decode (α := α) n <;> simp protected theorem some : Partrec (@Part.some α) := Computable.id theorem _root_.Decidable.Partrec.const' (s : Part σ) [Decidable s.Dom] : Partrec fun _ : α => s := (Computable.ofOption (const (toOption s))).of_eq fun _ => of_toOption s theorem const' (s : Part σ) : Partrec fun _ : α => s := haveI := Classical.dec s.Dom Decidable.Partrec.const' s protected theorem bind {f : α →. β} {g : α → β →. σ} (hf : Partrec f) (hg : Partrec₂ g) : Partrec fun a => (f a).bind (g a) := (hg.comp (Nat.Partrec.some.pair hf)).of_eq fun n => by simp [Seq.seq]; cases' e : decode (α := α) n with a <;> simp [e, encodek] theorem map {f : α →. β} {g : α → β → σ} (hf : Partrec f) (hg : Computable₂ g) : Partrec fun a => (f a).map (g a) := by simpa [bind_some_eq_map] using @Partrec.bind _ _ _ _ _ _ _ (fun a => Part.some ∘ (g a)) hf hg theorem to₂ {f : α × β →. σ} (hf : Partrec f) : Partrec₂ fun a b => f (a, b) := hf.of_eq fun ⟨_, _⟩ => rfl theorem nat_rec {f : α → ℕ} {g : α →. σ} {h : α → ℕ × σ →. σ} (hf : Computable f) (hg : Partrec g) (hh : Partrec₂ h) : Partrec fun a => (f a).rec (g a) fun y IH => IH.bind fun i => h a (y, i) := (Nat.Partrec.prec' hf hg hh).of_eq fun n => by cases' e : decode (α := α) n with a <;> simp [e] induction' f a with m IH <;> simp rw [IH, Part.bind_map] congr; funext s simp [encodek] nonrec theorem comp {f : β →. σ} {g : α → β} (hf : Partrec f) (hg : Computable g) : Partrec fun a => f (g a) := (hf.comp hg).of_eq fun n => by simp; cases' e : decode (α := α) n with a <;> simp [e, encodek] theorem nat_iff {f : ℕ →. ℕ} : Partrec f ↔ Nat.Partrec f := by simp [Partrec, map_id'] theorem map_encode_iff {f : α →. σ} : (Partrec fun a => (f a).map encode) ↔ Partrec f := Iff.rfl end Partrec namespace Partrec₂ variable {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} variable [Primcodable α] [Primcodable β] [Primcodable γ] [Primcodable δ] [Primcodable σ] theorem unpaired {f : ℕ → ℕ →. α} : Partrec (Nat.unpaired f) ↔ Partrec₂ f := ⟨fun h => by simpa using Partrec.comp (g := fun p : ℕ × ℕ => (p.1, p.2)) h Primrec₂.pair.to_comp, fun h => h.comp Primrec.unpair.to_comp⟩ theorem unpaired' {f : ℕ → ℕ →. ℕ} : Nat.Partrec (Nat.unpaired f) ↔ Partrec₂ f := Partrec.nat_iff.symm.trans unpaired nonrec theorem comp {f : β → γ →. σ} {g : α → β} {h : α → γ} (hf : Partrec₂ f) (hg : Computable g) (hh : Computable h) : Partrec fun a => f (g a) (h a) := hf.comp (hg.pair hh) theorem comp₂ {f : γ → δ →. σ} {g : α → β → γ} {h : α → β → δ} (hf : Partrec₂ f) (hg : Computable₂ g) (hh : Computable₂ h) : Partrec₂ fun a b => f (g a b) (h a b) := hf.comp hg hh end Partrec₂ namespace Computable variable {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variable [Primcodable α] [Primcodable β] [Primcodable γ] [Primcodable σ] nonrec theorem comp {f : β → σ} {g : α → β} (hf : Computable f) (hg : Computable g) : Computable fun a => f (g a) := hf.comp hg theorem comp₂ {f : γ → σ} {g : α → β → γ} (hf : Computable f) (hg : Computable₂ g) : Computable₂ fun a b => f (g a b) := hf.comp hg end Computable namespace Computable₂ variable {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} variable [Primcodable α] [Primcodable β] [Primcodable γ] [Primcodable δ] [Primcodable σ] theorem mk {f : α → β → σ} (hf : Computable fun p : α × β => f p.1 p.2) : Computable₂ f := hf nonrec theorem comp {f : β → γ → σ} {g : α → β} {h : α → γ} (hf : Computable₂ f) (hg : Computable g) (hh : Computable h) : Computable fun a => f (g a) (h a) := hf.comp (hg.pair hh) theorem comp₂ {f : γ → δ → σ} {g : α → β → γ} {h : α → β → δ} (hf : Computable₂ f) (hg : Computable₂ g) (hh : Computable₂ h) : Computable₂ fun a b => f (g a b) (h a b) := hf.comp hg hh end Computable₂ namespace Partrec variable {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variable [Primcodable α] [Primcodable β] [Primcodable γ] [Primcodable σ] open Computable theorem rfind {p : α → ℕ →. Bool} (hp : Partrec₂ p) : Partrec fun a => Nat.rfind (p a) := (Nat.Partrec.rfind <| hp.map ((Primrec.dom_bool fun b => cond b 0 1).comp Primrec.snd).to₂.to_comp).of_eq fun n => by cases' e : decode (α := α) n with a <;> simp [e, Nat.rfind_zero_none, map_id'] congr; funext n simp only [map_map, Function.comp] refine map_id' (fun b => ?_) _ cases b <;> rfl theorem rfindOpt {f : α → ℕ → Option σ} (hf : Computable₂ f) : Partrec fun a => Nat.rfindOpt (f a) := (rfind (Primrec.option_isSome.to_comp.comp hf).partrec.to₂).bind (ofOption hf) theorem nat_casesOn_right {f : α → ℕ} {g : α → σ} {h : α → ℕ →. σ} (hf : Computable f) (hg : Computable g) (hh : Partrec₂ h) : Partrec fun a => (f a).casesOn (some (g a)) (h a) := (nat_rec hf hg (hh.comp fst (pred.comp <| hf.comp fst)).to₂).of_eq fun a => by simp only [PFun.coe_val, Nat.pred_eq_sub_one]; cases' f a with n <;> simp refine ext fun b => ⟨fun H => ?_, fun H => ?_⟩ · rcases mem_bind_iff.1 H with ⟨c, _, h₂⟩ exact h₂ · have : ∀ m, (Nat.rec (motive := fun _ => Part σ) (Part.some (g a)) (fun y IH => IH.bind fun _ => h a n) m).Dom := by intro m induction m <;> simp [*, H.fst] exact ⟨⟨this n, H.fst⟩, H.snd⟩ theorem bind_decode₂_iff {f : α →. σ} : Partrec f ↔ Nat.Partrec fun n => Part.bind (decode₂ α n) fun a => (f a).map encode := ⟨fun hf => nat_iff.1 <| (Computable.ofOption Primrec.decode₂.to_comp).bind <| (map hf (Computable.encode.comp snd).to₂).comp snd, fun h => map_encode_iff.1 <| by simpa [encodek₂] using (nat_iff.2 h).comp (@Computable.encode α _)⟩ theorem vector_mOfFn : ∀ {n} {f : Fin n → α →. σ}, (∀ i, Partrec (f i)) → Partrec fun a : α => Vector.mOfFn fun i => f i a | 0, _, _ => const _ | n + 1, f, hf => by simp only [Vector.mOfFn, Nat.add_eq, Nat.add_zero, pure_eq_some, bind_eq_bind] exact (hf 0).bind (Partrec.bind ((vector_mOfFn fun i => hf i.succ).comp fst) (Primrec.vector_cons.to_comp.comp (snd.comp fst) snd)) end Partrec @[simp] theorem Vector.mOfFn_part_some {α n} : ∀ f : Fin n → α, (Vector.mOfFn fun i => Part.some (f i)) = Part.some (Vector.ofFn f) := Vector.mOfFn_pure namespace Computable variable {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variable [Primcodable α] [Primcodable β] [Primcodable γ] [Primcodable σ] theorem option_some_iff {f : α → σ} : (Computable fun a => Option.some (f a)) ↔ Computable f := ⟨fun h => encode_iff.1 <| Primrec.pred.to_comp.comp <| encode_iff.2 h, option_some.comp⟩ theorem bind_decode_iff {f : α → β → Option σ} : (Computable₂ fun a n => (decode (α := β) n).bind (f a)) ↔ Computable₂ f := ⟨fun hf => Nat.Partrec.of_eq (((Partrec.nat_iff.2 (Nat.Partrec.ppred.comp <| Nat.Partrec.of_primrec <| Primcodable.prim (α := β))).comp snd).bind (Computable.comp hf fst).to₂.partrec₂) fun n => by simp only [decode_prod_val, decode_nat, Option.map_some', PFun.coe_val, bind_eq_bind, bind_some, Part.map_bind, map_some] cases decode (α := α) n.unpair.1 <;> simp cases decode (α := β) n.unpair.2 <;> simp, fun hf => by have : Partrec fun a : α × ℕ => (encode (decode (α := β) a.2)).casesOn (some Option.none) fun n => Part.map (f a.1) (decode (α := β) n) := Partrec.nat_casesOn_right (h := fun (a : α × ℕ) (n : ℕ) ↦ map (fun b ↦ f a.1 b) (Part.ofOption (decode n))) (Primrec.encdec.to_comp.comp snd) (const Option.none) ((ofOption (Computable.decode.comp snd)).map (hf.comp (fst.comp <| fst.comp fst) snd).to₂) refine this.of_eq fun a => ?_ simp; cases decode (α := β) a.2 <;> simp [encodek]⟩ theorem map_decode_iff {f : α → β → σ} : (Computable₂ fun a n => (decode (α := β) n).map (f a)) ↔ Computable₂ f := by convert (bind_decode_iff (f := fun a => Option.some ∘ f a)).trans option_some_iff apply Option.map_eq_bind theorem nat_rec {f : α → ℕ} {g : α → σ} {h : α → ℕ × σ → σ} (hf : Computable f) (hg : Computable g) (hh : Computable₂ h) : Computable fun a => Nat.rec (motive := fun _ => σ) (g a) (fun y IH => h a (y, IH)) (f a) := (Partrec.nat_rec hf hg hh.partrec₂).of_eq fun a => by simp; induction f a <;> simp [*] theorem nat_casesOn {f : α → ℕ} {g : α → σ} {h : α → ℕ → σ} (hf : Computable f) (hg : Computable g) (hh : Computable₂ h) : Computable fun a => Nat.casesOn (motive := fun _ => σ) (f a) (g a) (h a) := nat_rec hf hg (hh.comp fst <| fst.comp snd).to₂ theorem cond {c : α → Bool} {f : α → σ} {g : α → σ} (hc : Computable c) (hf : Computable f) (hg : Computable g) : Computable fun a => cond (c a) (f a) (g a) := (nat_casesOn (encode_iff.2 hc) hg (hf.comp fst).to₂).of_eq fun a => by cases c a <;> rfl theorem option_casesOn {o : α → Option β} {f : α → σ} {g : α → β → σ} (ho : Computable o) (hf : Computable f) (hg : Computable₂ g) : @Computable _ σ _ _ fun a => Option.casesOn (o a) (f a) (g a) := option_some_iff.1 <| (nat_casesOn (encode_iff.2 ho) (option_some_iff.2 hf) (map_decode_iff.2 hg)).of_eq fun a => by cases o a <;> simp [encodek] theorem option_bind {f : α → Option β} {g : α → β → Option σ} (hf : Computable f) (hg : Computable₂ g) : Computable fun a => (f a).bind (g a) := (option_casesOn hf (const Option.none) hg).of_eq fun a => by cases f a <;> rfl theorem option_map {f : α → Option β} {g : α → β → σ} (hf : Computable f) (hg : Computable₂ g) : Computable fun a => (f a).map (g a) := by convert option_bind hf (option_some.comp₂ hg) apply Option.map_eq_bind theorem option_getD {f : α → Option β} {g : α → β} (hf : Computable f) (hg : Computable g) : Computable fun a => (f a).getD (g a) := (Computable.option_casesOn hf hg (show Computable₂ fun _ b => b from Computable.snd)).of_eq fun a => by cases f a <;> rfl theorem subtype_mk {f : α → β} {p : β → Prop} [DecidablePred p] {h : ∀ a, p (f a)} (hp : PrimrecPred p) (hf : Computable f) : @Computable _ _ _ (Primcodable.subtype hp) fun a => (⟨f a, h a⟩ : Subtype p) := hf theorem sum_casesOn {f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ → σ} (hf : Computable f) (hg : Computable₂ g) (hh : Computable₂ h) : @Computable _ σ _ _ fun a => Sum.casesOn (f a) (g a) (h a) := option_some_iff.1 <| (cond (nat_bodd.comp <| encode_iff.2 hf) (option_map (Computable.decode.comp <| nat_div2.comp <| encode_iff.2 hf) hh) (option_map (Computable.decode.comp <| nat_div2.comp <| encode_iff.2 hf) hg)).of_eq fun a => by cases' f a with b c <;> simp [Nat.div2_val] theorem nat_strong_rec (f : α → ℕ → σ) {g : α → List σ → Option σ} (hg : Computable₂ g) (H : ∀ a n, g a ((List.range n).map (f a)) = Option.some (f a n)) : Computable₂ f := suffices Computable₂ fun a n => (List.range n).map (f a) from option_some_iff.1 <| (list_get?.comp (this.comp fst (succ.comp snd)) snd).to₂.of_eq fun a => by simp [List.getElem?_range (Nat.lt_succ_self a.2)] option_some_iff.1 <| (nat_rec snd (const (Option.some [])) (to₂ <| option_bind (snd.comp snd) <| to₂ <| option_map (hg.comp (fst.comp <| fst.comp fst) snd) (to₂ <| list_concat.comp (snd.comp fst) snd))).of_eq fun a => by induction' a.2 with n IH; · rfl simp [IH, H, List.range_succ] theorem list_ofFn : ∀ {n} {f : Fin n → α → σ}, (∀ i, Computable (f i)) → Computable fun a => List.ofFn fun i => f i a | 0, _, _ => by simp only [List.ofFn_zero] exact const [] | n + 1, f, hf => by simp only [List.ofFn_succ] exact list_cons.comp (hf 0) (list_ofFn fun i => hf i.succ) theorem vector_ofFn {n} {f : Fin n → α → σ} (hf : ∀ i, Computable (f i)) : Computable fun a => Vector.ofFn fun i => f i a := (Partrec.vector_mOfFn hf).of_eq fun a => by simp end Computable namespace Partrec variable {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variable [Primcodable α] [Primcodable β] [Primcodable γ] [Primcodable σ] open Computable theorem option_some_iff {f : α →. σ} : (Partrec fun a => (f a).map Option.some) ↔ Partrec f := ⟨fun h => (Nat.Partrec.ppred.comp h).of_eq fun n => by -- Porting note: needed to help with applying bind_some_eq_map because `Function.comp` got -- less reducible. simp [Part.bind_assoc, ← Function.comp_apply (f := Part.some) (g := encode), bind_some_eq_map, -Function.comp_apply], fun hf => hf.map (option_some.comp snd).to₂⟩ theorem option_casesOn_right {o : α → Option β} {f : α → σ} {g : α → β →. σ} (ho : Computable o) (hf : Computable f) (hg : Partrec₂ g) : @Partrec _ σ _ _ fun a => Option.casesOn (o a) (Part.some (f a)) (g a) := have : Partrec fun a : α => Nat.casesOn (encode (o a)) (Part.some (f a)) (fun n => Part.bind (decode (α := β) n) (g a)) := nat_casesOn_right (h := fun a n ↦ Part.bind (ofOption (decode n)) fun b ↦ g a b) (encode_iff.2 ho) hf.partrec <| ((@Computable.decode β _).comp snd).ofOption.bind (hg.comp (fst.comp fst) snd).to₂ this.of_eq fun a => by cases' o a with b <;> simp [encodek] theorem sum_casesOn_right {f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ →. σ} (hf : Computable f) (hg : Computable₂ g) (hh : Partrec₂ h) : @Partrec _ σ _ _ fun a => Sum.casesOn (f a) (fun b => Part.some (g a b)) (h a) := have : Partrec fun a => (Option.casesOn (Sum.casesOn (f a) (fun _ => Option.none) Option.some : Option γ) (some (Sum.casesOn (f a) (fun b => some (g a b)) fun _ => Option.none)) fun c => (h a c).map Option.some : Part (Option σ)) := option_casesOn_right (g := fun a n => Part.map Option.some (h a n)) (sum_casesOn hf (const Option.none).to₂ (option_some.comp snd).to₂) (sum_casesOn (g := fun a n => Option.some (g a n)) hf (option_some.comp hg) (const Option.none).to₂) (option_some_iff.2 hh) option_some_iff.1 <| this.of_eq fun a => by cases f a <;> simp theorem sum_casesOn_left {f : α → β ⊕ γ} {g : α → β →. σ} {h : α → γ → σ} (hf : Computable f) (hg : Partrec₂ g) (hh : Computable₂ h) : @Partrec _ σ _ _ fun a => Sum.casesOn (f a) (g a) fun c => Part.some (h a c) := (sum_casesOn_right (sum_casesOn hf (sum_inr.comp snd).to₂ (sum_inl.comp snd).to₂) hh hg).of_eq fun a => by cases f a <;> simp theorem fix_aux {α σ} (f : α →. σ ⊕ α) (a : α) (b : σ) : let F : α → ℕ →. σ ⊕ α := fun a n => n.rec (some (Sum.inr a)) fun _ IH => IH.bind fun s => Sum.casesOn s (fun _ => Part.some s) f (∃ n : ℕ, ((∃ b' : σ, Sum.inl b' ∈ F a n) ∧ ∀ {m : ℕ}, m < n → ∃ b : α, Sum.inr b ∈ F a m) ∧ Sum.inl b ∈ F a n) ↔ b ∈ PFun.fix f a := by intro F; refine ⟨fun h => ?_, fun h => ?_⟩ · rcases h with ⟨n, ⟨_x, h₁⟩, h₂⟩ have : ∀ m a', Sum.inr a' ∈ F a m → b ∈ PFun.fix f a' → b ∈ PFun.fix f a := by intro m a' am ba induction' m with m IH generalizing a' <;> simp [F] at am · rwa [← am] rcases am with ⟨a₂, am₂, fa₂⟩ exact IH _ am₂ (PFun.mem_fix_iff.2 (Or.inr ⟨_, fa₂, ba⟩)) cases n <;> simp [F] at h₂ rcases h₂ with (h₂ | ⟨a', am', fa'⟩) · cases' h₁ (Nat.lt_succ_self _) with a' h injection mem_unique h h₂ · exact this _ _ am' (PFun.mem_fix_iff.2 (Or.inl fa')) · suffices ∀ a', b ∈ PFun.fix f a' → ∀ k, Sum.inr a' ∈ F a k → ∃ n, Sum.inl b ∈ F a n ∧ ∀ m < n, k ≤ m → ∃ a₂, Sum.inr a₂ ∈ F a m by rcases this _ h 0 (by simp [F]) with ⟨n, hn₁, hn₂⟩ exact ⟨_, ⟨⟨_, hn₁⟩, fun {m} mn => hn₂ m mn (Nat.zero_le _)⟩, hn₁⟩ intro a₁ h₁ apply @PFun.fixInduction _ _ _ _ _ _ h₁ intro a₂ h₂ IH k hk rcases PFun.mem_fix_iff.1 h₂ with (h₂ | ⟨a₃, am₃, _⟩) · refine ⟨k.succ, ?_, fun m mk km => ⟨a₂, ?_⟩⟩ · simpa [F] using Or.inr ⟨_, hk, h₂⟩ · rwa [le_antisymm (Nat.le_of_lt_succ mk) km] · rcases IH _ am₃ k.succ (by simpa [F] using ⟨_, hk, am₃⟩) with ⟨n, hn₁, hn₂⟩ refine ⟨n, hn₁, fun m mn km => ?_⟩ cases' km.lt_or_eq_dec with km km · exact hn₂ _ mn km · exact km ▸ ⟨_, hk⟩ theorem fix {f : α →. σ ⊕ α} (hf : Partrec f) : Partrec (PFun.fix f) := by let F : α → ℕ →. σ ⊕ α := fun a n => n.rec (some (Sum.inr a)) fun _ IH => IH.bind fun s => Sum.casesOn s (fun _ => Part.some s) f have hF : Partrec₂ F := Partrec.nat_rec snd (sum_inr.comp fst).partrec (sum_casesOn_right (snd.comp snd) (snd.comp <| snd.comp fst).to₂ (hf.comp snd).to₂).to₂ let p a n := @Part.map _ Bool (fun s => Sum.casesOn s (fun _ => true) fun _ => false) (F a n) have hp : Partrec₂ p := hF.map ((sum_casesOn Computable.id (const true).to₂ (const false).to₂).comp snd).to₂ exact (hp.rfind.bind (hF.bind (sum_casesOn_right snd snd.to₂ none.to₂).to₂).to₂).of_eq fun a => ext fun b => by simpa [p] using fix_aux f _ _ end Partrec
Computability\PartrecCode.lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Computability.Partrec import Mathlib.Data.Option.Basic /-! # Gödel Numbering for Partial Recursive Functions. This file defines `Nat.Partrec.Code`, an inductive datatype describing code for partial recursive functions on ℕ. It defines an encoding for these codes, and proves that the constructors are primitive recursive with respect to the encoding. It also defines the evaluation of these codes as partial functions using `PFun`, and proves that a function is partially recursive (as defined by `Nat.Partrec`) if and only if it is the evaluation of some code. ## Main Definitions * `Nat.Partrec.Code`: Inductive datatype for partial recursive codes. * `Nat.Partrec.Code.encodeCode`: A (computable) encoding of codes as natural numbers. * `Nat.Partrec.Code.ofNatCode`: The inverse of this encoding. * `Nat.Partrec.Code.eval`: The interpretation of a `Nat.Partrec.Code` as a partial function. ## Main Results * `Nat.Partrec.Code.rec_prim`: Recursion on `Nat.Partrec.Code` is primitive recursive. * `Nat.Partrec.Code.rec_computable`: Recursion on `Nat.Partrec.Code` is computable. * `Nat.Partrec.Code.smn`: The $S_n^m$ theorem. * `Nat.Partrec.Code.exists_code`: Partial recursiveness is equivalent to being the eval of a code. * `Nat.Partrec.Code.evaln_prim`: `evaln` is primitive recursive. * `Nat.Partrec.Code.fixed_point`: Roger's fixed point theorem. ## References * [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019] -/ open Encodable Denumerable namespace Nat.Partrec theorem rfind' {f} (hf : Nat.Partrec f) : Nat.Partrec (Nat.unpaired fun a m => (Nat.rfind fun n => (fun m => m = 0) <$> f (Nat.pair a (n + m))).map (· + m)) := Partrec₂.unpaired'.2 <| by refine Partrec.map ((@Partrec₂.unpaired' fun a b : ℕ => Nat.rfind fun n => (fun m => m = 0) <$> f (Nat.pair a (n + b))).1 ?_) (Primrec.nat_add.comp Primrec.snd <| Primrec.snd.comp Primrec.fst).to_comp.to₂ have : Nat.Partrec (fun a => Nat.rfind (fun n => (fun m => decide (m = 0)) <$> Nat.unpaired (fun a b => f (Nat.pair (Nat.unpair a).1 (b + (Nat.unpair a).2))) (Nat.pair a n))) := rfind (Partrec₂.unpaired'.2 ((Partrec.nat_iff.2 hf).comp (Primrec₂.pair.comp (Primrec.fst.comp <| Primrec.unpair.comp Primrec.fst) (Primrec.nat_add.comp Primrec.snd (Primrec.snd.comp <| Primrec.unpair.comp Primrec.fst))).to_comp)) simpa /-- Code for partial recursive functions from ℕ to ℕ. See `Nat.Partrec.Code.eval` for the interpretation of these constructors. -/ inductive Code : Type | zero : Code | succ : Code | left : Code | right : Code | pair : Code → Code → Code | comp : Code → Code → Code | prec : Code → Code → Code | rfind' : Code → Code compile_inductive% Code end Nat.Partrec namespace Nat.Partrec.Code instance instInhabited : Inhabited Code := ⟨zero⟩ /-- Returns a code for the constant function outputting a particular natural. -/ protected def const : ℕ → Code | 0 => zero | n + 1 => comp succ (Code.const n) theorem const_inj : ∀ {n₁ n₂}, Nat.Partrec.Code.const n₁ = Nat.Partrec.Code.const n₂ → n₁ = n₂ | 0, 0, _ => by simp | n₁ + 1, n₂ + 1, h => by dsimp [Nat.Partrec.Code.const] at h injection h with h₁ h₂ simp only [const_inj h₂] /-- A code for the identity function. -/ protected def id : Code := pair left right /-- Given a code `c` taking a pair as input, returns a code using `n` as the first argument to `c`. -/ def curry (c : Code) (n : ℕ) : Code := comp c (pair (Code.const n) Code.id) -- Porting note: `bit0` and `bit1` are deprecated. /-- An encoding of a `Nat.Partrec.Code` as a ℕ. -/ def encodeCode : Code → ℕ | zero => 0 | succ => 1 | left => 2 | right => 3 | pair cf cg => 2 * (2 * Nat.pair (encodeCode cf) (encodeCode cg)) + 4 | comp cf cg => 2 * (2 * Nat.pair (encodeCode cf) (encodeCode cg) + 1) + 4 | prec cf cg => (2 * (2 * Nat.pair (encodeCode cf) (encodeCode cg)) + 1) + 4 | rfind' cf => (2 * (2 * encodeCode cf + 1) + 1) + 4 /-- A decoder for `Nat.Partrec.Code.encodeCode`, taking any ℕ to the `Nat.Partrec.Code` it represents. -/ def ofNatCode : ℕ → Code | 0 => zero | 1 => succ | 2 => left | 3 => right | n + 4 => let m := n.div2.div2 have hm : m < n + 4 := by simp only [m, div2_val] exact lt_of_le_of_lt (le_trans (Nat.div_le_self _ _) (Nat.div_le_self _ _)) (Nat.succ_le_succ (Nat.le_add_right _ _)) have _m1 : m.unpair.1 < n + 4 := lt_of_le_of_lt m.unpair_left_le hm have _m2 : m.unpair.2 < n + 4 := lt_of_le_of_lt m.unpair_right_le hm match n.bodd, n.div2.bodd with | false, false => pair (ofNatCode m.unpair.1) (ofNatCode m.unpair.2) | false, true => comp (ofNatCode m.unpair.1) (ofNatCode m.unpair.2) | true , false => prec (ofNatCode m.unpair.1) (ofNatCode m.unpair.2) | true , true => rfind' (ofNatCode m) /-- Proof that `Nat.Partrec.Code.ofNatCode` is the inverse of `Nat.Partrec.Code.encodeCode`-/ private theorem encode_ofNatCode : ∀ n, encodeCode (ofNatCode n) = n | 0 => by simp [ofNatCode, encodeCode] | 1 => by simp [ofNatCode, encodeCode] | 2 => by simp [ofNatCode, encodeCode] | 3 => by simp [ofNatCode, encodeCode] | n + 4 => by let m := n.div2.div2 have hm : m < n + 4 := by simp only [m, div2_val] exact lt_of_le_of_lt (le_trans (Nat.div_le_self _ _) (Nat.div_le_self _ _)) (Nat.succ_le_succ (Nat.le_add_right _ _)) have _m1 : m.unpair.1 < n + 4 := lt_of_le_of_lt m.unpair_left_le hm have _m2 : m.unpair.2 < n + 4 := lt_of_le_of_lt m.unpair_right_le hm have IH := encode_ofNatCode m have IH1 := encode_ofNatCode m.unpair.1 have IH2 := encode_ofNatCode m.unpair.2 conv_rhs => rw [← Nat.bit_decomp n, ← Nat.bit_decomp n.div2] simp only [ofNatCode.eq_5] cases n.bodd <;> cases n.div2.bodd <;> simp [encodeCode, ofNatCode, IH, IH1, IH2, Nat.bit_val] instance instDenumerable : Denumerable Code := mk' ⟨encodeCode, ofNatCode, fun c => by induction c <;> try {rfl} <;> simp [encodeCode, ofNatCode, Nat.div2_val, *], encode_ofNatCode⟩ theorem encodeCode_eq : encode = encodeCode := rfl theorem ofNatCode_eq : ofNat Code = ofNatCode := rfl theorem encode_lt_pair (cf cg) : encode cf < encode (pair cf cg) ∧ encode cg < encode (pair cf cg) := by simp only [encodeCode_eq, encodeCode] have := Nat.mul_le_mul_right (Nat.pair cf.encodeCode cg.encodeCode) (by decide : 1 ≤ 2 * 2) rw [one_mul, mul_assoc] at this have := lt_of_le_of_lt this (lt_add_of_pos_right _ (by decide : 0 < 4)) exact ⟨lt_of_le_of_lt (Nat.left_le_pair _ _) this, lt_of_le_of_lt (Nat.right_le_pair _ _) this⟩ theorem encode_lt_comp (cf cg) : encode cf < encode (comp cf cg) ∧ encode cg < encode (comp cf cg) := by have : encode (pair cf cg) < encode (comp cf cg) := by simp [encodeCode_eq, encodeCode] exact (encode_lt_pair cf cg).imp (fun h => lt_trans h this) fun h => lt_trans h this theorem encode_lt_prec (cf cg) : encode cf < encode (prec cf cg) ∧ encode cg < encode (prec cf cg) := by have : encode (pair cf cg) < encode (prec cf cg) := by simp [encodeCode_eq, encodeCode] exact (encode_lt_pair cf cg).imp (fun h => lt_trans h this) fun h => lt_trans h this theorem encode_lt_rfind' (cf) : encode cf < encode (rfind' cf) := by simp only [encodeCode_eq, encodeCode] have := Nat.mul_le_mul_right cf.encodeCode (by decide : 1 ≤ 2 * 2) rw [one_mul, mul_assoc] at this refine lt_of_le_of_lt (le_trans this ?_) (lt_add_of_pos_right _ (by decide : 0 < 4)) exact le_of_lt (Nat.lt_succ_of_le <| Nat.mul_le_mul_left _ <| le_of_lt <| Nat.lt_succ_of_le <| Nat.mul_le_mul_left _ <| le_rfl) end Nat.Partrec.Code -- Porting note: Opening `Primrec` inside `namespace Nat.Partrec.Code` causes it to resolve -- to `Nat.Partrec`. Needs `open _root_.Partrec` support section open Primrec namespace Nat.Partrec.Code theorem pair_prim : Primrec₂ pair := Primrec₂.ofNat_iff.2 <| Primrec₂.encode_iff.1 <| nat_add.comp (nat_double.comp <| nat_double.comp <| Primrec₂.natPair.comp (encode_iff.2 <| (Primrec.ofNat Code).comp fst) (encode_iff.2 <| (Primrec.ofNat Code).comp snd)) (Primrec₂.const 4) theorem comp_prim : Primrec₂ comp := Primrec₂.ofNat_iff.2 <| Primrec₂.encode_iff.1 <| nat_add.comp (nat_double.comp <| nat_double_succ.comp <| Primrec₂.natPair.comp (encode_iff.2 <| (Primrec.ofNat Code).comp fst) (encode_iff.2 <| (Primrec.ofNat Code).comp snd)) (Primrec₂.const 4) theorem prec_prim : Primrec₂ prec := Primrec₂.ofNat_iff.2 <| Primrec₂.encode_iff.1 <| nat_add.comp (nat_double_succ.comp <| nat_double.comp <| Primrec₂.natPair.comp (encode_iff.2 <| (Primrec.ofNat Code).comp fst) (encode_iff.2 <| (Primrec.ofNat Code).comp snd)) (Primrec₂.const 4) theorem rfind_prim : Primrec rfind' := ofNat_iff.2 <| encode_iff.1 <| nat_add.comp (nat_double_succ.comp <| nat_double_succ.comp <| encode_iff.2 <| Primrec.ofNat Code) (const 4) theorem rec_prim' {α σ} [Primcodable α] [Primcodable σ] {c : α → Code} (hc : Primrec c) {z : α → σ} (hz : Primrec z) {s : α → σ} (hs : Primrec s) {l : α → σ} (hl : Primrec l) {r : α → σ} (hr : Primrec r) {pr : α → Code × Code × σ × σ → σ} (hpr : Primrec₂ pr) {co : α → Code × Code × σ × σ → σ} (hco : Primrec₂ co) {pc : α → Code × Code × σ × σ → σ} (hpc : Primrec₂ pc) {rf : α → Code × σ → σ} (hrf : Primrec₂ rf) : let PR (a) cf cg hf hg := pr a (cf, cg, hf, hg) let CO (a) cf cg hf hg := co a (cf, cg, hf, hg) let PC (a) cf cg hf hg := pc a (cf, cg, hf, hg) let RF (a) cf hf := rf a (cf, hf) let F (a : α) (c : Code) : σ := Nat.Partrec.Code.recOn c (z a) (s a) (l a) (r a) (PR a) (CO a) (PC a) (RF a) Primrec (fun a => F a (c a) : α → σ) := by intros _ _ _ _ F let G₁ : (α × List σ) × ℕ × ℕ → Option σ := fun p => letI a := p.1.1; letI IH := p.1.2; letI n := p.2.1; letI m := p.2.2 (IH.get? m).bind fun s => (IH.get? m.unpair.1).bind fun s₁ => (IH.get? m.unpair.2).map fun s₂ => cond n.bodd (cond n.div2.bodd (rf a (ofNat Code m, s)) (pc a (ofNat Code m.unpair.1, ofNat Code m.unpair.2, s₁, s₂))) (cond n.div2.bodd (co a (ofNat Code m.unpair.1, ofNat Code m.unpair.2, s₁, s₂)) (pr a (ofNat Code m.unpair.1, ofNat Code m.unpair.2, s₁, s₂))) have : Primrec G₁ := option_bind (list_get?.comp (snd.comp fst) (snd.comp snd)) <| .mk <| option_bind ((list_get?.comp (snd.comp fst) (fst.comp <| Primrec.unpair.comp (snd.comp snd))).comp fst) <| .mk <| option_map ((list_get?.comp (snd.comp fst) (snd.comp <| Primrec.unpair.comp (snd.comp snd))).comp <| fst.comp fst) <| .mk <| have a := fst.comp (fst.comp <| fst.comp <| fst.comp fst) have n := fst.comp (snd.comp <| fst.comp <| fst.comp fst) have m := snd.comp (snd.comp <| fst.comp <| fst.comp fst) have m₁ := fst.comp (Primrec.unpair.comp m) have m₂ := snd.comp (Primrec.unpair.comp m) have s := snd.comp (fst.comp fst) have s₁ := snd.comp fst have s₂ := snd (nat_bodd.comp n).cond ((nat_bodd.comp <| nat_div2.comp n).cond (hrf.comp a (((Primrec.ofNat Code).comp m).pair s)) (hpc.comp a (((Primrec.ofNat Code).comp m₁).pair <| ((Primrec.ofNat Code).comp m₂).pair <| s₁.pair s₂))) (Primrec.cond (nat_bodd.comp <| nat_div2.comp n) (hco.comp a (((Primrec.ofNat Code).comp m₁).pair <| ((Primrec.ofNat Code).comp m₂).pair <| s₁.pair s₂)) (hpr.comp a (((Primrec.ofNat Code).comp m₁).pair <| ((Primrec.ofNat Code).comp m₂).pair <| s₁.pair s₂))) let G : α → List σ → Option σ := fun a IH => IH.length.casesOn (some (z a)) fun n => n.casesOn (some (s a)) fun n => n.casesOn (some (l a)) fun n => n.casesOn (some (r a)) fun n => G₁ ((a, IH), n, n.div2.div2) have : Primrec₂ G := .mk <| nat_casesOn (list_length.comp snd) (option_some_iff.2 (hz.comp fst)) <| .mk <| nat_casesOn snd (option_some_iff.2 (hs.comp (fst.comp fst))) <| .mk <| nat_casesOn snd (option_some_iff.2 (hl.comp (fst.comp <| fst.comp fst))) <| .mk <| nat_casesOn snd (option_some_iff.2 (hr.comp (fst.comp <| fst.comp <| fst.comp fst))) <| .mk <| this.comp <| ((fst.pair snd).comp <| fst.comp <| fst.comp <| fst.comp <| fst).pair <| snd.pair <| nat_div2.comp <| nat_div2.comp snd refine (nat_strong_rec (fun a n => F a (ofNat Code n)) this.to₂ fun a n => ?_) |>.comp .id (encode_iff.2 hc) |>.of_eq fun a => by simp iterate 4 cases' n with n; · simp [ofNatCode_eq, ofNatCode]; rfl simp only [G]; rw [List.length_map, List.length_range] let m := n.div2.div2 show G₁ ((a, (List.range (n + 4)).map fun n => F a (ofNat Code n)), n, m) = some (F a (ofNat Code (n + 4))) have hm : m < n + 4 := by simp only [m, div2_val] exact lt_of_le_of_lt (le_trans (Nat.div_le_self ..) (Nat.div_le_self ..)) (Nat.succ_le_succ (Nat.le_add_right ..)) have m1 : m.unpair.1 < n + 4 := lt_of_le_of_lt m.unpair_left_le hm have m2 : m.unpair.2 < n + 4 := lt_of_le_of_lt m.unpair_right_le hm simp [G₁]; simp [m, List.getElem?_map, List.getElem?_range, hm, m1, m2] rw [show ofNat Code (n + 4) = ofNatCode (n + 4) from rfl] simp [ofNatCode] cases n.bodd <;> cases n.div2.bodd <;> rfl /-- Recursion on `Nat.Partrec.Code` is primitive recursive. -/ theorem rec_prim {α σ} [Primcodable α] [Primcodable σ] {c : α → Code} (hc : Primrec c) {z : α → σ} (hz : Primrec z) {s : α → σ} (hs : Primrec s) {l : α → σ} (hl : Primrec l) {r : α → σ} (hr : Primrec r) {pr : α → Code → Code → σ → σ → σ} (hpr : Primrec fun a : α × Code × Code × σ × σ => pr a.1 a.2.1 a.2.2.1 a.2.2.2.1 a.2.2.2.2) {co : α → Code → Code → σ → σ → σ} (hco : Primrec fun a : α × Code × Code × σ × σ => co a.1 a.2.1 a.2.2.1 a.2.2.2.1 a.2.2.2.2) {pc : α → Code → Code → σ → σ → σ} (hpc : Primrec fun a : α × Code × Code × σ × σ => pc a.1 a.2.1 a.2.2.1 a.2.2.2.1 a.2.2.2.2) {rf : α → Code → σ → σ} (hrf : Primrec fun a : α × Code × σ => rf a.1 a.2.1 a.2.2) : let F (a : α) (c : Code) : σ := Nat.Partrec.Code.recOn c (z a) (s a) (l a) (r a) (pr a) (co a) (pc a) (rf a) Primrec fun a => F a (c a) := rec_prim' hc hz hs hl hr (pr := fun a b => pr a b.1 b.2.1 b.2.2.1 b.2.2.2) (.mk hpr) (co := fun a b => co a b.1 b.2.1 b.2.2.1 b.2.2.2) (.mk hco) (pc := fun a b => pc a b.1 b.2.1 b.2.2.1 b.2.2.2) (.mk hpc) (rf := fun a b => rf a b.1 b.2) (.mk hrf) end Nat.Partrec.Code end namespace Nat.Partrec.Code section open Computable /-- Recursion on `Nat.Partrec.Code` is computable. -/ theorem rec_computable {α σ} [Primcodable α] [Primcodable σ] {c : α → Code} (hc : Computable c) {z : α → σ} (hz : Computable z) {s : α → σ} (hs : Computable s) {l : α → σ} (hl : Computable l) {r : α → σ} (hr : Computable r) {pr : α → Code × Code × σ × σ → σ} (hpr : Computable₂ pr) {co : α → Code × Code × σ × σ → σ} (hco : Computable₂ co) {pc : α → Code × Code × σ × σ → σ} (hpc : Computable₂ pc) {rf : α → Code × σ → σ} (hrf : Computable₂ rf) : let PR (a) cf cg hf hg := pr a (cf, cg, hf, hg) let CO (a) cf cg hf hg := co a (cf, cg, hf, hg) let PC (a) cf cg hf hg := pc a (cf, cg, hf, hg) let RF (a) cf hf := rf a (cf, hf) let F (a : α) (c : Code) : σ := Nat.Partrec.Code.recOn c (z a) (s a) (l a) (r a) (PR a) (CO a) (PC a) (RF a) Computable fun a => F a (c a) := by -- TODO(Mario): less copy-paste from previous proof intros _ _ _ _ F let G₁ : (α × List σ) × ℕ × ℕ → Option σ := fun p => letI a := p.1.1; letI IH := p.1.2; letI n := p.2.1; letI m := p.2.2 (IH.get? m).bind fun s => (IH.get? m.unpair.1).bind fun s₁ => (IH.get? m.unpair.2).map fun s₂ => cond n.bodd (cond n.div2.bodd (rf a (ofNat Code m, s)) (pc a (ofNat Code m.unpair.1, ofNat Code m.unpair.2, s₁, s₂))) (cond n.div2.bodd (co a (ofNat Code m.unpair.1, ofNat Code m.unpair.2, s₁, s₂)) (pr a (ofNat Code m.unpair.1, ofNat Code m.unpair.2, s₁, s₂))) have : Computable G₁ := by refine option_bind (list_get?.comp (snd.comp fst) (snd.comp snd)) <| .mk ?_ refine option_bind ((list_get?.comp (snd.comp fst) (fst.comp <| Computable.unpair.comp (snd.comp snd))).comp fst) <| .mk ?_ refine option_map ((list_get?.comp (snd.comp fst) (snd.comp <| Computable.unpair.comp (snd.comp snd))).comp <| fst.comp fst) <| .mk ?_ exact have a := fst.comp (fst.comp <| fst.comp <| fst.comp fst) have n := fst.comp (snd.comp <| fst.comp <| fst.comp fst) have m := snd.comp (snd.comp <| fst.comp <| fst.comp fst) have m₁ := fst.comp (Computable.unpair.comp m) have m₂ := snd.comp (Computable.unpair.comp m) have s := snd.comp (fst.comp fst) have s₁ := snd.comp fst have s₂ := snd (nat_bodd.comp n).cond ((nat_bodd.comp <| nat_div2.comp n).cond (hrf.comp a (((Computable.ofNat Code).comp m).pair s)) (hpc.comp a (((Computable.ofNat Code).comp m₁).pair <| ((Computable.ofNat Code).comp m₂).pair <| s₁.pair s₂))) (Computable.cond (nat_bodd.comp <| nat_div2.comp n) (hco.comp a (((Computable.ofNat Code).comp m₁).pair <| ((Computable.ofNat Code).comp m₂).pair <| s₁.pair s₂)) (hpr.comp a (((Computable.ofNat Code).comp m₁).pair <| ((Computable.ofNat Code).comp m₂).pair <| s₁.pair s₂))) let G : α → List σ → Option σ := fun a IH => IH.length.casesOn (some (z a)) fun n => n.casesOn (some (s a)) fun n => n.casesOn (some (l a)) fun n => n.casesOn (some (r a)) fun n => G₁ ((a, IH), n, n.div2.div2) have : Computable₂ G := .mk <| nat_casesOn (list_length.comp snd) (option_some_iff.2 (hz.comp fst)) <| .mk <| nat_casesOn snd (option_some_iff.2 (hs.comp (fst.comp fst))) <| .mk <| nat_casesOn snd (option_some_iff.2 (hl.comp (fst.comp <| fst.comp fst))) <| .mk <| nat_casesOn snd (option_some_iff.2 (hr.comp (fst.comp <| fst.comp <| fst.comp fst))) <| .mk <| this.comp <| ((fst.pair snd).comp <| fst.comp <| fst.comp <| fst.comp <| fst).pair <| snd.pair <| nat_div2.comp <| nat_div2.comp snd refine (nat_strong_rec (fun a n => F a (ofNat Code n)) this.to₂ fun a n => ?_) |>.comp .id (encode_iff.2 hc) |>.of_eq fun a => by simp iterate 4 cases' n with n; · simp [ofNatCode_eq, ofNatCode]; rfl simp only [G]; rw [List.length_map, List.length_range] let m := n.div2.div2 show G₁ ((a, (List.range (n + 4)).map fun n => F a (ofNat Code n)), n, m) = some (F a (ofNat Code (n + 4))) have hm : m < n + 4 := by simp only [m, div2_val] exact lt_of_le_of_lt (le_trans (Nat.div_le_self ..) (Nat.div_le_self ..)) (Nat.succ_le_succ (Nat.le_add_right ..)) have m1 : m.unpair.1 < n + 4 := lt_of_le_of_lt m.unpair_left_le hm have m2 : m.unpair.2 < n + 4 := lt_of_le_of_lt m.unpair_right_le hm simp [G₁]; simp [m, List.getElem?_map, List.getElem?_range, hm, m1, m2] rw [show ofNat Code (n + 4) = ofNatCode (n + 4) from rfl] simp [ofNatCode] cases n.bodd <;> cases n.div2.bodd <;> rfl end /-- The interpretation of a `Nat.Partrec.Code` as a partial function. * `Nat.Partrec.Code.zero`: The constant zero function. * `Nat.Partrec.Code.succ`: The successor function. * `Nat.Partrec.Code.left`: Left unpairing of a pair of ℕ (encoded by `Nat.pair`) * `Nat.Partrec.Code.right`: Right unpairing of a pair of ℕ (encoded by `Nat.pair`) * `Nat.Partrec.Code.pair`: Pairs the outputs of argument codes using `Nat.pair`. * `Nat.Partrec.Code.comp`: Composition of two argument codes. * `Nat.Partrec.Code.prec`: Primitive recursion. Given an argument of the form `Nat.pair a n`: * If `n = 0`, returns `eval cf a`. * If `n = succ k`, returns `eval cg (pair a (pair k (eval (prec cf cg) (pair a k))))` * `Nat.Partrec.Code.rfind'`: Minimization. For `f` an argument of the form `Nat.pair a m`, `rfind' f m` returns the least `a` such that `f a m = 0`, if one exists and `f b m` terminates for `b < a` -/ def eval : Code → ℕ →. ℕ | zero => pure 0 | succ => Nat.succ | left => ↑fun n : ℕ => n.unpair.1 | right => ↑fun n : ℕ => n.unpair.2 | pair cf cg => fun n => Nat.pair <$> eval cf n <*> eval cg n | comp cf cg => fun n => eval cg n >>= eval cf | prec cf cg => Nat.unpaired fun a n => n.rec (eval cf a) fun y IH => do let i ← IH eval cg (Nat.pair a (Nat.pair y i)) | rfind' cf => Nat.unpaired fun a m => (Nat.rfind fun n => (fun m => m = 0) <$> eval cf (Nat.pair a (n + m))).map (· + m) /-- Helper lemma for the evaluation of `prec` in the base case. -/ @[simp] theorem eval_prec_zero (cf cg : Code) (a : ℕ) : eval (prec cf cg) (Nat.pair a 0) = eval cf a := by rw [eval, Nat.unpaired, Nat.unpair_pair] simp (config := { Lean.Meta.Simp.neutralConfig with proj := true }) only [] rw [Nat.rec_zero] /-- Helper lemma for the evaluation of `prec` in the recursive case. -/ theorem eval_prec_succ (cf cg : Code) (a k : ℕ) : eval (prec cf cg) (Nat.pair a (Nat.succ k)) = do {let ih ← eval (prec cf cg) (Nat.pair a k); eval cg (Nat.pair a (Nat.pair k ih))} := by rw [eval, Nat.unpaired, Part.bind_eq_bind, Nat.unpair_pair] simp instance : Membership (ℕ →. ℕ) Code := ⟨fun f c => eval c = f⟩ @[simp] theorem eval_const : ∀ n m, eval (Code.const n) m = Part.some n | 0, m => rfl | n + 1, m => by simp! [eval_const n m] @[simp] theorem eval_id (n) : eval Code.id n = Part.some n := by simp! [Seq.seq] @[simp] theorem eval_curry (c n x) : eval (curry c n) x = eval c (Nat.pair n x) := by simp! [Seq.seq] theorem const_prim : Primrec Code.const := (_root_.Primrec.id.nat_iterate (_root_.Primrec.const zero) (comp_prim.comp (_root_.Primrec.const succ) Primrec.snd).to₂).of_eq fun n => by simp; induction n <;> simp [*, Code.const, Function.iterate_succ', -Function.iterate_succ] theorem curry_prim : Primrec₂ curry := comp_prim.comp Primrec.fst <| pair_prim.comp (const_prim.comp Primrec.snd) (_root_.Primrec.const Code.id) theorem curry_inj {c₁ c₂ n₁ n₂} (h : curry c₁ n₁ = curry c₂ n₂) : c₁ = c₂ ∧ n₁ = n₂ := ⟨by injection h, by injection h with h₁ h₂ injection h₂ with h₃ h₄ exact const_inj h₃⟩ /-- The $S_n^m$ theorem: There is a computable function, namely `Nat.Partrec.Code.curry`, that takes a program and a ℕ `n`, and returns a new program using `n` as the first argument. -/ theorem smn : ∃ f : Code → ℕ → Code, Computable₂ f ∧ ∀ c n x, eval (f c n) x = eval c (Nat.pair n x) := ⟨curry, Primrec₂.to_comp curry_prim, eval_curry⟩ /-- A function is partial recursive if and only if there is a code implementing it. Therefore, `eval` is a **universal partial recursive function**. -/ theorem exists_code {f : ℕ →. ℕ} : Nat.Partrec f ↔ ∃ c : Code, eval c = f := by refine ⟨fun h => ?_, ?_⟩ · induction h with | zero => exact ⟨zero, rfl⟩ | succ => exact ⟨succ, rfl⟩ | left => exact ⟨left, rfl⟩ | right => exact ⟨right, rfl⟩ | pair pf pg hf hg => rcases hf with ⟨cf, rfl⟩; rcases hg with ⟨cg, rfl⟩ exact ⟨pair cf cg, rfl⟩ | comp pf pg hf hg => rcases hf with ⟨cf, rfl⟩; rcases hg with ⟨cg, rfl⟩ exact ⟨comp cf cg, rfl⟩ | prec pf pg hf hg => rcases hf with ⟨cf, rfl⟩; rcases hg with ⟨cg, rfl⟩ exact ⟨prec cf cg, rfl⟩ | rfind pf hf => rcases hf with ⟨cf, rfl⟩ refine ⟨comp (rfind' cf) (pair Code.id zero), ?_⟩ simp [eval, Seq.seq, pure, PFun.pure, Part.map_id'] · rintro ⟨c, rfl⟩ induction c with | zero => exact Nat.Partrec.zero | succ => exact Nat.Partrec.succ | left => exact Nat.Partrec.left | right => exact Nat.Partrec.right | pair cf cg pf pg => exact pf.pair pg | comp cf cg pf pg => exact pf.comp pg | prec cf cg pf pg => exact pf.prec pg | rfind' cf pf => exact pf.rfind' -- Porting note: `>>`s in `evaln` are now `>>=` because `>>`s are not elaborated well in Lean4. /-- A modified evaluation for the code which returns an `Option ℕ` instead of a `Part ℕ`. To avoid undecidability, `evaln` takes a parameter `k` and fails if it encounters a number ≥ k in the course of its execution. Other than this, the semantics are the same as in `Nat.Partrec.Code.eval`. -/ def evaln : ℕ → Code → ℕ → Option ℕ | 0, _ => fun _ => Option.none | k + 1, zero => fun n => do guard (n ≤ k) return 0 | k + 1, succ => fun n => do guard (n ≤ k) return (Nat.succ n) | k + 1, left => fun n => do guard (n ≤ k) return n.unpair.1 | k + 1, right => fun n => do guard (n ≤ k) pure n.unpair.2 | k + 1, pair cf cg => fun n => do guard (n ≤ k) Nat.pair <$> evaln (k + 1) cf n <*> evaln (k + 1) cg n | k + 1, comp cf cg => fun n => do guard (n ≤ k) let x ← evaln (k + 1) cg n evaln (k + 1) cf x | k + 1, prec cf cg => fun n => do guard (n ≤ k) n.unpaired fun a n => n.casesOn (evaln (k + 1) cf a) fun y => do let i ← evaln k (prec cf cg) (Nat.pair a y) evaln (k + 1) cg (Nat.pair a (Nat.pair y i)) | k + 1, rfind' cf => fun n => do guard (n ≤ k) n.unpaired fun a m => do let x ← evaln (k + 1) cf (Nat.pair a m) if x = 0 then pure m else evaln k (rfind' cf) (Nat.pair a (m + 1)) theorem evaln_bound : ∀ {k c n x}, x ∈ evaln k c n → n < k | 0, c, n, x, h => by simp [evaln] at h | k + 1, c, n, x, h => by suffices ∀ {o : Option ℕ}, x ∈ do { guard (n ≤ k); o } → n < k + 1 by cases c <;> rw [evaln] at h <;> exact this h simpa [Option.bind_eq_some] using Nat.lt_succ_of_le theorem evaln_mono : ∀ {k₁ k₂ c n x}, k₁ ≤ k₂ → x ∈ evaln k₁ c n → x ∈ evaln k₂ c n | 0, k₂, c, n, x, _, h => by simp [evaln] at h | k + 1, k₂ + 1, c, n, x, hl, h => by have hl' := Nat.le_of_succ_le_succ hl have : ∀ {k k₂ n x : ℕ} {o₁ o₂ : Option ℕ}, k ≤ k₂ → (x ∈ o₁ → x ∈ o₂) → x ∈ do { guard (n ≤ k); o₁ } → x ∈ do { guard (n ≤ k₂); o₂ } := by simp only [Option.mem_def, bind, Option.bind_eq_some, Option.guard_eq_some', exists_and_left, exists_const, and_imp] introv h h₁ h₂ h₃ exact ⟨le_trans h₂ h, h₁ h₃⟩ simp? at h ⊢ says simp only [Option.mem_def] at h ⊢ induction' c with cf cg hf hg cf cg hf hg cf cg hf hg cf hf generalizing x n <;> rw [evaln] at h ⊢ <;> refine this hl' (fun h => ?_) h iterate 4 exact h · -- pair cf cg simp? [Seq.seq, Option.bind_eq_some] at h ⊢ says simp only [Seq.seq, Option.map_eq_map, Option.mem_def, Option.bind_eq_some, Option.map_eq_some', exists_exists_and_eq_and] at h ⊢ exact h.imp fun a => And.imp (hf _ _) <| Exists.imp fun b => And.imp_left (hg _ _) · -- comp cf cg simp? [Bind.bind, Option.bind_eq_some] at h ⊢ says simp only [bind, Option.mem_def, Option.bind_eq_some] at h ⊢ exact h.imp fun a => And.imp (hg _ _) (hf _ _) · -- prec cf cg revert h simp only [unpaired, bind, Option.mem_def] induction n.unpair.2 <;> simp [Option.bind_eq_some] · apply hf · exact fun y h₁ h₂ => ⟨y, evaln_mono hl' h₁, hg _ _ h₂⟩ · -- rfind' cf simp? [Bind.bind, Option.bind_eq_some] at h ⊢ says simp only [unpaired, bind, pair_unpair, Option.pure_def, Option.mem_def, Option.bind_eq_some] at h ⊢ refine h.imp fun x => And.imp (hf _ _) ?_ by_cases x0 : x = 0 <;> simp [x0] exact evaln_mono hl' theorem evaln_sound : ∀ {k c n x}, x ∈ evaln k c n → x ∈ eval c n | 0, _, n, x, h => by simp [evaln] at h | k + 1, c, n, x, h => by induction' c with cf cg hf hg cf cg hf hg cf cg hf hg cf hf generalizing x n <;> simp [eval, evaln, Option.bind_eq_some, Seq.seq] at h ⊢ <;> cases' h with _ h iterate 4 simpa [pure, PFun.pure, eq_comm] using h · -- pair cf cg rcases h with ⟨y, ef, z, eg, rfl⟩ exact ⟨_, hf _ _ ef, _, hg _ _ eg, rfl⟩ · --comp hf hg rcases h with ⟨y, eg, ef⟩ exact ⟨_, hg _ _ eg, hf _ _ ef⟩ · -- prec cf cg revert h induction' n.unpair.2 with m IH generalizing x <;> simp [Option.bind_eq_some] · apply hf · refine fun y h₁ h₂ => ⟨y, IH _ ?_, ?_⟩ · have := evaln_mono k.le_succ h₁ simp [evaln, Option.bind_eq_some] at this exact this.2 · exact hg _ _ h₂ · -- rfind' cf rcases h with ⟨m, h₁, h₂⟩ by_cases m0 : m = 0 <;> simp [m0] at h₂ · exact ⟨0, ⟨by simpa [m0] using hf _ _ h₁, fun {m} => (Nat.not_lt_zero _).elim⟩, by simp [h₂]⟩ · have := evaln_sound h₂ simp [eval] at this rcases this with ⟨y, ⟨hy₁, hy₂⟩, rfl⟩ refine ⟨y + 1, ⟨by simpa [add_comm, add_left_comm] using hy₁, fun {i} im => ?_⟩, by simp [add_comm, add_left_comm]⟩ cases' i with i · exact ⟨m, by simpa using hf _ _ h₁, m0⟩ · rcases hy₂ (Nat.lt_of_succ_lt_succ im) with ⟨z, hz, z0⟩ exact ⟨z, by simpa [add_comm, add_left_comm] using hz, z0⟩ theorem evaln_complete {c n x} : x ∈ eval c n ↔ ∃ k, x ∈ evaln k c n := by refine ⟨fun h => ?_, fun ⟨k, h⟩ => evaln_sound h⟩ rsuffices ⟨k, h⟩ : ∃ k, x ∈ evaln (k + 1) c n · exact ⟨k + 1, h⟩ induction c generalizing n x with simp [eval, evaln, pure, PFun.pure, Seq.seq, Option.bind_eq_some] at h ⊢ | pair cf cg hf hg => rcases h with ⟨x, hx, y, hy, rfl⟩ rcases hf hx with ⟨k₁, hk₁⟩; rcases hg hy with ⟨k₂, hk₂⟩ refine ⟨max k₁ k₂, ?_⟩ refine ⟨le_max_of_le_left <| Nat.le_of_lt_succ <| evaln_bound hk₁, _, evaln_mono (Nat.succ_le_succ <| le_max_left _ _) hk₁, _, evaln_mono (Nat.succ_le_succ <| le_max_right _ _) hk₂, rfl⟩ | comp cf cg hf hg => rcases h with ⟨y, hy, hx⟩ rcases hg hy with ⟨k₁, hk₁⟩; rcases hf hx with ⟨k₂, hk₂⟩ refine ⟨max k₁ k₂, ?_⟩ exact ⟨le_max_of_le_left <| Nat.le_of_lt_succ <| evaln_bound hk₁, _, evaln_mono (Nat.succ_le_succ <| le_max_left _ _) hk₁, evaln_mono (Nat.succ_le_succ <| le_max_right _ _) hk₂⟩ | prec cf cg hf hg => revert h generalize n.unpair.1 = n₁; generalize n.unpair.2 = n₂ induction' n₂ with m IH generalizing x n <;> simp [Option.bind_eq_some] · intro h rcases hf h with ⟨k, hk⟩ exact ⟨_, le_max_left _ _, evaln_mono (Nat.succ_le_succ <| le_max_right _ _) hk⟩ · intro y hy hx rcases IH hy with ⟨k₁, nk₁, hk₁⟩ rcases hg hx with ⟨k₂, hk₂⟩ refine ⟨(max k₁ k₂).succ, Nat.le_succ_of_le <| le_max_of_le_left <| le_trans (le_max_left _ (Nat.pair n₁ m)) nk₁, y, evaln_mono (Nat.succ_le_succ <| le_max_left _ _) ?_, evaln_mono (Nat.succ_le_succ <| Nat.le_succ_of_le <| le_max_right _ _) hk₂⟩ simp only [evaln.eq_8, bind, unpaired, unpair_pair, Option.mem_def, Option.bind_eq_some, Option.guard_eq_some', exists_and_left, exists_const] exact ⟨le_trans (le_max_right _ _) nk₁, hk₁⟩ | rfind' cf hf => rcases h with ⟨y, ⟨hy₁, hy₂⟩, rfl⟩ suffices ∃ k, y + n.unpair.2 ∈ evaln (k + 1) (rfind' cf) (Nat.pair n.unpair.1 n.unpair.2) by simpa [evaln, Option.bind_eq_some] revert hy₁ hy₂ generalize n.unpair.2 = m intro hy₁ hy₂ induction' y with y IH generalizing m <;> simp [evaln, Option.bind_eq_some] · simp at hy₁ rcases hf hy₁ with ⟨k, hk⟩ exact ⟨_, Nat.le_of_lt_succ <| evaln_bound hk, _, hk, by simp⟩ · rcases hy₂ (Nat.succ_pos _) with ⟨a, ha, a0⟩ rcases hf ha with ⟨k₁, hk₁⟩ rcases IH m.succ (by simpa [Nat.succ_eq_add_one, add_comm, add_left_comm] using hy₁) fun {i} hi => by simpa [Nat.succ_eq_add_one, add_comm, add_left_comm] using hy₂ (Nat.succ_lt_succ hi) with ⟨k₂, hk₂⟩ use (max k₁ k₂).succ rw [zero_add] at hk₁ use Nat.le_succ_of_le <| le_max_of_le_left <| Nat.le_of_lt_succ <| evaln_bound hk₁ use a use evaln_mono (Nat.succ_le_succ <| Nat.le_succ_of_le <| le_max_left _ _) hk₁ simpa [Nat.succ_eq_add_one, a0, -max_eq_left, -max_eq_right, add_comm, add_left_comm] using evaln_mono (Nat.succ_le_succ <| le_max_right _ _) hk₂ | _ => exact ⟨⟨_, le_rfl⟩, h.symm⟩ section open Primrec private def lup (L : List (List (Option ℕ))) (p : ℕ × Code) (n : ℕ) := do let l ← L.get? (encode p) let o ← l.get? n o private theorem hlup : Primrec fun p : _ × (_ × _) × _ => lup p.1 p.2.1 p.2.2 := Primrec.option_bind (Primrec.list_get?.comp Primrec.fst (Primrec.encode.comp <| Primrec.fst.comp Primrec.snd)) (Primrec.option_bind (Primrec.list_get?.comp Primrec.snd <| Primrec.snd.comp <| Primrec.snd.comp Primrec.fst) Primrec.snd) private def G (L : List (List (Option ℕ))) : Option (List (Option ℕ)) := Option.some <| let a := ofNat (ℕ × Code) L.length let k := a.1 let c := a.2 (List.range k).map fun n => k.casesOn Option.none fun k' => Nat.Partrec.Code.recOn c (some 0) -- zero (some (Nat.succ n)) (some n.unpair.1) (some n.unpair.2) (fun cf cg _ _ => do let x ← lup L (k, cf) n let y ← lup L (k, cg) n some (Nat.pair x y)) (fun cf cg _ _ => do let x ← lup L (k, cg) n lup L (k, cf) x) (fun cf cg _ _ => let z := n.unpair.1 n.unpair.2.casesOn (lup L (k, cf) z) fun y => do let i ← lup L (k', c) (Nat.pair z y) lup L (k, cg) (Nat.pair z (Nat.pair y i))) (fun cf _ => let z := n.unpair.1 let m := n.unpair.2 do let x ← lup L (k, cf) (Nat.pair z m) x.casesOn (some m) fun _ => lup L (k', c) (Nat.pair z (m + 1))) private theorem hG : Primrec G := by have a := (Primrec.ofNat (ℕ × Code)).comp (Primrec.list_length (α := List (Option ℕ))) have k := Primrec.fst.comp a refine Primrec.option_some.comp (Primrec.list_map (Primrec.list_range.comp k) (?_ : Primrec _)) replace k := k.comp (Primrec.fst (β := ℕ)) have n := Primrec.snd (α := List (List (Option ℕ))) (β := ℕ) refine Primrec.nat_casesOn k (_root_.Primrec.const Option.none) (?_ : Primrec _) have k := k.comp (Primrec.fst (β := ℕ)) have n := n.comp (Primrec.fst (β := ℕ)) have k' := Primrec.snd (α := List (List (Option ℕ)) × ℕ) (β := ℕ) have c := Primrec.snd.comp (a.comp <| (Primrec.fst (β := ℕ)).comp (Primrec.fst (β := ℕ))) apply Nat.Partrec.Code.rec_prim c (_root_.Primrec.const (some 0)) (Primrec.option_some.comp (_root_.Primrec.succ.comp n)) (Primrec.option_some.comp (Primrec.fst.comp <| Primrec.unpair.comp n)) (Primrec.option_some.comp (Primrec.snd.comp <| Primrec.unpair.comp n)) · have L := (Primrec.fst.comp Primrec.fst).comp (Primrec.fst (α := (List (List (Option ℕ)) × ℕ) × ℕ) (β := Code × Code × Option ℕ × Option ℕ)) have k := k.comp (Primrec.fst (β := Code × Code × Option ℕ × Option ℕ)) have n := n.comp (Primrec.fst (β := Code × Code × Option ℕ × Option ℕ)) have cf := Primrec.fst.comp (Primrec.snd (α := (List (List (Option ℕ)) × ℕ) × ℕ) (β := Code × Code × Option ℕ × Option ℕ)) have cg := (Primrec.fst.comp Primrec.snd).comp (Primrec.snd (α := (List (List (Option ℕ)) × ℕ) × ℕ) (β := Code × Code × Option ℕ × Option ℕ)) refine Primrec.option_bind (hlup.comp <| L.pair <| (k.pair cf).pair n) ?_ unfold Primrec₂ conv => congr · ext p dsimp only [] erw [Option.bind_eq_bind, ← Option.map_eq_bind] refine Primrec.option_map ((hlup.comp <| L.pair <| (k.pair cg).pair n).comp Primrec.fst) ?_ unfold Primrec₂ exact Primrec₂.natPair.comp (Primrec.snd.comp Primrec.fst) Primrec.snd · have L := (Primrec.fst.comp Primrec.fst).comp (Primrec.fst (α := (List (List (Option ℕ)) × ℕ) × ℕ) (β := Code × Code × Option ℕ × Option ℕ)) have k := k.comp (Primrec.fst (β := Code × Code × Option ℕ × Option ℕ)) have n := n.comp (Primrec.fst (β := Code × Code × Option ℕ × Option ℕ)) have cf := Primrec.fst.comp (Primrec.snd (α := (List (List (Option ℕ)) × ℕ) × ℕ) (β := Code × Code × Option ℕ × Option ℕ)) have cg := (Primrec.fst.comp Primrec.snd).comp (Primrec.snd (α := (List (List (Option ℕ)) × ℕ) × ℕ) (β := Code × Code × Option ℕ × Option ℕ)) refine Primrec.option_bind (hlup.comp <| L.pair <| (k.pair cg).pair n) ?_ unfold Primrec₂ have h := hlup.comp ((L.comp Primrec.fst).pair <| ((k.pair cf).comp Primrec.fst).pair Primrec.snd) exact h · have L := (Primrec.fst.comp Primrec.fst).comp (Primrec.fst (α := (List (List (Option ℕ)) × ℕ) × ℕ) (β := Code × Code × Option ℕ × Option ℕ)) have k := k.comp (Primrec.fst (β := Code × Code × Option ℕ × Option ℕ)) have n := n.comp (Primrec.fst (β := Code × Code × Option ℕ × Option ℕ)) have cf := Primrec.fst.comp (Primrec.snd (α := (List (List (Option ℕ)) × ℕ) × ℕ) (β := Code × Code × Option ℕ × Option ℕ)) have cg := (Primrec.fst.comp Primrec.snd).comp (Primrec.snd (α := (List (List (Option ℕ)) × ℕ) × ℕ) (β := Code × Code × Option ℕ × Option ℕ)) have z := Primrec.fst.comp (Primrec.unpair.comp n) refine Primrec.nat_casesOn (Primrec.snd.comp (Primrec.unpair.comp n)) (hlup.comp <| L.pair <| (k.pair cf).pair z) (?_ : Primrec _) have L := L.comp (Primrec.fst (β := ℕ)) have z := z.comp (Primrec.fst (β := ℕ)) have y := Primrec.snd (α := ((List (List (Option ℕ)) × ℕ) × ℕ) × Code × Code × Option ℕ × Option ℕ) (β := ℕ) have h₁ := hlup.comp <| L.pair <| (((k'.pair c).comp Primrec.fst).comp Primrec.fst).pair (Primrec₂.natPair.comp z y) refine Primrec.option_bind h₁ (?_ : Primrec _) have z := z.comp (Primrec.fst (β := ℕ)) have y := y.comp (Primrec.fst (β := ℕ)) have i := Primrec.snd (α := (((List (List (Option ℕ)) × ℕ) × ℕ) × Code × Code × Option ℕ × Option ℕ) × ℕ) (β := ℕ) have h₂ := hlup.comp ((L.comp Primrec.fst).pair <| ((k.pair cg).comp <| Primrec.fst.comp Primrec.fst).pair <| Primrec₂.natPair.comp z <| Primrec₂.natPair.comp y i) exact h₂ · have L := (Primrec.fst.comp Primrec.fst).comp (Primrec.fst (α := (List (List (Option ℕ)) × ℕ) × ℕ) (β := Code × Option ℕ)) have k := k.comp (Primrec.fst (β := Code × Option ℕ)) have n := n.comp (Primrec.fst (β := Code × Option ℕ)) have cf := Primrec.fst.comp (Primrec.snd (α := (List (List (Option ℕ)) × ℕ) × ℕ) (β := Code × Option ℕ)) have z := Primrec.fst.comp (Primrec.unpair.comp n) have m := Primrec.snd.comp (Primrec.unpair.comp n) have h₁ := hlup.comp <| L.pair <| (k.pair cf).pair (Primrec₂.natPair.comp z m) refine Primrec.option_bind h₁ (?_ : Primrec _) have m := m.comp (Primrec.fst (β := ℕ)) refine Primrec.nat_casesOn Primrec.snd (Primrec.option_some.comp m) ?_ unfold Primrec₂ exact (hlup.comp ((L.comp Primrec.fst).pair <| ((k'.pair c).comp <| Primrec.fst.comp Primrec.fst).pair (Primrec₂.natPair.comp (z.comp Primrec.fst) (_root_.Primrec.succ.comp m)))).comp Primrec.fst private theorem evaln_map (k c n) : ((((List.range k)[n]?).map (evaln k c)).bind fun b => b) = evaln k c n := by by_cases kn : n < k · simp [List.getElem?_range kn] · rw [List.getElem?_len_le] · cases e : evaln k c n · rfl exact kn.elim (evaln_bound e) simpa using kn /-- The `Nat.Partrec.Code.evaln` function is primitive recursive. -/ theorem evaln_prim : Primrec fun a : (ℕ × Code) × ℕ => evaln a.1.1 a.1.2 a.2 := have : Primrec₂ fun (_ : Unit) (n : ℕ) => let a := ofNat (ℕ × Code) n (List.range a.1).map (evaln a.1 a.2) := Primrec.nat_strong_rec _ (hG.comp Primrec.snd).to₂ fun _ p => by simp only [G, prod_ofNat_val, ofNat_nat, List.length_map, List.length_range, Nat.pair_unpair, Option.some_inj] refine List.map_congr_left fun n => ?_ have : List.range p = List.range (Nat.pair p.unpair.1 (encode (ofNat Code p.unpair.2))) := by simp rw [this] generalize p.unpair.1 = k generalize ofNat Code p.unpair.2 = c intro nk cases' k with k' · simp [evaln] let k := k' + 1 simp only [show k'.succ = k from rfl] simp? [Nat.lt_succ_iff] at nk says simp only [List.mem_range, Nat.lt_succ_iff] at nk have hg : ∀ {k' c' n}, Nat.pair k' (encode c') < Nat.pair k (encode c) → lup ((List.range (Nat.pair k (encode c))).map fun n => (List.range n.unpair.1).map (evaln n.unpair.1 (ofNat Code n.unpair.2))) (k', c') n = evaln k' c' n := by intro k₁ c₁ n₁ hl simp [lup, List.getElem?_range hl, evaln_map, Bind.bind] cases' c with cf cg cf cg cf cg cf <;> simp [evaln, nk, Bind.bind, Functor.map, Seq.seq, pure] · cases' encode_lt_pair cf cg with lf lg rw [hg (Nat.pair_lt_pair_right _ lf), hg (Nat.pair_lt_pair_right _ lg)] cases evaln k cf n · rfl cases evaln k cg n <;> rfl · cases' encode_lt_comp cf cg with lf lg rw [hg (Nat.pair_lt_pair_right _ lg)] cases evaln k cg n · rfl simp [hg (Nat.pair_lt_pair_right _ lf)] · cases' encode_lt_prec cf cg with lf lg rw [hg (Nat.pair_lt_pair_right _ lf)] cases n.unpair.2 · rfl simp only [decode_eq_ofNat, Option.some.injEq] rw [hg (Nat.pair_lt_pair_left _ k'.lt_succ_self)] cases evaln k' _ _ · rfl simp [hg (Nat.pair_lt_pair_right _ lg)] · have lf := encode_lt_rfind' cf rw [hg (Nat.pair_lt_pair_right _ lf)] cases' evaln k cf n with x · rfl simp only [decode_eq_ofNat, Option.some.injEq, Option.some_bind] cases x <;> simp [Nat.succ_ne_zero] rw [hg (Nat.pair_lt_pair_left _ k'.lt_succ_self)] (Primrec.option_bind (Primrec.list_get?.comp (this.comp (_root_.Primrec.const ()) (Primrec.encode_iff.2 Primrec.fst)) Primrec.snd) Primrec.snd.to₂).of_eq fun ⟨⟨k, c⟩, n⟩ => by simp [evaln_map] end section open Partrec Computable theorem eval_eq_rfindOpt (c n) : eval c n = Nat.rfindOpt fun k => evaln k c n := Part.ext fun x => by refine evaln_complete.trans (Nat.rfindOpt_mono ?_).symm intro a m n hl; apply evaln_mono hl theorem eval_part : Partrec₂ eval := (Partrec.rfindOpt (evaln_prim.to_comp.comp ((Computable.snd.pair (fst.comp fst)).pair (snd.comp fst))).to₂).of_eq fun a => by simp [eval_eq_rfindOpt] /-- Roger's fixed-point theorem: Any total, computable `f` has a fixed point: That is, under the interpretation given by `Nat.Partrec.Code.eval`, there is a code `c` such that `c` and `f c` have the same evaluation. -/ theorem fixed_point {f : Code → Code} (hf : Computable f) : ∃ c : Code, eval (f c) = eval c := let g (x y : ℕ) : Part ℕ := eval (ofNat Code x) x >>= fun b => eval (ofNat Code b) y have : Partrec₂ g := (eval_part.comp ((Computable.ofNat _).comp fst) fst).bind (eval_part.comp ((Computable.ofNat _).comp snd) (snd.comp fst)).to₂ let ⟨cg, eg⟩ := exists_code.1 this have eg' : ∀ a n, eval cg (Nat.pair a n) = Part.map encode (g a n) := by simp [eg] let F (x : ℕ) : Code := f (curry cg x) have : Computable F := hf.comp (curry_prim.comp (_root_.Primrec.const cg) _root_.Primrec.id).to_comp let ⟨cF, eF⟩ := exists_code.1 this have eF' : eval cF (encode cF) = Part.some (encode (F (encode cF))) := by simp [eF] ⟨curry cg (encode cF), funext fun n => show eval (f (curry cg (encode cF))) n = eval (curry cg (encode cF)) n by simp [g, eg', eF', Part.map_id']⟩ theorem fixed_point₂ {f : Code → ℕ →. ℕ} (hf : Partrec₂ f) : ∃ c : Code, eval c = f c := let ⟨cf, ef⟩ := exists_code.1 hf (fixed_point (curry_prim.comp (_root_.Primrec.const cf) Primrec.encode).to_comp).imp fun c e => funext fun n => by simp [e.symm, ef, Part.map_id'] end end Nat.Partrec.Code
Computability\Primrec.lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Algebra.Order.Ring.Nat import Mathlib.Data.List.GetD import Mathlib.Logic.Equiv.List import Mathlib.Logic.Function.Iterate /-! # The primitive recursive functions The primitive recursive functions are the least collection of functions `ℕ → ℕ` which are closed under projections (using the `pair` pairing function), composition, zero, successor, and primitive recursion (i.e. `Nat.rec` where the motive is `C n := ℕ`). We can extend this definition to a large class of basic types by using canonical encodings of types as natural numbers (Gödel numbering), which we implement through the type class `Encodable`. (More precisely, we need that the composition of encode with decode yields a primitive recursive function, so we have the `Primcodable` type class for this.) ## References * [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019] -/ open Mathlib (Vector) open Denumerable Encodable Function namespace Nat -- Porting note: elim is no longer required because lean 4 is better -- at inferring motive types (I think this is the reason) -- and worst case, we can always explicitly write (motive := fun _ => C) -- without having to then add all the other underscores -- /-- The non-dependent recursor on naturals. -/ -- def elim {C : Sort*} : C → (ℕ → C → C) → ℕ → C := -- @Nat.rec fun _ => C -- example {C : Sort*} (base : C) (succ : ℕ → C → C) (a : ℕ) : -- a.elim base succ = a.rec base succ := rfl -- Porting note: cases is no longer required because lean 4 is better -- at inferring motive types (I think this is the reason) -- /-- Cases on whether the input is 0 or a successor. -/ -- def cases {C : Sort*} (a : C) (f : ℕ → C) : ℕ → C := -- Nat.elim a fun n _ => f n -- example {C : Sort*} (a : C) (f : ℕ → C) (n : ℕ) : -- n.cases a f = n.casesOn a f := rfl /-- Calls the given function on a pair of entries `n`, encoded via the pairing function. -/ @[simp, reducible] def unpaired {α} (f : ℕ → ℕ → α) (n : ℕ) : α := f n.unpair.1 n.unpair.2 /-- The primitive recursive functions `ℕ → ℕ`. -/ protected inductive Primrec : (ℕ → ℕ) → Prop | zero : Nat.Primrec fun _ => 0 | protected succ : Nat.Primrec succ | left : Nat.Primrec fun n => n.unpair.1 | right : Nat.Primrec fun n => n.unpair.2 | pair {f g} : Nat.Primrec f → Nat.Primrec g → Nat.Primrec fun n => pair (f n) (g n) | comp {f g} : Nat.Primrec f → Nat.Primrec g → Nat.Primrec fun n => f (g n) | prec {f g} : Nat.Primrec f → Nat.Primrec g → Nat.Primrec (unpaired fun z n => n.rec (f z) fun y IH => g <| pair z <| pair y IH) namespace Primrec theorem of_eq {f g : ℕ → ℕ} (hf : Nat.Primrec f) (H : ∀ n, f n = g n) : Nat.Primrec g := (funext H : f = g) ▸ hf theorem const : ∀ n : ℕ, Nat.Primrec fun _ => n | 0 => zero | n + 1 => Primrec.succ.comp (const n) protected theorem id : Nat.Primrec id := (left.pair right).of_eq fun n => by simp theorem prec1 {f} (m : ℕ) (hf : Nat.Primrec f) : Nat.Primrec fun n => n.rec m fun y IH => f <| Nat.pair y IH := ((prec (const m) (hf.comp right)).comp (zero.pair Primrec.id)).of_eq fun n => by simp theorem casesOn1 {f} (m : ℕ) (hf : Nat.Primrec f) : Nat.Primrec (Nat.casesOn · m f) := (prec1 m (hf.comp left)).of_eq <| by simp -- Porting note: `Nat.Primrec.casesOn` is already declared as a recursor. theorem casesOn' {f g} (hf : Nat.Primrec f) (hg : Nat.Primrec g) : Nat.Primrec (unpaired fun z n => n.casesOn (f z) fun y => g <| Nat.pair z y) := (prec hf (hg.comp (pair left (left.comp right)))).of_eq fun n => by simp protected theorem swap : Nat.Primrec (unpaired (swap Nat.pair)) := (pair right left).of_eq fun n => by simp theorem swap' {f} (hf : Nat.Primrec (unpaired f)) : Nat.Primrec (unpaired (swap f)) := (hf.comp .swap).of_eq fun n => by simp theorem pred : Nat.Primrec pred := (casesOn1 0 Primrec.id).of_eq fun n => by cases n <;> simp [*] theorem add : Nat.Primrec (unpaired (· + ·)) := (prec .id ((Primrec.succ.comp right).comp right)).of_eq fun p => by simp; induction p.unpair.2 <;> simp [*, Nat.add_assoc] theorem sub : Nat.Primrec (unpaired (· - ·)) := (prec .id ((pred.comp right).comp right)).of_eq fun p => by simp; induction p.unpair.2 <;> simp [*, Nat.sub_add_eq] theorem mul : Nat.Primrec (unpaired (· * ·)) := (prec zero (add.comp (pair left (right.comp right)))).of_eq fun p => by simp; induction p.unpair.2 <;> simp [*, mul_succ, add_comm _ (unpair p).fst] theorem pow : Nat.Primrec (unpaired (· ^ ·)) := (prec (const 1) (mul.comp (pair (right.comp right) left))).of_eq fun p => by simp; induction p.unpair.2 <;> simp [*, Nat.pow_succ] end Primrec end Nat /-- A `Primcodable` type is an `Encodable` type for which the encode/decode functions are primitive recursive. -/ class Primcodable (α : Type*) extends Encodable α where -- Porting note: was `prim [] `. -- This means that `prim` does not take the type explicitly in Lean 4 prim : Nat.Primrec fun n => Encodable.encode (decode n) namespace Primcodable open Nat.Primrec instance (priority := 10) ofDenumerable (α) [Denumerable α] : Primcodable α := ⟨Nat.Primrec.succ.of_eq <| by simp⟩ /-- Builds a `Primcodable` instance from an equivalence to a `Primcodable` type. -/ def ofEquiv (α) {β} [Primcodable α] (e : β ≃ α) : Primcodable β := { __ := Encodable.ofEquiv α e prim := (@Primcodable.prim α _).of_eq fun n => by rw [decode_ofEquiv] cases (@decode α _ n) <;> simp [encode_ofEquiv] } instance empty : Primcodable Empty := ⟨zero⟩ instance unit : Primcodable PUnit := ⟨(casesOn1 1 zero).of_eq fun n => by cases n <;> simp⟩ instance option {α : Type*} [h : Primcodable α] : Primcodable (Option α) := ⟨(casesOn1 1 ((casesOn1 0 (.comp .succ .succ)).comp (@Primcodable.prim α _))).of_eq fun n => by cases n with | zero => rfl | succ n => rw [decode_option_succ] cases H : @decode α _ n <;> simp [H]⟩ instance bool : Primcodable Bool := ⟨(casesOn1 1 (casesOn1 2 zero)).of_eq fun n => match n with | 0 => rfl | 1 => rfl | (n + 2) => by rw [decode_ge_two] <;> simp⟩ end Primcodable /-- `Primrec f` means `f` is primitive recursive (after encoding its input and output as natural numbers). -/ def Primrec {α β} [Primcodable α] [Primcodable β] (f : α → β) : Prop := Nat.Primrec fun n => encode ((@decode α _ n).map f) namespace Primrec variable {α : Type*} {β : Type*} {σ : Type*} variable [Primcodable α] [Primcodable β] [Primcodable σ] open Nat.Primrec protected theorem encode : Primrec (@encode α _) := (@Primcodable.prim α _).of_eq fun n => by cases @decode α _ n <;> rfl protected theorem decode : Primrec (@decode α _) := Nat.Primrec.succ.comp (@Primcodable.prim α _) theorem dom_denumerable {α β} [Denumerable α] [Primcodable β] {f : α → β} : Primrec f ↔ Nat.Primrec fun n => encode (f (ofNat α n)) := ⟨fun h => (pred.comp h).of_eq fun n => by simp, fun h => (Nat.Primrec.succ.comp h).of_eq fun n => by simp⟩ theorem nat_iff {f : ℕ → ℕ} : Primrec f ↔ Nat.Primrec f := dom_denumerable theorem encdec : Primrec fun n => encode (@decode α _ n) := nat_iff.2 Primcodable.prim theorem option_some : Primrec (@some α) := ((casesOn1 0 (Nat.Primrec.succ.comp .succ)).comp (@Primcodable.prim α _)).of_eq fun n => by cases @decode α _ n <;> simp theorem of_eq {f g : α → σ} (hf : Primrec f) (H : ∀ n, f n = g n) : Primrec g := (funext H : f = g) ▸ hf theorem const (x : σ) : Primrec fun _ : α => x := ((casesOn1 0 (.const (encode x).succ)).comp (@Primcodable.prim α _)).of_eq fun n => by cases @decode α _ n <;> rfl protected theorem id : Primrec (@id α) := (@Primcodable.prim α).of_eq <| by simp theorem comp {f : β → σ} {g : α → β} (hf : Primrec f) (hg : Primrec g) : Primrec fun a => f (g a) := ((casesOn1 0 (.comp hf (pred.comp hg))).comp (@Primcodable.prim α _)).of_eq fun n => by cases @decode α _ n <;> simp [encodek] theorem succ : Primrec Nat.succ := nat_iff.2 Nat.Primrec.succ theorem pred : Primrec Nat.pred := nat_iff.2 Nat.Primrec.pred theorem encode_iff {f : α → σ} : (Primrec fun a => encode (f a)) ↔ Primrec f := ⟨fun h => Nat.Primrec.of_eq h fun n => by cases @decode α _ n <;> rfl, Primrec.encode.comp⟩ theorem ofNat_iff {α β} [Denumerable α] [Primcodable β] {f : α → β} : Primrec f ↔ Primrec fun n => f (ofNat α n) := dom_denumerable.trans <| nat_iff.symm.trans encode_iff protected theorem ofNat (α) [Denumerable α] : Primrec (ofNat α) := ofNat_iff.1 Primrec.id theorem option_some_iff {f : α → σ} : (Primrec fun a => some (f a)) ↔ Primrec f := ⟨fun h => encode_iff.1 <| pred.comp <| encode_iff.2 h, option_some.comp⟩ theorem of_equiv {β} {e : β ≃ α} : haveI := Primcodable.ofEquiv α e Primrec e := letI : Primcodable β := Primcodable.ofEquiv α e encode_iff.1 Primrec.encode theorem of_equiv_symm {β} {e : β ≃ α} : haveI := Primcodable.ofEquiv α e Primrec e.symm := letI := Primcodable.ofEquiv α e encode_iff.1 (show Primrec fun a => encode (e (e.symm a)) by simp [Primrec.encode]) theorem of_equiv_iff {β} (e : β ≃ α) {f : σ → β} : haveI := Primcodable.ofEquiv α e (Primrec fun a => e (f a)) ↔ Primrec f := letI := Primcodable.ofEquiv α e ⟨fun h => (of_equiv_symm.comp h).of_eq fun a => by simp, of_equiv.comp⟩ theorem of_equiv_symm_iff {β} (e : β ≃ α) {f : σ → α} : haveI := Primcodable.ofEquiv α e (Primrec fun a => e.symm (f a)) ↔ Primrec f := letI := Primcodable.ofEquiv α e ⟨fun h => (of_equiv.comp h).of_eq fun a => by simp, of_equiv_symm.comp⟩ end Primrec namespace Primcodable open Nat.Primrec instance prod {α β} [Primcodable α] [Primcodable β] : Primcodable (α × β) := ⟨((casesOn' zero ((casesOn' zero .succ).comp (pair right ((@Primcodable.prim β).comp left)))).comp (pair right ((@Primcodable.prim α).comp left))).of_eq fun n => by simp only [Nat.unpaired, Nat.unpair_pair, decode_prod_val] cases @decode α _ n.unpair.1; · simp cases @decode β _ n.unpair.2 <;> simp⟩ end Primcodable namespace Primrec variable {α : Type*} {σ : Type*} [Primcodable α] [Primcodable σ] open Nat.Primrec theorem fst {α β} [Primcodable α] [Primcodable β] : Primrec (@Prod.fst α β) := ((casesOn' zero ((casesOn' zero (Nat.Primrec.succ.comp left)).comp (pair right ((@Primcodable.prim β).comp left)))).comp (pair right ((@Primcodable.prim α).comp left))).of_eq fun n => by simp only [Nat.unpaired, Nat.unpair_pair, decode_prod_val] cases @decode α _ n.unpair.1 <;> simp cases @decode β _ n.unpair.2 <;> simp theorem snd {α β} [Primcodable α] [Primcodable β] : Primrec (@Prod.snd α β) := ((casesOn' zero ((casesOn' zero (Nat.Primrec.succ.comp right)).comp (pair right ((@Primcodable.prim β).comp left)))).comp (pair right ((@Primcodable.prim α).comp left))).of_eq fun n => by simp only [Nat.unpaired, Nat.unpair_pair, decode_prod_val] cases @decode α _ n.unpair.1 <;> simp cases @decode β _ n.unpair.2 <;> simp theorem pair {α β γ} [Primcodable α] [Primcodable β] [Primcodable γ] {f : α → β} {g : α → γ} (hf : Primrec f) (hg : Primrec g) : Primrec fun a => (f a, g a) := ((casesOn1 0 (Nat.Primrec.succ.comp <| .pair (Nat.Primrec.pred.comp hf) (Nat.Primrec.pred.comp hg))).comp (@Primcodable.prim α _)).of_eq fun n => by cases @decode α _ n <;> simp [encodek] theorem unpair : Primrec Nat.unpair := (pair (nat_iff.2 .left) (nat_iff.2 .right)).of_eq fun n => by simp theorem list_get?₁ : ∀ l : List α, Primrec l.get? | [] => dom_denumerable.2 zero | a :: l => dom_denumerable.2 <| (casesOn1 (encode a).succ <| dom_denumerable.1 <| list_get?₁ l).of_eq fun n => by cases n <;> simp end Primrec /-- `Primrec₂ f` means `f` is a binary primitive recursive function. This is technically unnecessary since we can always curry all the arguments together, but there are enough natural two-arg functions that it is convenient to express this directly. -/ def Primrec₂ {α β σ} [Primcodable α] [Primcodable β] [Primcodable σ] (f : α → β → σ) := Primrec fun p : α × β => f p.1 p.2 /-- `PrimrecPred p` means `p : α → Prop` is a (decidable) primitive recursive predicate, which is to say that `decide ∘ p : α → Bool` is primitive recursive. -/ def PrimrecPred {α} [Primcodable α] (p : α → Prop) [DecidablePred p] := Primrec fun a => decide (p a) /-- `PrimrecRel p` means `p : α → β → Prop` is a (decidable) primitive recursive relation, which is to say that `decide ∘ p : α → β → Bool` is primitive recursive. -/ def PrimrecRel {α β} [Primcodable α] [Primcodable β] (s : α → β → Prop) [∀ a b, Decidable (s a b)] := Primrec₂ fun a b => decide (s a b) namespace Primrec₂ variable {α : Type*} {β : Type*} {σ : Type*} variable [Primcodable α] [Primcodable β] [Primcodable σ] theorem mk {f : α → β → σ} (hf : Primrec fun p : α × β => f p.1 p.2) : Primrec₂ f := hf theorem of_eq {f g : α → β → σ} (hg : Primrec₂ f) (H : ∀ a b, f a b = g a b) : Primrec₂ g := (by funext a b; apply H : f = g) ▸ hg theorem const (x : σ) : Primrec₂ fun (_ : α) (_ : β) => x := Primrec.const _ protected theorem pair : Primrec₂ (@Prod.mk α β) := .pair .fst .snd theorem left : Primrec₂ fun (a : α) (_ : β) => a := .fst theorem right : Primrec₂ fun (_ : α) (b : β) => b := .snd theorem natPair : Primrec₂ Nat.pair := by simp [Primrec₂, Primrec]; constructor theorem unpaired {f : ℕ → ℕ → α} : Primrec (Nat.unpaired f) ↔ Primrec₂ f := ⟨fun h => by simpa using h.comp natPair, fun h => h.comp Primrec.unpair⟩ theorem unpaired' {f : ℕ → ℕ → ℕ} : Nat.Primrec (Nat.unpaired f) ↔ Primrec₂ f := Primrec.nat_iff.symm.trans unpaired theorem encode_iff {f : α → β → σ} : (Primrec₂ fun a b => encode (f a b)) ↔ Primrec₂ f := Primrec.encode_iff theorem option_some_iff {f : α → β → σ} : (Primrec₂ fun a b => some (f a b)) ↔ Primrec₂ f := Primrec.option_some_iff theorem ofNat_iff {α β σ} [Denumerable α] [Denumerable β] [Primcodable σ] {f : α → β → σ} : Primrec₂ f ↔ Primrec₂ fun m n : ℕ => f (ofNat α m) (ofNat β n) := (Primrec.ofNat_iff.trans <| by simp).trans unpaired theorem uncurry {f : α → β → σ} : Primrec (Function.uncurry f) ↔ Primrec₂ f := by rw [show Function.uncurry f = fun p : α × β => f p.1 p.2 from funext fun ⟨a, b⟩ => rfl]; rfl theorem curry {f : α × β → σ} : Primrec₂ (Function.curry f) ↔ Primrec f := by rw [← uncurry, Function.uncurry_curry] end Primrec₂ section Comp variable {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} variable [Primcodable α] [Primcodable β] [Primcodable γ] [Primcodable δ] [Primcodable σ] theorem Primrec.comp₂ {f : γ → σ} {g : α → β → γ} (hf : Primrec f) (hg : Primrec₂ g) : Primrec₂ fun a b => f (g a b) := hf.comp hg theorem Primrec₂.comp {f : β → γ → σ} {g : α → β} {h : α → γ} (hf : Primrec₂ f) (hg : Primrec g) (hh : Primrec h) : Primrec fun a => f (g a) (h a) := Primrec.comp hf (hg.pair hh) theorem Primrec₂.comp₂ {f : γ → δ → σ} {g : α → β → γ} {h : α → β → δ} (hf : Primrec₂ f) (hg : Primrec₂ g) (hh : Primrec₂ h) : Primrec₂ fun a b => f (g a b) (h a b) := hf.comp hg hh theorem PrimrecPred.comp {p : β → Prop} [DecidablePred p] {f : α → β} : PrimrecPred p → Primrec f → PrimrecPred fun a => p (f a) := Primrec.comp theorem PrimrecRel.comp {R : β → γ → Prop} [∀ a b, Decidable (R a b)] {f : α → β} {g : α → γ} : PrimrecRel R → Primrec f → Primrec g → PrimrecPred fun a => R (f a) (g a) := Primrec₂.comp theorem PrimrecRel.comp₂ {R : γ → δ → Prop} [∀ a b, Decidable (R a b)] {f : α → β → γ} {g : α → β → δ} : PrimrecRel R → Primrec₂ f → Primrec₂ g → PrimrecRel fun a b => R (f a b) (g a b) := PrimrecRel.comp end Comp theorem PrimrecPred.of_eq {α} [Primcodable α] {p q : α → Prop} [DecidablePred p] [DecidablePred q] (hp : PrimrecPred p) (H : ∀ a, p a ↔ q a) : PrimrecPred q := Primrec.of_eq hp fun a => Bool.decide_congr (H a) theorem PrimrecRel.of_eq {α β} [Primcodable α] [Primcodable β] {r s : α → β → Prop} [∀ a b, Decidable (r a b)] [∀ a b, Decidable (s a b)] (hr : PrimrecRel r) (H : ∀ a b, r a b ↔ s a b) : PrimrecRel s := Primrec₂.of_eq hr fun a b => Bool.decide_congr (H a b) namespace Primrec₂ variable {α : Type*} {β : Type*} {σ : Type*} variable [Primcodable α] [Primcodable β] [Primcodable σ] open Nat.Primrec theorem swap {f : α → β → σ} (h : Primrec₂ f) : Primrec₂ (swap f) := h.comp₂ Primrec₂.right Primrec₂.left theorem nat_iff {f : α → β → σ} : Primrec₂ f ↔ Nat.Primrec (.unpaired fun m n => encode <| (@decode α _ m).bind fun a => (@decode β _ n).map (f a)) := by have : ∀ (a : Option α) (b : Option β), Option.map (fun p : α × β => f p.1 p.2) (Option.bind a fun a : α => Option.map (Prod.mk a) b) = Option.bind a fun a => Option.map (f a) b := fun a b => by cases a <;> cases b <;> rfl simp [Primrec₂, Primrec, this] theorem nat_iff' {f : α → β → σ} : Primrec₂ f ↔ Primrec₂ fun m n : ℕ => (@decode α _ m).bind fun a => Option.map (f a) (@decode β _ n) := nat_iff.trans <| unpaired'.trans encode_iff end Primrec₂ namespace Primrec variable {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} variable [Primcodable α] [Primcodable β] [Primcodable γ] [Primcodable δ] [Primcodable σ] theorem to₂ {f : α × β → σ} (hf : Primrec f) : Primrec₂ fun a b => f (a, b) := hf.of_eq fun _ => rfl theorem nat_rec {f : α → β} {g : α → ℕ × β → β} (hf : Primrec f) (hg : Primrec₂ g) : Primrec₂ fun a (n : ℕ) => n.rec (motive := fun _ => β) (f a) fun n IH => g a (n, IH) := Primrec₂.nat_iff.2 <| ((Nat.Primrec.casesOn' .zero <| (Nat.Primrec.prec hf <| .comp hg <| Nat.Primrec.left.pair <| (Nat.Primrec.left.comp .right).pair <| Nat.Primrec.pred.comp <| Nat.Primrec.right.comp .right).comp <| Nat.Primrec.right.pair <| Nat.Primrec.right.comp Nat.Primrec.left).comp <| Nat.Primrec.id.pair <| (@Primcodable.prim α).comp Nat.Primrec.left).of_eq fun n => by simp only [Nat.unpaired, id_eq, Nat.unpair_pair, decode_prod_val, decode_nat, Option.some_bind, Option.map_map, Option.map_some'] cases' @decode α _ n.unpair.1 with a; · rfl simp only [Nat.pred_eq_sub_one, encode_some, Nat.succ_eq_add_one, encodek, Option.map_some', Option.some_bind, Option.map_map] induction' n.unpair.2 with m <;> simp [encodek] simp [*, encodek] theorem nat_rec' {f : α → ℕ} {g : α → β} {h : α → ℕ × β → β} (hf : Primrec f) (hg : Primrec g) (hh : Primrec₂ h) : Primrec fun a => (f a).rec (motive := fun _ => β) (g a) fun n IH => h a (n, IH) := (nat_rec hg hh).comp .id hf theorem nat_rec₁ {f : ℕ → α → α} (a : α) (hf : Primrec₂ f) : Primrec (Nat.rec a f) := nat_rec' .id (const a) <| comp₂ hf Primrec₂.right theorem nat_casesOn' {f : α → β} {g : α → ℕ → β} (hf : Primrec f) (hg : Primrec₂ g) : Primrec₂ fun a (n : ℕ) => (n.casesOn (f a) (g a) : β) := nat_rec hf <| hg.comp₂ Primrec₂.left <| comp₂ fst Primrec₂.right theorem nat_casesOn {f : α → ℕ} {g : α → β} {h : α → ℕ → β} (hf : Primrec f) (hg : Primrec g) (hh : Primrec₂ h) : Primrec fun a => ((f a).casesOn (g a) (h a) : β) := (nat_casesOn' hg hh).comp .id hf theorem nat_casesOn₁ {f : ℕ → α} (a : α) (hf : Primrec f) : Primrec (fun (n : ℕ) => (n.casesOn a f : α)) := nat_casesOn .id (const a) (comp₂ hf .right) theorem nat_iterate {f : α → ℕ} {g : α → β} {h : α → β → β} (hf : Primrec f) (hg : Primrec g) (hh : Primrec₂ h) : Primrec fun a => (h a)^[f a] (g a) := (nat_rec' hf hg (hh.comp₂ Primrec₂.left <| snd.comp₂ Primrec₂.right)).of_eq fun a => by induction f a <;> simp [*, -Function.iterate_succ, Function.iterate_succ'] theorem option_casesOn {o : α → Option β} {f : α → σ} {g : α → β → σ} (ho : Primrec o) (hf : Primrec f) (hg : Primrec₂ g) : @Primrec _ σ _ _ fun a => Option.casesOn (o a) (f a) (g a) := encode_iff.1 <| (nat_casesOn (encode_iff.2 ho) (encode_iff.2 hf) <| pred.comp₂ <| Primrec₂.encode_iff.2 <| (Primrec₂.nat_iff'.1 hg).comp₂ ((@Primrec.encode α _).comp fst).to₂ Primrec₂.right).of_eq fun a => by cases' o a with b <;> simp [encodek] theorem option_bind {f : α → Option β} {g : α → β → Option σ} (hf : Primrec f) (hg : Primrec₂ g) : Primrec fun a => (f a).bind (g a) := (option_casesOn hf (const none) hg).of_eq fun a => by cases f a <;> rfl theorem option_bind₁ {f : α → Option σ} (hf : Primrec f) : Primrec fun o => Option.bind o f := option_bind .id (hf.comp snd).to₂ theorem option_map {f : α → Option β} {g : α → β → σ} (hf : Primrec f) (hg : Primrec₂ g) : Primrec fun a => (f a).map (g a) := (option_bind hf (option_some.comp₂ hg)).of_eq fun x => by cases f x <;> rfl theorem option_map₁ {f : α → σ} (hf : Primrec f) : Primrec (Option.map f) := option_map .id (hf.comp snd).to₂ theorem option_iget [Inhabited α] : Primrec (@Option.iget α _) := (option_casesOn .id (const <| @default α _) .right).of_eq fun o => by cases o <;> rfl theorem option_isSome : Primrec (@Option.isSome α) := (option_casesOn .id (const false) (const true).to₂).of_eq fun o => by cases o <;> rfl theorem option_getD : Primrec₂ (@Option.getD α) := Primrec.of_eq (option_casesOn Primrec₂.left Primrec₂.right .right) fun ⟨o, a⟩ => by cases o <;> rfl theorem bind_decode_iff {f : α → β → Option σ} : (Primrec₂ fun a n => (@decode β _ n).bind (f a)) ↔ Primrec₂ f := ⟨fun h => by simpa [encodek] using h.comp fst ((@Primrec.encode β _).comp snd), fun h => option_bind (Primrec.decode.comp snd) <| h.comp (fst.comp fst) snd⟩ theorem map_decode_iff {f : α → β → σ} : (Primrec₂ fun a n => (@decode β _ n).map (f a)) ↔ Primrec₂ f := by simp only [Option.map_eq_bind] exact bind_decode_iff.trans Primrec₂.option_some_iff theorem nat_add : Primrec₂ ((· + ·) : ℕ → ℕ → ℕ) := Primrec₂.unpaired'.1 Nat.Primrec.add theorem nat_sub : Primrec₂ ((· - ·) : ℕ → ℕ → ℕ) := Primrec₂.unpaired'.1 Nat.Primrec.sub theorem nat_mul : Primrec₂ ((· * ·) : ℕ → ℕ → ℕ) := Primrec₂.unpaired'.1 Nat.Primrec.mul theorem cond {c : α → Bool} {f : α → σ} {g : α → σ} (hc : Primrec c) (hf : Primrec f) (hg : Primrec g) : Primrec fun a => bif (c a) then (f a) else (g a) := (nat_casesOn (encode_iff.2 hc) hg (hf.comp fst).to₂).of_eq fun a => by cases c a <;> rfl theorem ite {c : α → Prop} [DecidablePred c] {f : α → σ} {g : α → σ} (hc : PrimrecPred c) (hf : Primrec f) (hg : Primrec g) : Primrec fun a => if c a then f a else g a := by simpa [Bool.cond_decide] using cond hc hf hg theorem nat_le : PrimrecRel ((· ≤ ·) : ℕ → ℕ → Prop) := (nat_casesOn nat_sub (const true) (const false).to₂).of_eq fun p => by dsimp [swap] cases' e : p.1 - p.2 with n · simp [tsub_eq_zero_iff_le.1 e] · simp [not_le.2 (Nat.lt_of_sub_eq_succ e)] theorem nat_min : Primrec₂ (@min ℕ _) := ite nat_le fst snd theorem nat_max : Primrec₂ (@max ℕ _) := ite (nat_le.comp fst snd) snd fst theorem dom_bool (f : Bool → α) : Primrec f := (cond .id (const (f true)) (const (f false))).of_eq fun b => by cases b <;> rfl theorem dom_bool₂ (f : Bool → Bool → α) : Primrec₂ f := (cond fst ((dom_bool (f true)).comp snd) ((dom_bool (f false)).comp snd)).of_eq fun ⟨a, b⟩ => by cases a <;> rfl protected theorem not : Primrec not := dom_bool _ protected theorem and : Primrec₂ and := dom_bool₂ _ protected theorem or : Primrec₂ or := dom_bool₂ _ theorem _root_.PrimrecPred.not {p : α → Prop} [DecidablePred p] (hp : PrimrecPred p) : PrimrecPred fun a => ¬p a := (Primrec.not.comp hp).of_eq fun n => by simp theorem _root_.PrimrecPred.and {p q : α → Prop} [DecidablePred p] [DecidablePred q] (hp : PrimrecPred p) (hq : PrimrecPred q) : PrimrecPred fun a => p a ∧ q a := (Primrec.and.comp hp hq).of_eq fun n => by simp theorem _root_.PrimrecPred.or {p q : α → Prop} [DecidablePred p] [DecidablePred q] (hp : PrimrecPred p) (hq : PrimrecPred q) : PrimrecPred fun a => p a ∨ q a := (Primrec.or.comp hp hq).of_eq fun n => by simp -- Porting note: It is unclear whether we want to boolean versions -- of these lemmas, just the prop versions, or both -- The boolean versions are often actually easier to use -- but did not exist in Lean 3 protected theorem beq [DecidableEq α] : Primrec₂ (@BEq.beq α _) := have : PrimrecRel fun a b : ℕ => a = b := (PrimrecPred.and nat_le nat_le.swap).of_eq fun a => by simp [le_antisymm_iff] (this.comp₂ (Primrec.encode.comp₂ Primrec₂.left) (Primrec.encode.comp₂ Primrec₂.right)).of_eq fun a b => encode_injective.eq_iff protected theorem eq [DecidableEq α] : PrimrecRel (@Eq α) := Primrec.beq theorem nat_lt : PrimrecRel ((· < ·) : ℕ → ℕ → Prop) := (nat_le.comp snd fst).not.of_eq fun p => by simp theorem option_guard {p : α → β → Prop} [∀ a b, Decidable (p a b)] (hp : PrimrecRel p) {f : α → β} (hf : Primrec f) : Primrec fun a => Option.guard (p a) (f a) := ite (hp.comp Primrec.id hf) (option_some_iff.2 hf) (const none) theorem option_orElse : Primrec₂ ((· <|> ·) : Option α → Option α → Option α) := (option_casesOn fst snd (fst.comp fst).to₂).of_eq fun ⟨o₁, o₂⟩ => by cases o₁ <;> cases o₂ <;> rfl protected theorem decode₂ : Primrec (decode₂ α) := option_bind .decode <| option_guard (Primrec.beq.comp₂ (by exact encode_iff.mpr snd) (by exact fst.comp fst)) snd theorem list_findIdx₁ {p : α → β → Bool} (hp : Primrec₂ p) : ∀ l : List β, Primrec fun a => l.findIdx (p a) | [] => const 0 | a :: l => (cond (hp.comp .id (const a)) (const 0) (succ.comp (list_findIdx₁ hp l))).of_eq fun n => by simp [List.findIdx_cons] theorem list_indexOf₁ [DecidableEq α] (l : List α) : Primrec fun a => l.indexOf a := list_findIdx₁ (.swap .beq) l theorem dom_fintype [Finite α] (f : α → σ) : Primrec f := let ⟨l, _, m⟩ := Finite.exists_univ_list α option_some_iff.1 <| by haveI := decidableEqOfEncodable α refine ((list_get?₁ (l.map f)).comp (list_indexOf₁ l)).of_eq fun a => ?_ rw [List.get?_eq_getElem?, List.getElem?_map, List.getElem?_indexOf (m a), Option.map_some'] -- Porting note: These are new lemmas -- I added it because it actually simplified the proofs -- and because I couldn't understand the original proof /-- A function is `PrimrecBounded` if its size is bounded by a primitive recursive function -/ def PrimrecBounded (f : α → β) : Prop := ∃ g : α → ℕ, Primrec g ∧ ∀ x, encode (f x) ≤ g x theorem nat_findGreatest {f : α → ℕ} {p : α → ℕ → Prop} [∀ x n, Decidable (p x n)] (hf : Primrec f) (hp : PrimrecRel p) : Primrec fun x => (f x).findGreatest (p x) := (nat_rec' (h := fun x nih => if p x (nih.1 + 1) then nih.1 + 1 else nih.2) hf (const 0) (ite (hp.comp fst (snd |> fst.comp |> succ.comp)) (snd |> fst.comp |> succ.comp) (snd.comp snd))).of_eq fun x => by induction f x <;> simp [Nat.findGreatest, *] /-- To show a function `f : α → ℕ` is primitive recursive, it is enough to show that the function is bounded by a primitive recursive function and that its graph is primitive recursive -/ theorem of_graph {f : α → ℕ} (h₁ : PrimrecBounded f) (h₂ : PrimrecRel fun a b => f a = b) : Primrec f := by rcases h₁ with ⟨g, pg, hg : ∀ x, f x ≤ g x⟩ refine (nat_findGreatest pg h₂).of_eq fun n => ?_ exact (Nat.findGreatest_spec (P := fun b => f n = b) (hg n) rfl).symm -- We show that division is primitive recursive by showing that the graph is theorem nat_div : Primrec₂ ((· / ·) : ℕ → ℕ → ℕ) := by refine of_graph ⟨_, fst, fun p => Nat.div_le_self _ _⟩ ?_ have : PrimrecRel fun (a : ℕ × ℕ) (b : ℕ) => (a.2 = 0 ∧ b = 0) ∨ (0 < a.2 ∧ b * a.2 ≤ a.1 ∧ a.1 < (b + 1) * a.2) := PrimrecPred.or (.and (const 0 |> Primrec.eq.comp (fst |> snd.comp)) (const 0 |> Primrec.eq.comp snd)) (.and (nat_lt.comp (const 0) (fst |> snd.comp)) <| .and (nat_le.comp (nat_mul.comp snd (fst |> snd.comp)) (fst |> fst.comp)) (nat_lt.comp (fst.comp fst) (nat_mul.comp (Primrec.succ.comp snd) (snd.comp fst)))) refine this.of_eq ?_ rintro ⟨a, k⟩ q if H : k = 0 then simp [H, eq_comm] else have : q * k ≤ a ∧ a < (q + 1) * k ↔ q = a / k := by rw [le_antisymm_iff, ← (@Nat.lt_succ _ q), Nat.le_div_iff_mul_le' (Nat.pos_of_ne_zero H), Nat.div_lt_iff_lt_mul' (Nat.pos_of_ne_zero H)] simpa [H, zero_lt_iff, eq_comm (b := q)] theorem nat_mod : Primrec₂ ((· % ·) : ℕ → ℕ → ℕ) := (nat_sub.comp fst (nat_mul.comp snd nat_div)).to₂.of_eq fun m n => by apply Nat.sub_eq_of_eq_add simp [add_comm (m % n), Nat.div_add_mod] theorem nat_bodd : Primrec Nat.bodd := (Primrec.beq.comp (nat_mod.comp .id (const 2)) (const 1)).of_eq fun n => by cases H : n.bodd <;> simp [Nat.mod_two_of_bodd, H] theorem nat_div2 : Primrec Nat.div2 := (nat_div.comp .id (const 2)).of_eq fun n => n.div2_val.symm -- Porting note: this is no longer used -- theorem nat_boddDiv2 : Primrec Nat.boddDiv2 := pair nat_bodd nat_div2 -- Porting note: bit0 is deprecated theorem nat_double : Primrec (fun n : ℕ => 2 * n) := nat_mul.comp (const _) Primrec.id -- Porting note: bit1 is deprecated theorem nat_double_succ : Primrec (fun n : ℕ => 2 * n + 1) := nat_double |> Primrec.succ.comp -- Porting note: this is no longer used -- theorem nat_div_mod : Primrec₂ fun n k : ℕ => (n / k, n % k) := pair nat_div nat_mod end Primrec section variable {α : Type*} {β : Type*} {σ : Type*} variable [Primcodable α] [Primcodable β] [Primcodable σ] variable (H : Nat.Primrec fun n => Encodable.encode (@decode (List β) _ n)) open Primrec private def prim : Primcodable (List β) := ⟨H⟩ private theorem list_casesOn' {f : α → List β} {g : α → σ} {h : α → β × List β → σ} (hf : haveI := prim H; Primrec f) (hg : Primrec g) (hh : haveI := prim H; Primrec₂ h) : @Primrec _ σ _ _ fun a => List.casesOn (f a) (g a) fun b l => h a (b, l) := letI := prim H have : @Primrec _ (Option σ) _ _ fun a => (@decode (Option (β × List β)) _ (encode (f a))).map fun o => Option.casesOn o (g a) (h a) := ((@map_decode_iff _ (Option (β × List β)) _ _ _ _ _).2 <| to₂ <| option_casesOn snd (hg.comp fst) (hh.comp₂ (fst.comp₂ Primrec₂.left) Primrec₂.right)).comp .id (encode_iff.2 hf) option_some_iff.1 <| this.of_eq fun a => by cases' f a with b l <;> simp [encodek] private theorem list_foldl' {f : α → List β} {g : α → σ} {h : α → σ × β → σ} (hf : haveI := prim H; Primrec f) (hg : Primrec g) (hh : haveI := prim H; Primrec₂ h) : Primrec fun a => (f a).foldl (fun s b => h a (s, b)) (g a) := by letI := prim H let G (a : α) (IH : σ × List β) : σ × List β := List.casesOn IH.2 IH fun b l => (h a (IH.1, b), l) have hG : Primrec₂ G := list_casesOn' H (snd.comp snd) snd <| to₂ <| pair (hh.comp (fst.comp fst) <| pair ((fst.comp snd).comp fst) (fst.comp snd)) (snd.comp snd) let F := fun (a : α) (n : ℕ) => (G a)^[n] (g a, f a) have hF : Primrec fun a => (F a (encode (f a))).1 := (fst.comp <| nat_iterate (encode_iff.2 hf) (pair hg hf) <| hG) suffices ∀ a n, F a n = (((f a).take n).foldl (fun s b => h a (s, b)) (g a), (f a).drop n) by refine hF.of_eq fun a => ?_ rw [this, List.take_of_length_le (length_le_encode _)] introv dsimp only [F] generalize f a = l generalize g a = x induction' n with n IH generalizing l x · rfl simp only [iterate_succ, comp_apply] cases' l with b l <;> simp [IH] private theorem list_cons' : (haveI := prim H; Primrec₂ (@List.cons β)) := letI := prim H encode_iff.1 (succ.comp <| Primrec₂.natPair.comp (encode_iff.2 fst) (encode_iff.2 snd)) private theorem list_reverse' : haveI := prim H Primrec (@List.reverse β) := letI := prim H (list_foldl' H .id (const []) <| to₂ <| ((list_cons' H).comp snd fst).comp snd).of_eq (suffices ∀ l r, List.foldl (fun (s : List β) (b : β) => b :: s) r l = List.reverseAux l r from fun l => this l [] fun l => by induction l <;> simp [*, List.reverseAux]) end namespace Primcodable variable {α : Type*} {β : Type*} variable [Primcodable α] [Primcodable β] open Primrec instance sum : Primcodable (α ⊕ β) := ⟨Primrec.nat_iff.1 <| (encode_iff.2 (cond nat_bodd (((@Primrec.decode β _).comp nat_div2).option_map <| to₂ <| nat_double_succ.comp (Primrec.encode.comp snd)) (((@Primrec.decode α _).comp nat_div2).option_map <| to₂ <| nat_double.comp (Primrec.encode.comp snd)))).of_eq fun n => show _ = encode (decodeSum n) by simp only [decodeSum, Nat.boddDiv2_eq] cases Nat.bodd n <;> simp [decodeSum] · cases @decode α _ n.div2 <;> rfl · cases @decode β _ n.div2 <;> rfl⟩ instance list : Primcodable (List α) := ⟨letI H := @Primcodable.prim (List ℕ) _ have : Primrec₂ fun (a : α) (o : Option (List ℕ)) => o.map (List.cons (encode a)) := option_map snd <| (list_cons' H).comp ((@Primrec.encode α _).comp (fst.comp fst)) snd have : Primrec fun n => (ofNat (List ℕ) n).reverse.foldl (fun o m => (@decode α _ m).bind fun a => o.map (List.cons (encode a))) (some []) := list_foldl' H ((list_reverse' H).comp (.ofNat (List ℕ))) (const (some [])) (Primrec.comp₂ (bind_decode_iff.2 <| .swap this) Primrec₂.right) nat_iff.1 <| (encode_iff.2 this).of_eq fun n => by rw [List.foldl_reverse] apply Nat.case_strong_induction_on n; · simp intro n IH; simp cases' @decode α _ n.unpair.1 with a; · rfl simp only [decode_eq_ofNat, Option.some.injEq, Option.some_bind, Option.map_some'] suffices ∀ (o : Option (List ℕ)) (p), encode o = encode p → encode (Option.map (List.cons (encode a)) o) = encode (Option.map (List.cons a) p) from this _ _ (IH _ (Nat.unpair_right_le n)) intro o p IH cases o <;> cases p · rfl · injection IH · injection IH · exact congr_arg (fun k => (Nat.pair (encode a) k).succ.succ) (Nat.succ.inj IH)⟩ end Primcodable namespace Primrec variable {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variable [Primcodable α] [Primcodable β] [Primcodable γ] [Primcodable σ] theorem sum_inl : Primrec (@Sum.inl α β) := encode_iff.1 <| nat_double.comp Primrec.encode theorem sum_inr : Primrec (@Sum.inr α β) := encode_iff.1 <| nat_double_succ.comp Primrec.encode theorem sum_casesOn {f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ → σ} (hf : Primrec f) (hg : Primrec₂ g) (hh : Primrec₂ h) : @Primrec _ σ _ _ fun a => Sum.casesOn (f a) (g a) (h a) := option_some_iff.1 <| (cond (nat_bodd.comp <| encode_iff.2 hf) (option_map (Primrec.decode.comp <| nat_div2.comp <| encode_iff.2 hf) hh) (option_map (Primrec.decode.comp <| nat_div2.comp <| encode_iff.2 hf) hg)).of_eq fun a => by cases' f a with b c <;> simp [Nat.div2_val, encodek] theorem list_cons : Primrec₂ (@List.cons α) := list_cons' Primcodable.prim theorem list_casesOn {f : α → List β} {g : α → σ} {h : α → β × List β → σ} : Primrec f → Primrec g → Primrec₂ h → @Primrec _ σ _ _ fun a => List.casesOn (f a) (g a) fun b l => h a (b, l) := list_casesOn' Primcodable.prim theorem list_foldl {f : α → List β} {g : α → σ} {h : α → σ × β → σ} : Primrec f → Primrec g → Primrec₂ h → Primrec fun a => (f a).foldl (fun s b => h a (s, b)) (g a) := list_foldl' Primcodable.prim theorem list_reverse : Primrec (@List.reverse α) := list_reverse' Primcodable.prim theorem list_foldr {f : α → List β} {g : α → σ} {h : α → β × σ → σ} (hf : Primrec f) (hg : Primrec g) (hh : Primrec₂ h) : Primrec fun a => (f a).foldr (fun b s => h a (b, s)) (g a) := (list_foldl (list_reverse.comp hf) hg <| to₂ <| hh.comp fst <| (pair snd fst).comp snd).of_eq fun a => by simp [List.foldl_reverse] theorem list_head? : Primrec (@List.head? α) := (list_casesOn .id (const none) (option_some_iff.2 <| fst.comp snd).to₂).of_eq fun l => by cases l <;> rfl theorem list_headI [Inhabited α] : Primrec (@List.headI α _) := (option_iget.comp list_head?).of_eq fun l => l.head!_eq_head?.symm theorem list_tail : Primrec (@List.tail α) := (list_casesOn .id (const []) (snd.comp snd).to₂).of_eq fun l => by cases l <;> rfl theorem list_rec {f : α → List β} {g : α → σ} {h : α → β × List β × σ → σ} (hf : Primrec f) (hg : Primrec g) (hh : Primrec₂ h) : @Primrec _ σ _ _ fun a => List.recOn (f a) (g a) fun b l IH => h a (b, l, IH) := let F (a : α) := (f a).foldr (fun (b : β) (s : List β × σ) => (b :: s.1, h a (b, s))) ([], g a) have : Primrec F := list_foldr hf (pair (const []) hg) <| to₂ <| pair ((list_cons.comp fst (fst.comp snd)).comp snd) hh (snd.comp this).of_eq fun a => by suffices F a = (f a, List.recOn (f a) (g a) fun b l IH => h a (b, l, IH)) by rw [this] dsimp [F] induction' f a with b l IH <;> simp [*] theorem list_get? : Primrec₂ (@List.get? α) := let F (l : List α) (n : ℕ) := l.foldl (fun (s : ℕ ⊕ α) (a : α) => Sum.casesOn s (@Nat.casesOn (fun _ => ℕ ⊕ α) · (Sum.inr a) Sum.inl) Sum.inr) (Sum.inl n) have hF : Primrec₂ F := (list_foldl fst (sum_inl.comp snd) ((sum_casesOn fst (nat_casesOn snd (sum_inr.comp <| snd.comp fst) (sum_inl.comp snd).to₂).to₂ (sum_inr.comp snd).to₂).comp snd).to₂).to₂ have : @Primrec _ (Option α) _ _ fun p : List α × ℕ => Sum.casesOn (F p.1 p.2) (fun _ => none) some := sum_casesOn hF (const none).to₂ (option_some.comp snd).to₂ this.to₂.of_eq fun l n => by dsimp; symm induction' l with a l IH generalizing n; · rfl cases' n with n · dsimp [F] clear IH induction' l with _ l IH <;> simp [*] · apply IH theorem list_getD (d : α) : Primrec₂ fun l n => List.getD l n d := by simp only [List.getD_eq_getD_get?] exact option_getD.comp₂ list_get? (const _) theorem list_getI [Inhabited α] : Primrec₂ (@List.getI α _) := list_getD _ theorem list_append : Primrec₂ ((· ++ ·) : List α → List α → List α) := (list_foldr fst snd <| to₂ <| comp (@list_cons α _) snd).to₂.of_eq fun l₁ l₂ => by induction l₁ <;> simp [*] theorem list_concat : Primrec₂ fun l (a : α) => l ++ [a] := list_append.comp fst (list_cons.comp snd (const [])) theorem list_map {f : α → List β} {g : α → β → σ} (hf : Primrec f) (hg : Primrec₂ g) : Primrec fun a => (f a).map (g a) := (list_foldr hf (const []) <| to₂ <| list_cons.comp (hg.comp fst (fst.comp snd)) (snd.comp snd)).of_eq fun a => by induction f a <;> simp [*] theorem list_range : Primrec List.range := (nat_rec' .id (const []) ((list_concat.comp snd fst).comp snd).to₂).of_eq fun n => by simp; induction n <;> simp [*, List.range_succ] theorem list_join : Primrec (@List.join α) := (list_foldr .id (const []) <| to₂ <| comp (@list_append α _) snd).of_eq fun l => by dsimp; induction l <;> simp [*] theorem list_bind {f : α → List β} {g : α → β → List σ} (hf : Primrec f) (hg : Primrec₂ g) : Primrec (fun a => (f a).bind (g a)) := list_join.comp (list_map hf hg) theorem optionToList : Primrec (Option.toList : Option α → List α) := (option_casesOn Primrec.id (const []) ((list_cons.comp Primrec.id (const [])).comp₂ Primrec₂.right)).of_eq (fun o => by rcases o <;> simp) theorem listFilterMap {f : α → List β} {g : α → β → Option σ} (hf : Primrec f) (hg : Primrec₂ g) : Primrec fun a => (f a).filterMap (g a) := (list_bind hf (comp₂ optionToList hg)).of_eq fun _ ↦ Eq.symm <| List.filterMap_eq_bind_toList _ _ theorem list_length : Primrec (@List.length α) := (list_foldr (@Primrec.id (List α) _) (const 0) <| to₂ <| (succ.comp <| snd.comp snd).to₂).of_eq fun l => by dsimp; induction l <;> simp [*] theorem list_findIdx {f : α → List β} {p : α → β → Bool} (hf : Primrec f) (hp : Primrec₂ p) : Primrec fun a => (f a).findIdx (p a) := (list_foldr hf (const 0) <| to₂ <| cond (hp.comp fst <| fst.comp snd) (const 0) (succ.comp <| snd.comp snd)).of_eq fun a => by dsimp; induction f a <;> simp [List.findIdx_cons, *] theorem list_indexOf [DecidableEq α] : Primrec₂ (@List.indexOf α _) := to₂ <| list_findIdx snd <| Primrec.beq.comp₂ snd.to₂ (fst.comp fst).to₂ theorem nat_strong_rec (f : α → ℕ → σ) {g : α → List σ → Option σ} (hg : Primrec₂ g) (H : ∀ a n, g a ((List.range n).map (f a)) = some (f a n)) : Primrec₂ f := suffices Primrec₂ fun a n => (List.range n).map (f a) from Primrec₂.option_some_iff.1 <| (list_get?.comp (this.comp fst (succ.comp snd)) snd).to₂.of_eq fun a n => by simp [List.getElem?_range (Nat.lt_succ_self n)] Primrec₂.option_some_iff.1 <| (nat_rec (const (some [])) (to₂ <| option_bind (snd.comp snd) <| to₂ <| option_map (hg.comp (fst.comp fst) snd) (to₂ <| list_concat.comp (snd.comp fst) snd))).of_eq fun a n => by induction' n with n IH; · rfl simp [IH, H, List.range_succ] theorem listLookup [DecidableEq α] : Primrec₂ (List.lookup : α → List (α × β) → Option β) := (to₂ <| list_rec snd (const none) <| to₂ <| cond (Primrec.beq.comp (fst.comp fst) (fst.comp $ fst.comp snd)) (option_some.comp $ snd.comp $ fst.comp snd) (snd.comp $ snd.comp snd)).of_eq fun a ps => by induction' ps with p ps ih <;> simp [List.lookup, *] cases ha : a == p.1 <;> simp [ha] theorem nat_omega_rec' (f : β → σ) {m : β → ℕ} {l : β → List β} {g : β → List σ → Option σ} (hm : Primrec m) (hl : Primrec l) (hg : Primrec₂ g) (Ord : ∀ b, ∀ b' ∈ l b, m b' < m b) (H : ∀ b, g b ((l b).map f) = some (f b)) : Primrec f := by haveI : DecidableEq β := Encodable.decidableEqOfEncodable β let mapGraph (M : List (β × σ)) (bs : List β) : List σ := bs.bind (Option.toList <| M.lookup ·) let bindList (b : β) : ℕ → List β := fun n ↦ n.rec [b] fun _ bs ↦ bs.bind l let graph (b : β) : ℕ → List (β × σ) := fun i ↦ i.rec [] fun i ih ↦ (bindList b (m b - i)).filterMap fun b' ↦ (g b' $ mapGraph ih (l b')).map (b', ·) have mapGraph_primrec : Primrec₂ mapGraph := to₂ <| list_bind snd <| optionToList.comp₂ <| listLookup.comp₂ .right (fst.comp₂ .left) have bindList_primrec : Primrec₂ (bindList) := nat_rec' snd (list_cons.comp fst (const [])) (to₂ <| list_bind (snd.comp snd) (hl.comp₂ .right)) have graph_primrec : Primrec₂ (graph) := to₂ <| nat_rec' snd (const []) <| to₂ <| listFilterMap (bindList_primrec.comp (fst.comp fst) (nat_sub.comp (hm.comp $ fst.comp fst) (fst.comp snd))) <| to₂ <| option_map (hg.comp snd (mapGraph_primrec.comp (snd.comp $ snd.comp fst) (hl.comp snd))) (Primrec₂.pair.comp₂ (snd.comp₂ .left) .right) have : Primrec (fun b => ((graph b (m b + 1)).get? 0).map Prod.snd) := option_map (list_get?.comp (graph_primrec.comp Primrec.id (succ.comp hm)) (const 0)) (snd.comp₂ Primrec₂.right) exact option_some_iff.mp <| this.of_eq <| fun b ↦ by have graph_eq_map_bindList (i : ℕ) (hi : i ≤ m b + 1) : graph b i = (bindList b (m b + 1 - i)).map fun x ↦ (x, f x) := by have bindList_eq_nil : bindList b (m b + 1) = [] := have bindList_m_lt (k : ℕ) : ∀ b' ∈ bindList b k, m b' < m b + 1 - k := by induction' k with k ih <;> simp [bindList] intro a₂ a₁ ha₁ ha₂ have : k ≤ m b := Nat.lt_succ.mp (by simpa using Nat.add_lt_of_lt_sub $ Nat.zero_lt_of_lt (ih a₁ ha₁)) have : m a₁ ≤ m b - k := Nat.lt_succ.mp (by rw [← Nat.succ_sub this]; simpa using ih a₁ ha₁) exact lt_of_lt_of_le (Ord a₁ a₂ ha₂) this List.eq_nil_iff_forall_not_mem.mpr (by intro b' ha'; by_contra; simpa using bindList_m_lt (m b + 1) b' ha') have mapGraph_graph {bs bs' : List β} (has : bs' ⊆ bs) : mapGraph (bs.map $ fun x => (x, f x)) bs' = bs'.map f := by induction' bs' with b bs' ih <;> simp [mapGraph] · have : b ∈ bs ∧ bs' ⊆ bs := by simpa using has rcases this with ⟨ha, has'⟩ simpa [List.lookup_graph f ha] using ih has' have graph_succ : ∀ i, graph b (i + 1) = (bindList b (m b - i)).filterMap fun b' => (g b' <| mapGraph (graph b i) (l b')).map (b', ·) := fun _ => rfl have bindList_succ : ∀ i, bindList b (i + 1) = (bindList b i).bind l := fun _ => rfl induction' i with i ih · symm; simpa [graph] using bindList_eq_nil · simp only [graph_succ, ih (Nat.le_of_lt hi), Nat.succ_sub (Nat.lt_succ.mp hi), Nat.succ_eq_add_one, bindList_succ, Nat.reduceSubDiff] apply List.filterMap_eq_map_iff_forall_eq_some.mpr intro b' ha'; simp; rw [mapGraph_graph] · exact H b' · exact (List.infix_bind_of_mem ha' l).subset simp [graph_eq_map_bindList (m b + 1) (Nat.le_refl _), bindList] theorem nat_omega_rec (f : α → β → σ) {m : α → β → ℕ} {l : α → β → List β} {g : α → β × List σ → Option σ} (hm : Primrec₂ m) (hl : Primrec₂ l) (hg : Primrec₂ g) (Ord : ∀ a b, ∀ b' ∈ l a b, m a b' < m a b) (H : ∀ a b, g a (b, (l a b).map (f a)) = some (f a b)) : Primrec₂ f := Primrec₂.uncurry.mp <| nat_omega_rec' (Function.uncurry f) (Primrec₂.uncurry.mpr hm) (list_map (hl.comp fst snd) (Primrec₂.pair.comp₂ (fst.comp₂ .left) .right)) (hg.comp₂ (fst.comp₂ .left) (Primrec₂.pair.comp₂ (snd.comp₂ .left) .right)) (by simpa using Ord) (by simpa [Function.comp] using H) end Primrec namespace Primcodable variable {α : Type*} {β : Type*} variable [Primcodable α] [Primcodable β] open Primrec /-- A subtype of a primitive recursive predicate is `Primcodable`. -/ def subtype {p : α → Prop} [DecidablePred p] (hp : PrimrecPred p) : Primcodable (Subtype p) := ⟨have : Primrec fun n => (@decode α _ n).bind fun a => Option.guard p a := option_bind .decode (option_guard (hp.comp snd).to₂ snd) nat_iff.1 <| (encode_iff.2 this).of_eq fun n => show _ = encode ((@decode α _ n).bind fun a => _) by cases' @decode α _ n with a; · rfl dsimp [Option.guard] by_cases h : p a <;> simp [h]; rfl⟩ instance fin {n} : Primcodable (Fin n) := @ofEquiv _ _ (subtype <| nat_lt.comp .id (const n)) Fin.equivSubtype instance vector {n} : Primcodable (Vector α n) := subtype ((@Primrec.eq ℕ _ _).comp list_length (const _)) instance finArrow {n} : Primcodable (Fin n → α) := ofEquiv _ (Equiv.vectorEquivFin _ _).symm -- Porting note: Equiv.arrayEquivFin is not ported yet -- instance array {n} : Primcodable (Array' n α) := -- ofEquiv _ (Equiv.arrayEquivFin _ _) section ULower attribute [local instance] Encodable.decidableRangeEncode Encodable.decidableEqOfEncodable theorem mem_range_encode : PrimrecPred (fun n => n ∈ Set.range (encode : α → ℕ)) := have : PrimrecPred fun n => Encodable.decode₂ α n ≠ none := .not (Primrec.eq.comp (.option_bind .decode (.ite (Primrec.eq.comp (Primrec.encode.comp .snd) .fst) (Primrec.option_some.comp .snd) (.const _))) (.const _)) this.of_eq fun _ => decode₂_ne_none_iff instance ulower : Primcodable (ULower α) := Primcodable.subtype mem_range_encode end ULower end Primcodable namespace Primrec variable {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variable [Primcodable α] [Primcodable β] [Primcodable γ] [Primcodable σ] theorem subtype_val {p : α → Prop} [DecidablePred p] {hp : PrimrecPred p} : haveI := Primcodable.subtype hp Primrec (@Subtype.val α p) := by letI := Primcodable.subtype hp refine (@Primcodable.prim (Subtype p)).of_eq fun n => ?_ rcases @decode (Subtype p) _ n with (_ | ⟨a, h⟩) <;> rfl theorem subtype_val_iff {p : β → Prop} [DecidablePred p] {hp : PrimrecPred p} {f : α → Subtype p} : haveI := Primcodable.subtype hp (Primrec fun a => (f a).1) ↔ Primrec f := by letI := Primcodable.subtype hp refine ⟨fun h => ?_, fun hf => subtype_val.comp hf⟩ refine Nat.Primrec.of_eq h fun n => ?_ cases' @decode α _ n with a; · rfl simp; rfl theorem subtype_mk {p : β → Prop} [DecidablePred p] {hp : PrimrecPred p} {f : α → β} {h : ∀ a, p (f a)} (hf : Primrec f) : haveI := Primcodable.subtype hp Primrec fun a => @Subtype.mk β p (f a) (h a) := subtype_val_iff.1 hf theorem option_get {f : α → Option β} {h : ∀ a, (f a).isSome} : Primrec f → Primrec fun a => (f a).get (h a) := by intro hf refine (Nat.Primrec.pred.comp hf).of_eq fun n => ?_ generalize hx : @decode α _ n = x cases x <;> simp theorem ulower_down : Primrec (ULower.down : α → ULower α) := letI : ∀ a, Decidable (a ∈ Set.range (encode : α → ℕ)) := decidableRangeEncode _ subtype_mk .encode theorem ulower_up : Primrec (ULower.up : ULower α → α) := letI : ∀ a, Decidable (a ∈ Set.range (encode : α → ℕ)) := decidableRangeEncode _ option_get (Primrec.decode₂.comp subtype_val) theorem fin_val_iff {n} {f : α → Fin n} : (Primrec fun a => (f a).1) ↔ Primrec f := by letI : Primcodable { a // id a < n } := Primcodable.subtype (nat_lt.comp .id (const _)) exact (Iff.trans (by rfl) subtype_val_iff).trans (of_equiv_iff _) theorem fin_val {n} : Primrec (fun (i : Fin n) => (i : ℕ)) := fin_val_iff.2 .id theorem fin_succ {n} : Primrec (@Fin.succ n) := fin_val_iff.1 <| by simp [succ.comp fin_val] theorem vector_toList {n} : Primrec (@Vector.toList α n) := subtype_val theorem vector_toList_iff {n} {f : α → Vector β n} : (Primrec fun a => (f a).toList) ↔ Primrec f := subtype_val_iff theorem vector_cons {n} : Primrec₂ (@Vector.cons α n) := vector_toList_iff.1 <| by simpa using list_cons.comp fst (vector_toList_iff.2 snd) theorem vector_length {n} : Primrec (@Vector.length α n) := const _ theorem vector_head {n} : Primrec (@Vector.head α n) := option_some_iff.1 <| (list_head?.comp vector_toList).of_eq fun ⟨_ :: _, _⟩ => rfl theorem vector_tail {n} : Primrec (@Vector.tail α n) := vector_toList_iff.1 <| (list_tail.comp vector_toList).of_eq fun ⟨l, h⟩ => by cases l <;> rfl theorem vector_get {n} : Primrec₂ (@Vector.get α n) := option_some_iff.1 <| (list_get?.comp (vector_toList.comp fst) (fin_val.comp snd)).of_eq fun a => by rw [Vector.get_eq_get, ← List.get?_eq_get] rfl theorem list_ofFn : ∀ {n} {f : Fin n → α → σ}, (∀ i, Primrec (f i)) → Primrec fun a => List.ofFn fun i => f i a | 0, _, _ => const [] | n + 1, f, hf => by simpa [List.ofFn_succ] using list_cons.comp (hf 0) (list_ofFn fun i => hf i.succ) theorem vector_ofFn {n} {f : Fin n → α → σ} (hf : ∀ i, Primrec (f i)) : Primrec fun a => Vector.ofFn fun i => f i a := vector_toList_iff.1 <| by simp [list_ofFn hf] theorem vector_get' {n} : Primrec (@Vector.get α n) := of_equiv_symm theorem vector_ofFn' {n} : Primrec (@Vector.ofFn α n) := of_equiv theorem fin_app {n} : Primrec₂ (@id (Fin n → σ)) := (vector_get.comp (vector_ofFn'.comp fst) snd).of_eq fun ⟨v, i⟩ => by simp theorem fin_curry₁ {n} {f : Fin n → α → σ} : Primrec₂ f ↔ ∀ i, Primrec (f i) := ⟨fun h i => h.comp (const i) .id, fun h => (vector_get.comp ((vector_ofFn h).comp snd) fst).of_eq fun a => by simp⟩ theorem fin_curry {n} {f : α → Fin n → σ} : Primrec f ↔ Primrec₂ f := ⟨fun h => fin_app.comp (h.comp fst) snd, fun h => (vector_get'.comp (vector_ofFn fun i => show Primrec fun a => f a i from h.comp .id (const i))).of_eq fun a => by funext i; simp⟩ end Primrec namespace Nat open Mathlib.Vector /-- An alternative inductive definition of `Primrec` which does not use the pairing function on ℕ, and so has to work with n-ary functions on ℕ instead of unary functions. We prove that this is equivalent to the regular notion in `to_prim` and `of_prim`. -/ inductive Primrec' : ∀ {n}, (Vector ℕ n → ℕ) → Prop | zero : @Primrec' 0 fun _ => 0 | succ : @Primrec' 1 fun v => succ v.head | get {n} (i : Fin n) : Primrec' fun v => v.get i | comp {m n f} (g : Fin n → Vector ℕ m → ℕ) : Primrec' f → (∀ i, Primrec' (g i)) → Primrec' fun a => f (ofFn fun i => g i a) | prec {n f g} : @Primrec' n f → @Primrec' (n + 2) g → Primrec' fun v : Vector ℕ (n + 1) => v.head.rec (f v.tail) fun y IH => g (y ::ᵥ IH ::ᵥ v.tail) end Nat namespace Nat.Primrec' open Mathlib.Vector Primrec theorem to_prim {n f} (pf : @Nat.Primrec' n f) : Primrec f := by induction pf with | zero => exact .const 0 | succ => exact _root_.Primrec.succ.comp .vector_head | get i => exact Primrec.vector_get.comp .id (.const i) | comp _ _ _ hf hg => exact hf.comp (.vector_ofFn fun i => hg i) | @prec n f g _ _ hf hg => exact .nat_rec' .vector_head (hf.comp Primrec.vector_tail) (hg.comp <| Primrec.vector_cons.comp (Primrec.fst.comp .snd) <| Primrec.vector_cons.comp (Primrec.snd.comp .snd) <| (@Primrec.vector_tail _ _ (n + 1)).comp .fst).to₂ theorem of_eq {n} {f g : Vector ℕ n → ℕ} (hf : Primrec' f) (H : ∀ i, f i = g i) : Primrec' g := (funext H : f = g) ▸ hf theorem const {n} : ∀ m, @Primrec' n fun _ => m | 0 => zero.comp Fin.elim0 fun i => i.elim0 | m + 1 => succ.comp _ fun _ => const m theorem head {n : ℕ} : @Primrec' n.succ head := (get 0).of_eq fun v => by simp [get_zero] theorem tail {n f} (hf : @Primrec' n f) : @Primrec' n.succ fun v => f v.tail := (hf.comp _ fun i => @get _ i.succ).of_eq fun v => by rw [← ofFn_get v.tail]; congr; funext i; simp /-- A function from vectors to vectors is primitive recursive when all of its projections are. -/ def Vec {n m} (f : Vector ℕ n → Vector ℕ m) : Prop := ∀ i, Primrec' fun v => (f v).get i protected theorem nil {n} : @Vec n 0 fun _ => nil := fun i => i.elim0 protected theorem cons {n m f g} (hf : @Primrec' n f) (hg : @Vec n m g) : Vec fun v => f v ::ᵥ g v := fun i => Fin.cases (by simp [*]) (fun i => by simp [hg i]) i theorem idv {n} : @Vec n n id := get theorem comp' {n m f g} (hf : @Primrec' m f) (hg : @Vec n m g) : Primrec' fun v => f (g v) := (hf.comp _ hg).of_eq fun v => by simp theorem comp₁ (f : ℕ → ℕ) (hf : @Primrec' 1 fun v => f v.head) {n g} (hg : @Primrec' n g) : Primrec' fun v => f (g v) := hf.comp _ fun _ => hg theorem comp₂ (f : ℕ → ℕ → ℕ) (hf : @Primrec' 2 fun v => f v.head v.tail.head) {n g h} (hg : @Primrec' n g) (hh : @Primrec' n h) : Primrec' fun v => f (g v) (h v) := by simpa using hf.comp' (hg.cons <| hh.cons Primrec'.nil) theorem prec' {n f g h} (hf : @Primrec' n f) (hg : @Primrec' n g) (hh : @Primrec' (n + 2) h) : @Primrec' n fun v => (f v).rec (g v) fun y IH : ℕ => h (y ::ᵥ IH ::ᵥ v) := by simpa using comp' (prec hg hh) (hf.cons idv) theorem pred : @Primrec' 1 fun v => v.head.pred := (prec' head (const 0) head).of_eq fun v => by simp; cases v.head <;> rfl theorem add : @Primrec' 2 fun v => v.head + v.tail.head := (prec head (succ.comp₁ _ (tail head))).of_eq fun v => by simp; induction v.head <;> simp [*, Nat.succ_add] theorem sub : @Primrec' 2 fun v => v.head - v.tail.head := by have : @Primrec' 2 fun v ↦ (fun a b ↦ b - a) v.head v.tail.head := by refine (prec head (pred.comp₁ _ (tail head))).of_eq fun v => ?_ simp; induction v.head <;> simp [*, Nat.sub_add_eq] simpa using comp₂ (fun a b => b - a) this (tail head) head theorem mul : @Primrec' 2 fun v => v.head * v.tail.head := (prec (const 0) (tail (add.comp₂ _ (tail head) head))).of_eq fun v => by simp; induction v.head <;> simp [*, Nat.succ_mul]; rw [add_comm] theorem if_lt {n a b f g} (ha : @Primrec' n a) (hb : @Primrec' n b) (hf : @Primrec' n f) (hg : @Primrec' n g) : @Primrec' n fun v => if a v < b v then f v else g v := (prec' (sub.comp₂ _ hb ha) hg (tail <| tail hf)).of_eq fun v => by cases e : b v - a v · simp [not_lt.2 (tsub_eq_zero_iff_le.mp e)] · simp [Nat.lt_of_sub_eq_succ e] theorem natPair : @Primrec' 2 fun v => v.head.pair v.tail.head := if_lt head (tail head) (add.comp₂ _ (tail <| mul.comp₂ _ head head) head) (add.comp₂ _ (add.comp₂ _ (mul.comp₂ _ head head) head) (tail head)) protected theorem encode : ∀ {n}, @Primrec' n encode | 0 => (const 0).of_eq fun v => by rw [v.eq_nil]; rfl | n + 1 => (succ.comp₁ _ (natPair.comp₂ _ head (tail Primrec'.encode))).of_eq fun ⟨a :: l, e⟩ => rfl theorem sqrt : @Primrec' 1 fun v => v.head.sqrt := by suffices H : ∀ n : ℕ, n.sqrt = n.rec 0 fun x y => if x.succ < y.succ * y.succ then y else y.succ by simp only [H, succ_eq_add_one] have := @prec' 1 _ _ (fun v => by have x := v.head; have y := v.tail.head exact if x.succ < y.succ * y.succ then y else y.succ) head (const 0) ?_ · exact this have x1 : @Primrec' 3 fun v => v.head.succ := succ.comp₁ _ head have y1 : @Primrec' 3 fun v => v.tail.head.succ := succ.comp₁ _ (tail head) exact if_lt x1 (mul.comp₂ _ y1 y1) (tail head) y1 introv; symm induction' n with n IH; · simp dsimp; rw [IH]; split_ifs with h · exact le_antisymm (Nat.sqrt_le_sqrt (Nat.le_succ _)) (Nat.lt_succ_iff.1 <| Nat.sqrt_lt.2 h) · exact Nat.eq_sqrt.2 ⟨not_lt.1 h, Nat.sqrt_lt.1 <| Nat.lt_succ_iff.2 <| Nat.sqrt_succ_le_succ_sqrt _⟩ theorem unpair₁ {n f} (hf : @Primrec' n f) : @Primrec' n fun v => (f v).unpair.1 := by have s := sqrt.comp₁ _ hf have fss := sub.comp₂ _ hf (mul.comp₂ _ s s) refine (if_lt fss s fss s).of_eq fun v => ?_ simp [Nat.unpair]; split_ifs <;> rfl theorem unpair₂ {n f} (hf : @Primrec' n f) : @Primrec' n fun v => (f v).unpair.2 := by have s := sqrt.comp₁ _ hf have fss := sub.comp₂ _ hf (mul.comp₂ _ s s) refine (if_lt fss s s (sub.comp₂ _ fss s)).of_eq fun v => ?_ simp [Nat.unpair]; split_ifs <;> rfl theorem of_prim {n f} : Primrec f → @Primrec' n f := suffices ∀ f, Nat.Primrec f → @Primrec' 1 fun v => f v.head from fun hf => (pred.comp₁ _ <| (this _ hf).comp₁ (fun m => Encodable.encode <| (@decode (Vector ℕ n) _ m).map f) Primrec'.encode).of_eq fun i => by simp [encodek] fun f hf => by induction hf with | zero => exact const 0 | succ => exact succ | left => exact unpair₁ head | right => exact unpair₂ head | pair _ _ hf hg => exact natPair.comp₂ _ hf hg | comp _ _ hf hg => exact hf.comp₁ _ hg | prec _ _ hf hg => simpa using prec' (unpair₂ head) (hf.comp₁ _ (unpair₁ head)) (hg.comp₁ _ <| natPair.comp₂ _ (unpair₁ <| tail <| tail head) (natPair.comp₂ _ head (tail head))) theorem prim_iff {n f} : @Primrec' n f ↔ Primrec f := ⟨to_prim, of_prim⟩ theorem prim_iff₁ {f : ℕ → ℕ} : (@Primrec' 1 fun v => f v.head) ↔ Primrec f := prim_iff.trans ⟨fun h => (h.comp <| .vector_ofFn fun _ => .id).of_eq fun v => by simp, fun h => h.comp .vector_head⟩ theorem prim_iff₂ {f : ℕ → ℕ → ℕ} : (@Primrec' 2 fun v => f v.head v.tail.head) ↔ Primrec₂ f := prim_iff.trans ⟨fun h => (h.comp <| Primrec.vector_cons.comp .fst <| Primrec.vector_cons.comp .snd (.const nil)).of_eq fun v => by simp, fun h => h.comp .vector_head (Primrec.vector_head.comp .vector_tail)⟩ theorem vec_iff {m n f} : @Vec m n f ↔ Primrec f := ⟨fun h => by simpa using Primrec.vector_ofFn fun i => to_prim (h i), fun h i => of_prim <| Primrec.vector_get.comp h (.const i)⟩ end Nat.Primrec' theorem Primrec.nat_sqrt : Primrec Nat.sqrt := Nat.Primrec'.prim_iff₁.1 Nat.Primrec'.sqrt
Computability\Reduce.lean
/- Copyright (c) 2019 Minchao Wu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Minchao Wu, Mario Carneiro -/ import Mathlib.Computability.Halting /-! # Strong reducibility and degrees. This file defines the notions of computable many-one reduction and one-one reduction between sets, and shows that the corresponding degrees form a semilattice. ## Notations This file uses the local notation `⊕'` for `Sum.elim` to denote the disjoint union of two degrees. ## References * [Robert Soare, *Recursively enumerable sets and degrees*][soare1987] ## Tags computability, reducibility, reduction -/ universe u v w open Function /-- `p` is many-one reducible to `q` if there is a computable function translating questions about `p` to questions about `q`. -/ def ManyOneReducible {α β} [Primcodable α] [Primcodable β] (p : α → Prop) (q : β → Prop) := ∃ f, Computable f ∧ ∀ a, p a ↔ q (f a) @[inherit_doc ManyOneReducible] infixl:1000 " ≤₀ " => ManyOneReducible theorem ManyOneReducible.mk {α β} [Primcodable α] [Primcodable β] {f : α → β} (q : β → Prop) (h : Computable f) : (fun a => q (f a)) ≤₀ q := ⟨f, h, fun _ => Iff.rfl⟩ @[refl] theorem manyOneReducible_refl {α} [Primcodable α] (p : α → Prop) : p ≤₀ p := ⟨id, Computable.id, by simp⟩ @[trans] theorem ManyOneReducible.trans {α β γ} [Primcodable α] [Primcodable β] [Primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} : p ≤₀ q → q ≤₀ r → p ≤₀ r | ⟨f, c₁, h₁⟩, ⟨g, c₂, h₂⟩ => ⟨g ∘ f, c₂.comp c₁, fun a => ⟨fun h => by erw [← h₂, ← h₁]; assumption, fun h => by rwa [h₁, h₂]⟩⟩ theorem reflexive_manyOneReducible {α} [Primcodable α] : Reflexive (@ManyOneReducible α α _ _) := manyOneReducible_refl theorem transitive_manyOneReducible {α} [Primcodable α] : Transitive (@ManyOneReducible α α _ _) := fun _ _ _ => ManyOneReducible.trans /-- `p` is one-one reducible to `q` if there is an injective computable function translating questions about `p` to questions about `q`. -/ def OneOneReducible {α β} [Primcodable α] [Primcodable β] (p : α → Prop) (q : β → Prop) := ∃ f, Computable f ∧ Injective f ∧ ∀ a, p a ↔ q (f a) @[inherit_doc OneOneReducible] infixl:1000 " ≤₁ " => OneOneReducible theorem OneOneReducible.mk {α β} [Primcodable α] [Primcodable β] {f : α → β} (q : β → Prop) (h : Computable f) (i : Injective f) : (fun a => q (f a)) ≤₁ q := ⟨f, h, i, fun _ => Iff.rfl⟩ @[refl] theorem oneOneReducible_refl {α} [Primcodable α] (p : α → Prop) : p ≤₁ p := ⟨id, Computable.id, injective_id, by simp⟩ @[trans] theorem OneOneReducible.trans {α β γ} [Primcodable α] [Primcodable β] [Primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} : p ≤₁ q → q ≤₁ r → p ≤₁ r | ⟨f, c₁, i₁, h₁⟩, ⟨g, c₂, i₂, h₂⟩ => ⟨g ∘ f, c₂.comp c₁, i₂.comp i₁, fun a => ⟨fun h => by erw [← h₂, ← h₁]; assumption, fun h => by rwa [h₁, h₂]⟩⟩ theorem OneOneReducible.to_many_one {α β} [Primcodable α] [Primcodable β] {p : α → Prop} {q : β → Prop} : p ≤₁ q → p ≤₀ q | ⟨f, c, _, h⟩ => ⟨f, c, h⟩ theorem OneOneReducible.of_equiv {α β} [Primcodable α] [Primcodable β] {e : α ≃ β} (q : β → Prop) (h : Computable e) : (q ∘ e) ≤₁ q := OneOneReducible.mk _ h e.injective theorem OneOneReducible.of_equiv_symm {α β} [Primcodable α] [Primcodable β] {e : α ≃ β} (q : β → Prop) (h : Computable e.symm) : q ≤₁ (q ∘ e) := by convert OneOneReducible.of_equiv _ h; funext; simp theorem reflexive_oneOneReducible {α} [Primcodable α] : Reflexive (@OneOneReducible α α _ _) := oneOneReducible_refl theorem transitive_oneOneReducible {α} [Primcodable α] : Transitive (@OneOneReducible α α _ _) := fun _ _ _ => OneOneReducible.trans namespace ComputablePred variable {α : Type*} {β : Type*} {σ : Type*} variable [Primcodable α] [Primcodable β] [Primcodable σ] open Computable theorem computable_of_manyOneReducible {p : α → Prop} {q : β → Prop} (h₁ : p ≤₀ q) (h₂ : ComputablePred q) : ComputablePred p := by rcases h₁ with ⟨f, c, hf⟩ rw [show p = fun a => q (f a) from Set.ext hf] rcases computable_iff.1 h₂ with ⟨g, hg, rfl⟩ exact ⟨by infer_instance, by simpa using hg.comp c⟩ theorem computable_of_oneOneReducible {p : α → Prop} {q : β → Prop} (h : p ≤₁ q) : ComputablePred q → ComputablePred p := computable_of_manyOneReducible h.to_many_one end ComputablePred /-- `p` and `q` are many-one equivalent if each one is many-one reducible to the other. -/ def ManyOneEquiv {α β} [Primcodable α] [Primcodable β] (p : α → Prop) (q : β → Prop) := p ≤₀ q ∧ q ≤₀ p /-- `p` and `q` are one-one equivalent if each one is one-one reducible to the other. -/ def OneOneEquiv {α β} [Primcodable α] [Primcodable β] (p : α → Prop) (q : β → Prop) := p ≤₁ q ∧ q ≤₁ p @[refl] theorem manyOneEquiv_refl {α} [Primcodable α] (p : α → Prop) : ManyOneEquiv p p := ⟨manyOneReducible_refl _, manyOneReducible_refl _⟩ @[symm] theorem ManyOneEquiv.symm {α β} [Primcodable α] [Primcodable β] {p : α → Prop} {q : β → Prop} : ManyOneEquiv p q → ManyOneEquiv q p := And.symm @[trans] theorem ManyOneEquiv.trans {α β γ} [Primcodable α] [Primcodable β] [Primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} : ManyOneEquiv p q → ManyOneEquiv q r → ManyOneEquiv p r | ⟨pq, qp⟩, ⟨qr, rq⟩ => ⟨pq.trans qr, rq.trans qp⟩ theorem equivalence_of_manyOneEquiv {α} [Primcodable α] : Equivalence (@ManyOneEquiv α α _ _) := ⟨manyOneEquiv_refl, fun {_ _} => ManyOneEquiv.symm, fun {_ _ _} => ManyOneEquiv.trans⟩ @[refl] theorem oneOneEquiv_refl {α} [Primcodable α] (p : α → Prop) : OneOneEquiv p p := ⟨oneOneReducible_refl _, oneOneReducible_refl _⟩ @[symm] theorem OneOneEquiv.symm {α β} [Primcodable α] [Primcodable β] {p : α → Prop} {q : β → Prop} : OneOneEquiv p q → OneOneEquiv q p := And.symm @[trans] theorem OneOneEquiv.trans {α β γ} [Primcodable α] [Primcodable β] [Primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} : OneOneEquiv p q → OneOneEquiv q r → OneOneEquiv p r | ⟨pq, qp⟩, ⟨qr, rq⟩ => ⟨pq.trans qr, rq.trans qp⟩ theorem equivalence_of_oneOneEquiv {α} [Primcodable α] : Equivalence (@OneOneEquiv α α _ _) := ⟨oneOneEquiv_refl, fun {_ _} => OneOneEquiv.symm, fun {_ _ _} => OneOneEquiv.trans⟩ theorem OneOneEquiv.to_many_one {α β} [Primcodable α] [Primcodable β] {p : α → Prop} {q : β → Prop} : OneOneEquiv p q → ManyOneEquiv p q | ⟨pq, qp⟩ => ⟨pq.to_many_one, qp.to_many_one⟩ /-- a computable bijection -/ nonrec def Equiv.Computable {α β} [Primcodable α] [Primcodable β] (e : α ≃ β) := Computable e ∧ Computable e.symm theorem Equiv.Computable.symm {α β} [Primcodable α] [Primcodable β] {e : α ≃ β} : e.Computable → e.symm.Computable := And.symm theorem Equiv.Computable.trans {α β γ} [Primcodable α] [Primcodable β] [Primcodable γ] {e₁ : α ≃ β} {e₂ : β ≃ γ} : e₁.Computable → e₂.Computable → (e₁.trans e₂).Computable | ⟨l₁, r₁⟩, ⟨l₂, r₂⟩ => ⟨l₂.comp l₁, r₁.comp r₂⟩ theorem Computable.eqv (α) [Denumerable α] : (Denumerable.eqv α).Computable := ⟨Computable.encode, Computable.ofNat _⟩ theorem Computable.equiv₂ (α β) [Denumerable α] [Denumerable β] : (Denumerable.equiv₂ α β).Computable := (Computable.eqv _).trans (Computable.eqv _).symm theorem OneOneEquiv.of_equiv {α β} [Primcodable α] [Primcodable β] {e : α ≃ β} (h : e.Computable) {p} : OneOneEquiv (p ∘ e) p := ⟨OneOneReducible.of_equiv _ h.1, OneOneReducible.of_equiv_symm _ h.2⟩ theorem ManyOneEquiv.of_equiv {α β} [Primcodable α] [Primcodable β] {e : α ≃ β} (h : e.Computable) {p} : ManyOneEquiv (p ∘ e) p := (OneOneEquiv.of_equiv h).to_many_one theorem ManyOneEquiv.le_congr_left {α β γ} [Primcodable α] [Primcodable β] [Primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} (h : ManyOneEquiv p q) : p ≤₀ r ↔ q ≤₀ r := ⟨h.2.trans, h.1.trans⟩ theorem ManyOneEquiv.le_congr_right {α β γ} [Primcodable α] [Primcodable β] [Primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} (h : ManyOneEquiv q r) : p ≤₀ q ↔ p ≤₀ r := ⟨fun h' => h'.trans h.1, fun h' => h'.trans h.2⟩ theorem OneOneEquiv.le_congr_left {α β γ} [Primcodable α] [Primcodable β] [Primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} (h : OneOneEquiv p q) : p ≤₁ r ↔ q ≤₁ r := ⟨h.2.trans, h.1.trans⟩ theorem OneOneEquiv.le_congr_right {α β γ} [Primcodable α] [Primcodable β] [Primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} (h : OneOneEquiv q r) : p ≤₁ q ↔ p ≤₁ r := ⟨fun h' => h'.trans h.1, fun h' => h'.trans h.2⟩ theorem ManyOneEquiv.congr_left {α β γ} [Primcodable α] [Primcodable β] [Primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} (h : ManyOneEquiv p q) : ManyOneEquiv p r ↔ ManyOneEquiv q r := and_congr h.le_congr_left h.le_congr_right theorem ManyOneEquiv.congr_right {α β γ} [Primcodable α] [Primcodable β] [Primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} (h : ManyOneEquiv q r) : ManyOneEquiv p q ↔ ManyOneEquiv p r := and_congr h.le_congr_right h.le_congr_left theorem OneOneEquiv.congr_left {α β γ} [Primcodable α] [Primcodable β] [Primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} (h : OneOneEquiv p q) : OneOneEquiv p r ↔ OneOneEquiv q r := and_congr h.le_congr_left h.le_congr_right theorem OneOneEquiv.congr_right {α β γ} [Primcodable α] [Primcodable β] [Primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} (h : OneOneEquiv q r) : OneOneEquiv p q ↔ OneOneEquiv p r := and_congr h.le_congr_right h.le_congr_left @[simp] theorem ULower.down_computable {α} [Primcodable α] : (ULower.equiv α).Computable := ⟨Primrec.ulower_down.to_comp, Primrec.ulower_up.to_comp⟩ theorem manyOneEquiv_up {α} [Primcodable α] {p : α → Prop} : ManyOneEquiv (p ∘ ULower.up) p := ManyOneEquiv.of_equiv ULower.down_computable.symm local infixl:1001 " ⊕' " => Sum.elim open Nat.Primrec theorem OneOneReducible.disjoin_left {α β} [Primcodable α] [Primcodable β] {p : α → Prop} {q : β → Prop} : p ≤₁ p ⊕' q := ⟨Sum.inl, Computable.sum_inl, fun _ _ => Sum.inl.inj_iff.1, fun _ => Iff.rfl⟩ theorem OneOneReducible.disjoin_right {α β} [Primcodable α] [Primcodable β] {p : α → Prop} {q : β → Prop} : q ≤₁ p ⊕' q := ⟨Sum.inr, Computable.sum_inr, fun _ _ => Sum.inr.inj_iff.1, fun _ => Iff.rfl⟩ theorem disjoin_manyOneReducible {α β γ} [Primcodable α] [Primcodable β] [Primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} : p ≤₀ r → q ≤₀ r → (p ⊕' q) ≤₀ r | ⟨f, c₁, h₁⟩, ⟨g, c₂, h₂⟩ => ⟨Sum.elim f g, Computable.id.sum_casesOn (c₁.comp Computable.snd).to₂ (c₂.comp Computable.snd).to₂, fun x => by cases x <;> [apply h₁; apply h₂]⟩ theorem disjoin_le {α β γ} [Primcodable α] [Primcodable β] [Primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} : (p ⊕' q) ≤₀ r ↔ p ≤₀ r ∧ q ≤₀ r := ⟨fun h => ⟨OneOneReducible.disjoin_left.to_many_one.trans h, OneOneReducible.disjoin_right.to_many_one.trans h⟩, fun ⟨h₁, h₂⟩ => disjoin_manyOneReducible h₁ h₂⟩ variable {α : Type u} [Primcodable α] [Inhabited α] variable {β : Type v} [Primcodable β] [Inhabited β] variable {γ : Type w} [Primcodable γ] [Inhabited γ] /-- Computable and injective mapping of predicates to sets of natural numbers. -/ def toNat (p : Set α) : Set ℕ := { n | p ((Encodable.decode (α := α) n).getD default) } @[simp] theorem toNat_manyOneReducible {p : Set α} : toNat p ≤₀ p := ⟨fun n => (Encodable.decode (α := α) n).getD default, Computable.option_getD Computable.decode (Computable.const _), fun _ => Iff.rfl⟩ @[simp] theorem manyOneReducible_toNat {p : Set α} : p ≤₀ toNat p := ⟨Encodable.encode, Computable.encode, by simp [toNat, setOf]⟩ @[simp] theorem manyOneReducible_toNat_toNat {p : Set α} {q : Set β} : toNat p ≤₀ toNat q ↔ p ≤₀ q := ⟨fun h => manyOneReducible_toNat.trans (h.trans toNat_manyOneReducible), fun h => toNat_manyOneReducible.trans (h.trans manyOneReducible_toNat)⟩ @[simp] theorem toNat_manyOneEquiv {p : Set α} : ManyOneEquiv (toNat p) p := by simp [ManyOneEquiv] @[simp] theorem manyOneEquiv_toNat (p : Set α) (q : Set β) : ManyOneEquiv (toNat p) (toNat q) ↔ ManyOneEquiv p q := by simp [ManyOneEquiv] /-- A many-one degree is an equivalence class of sets up to many-one equivalence. -/ def ManyOneDegree : Type := Quotient (⟨ManyOneEquiv, equivalence_of_manyOneEquiv⟩ : Setoid (Set ℕ)) namespace ManyOneDegree /-- The many-one degree of a set on a primcodable type. -/ def of (p : α → Prop) : ManyOneDegree := Quotient.mk'' (toNat p) @[elab_as_elim] protected theorem ind_on {C : ManyOneDegree → Prop} (d : ManyOneDegree) (h : ∀ p : Set ℕ, C (of p)) : C d := Quotient.inductionOn' d h /-- Lifts a function on sets of natural numbers to many-one degrees. -/ -- @[elab_as_elim] -- Porting note: unexpected eliminator resulting type protected abbrev liftOn {φ} (d : ManyOneDegree) (f : Set ℕ → φ) (h : ∀ p q, ManyOneEquiv p q → f p = f q) : φ := Quotient.liftOn' d f h @[simp] protected theorem liftOn_eq {φ} (p : Set ℕ) (f : Set ℕ → φ) (h : ∀ p q, ManyOneEquiv p q → f p = f q) : (of p).liftOn f h = f p := rfl /-- Lifts a binary function on sets of natural numbers to many-one degrees. -/ @[reducible, simp] -- @[elab_as_elim] -- Porting note: unexpected eliminator resulting type protected def liftOn₂ {φ} (d₁ d₂ : ManyOneDegree) (f : Set ℕ → Set ℕ → φ) (h : ∀ p₁ p₂ q₁ q₂, ManyOneEquiv p₁ p₂ → ManyOneEquiv q₁ q₂ → f p₁ q₁ = f p₂ q₂) : φ := d₁.liftOn (fun p => d₂.liftOn (f p) fun q₁ q₂ hq => h _ _ _ _ (by rfl) hq) (by intro p₁ p₂ hp induction d₂ using ManyOneDegree.ind_on apply h · assumption · rfl) @[simp] protected theorem liftOn₂_eq {φ} (p q : Set ℕ) (f : Set ℕ → Set ℕ → φ) (h : ∀ p₁ p₂ q₁ q₂, ManyOneEquiv p₁ p₂ → ManyOneEquiv q₁ q₂ → f p₁ q₁ = f p₂ q₂) : (of p).liftOn₂ (of q) f h = f p q := rfl @[simp] theorem of_eq_of {p : α → Prop} {q : β → Prop} : of p = of q ↔ ManyOneEquiv p q := by rw [of, of, Quotient.eq''] unfold Setoid.r simp instance instInhabited : Inhabited ManyOneDegree := ⟨of (∅ : Set ℕ)⟩ /-- For many-one degrees `d₁` and `d₂`, `d₁ ≤ d₂` if the sets in `d₁` are many-one reducible to the sets in `d₂`. -/ instance instLE : LE ManyOneDegree := ⟨fun d₁ d₂ => ManyOneDegree.liftOn₂ d₁ d₂ (· ≤₀ ·) fun _p₁ _p₂ _q₁ _q₂ hp hq => propext (hp.le_congr_left.trans hq.le_congr_right)⟩ @[simp] theorem of_le_of {p : α → Prop} {q : β → Prop} : of p ≤ of q ↔ p ≤₀ q := manyOneReducible_toNat_toNat private theorem le_refl (d : ManyOneDegree) : d ≤ d := by induction d using ManyOneDegree.ind_on; simp; rfl private theorem le_antisymm {d₁ d₂ : ManyOneDegree} : d₁ ≤ d₂ → d₂ ≤ d₁ → d₁ = d₂ := by induction d₁ using ManyOneDegree.ind_on induction d₂ using ManyOneDegree.ind_on intro hp hq simp_all only [ManyOneEquiv, of_le_of, of_eq_of, true_and_iff] private theorem le_trans {d₁ d₂ d₃ : ManyOneDegree} : d₁ ≤ d₂ → d₂ ≤ d₃ → d₁ ≤ d₃ := by induction d₁ using ManyOneDegree.ind_on induction d₂ using ManyOneDegree.ind_on induction d₃ using ManyOneDegree.ind_on apply ManyOneReducible.trans instance instPartialOrder : PartialOrder ManyOneDegree where le := (· ≤ ·) le_refl := le_refl le_trans _ _ _ := le_trans le_antisymm _ _ := le_antisymm /-- The join of two degrees, induced by the disjoint union of two underlying sets. -/ instance instAdd : Add ManyOneDegree := ⟨fun d₁ d₂ => d₁.liftOn₂ d₂ (fun a b => of (a ⊕' b)) (by rintro a b c d ⟨hl₁, hr₁⟩ ⟨hl₂, hr₂⟩ rw [of_eq_of] exact ⟨disjoin_manyOneReducible (hl₁.trans OneOneReducible.disjoin_left.to_many_one) (hl₂.trans OneOneReducible.disjoin_right.to_many_one), disjoin_manyOneReducible (hr₁.trans OneOneReducible.disjoin_left.to_many_one) (hr₂.trans OneOneReducible.disjoin_right.to_many_one)⟩)⟩ @[simp] theorem add_of (p : Set α) (q : Set β) : of (p ⊕' q) = of p + of q := of_eq_of.mpr ⟨disjoin_manyOneReducible (manyOneReducible_toNat.trans OneOneReducible.disjoin_left.to_many_one) (manyOneReducible_toNat.trans OneOneReducible.disjoin_right.to_many_one), disjoin_manyOneReducible (toNat_manyOneReducible.trans OneOneReducible.disjoin_left.to_many_one) (toNat_manyOneReducible.trans OneOneReducible.disjoin_right.to_many_one)⟩ @[simp] protected theorem add_le {d₁ d₂ d₃ : ManyOneDegree} : d₁ + d₂ ≤ d₃ ↔ d₁ ≤ d₃ ∧ d₂ ≤ d₃ := by induction d₁ using ManyOneDegree.ind_on induction d₂ using ManyOneDegree.ind_on induction d₃ using ManyOneDegree.ind_on simpa only [← add_of, of_le_of] using disjoin_le @[simp] protected theorem le_add_left (d₁ d₂ : ManyOneDegree) : d₁ ≤ d₁ + d₂ := (ManyOneDegree.add_le.1 (le_refl _)).1 @[simp] protected theorem le_add_right (d₁ d₂ : ManyOneDegree) : d₂ ≤ d₁ + d₂ := (ManyOneDegree.add_le.1 (le_refl _)).2 instance instSemilatticeSup : SemilatticeSup ManyOneDegree := { ManyOneDegree.instPartialOrder with sup := (· + ·) le_sup_left := ManyOneDegree.le_add_left le_sup_right := ManyOneDegree.le_add_right sup_le := fun _ _ _ h₁ h₂ => ManyOneDegree.add_le.2 ⟨h₁, h₂⟩ } end ManyOneDegree
Computability\RegularExpressions.lean
/- Copyright (c) 2020 Fox Thomson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Fox Thomson -/ import Mathlib.Computability.Language import Mathlib.Tactic.AdaptationNote /-! # Regular Expressions This file contains the formal definition for regular expressions and basic lemmas. Note these are regular expressions in terms of formal language theory. Note this is different to regex's used in computer science such as the POSIX standard. ## TODO * Show that this regular expressions and DFA/NFA's are equivalent. -/ -- Porting note: this has been commented out -- * `attribute [pattern] has_mul.mul` has been added into this file, it could be moved. open List Set open Computability universe u variable {α β γ : Type*} /-- This is the definition of regular expressions. The names used here is to mirror the definition of a Kleene algebra (https://en.wikipedia.org/wiki/Kleene_algebra). * `0` (`zero`) matches nothing * `1` (`epsilon`) matches only the empty string * `char a` matches only the string 'a' * `star P` matches any finite concatenation of strings which match `P` * `P + Q` (`plus P Q`) matches anything which match `P` or `Q` * `P * Q` (`comp P Q`) matches `x ++ y` if `x` matches `P` and `y` matches `Q` -/ inductive RegularExpression (α : Type u) : Type u | zero : RegularExpression α | epsilon : RegularExpression α | char : α → RegularExpression α | plus : RegularExpression α → RegularExpression α → RegularExpression α | comp : RegularExpression α → RegularExpression α → RegularExpression α | star : RegularExpression α → RegularExpression α -- Porting note: `simpNF` gets grumpy about how the `foo_def`s below can simplify these.. attribute [nolint simpNF] RegularExpression.zero.sizeOf_spec attribute [nolint simpNF] RegularExpression.epsilon.sizeOf_spec attribute [nolint simpNF] RegularExpression.plus.sizeOf_spec attribute [nolint simpNF] RegularExpression.plus.injEq attribute [nolint simpNF] RegularExpression.comp.injEq attribute [nolint simpNF] RegularExpression.comp.sizeOf_spec namespace RegularExpression variable {a b : α} instance : Inhabited (RegularExpression α) := ⟨zero⟩ instance : Add (RegularExpression α) := ⟨plus⟩ instance : Mul (RegularExpression α) := ⟨comp⟩ instance : One (RegularExpression α) := ⟨epsilon⟩ instance : Zero (RegularExpression α) := ⟨zero⟩ instance : Pow (RegularExpression α) ℕ := ⟨fun n r => npowRec r n⟩ -- Porting note: declaration in an imported module --attribute [match_pattern] Mul.mul @[simp] theorem zero_def : (zero : RegularExpression α) = 0 := rfl @[simp] theorem one_def : (epsilon : RegularExpression α) = 1 := rfl @[simp] theorem plus_def (P Q : RegularExpression α) : plus P Q = P + Q := rfl @[simp] theorem comp_def (P Q : RegularExpression α) : comp P Q = P * Q := rfl -- Porting note: `matches` is reserved, moved to `matches'` #adaptation_note /-- around nightly-2024-02-25, we need to write `comp x y` in the pattern `comp P Q`, instead of `x * y`. -/ /-- `matches' P` provides a language which contains all strings that `P` matches -/ -- Porting note: was '@[simp] but removed based on -- https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/simpNF.20issues.20in.20Computability.2ERegularExpressions.20!4.232306/near/328355362 def matches' : RegularExpression α → Language α | 0 => 0 | 1 => 1 | char a => {[a]} | P + Q => P.matches' + Q.matches' | comp P Q => P.matches' * Q.matches' | star P => P.matches'∗ @[simp] theorem matches'_zero : (0 : RegularExpression α).matches' = 0 := rfl @[simp] theorem matches'_epsilon : (1 : RegularExpression α).matches' = 1 := rfl @[simp] theorem matches'_char (a : α) : (char a).matches' = {[a]} := rfl @[simp] theorem matches'_add (P Q : RegularExpression α) : (P + Q).matches' = P.matches' + Q.matches' := rfl @[simp] theorem matches'_mul (P Q : RegularExpression α) : (P * Q).matches' = P.matches' * Q.matches' := rfl @[simp] theorem matches'_pow (P : RegularExpression α) : ∀ n : ℕ, (P ^ n).matches' = P.matches' ^ n | 0 => matches'_epsilon | n + 1 => (matches'_mul _ _).trans <| Eq.trans (congrFun (congrArg HMul.hMul (matches'_pow P n)) (matches' P)) (pow_succ _ n).symm @[simp] theorem matches'_star (P : RegularExpression α) : P.star.matches' = P.matches'∗ := rfl #adaptation_note /-- around nightly-2024-02-25, we need to write `comp x y` in the pattern `comp P Q`, instead of `x * y`. -/ /-- `matchEpsilon P` is true if and only if `P` matches the empty string -/ def matchEpsilon : RegularExpression α → Bool | 0 => false | 1 => true | char _ => false | P + Q => P.matchEpsilon || Q.matchEpsilon | comp P Q => P.matchEpsilon && Q.matchEpsilon | star _P => true section DecidableEq variable [DecidableEq α] #adaptation_note /-- around nightly-2024-02-25, we need to write `comp x y` in the pattern `comp P Q`, instead of `x * y`. -/ /-- `P.deriv a` matches `x` if `P` matches `a :: x`, the Brzozowski derivative of `P` with respect to `a` -/ def deriv : RegularExpression α → α → RegularExpression α | 0, _ => 0 | 1, _ => 0 | char a₁, a₂ => if a₁ = a₂ then 1 else 0 | P + Q, a => deriv P a + deriv Q a | comp P Q, a => if P.matchEpsilon then deriv P a * Q + deriv Q a else deriv P a * Q | star P, a => deriv P a * star P @[simp] theorem deriv_zero (a : α) : deriv 0 a = 0 := rfl @[simp] theorem deriv_one (a : α) : deriv 1 a = 0 := rfl @[simp] theorem deriv_char_self (a : α) : deriv (char a) a = 1 := if_pos rfl @[simp] theorem deriv_char_of_ne (h : a ≠ b) : deriv (char a) b = 0 := if_neg h @[simp] theorem deriv_add (P Q : RegularExpression α) (a : α) : deriv (P + Q) a = deriv P a + deriv Q a := rfl @[simp] theorem deriv_star (P : RegularExpression α) (a : α) : deriv P.star a = deriv P a * star P := rfl /-- `P.rmatch x` is true if and only if `P` matches `x`. This is a computable definition equivalent to `matches'`. -/ def rmatch : RegularExpression α → List α → Bool | P, [] => matchEpsilon P | P, a :: as => rmatch (P.deriv a) as @[simp] theorem zero_rmatch (x : List α) : rmatch 0 x = false := by induction x <;> simp [rmatch, matchEpsilon, *] theorem one_rmatch_iff (x : List α) : rmatch 1 x ↔ x = [] := by induction x <;> simp [rmatch, matchEpsilon, *] theorem char_rmatch_iff (a : α) (x : List α) : rmatch (char a) x ↔ x = [a] := by cases' x with _ x · exact of_decide_eq_true rfl cases' x with head tail · rw [rmatch, deriv] split_ifs · tauto · simp [List.singleton_inj]; tauto · rw [rmatch, rmatch, deriv] split_ifs with h · simp only [deriv_one, zero_rmatch, cons.injEq, and_false] · simp only [deriv_zero, zero_rmatch, cons.injEq, and_false] theorem add_rmatch_iff (P Q : RegularExpression α) (x : List α) : (P + Q).rmatch x ↔ P.rmatch x ∨ Q.rmatch x := by induction' x with _ _ ih generalizing P Q · simp only [rmatch, matchEpsilon, Bool.or_eq_true_iff] · repeat rw [rmatch] rw [deriv_add] exact ih _ _ theorem mul_rmatch_iff (P Q : RegularExpression α) (x : List α) : (P * Q).rmatch x ↔ ∃ t u : List α, x = t ++ u ∧ P.rmatch t ∧ Q.rmatch u := by induction' x with a x ih generalizing P Q · rw [rmatch]; simp only [matchEpsilon] constructor · intro h refine ⟨[], [], rfl, ?_⟩ rw [rmatch, rmatch] rwa [Bool.and_eq_true_iff] at h · rintro ⟨t, u, h₁, h₂⟩ cases' List.append_eq_nil.1 h₁.symm with ht hu subst ht subst hu repeat rw [rmatch] at h₂ simp [h₂] · rw [rmatch]; simp only [deriv] split_ifs with hepsilon · rw [add_rmatch_iff, ih] constructor · rintro (⟨t, u, _⟩ | h) · exact ⟨a :: t, u, by tauto⟩ · exact ⟨[], a :: x, rfl, hepsilon, h⟩ · rintro ⟨t, u, h, hP, hQ⟩ cases' t with b t · right rw [List.nil_append] at h rw [← h] at hQ exact hQ · left rw [List.cons_append, List.cons_eq_cons] at h refine ⟨t, u, h.2, ?_, hQ⟩ rw [rmatch] at hP convert hP exact h.1 · rw [ih] constructor <;> rintro ⟨t, u, h, hP, hQ⟩ · exact ⟨a :: t, u, by tauto⟩ · cases' t with b t · contradiction · rw [List.cons_append, List.cons_eq_cons] at h refine ⟨t, u, h.2, ?_, hQ⟩ rw [rmatch] at hP convert hP exact h.1 theorem star_rmatch_iff (P : RegularExpression α) : ∀ x : List α, (star P).rmatch x ↔ ∃ S : List (List α), x = S.join ∧ ∀ t ∈ S, t ≠ [] ∧ P.rmatch t := fun x => by have IH := fun t (_h : List.length t < List.length x) => star_rmatch_iff P t clear star_rmatch_iff constructor · cases' x with a x · intro _h use []; dsimp; tauto · rw [rmatch, deriv, mul_rmatch_iff] rintro ⟨t, u, hs, ht, hu⟩ have hwf : u.length < (List.cons a x).length := by rw [hs, List.length_cons, List.length_append] omega rw [IH _ hwf] at hu rcases hu with ⟨S', hsum, helem⟩ use (a :: t) :: S' constructor · simp [hs, hsum] · intro t' ht' cases ht' with | head ht' => simp only [ne_eq, not_false_iff, true_and, rmatch] exact ht | tail _ ht' => exact helem t' ht' · rintro ⟨S, hsum, helem⟩ cases' x with a x · rfl · rw [rmatch, deriv, mul_rmatch_iff] cases' S with t' U · exact ⟨[], [], by tauto⟩ · cases' t' with b t · simp only [forall_eq_or_imp, List.mem_cons] at helem simp only [eq_self_iff_true, not_true, Ne, false_and_iff] at helem simp only [List.join, List.cons_append, List.cons_eq_cons] at hsum refine ⟨t, U.join, hsum.2, ?_, ?_⟩ · specialize helem (b :: t) (by simp) rw [rmatch] at helem convert helem.2 exact hsum.1 · have hwf : U.join.length < (List.cons a x).length := by rw [hsum.1, hsum.2] simp only [List.length_append, List.length_join, List.length] omega rw [IH _ hwf] refine ⟨U, rfl, fun t h => helem t ?_⟩ right assumption termination_by t => (P, t.length) @[simp] theorem rmatch_iff_matches' (P : RegularExpression α) (x : List α) : P.rmatch x ↔ x ∈ P.matches' := by induction P generalizing x with | zero => rw [zero_def, zero_rmatch] tauto | epsilon => rw [one_def, one_rmatch_iff, matches'_epsilon, Language.mem_one] | char => rw [char_rmatch_iff] rfl | plus _ _ ih₁ ih₂ => rw [plus_def, add_rmatch_iff, ih₁, ih₂] rfl | comp P Q ih₁ ih₂ => simp only [comp_def, mul_rmatch_iff, matches'_mul, Language.mem_mul, *] tauto | star _ ih => simp only [star_rmatch_iff, matches'_star, ih, Language.mem_kstar_iff_exists_nonempty, and_comm] instance (P : RegularExpression α) : DecidablePred (· ∈ P.matches') := fun _ ↦ decidable_of_iff _ (rmatch_iff_matches' _ _) end DecidableEq #adaptation_note /-- around nightly-2024-02-25, we need to write `comp x y` in the pattern `comp P Q`, instead of `x * y`. -/ /-- Map the alphabet of a regular expression. -/ @[simp] def map (f : α → β) : RegularExpression α → RegularExpression β | 0 => 0 | 1 => 1 | char a => char (f a) | R + S => map f R + map f S | comp R S => map f R * map f S | star R => star (map f R) @[simp] protected theorem map_pow (f : α → β) (P : RegularExpression α) : ∀ n : ℕ, map f (P ^ n) = map f P ^ n | 0 => by dsimp; rfl | n + 1 => (congr_arg (· * map f P) (RegularExpression.map_pow f P n) : _) #adaptation_note /-- around nightly-2024-02-25, we need to write `comp x y` in the pattern `comp P Q`, instead of `x * y`. -/ @[simp] theorem map_id : ∀ P : RegularExpression α, P.map id = P | 0 => rfl | 1 => rfl | char a => rfl | R + S => by simp_rw [map, map_id] | comp R S => by simp_rw [map, map_id]; rfl | star R => by simp_rw [map, map_id] #adaptation_note /-- around nightly-2024-02-25, we need to write `comp x y` in the pattern `comp P Q`, instead of `x * y`. -/ @[simp] theorem map_map (g : β → γ) (f : α → β) : ∀ P : RegularExpression α, (P.map f).map g = P.map (g ∘ f) | 0 => rfl | 1 => rfl | char a => rfl | R + S => by simp only [map, Function.comp_apply, map_map] | comp R S => by simp only [map, Function.comp_apply, map_map] | star R => by simp only [map, Function.comp_apply, map_map] #adaptation_note /-- around nightly-2024-02-25, we need to write `comp x y` in the pattern `comp R S`, instead of `x * y` (and the `erw` was just `rw`). -/ /-- The language of the map is the map of the language. -/ @[simp] theorem matches'_map (f : α → β) : ∀ P : RegularExpression α, (P.map f).matches' = Language.map f P.matches' | 0 => (map_zero _).symm | 1 => (map_one _).symm | char a => by rw [eq_comm] exact image_singleton -- Porting note: the following close with last `rw` but not with `simp`? | R + S => by simp only [matches'_map, map, matches'_add]; rw [map_add] | comp R S => by simp only [matches'_map, map, matches'_mul]; erw [map_mul] | star R => by simp_rw [map, matches', matches'_map] rw [Language.kstar_eq_iSup_pow, Language.kstar_eq_iSup_pow] simp_rw [← map_pow] exact image_iUnion.symm end RegularExpression
Computability\TMComputable.lean
/- Copyright (c) 2020 Pim Spelier, Daan van Gent. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Pim Spelier, Daan van Gent -/ import Mathlib.Algebra.Polynomial.Basic import Mathlib.Algebra.Polynomial.Eval import Mathlib.Computability.Encoding import Mathlib.Computability.TuringMachine /-! # Computable functions This file contains the definition of a Turing machine with some finiteness conditions (bundling the definition of TM2 in `TuringMachine.lean`), a definition of when a TM gives a certain output (in a certain time), and the definition of computability (in polynomial time or any time function) of a function between two types that have an encoding (as in `Encoding.lean`). ## Main theorems - `idComputableInPolyTime` : a TM + a proof it computes the identity on a type in polytime. - `idComputable` : a TM + a proof it computes the identity on a type. ## Implementation notes To count the execution time of a Turing machine, we have decided to count the number of times the `step` function is used. Each step executes a statement (of type `Stmt`); this is a function, and generally contains multiple "fundamental" steps (pushing, popping, and so on). However, as functions only contain a finite number of executions and each one is executed at most once, this execution time is up to multiplication by a constant the amount of fundamental steps. -/ open Computability namespace Turing /-- A bundled TM2 (an equivalent of the classical Turing machine, defined starting from the namespace `Turing.TM2` in `TuringMachine.lean`), with an input and output stack, a main function, an initial state and some finiteness guarantees. -/ structure FinTM2 where /-- index type of stacks -/ {K : Type} [kDecidableEq : DecidableEq K] /-- A TM2 machine has finitely many stacks. -/ [kFin : Fintype K] /-- input resp. output stack -/ (k₀ k₁ : K) /-- type of stack elements -/ (Γ : K → Type) /-- type of function labels -/ (Λ : Type) /-- a main function: the initial function that is executed, given by its label -/ (main : Λ) /-- A TM2 machine has finitely many function labels. -/ [ΛFin : Fintype Λ] /-- type of states of the machine -/ (σ : Type) /-- the initial state of the machine -/ (initialState : σ) /-- a TM2 machine has finitely many internal states. -/ [σFin : Fintype σ] /-- Each internal stack is finite. -/ [Γk₀Fin : Fintype (Γ k₀)] /-- the program itself, i.e. one function for every function label -/ (m : Λ → Turing.TM2.Stmt Γ Λ σ) attribute [nolint docBlame] FinTM2.kDecidableEq namespace FinTM2 section variable (tm : FinTM2) instance decidableEqK : DecidableEq tm.K := tm.kDecidableEq instance inhabitedσ : Inhabited tm.σ := ⟨tm.initialState⟩ /-- The type of statements (functions) corresponding to this TM. -/ def Stmt : Type := Turing.TM2.Stmt tm.Γ tm.Λ tm.σ -- Porting note: The `deriving Inhabited` handler couldn't derive this. instance inhabitedStmt : Inhabited (Stmt tm) := inferInstanceAs (Inhabited (Turing.TM2.Stmt tm.Γ tm.Λ tm.σ)) /-- The type of configurations (functions) corresponding to this TM. -/ def Cfg : Type := Turing.TM2.Cfg tm.Γ tm.Λ tm.σ instance inhabitedCfg : Inhabited (Cfg tm) := Turing.TM2.Cfg.inhabited _ _ _ /-- The step function corresponding to this TM. -/ @[simp] def step : tm.Cfg → Option tm.Cfg := Turing.TM2.step tm.m end end FinTM2 /-- The initial configuration corresponding to a list in the input alphabet. -/ def initList (tm : FinTM2) (s : List (tm.Γ tm.k₀)) : tm.Cfg where l := Option.some tm.main var := tm.initialState stk k := @dite (List (tm.Γ k)) (k = tm.k₀) (tm.kDecidableEq k tm.k₀) (fun h => by rw [h]; exact s) fun _ => [] /-- The final configuration corresponding to a list in the output alphabet. -/ def haltList (tm : FinTM2) (s : List (tm.Γ tm.k₁)) : tm.Cfg where l := Option.none var := tm.initialState stk k := @dite (List (tm.Γ k)) (k = tm.k₁) (tm.kDecidableEq k tm.k₁) (fun h => by rw [h]; exact s) fun _ => [] /-- A "proof" of the fact that `f` eventually reaches `b` when repeatedly evaluated on `a`, remembering the number of steps it takes. -/ structure EvalsTo {σ : Type*} (f : σ → Option σ) (a : σ) (b : Option σ) where /-- number of steps taken -/ steps : ℕ evals_in_steps : (flip bind f)^[steps] a = b -- note: this cannot currently be used in `calc`, as the last two arguments must be `a` and `b`. -- If this is desired, this argument order can be changed, but this spelling is I think the most -- natural, so there is a trade-off that needs to be made here. A notation can get around this. /-- A "proof" of the fact that `f` eventually reaches `b` in at most `m` steps when repeatedly evaluated on `a`, remembering the number of steps it takes. -/ structure EvalsToInTime {σ : Type*} (f : σ → Option σ) (a : σ) (b : Option σ) (m : ℕ) extends EvalsTo f a b where steps_le_m : steps ≤ m /-- Reflexivity of `EvalsTo` in 0 steps. -/ -- @[refl] -- Porting note: `@[refl]` attribute only applies to lemmas proving `x ∼ x` in Lean4. def EvalsTo.refl {σ : Type*} (f : σ → Option σ) (a : σ) : EvalsTo f a a := ⟨0, rfl⟩ /-- Transitivity of `EvalsTo` in the sum of the numbers of steps. -/ @[trans] def EvalsTo.trans {σ : Type*} (f : σ → Option σ) (a : σ) (b : σ) (c : Option σ) (h₁ : EvalsTo f a b) (h₂ : EvalsTo f b c) : EvalsTo f a c := ⟨h₂.steps + h₁.steps, by rw [Function.iterate_add_apply, h₁.evals_in_steps, h₂.evals_in_steps]⟩ /-- Reflexivity of `EvalsToInTime` in 0 steps. -/ -- @[refl] -- Porting note: `@[refl]` attribute only applies to lemmas proving `x ∼ x` in Lean4. def EvalsToInTime.refl {σ : Type*} (f : σ → Option σ) (a : σ) : EvalsToInTime f a a 0 := ⟨EvalsTo.refl f a, le_refl 0⟩ /-- Transitivity of `EvalsToInTime` in the sum of the numbers of steps. -/ @[trans] def EvalsToInTime.trans {σ : Type*} (f : σ → Option σ) (m₁ : ℕ) (m₂ : ℕ) (a : σ) (b : σ) (c : Option σ) (h₁ : EvalsToInTime f a b m₁) (h₂ : EvalsToInTime f b c m₂) : EvalsToInTime f a c (m₂ + m₁) := ⟨EvalsTo.trans f a b c h₁.toEvalsTo h₂.toEvalsTo, add_le_add h₂.steps_le_m h₁.steps_le_m⟩ /-- A proof of tm outputting l' when given l. -/ def TM2Outputs (tm : FinTM2) (l : List (tm.Γ tm.k₀)) (l' : Option (List (tm.Γ tm.k₁))) := EvalsTo tm.step (initList tm l) ((Option.map (haltList tm)) l') /-- A proof of tm outputting l' when given l in at most m steps. -/ def TM2OutputsInTime (tm : FinTM2) (l : List (tm.Γ tm.k₀)) (l' : Option (List (tm.Γ tm.k₁))) (m : ℕ) := EvalsToInTime tm.step (initList tm l) ((Option.map (haltList tm)) l') m /-- The forgetful map, forgetting the upper bound on the number of steps. -/ def TM2OutputsInTime.toTM2Outputs {tm : FinTM2} {l : List (tm.Γ tm.k₀)} {l' : Option (List (tm.Γ tm.k₁))} {m : ℕ} (h : TM2OutputsInTime tm l l' m) : TM2Outputs tm l l' := h.toEvalsTo /-- A (bundled TM2) Turing machine with input alphabet equivalent to `Γ₀` and output alphabet equivalent to `Γ₁`. -/ structure TM2ComputableAux (Γ₀ Γ₁ : Type) where /-- the underlying bundled TM2 -/ tm : FinTM2 /-- the input alphabet is equivalent to `Γ₀` -/ inputAlphabet : tm.Γ tm.k₀ ≃ Γ₀ /-- the output alphabet is equivalent to `Γ₁` -/ outputAlphabet : tm.Γ tm.k₁ ≃ Γ₁ /-- A Turing machine + a proof it outputs `f`. -/ structure TM2Computable {α β : Type} (ea : FinEncoding α) (eb : FinEncoding β) (f : α → β) extends TM2ComputableAux ea.Γ eb.Γ where /-- a proof this machine outputs `f` -/ outputsFun : ∀ a, TM2Outputs tm (List.map inputAlphabet.invFun (ea.encode a)) (Option.some ((List.map outputAlphabet.invFun) (eb.encode (f a)))) /-- A Turing machine + a time function + a proof it outputs `f` in at most `time(input.length)` steps. -/ structure TM2ComputableInTime {α β : Type} (ea : FinEncoding α) (eb : FinEncoding β) (f : α → β) extends TM2ComputableAux ea.Γ eb.Γ where /-- a time function -/ time : ℕ → ℕ /-- proof this machine outputs `f` in at most `time(input.length)` steps -/ outputsFun : ∀ a, TM2OutputsInTime tm (List.map inputAlphabet.invFun (ea.encode a)) (Option.some ((List.map outputAlphabet.invFun) (eb.encode (f a)))) (time (ea.encode a).length) /-- A Turing machine + a polynomial time function + a proof it outputs `f` in at most `time(input.length)` steps. -/ structure TM2ComputableInPolyTime {α β : Type} (ea : FinEncoding α) (eb : FinEncoding β) (f : α → β) extends TM2ComputableAux ea.Γ eb.Γ where /-- a polynomial time function -/ time : Polynomial ℕ /-- proof that this machine outputs `f` in at most `time(input.length)` steps -/ outputsFun : ∀ a, TM2OutputsInTime tm (List.map inputAlphabet.invFun (ea.encode a)) (Option.some ((List.map outputAlphabet.invFun) (eb.encode (f a)))) (time.eval (ea.encode a).length) /-- A forgetful map, forgetting the time bound on the number of steps. -/ def TM2ComputableInTime.toTM2Computable {α β : Type} {ea : FinEncoding α} {eb : FinEncoding β} {f : α → β} (h : TM2ComputableInTime ea eb f) : TM2Computable ea eb f := ⟨h.toTM2ComputableAux, fun a => TM2OutputsInTime.toTM2Outputs (h.outputsFun a)⟩ /-- A forgetful map, forgetting that the time function is polynomial. -/ def TM2ComputableInPolyTime.toTM2ComputableInTime {α β : Type} {ea : FinEncoding α} {eb : FinEncoding β} {f : α → β} (h : TM2ComputableInPolyTime ea eb f) : TM2ComputableInTime ea eb f := ⟨h.toTM2ComputableAux, fun n => h.time.eval n, h.outputsFun⟩ open Turing.TM2.Stmt /-- A Turing machine computing the identity on α. -/ def idComputer {α : Type} (ea : FinEncoding α) : FinTM2 where K := Unit k₀ := ⟨⟩ k₁ := ⟨⟩ Γ _ := ea.Γ Λ := Unit main := ⟨⟩ σ := Unit initialState := ⟨⟩ Γk₀Fin := ea.ΓFin m _ := halt instance inhabitedFinTM2 : Inhabited FinTM2 := ⟨idComputer Computability.inhabitedFinEncoding.default⟩ noncomputable section /-- A proof that the identity map on α is computable in polytime. -/ def idComputableInPolyTime {α : Type} (ea : FinEncoding α) : @TM2ComputableInPolyTime α α ea ea id where tm := idComputer ea inputAlphabet := Equiv.cast rfl outputAlphabet := Equiv.cast rfl time := 1 outputsFun _ := { steps := 1 evals_in_steps := rfl steps_le_m := by simp only [Polynomial.eval_one, le_refl] } instance inhabitedTM2ComputableInPolyTime : Inhabited (TM2ComputableInPolyTime (default : FinEncoding Bool) default id) := ⟨idComputableInPolyTime Computability.inhabitedFinEncoding.default⟩ instance inhabitedTM2OutputsInTime : Inhabited (TM2OutputsInTime (idComputer finEncodingBoolBool) (List.map (Equiv.cast rfl).invFun [false]) (some (List.map (Equiv.cast rfl).invFun [false])) (Polynomial.eval 1 1)) := ⟨(idComputableInPolyTime finEncodingBoolBool).outputsFun false⟩ instance inhabitedTM2Outputs : Inhabited (TM2Outputs (idComputer finEncodingBoolBool) (List.map (Equiv.cast rfl).invFun [false]) (some (List.map (Equiv.cast rfl).invFun [false]))) := ⟨TM2OutputsInTime.toTM2Outputs Turing.inhabitedTM2OutputsInTime.default⟩ instance inhabitedEvalsToInTime : Inhabited (EvalsToInTime (fun _ : Unit => some ⟨⟩) ⟨⟩ (some ⟨⟩) 0) := ⟨EvalsToInTime.refl _ _⟩ instance inhabitedTM2EvalsTo : Inhabited (EvalsTo (fun _ : Unit => some ⟨⟩) ⟨⟩ (some ⟨⟩)) := ⟨EvalsTo.refl _ _⟩ /-- A proof that the identity map on α is computable in time. -/ def idComputableInTime {α : Type} (ea : FinEncoding α) : @TM2ComputableInTime α α ea ea id := TM2ComputableInPolyTime.toTM2ComputableInTime <| idComputableInPolyTime ea instance inhabitedTM2ComputableInTime : Inhabited (TM2ComputableInTime finEncodingBoolBool finEncodingBoolBool id) := ⟨idComputableInTime Computability.inhabitedFinEncoding.default⟩ /-- A proof that the identity map on α is computable. -/ def idComputable {α : Type} (ea : FinEncoding α) : @TM2Computable α α ea ea id := TM2ComputableInTime.toTM2Computable <| idComputableInTime ea instance inhabitedTM2Computable : Inhabited (TM2Computable finEncodingBoolBool finEncodingBoolBool id) := ⟨idComputable Computability.inhabitedFinEncoding.default⟩ instance inhabitedTM2ComputableAux : Inhabited (TM2ComputableAux Bool Bool) := ⟨(default : TM2Computable finEncodingBoolBool finEncodingBoolBool id).toTM2ComputableAux⟩ end end Turing
Computability\TMToPartrec.lean
/- Copyright (c) 2020 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Computability.Halting import Mathlib.Computability.TuringMachine import Mathlib.Data.Num.Lemmas import Mathlib.Tactic.DeriveFintype /-! # Modelling partial recursive functions using Turing machines This file defines a simplified basis for partial recursive functions, and a `Turing.TM2` model Turing machine for evaluating these functions. This amounts to a constructive proof that every `Partrec` function can be evaluated by a Turing machine. ## Main definitions * `ToPartrec.Code`: a simplified basis for partial recursive functions, valued in `List ℕ →. List ℕ`. * `ToPartrec.Code.eval`: semantics for a `ToPartrec.Code` program * `PartrecToTM2.tr`: A TM2 turing machine which can evaluate `code` programs -/ open Mathlib (Vector) open Function (update) open Relation namespace Turing /-! ## A simplified basis for partrec This section constructs the type `Code`, which is a data type of programs with `List ℕ` input and output, with enough expressivity to write any partial recursive function. The primitives are: * `zero'` appends a `0` to the input. That is, `zero' v = 0 :: v`. * `succ` returns the successor of the head of the input, defaulting to zero if there is no head: * `succ [] = [1]` * `succ (n :: v) = [n + 1]` * `tail` returns the tail of the input * `tail [] = []` * `tail (n :: v) = v` * `cons f fs` calls `f` and `fs` on the input and conses the results: * `cons f fs v = (f v).head :: fs v` * `comp f g` calls `f` on the output of `g`: * `comp f g v = f (g v)` * `case f g` cases on the head of the input, calling `f` or `g` depending on whether it is zero or a successor (similar to `Nat.casesOn`). * `case f g [] = f []` * `case f g (0 :: v) = f v` * `case f g (n+1 :: v) = g (n :: v)` * `fix f` calls `f` repeatedly, using the head of the result of `f` to decide whether to call `f` again or finish: * `fix f v = []` if `f v = []` * `fix f v = w` if `f v = 0 :: w` * `fix f v = fix f w` if `f v = n+1 :: w` (the exact value of `n` is discarded) This basis is convenient because it is closer to the Turing machine model - the key operations are splitting and merging of lists of unknown length, while the messy `n`-ary composition operation from the traditional basis for partial recursive functions is absent - but it retains a compositional semantics. The first step in transitioning to Turing machines is to make a sequential evaluator for this basis, which we take up in the next section. -/ namespace ToPartrec /-- The type of codes for primitive recursive functions. Unlike `Nat.Partrec.Code`, this uses a set of operations on `List ℕ`. See `Code.eval` for a description of the behavior of the primitives. -/ inductive Code | zero' | succ | tail | cons : Code → Code → Code | comp : Code → Code → Code | case : Code → Code → Code | fix : Code → Code deriving DecidableEq, Inhabited /-- The semantics of the `Code` primitives, as partial functions `List ℕ →. List ℕ`. By convention we functions that return a single result return a singleton `[n]`, or in some cases `n :: v` where `v` will be ignored by a subsequent function. * `zero'` appends a `0` to the input. That is, `zero' v = 0 :: v`. * `succ` returns the successor of the head of the input, defaulting to zero if there is no head: * `succ [] = [1]` * `succ (n :: v) = [n + 1]` * `tail` returns the tail of the input * `tail [] = []` * `tail (n :: v) = v` * `cons f fs` calls `f` and `fs` on the input and conses the results: * `cons f fs v = (f v).head :: fs v` * `comp f g` calls `f` on the output of `g`: * `comp f g v = f (g v)` * `case f g` cases on the head of the input, calling `f` or `g` depending on whether it is zero or a successor (similar to `Nat.casesOn`). * `case f g [] = f []` * `case f g (0 :: v) = f v` * `case f g (n+1 :: v) = g (n :: v)` * `fix f` calls `f` repeatedly, using the head of the result of `f` to decide whether to call `f` again or finish: * `fix f v = []` if `f v = []` * `fix f v = w` if `f v = 0 :: w` * `fix f v = fix f w` if `f v = n+1 :: w` (the exact value of `n` is discarded) -/ def Code.eval : Code → List ℕ →. List ℕ | Code.zero' => fun v => pure (0 :: v) | Code.succ => fun v => pure [v.headI.succ] | Code.tail => fun v => pure v.tail | Code.cons f fs => fun v => do let n ← Code.eval f v let ns ← Code.eval fs v pure (n.headI :: ns) | Code.comp f g => fun v => g.eval v >>= f.eval | Code.case f g => fun v => v.headI.rec (f.eval v.tail) fun y _ => g.eval (y::v.tail) | Code.fix f => PFun.fix fun v => (f.eval v).map fun v => if v.headI = 0 then Sum.inl v.tail else Sum.inr v.tail namespace Code /- Porting note: The equation lemma of `eval` is too strong; it simplifies terms like the LHS of `pred_eval`. Even `eqns` can't fix this. We removed `simp` attr from `eval` and prepare new simp lemmas for `eval`. -/ @[simp] theorem zero'_eval : zero'.eval = fun v => pure (0 :: v) := by simp [eval] @[simp] theorem succ_eval : succ.eval = fun v => pure [v.headI.succ] := by simp [eval] @[simp] theorem tail_eval : tail.eval = fun v => pure v.tail := by simp [eval] @[simp] theorem cons_eval (f fs) : (cons f fs).eval = fun v => do { let n ← Code.eval f v let ns ← Code.eval fs v pure (n.headI :: ns) } := by simp [eval] @[simp] theorem comp_eval (f g) : (comp f g).eval = fun v => g.eval v >>= f.eval := by simp [eval] @[simp] theorem case_eval (f g) : (case f g).eval = fun v => v.headI.rec (f.eval v.tail) fun y _ => g.eval (y::v.tail) := by simp [eval] @[simp] theorem fix_eval (f) : (fix f).eval = PFun.fix fun v => (f.eval v).map fun v => if v.headI = 0 then Sum.inl v.tail else Sum.inr v.tail := by simp [eval] /-- `nil` is the constant nil function: `nil v = []`. -/ def nil : Code := tail.comp succ @[simp] theorem nil_eval (v) : nil.eval v = pure [] := by simp [nil] /-- `id` is the identity function: `id v = v`. -/ def id : Code := tail.comp zero' @[simp] theorem id_eval (v) : id.eval v = pure v := by simp [id] /-- `head` gets the head of the input list: `head [] = [0]`, `head (n :: v) = [n]`. -/ def head : Code := cons id nil @[simp] theorem head_eval (v) : head.eval v = pure [v.headI] := by simp [head] /-- `zero` is the constant zero function: `zero v = [0]`. -/ def zero : Code := cons zero' nil @[simp] theorem zero_eval (v) : zero.eval v = pure [0] := by simp [zero] /-- `pred` returns the predecessor of the head of the input: `pred [] = [0]`, `pred (0 :: v) = [0]`, `pred (n+1 :: v) = [n]`. -/ def pred : Code := case zero head @[simp] theorem pred_eval (v) : pred.eval v = pure [v.headI.pred] := by simp [pred]; cases v.headI <;> simp /-- `rfind f` performs the function of the `rfind` primitive of partial recursive functions. `rfind f v` returns the smallest `n` such that `(f (n :: v)).head = 0`. It is implemented as: rfind f v = pred (fix (fun (n::v) => f (n::v) :: n+1 :: v) (0 :: v)) The idea is that the initial state is `0 :: v`, and the `fix` keeps `n :: v` as its internal state; it calls `f (n :: v)` as the exit test and `n+1 :: v` as the next state. At the end we get `n+1 :: v` where `n` is the desired output, and `pred (n+1 :: v) = [n]` returns the result. -/ def rfind (f : Code) : Code := comp pred <| comp (fix <| cons f <| cons succ tail) zero' /-- `prec f g` implements the `prec` (primitive recursion) operation of partial recursive functions. `prec f g` evaluates as: * `prec f g [] = [f []]` * `prec f g (0 :: v) = [f v]` * `prec f g (n+1 :: v) = [g (n :: prec f g (n :: v) :: v)]` It is implemented as: G (a :: b :: IH :: v) = (b :: a+1 :: b-1 :: g (a :: IH :: v) :: v) F (0 :: f_v :: v) = (f_v :: v) F (n+1 :: f_v :: v) = (fix G (0 :: n :: f_v :: v)).tail.tail prec f g (a :: v) = [(F (a :: f v :: v)).head] Because `fix` always evaluates its body at least once, we must special case the `0` case to avoid calling `g` more times than necessary (which could be bad if `g` diverges). If the input is `0 :: v`, then `F (0 :: f v :: v) = (f v :: v)` so we return `[f v]`. If the input is `n+1 :: v`, we evaluate the function from the bottom up, with initial state `0 :: n :: f v :: v`. The first number counts up, providing arguments for the applications to `g`, while the second number counts down, providing the exit condition (this is the initial `b` in the return value of `G`, which is stripped by `fix`). After the `fix` is complete, the final state is `n :: 0 :: res :: v` where `res` is the desired result, and the rest reduces this to `[res]`. -/ def prec (f g : Code) : Code := let G := cons tail <| cons succ <| cons (comp pred tail) <| cons (comp g <| cons id <| comp tail tail) <| comp tail <| comp tail tail let F := case id <| comp (comp (comp tail tail) (fix G)) zero' cons (comp F (cons head <| cons (comp f tail) tail)) nil attribute [-simp] Part.bind_eq_bind Part.map_eq_map Part.pure_eq_some theorem exists_code.comp {m n} {f : Vector ℕ n →. ℕ} {g : Fin n → Vector ℕ m →. ℕ} (hf : ∃ c : Code, ∀ v : Vector ℕ n, c.eval v.1 = pure <$> f v) (hg : ∀ i, ∃ c : Code, ∀ v : Vector ℕ m, c.eval v.1 = pure <$> g i v) : ∃ c : Code, ∀ v : Vector ℕ m, c.eval v.1 = pure <$> ((Vector.mOfFn fun i => g i v) >>= f) := by rsuffices ⟨cg, hg⟩ : ∃ c : Code, ∀ v : Vector ℕ m, c.eval v.1 = Subtype.val <$> Vector.mOfFn fun i => g i v · obtain ⟨cf, hf⟩ := hf exact ⟨cf.comp cg, fun v => by simp [hg, hf, map_bind, seq_bind_eq, Function.comp] rfl⟩ clear hf f; induction' n with n IH · exact ⟨nil, fun v => by simp [Vector.mOfFn, Bind.bind]; rfl⟩ · obtain ⟨cg, hg₁⟩ := hg 0 obtain ⟨cl, hl⟩ := IH fun i => hg i.succ exact ⟨cons cg cl, fun v => by simp [Vector.mOfFn, hg₁, map_bind, seq_bind_eq, bind_assoc, (· ∘ ·), hl] rfl⟩ theorem exists_code {n} {f : Vector ℕ n →. ℕ} (hf : Nat.Partrec' f) : ∃ c : Code, ∀ v : Vector ℕ n, c.eval v.1 = pure <$> f v := by induction hf with | prim hf => induction hf with | zero => exact ⟨zero', fun ⟨[], _⟩ => rfl⟩ | succ => exact ⟨succ, fun ⟨[v], _⟩ => rfl⟩ | get i => refine Fin.succRec (fun n => ?_) (fun n i IH => ?_) i · exact ⟨head, fun ⟨List.cons a as, _⟩ => by simp [Bind.bind]; rfl⟩ · obtain ⟨c, h⟩ := IH exact ⟨c.comp tail, fun v => by simpa [← Vector.get_tail, Bind.bind] using h v.tail⟩ | comp g hf hg IHf IHg => simpa [Part.bind_eq_bind] using exists_code.comp IHf IHg | @prec n f g _ _ IHf IHg => obtain ⟨cf, hf⟩ := IHf obtain ⟨cg, hg⟩ := IHg simp only [Part.map_eq_map, Part.map_some, PFun.coe_val] at hf hg refine ⟨prec cf cg, fun v => ?_⟩ rw [← v.cons_head_tail] specialize hf v.tail replace hg := fun a b => hg (a ::ᵥ b ::ᵥ v.tail) simp only [Vector.cons_val, Vector.tail_val] at hf hg simp only [Part.map_eq_map, Part.map_some, Vector.cons_val, Vector.tail_cons, Vector.head_cons, PFun.coe_val, Vector.tail_val] simp only [← Part.pure_eq_some] at hf hg ⊢ induction' v.head with n _ <;> simp [prec, hf, Part.bind_assoc, ← Part.bind_some_eq_map, Part.bind_some, show ∀ x, pure x = [x] from fun _ => rfl, Bind.bind, Functor.map] suffices ∀ a b, a + b = n → (n.succ :: 0 :: g (n ::ᵥ Nat.rec (f v.tail) (fun y IH => g (y ::ᵥ IH ::ᵥ v.tail)) n ::ᵥ v.tail) :: v.val.tail : List ℕ) ∈ PFun.fix (fun v : List ℕ => Part.bind (cg.eval (v.headI :: v.tail.tail)) (fun x => Part.some (if v.tail.headI = 0 then Sum.inl (v.headI.succ :: v.tail.headI.pred :: x.headI :: v.tail.tail.tail : List ℕ) else Sum.inr (v.headI.succ :: v.tail.headI.pred :: x.headI :: v.tail.tail.tail)))) (a :: b :: Nat.rec (f v.tail) (fun y IH => g (y ::ᵥ IH ::ᵥ v.tail)) a :: v.val.tail) by erw [Part.eq_some_iff.2 (this 0 n (zero_add n))] simp only [List.headI, Part.bind_some, List.tail_cons] intro a b e induction' b with b IH generalizing a · refine PFun.mem_fix_iff.2 (Or.inl <| Part.eq_some_iff.1 ?_) simp only [hg, ← e, Part.bind_some, List.tail_cons, pure] rfl · refine PFun.mem_fix_iff.2 (Or.inr ⟨_, ?_, IH (a + 1) (by rwa [add_right_comm])⟩) simp only [hg, eval, Part.bind_some, Nat.rec_add_one, List.tail_nil, List.tail_cons, pure] exact Part.mem_some_iff.2 rfl | comp g _ _ IHf IHg => exact exists_code.comp IHf IHg | @rfind n f _ IHf => obtain ⟨cf, hf⟩ := IHf; refine ⟨rfind cf, fun v => ?_⟩ replace hf := fun a => hf (a ::ᵥ v) simp only [Part.map_eq_map, Part.map_some, Vector.cons_val, PFun.coe_val, show ∀ x, pure x = [x] from fun _ => rfl] at hf ⊢ refine Part.ext fun x => ?_ simp only [rfind, Part.bind_eq_bind, Part.pure_eq_some, Part.map_eq_map, Part.bind_some, exists_prop, cons_eval, comp_eval, fix_eval, tail_eval, succ_eval, zero'_eval, List.headI_nil, List.headI_cons, pred_eval, Part.map_some, false_eq_decide_iff, Part.mem_bind_iff, List.length, Part.mem_map_iff, Nat.mem_rfind, List.tail_nil, List.tail_cons, true_eq_decide_iff, Part.mem_some_iff, Part.map_bind] constructor · rintro ⟨v', h1, rfl⟩ suffices ∀ v₁ : List ℕ, v' ∈ PFun.fix (fun v => (cf.eval v).bind fun y => Part.some <| if y.headI = 0 then Sum.inl (v.headI.succ :: v.tail) else Sum.inr (v.headI.succ :: v.tail)) v₁ → ∀ n, (v₁ = n :: v.val) → (∀ m < n, ¬f (m ::ᵥ v) = 0) → ∃ a : ℕ, (f (a ::ᵥ v) = 0 ∧ ∀ {m : ℕ}, m < a → ¬f (m ::ᵥ v) = 0) ∧ [a] = [v'.headI.pred] by exact this _ h1 0 rfl (by rintro _ ⟨⟩) clear h1 intro v₀ h1 refine PFun.fixInduction h1 fun v₁ h2 IH => ?_ clear h1 rintro n rfl hm have := PFun.mem_fix_iff.1 h2 simp only [hf, Part.bind_some] at this split_ifs at this with h · simp only [List.headI_nil, List.headI_cons, exists_false, or_false_iff, Part.mem_some_iff, List.tail_cons, false_and_iff, Sum.inl.injEq] at this subst this exact ⟨_, ⟨h, @(hm)⟩, rfl⟩ · refine IH (n.succ::v.val) (by simp_all) _ rfl fun m h' => ?_ obtain h | rfl := Nat.lt_succ_iff_lt_or_eq.1 h' exacts [hm _ h, h] · rintro ⟨n, ⟨hn, hm⟩, rfl⟩ refine ⟨n.succ::v.1, ?_, rfl⟩ have : (n.succ::v.1 : List ℕ) ∈ PFun.fix (fun v => (cf.eval v).bind fun y => Part.some <| if y.headI = 0 then Sum.inl (v.headI.succ :: v.tail) else Sum.inr (v.headI.succ :: v.tail)) (n::v.val) := PFun.mem_fix_iff.2 (Or.inl (by simp [hf, hn])) generalize (n.succ :: v.1 : List ℕ) = w at this ⊢ clear hn induction' n with n IH · exact this refine IH (fun {m} h' => hm (Nat.lt_succ_of_lt h')) (PFun.mem_fix_iff.2 (Or.inr ⟨_, ?_, this⟩)) simp only [hf, hm n.lt_succ_self, Part.bind_some, List.headI, eq_self_iff_true, if_false, Part.mem_some_iff, and_self_iff, List.tail_cons] end Code /-! ## From compositional semantics to sequential semantics Our initial sequential model is designed to be as similar as possible to the compositional semantics in terms of its primitives, but it is a sequential semantics, meaning that rather than defining an `eval c : List ℕ →. List ℕ` function for each program, defined by recursion on programs, we have a type `Cfg` with a step function `step : Cfg → Option cfg` that provides a deterministic evaluation order. In order to do this, we introduce the notion of a *continuation*, which can be viewed as a `Code` with a hole in it where evaluation is currently taking place. Continuations can be assigned a `List ℕ →. List ℕ` semantics as well, with the interpretation being that given a `List ℕ` result returned from the code in the hole, the remainder of the program will evaluate to a `List ℕ` final value. The continuations are: * `halt`: the empty continuation: the hole is the whole program, whatever is returned is the final result. In our notation this is just `_`. * `cons₁ fs v k`: evaluating the first part of a `cons`, that is `k (_ :: fs v)`, where `k` is the outer continuation. * `cons₂ ns k`: evaluating the second part of a `cons`: `k (ns.headI :: _)`. (Technically we don't need to hold on to all of `ns` here since we are already committed to taking the head, but this is more regular.) * `comp f k`: evaluating the first part of a composition: `k (f _)`. * `fix f k`: waiting for the result of `f` in a `fix f` expression: `k (if _.headI = 0 then _.tail else fix f (_.tail))` The type `Cfg` of evaluation states is: * `ret k v`: we have received a result, and are now evaluating the continuation `k` with result `v`; that is, `k v` where `k` is ready to evaluate. * `halt v`: we are done and the result is `v`. The main theorem of this section is that for each code `c`, the state `stepNormal c halt v` steps to `v'` in finitely many steps if and only if `Code.eval c v = some v'`. -/ /-- The type of continuations, built up during evaluation of a `Code` expression. -/ inductive Cont | halt | cons₁ : Code → List ℕ → Cont → Cont | cons₂ : List ℕ → Cont → Cont | comp : Code → Cont → Cont | fix : Code → Cont → Cont deriving Inhabited /-- The semantics of a continuation. -/ def Cont.eval : Cont → List ℕ →. List ℕ | Cont.halt => pure | Cont.cons₁ fs as k => fun v => do let ns ← Code.eval fs as Cont.eval k (v.headI :: ns) | Cont.cons₂ ns k => fun v => Cont.eval k (ns.headI :: v) | Cont.comp f k => fun v => Code.eval f v >>= Cont.eval k | Cont.fix f k => fun v => if v.headI = 0 then k.eval v.tail else f.fix.eval v.tail >>= k.eval /-- The set of configurations of the machine: * `halt v`: The machine is about to stop and `v : List ℕ` is the result. * `ret k v`: The machine is about to pass `v : List ℕ` to continuation `k : Cont`. We don't have a state corresponding to normal evaluation because these are evaluated immediately to a `ret` "in zero steps" using the `stepNormal` function. -/ inductive Cfg | halt : List ℕ → Cfg | ret : Cont → List ℕ → Cfg deriving Inhabited /-- Evaluating `c : Code` in a continuation `k : Cont` and input `v : List ℕ`. This goes by recursion on `c`, building an augmented continuation and a value to pass to it. * `zero' v = 0 :: v` evaluates immediately, so we return it to the parent continuation * `succ v = [v.headI.succ]` evaluates immediately, so we return it to the parent continuation * `tail v = v.tail` evaluates immediately, so we return it to the parent continuation * `cons f fs v = (f v).headI :: fs v` requires two sub-evaluations, so we evaluate `f v` in the continuation `k (_.headI :: fs v)` (called `Cont.cons₁ fs v k`) * `comp f g v = f (g v)` requires two sub-evaluations, so we evaluate `g v` in the continuation `k (f _)` (called `Cont.comp f k`) * `case f g v = v.head.casesOn (f v.tail) (fun n => g (n :: v.tail))` has the information needed to evaluate the case statement, so we do that and transition to either `f v` or `g (n :: v.tail)`. * `fix f v = let v' := f v; if v'.headI = 0 then k v'.tail else fix f v'.tail` needs to first evaluate `f v`, so we do that and leave the rest for the continuation (called `Cont.fix f k`) -/ def stepNormal : Code → Cont → List ℕ → Cfg | Code.zero' => fun k v => Cfg.ret k (0::v) | Code.succ => fun k v => Cfg.ret k [v.headI.succ] | Code.tail => fun k v => Cfg.ret k v.tail | Code.cons f fs => fun k v => stepNormal f (Cont.cons₁ fs v k) v | Code.comp f g => fun k v => stepNormal g (Cont.comp f k) v | Code.case f g => fun k v => v.headI.rec (stepNormal f k v.tail) fun y _ => stepNormal g k (y::v.tail) | Code.fix f => fun k v => stepNormal f (Cont.fix f k) v /-- Evaluating a continuation `k : Cont` on input `v : List ℕ`. This is the second part of evaluation, when we receive results from continuations built by `stepNormal`. * `Cont.halt v = v`, so we are done and transition to the `Cfg.halt v` state * `Cont.cons₁ fs as k v = k (v.headI :: fs as)`, so we evaluate `fs as` now with the continuation `k (v.headI :: _)` (called `cons₂ v k`). * `Cont.cons₂ ns k v = k (ns.headI :: v)`, where we now have everything we need to evaluate `ns.headI :: v`, so we return it to `k`. * `Cont.comp f k v = k (f v)`, so we call `f v` with `k` as the continuation. * `Cont.fix f k v = k (if v.headI = 0 then k v.tail else fix f v.tail)`, where `v` is a value, so we evaluate the if statement and either call `k` with `v.tail`, or call `fix f v` with `k` as the continuation (which immediately calls `f` with `Cont.fix f k` as the continuation). -/ def stepRet : Cont → List ℕ → Cfg | Cont.halt, v => Cfg.halt v | Cont.cons₁ fs as k, v => stepNormal fs (Cont.cons₂ v k) as | Cont.cons₂ ns k, v => stepRet k (ns.headI :: v) | Cont.comp f k, v => stepNormal f k v | Cont.fix f k, v => if v.headI = 0 then stepRet k v.tail else stepNormal f (Cont.fix f k) v.tail /-- If we are not done (in `Cfg.halt` state), then we must be still stuck on a continuation, so this main loop calls `stepRet` with the new continuation. The overall `step` function transitions from one `Cfg` to another, only halting at the `Cfg.halt` state. -/ def step : Cfg → Option Cfg | Cfg.halt _ => none | Cfg.ret k v => some (stepRet k v) /-- In order to extract a compositional semantics from the sequential execution behavior of configurations, we observe that continuations have a monoid structure, with `Cont.halt` as the unit and `Cont.then` as the multiplication. `Cont.then k₁ k₂` runs `k₁` until it halts, and then takes the result of `k₁` and passes it to `k₂`. We will not prove it is associative (although it is), but we are instead interested in the associativity law `k₂ (eval c k₁) = eval c (k₁.then k₂)`. This holds at both the sequential and compositional levels, and allows us to express running a machine without the ambient continuation and relate it to the original machine's evaluation steps. In the literature this is usually where one uses Turing machines embedded inside other Turing machines, but this approach allows us to avoid changing the ambient type `Cfg` in the middle of the recursion. -/ def Cont.then : Cont → Cont → Cont | Cont.halt => fun k' => k' | Cont.cons₁ fs as k => fun k' => Cont.cons₁ fs as (k.then k') | Cont.cons₂ ns k => fun k' => Cont.cons₂ ns (k.then k') | Cont.comp f k => fun k' => Cont.comp f (k.then k') | Cont.fix f k => fun k' => Cont.fix f (k.then k') theorem Cont.then_eval {k k' : Cont} {v} : (k.then k').eval v = k.eval v >>= k'.eval := by induction' k with _ _ _ _ _ _ _ _ _ k_ih _ _ k_ih generalizing v <;> simp only [Cont.eval, Cont.then, bind_assoc, pure_bind, *] · simp only [← k_ih] · split_ifs <;> [rfl; simp only [← k_ih, bind_assoc]] /-- The `then k` function is a "configuration homomorphism". Its operation on states is to append `k` to the continuation of a `Cfg.ret` state, and to run `k` on `v` if we are in the `Cfg.halt v` state. -/ def Cfg.then : Cfg → Cont → Cfg | Cfg.halt v => fun k' => stepRet k' v | Cfg.ret k v => fun k' => Cfg.ret (k.then k') v /-- The `stepNormal` function respects the `then k'` homomorphism. Note that this is an exact equality, not a simulation; the original and embedded machines move in lock-step until the embedded machine reaches the halt state. -/ theorem stepNormal_then (c) (k k' : Cont) (v) : stepNormal c (k.then k') v = (stepNormal c k v).then k' := by induction c generalizing k v with simp only [Cont.then, stepNormal, *] | cons c c' ih _ => rw [← ih, Cont.then] | comp c c' _ ih' => rw [← ih', Cont.then] | case => cases v.headI <;> simp only [Nat.rec_zero] | fix c ih => rw [← ih, Cont.then] | _ => simp only [Cfg.then] /-- The `stepRet` function respects the `then k'` homomorphism. Note that this is an exact equality, not a simulation; the original and embedded machines move in lock-step until the embedded machine reaches the halt state. -/ theorem stepRet_then {k k' : Cont} {v} : stepRet (k.then k') v = (stepRet k v).then k' := by induction k generalizing v with simp only [Cont.then, stepRet, *] | cons₁ => rw [← stepNormal_then] rfl | comp => rw [← stepNormal_then] | fix _ _ k_ih => split_ifs · rw [← k_ih] · rw [← stepNormal_then] rfl | _ => simp only [Cfg.then] /-- This is a temporary definition, because we will prove in `code_is_ok` that it always holds. It asserts that `c` is semantically correct; that is, for any `k` and `v`, `eval (stepNormal c k v) = eval (Cfg.ret k (Code.eval c v))`, as an equality of partial values (so one diverges iff the other does). In particular, we can let `k = Cont.halt`, and then this asserts that `stepNormal c Cont.halt v` evaluates to `Cfg.halt (Code.eval c v)`. -/ def Code.Ok (c : Code) := ∀ k v, Turing.eval step (stepNormal c k v) = Code.eval c v >>= fun v => Turing.eval step (Cfg.ret k v) theorem Code.Ok.zero {c} (h : Code.Ok c) {v} : Turing.eval step (stepNormal c Cont.halt v) = Cfg.halt <$> Code.eval c v := by rw [h, ← bind_pure_comp]; congr; funext v exact Part.eq_some_iff.2 (mem_eval.2 ⟨ReflTransGen.single rfl, rfl⟩) theorem stepNormal.is_ret (c k v) : ∃ k' v', stepNormal c k v = Cfg.ret k' v' := by induction c generalizing k v with | cons _f fs IHf _IHfs => apply IHf | comp f _g _IHf IHg => apply IHg | case f g IHf IHg => rw [stepNormal] simp only [] cases v.headI <;> [apply IHf; apply IHg] | fix f IHf => apply IHf | _ => exact ⟨_, _, rfl⟩ theorem cont_eval_fix {f k v} (fok : Code.Ok f) : Turing.eval step (stepNormal f (Cont.fix f k) v) = f.fix.eval v >>= fun v => Turing.eval step (Cfg.ret k v) := by refine Part.ext fun x => ?_ simp only [Part.bind_eq_bind, Part.mem_bind_iff] constructor · suffices ∀ c, x ∈ eval step c → ∀ v c', c = Cfg.then c' (Cont.fix f k) → Reaches step (stepNormal f Cont.halt v) c' → ∃ v₁ ∈ f.eval v, ∃ v₂ ∈ if List.headI v₁ = 0 then pure v₁.tail else f.fix.eval v₁.tail, x ∈ eval step (Cfg.ret k v₂) by intro h obtain ⟨v₁, hv₁, v₂, hv₂, h₃⟩ := this _ h _ _ (stepNormal_then _ Cont.halt _ _) ReflTransGen.refl refine ⟨v₂, PFun.mem_fix_iff.2 ?_, h₃⟩ simp only [Part.eq_some_iff.2 hv₁, Part.map_some] split_ifs at hv₂ ⊢ · rw [Part.mem_some_iff.1 hv₂] exact Or.inl (Part.mem_some _) · exact Or.inr ⟨_, Part.mem_some _, hv₂⟩ refine fun c he => evalInduction he fun y h IH => ?_ rintro v (⟨v'⟩ | ⟨k', v'⟩) rfl hr <;> rw [Cfg.then] at h IH <;> simp only [] at h IH · have := mem_eval.2 ⟨hr, rfl⟩ rw [fok, Part.bind_eq_bind, Part.mem_bind_iff] at this obtain ⟨v'', h₁, h₂⟩ := this rw [reaches_eval] at h₂ swap · exact ReflTransGen.single rfl cases Part.mem_unique h₂ (mem_eval.2 ⟨ReflTransGen.refl, rfl⟩) refine ⟨v', h₁, ?_⟩ rw [stepRet] at h revert h by_cases he : v'.headI = 0 <;> simp only [exists_prop, if_pos, if_false, he] <;> intro h · refine ⟨_, Part.mem_some _, ?_⟩ rw [reaches_eval] · exact h exact ReflTransGen.single rfl · obtain ⟨k₀, v₀, e₀⟩ := stepNormal.is_ret f Cont.halt v'.tail have e₁ := stepNormal_then f Cont.halt (Cont.fix f k) v'.tail rw [e₀, Cont.then, Cfg.then] at e₁ simp only [] at e₁ obtain ⟨v₁, hv₁, v₂, hv₂, h₃⟩ := IH (stepRet (k₀.then (Cont.fix f k)) v₀) (by rw [stepRet, if_neg he, e₁]; rfl) v'.tail _ stepRet_then (by apply ReflTransGen.single; rw [e₀]; rfl) refine ⟨_, PFun.mem_fix_iff.2 ?_, h₃⟩ simp only [Part.eq_some_iff.2 hv₁, Part.map_some, Part.mem_some_iff] split_ifs at hv₂ ⊢ <;> [exact Or.inl (congr_arg Sum.inl (Part.mem_some_iff.1 hv₂)); exact Or.inr ⟨_, rfl, hv₂⟩] · exact IH _ rfl _ _ stepRet_then (ReflTransGen.tail hr rfl) · rintro ⟨v', he, hr⟩ rw [reaches_eval] at hr swap · exact ReflTransGen.single rfl refine PFun.fixInduction he fun v (he : v' ∈ f.fix.eval v) IH => ?_ rw [fok, Part.bind_eq_bind, Part.mem_bind_iff] obtain he | ⟨v'', he₁', _⟩ := PFun.mem_fix_iff.1 he · obtain ⟨v', he₁, he₂⟩ := (Part.mem_map_iff _).1 he split_ifs at he₂ with h; cases he₂ refine ⟨_, he₁, ?_⟩ rw [reaches_eval] swap · exact ReflTransGen.single rfl rwa [stepRet, if_pos h] · obtain ⟨v₁, he₁, he₂⟩ := (Part.mem_map_iff _).1 he₁' split_ifs at he₂ with h; cases he₂ clear he₁' refine ⟨_, he₁, ?_⟩ rw [reaches_eval] swap · exact ReflTransGen.single rfl rw [stepRet, if_neg h] exact IH v₁.tail ((Part.mem_map_iff _).2 ⟨_, he₁, if_neg h⟩) theorem code_is_ok (c) : Code.Ok c := by induction c with (intro k v; rw [stepNormal]) | cons f fs IHf IHfs => rw [Code.eval, IHf] simp only [bind_assoc, Cont.eval, pure_bind]; congr; funext v rw [reaches_eval]; swap · exact ReflTransGen.single rfl rw [stepRet, IHfs]; congr; funext v' refine Eq.trans (b := eval step (stepRet (Cont.cons₂ v k) v')) ?_ (Eq.symm ?_) <;> exact reaches_eval (ReflTransGen.single rfl) | comp f g IHf IHg => rw [Code.eval, IHg] simp only [bind_assoc, Cont.eval, pure_bind]; congr; funext v rw [reaches_eval]; swap · exact ReflTransGen.single rfl rw [stepRet, IHf] | case f g IHf IHg => simp only [Code.eval] cases v.headI <;> simp only [Nat.rec_zero, Part.bind_eq_bind] <;> [apply IHf; apply IHg] | fix f IHf => rw [cont_eval_fix IHf] | _ => simp only [Code.eval, pure_bind] theorem stepNormal_eval (c v) : eval step (stepNormal c Cont.halt v) = Cfg.halt <$> c.eval v := (code_is_ok c).zero theorem stepRet_eval {k v} : eval step (stepRet k v) = Cfg.halt <$> k.eval v := by induction k generalizing v with | halt => simp only [mem_eval, Cont.eval, map_pure] exact Part.eq_some_iff.2 (mem_eval.2 ⟨ReflTransGen.refl, rfl⟩) | cons₁ fs as k IH => rw [Cont.eval, stepRet, code_is_ok] simp only [← bind_pure_comp, bind_assoc]; congr; funext v' rw [reaches_eval]; swap · exact ReflTransGen.single rfl rw [stepRet, IH, bind_pure_comp] | cons₂ ns k IH => rw [Cont.eval, stepRet]; exact IH | comp f k IH => rw [Cont.eval, stepRet, code_is_ok] simp only [← bind_pure_comp, bind_assoc]; congr; funext v' rw [reaches_eval]; swap · exact ReflTransGen.single rfl rw [IH, bind_pure_comp] | fix f k IH => rw [Cont.eval, stepRet]; simp only [bind_pure_comp] split_ifs; · exact IH simp only [← bind_pure_comp, bind_assoc, cont_eval_fix (code_is_ok _)] congr; funext; rw [bind_pure_comp, ← IH] exact reaches_eval (ReflTransGen.single rfl) end ToPartrec /-! ## Simulating sequentialized partial recursive functions in TM2 At this point we have a sequential model of partial recursive functions: the `Cfg` type and `step : Cfg → Option Cfg` function from the previous section. The key feature of this model is that it does a finite amount of computation (in fact, an amount which is statically bounded by the size of the program) between each step, and no individual step can diverge (unlike the compositional semantics, where every sub-part of the computation is potentially divergent). So we can utilize the same techniques as in the other TM simulations in `Computability.TuringMachine` to prove that each step corresponds to a finite number of steps in a lower level model. (We don't prove it here, but in anticipation of the complexity class P, the simulation is actually polynomial-time as well.) The target model is `Turing.TM2`, which has a fixed finite set of stacks, a bit of local storage, with programs selected from a potentially infinite (but finitely accessible) set of program positions, or labels `Λ`, each of which executes a finite sequence of basic stack commands. For this program we will need four stacks, each on an alphabet `Γ'` like so: inductive Γ' | consₗ | cons | bit0 | bit1 We represent a number as a bit sequence, lists of numbers by putting `cons` after each element, and lists of lists of natural numbers by putting `consₗ` after each list. For example: 0 ~> [] 1 ~> [bit1] 6 ~> [bit0, bit1, bit1] [1, 2] ~> [bit1, cons, bit0, bit1, cons] [[], [1, 2]] ~> [consₗ, bit1, cons, bit0, bit1, cons, consₗ] The four stacks are `main`, `rev`, `aux`, `stack`. In normal mode, `main` contains the input to the current program (a `List ℕ`) and `stack` contains data (a `List (List ℕ)`) associated to the current continuation, and in `ret` mode `main` contains the value that is being passed to the continuation and `stack` contains the data for the continuation. The `rev` and `aux` stacks are usually empty; `rev` is used to store reversed data when e.g. moving a value from one stack to another, while `aux` is used as a temporary for a `main`/`stack` swap that happens during `cons₁` evaluation. The only local store we need is `Option Γ'`, which stores the result of the last pop operation. (Most of our working data are natural numbers, which are too large to fit in the local store.) The continuations from the previous section are data-carrying, containing all the values that have been computed and are awaiting other arguments. In order to have only a finite number of continuations appear in the program so that they can be used in machine states, we separate the data part (anything with type `List ℕ`) from the `Cont` type, producing a `Cont'` type that lacks this information. The data is kept on the `stack` stack. Because we want to have subroutines for e.g. moving an entire stack to another place, we use an infinite inductive type `Λ'` so that we can execute a program and then return to do something else without having to define too many different kinds of intermediate states. (We must nevertheless prove that only finitely many labels are accessible.) The labels are: * `move p k₁ k₂ q`: move elements from stack `k₁` to `k₂` while `p` holds of the value being moved. The last element, that fails `p`, is placed in neither stack but left in the local store. At the end of the operation, `k₂` will have the elements of `k₁` in reverse order. Then do `q`. * `clear p k q`: delete elements from stack `k` until `p` is true. Like `move`, the last element is left in the local storage. Then do `q`. * `copy q`: Move all elements from `rev` to both `main` and `stack` (in reverse order), then do `q`. That is, it takes `(a, b, c, d)` to `(b.reverse ++ a, [], c, b.reverse ++ d)`. * `push k f q`: push `f s`, where `s` is the local store, to stack `k`, then do `q`. This is a duplicate of the `push` instruction that is part of the TM2 model, but by having a subroutine just for this purpose we can build up programs to execute inside a `goto` statement, where we have the flexibility to be general recursive. * `read (f : Option Γ' → Λ')`: go to state `f s` where `s` is the local store. Again this is only here for convenience. * `succ q`: perform a successor operation. Assuming `[n]` is encoded on `main` before, `[n+1]` will be on main after. This implements successor for binary natural numbers. * `pred q₁ q₂`: perform a predecessor operation or `case` statement. If `[]` is encoded on `main` before, then we transition to `q₁` with `[]` on main; if `(0 :: v)` is on `main` before then `v` will be on `main` after and we transition to `q₁`; and if `(n+1 :: v)` is on `main` before then `n :: v` will be on `main` after and we transition to `q₂`. * `ret k`: call continuation `k`. Each continuation has its own interpretation of the data in `stack` and sets up the data for the next continuation. * `ret (cons₁ fs k)`: `v :: KData` on `stack` and `ns` on `main`, and the next step expects `v` on `main` and `ns :: KData` on `stack`. So we have to do a little dance here with six reverse-moves using the `aux` stack to perform a three-point swap, each of which involves two reversals. * `ret (cons₂ k)`: `ns :: KData` is on `stack` and `v` is on `main`, and we have to put `ns.headI :: v` on `main` and `KData` on `stack`. This is done using the `head` subroutine. * `ret (fix f k)`: This stores no data, so we just check if `main` starts with `0` and if so, remove it and call `k`, otherwise `clear` the first value and call `f`. * `ret halt`: the stack is empty, and `main` has the output. Do nothing and halt. In addition to these basic states, we define some additional subroutines that are used in the above: * `push'`, `peek'`, `pop'` are special versions of the builtins that use the local store to supply inputs and outputs. * `unrev`: special case `move false rev main` to move everything from `rev` back to `main`. Used as a cleanup operation in several functions. * `moveExcl p k₁ k₂ q`: same as `move` but pushes the last value read back onto the source stack. * `move₂ p k₁ k₂ q`: double `move`, so that the result comes out in the right order at the target stack. Implemented as `moveExcl p k rev; move false rev k₂`. Assumes that neither `k₁` nor `k₂` is `rev` and `rev` is initially empty. * `head k q`: get the first natural number from stack `k` and reverse-move it to `rev`, then clear the rest of the list at `k` and then `unrev` to reverse-move the head value to `main`. This is used with `k = main` to implement regular `head`, i.e. if `v` is on `main` before then `[v.headI]` will be on `main` after; and also with `k = stack` for the `cons` operation, which has `v` on `main` and `ns :: KData` on `stack`, and results in `KData` on `stack` and `ns.headI :: v` on `main`. * `trNormal` is the main entry point, defining states that perform a given `code` computation. It mostly just dispatches to functions written above. The main theorem of this section is `tr_eval`, which asserts that for each that for each code `c`, the state `init c v` steps to `halt v'` in finitely many steps if and only if `Code.eval c v = some v'`. -/ namespace PartrecToTM2 section open ToPartrec /-- The alphabet for the stacks in the program. `bit0` and `bit1` are used to represent `ℕ` values as lists of binary digits, `cons` is used to separate `List ℕ` values, and `consₗ` is used to separate `List (List ℕ)` values. See the section documentation. -/ inductive Γ' | consₗ | cons | bit0 | bit1 deriving DecidableEq, Inhabited, Fintype /-- The four stacks used by the program. `main` is used to store the input value in `trNormal` mode and the output value in `Λ'.ret` mode, while `stack` is used to keep all the data for the continuations. `rev` is used to store reversed lists when transferring values between stacks, and `aux` is only used once in `cons₁`. See the section documentation. -/ inductive K' | main | rev | aux | stack deriving DecidableEq, Inhabited open K' /-- Continuations as in `ToPartrec.Cont` but with the data removed. This is done because we want the set of all continuations in the program to be finite (so that it can ultimately be encoded into the finite state machine of a Turing machine), but a continuation can handle a potentially infinite number of data values during execution. -/ inductive Cont' | halt | cons₁ : Code → Cont' → Cont' | cons₂ : Cont' → Cont' | comp : Code → Cont' → Cont' | fix : Code → Cont' → Cont' deriving DecidableEq, Inhabited /-- The set of program positions. We make extensive use of inductive types here to let us describe "subroutines"; for example `clear p k q` is a program that clears stack `k`, then does `q` where `q` is another label. In order to prevent this from resulting in an infinite number of distinct accessible states, we are careful to be non-recursive (although loops are okay). See the section documentation for a description of all the programs. -/ inductive Λ' | move (p : Γ' → Bool) (k₁ k₂ : K') (q : Λ') | clear (p : Γ' → Bool) (k : K') (q : Λ') | copy (q : Λ') | push (k : K') (s : Option Γ' → Option Γ') (q : Λ') | read (f : Option Γ' → Λ') | succ (q : Λ') | pred (q₁ q₂ : Λ') | ret (k : Cont') compile_inductive% Code compile_inductive% Cont' compile_inductive% K' compile_inductive% Λ' instance Λ'.instInhabited : Inhabited Λ' := ⟨Λ'.ret Cont'.halt⟩ instance Λ'.instDecidableEq : DecidableEq Λ' := fun a b => by induction a generalizing b <;> cases b <;> first | apply Decidable.isFalse; rintro ⟨⟨⟩⟩; done | exact decidable_of_iff' _ (by simp [Function.funext_iff]; rfl) /-- The type of TM2 statements used by this machine. -/ def Stmt' := TM2.Stmt (fun _ : K' => Γ') Λ' (Option Γ') deriving Inhabited /-- The type of TM2 configurations used by this machine. -/ def Cfg' := TM2.Cfg (fun _ : K' => Γ') Λ' (Option Γ') deriving Inhabited open TM2.Stmt /-- A predicate that detects the end of a natural number, either `Γ'.cons` or `Γ'.consₗ` (or implicitly the end of the list), for use in predicate-taking functions like `move` and `clear`. -/ @[simp] def natEnd : Γ' → Bool | Γ'.consₗ => true | Γ'.cons => true | _ => false /-- Pop a value from the stack and place the result in local store. -/ @[simp] def pop' (k : K') : Stmt' → Stmt' := pop k fun _ v => v /-- Peek a value from the stack and place the result in local store. -/ @[simp] def peek' (k : K') : Stmt' → Stmt' := peek k fun _ v => v /-- Push the value in the local store to the given stack. -/ @[simp] def push' (k : K') : Stmt' → Stmt' := push k fun x => x.iget /-- Move everything from the `rev` stack to the `main` stack (reversed). -/ def unrev := Λ'.move (fun _ => false) rev main /-- Move elements from `k₁` to `k₂` while `p` holds, with the last element being left on `k₁`. -/ def moveExcl (p k₁ k₂ q) := Λ'.move p k₁ k₂ <| Λ'.push k₁ id q /-- Move elements from `k₁` to `k₂` without reversion, by performing a double move via the `rev` stack. -/ def move₂ (p k₁ k₂ q) := moveExcl p k₁ rev <| Λ'.move (fun _ => false) rev k₂ q /-- Assuming `trList v` is on the front of stack `k`, remove it, and push `v.headI` onto `main`. See the section documentation. -/ def head (k : K') (q : Λ') : Λ' := Λ'.move natEnd k rev <| (Λ'.push rev fun _ => some Γ'.cons) <| Λ'.read fun s => (if s = some Γ'.consₗ then id else Λ'.clear (fun x => x = Γ'.consₗ) k) <| unrev q /-- The program that evaluates code `c` with continuation `k`. This expects an initial state where `trList v` is on `main`, `trContStack k` is on `stack`, and `aux` and `rev` are empty. See the section documentation for details. -/ @[simp] def trNormal : Code → Cont' → Λ' | Code.zero', k => (Λ'.push main fun _ => some Γ'.cons) <| Λ'.ret k | Code.succ, k => head main <| Λ'.succ <| Λ'.ret k | Code.tail, k => Λ'.clear natEnd main <| Λ'.ret k | Code.cons f fs, k => (Λ'.push stack fun _ => some Γ'.consₗ) <| Λ'.move (fun _ => false) main rev <| Λ'.copy <| trNormal f (Cont'.cons₁ fs k) | Code.comp f g, k => trNormal g (Cont'.comp f k) | Code.case f g, k => Λ'.pred (trNormal f k) (trNormal g k) | Code.fix f, k => trNormal f (Cont'.fix f k) /-- The main program. See the section documentation for details. -/ def tr : Λ' → Stmt' | Λ'.move p k₁ k₂ q => pop' k₁ <| branch (fun s => s.elim true p) (goto fun _ => q) (push' k₂ <| goto fun _ => Λ'.move p k₁ k₂ q) | Λ'.push k f q => branch (fun s => (f s).isSome) ((push k fun s => (f s).iget) <| goto fun _ => q) (goto fun _ => q) | Λ'.read q => goto q | Λ'.clear p k q => pop' k <| branch (fun s => s.elim true p) (goto fun _ => q) (goto fun _ => Λ'.clear p k q) | Λ'.copy q => pop' rev <| branch Option.isSome (push' main <| push' stack <| goto fun _ => Λ'.copy q) (goto fun _ => q) | Λ'.succ q => pop' main <| branch (fun s => s = some Γ'.bit1) ((push rev fun _ => Γ'.bit0) <| goto fun _ => Λ'.succ q) <| branch (fun s => s = some Γ'.cons) ((push main fun _ => Γ'.cons) <| (push main fun _ => Γ'.bit1) <| goto fun _ => unrev q) ((push main fun _ => Γ'.bit1) <| goto fun _ => unrev q) | Λ'.pred q₁ q₂ => pop' main <| branch (fun s => s = some Γ'.bit0) ((push rev fun _ => Γ'.bit1) <| goto fun _ => Λ'.pred q₁ q₂) <| branch (fun s => natEnd s.iget) (goto fun _ => q₁) (peek' main <| branch (fun s => natEnd s.iget) (goto fun _ => unrev q₂) ((push rev fun _ => Γ'.bit0) <| goto fun _ => unrev q₂)) | Λ'.ret (Cont'.cons₁ fs k) => goto fun _ => move₂ (fun _ => false) main aux <| move₂ (fun s => s = Γ'.consₗ) stack main <| move₂ (fun _ => false) aux stack <| trNormal fs (Cont'.cons₂ k) | Λ'.ret (Cont'.cons₂ k) => goto fun _ => head stack <| Λ'.ret k | Λ'.ret (Cont'.comp f k) => goto fun _ => trNormal f k | Λ'.ret (Cont'.fix f k) => pop' main <| goto fun s => cond (natEnd s.iget) (Λ'.ret k) <| Λ'.clear natEnd main <| trNormal f (Cont'.fix f k) | Λ'.ret Cont'.halt => (load fun _ => none) <| halt /- Porting note: The equation lemma of `tr` simplifies to `match` structures. To prevent this, we replace equation lemmas of `tr`. -/ theorem tr_move (p k₁ k₂ q) : tr (Λ'.move p k₁ k₂ q) = pop' k₁ (branch (fun s => s.elim true p) (goto fun _ => q) (push' k₂ <| goto fun _ => Λ'.move p k₁ k₂ q)) := rfl theorem tr_push (k f q) : tr (Λ'.push k f q) = branch (fun s => (f s).isSome) ((push k fun s => (f s).iget) <| goto fun _ => q) (goto fun _ => q) := rfl theorem tr_read (q) : tr (Λ'.read q) = goto q := rfl theorem tr_clear (p k q) : tr (Λ'.clear p k q) = pop' k (branch (fun s => s.elim true p) (goto fun _ => q) (goto fun _ => Λ'.clear p k q)) := rfl theorem tr_copy (q) : tr (Λ'.copy q) = pop' rev (branch Option.isSome (push' main <| push' stack <| goto fun _ => Λ'.copy q) (goto fun _ => q)) := rfl theorem tr_succ (q) : tr (Λ'.succ q) = pop' main (branch (fun s => s = some Γ'.bit1) ((push rev fun _ => Γ'.bit0) <| goto fun _ => Λ'.succ q) <| branch (fun s => s = some Γ'.cons) ((push main fun _ => Γ'.cons) <| (push main fun _ => Γ'.bit1) <| goto fun _ => unrev q) ((push main fun _ => Γ'.bit1) <| goto fun _ => unrev q)) := rfl theorem tr_pred (q₁ q₂) : tr (Λ'.pred q₁ q₂) = pop' main (branch (fun s => s = some Γ'.bit0) ((push rev fun _ => Γ'.bit1) <| goto fun _ => Λ'.pred q₁ q₂) <| branch (fun s => natEnd s.iget) (goto fun _ => q₁) (peek' main <| branch (fun s => natEnd s.iget) (goto fun _ => unrev q₂) ((push rev fun _ => Γ'.bit0) <| goto fun _ => unrev q₂))) := rfl theorem tr_ret_cons₁ (fs k) : tr (Λ'.ret (Cont'.cons₁ fs k)) = goto fun _ => move₂ (fun _ => false) main aux <| move₂ (fun s => s = Γ'.consₗ) stack main <| move₂ (fun _ => false) aux stack <| trNormal fs (Cont'.cons₂ k) := rfl theorem tr_ret_cons₂ (k) : tr (Λ'.ret (Cont'.cons₂ k)) = goto fun _ => head stack <| Λ'.ret k := rfl theorem tr_ret_comp (f k) : tr (Λ'.ret (Cont'.comp f k)) = goto fun _ => trNormal f k := rfl theorem tr_ret_fix (f k) : tr (Λ'.ret (Cont'.fix f k)) = pop' main (goto fun s => cond (natEnd s.iget) (Λ'.ret k) <| Λ'.clear natEnd main <| trNormal f (Cont'.fix f k)) := rfl theorem tr_ret_halt : tr (Λ'.ret Cont'.halt) = (load fun _ => none) halt := rfl attribute [eqns tr_move tr_push tr_read tr_clear tr_copy tr_succ tr_pred tr_ret_cons₁ tr_ret_cons₂ tr_ret_comp tr_ret_fix tr_ret_halt] tr attribute [simp] tr /-- Translating a `Cont` continuation to a `Cont'` continuation simply entails dropping all the data. This data is instead encoded in `trContStack` in the configuration. -/ def trCont : Cont → Cont' | Cont.halt => Cont'.halt | Cont.cons₁ c _ k => Cont'.cons₁ c (trCont k) | Cont.cons₂ _ k => Cont'.cons₂ (trCont k) | Cont.comp c k => Cont'.comp c (trCont k) | Cont.fix c k => Cont'.fix c (trCont k) /-- We use `PosNum` to define the translation of binary natural numbers. A natural number is represented as a little-endian list of `bit0` and `bit1` elements: 1 = [bit1] 2 = [bit0, bit1] 3 = [bit1, bit1] 4 = [bit0, bit0, bit1] In particular, this representation guarantees no trailing `bit0`'s at the end of the list. -/ def trPosNum : PosNum → List Γ' | PosNum.one => [Γ'.bit1] | PosNum.bit0 n => Γ'.bit0 :: trPosNum n | PosNum.bit1 n => Γ'.bit1 :: trPosNum n /-- We use `Num` to define the translation of binary natural numbers. Positive numbers are translated using `trPosNum`, and `trNum 0 = []`. So there are never any trailing `bit0`'s in a translated `Num`. 0 = [] 1 = [bit1] 2 = [bit0, bit1] 3 = [bit1, bit1] 4 = [bit0, bit0, bit1] -/ def trNum : Num → List Γ' | Num.zero => [] | Num.pos n => trPosNum n /-- Because we use binary encoding, we define `trNat` in terms of `trNum`, using `Num`, which are binary natural numbers. (We could also use `Nat.binaryRecOn`, but `Num` and `PosNum` make for easy inductions.) -/ def trNat (n : ℕ) : List Γ' := trNum n @[simp] theorem trNat_zero : trNat 0 = [] := by rw [trNat, Nat.cast_zero]; rfl theorem trNat_default : trNat default = [] := trNat_zero /-- Lists are translated with a `cons` after each encoded number. For example: [] = [] [0] = [cons] [1] = [bit1, cons] [6, 0] = [bit0, bit1, bit1, cons, cons] -/ @[simp] def trList : List ℕ → List Γ' | [] => [] | n::ns => trNat n ++ Γ'.cons :: trList ns /-- Lists of lists are translated with a `consₗ` after each encoded list. For example: [] = [] [[]] = [consₗ] [[], []] = [consₗ, consₗ] [[0]] = [cons, consₗ] [[1, 2], [0]] = [bit1, cons, bit0, bit1, cons, consₗ, cons, consₗ] -/ @[simp] def trLList : List (List ℕ) → List Γ' | [] => [] | l::ls => trList l ++ Γ'.consₗ :: trLList ls /-- The data part of a continuation is a list of lists, which is encoded on the `stack` stack using `trLList`. -/ @[simp] def contStack : Cont → List (List ℕ) | Cont.halt => [] | Cont.cons₁ _ ns k => ns :: contStack k | Cont.cons₂ ns k => ns :: contStack k | Cont.comp _ k => contStack k | Cont.fix _ k => contStack k /-- The data part of a continuation is a list of lists, which is encoded on the `stack` stack using `trLList`. -/ def trContStack (k : Cont) := trLList (contStack k) /-- This is the nondependent eliminator for `K'`, but we use it specifically here in order to represent the stack data as four lists rather than as a function `K' → List Γ'`, because this makes rewrites easier. The theorems `K'.elim_update_main` et. al. show how such a function is updated after an `update` to one of the components. -/ def K'.elim (a b c d : List Γ') : K' → List Γ' | K'.main => a | K'.rev => b | K'.aux => c | K'.stack => d -- The equation lemma of `elim` simplifies to `match` structures. theorem K'.elim_main (a b c d) : K'.elim a b c d K'.main = a := rfl theorem K'.elim_rev (a b c d) : K'.elim a b c d K'.rev = b := rfl theorem K'.elim_aux (a b c d) : K'.elim a b c d K'.aux = c := rfl theorem K'.elim_stack (a b c d) : K'.elim a b c d K'.stack = d := rfl attribute [simp] K'.elim @[simp] theorem K'.elim_update_main {a b c d a'} : update (K'.elim a b c d) main a' = K'.elim a' b c d := by funext x; cases x <;> rfl @[simp] theorem K'.elim_update_rev {a b c d b'} : update (K'.elim a b c d) rev b' = K'.elim a b' c d := by funext x; cases x <;> rfl @[simp] theorem K'.elim_update_aux {a b c d c'} : update (K'.elim a b c d) aux c' = K'.elim a b c' d := by funext x; cases x <;> rfl @[simp] theorem K'.elim_update_stack {a b c d d'} : update (K'.elim a b c d) stack d' = K'.elim a b c d' := by funext x; cases x <;> rfl /-- The halting state corresponding to a `List ℕ` output value. -/ def halt (v : List ℕ) : Cfg' := ⟨none, none, K'.elim (trList v) [] [] []⟩ /-- The `Cfg` states map to `Cfg'` states almost one to one, except that in normal operation the local store contains an arbitrary garbage value. To make the final theorem cleaner we explicitly clear it in the halt state so that there is exactly one configuration corresponding to output `v`. -/ def TrCfg : Cfg → Cfg' → Prop | Cfg.ret k v, c' => ∃ s, c' = ⟨some (Λ'.ret (trCont k)), s, K'.elim (trList v) [] [] (trContStack k)⟩ | Cfg.halt v, c' => c' = halt v /-- This could be a general list definition, but it is also somewhat specialized to this application. `splitAtPred p L` will search `L` for the first element satisfying `p`. If it is found, say `L = l₁ ++ a :: l₂` where `a` satisfies `p` but `l₁` does not, then it returns `(l₁, some a, l₂)`. Otherwise, if there is no such element, it returns `(L, none, [])`. -/ def splitAtPred {α} (p : α → Bool) : List α → List α × Option α × List α | [] => ([], none, []) | a :: as => cond (p a) ([], some a, as) <| let ⟨l₁, o, l₂⟩ := splitAtPred p as ⟨a::l₁, o, l₂⟩ theorem splitAtPred_eq {α} (p : α → Bool) : ∀ L l₁ o l₂, (∀ x ∈ l₁, p x = false) → Option.elim' (L = l₁ ∧ l₂ = []) (fun a => p a = true ∧ L = l₁ ++ a::l₂) o → splitAtPred p L = (l₁, o, l₂) | [], _, none, _, _, ⟨rfl, rfl⟩ => rfl | [], l₁, some o, l₂, _, ⟨_, h₃⟩ => by simp at h₃ | a :: L, l₁, o, l₂, h₁, h₂ => by rw [splitAtPred] have IH := splitAtPred_eq p L cases' o with o · cases' l₁ with a' l₁ <;> rcases h₂ with ⟨⟨⟩, rfl⟩ rw [h₁ a (List.Mem.head _), cond, IH L none [] _ ⟨rfl, rfl⟩] exact fun x h => h₁ x (List.Mem.tail _ h) · cases' l₁ with a' l₁ <;> rcases h₂ with ⟨h₂, ⟨⟩⟩ · rw [h₂, cond] rw [h₁ a (List.Mem.head _), cond, IH l₁ (some o) l₂ _ ⟨h₂, _⟩] <;> try rfl exact fun x h => h₁ x (List.Mem.tail _ h) theorem splitAtPred_false {α} (L : List α) : splitAtPred (fun _ => false) L = (L, none, []) := splitAtPred_eq _ _ _ _ _ (fun _ _ => rfl) ⟨rfl, rfl⟩ theorem move_ok {p k₁ k₂ q s L₁ o L₂} {S : K' → List Γ'} (h₁ : k₁ ≠ k₂) (e : splitAtPred p (S k₁) = (L₁, o, L₂)) : Reaches₁ (TM2.step tr) ⟨some (Λ'.move p k₁ k₂ q), s, S⟩ ⟨some q, o, update (update S k₁ L₂) k₂ (L₁.reverseAux (S k₂))⟩ := by induction' L₁ with a L₁ IH generalizing S s · rw [(_ : [].reverseAux _ = _), Function.update_eq_self] swap · rw [Function.update_noteq h₁.symm, List.reverseAux_nil] refine TransGen.head' rfl ?_ simp only [TM2.step, Option.mem_def, TM2.stepAux, Option.elim, ne_eq] revert e; cases' S k₁ with a Sk <;> intro e · cases e rfl simp only [splitAtPred, Option.elim, List.head?, List.tail_cons, Option.iget_some] at e ⊢ revert e; cases p a <;> intro e <;> simp only [cond_false, cond_true, Prod.mk.injEq, true_and, false_and] at e ⊢ simp only [e] rfl · refine TransGen.head rfl ?_ simp only [TM2.step, Option.mem_def, TM2.stepAux, Option.elim, ne_eq, List.reverseAux_cons] cases' e₁ : S k₁ with a' Sk <;> rw [e₁, splitAtPred] at e · cases e cases e₂ : p a' <;> simp only [e₂, cond] at e swap · cases e rcases e₃ : splitAtPred p Sk with ⟨_, _, _⟩ rw [e₃] at e cases e simp only [List.head?_cons, e₂, List.tail_cons, ne_eq, cond_false] convert @IH _ (update (update S k₁ Sk) k₂ (a :: S k₂)) _ using 2 <;> simp [Function.update_noteq, h₁, h₁.symm, e₃, List.reverseAux] simp [Function.update_comm h₁.symm] theorem unrev_ok {q s} {S : K' → List Γ'} : Reaches₁ (TM2.step tr) ⟨some (unrev q), s, S⟩ ⟨some q, none, update (update S rev []) main (List.reverseAux (S rev) (S main))⟩ := move_ok (by decide) <| splitAtPred_false _ theorem move₂_ok {p k₁ k₂ q s L₁ o L₂} {S : K' → List Γ'} (h₁ : k₁ ≠ rev ∧ k₂ ≠ rev ∧ k₁ ≠ k₂) (h₂ : S rev = []) (e : splitAtPred p (S k₁) = (L₁, o, L₂)) : Reaches₁ (TM2.step tr) ⟨some (move₂ p k₁ k₂ q), s, S⟩ ⟨some q, none, update (update S k₁ (o.elim id List.cons L₂)) k₂ (L₁ ++ S k₂)⟩ := by refine (move_ok h₁.1 e).trans (TransGen.head rfl ?_) simp only [TM2.step, Option.mem_def, TM2.stepAux, id_eq, ne_eq, Option.elim] cases o <;> simp only [Option.elim, id] · simp only [TM2.stepAux, Option.isSome, cond_false] convert move_ok h₁.2.1.symm (splitAtPred_false _) using 2 simp only [Function.update_comm h₁.1, Function.update_idem] rw [show update S rev [] = S by rw [← h₂, Function.update_eq_self]] simp only [Function.update_noteq h₁.2.2.symm, Function.update_noteq h₁.2.1, Function.update_noteq h₁.1.symm, List.reverseAux_eq, h₂, Function.update_same, List.append_nil, List.reverse_reverse] · simp only [TM2.stepAux, Option.isSome, cond_true] convert move_ok h₁.2.1.symm (splitAtPred_false _) using 2 simp only [h₂, Function.update_comm h₁.1, List.reverseAux_eq, Function.update_same, List.append_nil, Function.update_idem] rw [show update S rev [] = S by rw [← h₂, Function.update_eq_self]] simp only [Function.update_noteq h₁.1.symm, Function.update_noteq h₁.2.2.symm, Function.update_noteq h₁.2.1, Function.update_same, List.reverse_reverse] theorem clear_ok {p k q s L₁ o L₂} {S : K' → List Γ'} (e : splitAtPred p (S k) = (L₁, o, L₂)) : Reaches₁ (TM2.step tr) ⟨some (Λ'.clear p k q), s, S⟩ ⟨some q, o, update S k L₂⟩ := by induction' L₁ with a L₁ IH generalizing S s · refine TransGen.head' rfl ?_ simp only [TM2.step, Option.mem_def, TM2.stepAux, Option.elim] revert e; cases' S k with a Sk <;> intro e · cases e rfl simp only [splitAtPred, Option.elim, List.head?, List.tail_cons] at e ⊢ revert e; cases p a <;> intro e <;> simp only [cond_false, cond_true, Prod.mk.injEq, true_and, false_and] at e ⊢ rcases e with ⟨e₁, e₂⟩ rw [e₁, e₂] · refine TransGen.head rfl ?_ simp only [TM2.step, Option.mem_def, TM2.stepAux, Option.elim] cases' e₁ : S k with a' Sk <;> rw [e₁, splitAtPred] at e · cases e cases e₂ : p a' <;> simp only [e₂, cond] at e swap · cases e rcases e₃ : splitAtPred p Sk with ⟨_, _, _⟩ rw [e₃] at e cases e simp only [List.head?_cons, e₂, List.tail_cons, cond_false] convert @IH _ (update S k Sk) _ using 2 <;> simp [e₃] theorem copy_ok (q s a b c d) : Reaches₁ (TM2.step tr) ⟨some (Λ'.copy q), s, K'.elim a b c d⟩ ⟨some q, none, K'.elim (List.reverseAux b a) [] c (List.reverseAux b d)⟩ := by induction' b with x b IH generalizing a d s · refine TransGen.single ?_ simp refine TransGen.head rfl ?_ simp only [TM2.step, Option.mem_def, TM2.stepAux, elim_rev, List.head?_cons, Option.isSome_some, List.tail_cons, elim_update_rev, ne_eq, Function.update_noteq, elim_main, elim_update_main, elim_stack, elim_update_stack, cond_true, List.reverseAux_cons] exact IH _ _ _ theorem trPosNum_natEnd : ∀ (n), ∀ x ∈ trPosNum n, natEnd x = false | PosNum.one, _, List.Mem.head _ => rfl | PosNum.bit0 _, _, List.Mem.head _ => rfl | PosNum.bit0 n, _, List.Mem.tail _ h => trPosNum_natEnd n _ h | PosNum.bit1 _, _, List.Mem.head _ => rfl | PosNum.bit1 n, _, List.Mem.tail _ h => trPosNum_natEnd n _ h theorem trNum_natEnd : ∀ (n), ∀ x ∈ trNum n, natEnd x = false | Num.pos n, x, h => trPosNum_natEnd n x h theorem trNat_natEnd (n) : ∀ x ∈ trNat n, natEnd x = false := trNum_natEnd _ theorem trList_ne_consₗ : ∀ (l), ∀ x ∈ trList l, x ≠ Γ'.consₗ | a :: l, x, h => by simp only [trList, List.mem_append, List.mem_cons] at h obtain h | rfl | h := h · rintro rfl cases trNat_natEnd _ _ h · rintro ⟨⟩ · exact trList_ne_consₗ l _ h theorem head_main_ok {q s L} {c d : List Γ'} : Reaches₁ (TM2.step tr) ⟨some (head main q), s, K'.elim (trList L) [] c d⟩ ⟨some q, none, K'.elim (trList [L.headI]) [] c d⟩ := by let o : Option Γ' := List.casesOn L none fun _ _ => some Γ'.cons refine (move_ok (by decide) (splitAtPred_eq _ _ (trNat L.headI) o (trList L.tail) (trNat_natEnd _) ?_)).trans (TransGen.head rfl (TransGen.head rfl ?_)) · cases L <;> simp [o] simp only [TM2.step, Option.mem_def, TM2.stepAux, elim_update_main, elim_rev, elim_update_rev, Function.update_same, trList] rw [if_neg (show o ≠ some Γ'.consₗ by cases L <;> simp [o])] refine (clear_ok (splitAtPred_eq _ _ _ none [] ?_ ⟨rfl, rfl⟩)).trans ?_ · exact fun x h => Bool.decide_false (trList_ne_consₗ _ _ h) convert unrev_ok using 2; simp [List.reverseAux_eq] theorem head_stack_ok {q s L₁ L₂ L₃} : Reaches₁ (TM2.step tr) ⟨some (head stack q), s, K'.elim (trList L₁) [] [] (trList L₂ ++ Γ'.consₗ :: L₃)⟩ ⟨some q, none, K'.elim (trList (L₂.headI :: L₁)) [] [] L₃⟩ := by cases' L₂ with a L₂ · refine TransGen.trans (move_ok (by decide) (splitAtPred_eq _ _ [] (some Γ'.consₗ) L₃ (by rintro _ ⟨⟩) ⟨rfl, rfl⟩)) (TransGen.head rfl (TransGen.head rfl ?_)) simp only [TM2.step, Option.mem_def, TM2.stepAux, ite_true, id_eq, trList, List.nil_append, elim_update_stack, elim_rev, List.reverseAux_nil, elim_update_rev, Function.update_same, List.headI_nil, trNat_default] convert unrev_ok using 2 simp · refine TransGen.trans (move_ok (by decide) (splitAtPred_eq _ _ (trNat a) (some Γ'.cons) (trList L₂ ++ Γ'.consₗ :: L₃) (trNat_natEnd _) ⟨rfl, by simp⟩)) (TransGen.head rfl (TransGen.head rfl ?_)) simp only [TM2.step, Option.mem_def, TM2.stepAux, ite_false, trList, List.append_assoc, List.cons_append, elim_update_stack, elim_rev, elim_update_rev, Function.update_same, List.headI_cons] refine TransGen.trans (clear_ok (splitAtPred_eq _ _ (trList L₂) (some Γ'.consₗ) L₃ (fun x h => Bool.decide_false (trList_ne_consₗ _ _ h)) ⟨rfl, by simp⟩)) ?_ convert unrev_ok using 2 simp [List.reverseAux_eq] theorem succ_ok {q s n} {c d : List Γ'} : Reaches₁ (TM2.step tr) ⟨some (Λ'.succ q), s, K'.elim (trList [n]) [] c d⟩ ⟨some q, none, K'.elim (trList [n.succ]) [] c d⟩ := by simp only [TM2.step, trList, trNat.eq_1, Nat.cast_succ, Num.add_one] cases' (n : Num) with a · refine TransGen.head rfl ?_ simp only [Option.mem_def, TM2.stepAux, elim_main, decide_False, elim_update_main, ne_eq, Function.update_noteq, elim_rev, elim_update_rev, decide_True, Function.update_same, cond_true, cond_false] convert unrev_ok using 1 simp only [elim_update_rev, elim_rev, elim_main, List.reverseAux_nil, elim_update_main] rfl simp only [trNum, Num.succ, Num.succ'] suffices ∀ l₁, ∃ l₁' l₂' s', List.reverseAux l₁ (trPosNum a.succ) = List.reverseAux l₁' l₂' ∧ Reaches₁ (TM2.step tr) ⟨some q.succ, s, K'.elim (trPosNum a ++ [Γ'.cons]) l₁ c d⟩ ⟨some (unrev q), s', K'.elim (l₂' ++ [Γ'.cons]) l₁' c d⟩ by obtain ⟨l₁', l₂', s', e, h⟩ := this [] simp? [List.reverseAux] at e says simp only [List.reverseAux] at e refine h.trans ?_ convert unrev_ok using 2 simp [e, List.reverseAux_eq] induction' a with m IH m _ generalizing s <;> intro l₁ · refine ⟨Γ'.bit0 :: l₁, [Γ'.bit1], some Γ'.cons, rfl, TransGen.head rfl (TransGen.single ?_)⟩ simp [trPosNum] · obtain ⟨l₁', l₂', s', e, h⟩ := IH (Γ'.bit0 :: l₁) refine ⟨l₁', l₂', s', e, TransGen.head ?_ h⟩ simp [PosNum.succ, trPosNum] rfl · refine ⟨l₁, _, some Γ'.bit0, rfl, TransGen.single ?_⟩ simp only [TM2.step, TM2.stepAux, elim_main, elim_update_main, ne_eq, Function.update_noteq, elim_rev, elim_update_rev, Function.update_same, Option.mem_def, Option.some.injEq] rfl theorem pred_ok (q₁ q₂ s v) (c d : List Γ') : ∃ s', Reaches₁ (TM2.step tr) ⟨some (Λ'.pred q₁ q₂), s, K'.elim (trList v) [] c d⟩ (v.headI.rec ⟨some q₁, s', K'.elim (trList v.tail) [] c d⟩ fun n _ => ⟨some q₂, s', K'.elim (trList (n::v.tail)) [] c d⟩) := by rcases v with (_ | ⟨_ | n, v⟩) · refine ⟨none, TransGen.single ?_⟩ simp · refine ⟨some Γ'.cons, TransGen.single ?_⟩ simp refine ⟨none, ?_⟩ simp only [TM2.step, trList, trNat.eq_1, trNum, Nat.cast_succ, Num.add_one, Num.succ, List.tail_cons, List.headI_cons] cases' (n : Num) with a · simp only [trPosNum, List.singleton_append, List.nil_append] refine TransGen.head rfl ?_ simp only [Option.mem_def, TM2.stepAux, elim_main, List.head?_cons, Option.some.injEq, decide_False, List.tail_cons, elim_update_main, ne_eq, Function.update_noteq, elim_rev, elim_update_rev, natEnd, Function.update_same, cond_true, cond_false] convert unrev_ok using 2 simp simp only [Num.succ'] suffices ∀ l₁, ∃ l₁' l₂' s', List.reverseAux l₁ (trPosNum a) = List.reverseAux l₁' l₂' ∧ Reaches₁ (TM2.step tr) ⟨some (q₁.pred q₂), s, K'.elim (trPosNum a.succ ++ Γ'.cons :: trList v) l₁ c d⟩ ⟨some (unrev q₂), s', K'.elim (l₂' ++ Γ'.cons :: trList v) l₁' c d⟩ by obtain ⟨l₁', l₂', s', e, h⟩ := this [] simp only [List.reverseAux] at e refine h.trans ?_ convert unrev_ok using 2 simp [e, List.reverseAux_eq] induction' a with m IH m IH generalizing s <;> intro l₁ · refine ⟨Γ'.bit1::l₁, [], some Γ'.cons, rfl, TransGen.head rfl (TransGen.single ?_)⟩ simp [trPosNum, show PosNum.one.succ = PosNum.one.bit0 from rfl] · obtain ⟨l₁', l₂', s', e, h⟩ := IH (some Γ'.bit0) (Γ'.bit1 :: l₁) refine ⟨l₁', l₂', s', e, TransGen.head ?_ h⟩ simp rfl · obtain ⟨a, l, e, h⟩ : ∃ a l, (trPosNum m = a::l) ∧ natEnd a = false := by cases m <;> refine ⟨_, _, rfl, rfl⟩ refine ⟨Γ'.bit0 :: l₁, _, some a, rfl, TransGen.single ?_⟩ simp [trPosNum, PosNum.succ, e, h, show some Γ'.bit1 ≠ some Γ'.bit0 by decide, Option.iget, -natEnd] rfl theorem trNormal_respects (c k v s) : ∃ b₂, TrCfg (stepNormal c k v) b₂ ∧ Reaches₁ (TM2.step tr) ⟨some (trNormal c (trCont k)), s, K'.elim (trList v) [] [] (trContStack k)⟩ b₂ := by induction c generalizing k v s with | zero' => refine ⟨_, ⟨s, rfl⟩, TransGen.single ?_⟩; simp | succ => refine ⟨_, ⟨none, rfl⟩, head_main_ok.trans succ_ok⟩ | tail => let o : Option Γ' := List.casesOn v none fun _ _ => some Γ'.cons refine ⟨_, ⟨o, rfl⟩, ?_⟩; convert clear_ok _ using 2 · simp; rfl swap refine splitAtPred_eq _ _ (trNat v.headI) _ _ (trNat_natEnd _) ?_ cases v <;> simp [o] | cons f fs IHf _ => obtain ⟨c, h₁, h₂⟩ := IHf (Cont.cons₁ fs v k) v none refine ⟨c, h₁, TransGen.head rfl <| (move_ok (by decide) (splitAtPred_false _)).trans ?_⟩ simp only [TM2.step, Option.mem_def, elim_stack, elim_update_stack, elim_update_main, ne_eq, Function.update_noteq, elim_main, elim_rev, elim_update_rev] refine (copy_ok _ none [] (trList v).reverse _ _).trans ?_ convert h₂ using 2 simp [List.reverseAux_eq, trContStack] | comp f _ _ IHg => exact IHg (Cont.comp f k) v s | case f g IHf IHg => rw [stepNormal] simp only obtain ⟨s', h⟩ := pred_ok _ _ s v _ _ revert h; cases' v.headI with n <;> intro h · obtain ⟨c, h₁, h₂⟩ := IHf k _ s' exact ⟨_, h₁, h.trans h₂⟩ · obtain ⟨c, h₁, h₂⟩ := IHg k _ s' exact ⟨_, h₁, h.trans h₂⟩ | fix f IH => apply IH theorem tr_ret_respects (k v s) : ∃ b₂, TrCfg (stepRet k v) b₂ ∧ Reaches₁ (TM2.step tr) ⟨some (Λ'.ret (trCont k)), s, K'.elim (trList v) [] [] (trContStack k)⟩ b₂ := by induction k generalizing v s with | halt => exact ⟨_, rfl, TransGen.single rfl⟩ | cons₁ fs as k _ => obtain ⟨s', h₁, h₂⟩ := trNormal_respects fs (Cont.cons₂ v k) as none refine ⟨s', h₁, TransGen.head rfl ?_⟩; simp refine (move₂_ok (by decide) ?_ (splitAtPred_false _)).trans ?_; · rfl simp only [TM2.step, Option.mem_def, Option.elim, id_eq, elim_update_main, elim_main, elim_aux, List.append_nil, elim_update_aux] refine (move₂_ok (L₁ := ?_) (o := ?_) (L₂ := ?_) (by decide) rfl ?_).trans ?_ pick_goal 4 · exact splitAtPred_eq _ _ _ (some Γ'.consₗ) _ (fun x h => Bool.decide_false (trList_ne_consₗ _ _ h)) ⟨rfl, rfl⟩ refine (move₂_ok (by decide) ?_ (splitAtPred_false _)).trans ?_; · rfl simp only [TM2.step, Option.mem_def, Option.elim, elim_update_stack, elim_main, List.append_nil, elim_update_main, id_eq, elim_update_aux, ne_eq, Function.update_noteq, elim_aux, elim_stack] exact h₂ | cons₂ ns k IH => obtain ⟨c, h₁, h₂⟩ := IH (ns.headI :: v) none exact ⟨c, h₁, TransGen.head rfl <| head_stack_ok.trans h₂⟩ | comp f k _ => obtain ⟨s', h₁, h₂⟩ := trNormal_respects f k v s exact ⟨_, h₁, TransGen.head rfl h₂⟩ | fix f k IH => rw [stepRet] have : if v.headI = 0 then natEnd (trList v).head?.iget = true ∧ (trList v).tail = trList v.tail else natEnd (trList v).head?.iget = false ∧ (trList v).tail = (trNat v.headI).tail ++ Γ'.cons :: trList v.tail := by cases' v with n · exact ⟨rfl, rfl⟩ cases' n with n · simp rw [trList, List.headI, trNat, Nat.cast_succ, Num.add_one, Num.succ, List.tail] cases (n : Num).succ' <;> exact ⟨rfl, rfl⟩ by_cases h : v.headI = 0 <;> simp only [h, ite_true, ite_false] at this ⊢ · obtain ⟨c, h₁, h₂⟩ := IH v.tail (trList v).head? refine ⟨c, h₁, TransGen.head rfl ?_⟩ simp only [Option.mem_def, TM2.stepAux, trContStack, contStack, elim_main, this, cond_true, elim_update_main] exact h₂ · obtain ⟨s', h₁, h₂⟩ := trNormal_respects f (Cont.fix f k) v.tail (some Γ'.cons) refine ⟨_, h₁, TransGen.head rfl <| TransGen.trans ?_ h₂⟩ simp only [Option.mem_def, TM2.stepAux, elim_main, this.1, cond_false, elim_update_main, trCont] convert clear_ok (splitAtPred_eq _ _ (trNat v.headI).tail (some Γ'.cons) _ _ _) using 2 · simp convert rfl · exact fun x h => trNat_natEnd _ _ (List.tail_subset _ h) · exact ⟨rfl, this.2⟩ theorem tr_respects : Respects step (TM2.step tr) TrCfg | Cfg.ret _ _, _, ⟨_, rfl⟩ => tr_ret_respects _ _ _ | Cfg.halt _, _, rfl => rfl /-- The initial state, evaluating function `c` on input `v`. -/ def init (c : Code) (v : List ℕ) : Cfg' := ⟨some (trNormal c Cont'.halt), none, K'.elim (trList v) [] [] []⟩ theorem tr_init (c v) : ∃ b, TrCfg (stepNormal c Cont.halt v) b ∧ Reaches₁ (TM2.step tr) (init c v) b := trNormal_respects _ _ _ _ theorem tr_eval (c v) : eval (TM2.step tr) (init c v) = halt <$> Code.eval c v := by obtain ⟨i, h₁, h₂⟩ := tr_init c v refine Part.ext fun x => ?_ rw [reaches_eval h₂.to_reflTransGen]; simp only [Part.map_eq_map, Part.mem_map_iff] refine ⟨fun h => ?_, ?_⟩ · obtain ⟨c, hc₁, hc₂⟩ := tr_eval_rev tr_respects h₁ h simp [stepNormal_eval] at hc₂ obtain ⟨v', hv, rfl⟩ := hc₂ exact ⟨_, hv, hc₁.symm⟩ · rintro ⟨v', hv, rfl⟩ have := Turing.tr_eval (b₁ := Cfg.halt v') tr_respects h₁ simp only [stepNormal_eval, Part.map_eq_map, Part.mem_map_iff, Cfg.halt.injEq, exists_eq_right] at this obtain ⟨_, ⟨⟩, h⟩ := this hv exact h /-- The set of machine states reachable via downward label jumps, discounting jumps via `ret`. -/ def trStmts₁ : Λ' → Finset Λ' | Q@(Λ'.move _ _ _ q) => insert Q <| trStmts₁ q | Q@(Λ'.push _ _ q) => insert Q <| trStmts₁ q | Q@(Λ'.read q) => insert Q <| Finset.univ.biUnion fun s => trStmts₁ (q s) | Q@(Λ'.clear _ _ q) => insert Q <| trStmts₁ q | Q@(Λ'.copy q) => insert Q <| trStmts₁ q | Q@(Λ'.succ q) => insert Q <| insert (unrev q) <| trStmts₁ q | Q@(Λ'.pred q₁ q₂) => insert Q <| trStmts₁ q₁ ∪ insert (unrev q₂) (trStmts₁ q₂) | Q@(Λ'.ret _) => {Q} theorem trStmts₁_trans {q q'} : q' ∈ trStmts₁ q → trStmts₁ q' ⊆ trStmts₁ q := by induction' q with _ _ _ q q_ih _ _ q q_ih q q_ih _ _ q q_ih q q_ih q q_ih q₁ q₂ q₁_ih q₂_ih _ <;> simp (config := { contextual := true }) only [trStmts₁, Finset.mem_insert, Finset.mem_union, or_imp, Finset.mem_singleton, Finset.Subset.refl, imp_true_iff, true_and_iff] repeat exact fun h => Finset.Subset.trans (q_ih h) (Finset.subset_insert _ _) · simp intro s h x h' simp only [Finset.mem_biUnion, Finset.mem_univ, true_and, Finset.mem_insert] exact Or.inr ⟨_, q_ih s h h'⟩ · constructor · rintro rfl apply Finset.subset_insert · intro h x h' simp only [Finset.mem_insert] exact Or.inr (Or.inr <| q_ih h h') · refine ⟨fun h x h' => ?_, fun _ x h' => ?_, fun h x h' => ?_⟩ <;> simp · exact Or.inr (Or.inr <| Or.inl <| q₁_ih h h') · cases' Finset.mem_insert.1 h' with h' h' <;> simp [h', unrev] · exact Or.inr (Or.inr <| Or.inr <| q₂_ih h h') theorem trStmts₁_self (q) : q ∈ trStmts₁ q := by induction q <;> · first |apply Finset.mem_singleton_self|apply Finset.mem_insert_self /-- The (finite!) set of machine states visited during the course of evaluation of `c`, including the state `ret k` but not any states after that (that is, the states visited while evaluating `k`). -/ def codeSupp' : Code → Cont' → Finset Λ' | c@Code.zero', k => trStmts₁ (trNormal c k) | c@Code.succ, k => trStmts₁ (trNormal c k) | c@Code.tail, k => trStmts₁ (trNormal c k) | c@(Code.cons f fs), k => trStmts₁ (trNormal c k) ∪ (codeSupp' f (Cont'.cons₁ fs k) ∪ (trStmts₁ (move₂ (fun _ => false) main aux <| move₂ (fun s => s = Γ'.consₗ) stack main <| move₂ (fun _ => false) aux stack <| trNormal fs (Cont'.cons₂ k)) ∪ (codeSupp' fs (Cont'.cons₂ k) ∪ trStmts₁ (head stack <| Λ'.ret k)))) | c@(Code.comp f g), k => trStmts₁ (trNormal c k) ∪ (codeSupp' g (Cont'.comp f k) ∪ (trStmts₁ (trNormal f k) ∪ codeSupp' f k)) | c@(Code.case f g), k => trStmts₁ (trNormal c k) ∪ (codeSupp' f k ∪ codeSupp' g k) | c@(Code.fix f), k => trStmts₁ (trNormal c k) ∪ (codeSupp' f (Cont'.fix f k) ∪ (trStmts₁ (Λ'.clear natEnd main <| trNormal f (Cont'.fix f k)) ∪ {Λ'.ret k})) @[simp] theorem codeSupp'_self (c k) : trStmts₁ (trNormal c k) ⊆ codeSupp' c k := by cases c <;> first | rfl | exact Finset.union_subset_left (fun _ a ↦ a) /-- The (finite!) set of machine states visited during the course of evaluation of a continuation `k`, not including the initial state `ret k`. -/ def contSupp : Cont' → Finset Λ' | Cont'.cons₁ fs k => trStmts₁ (move₂ (fun _ => false) main aux <| move₂ (fun s => s = Γ'.consₗ) stack main <| move₂ (fun _ => false) aux stack <| trNormal fs (Cont'.cons₂ k)) ∪ (codeSupp' fs (Cont'.cons₂ k) ∪ (trStmts₁ (head stack <| Λ'.ret k) ∪ contSupp k)) | Cont'.cons₂ k => trStmts₁ (head stack <| Λ'.ret k) ∪ contSupp k | Cont'.comp f k => codeSupp' f k ∪ contSupp k | Cont'.fix f k => codeSupp' (Code.fix f) k ∪ contSupp k | Cont'.halt => ∅ /-- The (finite!) set of machine states visited during the course of evaluation of `c` in continuation `k`. This is actually closed under forward simulation (see `tr_supports`), and the existence of this set means that the machine constructed in this section is in fact a proper Turing machine, with a finite set of states. -/ def codeSupp (c : Code) (k : Cont') : Finset Λ' := codeSupp' c k ∪ contSupp k @[simp] theorem codeSupp_self (c k) : trStmts₁ (trNormal c k) ⊆ codeSupp c k := Finset.Subset.trans (codeSupp'_self _ _) (Finset.union_subset_left fun _ a ↦ a) @[simp] theorem codeSupp_zero (k) : codeSupp Code.zero' k = trStmts₁ (trNormal Code.zero' k) ∪ contSupp k := rfl @[simp] theorem codeSupp_succ (k) : codeSupp Code.succ k = trStmts₁ (trNormal Code.succ k) ∪ contSupp k := rfl @[simp] theorem codeSupp_tail (k) : codeSupp Code.tail k = trStmts₁ (trNormal Code.tail k) ∪ contSupp k := rfl @[simp] theorem codeSupp_cons (f fs k) : codeSupp (Code.cons f fs) k = trStmts₁ (trNormal (Code.cons f fs) k) ∪ codeSupp f (Cont'.cons₁ fs k) := by simp [codeSupp, codeSupp', contSupp, Finset.union_assoc] @[simp] theorem codeSupp_comp (f g k) : codeSupp (Code.comp f g) k = trStmts₁ (trNormal (Code.comp f g) k) ∪ codeSupp g (Cont'.comp f k) := by simp only [codeSupp, codeSupp', trNormal, Finset.union_assoc, contSupp] rw [← Finset.union_assoc _ _ (contSupp k), Finset.union_eq_right.2 (codeSupp'_self _ _)] @[simp] theorem codeSupp_case (f g k) : codeSupp (Code.case f g) k = trStmts₁ (trNormal (Code.case f g) k) ∪ (codeSupp f k ∪ codeSupp g k) := by simp [codeSupp, codeSupp', contSupp, Finset.union_assoc, Finset.union_left_comm] @[simp] theorem codeSupp_fix (f k) : codeSupp (Code.fix f) k = trStmts₁ (trNormal (Code.fix f) k) ∪ codeSupp f (Cont'.fix f k) := by simp [codeSupp, codeSupp', contSupp, Finset.union_assoc, Finset.union_left_comm, Finset.union_left_idem] @[simp] theorem contSupp_cons₁ (fs k) : contSupp (Cont'.cons₁ fs k) = trStmts₁ (move₂ (fun _ => false) main aux <| move₂ (fun s => s = Γ'.consₗ) stack main <| move₂ (fun _ => false) aux stack <| trNormal fs (Cont'.cons₂ k)) ∪ codeSupp fs (Cont'.cons₂ k) := by simp [codeSupp, codeSupp', contSupp, Finset.union_assoc] @[simp] theorem contSupp_cons₂ (k) : contSupp (Cont'.cons₂ k) = trStmts₁ (head stack <| Λ'.ret k) ∪ contSupp k := rfl @[simp] theorem contSupp_comp (f k) : contSupp (Cont'.comp f k) = codeSupp f k := rfl theorem contSupp_fix (f k) : contSupp (Cont'.fix f k) = codeSupp f (Cont'.fix f k) := by simp (config := { contextual := true }) [codeSupp, codeSupp', contSupp, Finset.union_assoc, Finset.subset_iff] @[simp] theorem contSupp_halt : contSupp Cont'.halt = ∅ := rfl /-- The statement `Λ'.Supports S q` means that `contSupp k ⊆ S` for any `ret k` reachable from `q`. (This is a technical condition used in the proof that the machine is supported.) -/ def Λ'.Supports (S : Finset Λ') : Λ' → Prop | Λ'.move _ _ _ q => Λ'.Supports S q | Λ'.push _ _ q => Λ'.Supports S q | Λ'.read q => ∀ s, Λ'.Supports S (q s) | Λ'.clear _ _ q => Λ'.Supports S q | Λ'.copy q => Λ'.Supports S q | Λ'.succ q => Λ'.Supports S q | Λ'.pred q₁ q₂ => Λ'.Supports S q₁ ∧ Λ'.Supports S q₂ | Λ'.ret k => contSupp k ⊆ S /-- A shorthand for the predicate that we are proving in the main theorems `trStmts₁_supports`, `codeSupp'_supports`, `contSupp_supports`, `codeSupp_supports`. The set `S` is fixed throughout the proof, and denotes the full set of states in the machine, while `K` is a subset that we are currently proving a property about. The predicate asserts that every state in `K` is closed in `S` under forward simulation, i.e. stepping forward through evaluation starting from any state in `K` stays entirely within `S`. -/ def Supports (K S : Finset Λ') := ∀ q ∈ K, TM2.SupportsStmt S (tr q) theorem supports_insert {K S q} : Supports (insert q K) S ↔ TM2.SupportsStmt S (tr q) ∧ Supports K S := by simp [Supports] theorem supports_singleton {S q} : Supports {q} S ↔ TM2.SupportsStmt S (tr q) := by simp [Supports] theorem supports_union {K₁ K₂ S} : Supports (K₁ ∪ K₂) S ↔ Supports K₁ S ∧ Supports K₂ S := by simp [Supports, or_imp, forall_and] theorem supports_biUnion {K : Option Γ' → Finset Λ'} {S} : Supports (Finset.univ.biUnion K) S ↔ ∀ a, Supports (K a) S := by simpa [Supports] using forall_swap theorem head_supports {S k q} (H : (q : Λ').Supports S) : (head k q).Supports S := fun _ => by dsimp only; split_ifs <;> exact H theorem ret_supports {S k} (H₁ : contSupp k ⊆ S) : TM2.SupportsStmt S (tr (Λ'.ret k)) := by have W := fun {q} => trStmts₁_self q cases k with | halt => trivial | cons₁ => rw [contSupp_cons₁, Finset.union_subset_iff] at H₁; exact fun _ => H₁.1 W | cons₂ => rw [contSupp_cons₂, Finset.union_subset_iff] at H₁; exact fun _ => H₁.1 W | comp => rw [contSupp_comp] at H₁; exact fun _ => H₁ (codeSupp_self _ _ W) | fix => rw [contSupp_fix] at H₁ have L := @Finset.mem_union_left; have R := @Finset.mem_union_right intro s; dsimp only; cases natEnd s.iget · refine H₁ (R _ <| L _ <| R _ <| R _ <| L _ W) · exact H₁ (R _ <| L _ <| R _ <| R _ <| R _ <| Finset.mem_singleton_self _) theorem trStmts₁_supports {S q} (H₁ : (q : Λ').Supports S) (HS₁ : trStmts₁ q ⊆ S) : Supports (trStmts₁ q) S := by have W := fun {q} => trStmts₁_self q induction' q with _ _ _ q q_ih _ _ q q_ih q q_ih _ _ q q_ih q q_ih q q_ih q₁ q₂ q₁_ih q₂_ih _ <;> simp [trStmts₁, -Finset.singleton_subset_iff] at HS₁ ⊢ any_goals cases' Finset.insert_subset_iff.1 HS₁ with h₁ h₂ first | have h₃ := h₂ W | try simp [Finset.subset_iff] at h₂ · exact supports_insert.2 ⟨⟨fun _ => h₃, fun _ => h₁⟩, q_ih H₁ h₂⟩ -- move · exact supports_insert.2 ⟨⟨fun _ => h₃, fun _ => h₁⟩, q_ih H₁ h₂⟩ -- clear · exact supports_insert.2 ⟨⟨fun _ => h₁, fun _ => h₃⟩, q_ih H₁ h₂⟩ -- copy · exact supports_insert.2 ⟨⟨fun _ => h₃, fun _ => h₃⟩, q_ih H₁ h₂⟩ -- push · refine supports_insert.2 ⟨fun _ => h₂ _ W, ?_⟩ -- read exact supports_biUnion.2 fun _ => q_ih _ (H₁ _) fun _ h => h₂ _ h · refine supports_insert.2 ⟨⟨fun _ => h₁, fun _ => h₂.1, fun _ => h₂.1⟩, ?_⟩ -- succ exact supports_insert.2 ⟨⟨fun _ => h₂.2 _ W, fun _ => h₂.1⟩, q_ih H₁ h₂.2⟩ · refine -- pred supports_insert.2 ⟨⟨fun _ => h₁, fun _ => h₂.2 _ (Or.inl W), fun _ => h₂.1, fun _ => h₂.1⟩, ?_⟩ refine supports_insert.2 ⟨⟨fun _ => h₂.2 _ (Or.inr W), fun _ => h₂.1⟩, ?_⟩ refine supports_union.2 ⟨?_, ?_⟩ · exact q₁_ih H₁.1 fun _ h => h₂.2 _ (Or.inl h) · exact q₂_ih H₁.2 fun _ h => h₂.2 _ (Or.inr h) · exact supports_singleton.2 (ret_supports H₁) -- ret theorem trStmts₁_supports' {S q K} (H₁ : (q : Λ').Supports S) (H₂ : trStmts₁ q ∪ K ⊆ S) (H₃ : K ⊆ S → Supports K S) : Supports (trStmts₁ q ∪ K) S := by simp only [Finset.union_subset_iff] at H₂ exact supports_union.2 ⟨trStmts₁_supports H₁ H₂.1, H₃ H₂.2⟩ theorem trNormal_supports {S c k} (Hk : codeSupp c k ⊆ S) : (trNormal c k).Supports S := by induction c generalizing k with simp [Λ'.Supports, head] | zero' => exact Finset.union_subset_right Hk | succ => intro; split_ifs <;> exact Finset.union_subset_right Hk | tail => exact Finset.union_subset_right Hk | cons f fs IHf _ => apply IHf rw [codeSupp_cons] at Hk exact Finset.union_subset_right Hk | comp f g _ IHg => apply IHg; rw [codeSupp_comp] at Hk; exact Finset.union_subset_right Hk | case f g IHf IHg => simp only [codeSupp_case, Finset.union_subset_iff] at Hk exact ⟨IHf Hk.2.1, IHg Hk.2.2⟩ | fix f IHf => apply IHf; rw [codeSupp_fix] at Hk; exact Finset.union_subset_right Hk theorem codeSupp'_supports {S c k} (H : codeSupp c k ⊆ S) : Supports (codeSupp' c k) S := by induction c generalizing k with | cons f fs IHf IHfs => have H' := H; simp only [codeSupp_cons, Finset.union_subset_iff] at H' refine trStmts₁_supports' (trNormal_supports H) (Finset.union_subset_left H) fun h => ?_ refine supports_union.2 ⟨IHf H'.2, ?_⟩ refine trStmts₁_supports' (trNormal_supports ?_) (Finset.union_subset_right h) fun h => ?_ · simp only [codeSupp, Finset.union_subset_iff, contSupp] at h H ⊢ exact ⟨h.2.2.1, h.2.2.2, H.2⟩ refine supports_union.2 ⟨IHfs ?_, ?_⟩ · rw [codeSupp, contSupp_cons₁] at H' exact Finset.union_subset_right (Finset.union_subset_right H'.2) exact trStmts₁_supports (head_supports <| Finset.union_subset_right H) (Finset.union_subset_right h) | comp f g IHf IHg => have H' := H; rw [codeSupp_comp] at H'; have H' := Finset.union_subset_right H' refine trStmts₁_supports' (trNormal_supports H) (Finset.union_subset_left H) fun h => ?_ refine supports_union.2 ⟨IHg H', ?_⟩ refine trStmts₁_supports' (trNormal_supports ?_) (Finset.union_subset_right h) fun _ => ?_ · simp only [codeSupp', codeSupp, Finset.union_subset_iff, contSupp] at h H ⊢ exact ⟨h.2.2, H.2⟩ exact IHf (Finset.union_subset_right H') | case f g IHf IHg => have H' := H; simp only [codeSupp_case, Finset.union_subset_iff] at H' refine trStmts₁_supports' (trNormal_supports H) (Finset.union_subset_left H) fun _ => ?_ exact supports_union.2 ⟨IHf H'.2.1, IHg H'.2.2⟩ | fix f IHf => have H' := H; simp only [codeSupp_fix, Finset.union_subset_iff] at H' refine trStmts₁_supports' (trNormal_supports H) (Finset.union_subset_left H) fun h => ?_ refine supports_union.2 ⟨IHf H'.2, ?_⟩ refine trStmts₁_supports' (trNormal_supports ?_) (Finset.union_subset_right h) fun _ => ?_ · simp only [codeSupp', codeSupp, Finset.union_subset_iff, contSupp, trStmts₁, Finset.insert_subset_iff] at h H ⊢ exact ⟨h.1, ⟨H.1.1, h⟩, H.2⟩ exact supports_singleton.2 (ret_supports <| Finset.union_subset_right H) | _ => exact trStmts₁_supports (trNormal_supports H) (Finset.Subset.trans (codeSupp_self _ _) H) theorem contSupp_supports {S k} (H : contSupp k ⊆ S) : Supports (contSupp k) S := by induction k with | halt => simp [contSupp_halt, Supports] | cons₁ f k IH => have H₁ := H; rw [contSupp_cons₁] at H₁; have H₂ := Finset.union_subset_right H₁ refine trStmts₁_supports' (trNormal_supports H₂) H₁ fun h => ?_ refine supports_union.2 ⟨codeSupp'_supports H₂, ?_⟩ simp only [codeSupp, contSupp_cons₂, Finset.union_subset_iff] at H₂ exact trStmts₁_supports' (head_supports H₂.2.2) (Finset.union_subset_right h) IH | cons₂ k IH => have H' := H; rw [contSupp_cons₂] at H' exact trStmts₁_supports' (head_supports <| Finset.union_subset_right H') H' IH | comp f k IH => have H' := H; rw [contSupp_comp] at H'; have H₂ := Finset.union_subset_right H' exact supports_union.2 ⟨codeSupp'_supports H', IH H₂⟩ | fix f k IH => rw [contSupp] at H exact supports_union.2 ⟨codeSupp'_supports H, IH (Finset.union_subset_right H)⟩ theorem codeSupp_supports {S c k} (H : codeSupp c k ⊆ S) : Supports (codeSupp c k) S := supports_union.2 ⟨codeSupp'_supports H, contSupp_supports (Finset.union_subset_right H)⟩ /-- The set `codeSupp c k` is a finite set that witnesses the effective finiteness of the `tr` Turing machine. Starting from the initial state `trNormal c k`, forward simulation uses only states in `codeSupp c k`, so this is a finite state machine. Even though the underlying type of state labels `Λ'` is infinite, for a given partial recursive function `c` and continuation `k`, only finitely many states are accessed, corresponding roughly to subterms of `c`. -/ theorem tr_supports (c k) : @TM2.Supports _ _ _ _ ⟨trNormal c k⟩ tr (codeSupp c k) := ⟨codeSupp_self _ _ (trStmts₁_self _), fun _ => codeSupp_supports (Finset.Subset.refl _) _⟩ end end PartrecToTM2 end Turing
Computability\TuringMachine.lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Data.Fintype.Option import Mathlib.Data.Fintype.Prod import Mathlib.Data.Fintype.Pi import Mathlib.Data.Vector.Basic import Mathlib.Data.PFun import Mathlib.Logic.Function.Iterate import Mathlib.Order.Basic import Mathlib.Tactic.ApplyFun import Mathlib.Data.List.GetD /-! # Turing machines This file defines a sequence of simple machine languages, starting with Turing machines and working up to more complex languages based on Wang B-machines. ## Naming conventions Each model of computation in this file shares a naming convention for the elements of a model of computation. These are the parameters for the language: * `Γ` is the alphabet on the tape. * `Λ` is the set of labels, or internal machine states. * `σ` is the type of internal memory, not on the tape. This does not exist in the TM0 model, and later models achieve this by mixing it into `Λ`. * `K` is used in the TM2 model, which has multiple stacks, and denotes the number of such stacks. All of these variables denote "essentially finite" types, but for technical reasons it is convenient to allow them to be infinite anyway. When using an infinite type, we will be interested to prove that only finitely many values of the type are ever interacted with. Given these parameters, there are a few common structures for the model that arise: * `Stmt` is the set of all actions that can be performed in one step. For the TM0 model this set is finite, and for later models it is an infinite inductive type representing "possible program texts". * `Cfg` is the set of instantaneous configurations, that is, the state of the machine together with its environment. * `Machine` is the set of all machines in the model. Usually this is approximately a function `Λ → Stmt`, although different models have different ways of halting and other actions. * `step : Cfg → Option Cfg` is the function that describes how the state evolves over one step. If `step c = none`, then `c` is a terminal state, and the result of the computation is read off from `c`. Because of the type of `step`, these models are all deterministic by construction. * `init : Input → Cfg` sets up the initial state. The type `Input` depends on the model; in most cases it is `List Γ`. * `eval : Machine → Input → Part Output`, given a machine `M` and input `i`, starts from `init i`, runs `step` until it reaches an output, and then applies a function `Cfg → Output` to the final state to obtain the result. The type `Output` depends on the model. * `Supports : Machine → Finset Λ → Prop` asserts that a machine `M` starts in `S : Finset Λ`, and can only ever jump to other states inside `S`. This implies that the behavior of `M` on any input cannot depend on its values outside `S`. We use this to allow `Λ` to be an infinite set when convenient, and prove that only finitely many of these states are actually accessible. This formalizes "essentially finite" mentioned above. -/ -- After https://github.com/leanprover/lean4/pull/4400 -- the simp normal forms for `List` lookup use the `GetElem` typeclass, rather than `List.get?`. -- This file has not been updated to reflect that change, so uses a number of deprecated lemmas. -- Updating this file to allow restoring the deprecation linter would be much appreciated. set_option linter.deprecated false assert_not_exists MonoidWithZero open Mathlib (Vector) open Relation open Nat (iterate) open Function (update iterate_succ iterate_succ_apply iterate_succ' iterate_succ_apply' iterate_zero_apply) namespace Turing /-- The `BlankExtends` partial order holds of `l₁` and `l₂` if `l₂` is obtained by adding blanks (`default : Γ`) to the end of `l₁`. -/ def BlankExtends {Γ} [Inhabited Γ] (l₁ l₂ : List Γ) : Prop := ∃ n, l₂ = l₁ ++ List.replicate n default @[refl] theorem BlankExtends.refl {Γ} [Inhabited Γ] (l : List Γ) : BlankExtends l l := ⟨0, by simp⟩ @[trans] theorem BlankExtends.trans {Γ} [Inhabited Γ] {l₁ l₂ l₃ : List Γ} : BlankExtends l₁ l₂ → BlankExtends l₂ l₃ → BlankExtends l₁ l₃ := by rintro ⟨i, rfl⟩ ⟨j, rfl⟩ exact ⟨i + j, by simp⟩ theorem BlankExtends.below_of_le {Γ} [Inhabited Γ] {l l₁ l₂ : List Γ} : BlankExtends l l₁ → BlankExtends l l₂ → l₁.length ≤ l₂.length → BlankExtends l₁ l₂ := by rintro ⟨i, rfl⟩ ⟨j, rfl⟩ h; use j - i simp only [List.length_append, Nat.add_le_add_iff_left, List.length_replicate] at h simp only [← List.replicate_add, Nat.add_sub_cancel' h, List.append_assoc] /-- Any two extensions by blank `l₁,l₂` of `l` have a common join (which can be taken to be the longer of `l₁` and `l₂`). -/ def BlankExtends.above {Γ} [Inhabited Γ] {l l₁ l₂ : List Γ} (h₁ : BlankExtends l l₁) (h₂ : BlankExtends l l₂) : { l' // BlankExtends l₁ l' ∧ BlankExtends l₂ l' } := if h : l₁.length ≤ l₂.length then ⟨l₂, h₁.below_of_le h₂ h, BlankExtends.refl _⟩ else ⟨l₁, BlankExtends.refl _, h₂.below_of_le h₁ (le_of_not_ge h)⟩ theorem BlankExtends.above_of_le {Γ} [Inhabited Γ] {l l₁ l₂ : List Γ} : BlankExtends l₁ l → BlankExtends l₂ l → l₁.length ≤ l₂.length → BlankExtends l₁ l₂ := by rintro ⟨i, rfl⟩ ⟨j, e⟩ h; use i - j refine List.append_cancel_right (e.symm.trans ?_) rw [List.append_assoc, ← List.replicate_add, Nat.sub_add_cancel] apply_fun List.length at e simp only [List.length_append, List.length_replicate] at e rwa [← Nat.add_le_add_iff_left, e, Nat.add_le_add_iff_right] /-- `BlankRel` is the symmetric closure of `BlankExtends`, turning it into an equivalence relation. Two lists are related by `BlankRel` if one extends the other by blanks. -/ def BlankRel {Γ} [Inhabited Γ] (l₁ l₂ : List Γ) : Prop := BlankExtends l₁ l₂ ∨ BlankExtends l₂ l₁ @[refl] theorem BlankRel.refl {Γ} [Inhabited Γ] (l : List Γ) : BlankRel l l := Or.inl (BlankExtends.refl _) @[symm] theorem BlankRel.symm {Γ} [Inhabited Γ] {l₁ l₂ : List Γ} : BlankRel l₁ l₂ → BlankRel l₂ l₁ := Or.symm @[trans] theorem BlankRel.trans {Γ} [Inhabited Γ] {l₁ l₂ l₃ : List Γ} : BlankRel l₁ l₂ → BlankRel l₂ l₃ → BlankRel l₁ l₃ := by rintro (h₁ | h₁) (h₂ | h₂) · exact Or.inl (h₁.trans h₂) · rcases le_total l₁.length l₃.length with h | h · exact Or.inl (h₁.above_of_le h₂ h) · exact Or.inr (h₂.above_of_le h₁ h) · rcases le_total l₁.length l₃.length with h | h · exact Or.inl (h₁.below_of_le h₂ h) · exact Or.inr (h₂.below_of_le h₁ h) · exact Or.inr (h₂.trans h₁) /-- Given two `BlankRel` lists, there exists (constructively) a common join. -/ def BlankRel.above {Γ} [Inhabited Γ] {l₁ l₂ : List Γ} (h : BlankRel l₁ l₂) : { l // BlankExtends l₁ l ∧ BlankExtends l₂ l } := by refine if hl : l₁.length ≤ l₂.length then ⟨l₂, Or.elim h id fun h' ↦ ?_, BlankExtends.refl _⟩ else ⟨l₁, BlankExtends.refl _, Or.elim h (fun h' ↦ ?_) id⟩ · exact (BlankExtends.refl _).above_of_le h' hl · exact (BlankExtends.refl _).above_of_le h' (le_of_not_ge hl) /-- Given two `BlankRel` lists, there exists (constructively) a common meet. -/ def BlankRel.below {Γ} [Inhabited Γ] {l₁ l₂ : List Γ} (h : BlankRel l₁ l₂) : { l // BlankExtends l l₁ ∧ BlankExtends l l₂ } := by refine if hl : l₁.length ≤ l₂.length then ⟨l₁, BlankExtends.refl _, Or.elim h id fun h' ↦ ?_⟩ else ⟨l₂, Or.elim h (fun h' ↦ ?_) id, BlankExtends.refl _⟩ · exact (BlankExtends.refl _).above_of_le h' hl · exact (BlankExtends.refl _).above_of_le h' (le_of_not_ge hl) theorem BlankRel.equivalence (Γ) [Inhabited Γ] : Equivalence (@BlankRel Γ _) := ⟨BlankRel.refl, @BlankRel.symm _ _, @BlankRel.trans _ _⟩ /-- Construct a setoid instance for `BlankRel`. -/ def BlankRel.setoid (Γ) [Inhabited Γ] : Setoid (List Γ) := ⟨_, BlankRel.equivalence _⟩ /-- A `ListBlank Γ` is a quotient of `List Γ` by extension by blanks at the end. This is used to represent half-tapes of a Turing machine, so that we can pretend that the list continues infinitely with blanks. -/ def ListBlank (Γ) [Inhabited Γ] := Quotient (BlankRel.setoid Γ) instance ListBlank.inhabited {Γ} [Inhabited Γ] : Inhabited (ListBlank Γ) := ⟨Quotient.mk'' []⟩ instance ListBlank.hasEmptyc {Γ} [Inhabited Γ] : EmptyCollection (ListBlank Γ) := ⟨Quotient.mk'' []⟩ /-- A modified version of `Quotient.liftOn'` specialized for `ListBlank`, with the stronger precondition `BlankExtends` instead of `BlankRel`. -/ -- Porting note: Removed `@[elab_as_elim]` protected abbrev ListBlank.liftOn {Γ} [Inhabited Γ] {α} (l : ListBlank Γ) (f : List Γ → α) (H : ∀ a b, BlankExtends a b → f a = f b) : α := l.liftOn' f <| by rintro a b (h | h) <;> [exact H _ _ h; exact (H _ _ h).symm] /-- The quotient map turning a `List` into a `ListBlank`. -/ def ListBlank.mk {Γ} [Inhabited Γ] : List Γ → ListBlank Γ := Quotient.mk'' @[elab_as_elim] protected theorem ListBlank.induction_on {Γ} [Inhabited Γ] {p : ListBlank Γ → Prop} (q : ListBlank Γ) (h : ∀ a, p (ListBlank.mk a)) : p q := Quotient.inductionOn' q h /-- The head of a `ListBlank` is well defined. -/ def ListBlank.head {Γ} [Inhabited Γ] (l : ListBlank Γ) : Γ := by apply l.liftOn List.headI rintro a _ ⟨i, rfl⟩ cases a · cases i <;> rfl rfl @[simp] theorem ListBlank.head_mk {Γ} [Inhabited Γ] (l : List Γ) : ListBlank.head (ListBlank.mk l) = l.headI := rfl /-- The tail of a `ListBlank` is well defined (up to the tail of blanks). -/ def ListBlank.tail {Γ} [Inhabited Γ] (l : ListBlank Γ) : ListBlank Γ := by apply l.liftOn (fun l ↦ ListBlank.mk l.tail) rintro a _ ⟨i, rfl⟩ refine Quotient.sound' (Or.inl ?_) cases a · cases' i with i <;> [exact ⟨0, rfl⟩; exact ⟨i, rfl⟩] exact ⟨i, rfl⟩ @[simp] theorem ListBlank.tail_mk {Γ} [Inhabited Γ] (l : List Γ) : ListBlank.tail (ListBlank.mk l) = ListBlank.mk l.tail := rfl /-- We can cons an element onto a `ListBlank`. -/ def ListBlank.cons {Γ} [Inhabited Γ] (a : Γ) (l : ListBlank Γ) : ListBlank Γ := by apply l.liftOn (fun l ↦ ListBlank.mk (List.cons a l)) rintro _ _ ⟨i, rfl⟩ exact Quotient.sound' (Or.inl ⟨i, rfl⟩) @[simp] theorem ListBlank.cons_mk {Γ} [Inhabited Γ] (a : Γ) (l : List Γ) : ListBlank.cons a (ListBlank.mk l) = ListBlank.mk (a :: l) := rfl @[simp] theorem ListBlank.head_cons {Γ} [Inhabited Γ] (a : Γ) : ∀ l : ListBlank Γ, (l.cons a).head = a := Quotient.ind' fun _ ↦ rfl @[simp] theorem ListBlank.tail_cons {Γ} [Inhabited Γ] (a : Γ) : ∀ l : ListBlank Γ, (l.cons a).tail = l := Quotient.ind' fun _ ↦ rfl /-- The `cons` and `head`/`tail` functions are mutually inverse, unlike in the case of `List` where this only holds for nonempty lists. -/ @[simp] theorem ListBlank.cons_head_tail {Γ} [Inhabited Γ] : ∀ l : ListBlank Γ, l.tail.cons l.head = l := by apply Quotient.ind' refine fun l ↦ Quotient.sound' (Or.inr ?_) cases l · exact ⟨1, rfl⟩ · rfl /-- The `cons` and `head`/`tail` functions are mutually inverse, unlike in the case of `List` where this only holds for nonempty lists. -/ theorem ListBlank.exists_cons {Γ} [Inhabited Γ] (l : ListBlank Γ) : ∃ a l', l = ListBlank.cons a l' := ⟨_, _, (ListBlank.cons_head_tail _).symm⟩ /-- The n-th element of a `ListBlank` is well defined for all `n : ℕ`, unlike in a `List`. -/ def ListBlank.nth {Γ} [Inhabited Γ] (l : ListBlank Γ) (n : ℕ) : Γ := by apply l.liftOn (fun l ↦ List.getI l n) rintro l _ ⟨i, rfl⟩ cases' lt_or_le n _ with h h · rw [List.getI_append _ _ _ h] rw [List.getI_eq_default _ h] rcases le_or_lt _ n with h₂ | h₂ · rw [List.getI_eq_default _ h₂] rw [List.getI_eq_get _ h₂, List.get_eq_getElem, List.getElem_append_right' h, List.getElem_replicate] @[simp] theorem ListBlank.nth_mk {Γ} [Inhabited Γ] (l : List Γ) (n : ℕ) : (ListBlank.mk l).nth n = l.getI n := rfl @[simp] theorem ListBlank.nth_zero {Γ} [Inhabited Γ] (l : ListBlank Γ) : l.nth 0 = l.head := by conv => lhs; rw [← ListBlank.cons_head_tail l] exact Quotient.inductionOn' l.tail fun l ↦ rfl @[simp] theorem ListBlank.nth_succ {Γ} [Inhabited Γ] (l : ListBlank Γ) (n : ℕ) : l.nth (n + 1) = l.tail.nth n := by conv => lhs; rw [← ListBlank.cons_head_tail l] exact Quotient.inductionOn' l.tail fun l ↦ rfl @[ext] theorem ListBlank.ext {Γ} [i : Inhabited Γ] {L₁ L₂ : ListBlank Γ} : (∀ i, L₁.nth i = L₂.nth i) → L₁ = L₂ := by refine ListBlank.induction_on L₁ fun l₁ ↦ ListBlank.induction_on L₂ fun l₂ H ↦ ?_ wlog h : l₁.length ≤ l₂.length · cases le_total l₁.length l₂.length <;> [skip; symm] <;> apply this <;> try assumption intro rw [H] refine Quotient.sound' (Or.inl ⟨l₂.length - l₁.length, ?_⟩) refine List.ext_get ?_ fun i h h₂ ↦ Eq.symm ?_ · simp only [Nat.add_sub_cancel' h, List.length_append, List.length_replicate] simp only [ListBlank.nth_mk] at H cases' lt_or_le i l₁.length with h' h' · simp only [List.get_append _ h', List.get?_eq_get h, List.get?_eq_get h', ← List.getI_eq_get _ h, ← List.getI_eq_get _ h', H] · simp only [List.get_append_right' h', List.get_replicate, List.get?_eq_get h, List.get?_len_le h', ← List.getI_eq_default _ h', H, List.getI_eq_get _ h] /-- Apply a function to a value stored at the nth position of the list. -/ @[simp] def ListBlank.modifyNth {Γ} [Inhabited Γ] (f : Γ → Γ) : ℕ → ListBlank Γ → ListBlank Γ | 0, L => L.tail.cons (f L.head) | n + 1, L => (L.tail.modifyNth f n).cons L.head theorem ListBlank.nth_modifyNth {Γ} [Inhabited Γ] (f : Γ → Γ) (n i) (L : ListBlank Γ) : (L.modifyNth f n).nth i = if i = n then f (L.nth i) else L.nth i := by induction' n with n IH generalizing i L · cases i <;> simp only [ListBlank.nth_zero, if_true, ListBlank.head_cons, ListBlank.modifyNth, ListBlank.nth_succ, if_false, ListBlank.tail_cons, Nat.zero_eq] · cases i · rw [if_neg (Nat.succ_ne_zero _).symm] simp only [ListBlank.nth_zero, ListBlank.head_cons, ListBlank.modifyNth, Nat.zero_eq] · simp only [IH, ListBlank.modifyNth, ListBlank.nth_succ, ListBlank.tail_cons, Nat.succ.injEq] /-- A pointed map of `Inhabited` types is a map that sends one default value to the other. -/ structure PointedMap.{u, v} (Γ : Type u) (Γ' : Type v) [Inhabited Γ] [Inhabited Γ'] : Type max u v where /-- The map underlying this instance. -/ f : Γ → Γ' map_pt' : f default = default instance {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] : Inhabited (PointedMap Γ Γ') := ⟨⟨default, rfl⟩⟩ instance {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] : CoeFun (PointedMap Γ Γ') fun _ ↦ Γ → Γ' := ⟨PointedMap.f⟩ -- @[simp] -- Porting note (#10685): dsimp can prove this theorem PointedMap.mk_val {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (f : Γ → Γ') (pt) : (PointedMap.mk f pt : Γ → Γ') = f := rfl @[simp] theorem PointedMap.map_pt {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (f : PointedMap Γ Γ') : f default = default := PointedMap.map_pt' _ @[simp] theorem PointedMap.headI_map {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (f : PointedMap Γ Γ') (l : List Γ) : (l.map f).headI = f l.headI := by cases l <;> [exact (PointedMap.map_pt f).symm; rfl] /-- The `map` function on lists is well defined on `ListBlank`s provided that the map is pointed. -/ def ListBlank.map {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (f : PointedMap Γ Γ') (l : ListBlank Γ) : ListBlank Γ' := by apply l.liftOn (fun l ↦ ListBlank.mk (List.map f l)) rintro l _ ⟨i, rfl⟩; refine Quotient.sound' (Or.inl ⟨i, ?_⟩) simp only [PointedMap.map_pt, List.map_append, List.map_replicate] @[simp] theorem ListBlank.map_mk {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (f : PointedMap Γ Γ') (l : List Γ) : (ListBlank.mk l).map f = ListBlank.mk (l.map f) := rfl @[simp] theorem ListBlank.head_map {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (f : PointedMap Γ Γ') (l : ListBlank Γ) : (l.map f).head = f l.head := by conv => lhs; rw [← ListBlank.cons_head_tail l] exact Quotient.inductionOn' l fun a ↦ rfl @[simp] theorem ListBlank.tail_map {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (f : PointedMap Γ Γ') (l : ListBlank Γ) : (l.map f).tail = l.tail.map f := by conv => lhs; rw [← ListBlank.cons_head_tail l] exact Quotient.inductionOn' l fun a ↦ rfl @[simp] theorem ListBlank.map_cons {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (f : PointedMap Γ Γ') (l : ListBlank Γ) (a : Γ) : (l.cons a).map f = (l.map f).cons (f a) := by refine (ListBlank.cons_head_tail _).symm.trans ?_ simp only [ListBlank.head_map, ListBlank.head_cons, ListBlank.tail_map, ListBlank.tail_cons] @[simp] theorem ListBlank.nth_map {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (f : PointedMap Γ Γ') (l : ListBlank Γ) (n : ℕ) : (l.map f).nth n = f (l.nth n) := by refine l.inductionOn fun l ↦ ?_ -- Porting note: Added `suffices` to get `simp` to work. suffices ((mk l).map f).nth n = f ((mk l).nth n) by exact this simp only [List.get?_map, ListBlank.map_mk, ListBlank.nth_mk, List.getI_eq_iget_get?] cases l.get? n · exact f.2.symm · rfl /-- The `i`-th projection as a pointed map. -/ def proj {ι : Type*} {Γ : ι → Type*} [∀ i, Inhabited (Γ i)] (i : ι) : PointedMap (∀ i, Γ i) (Γ i) := ⟨fun a ↦ a i, rfl⟩ theorem proj_map_nth {ι : Type*} {Γ : ι → Type*} [∀ i, Inhabited (Γ i)] (i : ι) (L n) : (ListBlank.map (@proj ι Γ _ i) L).nth n = L.nth n i := by rw [ListBlank.nth_map]; rfl theorem ListBlank.map_modifyNth {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (F : PointedMap Γ Γ') (f : Γ → Γ) (f' : Γ' → Γ') (H : ∀ x, F (f x) = f' (F x)) (n) (L : ListBlank Γ) : (L.modifyNth f n).map F = (L.map F).modifyNth f' n := by induction' n with n IH generalizing L <;> simp only [*, ListBlank.head_map, ListBlank.modifyNth, ListBlank.map_cons, ListBlank.tail_map] /-- Append a list on the left side of a `ListBlank`. -/ @[simp] def ListBlank.append {Γ} [Inhabited Γ] : List Γ → ListBlank Γ → ListBlank Γ | [], L => L | a :: l, L => ListBlank.cons a (ListBlank.append l L) @[simp] theorem ListBlank.append_mk {Γ} [Inhabited Γ] (l₁ l₂ : List Γ) : ListBlank.append l₁ (ListBlank.mk l₂) = ListBlank.mk (l₁ ++ l₂) := by induction l₁ <;> simp only [*, ListBlank.append, List.nil_append, List.cons_append, ListBlank.cons_mk] theorem ListBlank.append_assoc {Γ} [Inhabited Γ] (l₁ l₂ : List Γ) (l₃ : ListBlank Γ) : ListBlank.append (l₁ ++ l₂) l₃ = ListBlank.append l₁ (ListBlank.append l₂ l₃) := by refine l₃.inductionOn fun l ↦ ?_ -- Porting note: Added `suffices` to get `simp` to work. suffices append (l₁ ++ l₂) (mk l) = append l₁ (append l₂ (mk l)) by exact this simp only [ListBlank.append_mk, List.append_assoc] /-- The `bind` function on lists is well defined on `ListBlank`s provided that the default element is sent to a sequence of default elements. -/ def ListBlank.bind {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (l : ListBlank Γ) (f : Γ → List Γ') (hf : ∃ n, f default = List.replicate n default) : ListBlank Γ' := by apply l.liftOn (fun l ↦ ListBlank.mk (List.bind l f)) rintro l _ ⟨i, rfl⟩; cases' hf with n e; refine Quotient.sound' (Or.inl ⟨i * n, ?_⟩) rw [List.append_bind, mul_comm]; congr induction' i with i IH · rfl simp only [IH, e, List.replicate_add, Nat.mul_succ, add_comm, List.replicate_succ, List.cons_bind] @[simp] theorem ListBlank.bind_mk {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (l : List Γ) (f : Γ → List Γ') (hf) : (ListBlank.mk l).bind f hf = ListBlank.mk (l.bind f) := rfl @[simp] theorem ListBlank.cons_bind {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (a : Γ) (l : ListBlank Γ) (f : Γ → List Γ') (hf) : (l.cons a).bind f hf = (l.bind f hf).append (f a) := by refine l.inductionOn fun l ↦ ?_ -- Porting note: Added `suffices` to get `simp` to work. suffices ((mk l).cons a).bind f hf = ((mk l).bind f hf).append (f a) by exact this simp only [ListBlank.append_mk, ListBlank.bind_mk, ListBlank.cons_mk, List.cons_bind] /-- The tape of a Turing machine is composed of a head element (which we imagine to be the current position of the head), together with two `ListBlank`s denoting the portions of the tape going off to the left and right. When the Turing machine moves right, an element is pulled from the right side and becomes the new head, while the head element is `cons`ed onto the left side. -/ structure Tape (Γ : Type*) [Inhabited Γ] where /-- The current position of the head. -/ head : Γ /-- The portion of the tape going off to the left. -/ left : ListBlank Γ /-- The portion of the tape going off to the right. -/ right : ListBlank Γ instance Tape.inhabited {Γ} [Inhabited Γ] : Inhabited (Tape Γ) := ⟨by constructor <;> apply default⟩ /-- A direction for the Turing machine `move` command, either left or right. -/ inductive Dir | left | right deriving DecidableEq, Inhabited /-- The "inclusive" left side of the tape, including both `left` and `head`. -/ def Tape.left₀ {Γ} [Inhabited Γ] (T : Tape Γ) : ListBlank Γ := T.left.cons T.head /-- The "inclusive" right side of the tape, including both `right` and `head`. -/ def Tape.right₀ {Γ} [Inhabited Γ] (T : Tape Γ) : ListBlank Γ := T.right.cons T.head /-- Move the tape in response to a motion of the Turing machine. Note that `T.move Dir.left` makes `T.left` smaller; the Turing machine is moving left and the tape is moving right. -/ def Tape.move {Γ} [Inhabited Γ] : Dir → Tape Γ → Tape Γ | Dir.left, ⟨a, L, R⟩ => ⟨L.head, L.tail, R.cons a⟩ | Dir.right, ⟨a, L, R⟩ => ⟨R.head, L.cons a, R.tail⟩ @[simp] theorem Tape.move_left_right {Γ} [Inhabited Γ] (T : Tape Γ) : (T.move Dir.left).move Dir.right = T := by cases T; simp [Tape.move] @[simp] theorem Tape.move_right_left {Γ} [Inhabited Γ] (T : Tape Γ) : (T.move Dir.right).move Dir.left = T := by cases T; simp [Tape.move] /-- Construct a tape from a left side and an inclusive right side. -/ def Tape.mk' {Γ} [Inhabited Γ] (L R : ListBlank Γ) : Tape Γ := ⟨R.head, L, R.tail⟩ @[simp] theorem Tape.mk'_left {Γ} [Inhabited Γ] (L R : ListBlank Γ) : (Tape.mk' L R).left = L := rfl @[simp] theorem Tape.mk'_head {Γ} [Inhabited Γ] (L R : ListBlank Γ) : (Tape.mk' L R).head = R.head := rfl @[simp] theorem Tape.mk'_right {Γ} [Inhabited Γ] (L R : ListBlank Γ) : (Tape.mk' L R).right = R.tail := rfl @[simp] theorem Tape.mk'_right₀ {Γ} [Inhabited Γ] (L R : ListBlank Γ) : (Tape.mk' L R).right₀ = R := ListBlank.cons_head_tail _ @[simp] theorem Tape.mk'_left_right₀ {Γ} [Inhabited Γ] (T : Tape Γ) : Tape.mk' T.left T.right₀ = T := by cases T simp only [Tape.right₀, Tape.mk', ListBlank.head_cons, ListBlank.tail_cons, eq_self_iff_true, and_self_iff] theorem Tape.exists_mk' {Γ} [Inhabited Γ] (T : Tape Γ) : ∃ L R, T = Tape.mk' L R := ⟨_, _, (Tape.mk'_left_right₀ _).symm⟩ @[simp] theorem Tape.move_left_mk' {Γ} [Inhabited Γ] (L R : ListBlank Γ) : (Tape.mk' L R).move Dir.left = Tape.mk' L.tail (R.cons L.head) := by simp only [Tape.move, Tape.mk', ListBlank.head_cons, eq_self_iff_true, ListBlank.cons_head_tail, and_self_iff, ListBlank.tail_cons] @[simp] theorem Tape.move_right_mk' {Γ} [Inhabited Γ] (L R : ListBlank Γ) : (Tape.mk' L R).move Dir.right = Tape.mk' (L.cons R.head) R.tail := by simp only [Tape.move, Tape.mk', ListBlank.head_cons, eq_self_iff_true, ListBlank.cons_head_tail, and_self_iff, ListBlank.tail_cons] /-- Construct a tape from a left side and an inclusive right side. -/ def Tape.mk₂ {Γ} [Inhabited Γ] (L R : List Γ) : Tape Γ := Tape.mk' (ListBlank.mk L) (ListBlank.mk R) /-- Construct a tape from a list, with the head of the list at the TM head and the rest going to the right. -/ def Tape.mk₁ {Γ} [Inhabited Γ] (l : List Γ) : Tape Γ := Tape.mk₂ [] l /-- The `nth` function of a tape is integer-valued, with index `0` being the head, negative indexes on the left and positive indexes on the right. (Picture a number line.) -/ def Tape.nth {Γ} [Inhabited Γ] (T : Tape Γ) : ℤ → Γ | 0 => T.head | (n + 1 : ℕ) => T.right.nth n | -(n + 1 : ℕ) => T.left.nth n @[simp] theorem Tape.nth_zero {Γ} [Inhabited Γ] (T : Tape Γ) : T.nth 0 = T.1 := rfl theorem Tape.right₀_nth {Γ} [Inhabited Γ] (T : Tape Γ) (n : ℕ) : T.right₀.nth n = T.nth n := by cases n <;> simp only [Tape.nth, Tape.right₀, Int.ofNat_zero, ListBlank.nth_zero, ListBlank.nth_succ, ListBlank.head_cons, ListBlank.tail_cons, Nat.zero_eq] @[simp] theorem Tape.mk'_nth_nat {Γ} [Inhabited Γ] (L R : ListBlank Γ) (n : ℕ) : (Tape.mk' L R).nth n = R.nth n := by rw [← Tape.right₀_nth, Tape.mk'_right₀] @[simp] theorem Tape.move_left_nth {Γ} [Inhabited Γ] : ∀ (T : Tape Γ) (i : ℤ), (T.move Dir.left).nth i = T.nth (i - 1) | ⟨_, L, _⟩, -(n + 1 : ℕ) => (ListBlank.nth_succ _ _).symm | ⟨_, L, _⟩, 0 => (ListBlank.nth_zero _).symm | ⟨a, L, R⟩, 1 => (ListBlank.nth_zero _).trans (ListBlank.head_cons _ _) | ⟨a, L, R⟩, (n + 1 : ℕ) + 1 => by rw [add_sub_cancel_right] change (R.cons a).nth (n + 1) = R.nth n rw [ListBlank.nth_succ, ListBlank.tail_cons] @[simp] theorem Tape.move_right_nth {Γ} [Inhabited Γ] (T : Tape Γ) (i : ℤ) : (T.move Dir.right).nth i = T.nth (i + 1) := by conv => rhs; rw [← T.move_right_left] rw [Tape.move_left_nth, add_sub_cancel_right] @[simp] theorem Tape.move_right_n_head {Γ} [Inhabited Γ] (T : Tape Γ) (i : ℕ) : ((Tape.move Dir.right)^[i] T).head = T.nth i := by induction i generalizing T · rfl · simp only [*, Tape.move_right_nth, Int.ofNat_succ, iterate_succ, Function.comp_apply] /-- Replace the current value of the head on the tape. -/ def Tape.write {Γ} [Inhabited Γ] (b : Γ) (T : Tape Γ) : Tape Γ := { T with head := b } @[simp] theorem Tape.write_self {Γ} [Inhabited Γ] : ∀ T : Tape Γ, T.write T.1 = T := by rintro ⟨⟩; rfl @[simp] theorem Tape.write_nth {Γ} [Inhabited Γ] (b : Γ) : ∀ (T : Tape Γ) {i : ℤ}, (T.write b).nth i = if i = 0 then b else T.nth i | _, 0 => rfl | _, (_ + 1 : ℕ) => rfl | _, -(_ + 1 : ℕ) => rfl @[simp] theorem Tape.write_mk' {Γ} [Inhabited Γ] (a b : Γ) (L R : ListBlank Γ) : (Tape.mk' L (R.cons a)).write b = Tape.mk' L (R.cons b) := by simp only [Tape.write, Tape.mk', ListBlank.head_cons, ListBlank.tail_cons, eq_self_iff_true, and_self_iff] /-- Apply a pointed map to a tape to change the alphabet. -/ def Tape.map {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (f : PointedMap Γ Γ') (T : Tape Γ) : Tape Γ' := ⟨f T.1, T.2.map f, T.3.map f⟩ @[simp] theorem Tape.map_fst {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (f : PointedMap Γ Γ') : ∀ T : Tape Γ, (T.map f).1 = f T.1 := by rintro ⟨⟩; rfl @[simp] theorem Tape.map_write {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (f : PointedMap Γ Γ') (b : Γ) : ∀ T : Tape Γ, (T.write b).map f = (T.map f).write (f b) := by rintro ⟨⟩; rfl -- Porting note: `simpNF` complains about LHS does not simplify when using the simp lemma on -- itself, but it does indeed. @[simp, nolint simpNF] theorem Tape.write_move_right_n {Γ} [Inhabited Γ] (f : Γ → Γ) (L R : ListBlank Γ) (n : ℕ) : ((Tape.move Dir.right)^[n] (Tape.mk' L R)).write (f (R.nth n)) = (Tape.move Dir.right)^[n] (Tape.mk' L (R.modifyNth f n)) := by induction' n with n IH generalizing L R · simp only [ListBlank.nth_zero, ListBlank.modifyNth, iterate_zero_apply, Nat.zero_eq] rw [← Tape.write_mk', ListBlank.cons_head_tail] simp only [ListBlank.head_cons, ListBlank.nth_succ, ListBlank.modifyNth, Tape.move_right_mk', ListBlank.tail_cons, iterate_succ_apply, IH] theorem Tape.map_move {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (f : PointedMap Γ Γ') (T : Tape Γ) (d) : (T.move d).map f = (T.map f).move d := by cases T cases d <;> simp only [Tape.move, Tape.map, ListBlank.head_map, eq_self_iff_true, ListBlank.map_cons, and_self_iff, ListBlank.tail_map] theorem Tape.map_mk' {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (f : PointedMap Γ Γ') (L R : ListBlank Γ) : (Tape.mk' L R).map f = Tape.mk' (L.map f) (R.map f) := by simp only [Tape.mk', Tape.map, ListBlank.head_map, eq_self_iff_true, and_self_iff, ListBlank.tail_map] theorem Tape.map_mk₂ {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (f : PointedMap Γ Γ') (L R : List Γ) : (Tape.mk₂ L R).map f = Tape.mk₂ (L.map f) (R.map f) := by simp only [Tape.mk₂, Tape.map_mk', ListBlank.map_mk] theorem Tape.map_mk₁ {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (f : PointedMap Γ Γ') (l : List Γ) : (Tape.mk₁ l).map f = Tape.mk₁ (l.map f) := Tape.map_mk₂ _ _ _ /-- Run a state transition function `σ → Option σ` "to completion". The return value is the last state returned before a `none` result. If the state transition function always returns `some`, then the computation diverges, returning `Part.none`. -/ def eval {σ} (f : σ → Option σ) : σ → Part σ := PFun.fix fun s ↦ Part.some <| (f s).elim (Sum.inl s) Sum.inr /-- The reflexive transitive closure of a state transition function. `Reaches f a b` means there is a finite sequence of steps `f a = some a₁`, `f a₁ = some a₂`, ... such that `aₙ = b`. This relation permits zero steps of the state transition function. -/ def Reaches {σ} (f : σ → Option σ) : σ → σ → Prop := ReflTransGen fun a b ↦ b ∈ f a /-- The transitive closure of a state transition function. `Reaches₁ f a b` means there is a nonempty finite sequence of steps `f a = some a₁`, `f a₁ = some a₂`, ... such that `aₙ = b`. This relation does not permit zero steps of the state transition function. -/ def Reaches₁ {σ} (f : σ → Option σ) : σ → σ → Prop := TransGen fun a b ↦ b ∈ f a theorem reaches₁_eq {σ} {f : σ → Option σ} {a b c} (h : f a = f b) : Reaches₁ f a c ↔ Reaches₁ f b c := TransGen.head'_iff.trans (TransGen.head'_iff.trans <| by rw [h]).symm theorem reaches_total {σ} {f : σ → Option σ} {a b c} (hab : Reaches f a b) (hac : Reaches f a c) : Reaches f b c ∨ Reaches f c b := ReflTransGen.total_of_right_unique (fun _ _ _ ↦ Option.mem_unique) hab hac theorem reaches₁_fwd {σ} {f : σ → Option σ} {a b c} (h₁ : Reaches₁ f a c) (h₂ : b ∈ f a) : Reaches f b c := by rcases TransGen.head'_iff.1 h₁ with ⟨b', hab, hbc⟩ cases Option.mem_unique hab h₂; exact hbc /-- A variation on `Reaches`. `Reaches₀ f a b` holds if whenever `Reaches₁ f b c` then `Reaches₁ f a c`. This is a weaker property than `Reaches` and is useful for replacing states with equivalent states without taking a step. -/ def Reaches₀ {σ} (f : σ → Option σ) (a b : σ) : Prop := ∀ c, Reaches₁ f b c → Reaches₁ f a c theorem Reaches₀.trans {σ} {f : σ → Option σ} {a b c : σ} (h₁ : Reaches₀ f a b) (h₂ : Reaches₀ f b c) : Reaches₀ f a c | _, h₃ => h₁ _ (h₂ _ h₃) @[refl] theorem Reaches₀.refl {σ} {f : σ → Option σ} (a : σ) : Reaches₀ f a a | _, h => h theorem Reaches₀.single {σ} {f : σ → Option σ} {a b : σ} (h : b ∈ f a) : Reaches₀ f a b | _, h₂ => h₂.head h theorem Reaches₀.head {σ} {f : σ → Option σ} {a b c : σ} (h : b ∈ f a) (h₂ : Reaches₀ f b c) : Reaches₀ f a c := (Reaches₀.single h).trans h₂ theorem Reaches₀.tail {σ} {f : σ → Option σ} {a b c : σ} (h₁ : Reaches₀ f a b) (h : c ∈ f b) : Reaches₀ f a c := h₁.trans (Reaches₀.single h) theorem reaches₀_eq {σ} {f : σ → Option σ} {a b} (e : f a = f b) : Reaches₀ f a b | _, h => (reaches₁_eq e).2 h theorem Reaches₁.to₀ {σ} {f : σ → Option σ} {a b : σ} (h : Reaches₁ f a b) : Reaches₀ f a b | _, h₂ => h.trans h₂ theorem Reaches.to₀ {σ} {f : σ → Option σ} {a b : σ} (h : Reaches f a b) : Reaches₀ f a b | _, h₂ => h₂.trans_right h theorem Reaches₀.tail' {σ} {f : σ → Option σ} {a b c : σ} (h : Reaches₀ f a b) (h₂ : c ∈ f b) : Reaches₁ f a c := h _ (TransGen.single h₂) /-- (co-)Induction principle for `eval`. If a property `C` holds of any point `a` evaluating to `b` which is either terminal (meaning `a = b`) or where the next point also satisfies `C`, then it holds of any point where `eval f a` evaluates to `b`. This formalizes the notion that if `eval f a` evaluates to `b` then it reaches terminal state `b` in finitely many steps. -/ @[elab_as_elim] def evalInduction {σ} {f : σ → Option σ} {b : σ} {C : σ → Sort*} {a : σ} (h : b ∈ eval f a) (H : ∀ a, b ∈ eval f a → (∀ a', f a = some a' → C a') → C a) : C a := PFun.fixInduction h fun a' ha' h' ↦ H _ ha' fun b' e ↦ h' _ <| Part.mem_some_iff.2 <| by rw [e]; rfl theorem mem_eval {σ} {f : σ → Option σ} {a b} : b ∈ eval f a ↔ Reaches f a b ∧ f b = none := by refine ⟨fun h ↦ ?_, fun ⟨h₁, h₂⟩ ↦ ?_⟩ · -- Porting note: Explicitly specify `c`. refine @evalInduction _ _ _ (fun a ↦ Reaches f a b ∧ f b = none) _ h fun a h IH ↦ ?_ cases' e : f a with a' · rw [Part.mem_unique h (PFun.mem_fix_iff.2 <| Or.inl <| Part.mem_some_iff.2 <| by rw [e]; rfl)] exact ⟨ReflTransGen.refl, e⟩ · rcases PFun.mem_fix_iff.1 h with (h | ⟨_, h, _⟩) <;> rw [e] at h <;> cases Part.mem_some_iff.1 h cases' IH a' e with h₁ h₂ exact ⟨ReflTransGen.head e h₁, h₂⟩ · refine ReflTransGen.head_induction_on h₁ ?_ fun h _ IH ↦ ?_ · refine PFun.mem_fix_iff.2 (Or.inl ?_) rw [h₂] apply Part.mem_some · refine PFun.mem_fix_iff.2 (Or.inr ⟨_, ?_, IH⟩) rw [h] apply Part.mem_some theorem eval_maximal₁ {σ} {f : σ → Option σ} {a b} (h : b ∈ eval f a) (c) : ¬Reaches₁ f b c | bc => by let ⟨_, b0⟩ := mem_eval.1 h let ⟨b', h', _⟩ := TransGen.head'_iff.1 bc cases b0.symm.trans h' theorem eval_maximal {σ} {f : σ → Option σ} {a b} (h : b ∈ eval f a) {c} : Reaches f b c ↔ c = b := let ⟨_, b0⟩ := mem_eval.1 h reflTransGen_iff_eq fun b' h' ↦ by cases b0.symm.trans h' theorem reaches_eval {σ} {f : σ → Option σ} {a b} (ab : Reaches f a b) : eval f a = eval f b := by refine Part.ext fun _ ↦ ⟨fun h ↦ ?_, fun h ↦ ?_⟩ · have ⟨ac, c0⟩ := mem_eval.1 h exact mem_eval.2 ⟨(or_iff_left_of_imp fun cb ↦ (eval_maximal h).1 cb ▸ ReflTransGen.refl).1 (reaches_total ab ac), c0⟩ · have ⟨bc, c0⟩ := mem_eval.1 h exact mem_eval.2 ⟨ab.trans bc, c0⟩ /-- Given a relation `tr : σ₁ → σ₂ → Prop` between state spaces, and state transition functions `f₁ : σ₁ → Option σ₁` and `f₂ : σ₂ → Option σ₂`, `Respects f₁ f₂ tr` means that if `tr a₁ a₂` holds initially and `f₁` takes a step to `a₂` then `f₂` will take one or more steps before reaching a state `b₂` satisfying `tr a₂ b₂`, and if `f₁ a₁` terminates then `f₂ a₂` also terminates. Such a relation `tr` is also known as a refinement. -/ def Respects {σ₁ σ₂} (f₁ : σ₁ → Option σ₁) (f₂ : σ₂ → Option σ₂) (tr : σ₁ → σ₂ → Prop) := ∀ ⦃a₁ a₂⦄, tr a₁ a₂ → (match f₁ a₁ with | some b₁ => ∃ b₂, tr b₁ b₂ ∧ Reaches₁ f₂ a₂ b₂ | none => f₂ a₂ = none : Prop) theorem tr_reaches₁ {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : Respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₁} (ab : Reaches₁ f₁ a₁ b₁) : ∃ b₂, tr b₁ b₂ ∧ Reaches₁ f₂ a₂ b₂ := by induction' ab with c₁ ac c₁ d₁ _ cd IH · have := H aa rwa [show f₁ a₁ = _ from ac] at this · rcases IH with ⟨c₂, cc, ac₂⟩ have := H cc rw [show f₁ c₁ = _ from cd] at this rcases this with ⟨d₂, dd, cd₂⟩ exact ⟨_, dd, ac₂.trans cd₂⟩ theorem tr_reaches {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : Respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₁} (ab : Reaches f₁ a₁ b₁) : ∃ b₂, tr b₁ b₂ ∧ Reaches f₂ a₂ b₂ := by rcases reflTransGen_iff_eq_or_transGen.1 ab with (rfl | ab) · exact ⟨_, aa, ReflTransGen.refl⟩ · have ⟨b₂, bb, h⟩ := tr_reaches₁ H aa ab exact ⟨b₂, bb, h.to_reflTransGen⟩ theorem tr_reaches_rev {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : Respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₂} (ab : Reaches f₂ a₂ b₂) : ∃ c₁ c₂, Reaches f₂ b₂ c₂ ∧ tr c₁ c₂ ∧ Reaches f₁ a₁ c₁ := by induction' ab with c₂ d₂ _ cd IH · exact ⟨_, _, ReflTransGen.refl, aa, ReflTransGen.refl⟩ · rcases IH with ⟨e₁, e₂, ce, ee, ae⟩ rcases ReflTransGen.cases_head ce with (rfl | ⟨d', cd', de⟩) · have := H ee revert this cases' eg : f₁ e₁ with g₁ <;> simp only [Respects, and_imp, exists_imp] · intro c0 cases cd.symm.trans c0 · intro g₂ gg cg rcases TransGen.head'_iff.1 cg with ⟨d', cd', dg⟩ cases Option.mem_unique cd cd' exact ⟨_, _, dg, gg, ae.tail eg⟩ · cases Option.mem_unique cd cd' exact ⟨_, _, de, ee, ae⟩ theorem tr_eval {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : Respects f₁ f₂ tr) {a₁ b₁ a₂} (aa : tr a₁ a₂) (ab : b₁ ∈ eval f₁ a₁) : ∃ b₂, tr b₁ b₂ ∧ b₂ ∈ eval f₂ a₂ := by cases' mem_eval.1 ab with ab b0 rcases tr_reaches H aa ab with ⟨b₂, bb, ab⟩ refine ⟨_, bb, mem_eval.2 ⟨ab, ?_⟩⟩ have := H bb; rwa [b0] at this theorem tr_eval_rev {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : Respects f₁ f₂ tr) {a₁ b₂ a₂} (aa : tr a₁ a₂) (ab : b₂ ∈ eval f₂ a₂) : ∃ b₁, tr b₁ b₂ ∧ b₁ ∈ eval f₁ a₁ := by cases' mem_eval.1 ab with ab b0 rcases tr_reaches_rev H aa ab with ⟨c₁, c₂, bc, cc, ac⟩ cases (reflTransGen_iff_eq (Option.eq_none_iff_forall_not_mem.1 b0)).1 bc refine ⟨_, cc, mem_eval.2 ⟨ac, ?_⟩⟩ have := H cc cases' hfc : f₁ c₁ with d₁ · rfl rw [hfc] at this rcases this with ⟨d₂, _, bd⟩ rcases TransGen.head'_iff.1 bd with ⟨e, h, _⟩ cases b0.symm.trans h theorem tr_eval_dom {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : Respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) : (eval f₂ a₂).Dom ↔ (eval f₁ a₁).Dom := ⟨fun h ↦ let ⟨_, _, h, _⟩ := tr_eval_rev H aa ⟨h, rfl⟩ h, fun h ↦ let ⟨_, _, h, _⟩ := tr_eval H aa ⟨h, rfl⟩ h⟩ /-- A simpler version of `Respects` when the state transition relation `tr` is a function. -/ def FRespects {σ₁ σ₂} (f₂ : σ₂ → Option σ₂) (tr : σ₁ → σ₂) (a₂ : σ₂) : Option σ₁ → Prop | some b₁ => Reaches₁ f₂ a₂ (tr b₁) | none => f₂ a₂ = none theorem frespects_eq {σ₁ σ₂} {f₂ : σ₂ → Option σ₂} {tr : σ₁ → σ₂} {a₂ b₂} (h : f₂ a₂ = f₂ b₂) : ∀ {b₁}, FRespects f₂ tr a₂ b₁ ↔ FRespects f₂ tr b₂ b₁ | some b₁ => reaches₁_eq h | none => by unfold FRespects; rw [h] theorem fun_respects {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂} : (Respects f₁ f₂ fun a b ↦ tr a = b) ↔ ∀ ⦃a₁⦄, FRespects f₂ tr (tr a₁) (f₁ a₁) := forall_congr' fun a₁ ↦ by cases f₁ a₁ <;> simp only [FRespects, Respects, exists_eq_left', forall_eq'] theorem tr_eval' {σ₁ σ₂} (f₁ : σ₁ → Option σ₁) (f₂ : σ₂ → Option σ₂) (tr : σ₁ → σ₂) (H : Respects f₁ f₂ fun a b ↦ tr a = b) (a₁) : eval f₂ (tr a₁) = tr <$> eval f₁ a₁ := Part.ext fun b₂ ↦ ⟨fun h ↦ let ⟨b₁, bb, hb⟩ := tr_eval_rev H rfl h (Part.mem_map_iff _).2 ⟨b₁, hb, bb⟩, fun h ↦ by rcases (Part.mem_map_iff _).1 h with ⟨b₁, ab, bb⟩ rcases tr_eval H rfl ab with ⟨_, rfl, h⟩ rwa [bb] at h⟩ /-! ## The TM0 model A TM0 Turing machine is essentially a Post-Turing machine, adapted for type theory. A Post-Turing machine with symbol type `Γ` and label type `Λ` is a function `Λ → Γ → Option (Λ × Stmt)`, where a `Stmt` can be either `move left`, `move right` or `write a` for `a : Γ`. The machine works over a "tape", a doubly-infinite sequence of elements of `Γ`, and an instantaneous configuration, `Cfg`, is a label `q : Λ` indicating the current internal state of the machine, and a `Tape Γ` (which is essentially `ℤ →₀ Γ`). The evolution is described by the `step` function: * If `M q T.head = none`, then the machine halts. * If `M q T.head = some (q', s)`, then the machine performs action `s : Stmt` and then transitions to state `q'`. The initial state takes a `List Γ` and produces a `Tape Γ` where the head of the list is the head of the tape and the rest of the list extends to the right, with the left side all blank. The final state takes the entire right side of the tape right or equal to the current position of the machine. (This is actually a `ListBlank Γ`, not a `List Γ`, because we don't know, at this level of generality, where the output ends. If equality to `default : Γ` is decidable we can trim the list to remove the infinite tail of blanks.) -/ namespace TM0 section -- type of tape symbols variable (Γ : Type*) [Inhabited Γ] -- type of "labels" or TM states variable (Λ : Type*) [Inhabited Λ] /-- A Turing machine "statement" is just a command to either move left or right, or write a symbol on the tape. -/ inductive Stmt | move : Dir → Stmt | write : Γ → Stmt local notation "Stmt₀" => Stmt Γ -- Porting note (#10750): added this to clean up types. instance Stmt.inhabited : Inhabited Stmt₀ := ⟨Stmt.write default⟩ /-- A Post-Turing machine with symbol type `Γ` and label type `Λ` is a function which, given the current state `q : Λ` and the tape head `a : Γ`, either halts (returns `none`) or returns a new state `q' : Λ` and a `Stmt` describing what to do, either a move left or right, or a write command. Both `Λ` and `Γ` are required to be inhabited; the default value for `Γ` is the "blank" tape value, and the default value of `Λ` is the initial state. -/ @[nolint unusedArguments] -- this is a deliberate addition, see comment def Machine [Inhabited Λ] := Λ → Γ → Option (Λ × Stmt₀) local notation "Machine₀" => Machine Γ Λ -- Porting note (#10750): added this to clean up types. instance Machine.inhabited : Inhabited Machine₀ := by unfold Machine; infer_instance /-- The configuration state of a Turing machine during operation consists of a label (machine state), and a tape. The tape is represented in the form `(a, L, R)`, meaning the tape looks like `L.rev ++ [a] ++ R` with the machine currently reading the `a`. The lists are automatically extended with blanks as the machine moves around. -/ structure Cfg where /-- The current machine state. -/ q : Λ /-- The current state of the tape: current symbol, left and right parts. -/ Tape : Tape Γ local notation "Cfg₀" => Cfg Γ Λ -- Porting note (#10750): added this to clean up types. instance Cfg.inhabited : Inhabited Cfg₀ := ⟨⟨default, default⟩⟩ variable {Γ Λ} /-- Execution semantics of the Turing machine. -/ def step (M : Machine₀) : Cfg₀ → Option Cfg₀ := fun ⟨q, T⟩ ↦ (M q T.1).map fun ⟨q', a⟩ ↦ ⟨q', match a with | Stmt.move d => T.move d | Stmt.write a => T.write a⟩ /-- The statement `Reaches M s₁ s₂` means that `s₂` is obtained starting from `s₁` after a finite number of steps from `s₂`. -/ def Reaches (M : Machine₀) : Cfg₀ → Cfg₀ → Prop := ReflTransGen fun a b ↦ b ∈ step M a /-- The initial configuration. -/ def init (l : List Γ) : Cfg₀ := ⟨default, Tape.mk₁ l⟩ /-- Evaluate a Turing machine on initial input to a final state, if it terminates. -/ def eval (M : Machine₀) (l : List Γ) : Part (ListBlank Γ) := (Turing.eval (step M) (init l)).map fun c ↦ c.Tape.right₀ /-- The raw definition of a Turing machine does not require that `Γ` and `Λ` are finite, and in practice we will be interested in the infinite `Λ` case. We recover instead a notion of "effectively finite" Turing machines, which only make use of a finite subset of their states. We say that a set `S ⊆ Λ` supports a Turing machine `M` if `S` is closed under the transition function and contains the initial state. -/ def Supports (M : Machine₀) (S : Set Λ) := default ∈ S ∧ ∀ {q a q' s}, (q', s) ∈ M q a → q ∈ S → q' ∈ S theorem step_supports (M : Machine₀) {S : Set Λ} (ss : Supports M S) : ∀ {c c' : Cfg₀}, c' ∈ step M c → c.q ∈ S → c'.q ∈ S := by intro ⟨q, T⟩ c' h₁ h₂ rcases Option.map_eq_some'.1 h₁ with ⟨⟨q', a⟩, h, rfl⟩ exact ss.2 h h₂ theorem univ_supports (M : Machine₀) : Supports M Set.univ := by constructor <;> intros <;> apply Set.mem_univ end section variable {Γ : Type*} [Inhabited Γ] variable {Γ' : Type*} [Inhabited Γ'] variable {Λ : Type*} [Inhabited Λ] variable {Λ' : Type*} [Inhabited Λ'] /-- Map a TM statement across a function. This does nothing to move statements and maps the write values. -/ def Stmt.map (f : PointedMap Γ Γ') : Stmt Γ → Stmt Γ' | Stmt.move d => Stmt.move d | Stmt.write a => Stmt.write (f a) /-- Map a configuration across a function, given `f : Γ → Γ'` a map of the alphabets and `g : Λ → Λ'` a map of the machine states. -/ def Cfg.map (f : PointedMap Γ Γ') (g : Λ → Λ') : Cfg Γ Λ → Cfg Γ' Λ' | ⟨q, T⟩ => ⟨g q, T.map f⟩ variable (M : Machine Γ Λ) (f₁ : PointedMap Γ Γ') (f₂ : PointedMap Γ' Γ) (g₁ : Λ → Λ') (g₂ : Λ' → Λ) /-- Because the state transition function uses the alphabet and machine states in both the input and output, to map a machine from one alphabet and machine state space to another we need functions in both directions, essentially an `Equiv` without the laws. -/ def Machine.map : Machine Γ' Λ' | q, l => (M (g₂ q) (f₂ l)).map (Prod.map g₁ (Stmt.map f₁)) theorem Machine.map_step {S : Set Λ} (f₂₁ : Function.RightInverse f₁ f₂) (g₂₁ : ∀ q ∈ S, g₂ (g₁ q) = q) : ∀ c : Cfg Γ Λ, c.q ∈ S → (step M c).map (Cfg.map f₁ g₁) = step (M.map f₁ f₂ g₁ g₂) (Cfg.map f₁ g₁ c) | ⟨q, T⟩, h => by unfold step Machine.map Cfg.map simp only [Turing.Tape.map_fst, g₂₁ q h, f₂₁ _] rcases M q T.1 with (_ | ⟨q', d | a⟩); · rfl · simp only [step, Cfg.map, Option.map_some', Tape.map_move f₁] rfl · simp only [step, Cfg.map, Option.map_some', Tape.map_write] rfl theorem map_init (g₁ : PointedMap Λ Λ') (l : List Γ) : (init l).map f₁ g₁ = init (l.map f₁) := congr (congr_arg Cfg.mk g₁.map_pt) (Tape.map_mk₁ _ _) theorem Machine.map_respects (g₁ : PointedMap Λ Λ') (g₂ : Λ' → Λ) {S} (ss : Supports M S) (f₂₁ : Function.RightInverse f₁ f₂) (g₂₁ : ∀ q ∈ S, g₂ (g₁ q) = q) : Respects (step M) (step (M.map f₁ f₂ g₁ g₂)) fun a b ↦ a.q ∈ S ∧ Cfg.map f₁ g₁ a = b := by intro c _ ⟨cs, rfl⟩ cases e : step M c · rw [← M.map_step f₁ f₂ g₁ g₂ f₂₁ g₂₁ _ cs, e] rfl · refine ⟨_, ⟨step_supports M ss e cs, rfl⟩, TransGen.single ?_⟩ rw [← M.map_step f₁ f₂ g₁ g₂ f₂₁ g₂₁ _ cs, e] rfl end end TM0 /-! ## The TM1 model The TM1 model is a simplification and extension of TM0 (Post-Turing model) in the direction of Wang B-machines. The machine's internal state is extended with a (finite) store `σ` of variables that may be accessed and updated at any time. A machine is given by a `Λ` indexed set of procedures or functions. Each function has a body which is a `Stmt`. Most of the regular commands are allowed to use the current value `a` of the local variables and the value `T.head` on the tape to calculate what to write or how to change local state, but the statements themselves have a fixed structure. The `Stmt`s can be as follows: * `move d q`: move left or right, and then do `q` * `write (f : Γ → σ → Γ) q`: write `f a T.head` to the tape, then do `q` * `load (f : Γ → σ → σ) q`: change the internal state to `f a T.head` * `branch (f : Γ → σ → Bool) qtrue qfalse`: If `f a T.head` is true, do `qtrue`, else `qfalse` * `goto (f : Γ → σ → Λ)`: Go to label `f a T.head` * `halt`: Transition to the halting state, which halts on the following step Note that here most statements do not have labels; `goto` commands can only go to a new function. Only the `goto` and `halt` statements actually take a step; the rest is done by recursion on statements and so take 0 steps. (There is a uniform bound on how many statements can be executed before the next `goto`, so this is an `O(1)` speedup with the constant depending on the machine.) The `halt` command has a one step stutter before actually halting so that any changes made before the halt have a chance to be "committed", since the `eval` relation uses the final configuration before the halt as the output, and `move` and `write` etc. take 0 steps in this model. -/ namespace TM1 section variable (Γ : Type*) [Inhabited Γ] -- Type of tape symbols variable (Λ : Type*) -- Type of function labels variable (σ : Type*) -- Type of variable settings /-- The TM1 model is a simplification and extension of TM0 (Post-Turing model) in the direction of Wang B-machines. The machine's internal state is extended with a (finite) store `σ` of variables that may be accessed and updated at any time. A machine is given by a `Λ` indexed set of procedures or functions. Each function has a body which is a `Stmt`, which can either be a `move` or `write` command, a `branch` (if statement based on the current tape value), a `load` (set the variable value), a `goto` (call another function), or `halt`. Note that here most statements do not have labels; `goto` commands can only go to a new function. All commands have access to the variable value and current tape value. -/ inductive Stmt | move : Dir → Stmt → Stmt | write : (Γ → σ → Γ) → Stmt → Stmt | load : (Γ → σ → σ) → Stmt → Stmt | branch : (Γ → σ → Bool) → Stmt → Stmt → Stmt | goto : (Γ → σ → Λ) → Stmt | halt : Stmt local notation "Stmt₁" => Stmt Γ Λ σ -- Porting note (#10750): added this to clean up types. open Stmt instance Stmt.inhabited : Inhabited Stmt₁ := ⟨halt⟩ /-- The configuration of a TM1 machine is given by the currently evaluating statement, the variable store value, and the tape. -/ structure Cfg where /-- The statement (if any) which is currently evaluated -/ l : Option Λ /-- The current value of the variable store -/ var : σ /-- The current state of the tape -/ Tape : Tape Γ local notation "Cfg₁" => Cfg Γ Λ σ -- Porting note (#10750): added this to clean up types. instance Cfg.inhabited [Inhabited σ] : Inhabited Cfg₁ := ⟨⟨default, default, default⟩⟩ variable {Γ Λ σ} /-- The semantics of TM1 evaluation. -/ def stepAux : Stmt₁ → σ → Tape Γ → Cfg₁ | move d q, v, T => stepAux q v (T.move d) | write a q, v, T => stepAux q v (T.write (a T.1 v)) | load s q, v, T => stepAux q (s T.1 v) T | branch p q₁ q₂, v, T => cond (p T.1 v) (stepAux q₁ v T) (stepAux q₂ v T) | goto l, v, T => ⟨some (l T.1 v), v, T⟩ | halt, v, T => ⟨none, v, T⟩ /-- The state transition function. -/ def step (M : Λ → Stmt₁) : Cfg₁ → Option Cfg₁ | ⟨none, _, _⟩ => none | ⟨some l, v, T⟩ => some (stepAux (M l) v T) /-- A set `S` of labels supports the statement `q` if all the `goto` statements in `q` refer only to other functions in `S`. -/ def SupportsStmt (S : Finset Λ) : Stmt₁ → Prop | move _ q => SupportsStmt S q | write _ q => SupportsStmt S q | load _ q => SupportsStmt S q | branch _ q₁ q₂ => SupportsStmt S q₁ ∧ SupportsStmt S q₂ | goto l => ∀ a v, l a v ∈ S | halt => True open scoped Classical /-- The subterm closure of a statement. -/ noncomputable def stmts₁ : Stmt₁ → Finset Stmt₁ | Q@(move _ q) => insert Q (stmts₁ q) | Q@(write _ q) => insert Q (stmts₁ q) | Q@(load _ q) => insert Q (stmts₁ q) | Q@(branch _ q₁ q₂) => insert Q (stmts₁ q₁ ∪ stmts₁ q₂) | Q => {Q} theorem stmts₁_self {q : Stmt₁} : q ∈ stmts₁ q := by cases q <;> simp only [stmts₁, Finset.mem_insert_self, Finset.mem_singleton_self] theorem stmts₁_trans {q₁ q₂ : Stmt₁} : q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ := by intro h₁₂ q₀ h₀₁ induction q₂ with ( simp only [stmts₁] at h₁₂ ⊢ simp only [Finset.mem_insert, Finset.mem_union, Finset.mem_singleton] at h₁₂) | branch p q₁ q₂ IH₁ IH₂ => rcases h₁₂ with (rfl | h₁₂ | h₁₂) · unfold stmts₁ at h₀₁ exact h₀₁ · exact Finset.mem_insert_of_mem (Finset.mem_union_left _ <| IH₁ h₁₂) · exact Finset.mem_insert_of_mem (Finset.mem_union_right _ <| IH₂ h₁₂) | goto l => subst h₁₂; exact h₀₁ | halt => subst h₁₂; exact h₀₁ | _ _ q IH => rcases h₁₂ with rfl | h₁₂ · exact h₀₁ · exact Finset.mem_insert_of_mem (IH h₁₂) theorem stmts₁_supportsStmt_mono {S : Finset Λ} {q₁ q₂ : Stmt₁} (h : q₁ ∈ stmts₁ q₂) (hs : SupportsStmt S q₂) : SupportsStmt S q₁ := by induction q₂ with simp only [stmts₁, SupportsStmt, Finset.mem_insert, Finset.mem_union, Finset.mem_singleton] at h hs | branch p q₁ q₂ IH₁ IH₂ => rcases h with (rfl | h | h); exacts [hs, IH₁ h hs.1, IH₂ h hs.2] | goto l => subst h; exact hs | halt => subst h; trivial | _ _ q IH => rcases h with (rfl | h) <;> [exact hs; exact IH h hs] /-- The set of all statements in a Turing machine, plus one extra value `none` representing the halt state. This is used in the TM1 to TM0 reduction. -/ noncomputable def stmts (M : Λ → Stmt₁) (S : Finset Λ) : Finset (Option Stmt₁) := Finset.insertNone (S.biUnion fun q ↦ stmts₁ (M q)) theorem stmts_trans {M : Λ → Stmt₁} {S : Finset Λ} {q₁ q₂ : Stmt₁} (h₁ : q₁ ∈ stmts₁ q₂) : some q₂ ∈ stmts M S → some q₁ ∈ stmts M S := by simp only [stmts, Finset.mem_insertNone, Finset.mem_biUnion, Option.mem_def, Option.some.injEq, forall_eq', exists_imp, and_imp] exact fun l ls h₂ ↦ ⟨_, ls, stmts₁_trans h₂ h₁⟩ variable [Inhabited Λ] /-- A set `S` of labels supports machine `M` if all the `goto` statements in the functions in `S` refer only to other functions in `S`. -/ def Supports (M : Λ → Stmt₁) (S : Finset Λ) := default ∈ S ∧ ∀ q ∈ S, SupportsStmt S (M q) theorem stmts_supportsStmt {M : Λ → Stmt₁} {S : Finset Λ} {q : Stmt₁} (ss : Supports M S) : some q ∈ stmts M S → SupportsStmt S q := by simp only [stmts, Finset.mem_insertNone, Finset.mem_biUnion, Option.mem_def, Option.some.injEq, forall_eq', exists_imp, and_imp] exact fun l ls h ↦ stmts₁_supportsStmt_mono h (ss.2 _ ls) theorem step_supports (M : Λ → Stmt₁) {S : Finset Λ} (ss : Supports M S) : ∀ {c c' : Cfg₁}, c' ∈ step M c → c.l ∈ Finset.insertNone S → c'.l ∈ Finset.insertNone S | ⟨some l₁, v, T⟩, c', h₁, h₂ => by replace h₂ := ss.2 _ (Finset.some_mem_insertNone.1 h₂) simp only [step, Option.mem_def, Option.some.injEq] at h₁; subst c' revert h₂; induction M l₁ generalizing v T with intro hs | branch p q₁' q₂' IH₁ IH₂ => unfold stepAux; cases p T.1 v · exact IH₂ _ _ hs.2 · exact IH₁ _ _ hs.1 | goto => exact Finset.some_mem_insertNone.2 (hs _ _) | halt => apply Multiset.mem_cons_self | _ _ q IH => exact IH _ _ hs variable [Inhabited σ] /-- The initial state, given a finite input that is placed on the tape starting at the TM head and going to the right. -/ def init (l : List Γ) : Cfg₁ := ⟨some default, default, Tape.mk₁ l⟩ /-- Evaluate a TM to completion, resulting in an output list on the tape (with an indeterminate number of blanks on the end). -/ def eval (M : Λ → Stmt₁) (l : List Γ) : Part (ListBlank Γ) := (Turing.eval (step M) (init l)).map fun c ↦ c.Tape.right₀ end end TM1 /-! ## TM1 emulator in TM0 To prove that TM1 computable functions are TM0 computable, we need to reduce each TM1 program to a TM0 program. So suppose a TM1 program is given. We take the following: * The alphabet `Γ` is the same for both TM1 and TM0 * The set of states `Λ'` is defined to be `Option Stmt₁ × σ`, that is, a TM1 statement or `none` representing halt, and the possible settings of the internal variables. Note that this is an infinite set, because `Stmt₁` is infinite. This is okay because we assume that from the initial TM1 state, only finitely many other labels are reachable, and there are only finitely many statements that appear in all of these functions. Even though `Stmt₁` contains a statement called `halt`, we must separate it from `none` (`some halt` steps to `none` and `none` actually halts) because there is a one step stutter in the TM1 semantics. -/ namespace TM1to0 section variable {Γ : Type*} [Inhabited Γ] variable {Λ : Type*} [Inhabited Λ] variable {σ : Type*} [Inhabited σ] local notation "Stmt₁" => TM1.Stmt Γ Λ σ local notation "Cfg₁" => TM1.Cfg Γ Λ σ local notation "Stmt₀" => TM0.Stmt Γ variable (M : Λ → TM1.Stmt Γ Λ σ) -- Porting note: Unfolded `Stmt₁`. -- Porting note: `Inhabited`s are not necessary, but `M` is necessary. set_option linter.unusedVariables false in /-- The base machine state space is a pair of an `Option Stmt₁` representing the current program to be executed, or `none` for the halt state, and a `σ` which is the local state (stored in the TM, not the tape). Because there are an infinite number of programs, this state space is infinite, but for a finitely supported TM1 machine and a finite type `σ`, only finitely many of these states are reachable. -/ @[nolint unusedArguments] -- We need the M assumption def Λ' (M : Λ → TM1.Stmt Γ Λ σ) := Option Stmt₁ × σ local notation "Λ'₁₀" => Λ' M -- Porting note (#10750): added this to clean up types. instance : Inhabited Λ'₁₀ := ⟨(some (M default), default)⟩ open TM0.Stmt /-- The core TM1 → TM0 translation function. Here `s` is the current value on the tape, and the `Stmt₁` is the TM1 statement to translate, with local state `v : σ`. We evaluate all regular instructions recursively until we reach either a `move` or `write` command, or a `goto`; in the latter case we emit a dummy `write s` step and transition to the new target location. -/ def trAux (s : Γ) : Stmt₁ → σ → Λ'₁₀ × Stmt₀ | TM1.Stmt.move d q, v => ((some q, v), move d) | TM1.Stmt.write a q, v => ((some q, v), write (a s v)) | TM1.Stmt.load a q, v => trAux s q (a s v) | TM1.Stmt.branch p q₁ q₂, v => cond (p s v) (trAux s q₁ v) (trAux s q₂ v) | TM1.Stmt.goto l, v => ((some (M (l s v)), v), write s) | TM1.Stmt.halt, v => ((none, v), write s) local notation "Cfg₁₀" => TM0.Cfg Γ Λ'₁₀ /-- The translated TM0 machine (given the TM1 machine input). -/ def tr : TM0.Machine Γ Λ'₁₀ | (none, _), _ => none | (some q, v), s => some (trAux M s q v) /-- Translate configurations from TM1 to TM0. -/ def trCfg : Cfg₁ → Cfg₁₀ | ⟨l, v, T⟩ => ⟨(l.map M, v), T⟩ theorem tr_respects : Respects (TM1.step M) (TM0.step (tr M)) fun (c₁ : Cfg₁) (c₂ : Cfg₁₀) ↦ trCfg M c₁ = c₂ := fun_respects.2 fun ⟨l₁, v, T⟩ ↦ by cases' l₁ with l₁; · exact rfl simp only [trCfg, TM1.step, FRespects, Option.map] induction M l₁ generalizing v T with | move _ _ IH => exact TransGen.head rfl (IH _ _) | write _ _ IH => exact TransGen.head rfl (IH _ _) | load _ _ IH => exact (reaches₁_eq (by rfl)).2 (IH _ _) | branch p _ _ IH₁ IH₂ => unfold TM1.stepAux; cases e : p T.1 v · exact (reaches₁_eq (by simp only [TM0.step, tr, trAux, e]; rfl)).2 (IH₂ _ _) · exact (reaches₁_eq (by simp only [TM0.step, tr, trAux, e]; rfl)).2 (IH₁ _ _) | _ => exact TransGen.single (congr_arg some (congr (congr_arg TM0.Cfg.mk rfl) (Tape.write_self T))) theorem tr_eval (l : List Γ) : TM0.eval (tr M) l = TM1.eval M l := (congr_arg _ (tr_eval' _ _ _ (tr_respects M) ⟨some _, _, _⟩)).trans (by rw [Part.map_eq_map, Part.map_map, TM1.eval] congr with ⟨⟩) variable [Fintype σ] /-- Given a finite set of accessible `Λ` machine states, there is a finite set of accessible machine states in the target (even though the type `Λ'` is infinite). -/ noncomputable def trStmts (S : Finset Λ) : Finset Λ'₁₀ := (TM1.stmts M S) ×ˢ Finset.univ open scoped Classical attribute [local simp] TM1.stmts₁_self theorem tr_supports {S : Finset Λ} (ss : TM1.Supports M S) : TM0.Supports (tr M) ↑(trStmts M S) := by constructor · apply Finset.mem_product.2 constructor · simp only [default, TM1.stmts, Finset.mem_insertNone, Option.mem_def, Option.some_inj, forall_eq', Finset.mem_biUnion] exact ⟨_, ss.1, TM1.stmts₁_self⟩ · apply Finset.mem_univ · intro q a q' s h₁ h₂ rcases q with ⟨_ | q, v⟩; · cases h₁ cases' q' with q' v' simp only [trStmts, Finset.mem_coe] at h₂ ⊢ rw [Finset.mem_product] at h₂ ⊢ simp only [Finset.mem_univ, and_true_iff] at h₂ ⊢ cases q'; · exact Multiset.mem_cons_self _ _ simp only [tr, Option.mem_def] at h₁ have := TM1.stmts_supportsStmt ss h₂ revert this; induction q generalizing v with intro hs | move d q => cases h₁; refine TM1.stmts_trans ?_ h₂ unfold TM1.stmts₁ exact Finset.mem_insert_of_mem TM1.stmts₁_self | write b q => cases h₁; refine TM1.stmts_trans ?_ h₂ unfold TM1.stmts₁ exact Finset.mem_insert_of_mem TM1.stmts₁_self | load b q IH => refine IH _ (TM1.stmts_trans ?_ h₂) h₁ hs unfold TM1.stmts₁ exact Finset.mem_insert_of_mem TM1.stmts₁_self | branch p q₁ q₂ IH₁ IH₂ => cases h : p a v <;> rw [trAux, h] at h₁ · refine IH₂ _ (TM1.stmts_trans ?_ h₂) h₁ hs.2 unfold TM1.stmts₁ exact Finset.mem_insert_of_mem (Finset.mem_union_right _ TM1.stmts₁_self) · refine IH₁ _ (TM1.stmts_trans ?_ h₂) h₁ hs.1 unfold TM1.stmts₁ exact Finset.mem_insert_of_mem (Finset.mem_union_left _ TM1.stmts₁_self) | goto l => cases h₁ exact Finset.some_mem_insertNone.2 (Finset.mem_biUnion.2 ⟨_, hs _ _, TM1.stmts₁_self⟩) | halt => cases h₁ end end TM1to0 /-! ## TM1(Γ) emulator in TM1(Bool) The most parsimonious Turing machine model that is still Turing complete is `TM0` with `Γ = Bool`. Because our construction in the previous section reducing `TM1` to `TM0` doesn't change the alphabet, we can do the alphabet reduction on `TM1` instead of `TM0` directly. The basic idea is to use a bijection between `Γ` and a subset of `Vector Bool n`, where `n` is a fixed constant. Each tape element is represented as a block of `n` bools. Whenever the machine wants to read a symbol from the tape, it traverses over the block, performing `n` `branch` instructions to each any of the `2^n` results. For the `write` instruction, we have to use a `goto` because we need to follow a different code path depending on the local state, which is not available in the TM1 model, so instead we jump to a label computed using the read value and the local state, which performs the writing and returns to normal execution. Emulation overhead is `O(1)`. If not for the above `write` behavior it would be 1-1 because we are exploiting the 0-step behavior of regular commands to avoid taking steps, but there are nevertheless a bounded number of `write` calls between `goto` statements because TM1 statements are finitely long. -/ namespace TM1to1 open TM1 section variable {Γ : Type*} [Inhabited Γ] theorem exists_enc_dec [Finite Γ] : ∃ (n : ℕ) (enc : Γ → Vector Bool n) (dec : Vector Bool n → Γ), enc default = Vector.replicate n false ∧ ∀ a, dec (enc a) = a := by rcases Finite.exists_equiv_fin Γ with ⟨n, ⟨e⟩⟩ letI : DecidableEq Γ := e.decidableEq let G : Fin n ↪ Fin n → Bool := ⟨fun a b ↦ a = b, fun a b h ↦ Bool.of_decide_true <| (congr_fun h b).trans <| Bool.decide_true rfl⟩ let H := (e.toEmbedding.trans G).trans (Equiv.vectorEquivFin _ _).symm.toEmbedding let enc := H.setValue default (Vector.replicate n false) exact ⟨_, enc, Function.invFun enc, H.setValue_eq _ _, Function.leftInverse_invFun enc.2⟩ variable {Λ : Type*} [Inhabited Λ] variable {σ : Type*} [Inhabited σ] local notation "Stmt₁" => Stmt Γ Λ σ local notation "Cfg₁" => Cfg Γ Λ σ /-- The configuration state of the TM. -/ inductive Λ' | normal : Λ → Λ' | write : Γ → Stmt₁ → Λ' local notation "Λ'₁" => @Λ' Γ Λ σ -- Porting note (#10750): added this to clean up types. instance : Inhabited Λ'₁ := ⟨Λ'.normal default⟩ local notation "Stmt'₁" => Stmt Bool Λ'₁ σ local notation "Cfg'₁" => Cfg Bool Λ'₁ σ /-- Read a vector of length `n` from the tape. -/ def readAux : ∀ n, (Vector Bool n → Stmt'₁) → Stmt'₁ | 0, f => f Vector.nil | i + 1, f => Stmt.branch (fun a _ ↦ a) (Stmt.move Dir.right <| readAux i fun v ↦ f (true ::ᵥ v)) (Stmt.move Dir.right <| readAux i fun v ↦ f (false ::ᵥ v)) variable {n : ℕ} (enc : Γ → Vector Bool n) (dec : Vector Bool n → Γ) /-- A move left or right corresponds to `n` moves across the super-cell. -/ def move (d : Dir) (q : Stmt'₁) : Stmt'₁ := (Stmt.move d)^[n] q local notation "moveₙ" => @move Γ Λ σ n -- Porting note (#10750): added this to clean up types. /-- To read a symbol from the tape, we use `readAux` to traverse the symbol, then return to the original position with `n` moves to the left. -/ def read (f : Γ → Stmt'₁) : Stmt'₁ := readAux n fun v ↦ moveₙ Dir.left <| f (dec v) /-- Write a list of bools on the tape. -/ def write : List Bool → Stmt'₁ → Stmt'₁ | [], q => q | a :: l, q => (Stmt.write fun _ _ ↦ a) <| Stmt.move Dir.right <| write l q /-- Translate a normal instruction. For the `write` command, we use a `goto` indirection so that we can access the current value of the tape. -/ def trNormal : Stmt₁ → Stmt'₁ | Stmt.move d q => moveₙ d <| trNormal q | Stmt.write f q => read dec fun a ↦ Stmt.goto fun _ s ↦ Λ'.write (f a s) q | Stmt.load f q => read dec fun a ↦ (Stmt.load fun _ s ↦ f a s) <| trNormal q | Stmt.branch p q₁ q₂ => read dec fun a ↦ Stmt.branch (fun _ s ↦ p a s) (trNormal q₁) (trNormal q₂) | Stmt.goto l => read dec fun a ↦ Stmt.goto fun _ s ↦ Λ'.normal (l a s) | Stmt.halt => Stmt.halt theorem stepAux_move (d : Dir) (q : Stmt'₁) (v : σ) (T : Tape Bool) : stepAux (moveₙ d q) v T = stepAux q v ((Tape.move d)^[n] T) := by suffices ∀ i, stepAux ((Stmt.move d)^[i] q) v T = stepAux q v ((Tape.move d)^[i] T) from this n intro i; induction' i with i IH generalizing T; · rfl rw [iterate_succ', iterate_succ] simp only [stepAux, Function.comp_apply] rw [IH] theorem supportsStmt_move {S : Finset Λ'₁} {d : Dir} {q : Stmt'₁} : SupportsStmt S (moveₙ d q) = SupportsStmt S q := by suffices ∀ {i}, SupportsStmt S ((Stmt.move d)^[i] q) = _ from this intro i; induction i generalizing q <;> simp only [*, iterate]; rfl theorem supportsStmt_write {S : Finset Λ'₁} {l : List Bool} {q : Stmt'₁} : SupportsStmt S (write l q) = SupportsStmt S q := by induction' l with _ l IH <;> simp only [write, SupportsStmt, *] theorem supportsStmt_read {S : Finset Λ'₁} : ∀ {f : Γ → Stmt'₁}, (∀ a, SupportsStmt S (f a)) → SupportsStmt S (read dec f) := suffices ∀ (i) (f : Vector Bool i → Stmt'₁), (∀ v, SupportsStmt S (f v)) → SupportsStmt S (readAux i f) from fun hf ↦ this n _ (by intro; simp only [supportsStmt_move, hf]) fun i f hf ↦ by induction' i with i IH; · exact hf _ constructor <;> apply IH <;> intro <;> apply hf variable (enc0 : enc default = Vector.replicate n false) section variable {enc} /-- The low level tape corresponding to the given tape over alphabet `Γ`. -/ def trTape' (L R : ListBlank Γ) : Tape Bool := by refine Tape.mk' (L.bind (fun x ↦ (enc x).toList.reverse) ⟨n, ?_⟩) (R.bind (fun x ↦ (enc x).toList) ⟨n, ?_⟩) <;> simp only [enc0, Vector.replicate, List.reverse_replicate, Bool.default_bool, Vector.toList_mk] /-- The low level tape corresponding to the given tape over alphabet `Γ`. -/ def trTape (T : Tape Γ) : Tape Bool := trTape' enc0 T.left T.right₀ theorem trTape_mk' (L R : ListBlank Γ) : trTape enc0 (Tape.mk' L R) = trTape' enc0 L R := by simp only [trTape, Tape.mk'_left, Tape.mk'_right₀] end variable (M : Λ → TM1.Stmt Γ Λ σ) -- Porting note: Unfolded `Stmt₁`. /-- The top level program. -/ def tr : Λ'₁ → Stmt'₁ | Λ'.normal l => trNormal dec (M l) | Λ'.write a q => write (enc a).toList <| moveₙ Dir.left <| trNormal dec q /-- The machine configuration translation. -/ def trCfg : Cfg₁ → Cfg'₁ | ⟨l, v, T⟩ => ⟨l.map Λ'.normal, v, trTape enc0 T⟩ variable {enc} theorem trTape'_move_left (L R : ListBlank Γ) : (Tape.move Dir.left)^[n] (trTape' enc0 L R) = trTape' enc0 L.tail (R.cons L.head) := by obtain ⟨a, L, rfl⟩ := L.exists_cons simp only [trTape', ListBlank.cons_bind, ListBlank.head_cons, ListBlank.tail_cons] suffices ∀ {L' R' l₁ l₂} (_ : Vector.toList (enc a) = List.reverseAux l₁ l₂), (Tape.move Dir.left)^[l₁.length] (Tape.mk' (ListBlank.append l₁ L') (ListBlank.append l₂ R')) = Tape.mk' L' (ListBlank.append (Vector.toList (enc a)) R') by simpa only [List.length_reverse, Vector.toList_length] using this (List.reverse_reverse _).symm intro _ _ l₁ l₂ e induction' l₁ with b l₁ IH generalizing l₂ · cases e rfl simp only [List.length, List.cons_append, iterate_succ_apply] convert IH e simp only [ListBlank.tail_cons, ListBlank.append, Tape.move_left_mk', ListBlank.head_cons] theorem trTape'_move_right (L R : ListBlank Γ) : (Tape.move Dir.right)^[n] (trTape' enc0 L R) = trTape' enc0 (L.cons R.head) R.tail := by suffices ∀ i L, (Tape.move Dir.right)^[i] ((Tape.move Dir.left)^[i] L) = L by refine (Eq.symm ?_).trans (this n _) simp only [trTape'_move_left, ListBlank.cons_head_tail, ListBlank.head_cons, ListBlank.tail_cons] intro i _ induction' i with i IH · rfl rw [iterate_succ_apply, iterate_succ_apply', Tape.move_left_right, IH] theorem stepAux_write (q : Stmt'₁) (v : σ) (a b : Γ) (L R : ListBlank Γ) : stepAux (write (enc a).toList q) v (trTape' enc0 L (ListBlank.cons b R)) = stepAux q v (trTape' enc0 (ListBlank.cons a L) R) := by simp only [trTape', ListBlank.cons_bind] suffices ∀ {L' R'} (l₁ l₂ l₂' : List Bool) (_ : l₂'.length = l₂.length), stepAux (write l₂ q) v (Tape.mk' (ListBlank.append l₁ L') (ListBlank.append l₂' R')) = stepAux q v (Tape.mk' (L'.append (List.reverseAux l₂ l₁)) R') by exact this [] _ _ ((enc b).2.trans (enc a).2.symm) clear a b L R intro L' R' l₁ l₂ l₂' e induction' l₂ with a l₂ IH generalizing l₁ l₂' · cases List.length_eq_zero.1 e rfl cases' l₂' with b l₂' <;> simp only [List.length_nil, List.length_cons, Nat.succ_inj'] at e rw [List.reverseAux, ← IH (a :: l₁) l₂' e] simp only [stepAux, ListBlank.append, Tape.write_mk', Tape.move_right_mk', ListBlank.head_cons, ListBlank.tail_cons] variable (encdec : ∀ a, dec (enc a) = a) theorem stepAux_read (f : Γ → Stmt'₁) (v : σ) (L R : ListBlank Γ) : stepAux (read dec f) v (trTape' enc0 L R) = stepAux (f R.head) v (trTape' enc0 L R) := by suffices ∀ f, stepAux (readAux n f) v (trTape' enc0 L R) = stepAux (f (enc R.head)) v (trTape' enc0 (L.cons R.head) R.tail) by rw [read, this, stepAux_move, encdec, trTape'_move_left enc0] simp only [ListBlank.head_cons, ListBlank.cons_head_tail, ListBlank.tail_cons] obtain ⟨a, R, rfl⟩ := R.exists_cons simp only [ListBlank.head_cons, ListBlank.tail_cons, trTape', ListBlank.cons_bind, ListBlank.append_assoc] suffices ∀ i f L' R' l₁ l₂ h, stepAux (readAux i f) v (Tape.mk' (ListBlank.append l₁ L') (ListBlank.append l₂ R')) = stepAux (f ⟨l₂, h⟩) v (Tape.mk' (ListBlank.append (l₂.reverseAux l₁) L') R') by intro f -- Porting note: Here was `change`. exact this n f (L.bind (fun x => (enc x).1.reverse) _) (R.bind (fun x => (enc x).1) _) [] _ (enc a).2 clear f L a R intro i f L' R' l₁ l₂ _ subst i induction' l₂ with a l₂ IH generalizing l₁ · rfl trans stepAux (readAux l₂.length fun v ↦ f (a ::ᵥ v)) v (Tape.mk' ((L'.append l₁).cons a) (R'.append l₂)) · dsimp [readAux, stepAux] simp only [ListBlank.head_cons, Tape.move_right_mk', ListBlank.tail_cons] cases a <;> rfl rw [← ListBlank.append, IH] rfl theorem tr_respects {enc₀} : Respects (step M) (step (tr enc dec M)) fun c₁ c₂ ↦ trCfg enc enc₀ c₁ = c₂ := fun_respects.2 fun ⟨l₁, v, T⟩ ↦ by obtain ⟨L, R, rfl⟩ := T.exists_mk' cases' l₁ with l₁ · exact rfl suffices ∀ q R, Reaches (step (tr enc dec M)) (stepAux (trNormal dec q) v (trTape' enc0 L R)) (trCfg enc enc0 (stepAux q v (Tape.mk' L R))) by refine TransGen.head' rfl ?_ rw [trTape_mk'] exact this _ R clear R l₁ intro q R induction q generalizing v L R with | move d q IH => cases d <;> simp only [trNormal, iterate, stepAux_move, stepAux, ListBlank.head_cons, Tape.move_left_mk', ListBlank.cons_head_tail, ListBlank.tail_cons, trTape'_move_left enc0, trTape'_move_right enc0] <;> apply IH | write f q IH => simp only [trNormal, stepAux_read dec enc0 encdec, stepAux] refine ReflTransGen.head rfl ?_ obtain ⟨a, R, rfl⟩ := R.exists_cons rw [tr, Tape.mk'_head, stepAux_write, ListBlank.head_cons, stepAux_move, trTape'_move_left enc0, ListBlank.head_cons, ListBlank.tail_cons, Tape.write_mk'] apply IH | load a q IH => simp only [trNormal, stepAux_read dec enc0 encdec] apply IH | branch p q₁ q₂ IH₁ IH₂ => simp only [trNormal, stepAux_read dec enc0 encdec, stepAux, Tape.mk'_head] cases p R.head v <;> [apply IH₂; apply IH₁] | goto l => simp only [trNormal, stepAux_read dec enc0 encdec, stepAux, trCfg, trTape_mk'] apply ReflTransGen.refl | halt => simp only [trNormal, stepAux, trCfg, stepAux_move, trTape'_move_left enc0, trTape'_move_right enc0, trTape_mk'] apply ReflTransGen.refl open scoped Classical variable [Fintype Γ] /-- The set of accessible `Λ'.write` machine states. -/ noncomputable def writes : Stmt₁ → Finset Λ'₁ | Stmt.move _ q => writes q | Stmt.write _ q => (Finset.univ.image fun a ↦ Λ'.write a q) ∪ writes q | Stmt.load _ q => writes q | Stmt.branch _ q₁ q₂ => writes q₁ ∪ writes q₂ | Stmt.goto _ => ∅ | Stmt.halt => ∅ /-- The set of accessible machine states, assuming that the input machine is supported on `S`, are the normal states embedded from `S`, plus all write states accessible from these states. -/ noncomputable def trSupp (S : Finset Λ) : Finset Λ'₁ := S.biUnion fun l ↦ insert (Λ'.normal l) (writes (M l)) theorem tr_supports {S : Finset Λ} (ss : Supports M S) : Supports (tr enc dec M) (trSupp M S) := ⟨Finset.mem_biUnion.2 ⟨_, ss.1, Finset.mem_insert_self _ _⟩, fun q h ↦ by suffices ∀ q, SupportsStmt S q → (∀ q' ∈ writes q, q' ∈ trSupp M S) → SupportsStmt (trSupp M S) (trNormal dec q) ∧ ∀ q' ∈ writes q, SupportsStmt (trSupp M S) (tr enc dec M q') by rcases Finset.mem_biUnion.1 h with ⟨l, hl, h⟩ have := this _ (ss.2 _ hl) fun q' hq ↦ Finset.mem_biUnion.2 ⟨_, hl, Finset.mem_insert_of_mem hq⟩ rcases Finset.mem_insert.1 h with (rfl | h) exacts [this.1, this.2 _ h] intro q hs hw induction q with | move d q IH => unfold writes at hw ⊢ replace IH := IH hs hw; refine ⟨?_, IH.2⟩ cases d <;> simp only [trNormal, iterate, supportsStmt_move, IH] | write f q IH => unfold writes at hw ⊢ simp only [Finset.mem_image, Finset.mem_union, Finset.mem_univ, exists_prop, true_and_iff] at hw ⊢ replace IH := IH hs fun q hq ↦ hw q (Or.inr hq) refine ⟨supportsStmt_read _ fun a _ s ↦ hw _ (Or.inl ⟨_, rfl⟩), fun q' hq ↦ ?_⟩ rcases hq with (⟨a, q₂, rfl⟩ | hq) · simp only [tr, supportsStmt_write, supportsStmt_move, IH.1] · exact IH.2 _ hq | load a q IH => unfold writes at hw ⊢ replace IH := IH hs hw exact ⟨supportsStmt_read _ fun _ ↦ IH.1, IH.2⟩ | branch p q₁ q₂ IH₁ IH₂ => unfold writes at hw ⊢ simp only [Finset.mem_union] at hw ⊢ replace IH₁ := IH₁ hs.1 fun q hq ↦ hw q (Or.inl hq) replace IH₂ := IH₂ hs.2 fun q hq ↦ hw q (Or.inr hq) exact ⟨supportsStmt_read _ fun _ ↦ ⟨IH₁.1, IH₂.1⟩, fun q ↦ Or.rec (IH₁.2 _) (IH₂.2 _)⟩ | goto l => simp only [writes, Finset.not_mem_empty]; refine ⟨?_, fun _ ↦ False.elim⟩ refine supportsStmt_read _ fun a _ s ↦ ?_ exact Finset.mem_biUnion.2 ⟨_, hs _ _, Finset.mem_insert_self _ _⟩ | halt => simp only [writes, Finset.not_mem_empty]; refine ⟨?_, fun _ ↦ False.elim⟩ simp only [SupportsStmt, supportsStmt_move, trNormal]⟩ end end TM1to1 /-! ## TM0 emulator in TM1 To establish that TM0 and TM1 are equivalent computational models, we must also have a TM0 emulator in TM1. The main complication here is that TM0 allows an action to depend on the value at the head and local state, while TM1 doesn't (in order to have more programming language-like semantics). So we use a computed `goto` to go to a state that performs the desired action and then returns to normal execution. One issue with this is that the `halt` instruction is supposed to halt immediately, not take a step to a halting state. To resolve this we do a check for `halt` first, then `goto` (with an unreachable branch). -/ namespace TM0to1 section variable {Γ : Type*} [Inhabited Γ] variable {Λ : Type*} [Inhabited Λ] /-- The machine states for a TM1 emulating a TM0 machine. States of the TM0 machine are embedded as `normal q` states, but the actual operation is split into two parts, a jump to `act s q` followed by the action and a jump to the next `normal` state. -/ inductive Λ' | normal : Λ → Λ' | act : TM0.Stmt Γ → Λ → Λ' local notation "Λ'₁" => @Λ' Γ Λ -- Porting note (#10750): added this to clean up types. instance : Inhabited Λ'₁ := ⟨Λ'.normal default⟩ local notation "Cfg₀" => TM0.Cfg Γ Λ local notation "Stmt₁" => TM1.Stmt Γ Λ'₁ Unit local notation "Cfg₁" => TM1.Cfg Γ Λ'₁ Unit variable (M : TM0.Machine Γ Λ) open TM1.Stmt /-- The program. -/ def tr : Λ'₁ → Stmt₁ | Λ'.normal q => branch (fun a _ ↦ (M q a).isNone) halt <| goto fun a _ ↦ match M q a with | none => default -- unreachable | some (q', s) => Λ'.act s q' | Λ'.act (TM0.Stmt.move d) q => move d <| goto fun _ _ ↦ Λ'.normal q | Λ'.act (TM0.Stmt.write a) q => (write fun _ _ ↦ a) <| goto fun _ _ ↦ Λ'.normal q /-- The configuration translation. -/ def trCfg : Cfg₀ → Cfg₁ | ⟨q, T⟩ => ⟨cond (M q T.1).isSome (some (Λ'.normal q)) none, (), T⟩ theorem tr_respects : Respects (TM0.step M) (TM1.step (tr M)) fun a b ↦ trCfg M a = b := fun_respects.2 fun ⟨q, T⟩ ↦ by cases' e : M q T.1 with val · simp only [TM0.step, trCfg, e]; exact Eq.refl none cases' val with q' s simp only [FRespects, TM0.step, trCfg, e, Option.isSome, cond, Option.map_some'] revert e -- Porting note: Added this so that `e` doesn't get into the `match`. have : TM1.step (tr M) ⟨some (Λ'.act s q'), (), T⟩ = some ⟨some (Λ'.normal q'), (), match s with | TM0.Stmt.move d => T.move d | TM0.Stmt.write a => T.write a⟩ := by cases' s with d a <;> rfl intro e refine TransGen.head ?_ (TransGen.head' this ?_) · simp only [TM1.step, TM1.stepAux] rw [e] rfl cases e' : M q' _ · apply ReflTransGen.single simp only [TM1.step, TM1.stepAux] rw [e'] rfl · rfl end end TM0to1 /-! ## The TM2 model The TM2 model removes the tape entirely from the TM1 model, replacing it with an arbitrary (finite) collection of stacks, each with elements of different types (the alphabet of stack `k : K` is `Γ k`). The statements are: * `push k (f : σ → Γ k) q` puts `f a` on the `k`-th stack, then does `q`. * `pop k (f : σ → Option (Γ k) → σ) q` changes the state to `f a (S k).head`, where `S k` is the value of the `k`-th stack, and removes this element from the stack, then does `q`. * `peek k (f : σ → Option (Γ k) → σ) q` changes the state to `f a (S k).head`, where `S k` is the value of the `k`-th stack, then does `q`. * `load (f : σ → σ) q` reads nothing but applies `f` to the internal state, then does `q`. * `branch (f : σ → Bool) qtrue qfalse` does `qtrue` or `qfalse` according to `f a`. * `goto (f : σ → Λ)` jumps to label `f a`. * `halt` halts on the next step. The configuration is a tuple `(l, var, stk)` where `l : Option Λ` is the current label to run or `none` for the halting state, `var : σ` is the (finite) internal state, and `stk : ∀ k, List (Γ k)` is the collection of stacks. (Note that unlike the `TM0` and `TM1` models, these are not `ListBlank`s, they have definite ends that can be detected by the `pop` command.) Given a designated stack `k` and a value `L : List (Γ k)`, the initial configuration has all the stacks empty except the designated "input" stack; in `eval` this designated stack also functions as the output stack. -/ namespace TM2 section variable {K : Type*} [DecidableEq K] -- Index type of stacks variable (Γ : K → Type*) -- Type of stack elements variable (Λ : Type*) -- Type of function labels variable (σ : Type*) -- Type of variable settings /-- The TM2 model removes the tape entirely from the TM1 model, replacing it with an arbitrary (finite) collection of stacks. The operation `push` puts an element on one of the stacks, and `pop` removes an element from a stack (and modifying the internal state based on the result). `peek` modifies the internal state but does not remove an element. -/ inductive Stmt | push : ∀ k, (σ → Γ k) → Stmt → Stmt | peek : ∀ k, (σ → Option (Γ k) → σ) → Stmt → Stmt | pop : ∀ k, (σ → Option (Γ k) → σ) → Stmt → Stmt | load : (σ → σ) → Stmt → Stmt | branch : (σ → Bool) → Stmt → Stmt → Stmt | goto : (σ → Λ) → Stmt | halt : Stmt local notation "Stmt₂" => Stmt Γ Λ σ -- Porting note (#10750): added this to clean up types. open Stmt instance Stmt.inhabited : Inhabited Stmt₂ := ⟨halt⟩ /-- A configuration in the TM2 model is a label (or `none` for the halt state), the state of local variables, and the stacks. (Note that the stacks are not `ListBlank`s, they have a definite size.) -/ structure Cfg where /-- The current label to run (or `none` for the halting state) -/ l : Option Λ /-- The internal state -/ var : σ /-- The (finite) collection of internal stacks -/ stk : ∀ k, List (Γ k) local notation "Cfg₂" => Cfg Γ Λ σ -- Porting note (#10750): added this to clean up types. instance Cfg.inhabited [Inhabited σ] : Inhabited Cfg₂ := ⟨⟨default, default, default⟩⟩ variable {Γ Λ σ} /-- The step function for the TM2 model. -/ @[simp] def stepAux : Stmt₂ → σ → (∀ k, List (Γ k)) → Cfg₂ | push k f q, v, S => stepAux q v (update S k (f v :: S k)) | peek k f q, v, S => stepAux q (f v (S k).head?) S | pop k f q, v, S => stepAux q (f v (S k).head?) (update S k (S k).tail) | load a q, v, S => stepAux q (a v) S | branch f q₁ q₂, v, S => cond (f v) (stepAux q₁ v S) (stepAux q₂ v S) | goto f, v, S => ⟨some (f v), v, S⟩ | halt, v, S => ⟨none, v, S⟩ /-- The step function for the TM2 model. -/ @[simp] def step (M : Λ → Stmt₂) : Cfg₂ → Option Cfg₂ | ⟨none, _, _⟩ => none | ⟨some l, v, S⟩ => some (stepAux (M l) v S) /-- The (reflexive) reachability relation for the TM2 model. -/ def Reaches (M : Λ → Stmt₂) : Cfg₂ → Cfg₂ → Prop := ReflTransGen fun a b ↦ b ∈ step M a /-- Given a set `S` of states, `SupportsStmt S q` means that `q` only jumps to states in `S`. -/ def SupportsStmt (S : Finset Λ) : Stmt₂ → Prop | push _ _ q => SupportsStmt S q | peek _ _ q => SupportsStmt S q | pop _ _ q => SupportsStmt S q | load _ q => SupportsStmt S q | branch _ q₁ q₂ => SupportsStmt S q₁ ∧ SupportsStmt S q₂ | goto l => ∀ v, l v ∈ S | halt => True open scoped Classical /-- The set of subtree statements in a statement. -/ noncomputable def stmts₁ : Stmt₂ → Finset Stmt₂ | Q@(push _ _ q) => insert Q (stmts₁ q) | Q@(peek _ _ q) => insert Q (stmts₁ q) | Q@(pop _ _ q) => insert Q (stmts₁ q) | Q@(load _ q) => insert Q (stmts₁ q) | Q@(branch _ q₁ q₂) => insert Q (stmts₁ q₁ ∪ stmts₁ q₂) | Q@(goto _) => {Q} | Q@halt => {Q} theorem stmts₁_self {q : Stmt₂} : q ∈ stmts₁ q := by cases q <;> simp only [Finset.mem_insert_self, Finset.mem_singleton_self, stmts₁] theorem stmts₁_trans {q₁ q₂ : Stmt₂} : q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ := by intro h₁₂ q₀ h₀₁ induction q₂ with ( simp only [stmts₁] at h₁₂ ⊢ simp only [Finset.mem_insert, Finset.mem_singleton, Finset.mem_union] at h₁₂) | branch f q₁ q₂ IH₁ IH₂ => rcases h₁₂ with (rfl | h₁₂ | h₁₂) · unfold stmts₁ at h₀₁ exact h₀₁ · exact Finset.mem_insert_of_mem (Finset.mem_union_left _ (IH₁ h₁₂)) · exact Finset.mem_insert_of_mem (Finset.mem_union_right _ (IH₂ h₁₂)) | goto l => subst h₁₂; exact h₀₁ | halt => subst h₁₂; exact h₀₁ | load _ q IH | _ _ _ q IH => rcases h₁₂ with (rfl | h₁₂) · unfold stmts₁ at h₀₁ exact h₀₁ · exact Finset.mem_insert_of_mem (IH h₁₂) theorem stmts₁_supportsStmt_mono {S : Finset Λ} {q₁ q₂ : Stmt₂} (h : q₁ ∈ stmts₁ q₂) (hs : SupportsStmt S q₂) : SupportsStmt S q₁ := by induction q₂ with simp only [stmts₁, SupportsStmt, Finset.mem_insert, Finset.mem_union, Finset.mem_singleton] at h hs | branch f q₁ q₂ IH₁ IH₂ => rcases h with (rfl | h | h); exacts [hs, IH₁ h hs.1, IH₂ h hs.2] | goto l => subst h; exact hs | halt => subst h; trivial | load _ _ IH | _ _ _ _ IH => rcases h with (rfl | h) <;> [exact hs; exact IH h hs] /-- The set of statements accessible from initial set `S` of labels. -/ noncomputable def stmts (M : Λ → Stmt₂) (S : Finset Λ) : Finset (Option Stmt₂) := Finset.insertNone (S.biUnion fun q ↦ stmts₁ (M q)) theorem stmts_trans {M : Λ → Stmt₂} {S : Finset Λ} {q₁ q₂ : Stmt₂} (h₁ : q₁ ∈ stmts₁ q₂) : some q₂ ∈ stmts M S → some q₁ ∈ stmts M S := by simp only [stmts, Finset.mem_insertNone, Finset.mem_biUnion, Option.mem_def, Option.some.injEq, forall_eq', exists_imp, and_imp] exact fun l ls h₂ ↦ ⟨_, ls, stmts₁_trans h₂ h₁⟩ variable [Inhabited Λ] /-- Given a TM2 machine `M` and a set `S` of states, `Supports M S` means that all states in `S` jump only to other states in `S`. -/ def Supports (M : Λ → Stmt₂) (S : Finset Λ) := default ∈ S ∧ ∀ q ∈ S, SupportsStmt S (M q) theorem stmts_supportsStmt {M : Λ → Stmt₂} {S : Finset Λ} {q : Stmt₂} (ss : Supports M S) : some q ∈ stmts M S → SupportsStmt S q := by simp only [stmts, Finset.mem_insertNone, Finset.mem_biUnion, Option.mem_def, Option.some.injEq, forall_eq', exists_imp, and_imp] exact fun l ls h ↦ stmts₁_supportsStmt_mono h (ss.2 _ ls) theorem step_supports (M : Λ → Stmt₂) {S : Finset Λ} (ss : Supports M S) : ∀ {c c' : Cfg₂}, c' ∈ step M c → c.l ∈ Finset.insertNone S → c'.l ∈ Finset.insertNone S | ⟨some l₁, v, T⟩, c', h₁, h₂ => by replace h₂ := ss.2 _ (Finset.some_mem_insertNone.1 h₂) simp only [step, Option.mem_def, Option.some.injEq] at h₁; subst c' revert h₂; induction M l₁ generalizing v T with intro hs | branch p q₁' q₂' IH₁ IH₂ => unfold stepAux; cases p v · exact IH₂ _ _ hs.2 · exact IH₁ _ _ hs.1 | goto => exact Finset.some_mem_insertNone.2 (hs _) | halt => apply Multiset.mem_cons_self | load _ _ IH | _ _ _ _ IH => exact IH _ _ hs variable [Inhabited σ] /-- The initial state of the TM2 model. The input is provided on a designated stack. -/ def init (k : K) (L : List (Γ k)) : Cfg₂ := ⟨some default, default, update (fun _ ↦ []) k L⟩ /-- Evaluates a TM2 program to completion, with the output on the same stack as the input. -/ def eval (M : Λ → Stmt₂) (k : K) (L : List (Γ k)) : Part (List (Γ k)) := (Turing.eval (step M) (init k L)).map fun c ↦ c.stk k end end TM2 /-! ## TM2 emulator in TM1 To prove that TM2 computable functions are TM1 computable, we need to reduce each TM2 program to a TM1 program. So suppose a TM2 program is given. This program has to maintain a whole collection of stacks, but we have only one tape, so we must "multiplex" them all together. Pictorially, if stack 1 contains `[a, b]` and stack 2 contains `[c, d, e, f]` then the tape looks like this: ``` bottom: ... | _ | T | _ | _ | _ | _ | ... stack 1: ... | _ | b | a | _ | _ | _ | ... stack 2: ... | _ | f | e | d | c | _ | ... ``` where a tape element is a vertical slice through the diagram. Here the alphabet is `Γ' := Bool × ∀ k, Option (Γ k)`, where: * `bottom : Bool` is marked only in one place, the initial position of the TM, and represents the tail of all stacks. It is never modified. * `stk k : Option (Γ k)` is the value of the `k`-th stack, if in range, otherwise `none` (which is the blank value). Note that the head of the stack is at the far end; this is so that push and pop don't have to do any shifting. In "resting" position, the TM is sitting at the position marked `bottom`. For non-stack actions, it operates in place, but for the stack actions `push`, `peek`, and `pop`, it must shuttle to the end of the appropriate stack, make its changes, and then return to the bottom. So the states are: * `normal (l : Λ)`: waiting at `bottom` to execute function `l` * `go k (s : StAct k) (q : Stmt₂)`: travelling to the right to get to the end of stack `k` in order to perform stack action `s`, and later continue with executing `q` * `ret (q : Stmt₂)`: travelling to the left after having performed a stack action, and executing `q` once we arrive Because of the shuttling, emulation overhead is `O(n)`, where `n` is the current maximum of the length of all stacks. Therefore a program that takes `k` steps to run in TM2 takes `O((m+k)k)` steps to run when emulated in TM1, where `m` is the length of the input. -/ namespace TM2to1 -- A displaced lemma proved in unnecessary generality theorem stk_nth_val {K : Type*} {Γ : K → Type*} {L : ListBlank (∀ k, Option (Γ k))} {k S} (n) (hL : ListBlank.map (proj k) L = ListBlank.mk (List.map some S).reverse) : L.nth n k = S.reverse.get? n := by rw [← proj_map_nth, hL, ← List.map_reverse, ListBlank.nth_mk, List.getI_eq_iget_get?, List.get?_map] cases S.reverse.get? n <;> rfl section variable {K : Type*} [DecidableEq K] variable {Γ : K → Type*} variable {Λ : Type*} [Inhabited Λ] variable {σ : Type*} [Inhabited σ] local notation "Stmt₂" => TM2.Stmt Γ Λ σ local notation "Cfg₂" => TM2.Cfg Γ Λ σ -- Porting note: `DecidableEq K` is not necessary. /-- The alphabet of the TM2 simulator on TM1 is a marker for the stack bottom, plus a vector of stack elements for each stack, or none if the stack does not extend this far. -/ def Γ' := Bool × ∀ k, Option (Γ k) local notation "Γ'₂₁" => @Γ' K Γ -- Porting note (#10750): added this to clean up types. instance Γ'.inhabited : Inhabited Γ'₂₁ := ⟨⟨false, fun _ ↦ none⟩⟩ instance Γ'.fintype [Fintype K] [∀ k, Fintype (Γ k)] : Fintype Γ'₂₁ := instFintypeProd _ _ /-- The bottom marker is fixed throughout the calculation, so we use the `addBottom` function to express the program state in terms of a tape with only the stacks themselves. -/ def addBottom (L : ListBlank (∀ k, Option (Γ k))) : ListBlank Γ'₂₁ := ListBlank.cons (true, L.head) (L.tail.map ⟨Prod.mk false, rfl⟩) theorem addBottom_map (L : ListBlank (∀ k, Option (Γ k))) : (addBottom L).map ⟨Prod.snd, by rfl⟩ = L := by simp only [addBottom, ListBlank.map_cons] convert ListBlank.cons_head_tail L generalize ListBlank.tail L = L' refine L'.induction_on fun l ↦ ?_; simp theorem addBottom_modifyNth (f : (∀ k, Option (Γ k)) → ∀ k, Option (Γ k)) (L : ListBlank (∀ k, Option (Γ k))) (n : ℕ) : (addBottom L).modifyNth (fun a ↦ (a.1, f a.2)) n = addBottom (L.modifyNth f n) := by cases n <;> simp only [addBottom, ListBlank.head_cons, ListBlank.modifyNth, ListBlank.tail_cons] congr; symm; apply ListBlank.map_modifyNth; intro; rfl theorem addBottom_nth_snd (L : ListBlank (∀ k, Option (Γ k))) (n : ℕ) : ((addBottom L).nth n).2 = L.nth n := by conv => rhs; rw [← addBottom_map L, ListBlank.nth_map] theorem addBottom_nth_succ_fst (L : ListBlank (∀ k, Option (Γ k))) (n : ℕ) : ((addBottom L).nth (n + 1)).1 = false := by rw [ListBlank.nth_succ, addBottom, ListBlank.tail_cons, ListBlank.nth_map] theorem addBottom_head_fst (L : ListBlank (∀ k, Option (Γ k))) : (addBottom L).head.1 = true := by rw [addBottom, ListBlank.head_cons] /-- A stack action is a command that interacts with the top of a stack. Our default position is at the bottom of all the stacks, so we have to hold on to this action while going to the end to modify the stack. -/ inductive StAct (k : K) | push : (σ → Γ k) → StAct k | peek : (σ → Option (Γ k) → σ) → StAct k | pop : (σ → Option (Γ k) → σ) → StAct k local notation "StAct₂" => @StAct K Γ σ -- Porting note (#10750): added this to clean up types. instance StAct.inhabited {k : K} : Inhabited (StAct₂ k) := ⟨StAct.peek fun s _ ↦ s⟩ section open StAct -- Porting note: `Inhabited Γ` is not necessary. /-- The TM2 statement corresponding to a stack action. -/ def stRun {k : K} : StAct₂ k → Stmt₂ → Stmt₂ | push f => TM2.Stmt.push k f | peek f => TM2.Stmt.peek k f | pop f => TM2.Stmt.pop k f /-- The effect of a stack action on the local variables, given the value of the stack. -/ def stVar {k : K} (v : σ) (l : List (Γ k)) : StAct₂ k → σ | push _ => v | peek f => f v l.head? | pop f => f v l.head? /-- The effect of a stack action on the stack. -/ def stWrite {k : K} (v : σ) (l : List (Γ k)) : StAct₂ k → List (Γ k) | push f => f v :: l | peek _ => l | pop _ => l.tail /-- We have partitioned the TM2 statements into "stack actions", which require going to the end of the stack, and all other actions, which do not. This is a modified recursor which lumps the stack actions into one. -/ @[elab_as_elim] def stmtStRec.{l} {C : Stmt₂ → Sort l} (H₁ : ∀ (k) (s : StAct₂ k) (q) (_ : C q), C (stRun s q)) (H₂ : ∀ (a q) (_ : C q), C (TM2.Stmt.load a q)) (H₃ : ∀ (p q₁ q₂) (_ : C q₁) (_ : C q₂), C (TM2.Stmt.branch p q₁ q₂)) (H₄ : ∀ l, C (TM2.Stmt.goto l)) (H₅ : C TM2.Stmt.halt) : ∀ n, C n | TM2.Stmt.push _ f q => H₁ _ (push f) _ (stmtStRec H₁ H₂ H₃ H₄ H₅ q) | TM2.Stmt.peek _ f q => H₁ _ (peek f) _ (stmtStRec H₁ H₂ H₃ H₄ H₅ q) | TM2.Stmt.pop _ f q => H₁ _ (pop f) _ (stmtStRec H₁ H₂ H₃ H₄ H₅ q) | TM2.Stmt.load _ q => H₂ _ _ (stmtStRec H₁ H₂ H₃ H₄ H₅ q) | TM2.Stmt.branch _ q₁ q₂ => H₃ _ _ _ (stmtStRec H₁ H₂ H₃ H₄ H₅ q₁) (stmtStRec H₁ H₂ H₃ H₄ H₅ q₂) | TM2.Stmt.goto _ => H₄ _ | TM2.Stmt.halt => H₅ theorem supports_run (S : Finset Λ) {k : K} (s : StAct₂ k) (q : Stmt₂) : TM2.SupportsStmt S (stRun s q) ↔ TM2.SupportsStmt S q := by cases s <;> rfl end /-- The machine states of the TM2 emulator. We can either be in a normal state when waiting for the next TM2 action, or we can be in the "go" and "return" states to go to the top of the stack and return to the bottom, respectively. -/ inductive Λ' | normal : Λ → Λ' | go (k : K) : StAct₂ k → Stmt₂ → Λ' | ret : Stmt₂ → Λ' local notation "Λ'₂₁" => @Λ' K Γ Λ σ -- Porting note (#10750): added this to clean up types. open Λ' instance Λ'.inhabited : Inhabited Λ'₂₁ := ⟨normal default⟩ local notation "Stmt₂₁" => TM1.Stmt Γ'₂₁ Λ'₂₁ σ local notation "Cfg₂₁" => TM1.Cfg Γ'₂₁ Λ'₂₁ σ open TM1.Stmt /-- The program corresponding to state transitions at the end of a stack. Here we start out just after the top of the stack, and should end just after the new top of the stack. -/ def trStAct {k : K} (q : Stmt₂₁) : StAct₂ k → Stmt₂₁ | StAct.push f => (write fun a s ↦ (a.1, update a.2 k <| some <| f s)) <| move Dir.right q | StAct.peek f => move Dir.left <| (load fun a s ↦ f s (a.2 k)) <| move Dir.right q | StAct.pop f => branch (fun a _ ↦ a.1) (load (fun _ s ↦ f s none) q) (move Dir.left <| (load fun a s ↦ f s (a.2 k)) <| write (fun a _ ↦ (a.1, update a.2 k none)) q) /-- The initial state for the TM2 emulator, given an initial TM2 state. All stacks start out empty except for the input stack, and the stack bottom mark is set at the head. -/ def trInit (k : K) (L : List (Γ k)) : List Γ'₂₁ := let L' : List Γ'₂₁ := L.reverse.map fun a ↦ (false, update (fun _ ↦ none) k (some a)) (true, L'.headI.2) :: L'.tail theorem step_run {k : K} (q : Stmt₂) (v : σ) (S : ∀ k, List (Γ k)) : ∀ s : StAct₂ k, TM2.stepAux (stRun s q) v S = TM2.stepAux q (stVar v (S k) s) (update S k (stWrite v (S k) s)) | StAct.push f => rfl | StAct.peek f => by unfold stWrite; rw [Function.update_eq_self]; rfl | StAct.pop f => rfl /-- The translation of TM2 statements to TM1 statements. regular actions have direct equivalents, but stack actions are deferred by going to the corresponding `go` state, so that we can find the appropriate stack top. -/ def trNormal : Stmt₂ → Stmt₂₁ | TM2.Stmt.push k f q => goto fun _ _ ↦ go k (StAct.push f) q | TM2.Stmt.peek k f q => goto fun _ _ ↦ go k (StAct.peek f) q | TM2.Stmt.pop k f q => goto fun _ _ ↦ go k (StAct.pop f) q | TM2.Stmt.load a q => load (fun _ ↦ a) (trNormal q) | TM2.Stmt.branch f q₁ q₂ => branch (fun _ ↦ f) (trNormal q₁) (trNormal q₂) | TM2.Stmt.goto l => goto fun _ s ↦ normal (l s) | TM2.Stmt.halt => halt theorem trNormal_run {k : K} (s : StAct₂ k) (q : Stmt₂) : trNormal (stRun s q) = goto fun _ _ ↦ go k s q := by cases s <;> rfl open scoped Classical /-- The set of machine states accessible from an initial TM2 statement. -/ noncomputable def trStmts₁ : Stmt₂ → Finset Λ'₂₁ | TM2.Stmt.push k f q => {go k (StAct.push f) q, ret q} ∪ trStmts₁ q | TM2.Stmt.peek k f q => {go k (StAct.peek f) q, ret q} ∪ trStmts₁ q | TM2.Stmt.pop k f q => {go k (StAct.pop f) q, ret q} ∪ trStmts₁ q | TM2.Stmt.load _ q => trStmts₁ q | TM2.Stmt.branch _ q₁ q₂ => trStmts₁ q₁ ∪ trStmts₁ q₂ | _ => ∅ theorem trStmts₁_run {k : K} {s : StAct₂ k} {q : Stmt₂} : trStmts₁ (stRun s q) = {go k s q, ret q} ∪ trStmts₁ q := by cases s <;> simp only [trStmts₁] theorem tr_respects_aux₂ {k : K} {q : Stmt₂₁} {v : σ} {S : ∀ k, List (Γ k)} {L : ListBlank (∀ k, Option (Γ k))} (hL : ∀ k, L.map (proj k) = ListBlank.mk ((S k).map some).reverse) (o : StAct₂ k) : let v' := stVar v (S k) o let Sk' := stWrite v (S k) o let S' := update S k Sk' ∃ L' : ListBlank (∀ k, Option (Γ k)), (∀ k, L'.map (proj k) = ListBlank.mk ((S' k).map some).reverse) ∧ TM1.stepAux (trStAct q o) v ((Tape.move Dir.right)^[(S k).length] (Tape.mk' ∅ (addBottom L))) = TM1.stepAux q v' ((Tape.move Dir.right)^[(S' k).length] (Tape.mk' ∅ (addBottom L'))) := by simp only [Function.update_same]; cases o with simp only [stWrite, stVar, trStAct, TM1.stepAux] | push f => have := Tape.write_move_right_n fun a : Γ' ↦ (a.1, update a.2 k (some (f v))) refine ⟨_, fun k' ↦ ?_, by -- Porting note: `rw [...]` to `erw [...]; rfl`. -- https://github.com/leanprover-community/mathlib4/issues/5164 erw [Tape.move_right_n_head, List.length, Tape.mk'_nth_nat, this, addBottom_modifyNth fun a ↦ update a k (some (f v)), Nat.add_one, iterate_succ'] rfl⟩ refine ListBlank.ext fun i ↦ ?_ rw [ListBlank.nth_map, ListBlank.nth_modifyNth, proj, PointedMap.mk_val] by_cases h' : k' = k · subst k' split_ifs with h <;> simp only [List.reverse_cons, Function.update_same, ListBlank.nth_mk, List.map] -- Porting note: `le_refl` is required. · rw [List.getI_eq_get, List.get_append_right'] <;> simp only [List.length_singleton, h, List.length_reverse, List.length_map, Nat.sub_self, Fin.zero_eta, List.get_cons_zero, le_refl, List.length_append, Nat.lt_succ_self] rw [← proj_map_nth, hL, ListBlank.nth_mk] cases' lt_or_gt_of_ne h with h h · rw [List.getI_append] simpa only [List.length_map, List.length_reverse] using h · rw [gt_iff_lt] at h rw [List.getI_eq_default, List.getI_eq_default] <;> simp only [Nat.add_one_le_iff, h, List.length, le_of_lt, List.length_reverse, List.length_append, List.length_map] · split_ifs <;> rw [Function.update_noteq h', ← proj_map_nth, hL] rw [Function.update_noteq h'] | peek f => rw [Function.update_eq_self] use L, hL; rw [Tape.move_left_right]; congr cases e : S k; · rfl rw [List.length_cons, iterate_succ', Function.comp, Tape.move_right_left, Tape.move_right_n_head, Tape.mk'_nth_nat, addBottom_nth_snd, stk_nth_val _ (hL k), e, List.reverse_cons, ← List.length_reverse, List.get?_concat_length] rfl | pop f => cases' e : S k with hd tl · simp only [Tape.mk'_head, ListBlank.head_cons, Tape.move_left_mk', List.length, Tape.write_mk', List.head?, iterate_zero_apply, List.tail_nil] rw [← e, Function.update_eq_self] exact ⟨L, hL, by rw [addBottom_head_fst, cond]⟩ · refine ⟨_, fun k' ↦ ?_, by erw [List.length_cons, Tape.move_right_n_head, Tape.mk'_nth_nat, addBottom_nth_succ_fst, cond, iterate_succ', Function.comp, Tape.move_right_left, Tape.move_right_n_head, Tape.mk'_nth_nat, Tape.write_move_right_n fun a : Γ' ↦ (a.1, update a.2 k none), addBottom_modifyNth fun a ↦ update a k none, addBottom_nth_snd, stk_nth_val _ (hL k), e, show (List.cons hd tl).reverse.get? tl.length = some hd by rw [List.reverse_cons, ← List.length_reverse, List.get?_concat_length], List.head?, List.tail]⟩ refine ListBlank.ext fun i ↦ ?_ rw [ListBlank.nth_map, ListBlank.nth_modifyNth, proj, PointedMap.mk_val] by_cases h' : k' = k · subst k' split_ifs with h <;> simp only [Function.update_same, ListBlank.nth_mk, List.tail] · rw [List.getI_eq_default] · rfl rw [h, List.length_reverse, List.length_map] rw [← proj_map_nth, hL, ListBlank.nth_mk, e, List.map, List.reverse_cons] cases' lt_or_gt_of_ne h with h h · rw [List.getI_append] simpa only [List.length_map, List.length_reverse] using h · rw [gt_iff_lt] at h rw [List.getI_eq_default, List.getI_eq_default] <;> simp only [Nat.add_one_le_iff, h, List.length, le_of_lt, List.length_reverse, List.length_append, List.length_map] · split_ifs <;> rw [Function.update_noteq h', ← proj_map_nth, hL] rw [Function.update_noteq h'] variable (M : Λ → TM2.Stmt Γ Λ σ) -- Porting note: Unfolded `Stmt₂`. /-- The TM2 emulator machine states written as a TM1 program. This handles the `go` and `ret` states, which shuttle to and from a stack top. -/ def tr : Λ'₂₁ → Stmt₂₁ | normal q => trNormal (M q) | go k s q => branch (fun a _ ↦ (a.2 k).isNone) (trStAct (goto fun _ _ ↦ ret q) s) (move Dir.right <| goto fun _ _ ↦ go k s q) | ret q => branch (fun a _ ↦ a.1) (trNormal q) (move Dir.left <| goto fun _ _ ↦ ret q) -- Porting note: unknown attribute -- attribute [local pp_using_anonymous_constructor] Turing.TM1.Cfg /-- The relation between TM2 configurations and TM1 configurations of the TM2 emulator. -/ inductive TrCfg : Cfg₂ → Cfg₂₁ → Prop | mk {q : Option Λ} {v : σ} {S : ∀ k, List (Γ k)} (L : ListBlank (∀ k, Option (Γ k))) : (∀ k, L.map (proj k) = ListBlank.mk ((S k).map some).reverse) → TrCfg ⟨q, v, S⟩ ⟨q.map normal, v, Tape.mk' ∅ (addBottom L)⟩ theorem tr_respects_aux₁ {k} (o q v) {S : List (Γ k)} {L : ListBlank (∀ k, Option (Γ k))} (hL : L.map (proj k) = ListBlank.mk (S.map some).reverse) (n) (H : n ≤ S.length) : Reaches₀ (TM1.step (tr M)) ⟨some (go k o q), v, Tape.mk' ∅ (addBottom L)⟩ ⟨some (go k o q), v, (Tape.move Dir.right)^[n] (Tape.mk' ∅ (addBottom L))⟩ := by induction' n with n IH; · rfl apply (IH (le_of_lt H)).tail rw [iterate_succ_apply'] simp only [TM1.step, TM1.stepAux, tr, Tape.mk'_nth_nat, Tape.move_right_n_head, addBottom_nth_snd, Option.mem_def] rw [stk_nth_val _ hL, List.get?_eq_get] · rfl · rwa [List.length_reverse] theorem tr_respects_aux₃ {q v} {L : ListBlank (∀ k, Option (Γ k))} (n) : Reaches₀ (TM1.step (tr M)) ⟨some (ret q), v, (Tape.move Dir.right)^[n] (Tape.mk' ∅ (addBottom L))⟩ ⟨some (ret q), v, Tape.mk' ∅ (addBottom L)⟩ := by induction' n with n IH; · rfl refine Reaches₀.head ?_ IH simp only [Option.mem_def, TM1.step] rw [Option.some_inj, tr, TM1.stepAux, Tape.move_right_n_head, Tape.mk'_nth_nat, addBottom_nth_succ_fst, TM1.stepAux, iterate_succ', Function.comp_apply, Tape.move_right_left] rfl theorem tr_respects_aux {q v T k} {S : ∀ k, List (Γ k)} (hT : ∀ k, ListBlank.map (proj k) T = ListBlank.mk ((S k).map some).reverse) (o : StAct₂ k) (IH : ∀ {v : σ} {S : ∀ k : K, List (Γ k)} {T : ListBlank (∀ k, Option (Γ k))}, (∀ k, ListBlank.map (proj k) T = ListBlank.mk ((S k).map some).reverse) → ∃ b, TrCfg (TM2.stepAux q v S) b ∧ Reaches (TM1.step (tr M)) (TM1.stepAux (trNormal q) v (Tape.mk' ∅ (addBottom T))) b) : ∃ b, TrCfg (TM2.stepAux (stRun o q) v S) b ∧ Reaches (TM1.step (tr M)) (TM1.stepAux (trNormal (stRun o q)) v (Tape.mk' ∅ (addBottom T))) b := by simp only [trNormal_run, step_run] have hgo := tr_respects_aux₁ M o q v (hT k) _ le_rfl obtain ⟨T', hT', hrun⟩ := tr_respects_aux₂ hT o have := hgo.tail' rfl rw [tr, TM1.stepAux, Tape.move_right_n_head, Tape.mk'_nth_nat, addBottom_nth_snd, stk_nth_val _ (hT k), List.get?_len_le (le_of_eq (List.length_reverse _)), Option.isNone, cond, hrun, TM1.stepAux] at this obtain ⟨c, gc, rc⟩ := IH hT' refine ⟨c, gc, (this.to₀.trans (tr_respects_aux₃ M _) c (TransGen.head' rfl ?_)).to_reflTransGen⟩ rw [tr, TM1.stepAux, Tape.mk'_head, addBottom_head_fst] exact rc attribute [local simp] Respects TM2.step TM2.stepAux trNormal theorem tr_respects : Respects (TM2.step M) (TM1.step (tr M)) TrCfg := by -- Porting note(#12129): additional beta reduction needed intro c₁ c₂ h cases' h with l v S L hT cases' l with l; · constructor rsuffices ⟨b, c, r⟩ : ∃ b, _ ∧ Reaches (TM1.step (tr M)) _ _ · exact ⟨b, c, TransGen.head' rfl r⟩ simp only [tr] -- Porting note: `refine'` failed because of implicit lambda, so `induction` is used. generalize M l = N induction N using stmtStRec generalizing v S L hT with | H₁ k s q IH => exact tr_respects_aux M hT s @IH | H₂ a _ IH => exact IH _ hT | H₃ p q₁ q₂ IH₁ IH₂ => unfold TM2.stepAux trNormal TM1.stepAux beta_reduce cases p v <;> [exact IH₂ _ hT; exact IH₁ _ hT] | H₄ => exact ⟨_, ⟨_, hT⟩, ReflTransGen.refl⟩ | H₅ => exact ⟨_, ⟨_, hT⟩, ReflTransGen.refl⟩ theorem trCfg_init (k) (L : List (Γ k)) : TrCfg (TM2.init k L) (TM1.init (trInit k L) : Cfg₂₁) := by rw [(_ : TM1.init _ = _)] · refine ⟨ListBlank.mk (L.reverse.map fun a ↦ update default k (some a)), fun k' ↦ ?_⟩ refine ListBlank.ext fun i ↦ ?_ rw [ListBlank.map_mk, ListBlank.nth_mk, List.getI_eq_iget_get?, List.map_map] have : ((proj k').f ∘ fun a => update (β := fun k => Option (Γ k)) default k (some a)) = fun a => (proj k').f (update (β := fun k => Option (Γ k)) default k (some a)) := rfl rw [this, List.get?_map, proj, PointedMap.mk_val] simp only [] by_cases h : k' = k · subst k' simp only [Function.update_same] rw [ListBlank.nth_mk, List.getI_eq_iget_get?, ← List.map_reverse, List.get?_map] · simp only [Function.update_noteq h] rw [ListBlank.nth_mk, List.getI_eq_iget_get?, List.map, List.reverse_nil] cases L.reverse.get? i <;> rfl · rw [trInit, TM1.init] dsimp only congr <;> cases L.reverse <;> try rfl simp only [List.map_map, List.tail_cons, List.map] rfl theorem tr_eval_dom (k) (L : List (Γ k)) : (TM1.eval (tr M) (trInit k L)).Dom ↔ (TM2.eval M k L).Dom := Turing.tr_eval_dom (tr_respects M) (trCfg_init k L) theorem tr_eval (k) (L : List (Γ k)) {L₁ L₂} (H₁ : L₁ ∈ TM1.eval (tr M) (trInit k L)) (H₂ : L₂ ∈ TM2.eval M k L) : ∃ (S : ∀ k, List (Γ k)) (L' : ListBlank (∀ k, Option (Γ k))), addBottom L' = L₁ ∧ (∀ k, L'.map (proj k) = ListBlank.mk ((S k).map some).reverse) ∧ S k = L₂ := by obtain ⟨c₁, h₁, rfl⟩ := (Part.mem_map_iff _).1 H₁ obtain ⟨c₂, h₂, rfl⟩ := (Part.mem_map_iff _).1 H₂ obtain ⟨_, ⟨L', hT⟩, h₃⟩ := Turing.tr_eval (tr_respects M) (trCfg_init k L) h₂ cases Part.mem_unique h₁ h₃ exact ⟨_, L', by simp only [Tape.mk'_right₀], hT, rfl⟩ /-- The support of a set of TM2 states in the TM2 emulator. -/ noncomputable def trSupp (S : Finset Λ) : Finset Λ'₂₁ := S.biUnion fun l ↦ insert (normal l) (trStmts₁ (M l)) theorem tr_supports {S} (ss : TM2.Supports M S) : TM1.Supports (tr M) (trSupp M S) := ⟨Finset.mem_biUnion.2 ⟨_, ss.1, Finset.mem_insert.2 <| Or.inl rfl⟩, fun l' h ↦ by suffices ∀ (q) (_ : TM2.SupportsStmt S q) (_ : ∀ x ∈ trStmts₁ q, x ∈ trSupp M S), TM1.SupportsStmt (trSupp M S) (trNormal q) ∧ ∀ l' ∈ trStmts₁ q, TM1.SupportsStmt (trSupp M S) (tr M l') by rcases Finset.mem_biUnion.1 h with ⟨l, lS, h⟩ have := this _ (ss.2 l lS) fun x hx ↦ Finset.mem_biUnion.2 ⟨_, lS, Finset.mem_insert_of_mem hx⟩ rcases Finset.mem_insert.1 h with (rfl | h) <;> [exact this.1; exact this.2 _ h] clear h l' refine stmtStRec ?_ ?_ ?_ ?_ ?_ · intro _ s _ IH ss' sub -- stack op rw [TM2to1.supports_run] at ss' simp only [TM2to1.trStmts₁_run, Finset.mem_union, Finset.mem_insert, Finset.mem_singleton] at sub have hgo := sub _ (Or.inl <| Or.inl rfl) have hret := sub _ (Or.inl <| Or.inr rfl) cases' IH ss' fun x hx ↦ sub x <| Or.inr hx with IH₁ IH₂ refine ⟨by simp only [trNormal_run, TM1.SupportsStmt]; intros; exact hgo, fun l h ↦ ?_⟩ rw [trStmts₁_run] at h simp only [TM2to1.trStmts₁_run, Finset.mem_union, Finset.mem_insert, Finset.mem_singleton] at h rcases h with (⟨rfl | rfl⟩ | h) · cases s · exact ⟨fun _ _ ↦ hret, fun _ _ ↦ hgo⟩ · exact ⟨fun _ _ ↦ hret, fun _ _ ↦ hgo⟩ · exact ⟨⟨fun _ _ ↦ hret, fun _ _ ↦ hret⟩, fun _ _ ↦ hgo⟩ · unfold TM1.SupportsStmt TM2to1.tr exact ⟨IH₁, fun _ _ ↦ hret⟩ · exact IH₂ _ h · intro _ _ IH ss' sub -- load unfold TM2to1.trStmts₁ at sub ⊢ exact IH ss' sub · intro _ _ _ IH₁ IH₂ ss' sub -- branch unfold TM2to1.trStmts₁ at sub cases' IH₁ ss'.1 fun x hx ↦ sub x <| Finset.mem_union_left _ hx with IH₁₁ IH₁₂ cases' IH₂ ss'.2 fun x hx ↦ sub x <| Finset.mem_union_right _ hx with IH₂₁ IH₂₂ refine ⟨⟨IH₁₁, IH₂₁⟩, fun l h ↦ ?_⟩ rw [trStmts₁] at h rcases Finset.mem_union.1 h with (h | h) <;> [exact IH₁₂ _ h; exact IH₂₂ _ h] · intro _ ss' _ -- goto simp only [trStmts₁, Finset.not_mem_empty]; refine ⟨?_, fun _ ↦ False.elim⟩ exact fun _ v ↦ Finset.mem_biUnion.2 ⟨_, ss' v, Finset.mem_insert_self _ _⟩ · intro _ _ -- halt simp only [trStmts₁, Finset.not_mem_empty] exact ⟨trivial, fun _ ↦ False.elim⟩⟩ end end TM2to1 end Turing
Computability\AkraBazzi\AkraBazzi.lean
/- Copyright (c) 2023 Frédéric Dupuis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Frédéric Dupuis -/ import Mathlib.Computability.AkraBazzi.GrowsPolynomially import Mathlib.Analysis.Calculus.Deriv.Inv import Mathlib.Analysis.SpecialFunctions.Pow.Deriv /-! # Divide-and-conquer recurrences and the Akra-Bazzi theorem A divide-and-conquer recurrence is a function `T : ℕ → ℝ` that satisfies a recurrence relation of the form `T(n) = ∑_{i=0}^{k-1} a_i T(r_i(n)) + g(n)` for large enough `n`, where `r_i(n)` is some function where `‖r_i(n) - b_i n‖ ∈ o(n / (log n)^2)` for every `i`, the `a_i`'s are some positive coefficients, and the `b_i`'s are reals `∈ (0,1)`. (Note that this can be improved to `O(n / (log n)^(1+ε))`, this is left as future work.) These recurrences arise mainly in the analysis of divide-and-conquer algorithms such as mergesort or Strassen's algorithm for matrix multiplication. This class of algorithms works by dividing an instance of the problem of size `n`, into `k` smaller instances, where the `i`'th instance is of size roughly `b_i n`, and calling itself recursively on those smaller instances. `T(n)` then represents the running time of the algorithm, and `g(n)` represents the running time required to actually divide up the instance and process the answers that come out of the recursive calls. Since virtually all such algorithms produce instances that are only approximately of size `b_i n` (they have to round up or down at the very least), we allow the instance sizes to be given by some function `r_i(n)` that approximates `b_i n`. The Akra-Bazzi theorem gives the asymptotic order of such a recurrence: it states that `T(n) ∈ Θ(n^p (1 + ∑_{u=0}^{n-1} g(n) / u^{p+1}))`, where `p` is the unique real number such that `∑ a_i b_i^p = 1`. ## Main definitions and results * `AkraBazziRecurrence T g a b r`: the predicate stating that `T : ℕ → ℝ` satisfies an Akra-Bazzi recurrence with parameters `g`, `a`, `b` and `r` as above. * `GrowsPolynomially`: The growth condition that `g` must satisfy for the theorem to apply. It roughly states that `c₁ g(n) ≤ g(u) ≤ c₂ g(n)`, for u between b*n and n for any constant `b ∈ (0,1)`. * `sumTransform`: The transformation which turns a function `g` into `n^p * ∑ u ∈ Finset.Ico n₀ n, g u / u^(p+1)`. * `asympBound`: The asymptotic bound satisfied by an Akra-Bazzi recurrence, namely `n^p (1 + ∑ g(u) / u^(p+1))` * `isTheta_asympBound`: The main result stating that `T(n) ∈ Θ(n^p (1 + ∑_{u=0}^{n-1} g(n) / u^{p+1}))` ## Implementation Note that the original version of the theorem has an integral rather than a sum in the above expression, and first considers the `T : ℝ → ℝ` case before moving on to `ℕ → ℝ`. We prove the above version with a sum, as it is simpler and more relevant for algorithms. ## TODO * Specialize this theorem to the very common case where the recurrence is of the form `T(n) = ℓT(r_i(n)) + g(n)` where `g(n) ∈ Θ(n^t)` for some `t`. (This is often called the "master theorem" in the literature.) * Add the original version of the theorem with an integral instead of a sum. ## References * Mohamad Akra and Louay Bazzi, On the solution of linear recurrence equations * Tom Leighton, Notes on better master theorems for divide-and-conquer recurrences * Manuel Eberl, Asymptotic reasoning in a proof assistant -/ open Finset Real Filter Asymptotics open scoped Topology /-! #### Definition of Akra-Bazzi recurrences This section defines the predicate `AkraBazziRecurrence T g a b r` which states that `T` satisfies the recurrence `T(n) = ∑_{i=0}^{k-1} a_i T(r_i(n)) + g(n)` with appropriate conditions on the various parameters. -/ /-- An Akra-Bazzi recurrence is a function that satisfies the recurrence `T n = (∑ i, a i * T (r i n)) + g n`. -/ structure AkraBazziRecurrence {α : Type*} [Fintype α] [Nonempty α] (T : ℕ → ℝ) (g : ℝ → ℝ) (a : α → ℝ) (b : α → ℝ) (r : α → ℕ → ℕ) where /-- Point below which the recurrence is in the base case -/ n₀ : ℕ /-- `n₀` is always `> 0` -/ n₀_gt_zero : 0 < n₀ /-- The `a`'s are nonzero -/ a_pos : ∀ i, 0 < a i /-- The `b`'s are nonzero -/ b_pos : ∀ i, 0 < b i /-- The b's are less than 1 -/ b_lt_one : ∀ i, b i < 1 /-- `g` is nonnegative -/ g_nonneg : ∀ x ≥ 0, 0 ≤ g x /-- `g` grows polynomially -/ g_grows_poly : AkraBazziRecurrence.GrowsPolynomially g /-- The actual recurrence -/ h_rec (n : ℕ) (hn₀ : n₀ ≤ n) : T n = (∑ i, a i * T (r i n)) + g n /-- Base case: `T(n) > 0` whenever `n < n₀` -/ T_gt_zero' (n : ℕ) (hn : n < n₀) : 0 < T n /-- The `r`'s always reduce `n` -/ r_lt_n : ∀ i n, n₀ ≤ n → r i n < n /-- The `r`'s approximate the `b`'s -/ dist_r_b : ∀ i, (fun n => (r i n : ℝ) - b i * n) =o[atTop] fun n => n / (log n) ^ 2 namespace AkraBazziRecurrence section min_max variable {α : Type*} [Finite α] [Nonempty α] /-- Smallest `b i` -/ noncomputable def min_bi (b : α → ℝ) : α := Classical.choose <| Finite.exists_min b /-- Largest `b i` -/ noncomputable def max_bi (b : α → ℝ) : α := Classical.choose <| Finite.exists_max b @[aesop safe apply] lemma min_bi_le {b : α → ℝ} (i : α) : b (min_bi b) ≤ b i := Classical.choose_spec (Finite.exists_min b) i @[aesop safe apply] lemma max_bi_le {b : α → ℝ} (i : α) : b i ≤ b (max_bi b) := Classical.choose_spec (Finite.exists_max b) i end min_max variable {α : Type*} [Fintype α] [Nonempty α] {T : ℕ → ℝ} {g : ℝ → ℝ} {a b : α → ℝ} {r : α → ℕ → ℕ} (R : AkraBazziRecurrence T g a b r) lemma dist_r_b' : ∀ᶠ n in atTop, ∀ i, ‖(r i n : ℝ) - b i * n‖ ≤ n / log n ^ 2 := by rw [Filter.eventually_all] intro i simpa using IsLittleO.eventuallyLE (R.dist_r_b i) lemma isLittleO_self_div_log_id : (fun (n : ℕ) => n / log n ^ 2) =o[atTop] (fun (n : ℕ) => (n : ℝ)) := by calc (fun (n : ℕ) => (n : ℝ) / log n ^ 2) = fun (n : ℕ) => (n : ℝ) * ((log n) ^ 2)⁻¹ := by simp_rw [div_eq_mul_inv] _ =o[atTop] fun (n : ℕ) => (n : ℝ) * 1⁻¹ := by refine IsBigO.mul_isLittleO (isBigO_refl _ _) ?_ refine IsLittleO.inv_rev ?main ?zero case zero => simp case main => calc _ = (fun (_ : ℕ) => ((1 : ℝ) ^ 2)) := by simp _ =o[atTop] (fun (n : ℕ) => (log n)^2) := IsLittleO.pow (IsLittleO.natCast_atTop <| isLittleO_const_log_atTop) (by norm_num) _ = (fun (n : ℕ) => (n : ℝ)) := by ext; simp lemma eventually_b_le_r : ∀ᶠ (n : ℕ) in atTop, ∀ i, (b i : ℝ) * n - (n / log n ^ 2) ≤ r i n := by filter_upwards [R.dist_r_b'] with n hn intro i have h₁ : 0 ≤ b i := le_of_lt <| R.b_pos _ rw [sub_le_iff_le_add, add_comm, ← sub_le_iff_le_add] calc (b i : ℝ) * n - r i n = ‖b i * n‖ - ‖(r i n : ℝ)‖ := by simp only [norm_mul, RCLike.norm_natCast, sub_left_inj, Nat.cast_eq_zero, Real.norm_of_nonneg h₁] _ ≤ ‖(b i * n : ℝ) - r i n‖ := norm_sub_norm_le _ _ _ = ‖(r i n : ℝ) - b i * n‖ := norm_sub_rev _ _ _ ≤ n / log n ^ 2 := hn i lemma eventually_r_le_b : ∀ᶠ (n : ℕ) in atTop, ∀ i, r i n ≤ (b i : ℝ) * n + (n / log n ^ 2) := by filter_upwards [R.dist_r_b'] with n hn intro i calc r i n = b i * n + (r i n - b i * n) := by ring _ ≤ b i * n + ‖r i n - b i * n‖ := by gcongr; exact Real.le_norm_self _ _ ≤ b i * n + n / log n ^ 2 := by gcongr; exact hn i lemma eventually_r_lt_n : ∀ᶠ (n : ℕ) in atTop, ∀ i, r i n < n := by filter_upwards [eventually_ge_atTop R.n₀] with n hn exact fun i => R.r_lt_n i n hn lemma eventually_bi_mul_le_r : ∀ᶠ (n : ℕ) in atTop, ∀ i, (b (min_bi b) / 2) * n ≤ r i n := by have gt_zero : 0 < b (min_bi b) := R.b_pos (min_bi b) have hlo := isLittleO_self_div_log_id rw [Asymptotics.isLittleO_iff] at hlo have hlo' := hlo (by positivity : 0 < b (min_bi b) / 2) filter_upwards [hlo', R.eventually_b_le_r] with n hn hn' intro i simp only [Real.norm_of_nonneg (by positivity : 0 ≤ (n : ℝ))] at hn calc b (min_bi b) / 2 * n = b (min_bi b) * n - b (min_bi b) / 2 * n := by ring _ ≤ b (min_bi b) * n - ‖n / log n ^ 2‖ := by gcongr _ ≤ b i * n - ‖n / log n ^ 2‖ := by gcongr; aesop _ = b i * n - n / log n ^ 2 := by congr exact Real.norm_of_nonneg <| by positivity _ ≤ r i n := hn' i lemma bi_min_div_two_lt_one : b (min_bi b) / 2 < 1 := by have gt_zero : 0 < b (min_bi b) := R.b_pos (min_bi b) calc b (min_bi b) / 2 < b (min_bi b) := by aesop (add safe apply div_two_lt_of_pos) _ < 1 := R.b_lt_one _ lemma bi_min_div_two_pos : 0 < b (min_bi b) / 2 := div_pos (R.b_pos _) (by norm_num) lemma exists_eventually_const_mul_le_r : ∃ c ∈ Set.Ioo (0 : ℝ) 1, ∀ᶠ (n : ℕ) in atTop, ∀ i, c * n ≤ r i n := by have gt_zero : 0 < b (min_bi b) := R.b_pos (min_bi b) exact ⟨b (min_bi b) / 2, ⟨⟨by positivity, R.bi_min_div_two_lt_one⟩, R.eventually_bi_mul_le_r⟩⟩ lemma eventually_r_ge (C : ℝ) : ∀ᶠ (n : ℕ) in atTop, ∀ i, C ≤ r i n := by obtain ⟨c, hc_mem, hc⟩ := R.exists_eventually_const_mul_le_r filter_upwards [eventually_ge_atTop ⌈C / c⌉₊, hc] with n hn₁ hn₂ have h₁ := hc_mem.1 intro i calc C = c * (C / c) := by rw [← mul_div_assoc] exact (mul_div_cancel_left₀ _ (by positivity)).symm _ ≤ c * ⌈C / c⌉₊ := by gcongr; simp [Nat.le_ceil] _ ≤ c * n := by gcongr _ ≤ r i n := hn₂ i lemma tendsto_atTop_r (i : α) : Tendsto (r i) atTop atTop := by rw [tendsto_atTop] intro b have := R.eventually_r_ge b rw [Filter.eventually_all] at this exact_mod_cast this i lemma tendsto_atTop_r_real (i : α) : Tendsto (fun n => (r i n : ℝ)) atTop atTop := Tendsto.comp tendsto_natCast_atTop_atTop (R.tendsto_atTop_r i) lemma exists_eventually_r_le_const_mul : ∃ c ∈ Set.Ioo (0 : ℝ) 1, ∀ᶠ (n : ℕ) in atTop, ∀ i, r i n ≤ c * n := by let c := b (max_bi b) + (1 - b (max_bi b)) / 2 have h_max_bi_pos : 0 < b (max_bi b) := R.b_pos _ have h_max_bi_lt_one : 0 < 1 - b (max_bi b) := by have : b (max_bi b) < 1 := R.b_lt_one _ linarith have hc_pos : 0 < c := by positivity have h₁ : 0 < (1 - b (max_bi b)) / 2 := by positivity have hc_lt_one : c < 1 := calc b (max_bi b) + (1 - b (max_bi b)) / 2 = b (max_bi b) * (1 / 2) + 1 / 2 := by ring _ < 1 * (1 / 2) + 1 / 2 := by gcongr exact R.b_lt_one _ _ = 1 := by norm_num refine ⟨c, ⟨hc_pos, hc_lt_one⟩, ?_⟩ have hlo := isLittleO_self_div_log_id rw [Asymptotics.isLittleO_iff] at hlo have hlo' := hlo h₁ filter_upwards [hlo', R.eventually_r_le_b] with n hn hn' intro i rw [Real.norm_of_nonneg (by positivity)] at hn simp only [Real.norm_of_nonneg (by positivity : 0 ≤ (n : ℝ))] at hn calc r i n ≤ b i * n + n / log n ^ 2 := by exact hn' i _ ≤ b i * n + (1 - b (max_bi b)) / 2 * n := by gcongr _ = (b i + (1 - b (max_bi b)) / 2) * n := by ring _ ≤ (b (max_bi b) + (1 - b (max_bi b)) / 2) * n := by gcongr; exact max_bi_le _ lemma eventually_r_pos : ∀ᶠ (n : ℕ) in atTop, ∀ i, 0 < r i n := by rw [Filter.eventually_all] exact fun i => (R.tendsto_atTop_r i).eventually_gt_atTop 0 lemma eventually_log_b_mul_pos : ∀ᶠ (n : ℕ) in atTop, ∀ i, 0 < log (b i * n) := by rw [Filter.eventually_all] intro i have h : Tendsto (fun (n : ℕ) => log (b i * n)) atTop atTop := Tendsto.comp tendsto_log_atTop <| Tendsto.const_mul_atTop (b_pos R i) tendsto_natCast_atTop_atTop exact h.eventually_gt_atTop 0 @[aesop safe apply] lemma T_pos (n : ℕ) : 0 < T n := by induction n using Nat.strongInductionOn with | ind n h_ind => cases lt_or_le n R.n₀ with | inl hn => exact R.T_gt_zero' n hn -- n < R.n₀ | inr hn => -- R.n₀ ≤ n rw [R.h_rec n hn] have := R.g_nonneg refine add_pos_of_pos_of_nonneg (Finset.sum_pos ?sum_elems univ_nonempty) (by aesop) exact fun i _ => mul_pos (R.a_pos i) <| h_ind _ (R.r_lt_n i _ hn) @[aesop safe apply] lemma T_nonneg (n : ℕ) : 0 ≤ T n := le_of_lt <| R.T_pos n /-! #### Smoothing function We define `ε` as the "smoothing function" `fun n => 1 / log n`, which will be used in the form of a factor of `1 ± ε n` needed to make the induction step go through. This is its own definition to make it easier to switch to a different smoothing function. For example, choosing `1 / log n ^ δ` for a suitable choice of `δ` leads to a slightly tighter theorem at the price of a more complicated proof. This part of the file then proves several properties of this function that will be needed later in the proof. -/ /-- The "smoothing function" is defined as `1 / log n`. This is defined as an `ℝ → ℝ` function as opposed to `ℕ → ℝ` since this is more convenient for the proof, where we need to e.g. take derivatives. -/ noncomputable def smoothingFn (n : ℝ) : ℝ := 1 / log n local notation "ε" => smoothingFn lemma one_add_smoothingFn_le_two {x : ℝ} (hx : exp 1 ≤ x) : 1 + ε x ≤ 2 := by simp only [smoothingFn, ← one_add_one_eq_two] gcongr have : 1 < x := by calc 1 = exp 0 := by simp _ < exp 1 := by simp _ ≤ x := hx rw [div_le_one (log_pos this)] calc 1 = log (exp 1) := by simp _ ≤ log x := log_le_log (exp_pos _) hx lemma isLittleO_smoothingFn_one : ε =o[atTop] (fun _ => (1 : ℝ)) := by unfold smoothingFn refine isLittleO_of_tendsto (fun _ h => False.elim <| one_ne_zero h) ?_ simp only [one_div, div_one] exact Tendsto.inv_tendsto_atTop Real.tendsto_log_atTop lemma isEquivalent_one_add_smoothingFn_one : (fun x => 1 + ε x) ~[atTop] (fun _ => (1 : ℝ)) := IsEquivalent.add_isLittleO IsEquivalent.refl isLittleO_smoothingFn_one lemma isEquivalent_one_sub_smoothingFn_one : (fun x => 1 - ε x) ~[atTop] (fun _ => (1 : ℝ)) := IsEquivalent.sub_isLittleO IsEquivalent.refl isLittleO_smoothingFn_one lemma growsPolynomially_one_sub_smoothingFn : GrowsPolynomially fun x => 1 - ε x := GrowsPolynomially.of_isEquivalent_const isEquivalent_one_sub_smoothingFn_one lemma growsPolynomially_one_add_smoothingFn : GrowsPolynomially fun x => 1 + ε x := GrowsPolynomially.of_isEquivalent_const isEquivalent_one_add_smoothingFn_one lemma eventually_one_sub_smoothingFn_gt_const_real (c : ℝ) (hc : c < 1) : ∀ᶠ (x : ℝ) in atTop, c < 1 - ε x := by have h₁ : Tendsto (fun x => 1 - ε x) atTop (𝓝 1) := by rw [← isEquivalent_const_iff_tendsto one_ne_zero] exact isEquivalent_one_sub_smoothingFn_one rw [tendsto_order] at h₁ exact h₁.1 c hc lemma eventually_one_sub_smoothingFn_gt_const (c : ℝ) (hc : c < 1) : ∀ᶠ (n : ℕ) in atTop, c < 1 - ε n := Eventually.natCast_atTop (p := fun n => c < 1 - ε n) <| eventually_one_sub_smoothingFn_gt_const_real c hc lemma eventually_one_sub_smoothingFn_pos_real : ∀ᶠ (x : ℝ) in atTop, 0 < 1 - ε x := eventually_one_sub_smoothingFn_gt_const_real 0 zero_lt_one lemma eventually_one_sub_smoothingFn_pos : ∀ᶠ (n : ℕ) in atTop, 0 < 1 - ε n := (eventually_one_sub_smoothingFn_pos_real).natCast_atTop lemma eventually_one_sub_smoothingFn_nonneg : ∀ᶠ (n : ℕ) in atTop, 0 ≤ 1 - ε n := by filter_upwards [eventually_one_sub_smoothingFn_pos] with n hn; exact le_of_lt hn lemma eventually_one_sub_smoothingFn_r_pos : ∀ᶠ (n : ℕ) in atTop, ∀ i, 0 < 1 - ε (r i n) := by rw [Filter.eventually_all] exact fun i => (R.tendsto_atTop_r_real i).eventually eventually_one_sub_smoothingFn_pos_real @[aesop safe apply] lemma differentiableAt_smoothingFn {x : ℝ} (hx : 1 < x) : DifferentiableAt ℝ ε x := by have : log x ≠ 0 := Real.log_ne_zero_of_pos_of_ne_one (by positivity) (ne_of_gt hx) show DifferentiableAt ℝ (fun z => 1 / log z) x simp_rw [one_div] exact DifferentiableAt.inv (differentiableAt_log (by positivity)) this @[aesop safe apply] lemma differentiableAt_one_sub_smoothingFn {x : ℝ} (hx : 1 < x) : DifferentiableAt ℝ (fun z => 1 - ε z) x := DifferentiableAt.sub (differentiableAt_const _) <| differentiableAt_smoothingFn hx lemma differentiableOn_one_sub_smoothingFn : DifferentiableOn ℝ (fun z => 1 - ε z) (Set.Ioi 1) := fun _ hx => (differentiableAt_one_sub_smoothingFn hx).differentiableWithinAt @[aesop safe apply] lemma differentiableAt_one_add_smoothingFn {x : ℝ} (hx : 1 < x) : DifferentiableAt ℝ (fun z => 1 + ε z) x := DifferentiableAt.add (differentiableAt_const _) <| differentiableAt_smoothingFn hx lemma differentiableOn_one_add_smoothingFn : DifferentiableOn ℝ (fun z => 1 + ε z) (Set.Ioi 1) := fun _ hx => (differentiableAt_one_add_smoothingFn hx).differentiableWithinAt lemma deriv_smoothingFn {x : ℝ} (hx : 1 < x) : deriv ε x = -x⁻¹ / (log x ^ 2) := by have : log x ≠ 0 := Real.log_ne_zero_of_pos_of_ne_one (by positivity) (ne_of_gt hx) show deriv (fun z => 1 / log z) x = -x⁻¹ / (log x ^ 2) rw [deriv_div] <;> aesop lemma isLittleO_deriv_smoothingFn : deriv ε =o[atTop] fun x => x⁻¹ := calc deriv ε =ᶠ[atTop] fun x => -x⁻¹ / (log x ^ 2) := by filter_upwards [eventually_gt_atTop 1] with x hx rw [deriv_smoothingFn hx] _ = fun x => (-x * log x ^ 2)⁻¹ := by simp_rw [neg_div, div_eq_mul_inv, ← mul_inv, neg_inv, neg_mul] _ =o[atTop] fun x => (x * 1)⁻¹ := by refine IsLittleO.inv_rev ?_ ?_ · refine IsBigO.mul_isLittleO (by rw [isBigO_neg_right]; aesop (add safe isBigO_refl)) ?_ rw [isLittleO_one_left_iff] exact Tendsto.comp tendsto_norm_atTop_atTop <| Tendsto.comp (tendsto_pow_atTop (by norm_num)) tendsto_log_atTop · exact Filter.eventually_of_forall (fun x hx => by rw [mul_one] at hx; simp [hx]) _ = fun x => x⁻¹ := by simp lemma eventually_deriv_one_sub_smoothingFn : deriv (fun x => 1 - ε x) =ᶠ[atTop] fun x => x⁻¹ / (log x ^ 2) := calc deriv (fun x => 1 - ε x) =ᶠ[atTop] -(deriv ε) := by filter_upwards [eventually_gt_atTop 1] with x hx; rw [deriv_sub] <;> aesop _ =ᶠ[atTop] fun x => x⁻¹ / (log x ^ 2) := by filter_upwards [eventually_gt_atTop 1] with x hx simp [deriv_smoothingFn hx, neg_div] lemma eventually_deriv_one_add_smoothingFn : deriv (fun x => 1 + ε x) =ᶠ[atTop] fun x => -x⁻¹ / (log x ^ 2) := calc deriv (fun x => 1 + ε x) =ᶠ[atTop] deriv ε := by filter_upwards [eventually_gt_atTop 1] with x hx; rw [deriv_add] <;> aesop _ =ᶠ[atTop] fun x => -x⁻¹ / (log x ^ 2) := by filter_upwards [eventually_gt_atTop 1] with x hx simp [deriv_smoothingFn hx] lemma isLittleO_deriv_one_sub_smoothingFn : deriv (fun x => 1 - ε x) =o[atTop] fun (x : ℝ) => x⁻¹ := calc deriv (fun x => 1 - ε x) =ᶠ[atTop] fun z => -(deriv ε z) := by filter_upwards [eventually_gt_atTop 1] with x hx; rw [deriv_sub] <;> aesop _ =o[atTop] fun x => x⁻¹ := by rw [isLittleO_neg_left]; exact isLittleO_deriv_smoothingFn lemma isLittleO_deriv_one_add_smoothingFn : deriv (fun x => 1 + ε x) =o[atTop] fun (x : ℝ) => x⁻¹ := calc deriv (fun x => 1 + ε x) =ᶠ[atTop] fun z => deriv ε z := by filter_upwards [eventually_gt_atTop 1] with x hx; rw [deriv_add] <;> aesop _ =o[atTop] fun x => x⁻¹ := isLittleO_deriv_smoothingFn lemma eventually_one_add_smoothingFn_pos : ∀ᶠ (n : ℕ) in atTop, 0 < 1 + ε n := by have h₁ := isLittleO_smoothingFn_one rw [isLittleO_iff] at h₁ refine Eventually.natCast_atTop (p := fun n => 0 < 1 + ε n) ?_ filter_upwards [h₁ (by norm_num : (0 : ℝ) < 1/2), eventually_gt_atTop 1] with x _ hx' have : 0 < log x := Real.log_pos hx' show 0 < 1 + 1 / log x positivity lemma eventually_one_add_smoothingFn_r_pos : ∀ᶠ (n : ℕ) in atTop, ∀ i, 0 < 1 + ε (r i n) := by rw [Filter.eventually_all] exact fun i => (R.tendsto_atTop_r i).eventually (f := r i) eventually_one_add_smoothingFn_pos lemma eventually_one_add_smoothingFn_nonneg : ∀ᶠ (n : ℕ) in atTop, 0 ≤ 1 + ε n := by filter_upwards [eventually_one_add_smoothingFn_pos] with n hn; exact le_of_lt hn lemma strictAntiOn_smoothingFn : StrictAntiOn ε (Set.Ioi 1) := by show StrictAntiOn (fun x => 1 / log x) (Set.Ioi 1) simp_rw [one_div] refine StrictAntiOn.comp_strictMonoOn inv_strictAntiOn ?log fun _ hx => log_pos hx refine StrictMonoOn.mono strictMonoOn_log (fun x hx => ?_) exact Set.Ioi_subset_Ioi zero_le_one hx lemma strictMonoOn_one_sub_smoothingFn : StrictMonoOn (fun (x : ℝ) => (1 : ℝ) - ε x) (Set.Ioi 1) := by simp_rw [sub_eq_add_neg] exact StrictMonoOn.const_add (StrictAntiOn.neg <| strictAntiOn_smoothingFn) 1 lemma strictAntiOn_one_add_smoothingFn : StrictAntiOn (fun (x : ℝ) => (1 : ℝ) + ε x) (Set.Ioi 1) := StrictAntiOn.const_add strictAntiOn_smoothingFn 1 lemma isEquivalent_smoothingFn_sub_self (i : α) : (fun (n : ℕ) => ε (b i * n) - ε n) ~[atTop] fun n => -log (b i) / (log n)^2 := by calc (fun (n : ℕ) => 1 / log (b i * n) - 1 / log n) =ᶠ[atTop] fun (n : ℕ) => (log n - log (b i * n)) / (log (b i * n) * log n) := by filter_upwards [eventually_gt_atTop 1, R.eventually_log_b_mul_pos] with n hn hn' have h_log_pos : 0 < log n := Real.log_pos <| by aesop simp only [one_div] rw [inv_sub_inv (by have := hn' i; positivity) (by aesop)] _ =ᶠ[atTop] (fun (n : ℕ) ↦ (log n - log (b i) - log n) / ((log (b i) + log n) * log n)) := by filter_upwards [eventually_ne_atTop 0] with n hn have : 0 < b i := R.b_pos i rw [log_mul (by positivity) (by aesop), sub_add_eq_sub_sub] _ = (fun (n : ℕ) => -log (b i) / ((log (b i) + log n) * log n)) := by ext; congr; ring _ ~[atTop] (fun (n : ℕ) => -log (b i) / (log n * log n)) := by refine IsEquivalent.div (IsEquivalent.refl) <| IsEquivalent.mul ?_ (IsEquivalent.refl) have : (fun (n : ℕ) => log (b i) + log n) = fun (n : ℕ) => log n + log (b i) := by ext; simp [add_comm] rw [this] exact IsEquivalent.add_isLittleO IsEquivalent.refl <| IsLittleO.natCast_atTop (f := fun (_ : ℝ) => log (b i)) isLittleO_const_log_atTop _ = (fun (n : ℕ) => -log (b i) / (log n)^2) := by ext; congr 1; rw [← pow_two] lemma isTheta_smoothingFn_sub_self (i : α) : (fun (n : ℕ) => ε (b i * n) - ε n) =Θ[atTop] fun n => 1 / (log n)^2 := by calc (fun (n : ℕ) => ε (b i * n) - ε n) =Θ[atTop] fun n => (-log (b i)) / (log n)^2 := by exact (R.isEquivalent_smoothingFn_sub_self i).isTheta _ = fun (n : ℕ) => (-log (b i)) * 1 / (log n)^2 := by simp only [mul_one] _ = fun (n : ℕ) => -log (b i) * (1 / (log n)^2) := by simp_rw [← mul_div_assoc] _ =Θ[atTop] fun (n : ℕ) => 1 / (log n)^2 := by have : -log (b i) ≠ 0 := by rw [neg_ne_zero] exact Real.log_ne_zero_of_pos_of_ne_one (R.b_pos i) (ne_of_lt <| R.b_lt_one i) rw [← isTheta_const_mul_right this] /-! #### Akra-Bazzi exponent `p` Every Akra-Bazzi recurrence has an associated exponent, denoted by `p : ℝ`, such that `∑ a_i b_i^p = 1`. This section shows the existence and uniqueness of this exponent `p` for any `R : AkraBazziRecurrence`, and defines `R.asympBound` to be the asymptotic bound satisfied by `R`, namely `n^p (1 + ∑_{u < n} g(u) / u^(p+1))`. -/ @[continuity] lemma continuous_sumCoeffsExp : Continuous (fun (p : ℝ) => ∑ i, a i * (b i) ^ p) := by refine continuous_finset_sum Finset.univ fun i _ => Continuous.mul (by continuity) ?_ exact Continuous.rpow continuous_const continuous_id (fun x => Or.inl (ne_of_gt (R.b_pos i))) lemma strictAnti_sumCoeffsExp : StrictAnti (fun (p : ℝ) => ∑ i, a i * (b i) ^ p) := by rw [← Finset.sum_fn] refine Finset.sum_induction_nonempty _ _ (fun _ _ => StrictAnti.add) univ_nonempty ?terms refine fun i _ => StrictAnti.const_mul ?_ (R.a_pos i) exact Real.strictAnti_rpow_of_base_lt_one (R.b_pos i) (R.b_lt_one i) lemma tendsto_zero_sumCoeffsExp : Tendsto (fun (p : ℝ) => ∑ i, a i * (b i) ^ p) atTop (𝓝 0) := by have h₁ : Finset.univ.sum (fun _ : α => (0 : ℝ)) = 0 := by simp rw [← h₁] refine tendsto_finset_sum (univ : Finset α) (fun i _ => ?_) rw [← mul_zero (a i)] refine Tendsto.mul (by simp) <| tendsto_rpow_atTop_of_base_lt_one _ ?_ (R.b_lt_one i) have := R.b_pos i linarith lemma tendsto_atTop_sumCoeffsExp : Tendsto (fun (p : ℝ) => ∑ i, a i * (b i) ^ p) atBot atTop := by have h₁ : Tendsto (fun p : ℝ => (a (max_bi b) : ℝ) * b (max_bi b) ^ p) atBot atTop := Tendsto.mul_atTop (R.a_pos (max_bi b)) (by simp) <| tendsto_rpow_atBot_of_base_lt_one _ (by have := R.b_pos (max_bi b); linarith) (R.b_lt_one _) refine tendsto_atTop_mono (fun p => ?_) h₁ refine Finset.single_le_sum (f := fun i => (a i : ℝ) * b i ^ p) (fun i _ => ?_) (mem_univ _) have h₁ : 0 < a i := R.a_pos i have h₂ : 0 < b i := R.b_pos i positivity lemma one_mem_range_sumCoeffsExp : 1 ∈ Set.range (fun (p : ℝ) => ∑ i, a i * (b i) ^ p) := by refine mem_range_of_exists_le_of_exists_ge R.continuous_sumCoeffsExp ?le_one ?ge_one case le_one => exact Eventually.exists <| eventually_le_of_tendsto_lt zero_lt_one R.tendsto_zero_sumCoeffsExp case ge_one => exact Eventually.exists <| R.tendsto_atTop_sumCoeffsExp.eventually_ge_atTop _ /-- The function x ↦ ∑ a_i b_i^x is injective. This implies the uniqueness of `p`. -/ lemma injective_sumCoeffsExp : Function.Injective (fun (p : ℝ) => ∑ i, a i * (b i) ^ p) := R.strictAnti_sumCoeffsExp.injective variable (a b) in /-- The exponent `p` associated with a particular Akra-Bazzi recurrence. -/ noncomputable irreducible_def p : ℝ := Function.invFun (fun (p : ℝ) => ∑ i, a i * (b i) ^ p) 1 @[simp] lemma sumCoeffsExp_p_eq_one : ∑ i, a i * (b i) ^ p a b = 1 := by simp only [p] exact Function.invFun_eq (by rw [← Set.mem_range]; exact R.one_mem_range_sumCoeffsExp) /-! #### The sum transform This section defines the "sum transform" of a function `g` as `∑ u ∈ Finset.Ico n₀ n, g u / u^(p+1)`, and uses it to define `asympBound` as the bound satisfied by an Akra-Bazzi recurrence. Several properties of the sum transform are then proven. -/ /-- The transformation which turns a function `g` into `n^p * ∑ u ∈ Finset.Ico n₀ n, g u / u^(p+1)`. -/ noncomputable def sumTransform (p : ℝ) (g : ℝ → ℝ) (n₀ n : ℕ) := n^p * ∑ u ∈ Finset.Ico n₀ n, g u / u^(p + 1) lemma sumTransform_def {p : ℝ} {g : ℝ → ℝ} {n₀ n : ℕ} : sumTransform p g n₀ n = n^p * ∑ u ∈ Finset.Ico n₀ n, g u / u^(p + 1) := rfl variable (g) (a) (b) /-- The asymptotic bound satisfied by an Akra-Bazzi recurrence, namely `n^p (1 + ∑_{u < n} g(u) / u^(p+1))`. -/ noncomputable def asympBound (n : ℕ) : ℝ := n ^ p a b + sumTransform (p a b) g 0 n lemma asympBound_def {n : ℕ} : asympBound g a b n = n ^ p a b + sumTransform (p a b) g 0 n := rfl variable {g} {a} {b} lemma asympBound_def' {n : ℕ} : asympBound g a b n = n ^ p a b * (1 + (∑ u ∈ range n, g u / u ^ (p a b + 1))) := by simp [asympBound_def, sumTransform, mul_add, mul_one, Finset.sum_Ico_eq_sum_range] lemma asympBound_pos (n : ℕ) (hn : 0 < n) : 0 < asympBound g a b n := by calc 0 < (n : ℝ) ^ p a b * (1 + 0) := by aesop (add safe Real.rpow_pos_of_pos) _ ≤ asympBound g a b n := by simp only [asympBound_def'] gcongr n^p a b * (1 + ?_) have := R.g_nonneg aesop (add safe Real.rpow_nonneg, safe div_nonneg, safe Finset.sum_nonneg) lemma eventually_asympBound_pos : ∀ᶠ (n : ℕ) in atTop, 0 < asympBound g a b n := by filter_upwards [eventually_gt_atTop 0] with n hn exact R.asympBound_pos n hn lemma eventually_asympBound_r_pos : ∀ᶠ (n : ℕ) in atTop, ∀ i, 0 < asympBound g a b (r i n) := by rw [Filter.eventually_all] exact fun i => (R.tendsto_atTop_r i).eventually R.eventually_asympBound_pos lemma eventually_atTop_sumTransform_le : ∃ c > 0, ∀ᶠ (n : ℕ) in atTop, ∀ i, sumTransform (p a b) g (r i n) n ≤ c * g n := by obtain ⟨c₁, hc₁_mem, hc₁⟩ := R.exists_eventually_const_mul_le_r obtain ⟨c₂, hc₂_mem, hc₂⟩ := R.g_grows_poly.eventually_atTop_le_nat hc₁_mem have hc₁_pos : 0 < c₁ := hc₁_mem.1 refine ⟨max c₂ (c₂ / c₁ ^ (p a b + 1)), by positivity, ?_⟩ filter_upwards [hc₁, hc₂, R.eventually_r_pos, R.eventually_r_lt_n, eventually_gt_atTop 0] with n hn₁ hn₂ hrpos hr_lt_n hn_pos intro i have hrpos_i := hrpos i have g_nonneg : 0 ≤ g n := R.g_nonneg n (by positivity) cases le_or_lt 0 (p a b + 1) with | inl hp => -- 0 ≤ p a b + 1 calc sumTransform (p a b) g (r i n) n = n ^ (p a b) * (∑ u ∈ Finset.Ico (r i n) n, g u / u ^ ((p a b) + 1)) := by rfl _ ≤ n ^ (p a b) * (∑ u ∈ Finset.Ico (r i n) n, c₂ * g n / u ^ ((p a b) + 1)) := by gcongr with u hu rw [Finset.mem_Ico] at hu have hu' : u ∈ Set.Icc (r i n) n := ⟨hu.1, by omega⟩ refine hn₂ u ?_ rw [Set.mem_Icc] refine ⟨?_, by norm_cast; omega⟩ calc c₁ * n ≤ r i n := by exact hn₁ i _ ≤ u := by exact_mod_cast hu'.1 _ ≤ n ^ (p a b) * (∑ _u ∈ Finset.Ico (r i n) n, c₂ * g n / (r i n) ^ ((p a b) + 1)) := by gcongr with u hu; rw [Finset.mem_Ico] at hu; exact hu.1 _ ≤ n ^ (p a b) * (Finset.Ico (r i n) n).card • (c₂ * g n / (r i n) ^ ((p a b) + 1)) := by gcongr; exact Finset.sum_le_card_nsmul _ _ _ (fun x _ => by rfl) _ = n ^ (p a b) * (Finset.Ico (r i n) n).card * (c₂ * g n / (r i n) ^ ((p a b) + 1)) := by rw [nsmul_eq_mul, mul_assoc] _ = n ^ (p a b) * (n - r i n) * (c₂ * g n / (r i n) ^ ((p a b) + 1)) := by congr; rw [Nat.card_Ico, Nat.cast_sub (le_of_lt <| hr_lt_n i)] _ ≤ n ^ (p a b) * n * (c₂ * g n / (r i n) ^ ((p a b) + 1)) := by gcongr; simp only [tsub_le_iff_right, le_add_iff_nonneg_right, Nat.cast_nonneg] _ ≤ n ^ (p a b) * n * (c₂ * g n / (c₁ * n) ^ ((p a b) + 1)) := by gcongr; exact hn₁ i _ = c₂ * g n * n ^ ((p a b) + 1) / (c₁ * n) ^ ((p a b) + 1) := by rw [← Real.rpow_add_one (by positivity) (p a b)]; ring _ = c₂ * g n * n ^ ((p a b) + 1) / (n ^ ((p a b) + 1) * c₁ ^ ((p a b) + 1)) := by rw [mul_comm c₁, Real.mul_rpow (by positivity) (by positivity)] _ = c₂ * g n * (n ^ ((p a b) + 1) / (n ^ ((p a b) + 1))) / c₁ ^ ((p a b) + 1) := by ring _ = c₂ * g n / c₁ ^ ((p a b) + 1) := by rw [div_self (by positivity), mul_one] _ = (c₂ / c₁ ^ ((p a b) + 1)) * g n := by ring _ ≤ max c₂ (c₂ / c₁ ^ ((p a b) + 1)) * g n := by gcongr; exact le_max_right _ _ | inr hp => -- p a b + 1 < 0 calc sumTransform (p a b) g (r i n) n = n ^ (p a b) * (∑ u ∈ Finset.Ico (r i n) n, g u / u ^ ((p a b) + 1)) := by rfl _ ≤ n ^ (p a b) * (∑ u ∈ Finset.Ico (r i n) n, c₂ * g n / u ^ ((p a b) + 1)) := by gcongr with u hu rw [Finset.mem_Ico] at hu have hu' : u ∈ Set.Icc (r i n) n := ⟨hu.1, by omega⟩ refine hn₂ u ?_ rw [Set.mem_Icc] refine ⟨?_, by norm_cast; omega⟩ calc c₁ * n ≤ r i n := by exact hn₁ i _ ≤ u := by exact_mod_cast hu'.1 _ ≤ n ^ (p a b) * (∑ _u ∈ Finset.Ico (r i n) n, c₂ * g n / n ^ ((p a b) + 1)) := by gcongr n ^ (p a b) * (Finset.Ico (r i n) n).sum (fun _ => c₂ * g n / ?_) with u hu rw [Finset.mem_Ico] at hu have : 0 < u := calc 0 < r i n := by exact hrpos_i _ ≤ u := by exact hu.1 exact rpow_le_rpow_of_exponent_nonpos (by positivity) (by exact_mod_cast (le_of_lt hu.2)) (le_of_lt hp) _ ≤ n ^ (p a b) * (Finset.Ico (r i n) n).card • (c₂ * g n / n ^ ((p a b) + 1)) := by gcongr; exact Finset.sum_le_card_nsmul _ _ _ (fun x _ => by rfl) _ = n ^ (p a b) * (Finset.Ico (r i n) n).card * (c₂ * g n / n ^ ((p a b) + 1)) := by rw [nsmul_eq_mul, mul_assoc] _ = n ^ (p a b) * (n - r i n) * (c₂ * g n / n ^ ((p a b) + 1)) := by congr; rw [Nat.card_Ico, Nat.cast_sub (le_of_lt <| hr_lt_n i)] _ ≤ n ^ (p a b) * n * (c₂ * g n / n ^ ((p a b) + 1)) := by gcongr; simp only [tsub_le_iff_right, le_add_iff_nonneg_right, Nat.cast_nonneg] _ = c₂ * (n^((p a b) + 1) / n ^ ((p a b) + 1)) * g n := by rw [← Real.rpow_add_one (by positivity) (p a b)]; ring _ = c₂ * g n := by rw [div_self (by positivity), mul_one] _ ≤ max c₂ (c₂ / c₁ ^ ((p a b) + 1)) * g n := by gcongr; exact le_max_left _ _ lemma eventually_atTop_sumTransform_ge : ∃ c > 0, ∀ᶠ (n : ℕ) in atTop, ∀ i, c * g n ≤ sumTransform (p a b) g (r i n) n := by obtain ⟨c₁, hc₁_mem, hc₁⟩ := R.exists_eventually_const_mul_le_r obtain ⟨c₂, hc₂_mem, hc₂⟩ := R.g_grows_poly.eventually_atTop_ge_nat hc₁_mem obtain ⟨c₃, hc₃_mem, hc₃⟩ := R.exists_eventually_r_le_const_mul have hc₁_pos : 0 < c₁ := hc₁_mem.1 have hc₃' : 0 < (1 - c₃) := by have := hc₃_mem.2; linarith refine ⟨min (c₂ * (1 - c₃)) ((1 - c₃) * c₂ / c₁^((p a b) + 1)), by positivity, ?_⟩ filter_upwards [hc₁, hc₂, hc₃, R.eventually_r_pos, R.eventually_r_lt_n, eventually_gt_atTop 0] with n hn₁ hn₂ hn₃ hrpos hr_lt_n hn_pos intro i have hrpos_i := hrpos i have g_nonneg : 0 ≤ g n := R.g_nonneg n (by positivity) cases le_or_gt 0 (p a b + 1) with | inl hp => -- 0 ≤ (p a b) + 1 calc sumTransform (p a b) g (r i n) n = n ^ (p a b) * (∑ u ∈ Finset.Ico (r i n) n, g u / u ^ ((p a b) + 1)) := rfl _ ≥ n ^ (p a b) * (∑ u ∈ Finset.Ico (r i n) n, c₂ * g n / u^((p a b) + 1)) := by gcongr with u hu rw [Finset.mem_Ico] at hu have hu' : u ∈ Set.Icc (r i n) n := ⟨hu.1, by omega⟩ refine hn₂ u ?_ rw [Set.mem_Icc] refine ⟨?_, by norm_cast; omega⟩ calc c₁ * n ≤ r i n := by exact hn₁ i _ ≤ u := by exact_mod_cast hu'.1 _ ≥ n ^ (p a b) * (∑ _u ∈ Finset.Ico (r i n) n, c₂ * g n / n ^ ((p a b) + 1)) := by gcongr with u hu · rw [Finset.mem_Ico] at hu have := calc 0 < r i n := hrpos_i _ ≤ u := hu.1 positivity · rw [Finset.mem_Ico] at hu exact le_of_lt hu.2 _ ≥ n ^ (p a b) * (Finset.Ico (r i n) n).card • (c₂ * g n / n ^ ((p a b) + 1)) := by gcongr; exact Finset.card_nsmul_le_sum _ _ _ (fun x _ => by rfl) _ = n ^ (p a b) * (Finset.Ico (r i n) n).card * (c₂ * g n / n ^ ((p a b) + 1)) := by rw [nsmul_eq_mul, mul_assoc] _ = n ^ (p a b) * (n - r i n) * (c₂ * g n / n ^ ((p a b) + 1)) := by congr; rw [Nat.card_Ico, Nat.cast_sub (le_of_lt <| hr_lt_n i)] _ ≥ n ^ (p a b) * (n - c₃ * n) * (c₂ * g n / n ^ ((p a b) + 1)) := by gcongr; exact hn₃ i _ = n ^ (p a b) * n * (1 - c₃) * (c₂ * g n / n ^ ((p a b) + 1)) := by ring _ = c₂ * (1 - c₃) * g n * (n ^ ((p a b) + 1) / n ^ ((p a b) + 1)) := by rw [← Real.rpow_add_one (by positivity) (p a b)]; ring _ = c₂ * (1 - c₃) * g n := by rw [div_self (by positivity), mul_one] _ ≥ min (c₂ * (1 - c₃)) ((1 - c₃) * c₂ / c₁ ^ ((p a b) + 1)) * g n := by gcongr; exact min_le_left _ _ | inr hp => -- (p a b) + 1 < 0 calc sumTransform (p a b) g (r i n) n = n ^ (p a b) * (∑ u ∈ Finset.Ico (r i n) n, g u / u^((p a b) + 1)) := by rfl _ ≥ n ^ (p a b) * (∑ u ∈ Finset.Ico (r i n) n, c₂ * g n / u ^ ((p a b) + 1)) := by gcongr with u hu rw [Finset.mem_Ico] at hu have hu' : u ∈ Set.Icc (r i n) n := ⟨hu.1, by omega⟩ refine hn₂ u ?_ rw [Set.mem_Icc] refine ⟨?_, by norm_cast; omega⟩ calc c₁ * n ≤ r i n := by exact hn₁ i _ ≤ u := by exact_mod_cast hu'.1 _ ≥ n ^ (p a b) * (∑ _u ∈ Finset.Ico (r i n) n, c₂ * g n / (r i n) ^ ((p a b) + 1)) := by gcongr n^(p a b) * (Finset.Ico (r i n) n).sum (fun _ => c₂ * g n / ?_) with u hu · rw [Finset.mem_Ico] at hu have := calc 0 < r i n := hrpos_i _ ≤ u := hu.1 positivity · rw [Finset.mem_Ico] at hu exact rpow_le_rpow_of_exponent_nonpos (by positivity) (by exact_mod_cast hu.1) (le_of_lt hp) _ ≥ n ^ (p a b) * (Finset.Ico (r i n) n).card • (c₂ * g n / (r i n) ^ ((p a b) + 1)) := by gcongr; exact Finset.card_nsmul_le_sum _ _ _ (fun x _ => by rfl) _ = n ^ (p a b) * (Finset.Ico (r i n) n).card * (c₂ * g n / (r i n) ^ ((p a b) + 1)) := by rw [nsmul_eq_mul, mul_assoc] _ ≥ n ^ (p a b) * (Finset.Ico (r i n) n).card * (c₂ * g n / (c₁ * n) ^ ((p a b) + 1)) := by gcongr n^(p a b) * (Finset.Ico (r i n) n).card * (c₂ * g n / ?_) exact rpow_le_rpow_of_exponent_nonpos (by positivity) (hn₁ i) (le_of_lt hp) _ = n ^ (p a b) * (n - r i n) * (c₂ * g n / (c₁ * n) ^ ((p a b) + 1)) := by congr; rw [Nat.card_Ico, Nat.cast_sub (le_of_lt <| hr_lt_n i)] _ ≥ n ^ (p a b) * (n - c₃ * n) * (c₂ * g n / (c₁ * n) ^ ((p a b) + 1)) := by gcongr; exact hn₃ i _ = n ^ (p a b) * n * (1 - c₃) * (c₂ * g n / (c₁ * n) ^ ((p a b) + 1)) := by ring _ = n ^ (p a b) * n * (1 - c₃) * (c₂ * g n / (c₁ ^ ((p a b) + 1) * n ^ ((p a b) + 1))) := by rw [Real.mul_rpow (by positivity) (by positivity)] _ = (n ^ ((p a b) + 1) / n ^ ((p a b) + 1)) * (1 - c₃) * c₂ * g n / c₁ ^ ((p a b) + 1) := by rw [← Real.rpow_add_one (by positivity) (p a b)]; ring _ = (1 - c₃) * c₂ / c₁ ^ ((p a b) + 1) * g n := by rw [div_self (by positivity), one_mul]; ring _ ≥ min (c₂ * (1 - c₃)) ((1 - c₃) * c₂ / c₁ ^ ((p a b) + 1)) * g n := by gcongr; exact min_le_right _ _ /-! #### Technical lemmas The next several lemmas are technical lemmas leading up to `rpow_p_mul_one_sub_smoothingFn_le` and `rpow_p_mul_one_add_smoothingFn_ge`, which are key steps in the main proof. -/ lemma isBigO_apply_r_sub_b (q : ℝ → ℝ) (hq_diff : DifferentiableOn ℝ q (Set.Ioi 1)) (hq_poly : GrowsPolynomially fun x => ‖deriv q x‖) (i : α) : (fun n => q (r i n) - q (b i * n)) =O[atTop] fun n => (deriv q n) * (r i n - b i * n) := by let b' := b (min_bi b) / 2 have hb_pos : 0 < b' := by have := R.b_pos (min_bi b); positivity have hb_lt_one : b' < 1 := calc b (min_bi b) / 2 < b (min_bi b) := by exact div_two_lt_of_pos (R.b_pos (min_bi b)) _ < 1 := R.b_lt_one (min_bi b) have hb : b' ∈ Set.Ioo 0 1 := ⟨hb_pos, hb_lt_one⟩ have hb' : ∀ i, b' ≤ b i := fun i => calc b (min_bi b) / 2 ≤ b i / 2 := by gcongr; aesop _ ≤ b i := by exact le_of_lt <| div_two_lt_of_pos (R.b_pos i) obtain ⟨c₁, _, c₂, _, hq_poly⟩ := hq_poly b' hb rw [isBigO_iff] refine ⟨c₂, ?_⟩ have h_tendsto : Tendsto (fun x => b' * x) atTop atTop := Tendsto.const_mul_atTop hb_pos tendsto_id filter_upwards [hq_poly.natCast_atTop, R.eventually_bi_mul_le_r, eventually_ge_atTop R.n₀, eventually_gt_atTop 0, (h_tendsto.eventually_gt_atTop 1).natCast_atTop] with n hn h_bi_le_r h_ge_n₀ h_n_pos h_bn rw [norm_mul, ← mul_assoc] refine Convex.norm_image_sub_le_of_norm_deriv_le (s := Set.Icc (b'*n) n) (fun z hz => ?diff) (fun z hz => (hn z hz).2) (convex_Icc _ _) ?mem_Icc <| ⟨h_bi_le_r i, by exact_mod_cast (le_of_lt (R.r_lt_n i n h_ge_n₀))⟩ case diff => refine hq_diff.differentiableAt (Ioi_mem_nhds ?_) calc 1 < b' * n := by exact h_bn _ ≤ z := hz.1 case mem_Icc => refine ⟨by gcongr; exact hb' i, ?_⟩ calc b i * n ≤ 1 * n := by gcongr; exact le_of_lt <| R.b_lt_one i _ = n := by simp lemma eventually_deriv_rpow_p_mul_one_sub_smoothingFn (p : ℝ) : deriv (fun z => z ^ p * (1 - ε z)) =ᶠ[atTop] fun z => p * z ^ (p-1) * (1 - ε z) + z ^ (p-1) / (log z ^ 2) := calc deriv (fun x => x ^ p * (1 - ε x)) =ᶠ[atTop] fun x => deriv (· ^ p) x * (1 - ε x) + x ^ p * deriv (1 - ε ·) x := by filter_upwards [eventually_gt_atTop 1] with x hx rw [deriv_mul] · exact differentiableAt_rpow_const_of_ne _ (by positivity) · exact differentiableAt_one_sub_smoothingFn hx _ =ᶠ[atTop] fun x => p * x ^ (p-1) * (1 - ε x) + x ^ p * (x⁻¹ / (log x ^ 2)) := by filter_upwards [eventually_gt_atTop 1, eventually_deriv_one_sub_smoothingFn] with x hx hderiv rw [hderiv, Real.deriv_rpow_const (Or.inl <| by positivity)] _ =ᶠ[atTop] fun x => p * x ^ (p-1) * (1 - ε x) + x ^ (p-1) / (log x ^ 2) := by filter_upwards [eventually_gt_atTop 0] with x hx rw [mul_div, ← Real.rpow_neg_one, ← Real.rpow_add (by positivity), sub_eq_add_neg] lemma eventually_deriv_rpow_p_mul_one_add_smoothingFn (p : ℝ) : deriv (fun z => z ^ p * (1 + ε z)) =ᶠ[atTop] fun z => p * z ^ (p-1) * (1 + ε z) - z ^ (p-1) / (log z ^ 2) := calc deriv (fun x => x ^ p * (1 + ε x)) =ᶠ[atTop] fun x => deriv (· ^ p) x * (1 + ε x) + x ^ p * deriv (1 + ε ·) x := by filter_upwards [eventually_gt_atTop 1] with x hx rw [deriv_mul] · exact differentiableAt_rpow_const_of_ne _ (by positivity) · exact differentiableAt_one_add_smoothingFn hx _ =ᶠ[atTop] fun x => p * x ^ (p-1) * (1 + ε x) - x ^ p * (x⁻¹ / (log x ^ 2)) := by filter_upwards [eventually_gt_atTop 1, eventually_deriv_one_add_smoothingFn] with x hx hderiv simp [hderiv, Real.deriv_rpow_const (Or.inl <| by positivity), neg_div, sub_eq_add_neg] _ =ᶠ[atTop] fun x => p * x ^ (p-1) * (1 + ε x) - x ^ (p-1) / (log x ^ 2) := by filter_upwards [eventually_gt_atTop 0] with x hx simp [mul_div, ← Real.rpow_neg_one, ← Real.rpow_add (by positivity), sub_eq_add_neg] lemma isEquivalent_deriv_rpow_p_mul_one_sub_smoothingFn {p : ℝ} (hp : p ≠ 0) : deriv (fun z => z ^ p * (1 - ε z)) ~[atTop] fun z => p * z ^ (p-1) := calc deriv (fun z => z ^ p * (1 - ε z)) =ᶠ[atTop] fun z => p * z ^ (p-1) * (1 - ε z) + z^(p-1) / (log z ^ 2) := eventually_deriv_rpow_p_mul_one_sub_smoothingFn p _ ~[atTop] fun z => p * z ^ (p-1) := by refine IsEquivalent.add_isLittleO ?one ?two case one => calc (fun z => p * z ^ (p-1) * (1 - ε z)) ~[atTop] fun z => p * z ^ (p-1) * 1 := IsEquivalent.mul IsEquivalent.refl isEquivalent_one_sub_smoothingFn_one _ = fun z => p * z ^ (p-1) := by ext; ring case two => calc (fun z => z ^ (p-1) / (log z ^ 2)) =o[atTop] fun z => z ^ (p-1) / 1 := by simp_rw [div_eq_mul_inv] refine IsBigO.mul_isLittleO (isBigO_refl _ _) (IsLittleO.inv_rev ?_ (by aesop (add safe eventually_of_forall))) rw [isLittleO_const_left] refine Or.inr <| Tendsto.comp tendsto_norm_atTop_atTop ?_ exact Tendsto.comp (g := fun z => z ^ 2) (tendsto_pow_atTop (by norm_num)) tendsto_log_atTop _ = fun z => z ^ (p-1) := by ext; simp _ =Θ[atTop] fun z => p * z ^ (p-1) := by exact IsTheta.const_mul_right hp <| isTheta_refl _ _ lemma isEquivalent_deriv_rpow_p_mul_one_add_smoothingFn {p : ℝ} (hp : p ≠ 0) : deriv (fun z => z ^ p * (1 + ε z)) ~[atTop] fun z => p * z ^ (p-1) := calc deriv (fun z => z ^ p * (1 + ε z)) =ᶠ[atTop] fun z => p * z ^ (p-1) * (1 + ε z) - z ^ (p-1) / (log z ^ 2) := eventually_deriv_rpow_p_mul_one_add_smoothingFn p _ ~[atTop] fun z => p * z ^ (p-1) := by refine IsEquivalent.add_isLittleO ?one ?two case one => calc (fun z => p * z ^ (p-1) * (1 + ε z)) ~[atTop] fun z => p * z ^ (p-1) * 1 := IsEquivalent.mul IsEquivalent.refl isEquivalent_one_add_smoothingFn_one _ = fun z => p * z ^ (p-1) := by ext; ring case two => calc (fun z => -(z ^ (p-1) / (log z ^ 2))) =o[atTop] fun z => z ^ (p-1) / 1 := by simp_rw [isLittleO_neg_left, div_eq_mul_inv] refine IsBigO.mul_isLittleO (isBigO_refl _ _) (IsLittleO.inv_rev ?_ (by aesop (add safe eventually_of_forall))) rw [isLittleO_const_left] refine Or.inr <| Tendsto.comp tendsto_norm_atTop_atTop ?_ exact Tendsto.comp (g := fun z => z ^ 2) (tendsto_pow_atTop (by norm_num)) tendsto_log_atTop _ = fun z => z ^ (p-1) := by ext; simp _ =Θ[atTop] fun z => p * z ^ (p-1) := by exact IsTheta.const_mul_right hp <| isTheta_refl _ _ lemma isTheta_deriv_rpow_p_mul_one_sub_smoothingFn {p : ℝ} (hp : p ≠ 0) : (fun x => ‖deriv (fun z => z ^ p * (1 - ε z)) x‖) =Θ[atTop] fun z => z ^ (p-1) := by refine IsTheta.norm_left ?_ calc (fun x => deriv (fun z => z ^ p * (1 - ε z)) x) =Θ[atTop] fun z => p * z ^ (p-1) := (isEquivalent_deriv_rpow_p_mul_one_sub_smoothingFn hp).isTheta _ =Θ[atTop] fun z => z ^ (p-1) := IsTheta.const_mul_left hp <| isTheta_refl _ _ lemma isTheta_deriv_rpow_p_mul_one_add_smoothingFn {p : ℝ} (hp : p ≠ 0) : (fun x => ‖deriv (fun z => z ^ p * (1 + ε z)) x‖) =Θ[atTop] fun z => z ^ (p-1) := by refine IsTheta.norm_left ?_ calc (fun x => deriv (fun z => z ^ p * (1 + ε z)) x) =Θ[atTop] fun z => p * z ^ (p-1) := (isEquivalent_deriv_rpow_p_mul_one_add_smoothingFn hp).isTheta _ =Θ[atTop] fun z => z ^ (p-1) := IsTheta.const_mul_left hp <| isTheta_refl _ _ lemma growsPolynomially_deriv_rpow_p_mul_one_sub_smoothingFn (p : ℝ) : GrowsPolynomially fun x => ‖deriv (fun z => z ^ p * (1 - ε z)) x‖ := by cases eq_or_ne p 0 with | inl hp => -- p = 0 have h₁ : (fun x => ‖deriv (fun z => z ^ p * (1 - ε z)) x‖) =ᶠ[atTop] fun z => z⁻¹ / (log z ^ 2) := by filter_upwards [eventually_deriv_one_sub_smoothingFn, eventually_gt_atTop 1] with x hx hx_pos have : 0 ≤ x⁻¹ / (log x ^ 2) := by have hlog : 0 < log x := Real.log_pos hx_pos positivity simp only [hp, Real.rpow_zero, one_mul, differentiableAt_const, hx, Real.norm_of_nonneg this] refine GrowsPolynomially.congr_of_eventuallyEq h₁ ?_ refine GrowsPolynomially.div (GrowsPolynomially.inv growsPolynomially_id) (GrowsPolynomially.pow 2 growsPolynomially_log ?_) filter_upwards [eventually_ge_atTop 1] with _ hx exact log_nonneg hx | inr hp => -- p ≠ 0 refine GrowsPolynomially.of_isTheta (growsPolynomially_rpow (p-1)) (isTheta_deriv_rpow_p_mul_one_sub_smoothingFn hp) ?_ filter_upwards [eventually_gt_atTop 0] with _ _ positivity lemma growsPolynomially_deriv_rpow_p_mul_one_add_smoothingFn (p : ℝ) : GrowsPolynomially fun x => ‖deriv (fun z => z ^ p * (1 + ε z)) x‖ := by cases eq_or_ne p 0 with | inl hp => -- p = 0 have h₁ : (fun x => ‖deriv (fun z => z ^ p * (1 + ε z)) x‖) =ᶠ[atTop] fun z => z⁻¹ / (log z ^ 2) := by filter_upwards [eventually_deriv_one_add_smoothingFn, eventually_gt_atTop 1] with x hx hx_pos have : 0 ≤ x⁻¹ / (log x ^ 2) := by have hlog : 0 < log x := Real.log_pos hx_pos positivity simp only [neg_div, norm_neg, hp, Real.rpow_zero, one_mul, differentiableAt_const, hx, Real.norm_of_nonneg this] refine GrowsPolynomially.congr_of_eventuallyEq h₁ ?_ refine GrowsPolynomially.div (GrowsPolynomially.inv growsPolynomially_id) (GrowsPolynomially.pow 2 growsPolynomially_log ?_) filter_upwards [eventually_ge_atTop 1] with x hx exact log_nonneg hx | inr hp => -- p ≠ 0 refine GrowsPolynomially.of_isTheta (growsPolynomially_rpow (p-1)) (isTheta_deriv_rpow_p_mul_one_add_smoothingFn hp) ?_ filter_upwards [eventually_gt_atTop 0] with _ _ positivity lemma rpow_p_mul_one_sub_smoothingFn_le : ∀ᶠ (n : ℕ) in atTop, ∀ i, (r i n) ^ (p a b) * (1 - ε (r i n)) ≤ (b i) ^ (p a b) * n ^ (p a b) * (1 - ε n) := by rw [Filter.eventually_all] intro i let q : ℝ → ℝ := fun x => x ^ (p a b) * (1 - ε x) have h_diff_q : DifferentiableOn ℝ q (Set.Ioi 1) := by refine DifferentiableOn.mul (DifferentiableOn.mono (differentiableOn_rpow_const _) fun z hz => ?_) differentiableOn_one_sub_smoothingFn rw [Set.mem_compl_singleton_iff] rw [Set.mem_Ioi] at hz exact ne_of_gt <| zero_lt_one.trans hz have h_deriv_q : deriv q =O[atTop] fun x => x ^ ((p a b) - 1) := calc deriv q = deriv fun x => (fun z => z ^ (p a b)) x * (fun z => 1 - ε z) x := by rfl _ =ᶠ[atTop] fun x => deriv (fun z => z ^ (p a b)) x * (1 - ε x) + x ^ (p a b) * deriv (fun z => 1 - ε z) x := by filter_upwards [eventually_ne_atTop 0, eventually_gt_atTop 1] with x hx hx' rw [deriv_mul] <;> aesop _ =O[atTop] fun x => x ^ ((p a b) - 1) := by refine IsBigO.add ?left ?right case left => calc (fun x => deriv (fun z => z ^ (p a b)) x * (1 - ε x)) =O[atTop] fun x => x ^ ((p a b) - 1) * (1 - ε x) := by exact IsBigO.mul (isBigO_deriv_rpow_const_atTop (p a b)) (isBigO_refl _ _) _ =O[atTop] fun x => x ^ ((p a b) - 1) * 1 := by refine IsBigO.mul (isBigO_refl _ _) isEquivalent_one_sub_smoothingFn_one.isBigO _ = fun x => x ^ ((p a b) - 1) := by ext; rw [mul_one] case right => calc (fun x => x ^ (p a b) * deriv (fun z => 1 - ε z) x) =O[atTop] (fun x => x ^ (p a b) * x⁻¹) := by exact IsBigO.mul (isBigO_refl _ _) isLittleO_deriv_one_sub_smoothingFn.isBigO _ =ᶠ[atTop] fun x => x ^ ((p a b) - 1) := by filter_upwards [eventually_gt_atTop 0] with x hx rw [← Real.rpow_neg_one, ← Real.rpow_add hx, ← sub_eq_add_neg] have h_main_norm : (fun (n : ℕ) => ‖q (r i n) - q (b i * n)‖) ≤ᶠ[atTop] fun (n : ℕ) => ‖(b i) ^ (p a b) * n ^ (p a b) * (ε (b i * n) - ε n)‖ := by refine IsLittleO.eventuallyLE ?_ calc (fun (n : ℕ) => q (r i n) - q (b i * n)) =O[atTop] fun n => (deriv q n) * (r i n - b i * n) := by exact R.isBigO_apply_r_sub_b q h_diff_q (growsPolynomially_deriv_rpow_p_mul_one_sub_smoothingFn (p a b)) i _ =o[atTop] fun n => (deriv q n) * (n / log n ^ 2) := by exact IsBigO.mul_isLittleO (isBigO_refl _ _) (R.dist_r_b i) _ =O[atTop] fun n => n^((p a b) - 1) * (n / log n ^ 2) := by exact IsBigO.mul (IsBigO.natCast_atTop h_deriv_q) (isBigO_refl _ _) _ =ᶠ[atTop] fun n => n^(p a b) / (log n) ^ 2 := by filter_upwards [eventually_ne_atTop 0] with n hn have hn' : (n : ℝ) ≠ 0 := by positivity simp [← mul_div_assoc, ← Real.rpow_add_one hn'] _ = fun (n : ℕ) => (n : ℝ) ^ (p a b) * (1 / (log n)^2) := by simp_rw [mul_div, mul_one] _ =Θ[atTop] fun (n : ℕ) => (b i) ^ (p a b) * n ^ (p a b) * (1 / (log n)^2) := by refine IsTheta.symm ?_ simp_rw [mul_assoc] refine IsTheta.const_mul_left ?_ (isTheta_refl _ _) have := R.b_pos i; positivity _ =Θ[atTop] fun (n : ℕ) => (b i)^(p a b) * n^(p a b) * (ε (b i * n) - ε n) := by exact IsTheta.symm <| IsTheta.mul (isTheta_refl _ _) <| R.isTheta_smoothingFn_sub_self i have h_main : (fun (n : ℕ) => q (r i n) - q (b i * n)) ≤ᶠ[atTop] fun (n : ℕ) => (b i) ^ (p a b) * n ^ (p a b) * (ε (b i * n) - ε n) := by calc (fun (n : ℕ) => q (r i n) - q (b i * n)) ≤ᶠ[atTop] fun (n : ℕ) => ‖q (r i n) - q (b i * n)‖ := by filter_upwards with _; exact le_norm_self _ _ ≤ᶠ[atTop] fun (n : ℕ) => ‖(b i) ^ (p a b) * n ^ (p a b) * (ε (b i * n) - ε n)‖ := h_main_norm _ =ᶠ[atTop] fun (n : ℕ) => (b i) ^ (p a b) * n ^ (p a b) * (ε (b i * n) - ε n) := by filter_upwards [eventually_gt_atTop ⌈(b i)⁻¹⌉₊, eventually_gt_atTop 1] with n hn hn' refine norm_of_nonneg ?_ have h₁ := R.b_pos i have h₂ : 0 ≤ ε (b i * n) - ε n := by refine sub_nonneg_of_le <| (strictAntiOn_smoothingFn.le_iff_le ?n_gt_one ?bn_gt_one).mpr ?le case n_gt_one => rwa [Set.mem_Ioi, Nat.one_lt_cast] case bn_gt_one => calc 1 = b i * (b i)⁻¹ := by rw [mul_inv_cancel (by positivity)] _ ≤ b i * ⌈(b i)⁻¹⌉₊ := by gcongr; exact Nat.le_ceil _ _ < b i * n := by gcongr; rw [Nat.cast_lt]; exact hn case le => calc b i * n ≤ 1 * n := by have := R.b_lt_one i; gcongr _ = n := by rw [one_mul] positivity filter_upwards [h_main] with n hn have h₁ : q (b i * n) + (b i) ^ (p a b) * n ^ (p a b) * (ε (b i * n) - ε n) = (b i) ^ (p a b) * n ^ (p a b) * (1 - ε n) := by have := R.b_pos i simp only [q, mul_rpow (by positivity : (0 : ℝ) ≤ b i) (by positivity : (0 : ℝ) ≤ n)] ring show q (r i n) ≤ (b i) ^ (p a b) * n ^ (p a b) * (1 - ε n) rw [← h₁, ← sub_le_iff_le_add'] exact hn lemma rpow_p_mul_one_add_smoothingFn_ge : ∀ᶠ (n : ℕ) in atTop, ∀ i, (b i) ^ (p a b) * n ^ (p a b) * (1 + ε n) ≤ (r i n) ^ (p a b) * (1 + ε (r i n)) := by rw [Filter.eventually_all] intro i let q : ℝ → ℝ := fun x => x ^ (p a b) * (1 + ε x) have h_diff_q : DifferentiableOn ℝ q (Set.Ioi 1) := by refine DifferentiableOn.mul (DifferentiableOn.mono (differentiableOn_rpow_const _) fun z hz => ?_) differentiableOn_one_add_smoothingFn rw [Set.mem_compl_singleton_iff] rw [Set.mem_Ioi] at hz exact ne_of_gt <| zero_lt_one.trans hz have h_deriv_q : deriv q =O[atTop] fun x => x ^ ((p a b) - 1) := calc deriv q = deriv fun x => (fun z => z ^ (p a b)) x * (fun z => 1 + ε z) x := by rfl _ =ᶠ[atTop] fun x => deriv (fun z => z ^ (p a b)) x * (1 + ε x) + x ^ (p a b) * deriv (fun z => 1 + ε z) x := by filter_upwards [eventually_ne_atTop 0, eventually_gt_atTop 1] with x hx hx' rw [deriv_mul] <;> aesop _ =O[atTop] fun x => x ^ ((p a b) - 1) := by refine IsBigO.add ?left ?right case left => calc (fun x => deriv (fun z => z ^ (p a b)) x * (1 + ε x)) =O[atTop] fun x => x ^ ((p a b) - 1) * (1 + ε x) := by exact IsBigO.mul (isBigO_deriv_rpow_const_atTop (p a b)) (isBigO_refl _ _) _ =O[atTop] fun x => x ^ ((p a b) - 1) * 1 := IsBigO.mul (isBigO_refl _ _) isEquivalent_one_add_smoothingFn_one.isBigO _ = fun x => x ^ ((p a b) - 1) := by ext; rw [mul_one] case right => calc (fun x => x ^ (p a b) * deriv (fun z => 1 + ε z) x) =O[atTop] (fun x => x ^ (p a b) * x⁻¹) := by exact IsBigO.mul (isBigO_refl _ _) isLittleO_deriv_one_add_smoothingFn.isBigO _ =ᶠ[atTop] fun x => x ^ ((p a b) - 1) := by filter_upwards [eventually_gt_atTop 0] with x hx rw [← Real.rpow_neg_one, ← Real.rpow_add hx, ← sub_eq_add_neg] have h_main_norm : (fun (n : ℕ) => ‖q (r i n) - q (b i * n)‖) ≤ᶠ[atTop] fun (n : ℕ) => ‖(b i) ^ (p a b) * n ^ (p a b) * (ε (b i * n) - ε n)‖ := by refine IsLittleO.eventuallyLE ?_ calc (fun (n : ℕ) => q (r i n) - q (b i * n)) =O[atTop] fun n => (deriv q n) * (r i n - b i * n) := by exact R.isBigO_apply_r_sub_b q h_diff_q (growsPolynomially_deriv_rpow_p_mul_one_add_smoothingFn (p a b)) i _ =o[atTop] fun n => (deriv q n) * (n / log n ^ 2) := by exact IsBigO.mul_isLittleO (isBigO_refl _ _) (R.dist_r_b i) _ =O[atTop] fun n => n ^ ((p a b) - 1) * (n / log n ^ 2) := by exact IsBigO.mul (IsBigO.natCast_atTop h_deriv_q) (isBigO_refl _ _) _ =ᶠ[atTop] fun n => n ^ (p a b) / (log n) ^ 2 := by filter_upwards [eventually_ne_atTop 0] with n hn have hn' : (n : ℝ) ≠ 0 := by positivity simp [← mul_div_assoc, ← Real.rpow_add_one hn'] _ = fun (n : ℕ) => (n : ℝ) ^ (p a b) * (1 / (log n) ^ 2) := by simp_rw [mul_div, mul_one] _ =Θ[atTop] fun (n : ℕ) => (b i) ^ (p a b) * n ^ (p a b) * (1 / (log n) ^ 2) := by refine IsTheta.symm ?_ simp_rw [mul_assoc] refine IsTheta.const_mul_left ?_ (isTheta_refl _ _) have := R.b_pos i; positivity _ =Θ[atTop] fun (n : ℕ) => (b i) ^ (p a b) * n ^ (p a b) * (ε (b i * n) - ε n) := by exact IsTheta.symm <| IsTheta.mul (isTheta_refl _ _) <| R.isTheta_smoothingFn_sub_self i have h_main : (fun (n : ℕ) => q (b i * n) - q (r i n)) ≤ᶠ[atTop] fun (n : ℕ) => (b i) ^ (p a b) * n ^ (p a b) * (ε (b i * n) - ε n) := by calc (fun (n : ℕ) => q (b i * n) - q (r i n)) ≤ᶠ[atTop] fun (n : ℕ) => ‖q (r i n) - q (b i * n)‖ := by filter_upwards with _; rw [norm_sub_rev]; exact le_norm_self _ _ ≤ᶠ[atTop] fun (n : ℕ) => ‖(b i) ^ (p a b) * n ^ (p a b) * (ε (b i * n) - ε n)‖ := h_main_norm _ =ᶠ[atTop] fun (n : ℕ) => (b i) ^ (p a b) * n ^ (p a b) * (ε (b i * n) - ε n) := by filter_upwards [eventually_gt_atTop ⌈(b i)⁻¹⌉₊, eventually_gt_atTop 1] with n hn hn' refine norm_of_nonneg ?_ have h₁ := R.b_pos i have h₂ : 0 ≤ ε (b i * n) - ε n := by refine sub_nonneg_of_le <| (strictAntiOn_smoothingFn.le_iff_le ?n_gt_one ?bn_gt_one).mpr ?le case n_gt_one => show 1 < (n : ℝ) rw [Nat.one_lt_cast] exact hn' case bn_gt_one => calc 1 = b i * (b i)⁻¹ := by rw [mul_inv_cancel (by positivity)] _ ≤ b i * ⌈(b i)⁻¹⌉₊ := by gcongr; exact Nat.le_ceil _ _ < b i * n := by gcongr; rw [Nat.cast_lt]; exact hn case le => calc b i * n ≤ 1 * n := by have := R.b_lt_one i; gcongr _ = n := by rw [one_mul] positivity filter_upwards [h_main] with n hn have h₁ : q (b i * n) - (b i) ^ (p a b) * n ^ (p a b) * (ε (b i * n) - ε n) = (b i) ^ (p a b) * n ^ (p a b) * (1 + ε n) := by have := R.b_pos i simp only [q, mul_rpow (by positivity : (0 : ℝ) ≤ b i) (by positivity : (0 : ℝ) ≤ n)] ring show (b i) ^ (p a b) * n ^ (p a b) * (1 + ε n) ≤ q (r i n) rw [← h₁, sub_le_iff_le_add', ← sub_le_iff_le_add] exact hn /-! #### Main proof This final section proves the Akra-Bazzi theorem. -/ lemma base_nonempty {n : ℕ} (hn : 0 < n) : (Finset.Ico (⌊b (min_bi b) / 2 * n⌋₊) n).Nonempty := by let b' := b (min_bi b) have hb_pos : 0 < b' := R.b_pos _ simp_rw [Finset.nonempty_Ico] exact_mod_cast calc ⌊b' / 2 * n⌋₊ ≤ b' / 2 * n := by exact Nat.floor_le (by positivity) _ < 1 / 2 * n := by gcongr; exact R.b_lt_one (min_bi b) _ ≤ 1 * n := by gcongr; norm_num _ = n := by simp /-- The main proof of the upper bound part of the Akra-Bazzi theorem. The factor `1 - ε n` does not change the asymptotic order, but is needed for the induction step to go through. -/ lemma T_isBigO_smoothingFn_mul_asympBound : T =O[atTop] (fun n => (1 - ε n) * asympBound g a b n) := by let b' := b (min_bi b) / 2 have hb_pos : 0 < b' := R.bi_min_div_two_pos rw [isBigO_atTop_iff_eventually_exists] obtain ⟨c₁, hc₁, h_sumTransform_aux⟩ := R.eventually_atTop_sumTransform_ge filter_upwards [eventually_ge_atTop R.n₀, -- n₀_ge_Rn₀ eventually_forall_ge_atTop.mpr eventually_one_sub_smoothingFn_pos, -- h_smoothing_pos eventually_forall_ge_atTop.mpr <| eventually_one_sub_smoothingFn_gt_const (1/2) (by norm_num), -- h_smoothing_gt_half eventually_forall_ge_atTop.mpr R.eventually_asympBound_pos, -- h_asympBound_pos eventually_forall_ge_atTop.mpr R.eventually_asympBound_r_pos, -- h_asympBound_r_pos (tendsto_nat_floor_mul_atTop b' hb_pos).eventually_forall_ge_atTop R.eventually_asympBound_pos, -- h_asympBound_floor eventually_gt_atTop 0, -- n₀_pos eventually_forall_ge_atTop.mpr R.eventually_one_sub_smoothingFn_r_pos, -- h_smoothing_r_pos eventually_forall_ge_atTop.mpr R.rpow_p_mul_one_sub_smoothingFn_le, -- bound1 (tendsto_nat_floor_mul_atTop b' hb_pos).eventually_forall_ge_atTop eventually_one_sub_smoothingFn_pos, -- h_smoothingFn_floor eventually_forall_ge_atTop.mpr h_sumTransform_aux, -- h_sumTransform eventually_forall_ge_atTop.mpr R.eventually_bi_mul_le_r] -- h_bi_le_r with n₀ n₀_ge_Rn₀ h_smoothing_pos h_smoothing_gt_half h_asympBound_pos h_asympBound_r_pos h_asympBound_floor n₀_pos h_smoothing_r_pos bound1 h_smoothingFn_floor h_sumTransform h_bi_le_r -- Max of the ratio `T(n) / asympBound(n)` over the base case `n ∈ [b * n₀, n₀)` have h_base_nonempty := R.base_nonempty n₀_pos let base_max : ℝ := (Finset.Ico (⌊b' * n₀⌋₊) n₀).sup' h_base_nonempty fun n => T n / ((1 - ε n) * asympBound g a b n) -- The big-O constant we are aiming for: max of the base case ratio and what we need to -- cancel out the `g(n)` term in the calculation below set C := max (2 * c₁⁻¹) base_max with hC refine ⟨C, fun n hn => ?_⟩ -- Base case: statement is true for `b' * n₀ ≤ n < n₀` have h_base : ∀ n ∈ Finset.Ico (⌊b' * n₀⌋₊) n₀, T n ≤ C * ((1 - ε n) * asympBound g a b n) := by intro n hn rw [Finset.mem_Ico] at hn have htmp1 : 0 < 1 - ε n := h_smoothingFn_floor n hn.1 have htmp2 : 0 < asympBound g a b n := h_asympBound_floor n hn.1 rw [← _root_.div_le_iff (by positivity)] rw [← Finset.mem_Ico] at hn calc T n / ((1 - ε ↑n) * asympBound g a b n) ≤ (Finset.Ico (⌊b' * n₀⌋₊) n₀).sup' h_base_nonempty (fun z => T z / ((1 - ε z) * asympBound g a b z)) := Finset.le_sup'_of_le _ (b := n) hn le_rfl _ ≤ C := le_max_right _ _ have h_asympBound_pos' : 0 < asympBound g a b n := h_asympBound_pos n hn have h_one_sub_smoothingFn_pos' : 0 < 1 - ε n := h_smoothing_pos n hn rw [Real.norm_of_nonneg (R.T_nonneg n), Real.norm_of_nonneg (by positivity)] -- We now prove all other cases by induction induction n using Nat.strongInductionOn with | ind n h_ind => have b_mul_n₀_le_ri i : ⌊b' * ↑n₀⌋₊ ≤ r i n := by exact_mod_cast calc ⌊b' * (n₀ : ℝ)⌋₊ ≤ b' * n₀ := Nat.floor_le <| by positivity _ ≤ b' * n := by gcongr _ ≤ r i n := h_bi_le_r n hn i have g_pos : 0 ≤ g n := R.g_nonneg n (by positivity) calc T n = (∑ i, a i * T (r i n)) + g n := by exact R.h_rec n <| n₀_ge_Rn₀.trans hn _ ≤ (∑ i, a i * (C * ((1 - ε (r i n)) * asympBound g a b (r i n)))) + g n := by -- Apply the induction hypothesis, or use the base case depending on how large n is gcongr (∑ i, a i * ?_) + g n with i _ · exact le_of_lt <| R.a_pos _ · if ri_lt_n₀ : r i n < n₀ then exact h_base _ <| by simp_all only [gt_iff_lt, Nat.ofNat_pos, div_pos_iff_of_pos_right, eventually_atTop, sub_pos, one_div, mem_Ico, and_imp, forall_true_left, mem_univ, and_self, b', C, base_max] else push_neg at ri_lt_n₀ exact h_ind (r i n) (R.r_lt_n _ _ (n₀_ge_Rn₀.trans hn)) ri_lt_n₀ (h_asympBound_r_pos _ hn _) (h_smoothing_r_pos n hn i) _ = (∑ i, a i * (C * ((1 - ε (r i n)) * ((r i n) ^ (p a b) * (1 + (∑ u ∈ range (r i n), g u / u ^ ((p a b) + 1))))))) + g n := by simp_rw [asympBound_def'] _ = (∑ i, C * a i * ((r i n) ^ (p a b) * (1 - ε (r i n)) * ((1 + (∑ u ∈ range (r i n), g u / u ^ ((p a b) + 1)))))) + g n := by congr; ext; ring _ ≤ (∑ i, C * a i * ((b i) ^ (p a b) * n ^ (p a b) * (1 - ε n) * ((1 + (∑ u ∈ range (r i n), g u / u ^ ((p a b) + 1)))))) + g n := by gcongr (∑ i, C * a i * (?_ * ((1 + (∑ u ∈ range (r i n), g u / u ^ ((p a b) + 1)))))) + g n with i · have := R.a_pos i positivity · refine add_nonneg zero_le_one <| Finset.sum_nonneg fun j _ => ?_ rw [div_nonneg_iff] exact Or.inl ⟨R.g_nonneg j (by positivity), by positivity⟩ · exact bound1 n hn i _ = (∑ i, C * a i * ((b i) ^ (p a b) * n ^ (p a b) * (1 - ε n) * ((1 + ((∑ u ∈ range n, g u / u ^ ((p a b) + 1)) - (∑ u ∈ Finset.Ico (r i n) n, g u / u ^ ((p a b) + 1))))))) + g n := by congr; ext i; congr refine eq_sub_of_add_eq ?_ rw [add_comm] exact add_eq_of_eq_sub <| Finset.sum_Ico_eq_sub _ <| le_of_lt <| R.r_lt_n i n <| n₀_ge_Rn₀.trans hn _ = (∑ i, C * a i * ((b i) ^ (p a b) * (1 - ε n) * ((n ^ (p a b) * (1 + (∑ u ∈ range n, g u / u ^ ((p a b) + 1))) - n ^ (p a b) * (∑ u ∈ Finset.Ico (r i n) n, g u / u ^ ((p a b) + 1)))))) + g n := by congr; ext; ring _ = (∑ i, C * a i * ((b i) ^ (p a b) * (1 - ε n) * ((asympBound g a b n - sumTransform (p a b) g (r i n) n)))) + g n := by simp_rw [asympBound_def', sumTransform_def] _ ≤ (∑ i, C * a i * ((b i) ^ (p a b) * (1 - ε n) * ((asympBound g a b n - c₁ * g n)))) + g n := by gcongr with i · have := R.a_pos i positivity · have := R.b_pos i positivity · exact h_sumTransform n hn i _ = (∑ i, C * (1 - ε n) * ((asympBound g a b n - c₁ * g n)) * (a i * (b i) ^ (p a b))) + g n := by congr; ext; ring _ = C * (1 - ε n) * (asympBound g a b n - c₁ * g n) + g n := by rw [← Finset.mul_sum, R.sumCoeffsExp_p_eq_one, mul_one] _ = C * (1 - ε n) * asympBound g a b n + (1 - C * c₁ * (1 - ε n)) * g n := by ring _ ≤ C * (1 - ε n) * asympBound g a b n + 0 := by gcongr refine mul_nonpos_of_nonpos_of_nonneg ?_ g_pos rw [sub_nonpos] calc 1 ≤ 2 * (c₁⁻¹ * c₁) * (1/2) := by rw [inv_mul_cancel (by positivity : c₁ ≠ 0)]; norm_num _ = (2 * c₁⁻¹) * c₁ * (1/2) := by ring _ ≤ C * c₁ * (1 - ε n) := by gcongr · rw [hC]; exact le_max_left _ _ · exact le_of_lt <| h_smoothing_gt_half n hn _ = C * ((1 - ε n) * asympBound g a b n) := by ring /-- The main proof of the lower bound part of the Akra-Bazzi theorem. The factor `1 + ε n` does not change the asymptotic order, but is needed for the induction step to go through. -/ lemma smoothingFn_mul_asympBound_isBigO_T : (fun (n : ℕ) => (1 + ε n) * asympBound g a b n) =O[atTop] T := by let b' := b (min_bi b) / 2 have hb_pos : 0 < b' := R.bi_min_div_two_pos rw [isBigO_atTop_iff_eventually_exists_pos] obtain ⟨c₁, hc₁, h_sumTransform_aux⟩ := R.eventually_atTop_sumTransform_le filter_upwards [eventually_ge_atTop R.n₀, -- n₀_ge_Rn₀ (tendsto_nat_floor_mul_atTop b' hb_pos).eventually_gt_atTop 0, -- h_b_floor eventually_forall_ge_atTop.mpr eventually_one_add_smoothingFn_pos, -- h_smoothing_pos (tendsto_nat_floor_mul_atTop b' hb_pos).eventually_forall_ge_atTop eventually_one_add_smoothingFn_pos, -- h_smoothing_pos' eventually_forall_ge_atTop.mpr R.eventually_asympBound_pos, -- h_asympBound_pos eventually_forall_ge_atTop.mpr R.eventually_asympBound_r_pos, -- h_asympBound_r_pos (tendsto_nat_floor_mul_atTop b' hb_pos).eventually_forall_ge_atTop R.eventually_asympBound_pos, -- h_asympBound_floor eventually_gt_atTop 0, -- n₀_pos eventually_forall_ge_atTop.mpr R.eventually_one_add_smoothingFn_r_pos, -- h_smoothing_r_pos eventually_forall_ge_atTop.mpr R.rpow_p_mul_one_add_smoothingFn_ge, -- bound2 (tendsto_nat_floor_mul_atTop b' hb_pos).eventually_forall_ge_atTop eventually_one_add_smoothingFn_pos, -- h_smoothingFn_floor eventually_forall_ge_atTop.mpr h_sumTransform_aux, -- h_sumTransform eventually_forall_ge_atTop.mpr R.eventually_bi_mul_le_r, -- h_bi_le_r eventually_forall_ge_atTop.mpr (eventually_ge_atTop ⌈exp 1⌉₊)] -- h_exp with n₀ n₀_ge_Rn₀ h_b_floor h_smoothing_pos h_smoothing_pos' h_asympBound_pos h_asympBound_r_pos h_asympBound_floor n₀_pos h_smoothing_r_pos bound2 h_smoothingFn_floor h_sumTransform h_bi_le_r h_exp have h_base_nonempty := R.base_nonempty n₀_pos -- Min of the ratio T(n) / asympBound(n) over the base case n ∈ [b * n₀, n₀) set base_min : ℝ := (Finset.Ico (⌊b' * n₀⌋₊) n₀).inf' h_base_nonempty (fun n => T n / ((1 + ε n) * asympBound g a b n)) with base_min_def -- The big-O constant we are aiming for: min of the base case ratio and what we need to cancel -- out the g(n) term in the calculation below let C := min (2 * c₁)⁻¹ base_min have hC_pos : 0 < C := by refine lt_min (by positivity) ?_ obtain ⟨m, hm_mem, hm⟩ := Finset.exists_mem_eq_inf' h_base_nonempty (fun n => T n / ((1 + ε n) * asympBound g a b n)) calc 0 < T m / ((1 + ε m) * asympBound g a b m) := by have H₁ : 0 < T m := by exact R.T_pos _ have H₂ : 0 < 1 + ε m := by rw [Finset.mem_Ico] at hm_mem exact h_smoothing_pos' m hm_mem.1 have H₃ : 0 < asympBound g a b m := by refine R.asympBound_pos m ?_ calc 0 < ⌊b' * n₀⌋₊ := by exact h_b_floor _ ≤ m := by rw [Finset.mem_Ico] at hm_mem; exact hm_mem.1 positivity _ = base_min := by rw [base_min_def, hm] refine ⟨C, hC_pos, fun n hn => ?_⟩ -- Base case: statement is true for `b' * n₀ ≤ n < n₀` have h_base : ∀ n ∈ Finset.Ico (⌊b' * n₀⌋₊) n₀, C * ((1 + ε n) * asympBound g a b n) ≤ T n := by intro n hn rw [Finset.mem_Ico] at hn have htmp1 : 0 < 1 + ε n := h_smoothingFn_floor n hn.1 have htmp2 : 0 < asympBound g a b n := h_asympBound_floor n hn.1 rw [← _root_.le_div_iff (by positivity)] rw [← Finset.mem_Ico] at hn calc T n / ((1 + ε ↑n) * asympBound g a b n) ≥ (Finset.Ico (⌊b' * n₀⌋₊) n₀).inf' h_base_nonempty fun z => T z / ((1 + ε z) * asympBound g a b z) := Finset.inf'_le_of_le _ (b := n) hn <| le_refl _ _ ≥ C := min_le_right _ _ have h_asympBound_pos' : 0 < asympBound g a b n := h_asympBound_pos n hn have h_one_sub_smoothingFn_pos' : 0 < 1 + ε n := h_smoothing_pos n hn rw [Real.norm_of_nonneg (R.T_nonneg n), Real.norm_of_nonneg (by positivity)] -- We now prove all other cases by induction induction n using Nat.strongInductionOn with | ind n h_ind => have b_mul_n₀_le_ri i : ⌊b' * ↑n₀⌋₊ ≤ r i n := by exact_mod_cast calc ⌊b' * ↑n₀⌋₊ ≤ b' * n₀ := Nat.floor_le <| by positivity _ ≤ b' * n := by gcongr _ ≤ r i n := h_bi_le_r n hn i have g_pos : 0 ≤ g n := R.g_nonneg n (by positivity) calc T n = (∑ i, a i * T (r i n)) + g n := by exact R.h_rec n <| n₀_ge_Rn₀.trans hn _ ≥ (∑ i, a i * (C * ((1 + ε (r i n)) * asympBound g a b (r i n)))) + g n := by -- Apply the induction hypothesis, or use the base case depending on how large `n` is gcongr (∑ i, a i * ?_) + g n with i _ · exact le_of_lt <| R.a_pos _ · cases lt_or_le (r i n) n₀ with | inl ri_lt_n₀ => exact h_base _ <| Finset.mem_Ico.mpr ⟨b_mul_n₀_le_ri i, ri_lt_n₀⟩ | inr n₀_le_ri => exact h_ind (r i n) (R.r_lt_n _ _ (n₀_ge_Rn₀.trans hn)) n₀_le_ri (h_asympBound_r_pos _ hn _) (h_smoothing_r_pos n hn i) _ = (∑ i, a i * (C * ((1 + ε (r i n)) * ((r i n) ^ (p a b) * (1 + (∑ u ∈ range (r i n), g u / u ^ ((p a b) + 1))))))) + g n := by simp_rw [asympBound_def'] _ = (∑ i, C * a i * ((r i n)^(p a b) * (1 + ε (r i n)) * ((1 + (∑ u ∈ range (r i n), g u / u ^ ((p a b) + 1)))))) + g n := by congr; ext; ring _ ≥ (∑ i, C * a i * ((b i) ^ (p a b) * n ^ (p a b) * (1 + ε n) * ((1 + (∑ u ∈ range (r i n), g u / u ^ ((p a b) + 1)))))) + g n := by gcongr (∑ i, C * a i * (?_ * ((1 + (∑ u ∈ range (r i n), g u / u ^ ((p a b) + 1)))))) + g n with i · have := R.a_pos i positivity · refine add_nonneg zero_le_one <| Finset.sum_nonneg fun j _ => ?_ rw [div_nonneg_iff] exact Or.inl ⟨R.g_nonneg j (by positivity), by positivity⟩ · exact bound2 n hn i _ = (∑ i, C * a i * ((b i) ^ (p a b) * n ^ (p a b) * (1 + ε n) * ((1 + ((∑ u ∈ range n, g u / u ^ ((p a b) + 1)) - (∑ u ∈ Finset.Ico (r i n) n, g u / u ^ ((p a b) + 1))))))) + g n := by congr; ext i; congr refine eq_sub_of_add_eq ?_ rw [add_comm] exact add_eq_of_eq_sub <| Finset.sum_Ico_eq_sub _ <| le_of_lt <| R.r_lt_n i n <| n₀_ge_Rn₀.trans hn _ = (∑ i, C * a i * ((b i) ^ (p a b) * (1 + ε n) * ((n ^ (p a b) * (1 + (∑ u ∈ range n, g u / u ^ ((p a b) + 1))) - n ^ (p a b) * (∑ u ∈ Finset.Ico (r i n) n, g u / u ^ ((p a b) + 1)))))) + g n := by congr; ext; ring _ = (∑ i, C * a i * ((b i) ^ (p a b) * (1 + ε n) * ((asympBound g a b n - sumTransform (p a b) g (r i n) n)))) + g n := by simp_rw [asympBound_def', sumTransform_def] _ ≥ (∑ i, C * a i * ((b i) ^ (p a b) * (1 + ε n) * ((asympBound g a b n - c₁ * g n)))) + g n := by gcongr with i · have := R.a_pos i positivity · have := R.b_pos i positivity · exact h_sumTransform n hn i _ = (∑ i, C * (1 + ε n) * ((asympBound g a b n - c₁ * g n)) * (a i * (b i) ^ (p a b))) + g n := by congr; ext; ring _ = C * (1 + ε n) * (asympBound g a b n - c₁ * g n) + g n := by rw [← Finset.mul_sum, R.sumCoeffsExp_p_eq_one, mul_one] _ = C * (1 + ε n) * asympBound g a b n + (1 - C * c₁ * (1 + ε n)) * g n := by ring _ ≥ C * (1 + ε n) * asympBound g a b n + 0 := by gcongr refine mul_nonneg ?_ g_pos rw [sub_nonneg] calc C * c₁ * (1 + ε n) ≤ C * c₁ * 2 := by gcongr refine one_add_smoothingFn_le_two ?_ calc exp 1 ≤ ⌈exp 1⌉₊ := by exact Nat.le_ceil _ _ ≤ n := by exact_mod_cast h_exp n hn _ = C * (2 * c₁) := by ring _ ≤ (2 * c₁)⁻¹ * (2 * c₁) := by gcongr; exact min_le_left _ _ _ = c₁⁻¹ * c₁ := by ring _ = 1 := inv_mul_cancel (by positivity) _ = C * ((1 + ε n) * asympBound g a b n) := by ring /-- The **Akra-Bazzi theorem**: `T ∈ O(n^p (1 + ∑_u^n g(u) / u^{p+1}))` -/ theorem isBigO_asympBound : T =O[atTop] asympBound g a b := by calc T =O[atTop] (fun n => (1 - ε n) * asympBound g a b n) := by exact R.T_isBigO_smoothingFn_mul_asympBound _ =O[atTop] (fun n => 1 * asympBound g a b n) := by refine IsBigO.mul (isBigO_const_of_tendsto (y := 1) ?_ one_ne_zero) (isBigO_refl _ _) rw [← Function.comp_def (fun n => 1 - ε n) Nat.cast] exact Tendsto.comp isEquivalent_one_sub_smoothingFn_one.tendsto_const tendsto_natCast_atTop_atTop _ = asympBound g a b := by simp /-- The **Akra-Bazzi theorem**: `T ∈ Ω(n^p (1 + ∑_u^n g(u) / u^{p+1}))` -/ theorem isBigO_symm_asympBound : asympBound g a b =O[atTop] T := by calc asympBound g a b = (fun n => 1 * asympBound g a b n) := by simp _ ~[atTop] (fun n => (1 + ε n) * asympBound g a b n) := by refine IsEquivalent.mul (IsEquivalent.symm ?_) IsEquivalent.refl rw [Function.const_def, isEquivalent_const_iff_tendsto one_ne_zero, ← Function.comp_def (fun n => 1 + ε n) Nat.cast] exact Tendsto.comp isEquivalent_one_add_smoothingFn_one.tendsto_const tendsto_natCast_atTop_atTop _ =O[atTop] T := R.smoothingFn_mul_asympBound_isBigO_T /-- The **Akra-Bazzi theorem**: `T ∈ Θ(n^p (1 + ∑_u^n g(u) / u^{p+1}))` -/ theorem isTheta_asympBound : T =Θ[atTop] asympBound g a b := ⟨R.isBigO_asympBound, R.isBigO_symm_asympBound⟩ end AkraBazziRecurrence
Computability\AkraBazzi\GrowsPolynomially.lean
/- Copyright (c) 2023 Frédéric Dupuis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Frédéric Dupuis -/ import Mathlib.Analysis.Asymptotics.AsymptoticEquivalent import Mathlib.Analysis.SpecialFunctions.Pow.Real import Mathlib.Algebra.Order.ToIntervalMod import Mathlib.Analysis.SpecialFunctions.Log.Base /-! # Akra-Bazzi theorem: The polynomial growth condition This file defines and develops an API for the polynomial growth condition that appears in the statement of the Akra-Bazzi theorem: for the Akra-Bazzi theorem to hold, the function `g` must satisfy the condition that `c₁ g(n) ≤ g(u) ≤ c₂ g(n)`, for u between b*n and n for any constant `b ∈ (0,1)`. ## Implementation notes Our definition states that the condition must hold for any `b ∈ (0,1)`. This is equivalent to only requiring it for `b = 1/2` or any other particular value between 0 and 1. While this could in principle make it harder to prove that a particular function grows polynomially, this issue doesn't seem to arise in practice. -/ open Finset Real Filter Asymptotics open scoped Topology namespace AkraBazziRecurrence /-- The growth condition that the function `g` must satisfy for the Akra-Bazzi theorem to apply. It roughly states that `c₁ g(n) ≤ g(u) ≤ c₂ g(n)`, for `u` between `b*n` and `n` for any constant `b ∈ (0,1)`. -/ def GrowsPolynomially (f : ℝ → ℝ) : Prop := ∀ b ∈ Set.Ioo 0 1, ∃ c₁ > 0, ∃ c₂ > 0, ∀ᶠ x in atTop, ∀ u ∈ Set.Icc (b * x) x, f u ∈ Set.Icc (c₁ * (f x)) (c₂ * f x) namespace GrowsPolynomially lemma congr_of_eventuallyEq {f g : ℝ → ℝ} (hfg : f =ᶠ[atTop] g) (hg : GrowsPolynomially g) : GrowsPolynomially f := by intro b hb have hg' := hg b hb obtain ⟨c₁, hc₁_mem, c₂, hc₂_mem, hg'⟩ := hg' refine ⟨c₁, hc₁_mem, c₂, hc₂_mem, ?_⟩ filter_upwards [hg', (tendsto_id.const_mul_atTop hb.1).eventually_forall_ge_atTop hfg, hfg] with x hx₁ hx₂ hx₃ intro u hu rw [hx₂ u hu.1, hx₃] exact hx₁ u hu lemma iff_eventuallyEq {f g : ℝ → ℝ} (h : f =ᶠ[atTop] g) : GrowsPolynomially f ↔ GrowsPolynomially g := ⟨fun hf => congr_of_eventuallyEq h.symm hf, fun hg => congr_of_eventuallyEq h hg⟩ variable {f : ℝ → ℝ} lemma eventually_atTop_le {b : ℝ} (hb : b ∈ Set.Ioo 0 1) (hf : GrowsPolynomially f) : ∃ c > 0, ∀ᶠ x in atTop, ∀ u ∈ Set.Icc (b * x) x, f u ≤ c * f x := by obtain ⟨c₁, _, c₂, hc₂, h⟩ := hf b hb refine ⟨c₂, hc₂, ?_⟩ filter_upwards [h] exact fun _ H u hu => (H u hu).2 lemma eventually_atTop_le_nat {b : ℝ} (hb : b ∈ Set.Ioo 0 1) (hf : GrowsPolynomially f) : ∃ c > 0, ∀ᶠ (n : ℕ) in atTop, ∀ u ∈ Set.Icc (b * n) n, f u ≤ c * f n := by obtain ⟨c, hc_mem, hc⟩ := hf.eventually_atTop_le hb exact ⟨c, hc_mem, hc.natCast_atTop⟩ lemma eventually_atTop_ge {b : ℝ} (hb : b ∈ Set.Ioo 0 1) (hf : GrowsPolynomially f) : ∃ c > 0, ∀ᶠ x in atTop, ∀ u ∈ Set.Icc (b * x) x, c * f x ≤ f u := by obtain ⟨c₁, hc₁, c₂, _, h⟩ := hf b hb refine ⟨c₁, hc₁, ?_⟩ filter_upwards [h] exact fun _ H u hu => (H u hu).1 lemma eventually_atTop_ge_nat {b : ℝ} (hb : b ∈ Set.Ioo 0 1) (hf : GrowsPolynomially f) : ∃ c > 0, ∀ᶠ (n : ℕ) in atTop, ∀ u ∈ Set.Icc (b * n) n, c * f n ≤ f u := by obtain ⟨c, hc_mem, hc⟩ := hf.eventually_atTop_ge hb exact ⟨c, hc_mem, hc.natCast_atTop⟩ lemma eventually_zero_of_frequently_zero (hf : GrowsPolynomially f) (hf' : ∃ᶠ x in atTop, f x = 0) : ∀ᶠ x in atTop, f x = 0 := by obtain ⟨c₁, hc₁_mem, c₂, hc₂_mem, hf⟩ := hf (1/2) (by norm_num) rw [frequently_atTop] at hf' filter_upwards [eventually_forall_ge_atTop.mpr hf, eventually_gt_atTop 0] with x hx hx_pos obtain ⟨x₀, hx₀_ge, hx₀⟩ := hf' (max x 1) have x₀_pos := calc 0 < 1 := by norm_num _ ≤ x₀ := le_of_max_le_right hx₀_ge have hmain : ∀ (m : ℕ) (z : ℝ), x ≤ z → z ∈ Set.Icc ((2 : ℝ)^(-(m : ℤ) -1) * x₀) ((2 : ℝ)^(-(m : ℤ)) * x₀) → f z = 0 := by intro m induction m with | zero => simp only [Nat.zero_eq, CharP.cast_eq_zero, neg_zero, zero_sub, zpow_zero, one_mul] at * specialize hx x₀ (le_of_max_le_left hx₀_ge) simp only [hx₀, mul_zero, Set.Icc_self, Set.mem_singleton_iff] at hx refine fun z _ hz => hx _ ?_ simp only [zpow_neg, zpow_one] at hz simp only [one_div, hz] | succ k ih => intro z hxz hz simp only [Nat.succ_eq_add_one, Nat.cast_add, Nat.cast_one] at * have hx' : x ≤ (2 : ℝ)^(-(k : ℤ) - 1) * x₀ := by calc x ≤ z := hxz _ ≤ _ := by simp only [neg_add, ← sub_eq_add_neg] at hz; exact hz.2 specialize hx ((2 : ℝ)^(-(k : ℤ) - 1) * x₀) hx' z specialize ih ((2 : ℝ)^(-(k : ℤ) - 1) * x₀) hx' ?ineq case ineq => rw [Set.left_mem_Icc] gcongr · norm_num · linarith simp only [ih, mul_zero, Set.Icc_self, Set.mem_singleton_iff] at hx refine hx ⟨?lb₁, ?ub₁⟩ case lb₁ => rw [one_div, ← zpow_neg_one, ← mul_assoc, ← zpow_add₀ (by norm_num)] have h₁ : (-1 : ℤ) + (-k - 1) = -k - 2 := by ring have h₂ : -(k + (1 : ℤ)) - 1 = -k - 2 := by ring rw [h₁] rw [h₂] at hz exact hz.1 case ub₁ => have := hz.2 simp only [neg_add, ← sub_eq_add_neg] at this exact this refine hmain ⌊-logb 2 (x / x₀)⌋₊ x le_rfl ⟨?lb, ?ub⟩ case lb => rw [← le_div_iff x₀_pos] refine (logb_le_logb (b := 2) (by norm_num) (zpow_pos_of_pos (by norm_num) _) (by positivity)).mp ?_ rw [← rpow_intCast, logb_rpow (by norm_num) (by norm_num), ← neg_le_neg_iff] simp only [Int.cast_sub, Int.cast_neg, Int.cast_natCast, Int.cast_one, neg_sub, sub_neg_eq_add] calc -logb 2 (x/x₀) ≤ ⌈-logb 2 (x/x₀)⌉₊ := Nat.le_ceil (-logb 2 (x / x₀)) _ ≤ _ := by rw [add_comm]; exact_mod_cast Nat.ceil_le_floor_add_one _ case ub => rw [← div_le_iff x₀_pos] refine (logb_le_logb (b := 2) (by norm_num) (by positivity) (zpow_pos_of_pos (by norm_num) _)).mp ?_ rw [← rpow_intCast, logb_rpow (by norm_num) (by norm_num), ← neg_le_neg_iff] simp only [Int.cast_neg, Int.cast_natCast, neg_neg] have : 0 ≤ -logb 2 (x / x₀) := by rw [neg_nonneg] refine logb_nonpos (by norm_num) (by positivity) ?_ rw [div_le_one x₀_pos] exact le_of_max_le_left hx₀_ge exact_mod_cast Nat.floor_le this lemma eventually_atTop_nonneg_or_nonpos (hf : GrowsPolynomially f) : (∀ᶠ x in atTop, 0 ≤ f x) ∨ (∀ᶠ x in atTop, f x ≤ 0) := by obtain ⟨c₁, _, c₂, _, h⟩ := hf (1/2) (by norm_num) match lt_trichotomy c₁ c₂ with | .inl hlt => -- c₁ < c₂ left filter_upwards [h, eventually_ge_atTop 0] with x hx hx_nonneg have h' : 3 / 4 * x ∈ Set.Icc (1 / 2 * x) x := by rw [Set.mem_Icc] exact ⟨by gcongr ?_ * x; norm_num, by linarith⟩ have hu := hx (3/4 * x) h' have hu := Set.nonempty_of_mem hu rw [Set.nonempty_Icc] at hu have hu' : 0 ≤ (c₂ - c₁) * f x := by linarith exact nonneg_of_mul_nonneg_right hu' (by linarith) | .inr (.inr hgt) => -- c₂ < c₁ right filter_upwards [h, eventually_ge_atTop 0] with x hx hx_nonneg have h' : 3 / 4 * x ∈ Set.Icc (1 / 2 * x) x := by rw [Set.mem_Icc] exact ⟨by gcongr ?_ * x; norm_num, by linarith⟩ have hu := hx (3/4 * x) h' have hu := Set.nonempty_of_mem hu rw [Set.nonempty_Icc] at hu have hu' : (c₁ - c₂) * f x ≤ 0 := by linarith exact nonpos_of_mul_nonpos_right hu' (by linarith) | .inr (.inl heq) => -- c₁ = c₂ have hmain : ∃ c, ∀ᶠ x in atTop, f x = c := by simp only [heq, Set.Icc_self, Set.mem_singleton_iff, one_mul] at h rw [eventually_atTop] at h obtain ⟨n₀, hn₀⟩ := h refine ⟨f (max n₀ 2), ?_⟩ rw [eventually_atTop] refine ⟨max n₀ 2, ?_⟩ refine Real.induction_Ico_mul _ 2 (by norm_num) (by positivity) ?base ?step case base => intro x ⟨hxlb, hxub⟩ have h₁ := calc n₀ ≤ 1 * max n₀ 2 := by simp _ ≤ 2 * max n₀ 2 := by gcongr; norm_num have h₂ := hn₀ (2 * max n₀ 2) h₁ (max n₀ 2) ⟨by simp [-max_le_iff, hxlb], by linarith⟩ rw [h₂] exact hn₀ (2 * max n₀ 2) h₁ x ⟨by simp [-max_le_iff, hxlb], le_of_lt hxub⟩ case step => intro n hn hyp_ind z hz have z_nonneg : 0 ≤ z := by calc (0 : ℝ) ≤ (2 : ℝ)^n * max n₀ 2 := by exact mul_nonneg (pow_nonneg (by norm_num) _) (by norm_num) _ ≤ z := by exact_mod_cast hz.1 have le_2n : max n₀ 2 ≤ (2 : ℝ)^n * max n₀ 2 := by nth_rewrite 1 [← one_mul (max n₀ 2)] gcongr exact one_le_pow_of_one_le (by norm_num : (1 : ℝ) ≤ 2) _ have n₀_le_z : n₀ ≤ z := by calc n₀ ≤ max n₀ 2 := by simp _ ≤ (2 : ℝ)^n * max n₀ 2 := le_2n _ ≤ _ := by exact_mod_cast hz.1 have fz_eq_c₂fz : f z = c₂ * f z := hn₀ z n₀_le_z z ⟨by linarith, le_rfl⟩ have z_to_half_z' : f (1/2 * z) = c₂ * f z := hn₀ z n₀_le_z (1/2 * z) ⟨le_rfl, by linarith⟩ have z_to_half_z : f (1/2 * z) = f z := by rwa [← fz_eq_c₂fz] at z_to_half_z' have half_z_to_base : f (1/2 * z) = f (max n₀ 2) := by refine hyp_ind (1/2 * z) ⟨?lb, ?ub⟩ case lb => calc max n₀ 2 ≤ ((1 : ℝ)/(2 : ℝ)) * (2 : ℝ) ^ 1 * max n₀ 2 := by simp _ ≤ ((1 : ℝ)/(2 : ℝ)) * (2 : ℝ) ^ n * max n₀ 2 := by gcongr; norm_num _ ≤ _ := by rw [mul_assoc]; gcongr; exact_mod_cast hz.1 case ub => have h₁ : (2 : ℝ)^n = ((1 : ℝ)/(2 : ℝ)) * (2 : ℝ)^(n+1) := by rw [one_div, pow_add, pow_one] ring rw [h₁, mul_assoc] gcongr exact_mod_cast hz.2 rw [← z_to_half_z, half_z_to_base] obtain ⟨c, hc⟩ := hmain cases le_or_lt 0 c with | inl hpos => exact Or.inl <| by filter_upwards [hc] with _ hc; simpa only [hc] | inr hneg => right filter_upwards [hc] with x hc exact le_of_lt <| by simpa only [hc] lemma eventually_atTop_zero_or_pos_or_neg (hf : GrowsPolynomially f) : (∀ᶠ x in atTop, f x = 0) ∨ (∀ᶠ x in atTop, 0 < f x) ∨ (∀ᶠ x in atTop, f x < 0) := by if h : ∃ᶠ x in atTop, f x = 0 then exact Or.inl <| eventually_zero_of_frequently_zero hf h else rw [not_frequently] at h push_neg at h cases eventually_atTop_nonneg_or_nonpos hf with | inl h' => refine Or.inr (Or.inl ?_) simp only [lt_iff_le_and_ne] rw [eventually_and] exact ⟨h', by filter_upwards [h] with x hx; exact hx.symm⟩ | inr h' => refine Or.inr (Or.inr ?_) simp only [lt_iff_le_and_ne] rw [eventually_and] exact ⟨h', h⟩ protected lemma neg {f : ℝ → ℝ} (hf : GrowsPolynomially f) : GrowsPolynomially (-f) := by intro b hb obtain ⟨c₁, hc₁_mem, c₂, hc₂_mem, hf⟩ := hf b hb refine ⟨c₂, hc₂_mem, c₁, hc₁_mem, ?_⟩ filter_upwards [hf] with x hx intro u hu simp only [Pi.neg_apply, Set.neg_mem_Icc_iff, neg_mul_eq_mul_neg, neg_neg] exact hx u hu protected lemma neg_iff {f : ℝ → ℝ} : GrowsPolynomially f ↔ GrowsPolynomially (-f) := ⟨fun hf => hf.neg, fun hf => by rw [← neg_neg f]; exact hf.neg⟩ protected lemma abs (hf : GrowsPolynomially f) : GrowsPolynomially (fun x => |f x|) := by cases eventually_atTop_nonneg_or_nonpos hf with | inl hf' => have hmain : f =ᶠ[atTop] fun x => |f x| := by filter_upwards [hf'] with x hx rw [abs_of_nonneg hx] rw [← iff_eventuallyEq hmain] exact hf | inr hf' => have hmain : -f =ᶠ[atTop] fun x => |f x| := by filter_upwards [hf'] with x hx simp only [Pi.neg_apply, abs_of_nonpos hx] rw [← iff_eventuallyEq hmain] exact hf.neg protected lemma norm (hf : GrowsPolynomially f) : GrowsPolynomially (fun x => ‖f x‖) := by simp only [norm_eq_abs] exact hf.abs end GrowsPolynomially variable {f : ℝ → ℝ} lemma growsPolynomially_const {c : ℝ} : GrowsPolynomially (fun _ => c) := by refine fun _ _ => ⟨1, by norm_num, 1, by norm_num, ?_⟩ filter_upwards [] with x simp lemma growsPolynomially_id : GrowsPolynomially (fun x => x) := by intro b hb refine ⟨b, hb.1, ?_⟩ refine ⟨1, by norm_num, ?_⟩ filter_upwards with x u hu simp only [one_mul, gt_iff_lt, not_le, Set.mem_Icc] exact ⟨hu.1, hu.2⟩ protected lemma GrowsPolynomially.mul {f g : ℝ → ℝ} (hf : GrowsPolynomially f) (hg : GrowsPolynomially g) : GrowsPolynomially fun x => f x * g x := by suffices GrowsPolynomially fun x => |f x| * |g x| by cases eventually_atTop_nonneg_or_nonpos hf with | inl hf' => cases eventually_atTop_nonneg_or_nonpos hg with | inl hg' => have hmain : (fun x => f x * g x) =ᶠ[atTop] fun x => |f x| * |g x| := by filter_upwards [hf', hg'] with x hx₁ hx₂ rw [abs_of_nonneg hx₁, abs_of_nonneg hx₂] rwa [iff_eventuallyEq hmain] | inr hg' => have hmain : (fun x => f x * g x) =ᶠ[atTop] fun x => -|f x| * |g x| := by filter_upwards [hf', hg'] with x hx₁ hx₂ simp [abs_of_nonneg hx₁, abs_of_nonpos hx₂] simp only [iff_eventuallyEq hmain, neg_mul] exact this.neg | inr hf' => cases eventually_atTop_nonneg_or_nonpos hg with | inl hg' => have hmain : (fun x => f x * g x) =ᶠ[atTop] fun x => -|f x| * |g x| := by filter_upwards [hf', hg'] with x hx₁ hx₂ rw [abs_of_nonpos hx₁, abs_of_nonneg hx₂, neg_neg] simp only [iff_eventuallyEq hmain, neg_mul] exact this.neg | inr hg' => have hmain : (fun x => f x * g x) =ᶠ[atTop] fun x => |f x| * |g x| := by filter_upwards [hf', hg'] with x hx₁ hx₂ simp [abs_of_nonpos hx₁, abs_of_nonpos hx₂] simp only [iff_eventuallyEq hmain, neg_mul] exact this intro b hb have hf := hf.abs b hb have hg := hg.abs b hb obtain ⟨c₁, hc₁_mem, c₂, hc₂_mem, hf⟩ := hf obtain ⟨c₃, hc₃_mem, c₄, hc₄_mem, hg⟩ := hg refine ⟨c₁ * c₃, by show 0 < c₁ * c₃; positivity, ?_⟩ refine ⟨c₂ * c₄, by show 0 < c₂ * c₄; positivity, ?_⟩ filter_upwards [hf, hg] with x hf hg intro u hu refine ⟨?lb, ?ub⟩ case lb => calc c₁ * c₃ * (|f x| * |g x|) = (c₁ * |f x|) * (c₃ * |g x|) := by ring _ ≤ |f u| * |g u| := by gcongr · exact (hf u hu).1 · exact (hg u hu).1 case ub => calc |f u| * |g u| ≤ (c₂ * |f x|) * (c₄ * |g x|) := by gcongr · exact (hf u hu).2 · exact (hg u hu).2 _ = c₂ * c₄ * (|f x| * |g x|) := by ring lemma GrowsPolynomially.const_mul {f : ℝ → ℝ} {c : ℝ} (hf : GrowsPolynomially f) : GrowsPolynomially fun x => c * f x := GrowsPolynomially.mul growsPolynomially_const hf protected lemma GrowsPolynomially.add {f g : ℝ → ℝ} (hf : GrowsPolynomially f) (hg : GrowsPolynomially g) (hf' : 0 ≤ᶠ[atTop] f) (hg' : 0 ≤ᶠ[atTop] g) : GrowsPolynomially fun x => f x + g x := by intro b hb have hf := hf b hb have hg := hg b hb obtain ⟨c₁, hc₁_mem, c₂, hc₂_mem, hf⟩ := hf obtain ⟨c₃, hc₃_mem, c₄, _, hg⟩ := hg refine ⟨min c₁ c₃, by show 0 < min c₁ c₃; positivity, ?_⟩ refine ⟨max c₂ c₄, by show 0 < max c₂ c₄; positivity, ?_⟩ filter_upwards [hf, hg, (tendsto_id.const_mul_atTop hb.1).eventually_forall_ge_atTop hf', (tendsto_id.const_mul_atTop hb.1).eventually_forall_ge_atTop hg', eventually_ge_atTop 0] with x hf hg hf' hg' hx_pos intro u hu have hbx : b * x ≤ x := calc b * x ≤ 1 * x := by gcongr; exact le_of_lt hb.2 _ = x := by ring have fx_nonneg : 0 ≤ f x := hf' x hbx have gx_nonneg : 0 ≤ g x := hg' x hbx refine ⟨?lb, ?ub⟩ case lb => calc min c₁ c₃ * (f x + g x) = min c₁ c₃ * f x + min c₁ c₃ * g x := by simp only [mul_add] _ ≤ c₁ * f x + c₃ * g x := by gcongr · exact min_le_left _ _ · exact min_le_right _ _ _ ≤ f u + g u := by gcongr · exact (hf u hu).1 · exact (hg u hu).1 case ub => calc max c₂ c₄ * (f x + g x) = max c₂ c₄ * f x + max c₂ c₄ * g x := by simp only [mul_add] _ ≥ c₂ * f x + c₄ * g x := by gcongr · exact le_max_left _ _ · exact le_max_right _ _ _ ≥ f u + g u := by gcongr · exact (hf u hu).2 · exact (hg u hu).2 lemma GrowsPolynomially.add_isLittleO {f g : ℝ → ℝ} (hf : GrowsPolynomially f) (hfg : g =o[atTop] f) : GrowsPolynomially fun x => f x + g x := by intro b hb have hb_ub := hb.2 rw [isLittleO_iff] at hfg cases hf.eventually_atTop_nonneg_or_nonpos with | inl hf' => -- f is eventually non-negative have hf := hf b hb obtain ⟨c₁, hc₁_mem : 0 < c₁, c₂, hc₂_mem : 0 < c₂, hf⟩ := hf specialize hfg (c := 1/2) (by norm_num) refine ⟨c₁ / 3, by positivity, 3*c₂, by positivity, ?_⟩ filter_upwards [hf, (tendsto_id.const_mul_atTop hb.1).eventually_forall_ge_atTop hfg, (tendsto_id.const_mul_atTop hb.1).eventually_forall_ge_atTop hf', eventually_ge_atTop 0] with x hf₁ hfg' hf₂ hx_nonneg have hbx : b * x ≤ x := by nth_rewrite 2 [← one_mul x]; gcongr have hfg₂ : ‖g x‖ ≤ 1/2 * f x := by calc ‖g x‖ ≤ 1/2 * ‖f x‖ := hfg' x hbx _ = 1/2 * f x := by congr; exact norm_of_nonneg (hf₂ _ hbx) have hx_ub : f x + g x ≤ 3/2 * f x := by calc _ ≤ f x + ‖g x‖ := by gcongr; exact le_norm_self (g x) _ ≤ f x + 1/2 * f x := by gcongr _ = 3/2 * f x := by ring have hx_lb : 1/2 * f x ≤ f x + g x := by calc f x + g x ≥ f x - ‖g x‖ := by rw [sub_eq_add_neg, norm_eq_abs]; gcongr; exact neg_abs_le (g x) _ ≥ f x - 1/2 * f x := by gcongr _ = 1/2 * f x := by ring intro u ⟨hu_lb, hu_ub⟩ have hfu_nonneg : 0 ≤ f u := hf₂ _ hu_lb have hfg₃ : ‖g u‖ ≤ 1/2 * f u := by calc ‖g u‖ ≤ 1/2 * ‖f u‖ := hfg' _ hu_lb _ = 1/2 * f u := by congr; simp only [norm_eq_abs, abs_eq_self, hfu_nonneg] refine ⟨?lb, ?ub⟩ case lb => calc f u + g u ≥ f u - ‖g u‖ := by rw [sub_eq_add_neg, norm_eq_abs]; gcongr; exact neg_abs_le _ _ ≥ f u - 1/2 * f u := by gcongr _ = 1/2 * f u := by ring _ ≥ 1/2 * (c₁ * f x) := by gcongr; exact (hf₁ u ⟨hu_lb, hu_ub⟩).1 _ = c₁/3 * (3/2 * f x) := by ring _ ≥ c₁/3 * (f x + g x) := by gcongr case ub => calc _ ≤ f u + ‖g u‖ := by gcongr; exact le_norm_self (g u) _ ≤ f u + 1/2 * f u := by gcongr _ = 3/2 * f u := by ring _ ≤ 3/2 * (c₂ * f x) := by gcongr; exact (hf₁ u ⟨hu_lb, hu_ub⟩).2 _ = 3*c₂ * (1/2 * f x) := by ring _ ≤ 3*c₂ * (f x + g x) := by gcongr | inr hf' => -- f is eventually nonpos have hf := hf b hb obtain ⟨c₁, hc₁_mem : 0 < c₁, c₂, hc₂_mem : 0 < c₂, hf⟩ := hf specialize hfg (c := 1/2) (by norm_num) refine ⟨3*c₁, by positivity, c₂/3, by positivity, ?_⟩ filter_upwards [hf, (tendsto_id.const_mul_atTop hb.1).eventually_forall_ge_atTop hfg, (tendsto_id.const_mul_atTop hb.1).eventually_forall_ge_atTop hf', eventually_ge_atTop 0] with x hf₁ hfg' hf₂ hx_nonneg have hbx : b * x ≤ x := by nth_rewrite 2 [← one_mul x]; gcongr have hfg₂ : ‖g x‖ ≤ -1/2 * f x := by calc ‖g x‖ ≤ 1/2 * ‖f x‖ := hfg' x hbx _ = 1/2 * (-f x) := by congr; exact norm_of_nonpos (hf₂ x hbx) _ = _ := by ring have hx_ub : f x + g x ≤ 1/2 * f x := by calc _ ≤ f x + ‖g x‖ := by gcongr; exact le_norm_self (g x) _ ≤ f x + (-1/2 * f x) := by gcongr _ = 1/2 * f x := by ring have hx_lb : 3/2 * f x ≤ f x + g x := by calc f x + g x ≥ f x - ‖g x‖ := by rw [sub_eq_add_neg, norm_eq_abs]; gcongr; exact neg_abs_le (g x) _ ≥ f x + 1/2 * f x := by rw [sub_eq_add_neg] gcongr refine le_of_neg_le_neg ?bc.a rwa [neg_neg, ← neg_mul, ← neg_div] _ = 3/2 * f x := by ring intro u ⟨hu_lb, hu_ub⟩ have hfu_nonpos : f u ≤ 0 := hf₂ _ hu_lb have hfg₃ : ‖g u‖ ≤ -1/2 * f u := by calc ‖g u‖ ≤ 1/2 * ‖f u‖ := hfg' _ hu_lb _ = 1/2 * (-f u) := by congr; exact norm_of_nonpos hfu_nonpos _ = -1/2 * f u := by ring refine ⟨?lb, ?ub⟩ case lb => calc f u + g u ≥ f u - ‖g u‖ := by rw [sub_eq_add_neg, norm_eq_abs]; gcongr; exact neg_abs_le _ _ ≥ f u + 1/2 * f u := by rw [sub_eq_add_neg] gcongr refine le_of_neg_le_neg ?_ rwa [neg_neg, ← neg_mul, ← neg_div] _ = 3/2 * f u := by ring _ ≥ 3/2 * (c₁ * f x) := by gcongr; exact (hf₁ u ⟨hu_lb, hu_ub⟩).1 _ = 3*c₁ * (1/2 * f x) := by ring _ ≥ 3*c₁ * (f x + g x) := by gcongr case ub => calc _ ≤ f u + ‖g u‖ := by gcongr; exact le_norm_self (g u) _ ≤ f u - 1/2 * f u := by rw [sub_eq_add_neg] gcongr rwa [← neg_mul, ← neg_div] _ = 1/2 * f u := by ring _ ≤ 1/2 * (c₂ * f x) := by gcongr; exact (hf₁ u ⟨hu_lb, hu_ub⟩).2 _ = c₂/3 * (3/2 * f x) := by ring _ ≤ c₂/3 * (f x + g x) := by gcongr protected lemma GrowsPolynomially.inv {f : ℝ → ℝ} (hf : GrowsPolynomially f) : GrowsPolynomially fun x => (f x)⁻¹ := by cases hf.eventually_atTop_zero_or_pos_or_neg with | inl hf' => refine fun b hb => ⟨1, by simp, 1, by simp, ?_⟩ have hb_pos := hb.1 filter_upwards [hf', (tendsto_id.const_mul_atTop hb_pos).eventually_forall_ge_atTop hf'] with x hx hx' intro u hu simp only [hx, inv_zero, mul_zero, Set.Icc_self, Set.mem_singleton_iff, hx' u hu.1] | inr hf_pos_or_neg => suffices GrowsPolynomially fun x => |(f x)⁻¹| by cases hf_pos_or_neg with | inl hf' => have hmain : (fun x => (f x)⁻¹) =ᶠ[atTop] fun x => |(f x)⁻¹| := by filter_upwards [hf'] with x hx₁ rw [abs_of_nonneg (inv_nonneg_of_nonneg (le_of_lt hx₁))] rwa [iff_eventuallyEq hmain] | inr hf' => have hmain : (fun x => (f x)⁻¹) =ᶠ[atTop] fun x => -|(f x)⁻¹| := by filter_upwards [hf'] with x hx₁ simp [abs_of_nonpos (inv_nonpos.mpr (le_of_lt hx₁))] rw [iff_eventuallyEq hmain] exact this.neg have hf' : ∀ᶠ x in atTop, f x ≠ 0 := by cases hf_pos_or_neg with | inl H => filter_upwards [H] with _ hx; exact (ne_of_lt hx).symm | inr H => filter_upwards [H] with _ hx; exact (ne_of_gt hx).symm simp only [abs_inv] have hf := hf.abs intro b hb have hb_pos := hb.1 obtain ⟨c₁, hc₁_mem, c₂, hc₂_mem, hf⟩ := hf b hb refine ⟨c₂⁻¹, by show 0 < c₂⁻¹; positivity, ?_⟩ refine ⟨c₁⁻¹, by show 0 < c₁⁻¹; positivity, ?_⟩ filter_upwards [hf, hf', (tendsto_id.const_mul_atTop hb_pos).eventually_forall_ge_atTop hf'] with x hx hx' hx'' intro u hu have h₁ : 0 < |f u| := by rw [abs_pos]; exact hx'' u hu.1 refine ⟨?lb, ?ub⟩ case lb => rw [← mul_inv] gcongr exact (hx u hu).2 case ub => rw [← mul_inv] gcongr exact (hx u hu).1 protected lemma GrowsPolynomially.div {f g : ℝ → ℝ} (hf : GrowsPolynomially f) (hg : GrowsPolynomially g) : GrowsPolynomially fun x => f x / g x := by have : (fun x => f x / g x) = fun x => f x * (g x)⁻¹ := by ext; rw [div_eq_mul_inv] rw [this] exact GrowsPolynomially.mul hf (GrowsPolynomially.inv hg) protected lemma GrowsPolynomially.rpow (p : ℝ) (hf : GrowsPolynomially f) (hf_nonneg : ∀ᶠ x in atTop, 0 ≤ f x) : GrowsPolynomially fun x => (f x) ^ p := by intro b hb obtain ⟨c₁, (hc₁_mem : 0 < c₁), c₂, hc₂_mem, hfnew⟩ := hf b hb have hc₁p : 0 < c₁ ^ p := Real.rpow_pos_of_pos hc₁_mem _ have hc₂p : 0 < c₂ ^ p := Real.rpow_pos_of_pos hc₂_mem _ cases le_or_lt 0 p with | inl => -- 0 ≤ p refine ⟨c₁^p, hc₁p, ?_⟩ refine ⟨c₂^p, hc₂p, ?_⟩ filter_upwards [eventually_gt_atTop 0, hfnew, hf_nonneg, (tendsto_id.const_mul_atTop hb.1).eventually_forall_ge_atTop hf_nonneg] with x _ hf₁ hf_nonneg hf_nonneg₂ intro u hu have fu_nonneg : 0 ≤ f u := hf_nonneg₂ u hu.1 refine ⟨?lb, ?ub⟩ case lb => calc c₁^p * (f x)^p = (c₁ * f x)^p := by rw [mul_rpow (le_of_lt hc₁_mem) hf_nonneg] _ ≤ _ := by gcongr; exact (hf₁ u hu).1 case ub => calc (f u)^p ≤ (c₂ * f x)^p := by gcongr; exact (hf₁ u hu).2 _ = _ := by rw [← mul_rpow (le_of_lt hc₂_mem) hf_nonneg] | inr hp => -- p < 0 match hf.eventually_atTop_zero_or_pos_or_neg with | .inl hzero => -- eventually zero refine ⟨1, by norm_num, 1, by norm_num, ?_⟩ filter_upwards [hzero, hfnew] with x hx hx' intro u hu simp only [hx, ne_eq, zero_rpow (ne_of_lt hp), mul_zero, le_refl, not_true, lt_self_iff_false, Set.Icc_self, Set.mem_singleton_iff] simp only [hx, mul_zero, Set.Icc_self, Set.mem_singleton_iff] at hx' rw [hx' u hu, zero_rpow (ne_of_lt hp)] | .inr (.inl hpos) => -- eventually positive refine ⟨c₂^p, hc₂p, ?_⟩ refine ⟨c₁^p, hc₁p, ?_⟩ filter_upwards [eventually_gt_atTop 0, hfnew, hpos, (tendsto_id.const_mul_atTop hb.1).eventually_forall_ge_atTop hpos] with x _ hf₁ hf_pos hf_pos₂ intro u hu refine ⟨?lb, ?ub⟩ case lb => calc c₂^p * (f x)^p = (c₂ * f x)^p := by rw [mul_rpow (le_of_lt hc₂_mem) (le_of_lt hf_pos)] _ ≤ _ := rpow_le_rpow_of_exponent_nonpos (hf_pos₂ u hu.1) (hf₁ u hu).2 (le_of_lt hp) case ub => calc (f u)^p ≤ (c₁ * f x)^p := by exact rpow_le_rpow_of_exponent_nonpos (by positivity) (hf₁ u hu).1 (le_of_lt hp) _ = _ := by rw [← mul_rpow (le_of_lt hc₁_mem) (le_of_lt hf_pos)] | .inr (.inr hneg) => -- eventually negative (which is impossible) have : ∀ᶠ (_ : ℝ) in atTop, False := by filter_upwards [hf_nonneg, hneg] with x hx hx'; linarith rw [Filter.eventually_false_iff_eq_bot] at this exact False.elim <| (atTop_neBot).ne this protected lemma GrowsPolynomially.pow (p : ℕ) (hf : GrowsPolynomially f) (hf_nonneg : ∀ᶠ x in atTop, 0 ≤ f x) : GrowsPolynomially fun x => (f x) ^ p := by simp_rw [← rpow_natCast] exact hf.rpow p hf_nonneg protected lemma GrowsPolynomially.zpow (p : ℤ) (hf : GrowsPolynomially f) (hf_nonneg : ∀ᶠ x in atTop, 0 ≤ f x) : GrowsPolynomially fun x => (f x) ^ p := by simp_rw [← rpow_intCast] exact hf.rpow p hf_nonneg lemma growsPolynomially_rpow (p : ℝ) : GrowsPolynomially fun x => x ^ p := (growsPolynomially_id).rpow p (eventually_ge_atTop 0) lemma growsPolynomially_pow (p : ℕ) : GrowsPolynomially fun x => x ^ p := (growsPolynomially_id).pow p (eventually_ge_atTop 0) lemma growsPolynomially_zpow (p : ℤ) : GrowsPolynomially fun x => x ^ p := (growsPolynomially_id).zpow p (eventually_ge_atTop 0) lemma growsPolynomially_log : GrowsPolynomially Real.log := by intro b hb have hb₀ : 0 < b := hb.1 refine ⟨1 / 2, by norm_num, ?_⟩ refine ⟨1, by norm_num, ?_⟩ have h_tendsto : Tendsto (fun x => 1 / 2 * Real.log x) atTop atTop := Tendsto.const_mul_atTop (by norm_num) Real.tendsto_log_atTop filter_upwards [eventually_gt_atTop 1, (tendsto_id.const_mul_atTop hb.1).eventually_forall_ge_atTop <| h_tendsto.eventually (eventually_gt_atTop (-Real.log b)) ] with x hx_pos hx intro u hu refine ⟨?lb, ?ub⟩ case lb => calc 1 / 2 * Real.log x = Real.log x + (-1 / 2) * Real.log x := by ring _ ≤ Real.log x + Real.log b := by gcongr rw [neg_div, neg_mul, ← neg_le] refine le_of_lt (hx x ?_) calc b * x ≤ 1 * x := by gcongr; exact le_of_lt hb.2 _ = x := by rw [one_mul] _ = Real.log (b * x) := by rw [← Real.log_mul (by positivity) (by positivity), mul_comm] _ ≤ Real.log u := by gcongr; exact hu.1 case ub => rw [one_mul] gcongr · calc 0 < b * x := by positivity _ ≤ u := by exact hu.1 · exact hu.2 lemma GrowsPolynomially.of_isTheta {f g : ℝ → ℝ} (hg : GrowsPolynomially g) (hf : f =Θ[atTop] g) (hf' : ∀ᶠ x in atTop, 0 ≤ f x) : GrowsPolynomially f := by intro b hb have hb_pos := hb.1 have hf_lb := isBigO_iff''.mp hf.isBigO_symm have hf_ub := isBigO_iff'.mp hf.isBigO obtain ⟨c₁, hc₁_pos : 0 < c₁, hf_lb⟩ := hf_lb obtain ⟨c₂, hc₂_pos : 0 < c₂, hf_ub⟩ := hf_ub have hg := hg.norm b hb obtain ⟨c₃, hc₃_pos : 0 < c₃, hg⟩ := hg obtain ⟨c₄, hc₄_pos : 0 < c₄, hg⟩ := hg have h_lb_pos : 0 < c₁ * c₂⁻¹ * c₃ := by positivity have h_ub_pos : 0 < c₂ * c₄ * c₁⁻¹ := by positivity refine ⟨c₁ * c₂⁻¹ * c₃, h_lb_pos, ?_⟩ refine ⟨c₂ * c₄ * c₁⁻¹, h_ub_pos, ?_⟩ have c₂_cancel : c₂⁻¹ * c₂ = 1 := inv_mul_cancel (by positivity) have c₁_cancel : c₁⁻¹ * c₁ = 1 := inv_mul_cancel (by positivity) filter_upwards [(tendsto_id.const_mul_atTop hb_pos).eventually_forall_ge_atTop hf', (tendsto_id.const_mul_atTop hb_pos).eventually_forall_ge_atTop hf_lb, (tendsto_id.const_mul_atTop hb_pos).eventually_forall_ge_atTop hf_ub, (tendsto_id.const_mul_atTop hb_pos).eventually_forall_ge_atTop hg, eventually_ge_atTop 0] with x hf_pos h_lb h_ub hg_bound hx_pos intro u hu have hbx : b * x ≤ x := calc b * x ≤ 1 * x := by gcongr; exact le_of_lt hb.2 _ = x := by rw [one_mul] have hg_bound := hg_bound x hbx refine ⟨?lb, ?ub⟩ case lb => calc c₁ * c₂⁻¹ * c₃ * f x ≤ c₁ * c₂⁻¹ * c₃ * (c₂ * ‖g x‖) := by rw [← Real.norm_of_nonneg (hf_pos x hbx)]; gcongr; exact h_ub x hbx _ = (c₂⁻¹ * c₂) * c₁ * (c₃ * ‖g x‖) := by ring _ = c₁ * (c₃ * ‖g x‖) := by simp [c₂_cancel] _ ≤ c₁ * ‖g u‖ := by gcongr; exact (hg_bound u hu).1 _ ≤ f u := by rw [← Real.norm_of_nonneg (hf_pos u hu.1)] exact h_lb u hu.1 case ub => calc f u ≤ c₂ * ‖g u‖ := by rw [← Real.norm_of_nonneg (hf_pos u hu.1)]; exact h_ub u hu.1 _ ≤ c₂ * (c₄ * ‖g x‖) := by gcongr; exact (hg_bound u hu).2 _ = c₂ * c₄ * (c₁⁻¹ * c₁) * ‖g x‖ := by simp [c₁_cancel]; ring _ = c₂ * c₄ * c₁⁻¹ * (c₁ * ‖g x‖) := by ring _ ≤ c₂ * c₄ * c₁⁻¹ * f x := by gcongr rw [← Real.norm_of_nonneg (hf_pos x hbx)] exact h_lb x hbx lemma GrowsPolynomially.of_isEquivalent {f g : ℝ → ℝ} (hg : GrowsPolynomially g) (hf : f ~[atTop] g) : GrowsPolynomially f := by have : f = g + (f - g) := by ext; simp rw [this] exact add_isLittleO hg hf lemma GrowsPolynomially.of_isEquivalent_const {f : ℝ → ℝ} {c : ℝ} (hf : f ~[atTop] fun _ => c) : GrowsPolynomially f := of_isEquivalent growsPolynomially_const hf end AkraBazziRecurrence
Condensed\Basic.lean
/- Copyright (c) 2023 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import Mathlib.CategoryTheory.Sites.Sheaf import Mathlib.Topology.Category.CompHaus.EffectiveEpi /-! # Condensed Objects This file defines the category of condensed objects in a category `C`, following the work of Clausen-Scholze and Barwick-Haine. ## Implementation Details We use the coherent Grothendieck topology on `CompHaus`, and define condensed objects in `C` to be `C`-valued sheaves, with respect to this Grothendieck topology. Note: Our definition more closely resembles "Pyknotic objects" in the sense of Barwick-Haine, as we do not impose cardinality bounds, and manage universes carefully instead. ## References - [barwickhaine2019]: *Pyknotic objects, I. Basic notions*, 2019. - [scholze2019condensed]: *Lectures on Condensed Mathematics*, 2019. -/ open CategoryTheory Limits open CategoryTheory universe u v w /-- `Condensed.{u} C` is the category of condensed objects in a category `C`, which are defined as sheaves on `CompHaus.{u}` with respect to the coherent Grothendieck topology. -/ def Condensed (C : Type w) [Category.{v} C] := Sheaf (coherentTopology CompHaus.{u}) C instance {C : Type w} [Category.{v} C] : Category (Condensed.{u} C) := show Category (Sheaf _ _) from inferInstance /-- Condensed sets (types) with the appropriate universe levels, i.e. `Type (u+1)`-valued sheaves on `CompHaus.{u}`. -/ abbrev CondensedSet := Condensed.{u} (Type (u+1)) namespace Condensed variable {C : Type w} [Category.{v} C] @[simp] lemma id_val (X : Condensed.{u} C) : (𝟙 X : X ⟶ X).val = 𝟙 _ := rfl @[simp] lemma comp_val {X Y Z : Condensed.{u} C} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g).val = f.val ≫ g.val := rfl @[ext] lemma hom_ext {X Y : Condensed.{u} C} (f g : X ⟶ Y) (h : ∀ S, f.val.app S = g.val.app S) : f = g := by apply Sheaf.hom_ext ext exact h _ end Condensed namespace CondensedSet -- Note: `simp` can prove this when stated for `Condensed C` for a concrete category `C`. -- However, it doesn't seem to see through the abbreviation `CondensedSet` @[simp] lemma hom_naturality_apply {X Y : CondensedSet.{u}} (f : X ⟶ Y) {S T : CompHausᵒᵖ} (g : S ⟶ T) (x : X.val.obj S) : f.val.app T (X.val.map g x) = Y.val.map g (f.val.app S x) := NatTrans.naturality_apply f.val g x end CondensedSet
Condensed\Epi.lean
/- Copyright (c) 2024 Dagur Asgeirsson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Dagur Asgeirsson -/ import Mathlib.CategoryTheory.ConcreteCategory.EpiMono import Mathlib.CategoryTheory.Sites.Coherent.LocallySurjective import Mathlib.CategoryTheory.Sites.EpiMono import Mathlib.Condensed.Equivalence import Mathlib.Condensed.Module /-! # Epimorphisms of condensed objects This file characterises epimorphisms of condensed sets and condensed `R`-modules for any ring `R`, as those morphisms which are objectwise surjective on `Stonean` (see `CondensedSet.epi_iff_surjective_on_stonean` and `CondensedMod.epi_iff_surjective_on_stonean`). -/ universe v u w u' v' open CategoryTheory Sheaf Opposite Limits Condensed ConcreteCategory attribute [local instance] ConcreteCategory.hasCoeToSort ConcreteCategory.instFunLike namespace Condensed variable (A : Type u') [Category.{v'} A] [ConcreteCategory.{v'} A] [HasFunctorialSurjectiveInjectiveFactorization A] variable {X Y : Condensed.{u} A} (f : X ⟶ Y) variable [(coherentTopology CompHaus).WEqualsLocallyBijective A] [HasSheafify (coherentTopology CompHaus) A] [(coherentTopology CompHaus.{u}).HasSheafCompose (CategoryTheory.forget A)] [Balanced (Sheaf (coherentTopology CompHaus) A)] [PreservesFiniteProducts (CategoryTheory.forget A)] in lemma epi_iff_locallySurjective_on_compHaus : Epi f ↔ ∀ (S : CompHaus) (y : Y.val.obj ⟨S⟩), (∃ (S' : CompHaus) (φ : S' ⟶ S) (_ : Function.Surjective φ) (x : X.val.obj ⟨S'⟩), f.val.app ⟨S'⟩ x = Y.val.map ⟨φ⟩ y) := by rw [← isLocallySurjective_iff_epi', coherentTopology.isLocallySurjective_iff, regularTopology.isLocallySurjective_iff] simp_rw [((CompHaus.effectiveEpi_tfae _).out 0 2 :)] variable [PreservesFiniteProducts (CategoryTheory.forget A)] [∀ (X : CompHausᵒᵖ), HasLimitsOfShape (StructuredArrow X Stonean.toCompHaus.op) A] [(extensiveTopology Stonean).WEqualsLocallyBijective A] [HasSheafify (extensiveTopology Stonean) A] [(extensiveTopology Stonean.{u}).HasSheafCompose (CategoryTheory.forget A)] [Balanced (Sheaf (extensiveTopology Stonean) A)] in lemma epi_iff_surjective_on_stonean : Epi f ↔ ∀ (S : Stonean), Function.Surjective (f.val.app (op S.compHaus)) := by rw [← (StoneanCompHaus.equivalence A).inverse.epi_map_iff_epi, ← Presheaf.coherentExtensiveEquivalence.functor.epi_map_iff_epi, ← isLocallySurjective_iff_epi'] exact extensiveTopology.isLocallySurjective_iff (D := A) _ end Condensed namespace CondensedSet variable {X Y : CondensedSet.{u}} (f : X ⟶ Y) lemma epi_iff_locallySurjective_on_compHaus : Epi f ↔ ∀ (S : CompHaus) (y : Y.val.obj ⟨S⟩), (∃ (S' : CompHaus) (φ : S' ⟶ S) (_ : Function.Surjective φ) (x : X.val.obj ⟨S'⟩), f.val.app ⟨S'⟩ x = Y.val.map ⟨φ⟩ y) := Condensed.epi_iff_locallySurjective_on_compHaus _ f lemma epi_iff_surjective_on_stonean : Epi f ↔ ∀ (S : Stonean), Function.Surjective (f.val.app (op S.compHaus)) := Condensed.epi_iff_surjective_on_stonean _ f end CondensedSet namespace CondensedMod variable (R : Type (u+1)) [Ring R] {X Y : CondensedMod.{u} R} (f : X ⟶ Y) lemma epi_iff_locallySurjective_on_compHaus : Epi f ↔ ∀ (S : CompHaus) (y : Y.val.obj ⟨S⟩), (∃ (S' : CompHaus) (φ : S' ⟶ S) (_ : Function.Surjective φ) (x : X.val.obj ⟨S'⟩), f.val.app ⟨S'⟩ x = Y.val.map ⟨φ⟩ y) := Condensed.epi_iff_locallySurjective_on_compHaus _ f lemma epi_iff_surjective_on_stonean : Epi f ↔ ∀ (S : Stonean), Function.Surjective (f.val.app (op S.compHaus)) := have : HasLimitsOfSize.{u, u+1} (ModuleCat R) := hasLimitsOfSizeShrink.{u, u+1, u+1, u+1} _ Condensed.epi_iff_surjective_on_stonean _ f end CondensedMod
Condensed\Equivalence.lean
/- Copyright (c) 2023 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz, Nick Kuhn, Dagur Asgeirsson -/ import Mathlib.Topology.Category.Profinite.EffectiveEpi import Mathlib.Topology.Category.Stonean.EffectiveEpi import Mathlib.Condensed.Basic import Mathlib.CategoryTheory.Sites.Coherent.SheafComparison /-! # Sheaves on CompHaus are equivalent to sheaves on Stonean The forgetful functor from extremally disconnected spaces `Stonean` to compact Hausdorff spaces `CompHaus` has the marvellous property that it induces an equivalence of categories between sheaves on these two sites. With the terminology of nLab, `Stonean` is a *dense subsite* of `CompHaus`: see https://ncatlab.org/nlab/show/dense+sub-site Since Stonean spaces are the projective objects in `CompHaus`, which has enough projectives, and the notions of effective epimorphism, epimorphism and surjective continuous map are equivalent in `CompHaus` and `Stonean`, we can use the general setup in `Mathlib.CategoryTheory.Sites.Coherent.SheafComparison` to deduce the equivalence of categories. We give the corresponding statements for `Profinite` as well. ## Main results * `Condensed.StoneanCompHaus.equivalence`: the equivalence from coherent sheaves on `Stonean` to coherent sheaves on `CompHaus` (i.e. condensed sets). * `Condensed.StoneanProfinite.equivalence`: the equivalence from coherent sheaves on `Stonean` to coherent sheaves on `Profinite`. * `Condensed.ProfiniteCompHaus.equivalence`: the equivalence from coherent sheaves on `Profinite` to coherent sheaves on `CompHaus` (i.e. condensed sets). -/ universe u open CategoryTheory Limits namespace Condensed namespace StoneanCompHaus /-- The equivalence from coherent sheaves on `Stonean` to coherent sheaves on `CompHaus` (i.e. condensed sets). -/ noncomputable def equivalence (A : Type*) [Category A] [∀ X, HasLimitsOfShape (StructuredArrow X Stonean.toCompHaus.op) A] : Sheaf (coherentTopology Stonean) A ≌ Condensed.{u} A := coherentTopology.equivalence' Stonean.toCompHaus A end StoneanCompHaus namespace StoneanProfinite instance : Stonean.toProfinite.PreservesEffectiveEpis where preserves f h := ((Profinite.effectiveEpi_tfae _).out 0 2).mpr (((Stonean.effectiveEpi_tfae _).out 0 2).mp h) instance : Stonean.toProfinite.ReflectsEffectiveEpis where reflects f h := ((Stonean.effectiveEpi_tfae f).out 0 2).mpr (((Profinite.effectiveEpi_tfae _).out 0 2).mp h) /-- An effective presentation of an `X : Profinite` with respect to the inclusion functor from `Stonean` -/ noncomputable def stoneanToProfiniteEffectivePresentation (X : Profinite) : Stonean.toProfinite.EffectivePresentation X where p := X.presentation f := Profinite.presentation.π X effectiveEpi := ((Profinite.effectiveEpi_tfae _).out 0 1).mpr (inferInstance : Epi _) instance : Stonean.toProfinite.EffectivelyEnough where presentation X := ⟨stoneanToProfiniteEffectivePresentation X⟩ /-- The equivalence from coherent sheaves on `Stonean` to coherent sheaves on `Profinite`. -/ noncomputable def equivalence (A : Type*) [Category A] [∀ X, HasLimitsOfShape (StructuredArrow X Stonean.toProfinite.op) A] : Sheaf (coherentTopology Stonean) A ≌ Sheaf (coherentTopology Profinite) A := coherentTopology.equivalence' Stonean.toProfinite A end StoneanProfinite namespace ProfiniteCompHaus /-- The equivalence from coherent sheaves on `Profinite` to coherent sheaves on `CompHaus` (i.e. condensed sets). -/ noncomputable def equivalence (A : Type*) [Category A] [∀ X, HasLimitsOfShape (StructuredArrow X profiniteToCompHaus.op) A] : Sheaf (coherentTopology Profinite) A ≌ Condensed.{u} A := coherentTopology.equivalence' profiniteToCompHaus A end ProfiniteCompHaus variable {A : Type*} [Category A] (X : Condensed.{u} A) lemma isSheafProfinite [∀ Y, HasLimitsOfShape (StructuredArrow Y profiniteToCompHaus.{u}.op) A] : Presheaf.IsSheaf (coherentTopology Profinite) (profiniteToCompHaus.op ⋙ X.val) := ((ProfiniteCompHaus.equivalence A).inverse.obj X).cond lemma isSheafStonean [∀ Y, HasLimitsOfShape (StructuredArrow Y Stonean.toCompHaus.{u}.op) A] : Presheaf.IsSheaf (coherentTopology Stonean) (Stonean.toCompHaus.op ⋙ X.val) := ((StoneanCompHaus.equivalence A).inverse.obj X).cond end Condensed
Condensed\Explicit.lean
/- Copyright (c) 2023 Dagur Asgeirsson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Dagur Asgeirsson, Riccardo Brasca, Filippo A. E. Nuccio -/ import Mathlib.Condensed.Module import Mathlib.Condensed.Equivalence /-! # The explicit sheaf condition for condensed sets We give the following three explicit descriptions of condensed objects: * `Condensed.ofSheafStonean`: A finite-product-preserving presheaf on `Stonean`. * `Condensed.ofSheafProfinite`: A finite-product-preserving presheaf on `Profinite`, satisfying `EqualizerCondition`. * `Condensed.ofSheafStonean`: A finite-product-preserving presheaf on `CompHaus`, satisfying `EqualizerCondition`. The property `EqualizerCondition` is defined in `Mathlib/CategoryTheory/Sites/RegularSheaves.lean` and it says that for any effective epi `X ⟶ B` (in this case that is equivalent to being a continuous surjection), the presheaf `F` exhibits `F(B)` as the equalizer of the two maps `F(X) ⇉ F(X ×_B X)` We also give variants for condensed objects in concrete categories whose forgetful functor reflects finite limits (resp. products), where it is enough to check the sheaf condition after postcomposing with the forgetful functor. -/ universe u open CategoryTheory Limits Opposite Functor Presheaf regularTopology namespace Condensed variable {A : Type*} [Category A] /-- The condensed object associated to a finite-product-preserving presheaf on `Stonean`. -/ noncomputable def ofSheafStonean [∀ X, HasLimitsOfShape (StructuredArrow X Stonean.toCompHaus.op) A] (F : Stonean.{u}ᵒᵖ ⥤ A) [PreservesFiniteProducts F] : Condensed A := StoneanCompHaus.equivalence A |>.functor.obj { val := F cond := by rw [isSheaf_iff_preservesFiniteProducts_of_projective F] exact ⟨⟨fun _ _ ↦ inferInstance⟩⟩ } /-- The condensed object associated to a presheaf on `Stonean` whose postcomposition with the forgetful functor preserves finite products. -/ noncomputable def ofSheafForgetStonean [∀ X, HasLimitsOfShape (StructuredArrow X Stonean.toCompHaus.op) A] [ConcreteCategory A] [ReflectsFiniteProducts (CategoryTheory.forget A)] (F : Stonean.{u}ᵒᵖ ⥤ A) [PreservesFiniteProducts (F ⋙ CategoryTheory.forget A)] : Condensed A := StoneanCompHaus.equivalence A |>.functor.obj { val := F cond := by apply isSheaf_coherent_of_projective_of_comp F (CategoryTheory.forget A) rw [isSheaf_iff_preservesFiniteProducts_of_projective] exact ⟨⟨fun _ _ ↦ inferInstance⟩⟩ } /-- The condensed object associated to a presheaf on `Profinite` which preserves finite products and satisfies the equalizer condition. -/ noncomputable def ofSheafProfinite [∀ X, HasLimitsOfShape (StructuredArrow X profiniteToCompHaus.op) A] (F : Profinite.{u}ᵒᵖ ⥤ A) [PreservesFiniteProducts F] (hF : EqualizerCondition F) : Condensed A := ProfiniteCompHaus.equivalence A |>.functor.obj { val := F cond := by rw [isSheaf_iff_preservesFiniteProducts_and_equalizerCondition F] exact ⟨⟨⟨fun _ _ ↦ inferInstance⟩⟩, hF⟩ } /-- The condensed object associated to a presheaf on `Profinite` whose postcomposition with the forgetful functor preserves finite products and satisfies the equalizer condition. -/ noncomputable def ofSheafForgetProfinite [∀ X, HasLimitsOfShape (StructuredArrow X profiniteToCompHaus.op) A] [ConcreteCategory A] [ReflectsFiniteLimits (CategoryTheory.forget A)] (F : Profinite.{u}ᵒᵖ ⥤ A) [PreservesFiniteProducts (F ⋙ CategoryTheory.forget A)] (hF : EqualizerCondition (F ⋙ CategoryTheory.forget A)) : Condensed A := ProfiniteCompHaus.equivalence A |>.functor.obj { val := F cond := by apply isSheaf_coherent_of_hasPullbacks_of_comp F (CategoryTheory.forget A) rw [isSheaf_iff_preservesFiniteProducts_and_equalizerCondition] exact ⟨⟨⟨fun _ _ ↦ inferInstance⟩⟩, hF⟩ } /-- The condensed object associated to a presheaf on `CompHaus` which preserves finite products and satisfies the equalizer condition. -/ noncomputable def ofSheafCompHaus (F : CompHaus.{u}ᵒᵖ ⥤ A) [PreservesFiniteProducts F] (hF : EqualizerCondition F) : Condensed A where val := F cond := by rw [isSheaf_iff_preservesFiniteProducts_and_equalizerCondition F] exact ⟨⟨⟨fun _ _ ↦ inferInstance⟩⟩, hF⟩ /-- The condensed object associated to a presheaf on `CompHaus` whose postcomposition with the forgetful functor preserves finite products and satisfies the equalizer condition. -/ noncomputable def ofSheafForgetCompHaus [ConcreteCategory A] [ReflectsFiniteLimits (CategoryTheory.forget A)] (F : CompHaus.{u}ᵒᵖ ⥤ A) [PreservesFiniteProducts (F ⋙ CategoryTheory.forget A)] (hF : EqualizerCondition (F ⋙ CategoryTheory.forget A)) : Condensed A where val := F cond := by apply isSheaf_coherent_of_hasPullbacks_of_comp F (CategoryTheory.forget A) rw [isSheaf_iff_preservesFiniteProducts_and_equalizerCondition] exact ⟨⟨⟨fun _ _ ↦ inferInstance⟩⟩, hF⟩ /-- A condensed object satisfies the equalizer condition. -/ theorem equalizerCondition (X : Condensed A) : EqualizerCondition X.val := isSheaf_iff_preservesFiniteProducts_and_equalizerCondition X.val |>.mp X.cond |>.2 /-- A condensed object preserves finite products. -/ noncomputable instance (X : Condensed A) : PreservesFiniteProducts X.val := isSheaf_iff_preservesFiniteProducts_and_equalizerCondition X.val |>.mp X.cond |>.1.some /-- A condensed object regarded as a sheaf on `Profinite` preserves finite products. -/ noncomputable instance (X : Sheaf (coherentTopology Profinite.{u}) A) : PreservesFiniteProducts X.val := isSheaf_iff_preservesFiniteProducts_and_equalizerCondition X.val |>.mp X.cond |>.1.some /-- A condensed object regarded as a sheaf on `Profinite` satisfies the equalizer condition. -/ theorem equalizerCondition_profinite (X : Sheaf (coherentTopology Profinite.{u}) A) : EqualizerCondition X.val := isSheaf_iff_preservesFiniteProducts_and_equalizerCondition X.val |>.mp X.cond |>.2 /-- A condensed object regarded as a sheaf on `Stonean` preserves finite products. -/ noncomputable instance (X : Sheaf (coherentTopology Stonean.{u}) A) : PreservesFiniteProducts X.val := isSheaf_iff_preservesFiniteProducts_of_projective X.val |>.mp X.cond |>.some end Condensed namespace CondensedSet /-- A `CondensedSet` version of `Condensed.ofSheafStonean`. -/ noncomputable abbrev ofSheafStonean (F : Stonean.{u}ᵒᵖ ⥤ Type (u+1)) [PreservesFiniteProducts F] : CondensedSet := Condensed.ofSheafStonean F /-- A `CondensedSet` version of `Condensed.ofSheafProfinite`. -/ noncomputable abbrev ofSheafProfinite (F : Profinite.{u}ᵒᵖ ⥤ Type (u+1)) [PreservesFiniteProducts F] (hF : EqualizerCondition F) : CondensedSet := Condensed.ofSheafProfinite F hF /-- A `CondensedSet` version of `Condensed.ofSheafCompHaus`. -/ noncomputable abbrev ofSheafCompHaus (F : CompHaus.{u}ᵒᵖ ⥤ Type (u+1)) [PreservesFiniteProducts F] (hF : EqualizerCondition F) : CondensedSet := Condensed.ofSheafCompHaus F hF end CondensedSet namespace CondensedMod variable (R : Type (u+1)) [Ring R] /-- A `CondensedMod` version of `Condensed.ofSheafStonean`. -/ noncomputable abbrev ofSheafStonean (F : Stonean.{u}ᵒᵖ ⥤ ModuleCat.{u+1} R) [PreservesFiniteProducts F] : CondensedMod R := haveI : HasLimitsOfSize.{u, u+1} (ModuleCat R) := hasLimitsOfSizeShrink.{u, u+1, u+1, u+1} _ Condensed.ofSheafStonean F /-- A `CondensedMod` version of `Condensed.ofSheafProfinite`. -/ noncomputable abbrev ofSheafProfinite (F : Profinite.{u}ᵒᵖ ⥤ ModuleCat.{u+1} R) [PreservesFiniteProducts F] (hF : EqualizerCondition F) : CondensedMod R := haveI : HasLimitsOfSize.{u, u+1} (ModuleCat R) := hasLimitsOfSizeShrink.{u, u+1, u+1, u+1} _ Condensed.ofSheafProfinite F hF /-- A `CondensedMod` version of `Condensed.ofSheafCompHaus`. -/ noncomputable abbrev ofSheafCompHaus (F : CompHaus.{u}ᵒᵖ ⥤ ModuleCat.{u+1} R) [PreservesFiniteProducts F] (hF : EqualizerCondition F) : CondensedMod R := Condensed.ofSheafCompHaus F hF end CondensedMod
Condensed\Functors.lean
/- Copyright (c) 2023 Dagur Asgeirsson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Dagur Asgeirsson -/ import Mathlib.CategoryTheory.Limits.Preserves.Ulift import Mathlib.CategoryTheory.Sites.Coherent.CoherentSheaves import Mathlib.CategoryTheory.Sites.Whiskering import Mathlib.Condensed.Basic import Mathlib.Topology.Category.Stonean.Basic /-! # Functors from categories of topological spaces to condensed sets This file defines the embedding of the test objects (compact Hausdorff spaces) into condensed sets. ## Main definitions * `compHausToCondensed : CompHaus.{u} ⥤ CondensedSet.{u}` is essentially the yoneda presheaf functor. We also define `profiniteToCondensed` and `stoneanToCondensed`. TODO (Dagur): * Define the analogues of `compHausToCondensed` for sheaves on `Profinite` and `Stonean` and provide the relevant isomorphisms with `profiniteToCondensed` and `stoneanToCondensed`. * Define the functor `Type (u+1) ⥤ CondensedSet.{u}` which takes a set `X` to the presheaf given by mapping a compact Hausdorff space `S` to `LocallyConstant S X`, along with the isomorphism with the functor that goes through `TopCat.{u+1}`. -/ universe u v open CategoryTheory Limits section Universes /-- Increase the size of the target category of condensed sets. -/ def Condensed.ulift : Condensed.{u} (Type u) ⥤ CondensedSet.{u} := sheafCompose (coherentTopology CompHaus) uliftFunctor.{u+1, u} instance : Condensed.ulift.Full := show (sheafCompose _ _).Full from inferInstance instance : Condensed.ulift.Faithful := show (sheafCompose _ _).Faithful from inferInstance end Universes section Topology /-- The functor from `CompHaus` to `Condensed.{u} (Type u)` given by the Yoneda sheaf. -/ def compHausToCondensed' : CompHaus.{u} ⥤ Condensed.{u} (Type u) := (coherentTopology.subcanonical CompHaus).yoneda /-- The yoneda presheaf as an actual condensed set. -/ def compHausToCondensed : CompHaus.{u} ⥤ CondensedSet.{u} := compHausToCondensed' ⋙ Condensed.ulift /-- Dot notation for the value of `compHausToCondensed`. -/ abbrev CompHaus.toCondensed (S : CompHaus.{u}) : CondensedSet.{u} := compHausToCondensed.obj S /-- The yoneda presheaf as a condensed set, restricted to profinite spaces. -/ def profiniteToCondensed : Profinite.{u} ⥤ CondensedSet.{u} := profiniteToCompHaus ⋙ compHausToCondensed /-- Dot notation for the value of `profiniteToCondensed`. -/ abbrev Profinite.toCondensed (S : Profinite.{u}) : CondensedSet.{u} := profiniteToCondensed.obj S /-- The yoneda presheaf as a condensed set, restricted to Stonean spaces. -/ def stoneanToCondensed : Stonean.{u} ⥤ CondensedSet.{u} := Stonean.toCompHaus ⋙ compHausToCondensed /-- Dot notation for the value of `stoneanToCondensed`. -/ abbrev Stonean.toCondensed (S : Stonean.{u}) : CondensedSet.{u} := stoneanToCondensed.obj S instance : compHausToCondensed'.Full := show (Sheaf.Subcanonical.yoneda _).Full from inferInstance instance : compHausToCondensed'.Faithful := show (Sheaf.Subcanonical.yoneda _).Faithful from inferInstance instance : compHausToCondensed.Full := show (_ ⋙ _).Full from inferInstance instance : compHausToCondensed.Faithful := show (_ ⋙ _).Faithful from inferInstance end Topology
Condensed\Limits.lean
/- Copyright (c) 2023 Dagur Asgeirsson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Dagur Asgeirsson -/ import Mathlib.Condensed.Module /-! # Limits in categories of condensed objects This file adds some instances for limits in condensed sets and condensed modules. -/ universe u open CategoryTheory Limits instance : HasLimits CondensedSet.{u} := by change HasLimits (Sheaf _ _) infer_instance instance : HasLimitsOfSize.{u, u + 1} CondensedSet.{u} := hasLimitsOfSizeShrink.{u, u+1, u+1, u} _ variable (R : Type (u+1)) [Ring R] instance : HasLimits (CondensedMod.{u} R) := by change HasLimits (Sheaf _ _) infer_instance instance : HasLimitsOfSize.{u, u + 1} (CondensedMod.{u} R) := hasLimitsOfSizeShrink.{u, u+1, u+1, u} _
Condensed\Module.lean
/- Copyright (c) 2024 Dagur Asgeirsson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Dagur Asgeirsson -/ import Mathlib.Algebra.Category.ModuleCat.Abelian import Mathlib.Algebra.Category.ModuleCat.Colimits import Mathlib.Algebra.Category.ModuleCat.FilteredColimits import Mathlib.Algebra.Category.ModuleCat.Adjunctions import Mathlib.CategoryTheory.Sites.Abelian import Mathlib.CategoryTheory.Sites.Adjunction import Mathlib.CategoryTheory.Sites.LeftExact import Mathlib.Condensed.Basic /-! # Condensed `R`-modules This files defines condensed modules over a ring `R`. ## Main results * Condensed `R`-modules form an abelian category. * The forgetful functor from condensed `R`-modules to condensed sets has a left adjoint, sending a condensed set to the corresponding *free* condensed `R`-module. -/ universe u open CategoryTheory variable (R : Type (u+1)) [Ring R] /-- The category of condensed `R`-modules, defined as sheaves of `R`-modules over `CompHaus` with respect to the coherent Grothendieck topology. -/ abbrev CondensedMod := Condensed.{u} (ModuleCat.{u+1} R) noncomputable instance : Abelian (CondensedMod.{u} R) := sheafIsAbelian /-- The forgetful functor from condensed `R`-modules to condensed sets. -/ def Condensed.forget : CondensedMod R ⥤ CondensedSet := sheafCompose _ (CategoryTheory.forget _) /-- The left adjoint to the forgetful functor. The *free condensed `R`-module* on a condensed set. -/ noncomputable def Condensed.free : CondensedSet ⥤ CondensedMod R := Sheaf.composeAndSheafify _ (ModuleCat.free R) /-- The condensed version of the free-forgetful adjunction. -/ noncomputable def Condensed.freeForgetAdjunction : free R ⊣ forget R := Sheaf.adjunction _ (ModuleCat.adj R) /-- The category of condensed abelian groups is defined as condensed `ℤ`-modules. -/ abbrev CondensedAb := CondensedMod.{u} (ULift ℤ) noncomputable example : Abelian CondensedAb.{u} := inferInstance /-- The forgetful functor from condensed abelian groups to condensed sets. -/ abbrev Condensed.abForget : CondensedAb ⥤ CondensedSet := forget _ /-- The free condensed abelian group on a condensed set. -/ noncomputable abbrev Condensed.freeAb : CondensedSet ⥤ CondensedAb := free _ /-- The free-forgetful adjunction for condensed abelian groups. -/ noncomputable abbrev Condensed.setAbAdjunction : freeAb ⊣ abForget := freeForgetAdjunction _ namespace CondensedMod -- Note: `simp` can prove this when stated for `Condensed C` for a concrete category `C`. -- However, it doesn't seem to see through the abbreviation `CondensedMod` @[simp] lemma hom_naturality_apply {X Y : CondensedMod.{u} R} (f : X ⟶ Y) {S T : CompHausᵒᵖ} (g : S ⟶ T) (x : X.val.obj S) : f.val.app T (X.val.map g x) = Y.val.map g (f.val.app S x) := NatTrans.naturality_apply f.val g x end CondensedMod
Condensed\Solid.lean
/- Copyright (c) 2023 Dagur Asgeirsson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Dagur Asgeirsson -/ import Mathlib.CategoryTheory.Functor.KanExtension.Pointwise import Mathlib.Condensed.Functors import Mathlib.Condensed.Limits /-! # Solid modules This file contains the definition of a solid `R`-module: `CondensedMod.isSolid R`. Solid modules groups were introduced in [scholze2019condensed], Definition 5.1. ## Main definition * `CondensedMod.IsSolid R`: the predicate on condensed `R`-modules describing the property of being solid. TODO (hard): prove that `((profiniteSolid ℤ).obj S).IsSolid` for `S : Profinite`. TODO (slightly easier): prove that `((profiniteSolid 𝔽ₚ).obj S).IsSolid` for `S : Profinite`. -/ universe u variable (R : Type (u+1)) [Ring R] open CategoryTheory Limits Profinite Condensed noncomputable section namespace Condensed /-- The free condensed abelian group on a finite set. -/ abbrev finFree : FintypeCat.{u} ⥤ CondensedMod.{u} R := FintypeCat.toProfinite ⋙ profiniteToCondensed ⋙ free R /-- The free condensed abelian group on a profinite space. -/ abbrev profiniteFree : Profinite.{u} ⥤ CondensedMod.{u} R := profiniteToCondensed ⋙ free R /-- The functor sending a profinite space `S` to the condensed abelian group `R[S]^\solid`. -/ def profiniteSolid : Profinite.{u} ⥤ CondensedMod.{u} R := Functor.rightKanExtension FintypeCat.toProfinite (finFree R) /-- The natural transformation `FintypeCat.toProfinite ⋙ profiniteSolid R ⟶ finFree R` which is part of the assertion that `profiniteSolid R` is the (pointwise) right Kan extension of `finFree R` along `FintypeCat.toProfinite`. -/ def profiniteSolidCounit : FintypeCat.toProfinite ⋙ profiniteSolid R ⟶ finFree R := Functor.rightKanExtensionCounit FintypeCat.toProfinite (finFree R) instance : (profiniteSolid R).IsRightKanExtension (profiniteSolidCounit R) := by dsimp only [profiniteSolidCounit, profiniteSolid] infer_instance /-- The functor `Profinite.{u} ⥤ CondensedMod.{u} R` is a pointwise right Kan extension of `finFree R : FintypeCat.{u} ⥤ CondensedMod.{u} R` along `FintypeCat.toProfinite`. -/ def profiniteSolidIsPointwiseRightKanExtension : (Functor.RightExtension.mk _ (profiniteSolidCounit R)).IsPointwiseRightKanExtension := Functor.isPointwiseRightKanExtensionOfIsRightKanExtension _ _ /-- The natural transformation `R[S] ⟶ R[S]^\solid`. -/ def profiniteSolidification : profiniteFree R ⟶ profiniteSolid.{u} R := (profiniteSolid R).liftOfIsRightKanExtension (profiniteSolidCounit R) _ (𝟙 _) end Condensed /-- The predicate on condensed abelian groups describing the property of being solid. -/ class CondensedMod.IsSolid (A : CondensedMod.{u} R) : Prop where isIso_solidification_map : ∀ X : Profinite.{u}, IsIso ((yoneda.obj A).map ((profiniteSolidification R).app X).op)
Condensed\TopCatAdjunction.lean
/- Copyright (c) 2024 Dagur Asgeirsson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Dagur Asgeirsson -/ import Mathlib.Condensed.TopComparison import Mathlib.Topology.Category.CompactlyGenerated /-! # The adjunction between condensed sets and topological spaces This file defines the functor `condensedSetToTopCat : CondensedSet.{u} ⥤ TopCat.{u+1}` which is left adjoint to `topCatToCondensedSet : TopCat.{u+1} ⥤ CondensedSet.{u}`. We prove that the counit is bijective (but not in general an isomorphism) and conclude that the right adjoint is faithful. The counit is an isomorphism for compactly generated spaces, and we conclude that the functor `topCatToCondensedSet` is fully faithful when restricted to compactly generated spaces. -/ universe u open Condensed CondensedSet CategoryTheory attribute [local instance] ConcreteCategory.instFunLike variable (X : CondensedSet.{u}) /-- Auxiliary definition to define the topology on `X(*)` for a condensed set `X`. -/ private def _root_.CompHaus.const (S : CompHaus.{u}) (s : S) : CompHaus.of PUnit.{u+1} ⟶ S := ContinuousMap.const _ s /-- Auxiliary definition to define the topology on `X(*)` for a condensed set `X`. -/ private def CondensedSet.coinducingCoprod : (Σ (i : (S : CompHaus.{u}) × X.val.obj ⟨S⟩), i.fst) → X.val.obj ⟨CompHaus.of PUnit⟩ := fun ⟨⟨S, i⟩, s⟩ ↦ X.val.map (S.const s).op i /-- Let `X` be a condensed set. We define a topology on `X(*)` as the quotient topology of all the maps from compact Hausdorff `S` spaces to `X(*)`, corresponding to elements of `X(S)`. In other words, the topology coinduced by the map `CondensedSet.coinducingCoprod` above. -/ local instance : TopologicalSpace (X.val.obj ⟨CompHaus.of PUnit⟩) := TopologicalSpace.coinduced (coinducingCoprod X) inferInstance /-- The object part of the functor `CondensedSet ⥤ TopCat`  -/ def CondensedSet.toTopCat : TopCat.{u+1} := TopCat.of (X.val.obj ⟨CompHaus.of PUnit⟩) namespace CondensedSet lemma continuous_coinducingCoprod {S : CompHaus.{u}} (x : X.val.obj ⟨S⟩) : Continuous fun a ↦ (X.coinducingCoprod ⟨⟨S, x⟩, a⟩) := by suffices ∀ (i : (T : CompHaus.{u}) × X.val.obj ⟨T⟩), Continuous (fun (a : i.fst) ↦ X.coinducingCoprod ⟨i, a⟩) from this ⟨_, _⟩ rw [← continuous_sigma_iff] apply continuous_coinduced_rng variable {X} {Y : CondensedSet} (f : X ⟶ Y) /-- The map part of the functor `CondensedSet ⥤ TopCat`  -/ @[simps] def toTopCatMap : X.toTopCat ⟶ Y.toTopCat where toFun := f.val.app ⟨CompHaus.of PUnit⟩ continuous_toFun := by rw [continuous_coinduced_dom] apply continuous_sigma intro ⟨S, x⟩ simp only [Function.comp_apply, coinducingCoprod] have : (fun (a : S) ↦ f.val.app ⟨CompHaus.of PUnit⟩ (X.val.map (S.const a).op x)) = (fun (a : S) ↦ Y.val.map (S.const a).op (f.val.app ⟨S⟩ x)) := funext fun a ↦ NatTrans.naturality_apply f.val (S.const a).op x rw [this] exact continuous_coinducingCoprod Y _ end CondensedSet /-- The functor `CondensedSet ⥤ TopCat`  -/ @[simps] def condensedSetToTopCat : CondensedSet.{u} ⥤ TopCat.{u+1} where obj X := X.toTopCat map f := toTopCatMap f namespace CondensedSet /-- The counit of the adjunction `condensedSetToTopCat ⊣ topCatToCondensedSet` -/ @[simps] def topCatAdjunctionCounit (X : TopCat.{u+1}) : X.toCondensedSet.toTopCat ⟶ X where toFun x := x.1 PUnit.unit continuous_toFun := by rw [continuous_coinduced_dom] continuity /-- The counit of the adjunction `condensedSetToTopCat ⊣ topCatToCondensedSet` is always bijective, but not an isomorphism in general (the inverse isn't continuous unless `X` is compactly generated). -/ def topCatAdjunctionCounitEquiv (X : TopCat.{u+1}) : X.toCondensedSet.toTopCat ≃ X where toFun := topCatAdjunctionCounit X invFun x := ContinuousMap.const _ x left_inv _ := rfl right_inv _ := rfl lemma topCatAdjunctionCounit_bijective (X : TopCat.{u+1}) : Function.Bijective (topCatAdjunctionCounit X) := (topCatAdjunctionCounitEquiv X).bijective /-- The unit of the adjunction `condensedSetToTopCat ⊣ topCatToCondensedSet` -/ @[simps val_app val_app_apply] def topCatAdjunctionUnit (X : CondensedSet.{u}) : X ⟶ X.toTopCat.toCondensedSet where val := { app := fun S x ↦ { toFun := fun s ↦ X.val.map (S.unop.const s).op x continuous_toFun := by suffices ∀ (i : (T : CompHaus.{u}) × X.val.obj ⟨T⟩), Continuous (fun (a : i.fst) ↦ X.coinducingCoprod ⟨i, a⟩) from this ⟨_, _⟩ rw [← continuous_sigma_iff] apply continuous_coinduced_rng } naturality := fun _ _ _ ↦ by ext simp only [TopCat.toCondensedSet_val_obj, CompHausLike.compHausLikeToTop_obj, Opposite.op_unop, types_comp_apply, TopCat.toCondensedSet_val_map, ← FunctorToTypes.map_comp_apply] rfl } /-- The adjunction `condensedSetToTopCat ⊣ topCatToCondensedSet` -/ noncomputable def topCatAdjunction : condensedSetToTopCat.{u} ⊣ topCatToCondensedSet := Adjunction.mkOfUnitCounit { unit := { app := topCatAdjunctionUnit } counit := { app := topCatAdjunctionCounit } left_triangle := by ext Y change Y.val.map (𝟙 _) _ = _ simp } instance (X : TopCat) : Epi (topCatAdjunction.counit.app X) := by rw [TopCat.epi_iff_surjective] exact (topCatAdjunctionCounit_bijective _).2 instance : topCatToCondensedSet.Faithful := topCatAdjunction.faithful_R_of_epi_counit_app open CompactlyGenerated instance (X : CondensedSet.{u}) : UCompactlyGeneratedSpace.{u, u+1} X.toTopCat := by apply uCompactlyGeneratedSpace_of_continuous_maps intro Y _ f h rw [continuous_coinduced_dom, continuous_sigma_iff] exact fun ⟨S, s⟩ ↦ h S ⟨_, continuous_coinducingCoprod X _⟩ instance (X : CondensedSet.{u}) : UCompactlyGeneratedSpace.{u, u+1} (condensedSetToTopCat.obj X) := inferInstanceAs (UCompactlyGeneratedSpace.{u, u+1} X.toTopCat) /-- The functor from condensed sets to topological spaces lands in compactly generated spaces. -/ def condensedSetToCompactlyGenerated : CondensedSet.{u} ⥤ CompactlyGenerated.{u, u+1} where obj X := CompactlyGenerated.of (condensedSetToTopCat.obj X) map f := toTopCatMap f /-- The functor from topological spaces to condensed sets restricted to compactly generated spaces. -/ noncomputable def compactlyGeneratedToCondensedSet : CompactlyGenerated.{u, u+1} ⥤ CondensedSet.{u} := compactlyGeneratedToTop ⋙ topCatToCondensedSet /-- The adjunction `condensedSetToTopCat ⊣ topCatToCondensedSet` restricted to compactly generated spaces. -/ noncomputable def compactlyGeneratedAdjunction : condensedSetToCompactlyGenerated ⊣ compactlyGeneratedToCondensedSet := topCatAdjunction.restrictFullyFaithful (iC := 𝟭 _) (iD := compactlyGeneratedToTop) (Functor.FullyFaithful.id _) fullyFaithfulCompactlyGeneratedToTop (Iso.refl _) (Iso.refl _) /-- The counit of the adjunction `condensedSetToCompactlyGenerated ⊣ compactlyGeneratedToCondensedSet` is a homeomorphism. -/ def compactlyGeneratedAdjunctionCounitHomeo (X : TopCat.{u+1}) [UCompactlyGeneratedSpace.{u} X] : X.toCondensedSet.toTopCat ≃ₜ X where toEquiv := topCatAdjunctionCounitEquiv X continuous_toFun := (topCatAdjunctionCounit X).continuous continuous_invFun := by apply continuous_from_uCompactlyGeneratedSpace exact fun _ _ ↦ continuous_coinducingCoprod X.toCondensedSet _ /-- The counit of the adjunction `condensedSetToCompactlyGenerated ⊣ compactlyGeneratedToCondensedSet` is an isomorphism. -/ noncomputable def compactlyGeneratedAdjunctionCounitIso (X : CompactlyGenerated.{u, u+1}) : condensedSetToCompactlyGenerated.obj (compactlyGeneratedToCondensedSet.obj X) ≅ X := isoOfHomeo (compactlyGeneratedAdjunctionCounitHomeo X.toTop) instance : IsIso compactlyGeneratedAdjunction.counit := by rw [NatTrans.isIso_iff_isIso_app] intro X exact inferInstanceAs (IsIso (compactlyGeneratedAdjunctionCounitIso X).hom) /-- The functor from topological spaces to condensed sets restricted to compactly generated spaces is fully faithful. -/ noncomputable def fullyFaithfulCompactlyGeneratedToCondensedSet : compactlyGeneratedToCondensedSet.FullyFaithful := compactlyGeneratedAdjunction.fullyFaithfulROfIsIsoCounit end CondensedSet
Condensed\TopComparison.lean
/- Copyright (c) 2023 Dagur Asgeirsson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Dagur Asgeirsson -/ import Mathlib.CategoryTheory.Limits.Preserves.Opposites import Mathlib.Topology.Category.TopCat.Yoneda import Mathlib.Condensed.Explicit /-! # The functor from topological spaces to condensed sets This file builds on the API from the file `TopCat.Yoneda`. If the forgetful functor to `TopCat` has nice properties, like preserving pullbacks and finite coproducts, then this Yoneda presheaf satisfies the sheaf condition for the regular and extensive topologies respectively. We apply this API to `CompHaus` and define the functor `topCatToCondensedSet : TopCat.{u+1} ⥤ CondensedSet.{u}`. -/ universe w w' v u open CategoryTheory Opposite Limits regularTopology ContinuousMap variable {C : Type u} [Category.{v} C] (G : C ⥤ TopCat.{w}) (X : Type w') [TopologicalSpace X] /-- An auxiliary lemma to that allows us to use `QuotientMap.lift` in the proof of `equalizerCondition_yonedaPresheaf`. -/ theorem factorsThrough_of_pullbackCondition {Z B : C} {π : Z ⟶ B} [HasPullback π π] [PreservesLimit (cospan π π) G] {a : C(G.obj Z, X)} (ha : a ∘ (G.map (pullback.fst _ _)) = a ∘ (G.map (pullback.snd π π))) : Function.FactorsThrough a (G.map π) := by intro x y hxy let xy : G.obj (pullback π π) := (PreservesPullback.iso G π π).inv <| (TopCat.pullbackIsoProdSubtype (G.map π) (G.map π)).inv ⟨(x, y), hxy⟩ have ha' := congr_fun ha xy dsimp at ha' have h₁ : ∀ y, G.map (pullback.fst _ _) ((PreservesPullback.iso G π π).inv y) = pullback.fst (G.map π) (G.map π) y := by simp only [← PreservesPullback.iso_inv_fst]; intro y; rfl have h₂ : ∀ y, G.map (pullback.snd _ _) ((PreservesPullback.iso G π π).inv y) = pullback.snd (G.map π) (G.map π) y := by simp only [← PreservesPullback.iso_inv_snd]; intro y; rfl erw [h₁, h₂, TopCat.pullbackIsoProdSubtype_inv_fst_apply, TopCat.pullbackIsoProdSubtype_inv_snd_apply] at ha' simpa using ha' /-- If `G` preserves the relevant pullbacks and every effective epi in `C` is a quotient map (which is the case when `C` is `CompHaus` or `Profinite`), then `yonedaPresheaf` satisfies the equalizer condition which is required to be a sheaf for the regular topology. -/ theorem equalizerCondition_yonedaPresheaf [∀ (Z B : C) (π : Z ⟶ B) [EffectiveEpi π], PreservesLimit (cospan π π) G] (hq : ∀ (Z B : C) (π : Z ⟶ B) [EffectiveEpi π], QuotientMap (G.map π)) : EqualizerCondition (yonedaPresheaf G X) := by apply EqualizerCondition.mk intro Z B π _ _ refine ⟨fun a b h ↦ ?_, fun ⟨a, ha⟩ ↦ ?_⟩ · simp only [yonedaPresheaf, unop_op, Quiver.Hom.unop_op, Set.coe_setOf, MapToEqualizer, Set.mem_setOf_eq, Subtype.mk.injEq, comp, ContinuousMap.mk.injEq] at h simp only [yonedaPresheaf, unop_op] ext x obtain ⟨y, hy⟩ := (hq Z B π).surjective x rw [← hy] exact congr_fun h y · simp only [yonedaPresheaf, comp, unop_op, Quiver.Hom.unop_op, Set.mem_setOf_eq, ContinuousMap.mk.injEq] at ha simp only [yonedaPresheaf, comp, unop_op, Quiver.Hom.unop_op, Set.coe_setOf, MapToEqualizer, Set.mem_setOf_eq, Subtype.mk.injEq] simp only [yonedaPresheaf, unop_op] at a refine ⟨(hq Z B π).lift a (factorsThrough_of_pullbackCondition G X ha), ?_⟩ congr exact DFunLike.ext'_iff.mp ((hq Z B π).lift_comp a (factorsThrough_of_pullbackCondition G X ha)) /-- If `G` preserves finite coproducts (which is the case when `C` is `CompHaus`, `Profinite` or `Stonean`), then `yonedaPresheaf` preserves finite products, which is required to be a sheaf for the extensive topology. -/ noncomputable instance [PreservesFiniteCoproducts G] : PreservesFiniteProducts (yonedaPresheaf G X) := by change PreservesFiniteProducts (G.op ⋙ yonedaPresheaf' X) have h' : PreservesFiniteProducts (yonedaPresheaf' X) := inferInstance have h : PreservesFiniteProducts G.op := { preserves := fun J _ => by apply (config := { allowSynthFailures := true }) preservesLimitsOfShapeOp exact preservesColimitsOfShapeOfEquiv (Discrete.opposite J).symm _ } constructor intro J _ have := h.1 J have := h'.1 J exact compPreservesLimitsOfShape _ _ /-- Associate to a `(u+1)`-small topological space the corresponding condensed set, given by `yonedaPresheaf`. -/ @[simps! val_obj val_map] noncomputable def TopCat.toCondensedSet (X : TopCat.{u+1}) : CondensedSet.{u} := @CondensedSet.ofSheafCompHaus (yonedaPresheaf.{u, u+1, u, u+1} compHausToTop.{u} X) _ (by apply (config := { allowSynthFailures := true }) equalizerCondition_yonedaPresheaf compHausToTop.{u} X intro Z B π he rw [((CompHaus.effectiveEpi_tfae π).out 0 2 :)] at he apply QuotientMap.of_surjective_continuous he π.continuous ) /-- `TopCat.toCondensedSet` yields a functor from `TopCat.{u+1}` to `CondensedSet.{u}`. -/ @[simps] noncomputable def topCatToCondensedSet : TopCat.{u+1} ⥤ CondensedSet.{u} where obj X := X.toCondensedSet map f := ⟨⟨fun _ g ↦ f.comp g, by aesop⟩⟩
Condensed\Discrete\Basic.lean
/- Copyright (c) 2023 Dagur Asgeirsson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Dagur Asgeirsson -/ import Mathlib.CategoryTheory.Sites.ConstantSheaf import Mathlib.CategoryTheory.Sites.Equivalence import Mathlib.Condensed.Basic import Mathlib.Condensed.Light.Basic /-! # Discrete-underlying adjunction Given a category `C` with sheafification with respect to the coherent topology on compact Hausdorff spaces, we define a functor `C ⥤ Condensed C` which associates to an object of `C` the corresponding "discrete" condensed object (see `Condensed.discrete`). In `Condensed.discreteUnderlyingAdj` we prove that this functor is left adjoint to the forgetful functor from `Condensed C` to `C`. We also give the variant `LightCondensed.discreteUnderlyingAdj` for light condensed objects. -/ universe u v w open CategoryTheory Limits Opposite GrothendieckTopology namespace Condensed variable (C : Type w) [Category.{u+1} C] [HasWeakSheafify (coherentTopology CompHaus.{u}) C] /-- The discrete condensed object associated to an object of `C` is the constant sheaf at that object. -/ @[simps!] noncomputable def discrete : C ⥤ Condensed.{u} C := constantSheaf _ C /-- The underlying object of a condensed object in `C` is the condensed object evaluated at a point. This can be viewed as a sort of forgetful functor from `Condensed C` to `C` -/ @[simps!] noncomputable def underlying : Condensed.{u} C ⥤ C := (sheafSections _ _).obj ⟨CompHaus.of PUnit.{u+1}⟩ /-- Discreteness is left adjoint to the forgetful functor. When `C` is `Type*`, this is analogous to `TopCat.adj₁ : TopCat.discrete ⊣ forget TopCat`.   -/ noncomputable def discreteUnderlyingAdj : discrete C ⊣ underlying C := constantSheafAdj _ _ CompHaus.isTerminalPUnit end Condensed namespace LightCondensed variable (C : Type w) [Category.{u} C] [HasSheafify (coherentTopology LightProfinite.{u}) C] /-- The discrete light condensed object associated to an object of `C` is the constant sheaf at that object. -/ @[simps!] noncomputable def discrete : C ⥤ LightCondensed.{u} C := constantSheaf _ C /-- The underlying object of a condensed object in `C` is the light condensed object evaluated at a point. This can be viewed as a sort of forgetful functor from `LightCondensed C` to `C` -/ @[simps!] noncomputable def underlying : LightCondensed.{u} C ⥤ C := (sheafSections _ _).obj (op (LightProfinite.of PUnit)) /-- Discreteness is left adjoint to the forgetful functor. When `C` is `Type*`, this is analogous to `TopCat.adj₁ : TopCat.discrete ⊣ forget TopCat`.   -/ noncomputable def discreteUnderlyingAdj : discrete C ⊣ underlying C := constantSheafAdj _ _ CompHausLike.isTerminalPUnit end LightCondensed /-- A version of `LightCondensed.discrete` in the `LightCondSet` namespace -/ noncomputable abbrev LightCondSet.discrete := LightCondensed.discrete (Type u) /-- A version of `LightCondensed.underlying` in the `LightCondSet` namespace -/ noncomputable abbrev LightCondSet.underlying := LightCondensed.underlying (Type u) /-- A version of `LightCondensed.discrete_underlying_adj` in the `LightCondSet` namespace -/ noncomputable abbrev LightCondSet.discreteUnderlyingAdj : discrete ⊣ underlying := LightCondensed.discreteUnderlyingAdj _
Condensed\Light\Basic.lean
/- Copyright (c) 2023 Dagur Asgeirsson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Dagur Asgeirsson -/ import Mathlib.CategoryTheory.Sites.Sheaf import Mathlib.Topology.Category.LightProfinite.EffectiveEpi /-! # Light condensed objects This file defines the category of light condensed objects in a category `C`, following the work of Clausen-Scholze (see https://www.youtube.com/playlist?list=PLx5f8IelFRgGmu6gmL-Kf_Rl_6Mm7juZO). -/ universe u v w open CategoryTheory Limits /-- `LightCondensed.{u} C` is the category of light condensed objects in a category `C`, which are defined as sheaves on `LightProfinite.{u}` with respect to the coherent Grothendieck topology. -/ def LightCondensed (C : Type w) [Category.{v} C] := Sheaf (coherentTopology LightProfinite.{u}) C instance {C : Type w} [Category.{v} C] : Category (LightCondensed.{u} C) := show Category (Sheaf _ _) from inferInstance /-- Light condensed sets. Because `LightProfinite` is an essentially small category, we don't need the same universe bump as in `CondensedSet`. -/ abbrev LightCondSet := LightCondensed.{u} (Type u) namespace LightCondensed variable {C : Type w} [Category.{v} C] @[simp] lemma id_val (X : LightCondensed.{u} C) : (𝟙 X : X ⟶ X).val = 𝟙 _ := rfl @[simp] lemma comp_val {X Y Z : LightCondensed.{u} C} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g).val = f.val ≫ g.val := rfl @[ext] lemma hom_ext {X Y : LightCondensed.{u} C} (f g : X ⟶ Y) (h : ∀ S, f.val.app S = g.val.app S) : f = g := by apply Sheaf.hom_ext ext exact h _ end LightCondensed namespace LightCondSet -- Note: `simp` can prove this when stated for `LightCondensed C` for a concrete category `C`. -- However, it doesn't seem to see through the abbreviation `LightCondSet` @[simp] lemma hom_naturality_apply {X Y : LightCondSet.{u}} (f : X ⟶ Y) {S T : LightProfiniteᵒᵖ} (g : S ⟶ T) (x : X.val.obj S) : f.val.app T (X.val.map g x) = Y.val.map g (f.val.app S x) := NatTrans.naturality_apply f.val g x end LightCondSet
Condensed\Light\Epi.lean
/- Copyright (c) 2024 Dagur Asgeirsson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Dagur Asgeirsson -/ import Mathlib.CategoryTheory.ConcreteCategory.EpiMono import Mathlib.CategoryTheory.Sites.EpiMono import Mathlib.CategoryTheory.Sites.Coherent.LocallySurjective import Mathlib.Condensed.Light.Module /-! # Epimorphisms of light condensed objects This file characterises epimorphisms in light condensed sets and modules as the locally surjective morphisms. Here, the condition of locally surjective is phrased in terms of continuous surjections of light profinite sets. -/ universe v u w u' v' open CategoryTheory Sheaf Limits ConcreteCategory GrothendieckTopology attribute [local instance] ConcreteCategory.hasCoeToSort ConcreteCategory.instFunLike namespace LightCondensed variable (A : Type u') [Category.{v'} A] [ConcreteCategory.{w} A] [PreservesFiniteProducts (CategoryTheory.forget A)] variable {X Y : LightCondensed.{u} A} (f : X ⟶ Y) lemma isLocallySurjective_iff_locallySurjective_on_lightProfinite : IsLocallySurjective f ↔ ∀ (S : LightProfinite) (y : Y.val.obj ⟨S⟩), (∃ (S' : LightProfinite) (φ : S' ⟶ S) (_ : Function.Surjective φ) (x : X.val.obj ⟨S'⟩), f.val.app ⟨S'⟩ x = Y.val.map ⟨φ⟩ y) := by rw [coherentTopology.isLocallySurjective_iff, regularTopology.isLocallySurjective_iff] simp_rw [LightProfinite.effectiveEpi_iff_surjective] end LightCondensed namespace LightCondSet variable {X Y : LightCondSet.{u}} (f : X ⟶ Y) lemma epi_iff_locallySurjective_on_lightProfinite : Epi f ↔ ∀ (S : LightProfinite) (y : Y.val.obj ⟨S⟩), (∃ (S' : LightProfinite) (φ : S' ⟶ S) (_ : Function.Surjective φ) (x : X.val.obj ⟨S'⟩), f.val.app ⟨S'⟩ x = Y.val.map ⟨φ⟩ y) := by rw [← isLocallySurjective_iff_epi'] exact LightCondensed.isLocallySurjective_iff_locallySurjective_on_lightProfinite _ f end LightCondSet namespace LightCondMod variable (R : Type u) [Ring R] {X Y : LightCondMod.{u} R} (f : X ⟶ Y) lemma epi_iff_locallySurjective_on_lightProfinite : Epi f ↔ ∀ (S : LightProfinite) (y : Y.val.obj ⟨S⟩), (∃ (S' : LightProfinite) (φ : S' ⟶ S) (_ : Function.Surjective φ) (x : X.val.obj ⟨S'⟩), f.val.app ⟨S'⟩ x = Y.val.map ⟨φ⟩ y) := by rw [← isLocallySurjective_iff_epi'] exact LightCondensed.isLocallySurjective_iff_locallySurjective_on_lightProfinite _ f end LightCondMod
Condensed\Light\Explicit.lean
/- Copyright (c) 2023 Dagur Asgeirsson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Dagur Asgeirsson -/ import Mathlib.CategoryTheory.Sites.Coherent.SheafComparison import Mathlib.Condensed.Light.Module /-! # The explicit sheaf condition for light condensed sets We give explicit description of light condensed sets: * `LightCondensed.ofSheafLightProfinite`: A finite-product-preserving presheaf on `LightProfinite`, satisfying `EqualizerCondition`. The property `EqualizerCondition` is defined in `Mathlib/CategoryTheory/Sites/RegularExtensive.lean` and it says that for any effective epi `X ⟶ B` (in this case that is equivalent to being a continuous surjection), the presheaf `F` exhibits `F(B)` as the equalizer of the two maps `F(X) ⇉ F(X ×_B X)` We also give variants for light condensed objects in concrete categories whose forgetful functor reflects finite limits (resp. products), where it is enough to check the sheaf condition after postcomposing with the forgetful functor. -/ universe v u w open CategoryTheory Limits Opposite Functor Presheaf regularTopology variable {A : Type*} [Category A] namespace LightCondensed /-- The light condensed object associated to a presheaf on `LightProfinite` which preserves finite products and satisfies the equalizer condition. -/ @[simps] noncomputable def ofSheafLightProfinite (F : LightProfinite.{u}ᵒᵖ ⥤ A) [PreservesFiniteProducts F] (hF : EqualizerCondition F) : LightCondensed A where val := F cond := by rw [isSheaf_iff_preservesFiniteProducts_and_equalizerCondition F] exact ⟨⟨⟨fun _ _ ↦ inferInstance⟩⟩, hF⟩ /-- The light condensed object associated to a presheaf on `LightProfinite` whose postcomposition with the forgetful functor preserves finite products and satisfies the equalizer condition. -/ @[simps] noncomputable def ofSheafForgetLightProfinite [ConcreteCategory A] [ReflectsFiniteLimits (CategoryTheory.forget A)] (F : LightProfinite.{u}ᵒᵖ ⥤ A) [PreservesFiniteProducts (F ⋙ CategoryTheory.forget A)] (hF : EqualizerCondition (F ⋙ CategoryTheory.forget A)) : LightCondensed A where val := F cond := by apply isSheaf_coherent_of_hasPullbacks_of_comp F (CategoryTheory.forget A) rw [isSheaf_iff_preservesFiniteProducts_and_equalizerCondition] exact ⟨⟨⟨fun _ _ ↦ inferInstance⟩⟩, hF⟩ /-- A light condensed object satisfies the equalizer condition. -/ theorem equalizerCondition (X : LightCondensed A) : EqualizerCondition X.val := isSheaf_iff_preservesFiniteProducts_and_equalizerCondition X.val |>.mp X.cond |>.2 /-- A light condensed object preserves finite products. -/ noncomputable instance (X : LightCondensed A) : PreservesFiniteProducts X.val := isSheaf_iff_preservesFiniteProducts_and_equalizerCondition X.val |>.mp X.cond |>.1.some end LightCondensed namespace LightCondSet /-- A `LightCondSet` version of `LightCondensed.ofSheafLightProfinite`. -/ noncomputable abbrev ofSheafLightProfinite (F : LightProfinite.{u}ᵒᵖ ⥤ Type u) [PreservesFiniteProducts F] (hF : EqualizerCondition F) : LightCondSet := LightCondensed.ofSheafLightProfinite F hF end LightCondSet namespace LightCondMod variable (R : Type u) [Ring R] /-- A `LightCondAb` version of `LightCondensed.ofSheafLightProfinite`. -/ noncomputable abbrev ofSheafLightProfinite (F : LightProfinite.{u}ᵒᵖ ⥤ ModuleCat.{u} R) [PreservesFiniteProducts F] (hF : EqualizerCondition F) : LightCondMod.{u} R := LightCondensed.ofSheafLightProfinite F hF end LightCondMod namespace LightCondAb /-- A `LightCondAb` version of `LightCondensed.ofSheafLightProfinite`. -/ noncomputable abbrev ofSheafLightProfinite (F : LightProfiniteᵒᵖ ⥤ ModuleCat ℤ) [PreservesFiniteProducts F] (hF : EqualizerCondition F) : LightCondAb := LightCondMod.ofSheafLightProfinite ℤ F hF end LightCondAb
Condensed\Light\Functors.lean
/- Copyright (c) 2023 Dagur Asgeirsson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Dagur Asgeirsson -/ import Mathlib.CategoryTheory.Sites.Coherent.CoherentSheaves import Mathlib.Condensed.Light.Basic /-! # Functors from categories of topological spaces to light condensed sets This file defines the embedding of the test objects (light profinite sets) into light condensed sets. ## Main definitions * `lightProfiniteToLightCondSet : LightProfinite.{u} ⥤ LightCondSet.{u}`  is the yoneda presheaf functor. TODO (Dagur): * Define the functor `Type u ⥤ LightCondSet.{u}` which takes a set `X` to the presheaf given by mapping a light profinite space `S` to `LocallyConstant S X`, along with the isomorphism with the functor that goes through `TopCat.{u+1}`. -/ universe u v open CategoryTheory Limits /-- The functor from `LightProfinite.{u}` to `LightCondSet.{u}` given by the Yoneda sheaf. -/ def lightProfiniteToLightCondSet : LightProfinite.{u} ⥤ LightCondSet.{u} := (coherentTopology.subcanonical LightProfinite).yoneda /-- Dot notation for the value of `lightProfiniteToLightCondSet`. -/ abbrev LightProfinite.toCondensed (S : LightProfinite.{u}) : LightCondSet.{u} := lightProfiniteToLightCondSet.obj S /-- `lightProfiniteToLightCondSet` is fully faithful. -/ abbrev lightProfiniteToLightCondSetFullyFaithful : lightProfiniteToLightCondSet.FullyFaithful := Sheaf.Subcanonical.yonedaFullyFaithful _ instance : lightProfiniteToLightCondSet.Full := show (Sheaf.Subcanonical.yoneda _).Full from inferInstance instance : lightProfiniteToLightCondSet.Faithful := show (Sheaf.Subcanonical.yoneda _).Faithful from inferInstance
Condensed\Light\Module.lean
/- Copyright (c) 2024 Dagur Asgeirsson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Dagur Asgeirsson -/ import Mathlib.Algebra.Category.ModuleCat.Abelian import Mathlib.Algebra.Category.ModuleCat.Adjunctions import Mathlib.Algebra.Category.ModuleCat.Colimits import Mathlib.Algebra.Category.ModuleCat.FilteredColimits import Mathlib.CategoryTheory.Sites.Abelian import Mathlib.CategoryTheory.Sites.Adjunction import Mathlib.CategoryTheory.Sites.Equivalence import Mathlib.Condensed.Light.Basic /-! # Light condensed `R`-modules This files defines light condensed modules over a ring `R`. ## Main results * Light condensed `R`-modules form an abelian category. * The forgetful functor from light condensed `R`-modules to light condensed sets has a left adjoint, sending a light condensed set to the corresponding *free* light condensed `R`-module. -/ universe u open CategoryTheory variable (R : Type u) [Ring R] /-- The category of condensed `R`-modules, defined as sheaves of `R`-modules over `CompHaus` with respect to the coherent Grothendieck topology. -/ abbrev LightCondMod := LightCondensed.{u} (ModuleCat.{u} R) noncomputable instance : Abelian (LightCondMod.{u} R) := sheafIsAbelian /-- The forgetful functor from condensed `R`-modules to condensed sets. -/ def LightCondensed.forget : LightCondMod R ⥤ LightCondSet := sheafCompose _ (CategoryTheory.forget _) /-- The left adjoint to the forgetful functor. The *free condensed `R`-module* on a condensed set. -/ noncomputable def LightCondensed.free : LightCondSet ⥤ LightCondMod R := Sheaf.composeAndSheafify _ (ModuleCat.free R) /-- The condensed version of the free-forgetful adjunction. -/ noncomputable def LightCondensed.freeForgetAdjunction : free R ⊣ forget R := Sheaf.adjunction _ (ModuleCat.adj R) /-- The category of condensed abelian groups, defined as sheaves of abelian groups over `CompHaus` with respect to the coherent Grothendieck topology. -/ abbrev LightCondAb := LightCondMod ℤ noncomputable example : Abelian LightCondAb := inferInstance namespace LightCondMod -- Note: `simp` can prove this when stated for `LightCondensed C` for a concrete category `C`. -- However, it doesn't seem to see through the abbreviation `LightCondMod` @[simp] lemma hom_naturality_apply {X Y : LightCondMod.{u} R} (f : X ⟶ Y) {S T : LightProfiniteᵒᵖ} (g : S ⟶ T) (x : X.val.obj S) : f.val.app T (X.val.map g x) = Y.val.map g (f.val.app S x) := NatTrans.naturality_apply f.val g x end LightCondMod
Condensed\Light\TopCatAdjunction.lean
/- Copyright (c) 2024 Dagur Asgeirsson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Dagur Asgeirsson -/ import Mathlib.Condensed.Light.TopComparison import Mathlib.Topology.Category.Sequential import Mathlib.Topology.Category.LightProfinite.Sequence /-! # The adjunction between light condensed sets and topological spaces This file defines the functor `lightCondSetToTopCat : LightCondSet.{u} ⥤ TopCat.{u}` which is left adjoint to `topCatToLightCondSet : TopCat.{u} ⥤ LightCondSet.{u}`. We prove that the counit is bijective (but not in general an isomorphism) and conclude that the right adjoint is faithful. The counit is an isomorphism for sequential spaces, and we conclude that the functor `topCatToLightCondSet` is fully faithful when restricted to sequential spaces. -/ universe u open LightCondensed LightCondSet CategoryTheory LightProfinite attribute [local instance] ConcreteCategory.instFunLike namespace LightCondSet variable (X : LightCondSet.{u}) /-- Auxiliary definition to define the topology on `X(*)` for a light condensed set `X`. -/ private def _root_.LightProfinite.const (S : LightProfinite.{u}) (s : S) : LightProfinite.of PUnit.{u+1} ⟶ S := ContinuousMap.const _ s /-- Auxiliary definition to define the topology on `X(*)` for a light condensed set `X`. -/ private def coinducingCoprod : (Σ (i : (S : LightProfinite.{u}) × X.val.obj ⟨S⟩), i.fst) → X.val.obj ⟨LightProfinite.of PUnit⟩ := fun ⟨⟨S, i⟩, s⟩ ↦ X.val.map (S.const s).op i /-- Let `X` be a light condensed set. We define a topology on `X(*)` as the quotient topology of all the maps from light profinite sets `S` to `X(*)`, corresponding to elements of `X(S)`. In other words, the topology coinduced by the map `LightCondSet.coinducingCoprod` above. -/ local instance underlyingTopologicalSpace : TopologicalSpace (X.val.obj ⟨LightProfinite.of PUnit⟩) := TopologicalSpace.coinduced (coinducingCoprod X) inferInstance /-- The object part of the functor `LightCondSet ⥤ TopCat`  -/ def toTopCat : TopCat.{u} := TopCat.of (X.val.obj ⟨LightProfinite.of PUnit⟩) lemma continuous_coinducingCoprod {S : LightProfinite.{u}} (x : X.val.obj ⟨S⟩) : Continuous fun a ↦ (X.coinducingCoprod ⟨⟨S, x⟩, a⟩) := by suffices ∀ (i : (T : LightProfinite.{u}) × X.val.obj ⟨T⟩), Continuous (fun (a : i.fst) ↦ X.coinducingCoprod ⟨i, a⟩) from this ⟨_, _⟩ rw [← continuous_sigma_iff] apply continuous_coinduced_rng variable {X} {Y : LightCondSet} (f : X ⟶ Y) /-- The map part of the functor `LightCondSet ⥤ TopCat`  -/ @[simps] def toTopCatMap : X.toTopCat ⟶ Y.toTopCat where toFun := f.val.app ⟨LightProfinite.of PUnit⟩ continuous_toFun := by rw [continuous_coinduced_dom] apply continuous_sigma intro ⟨S, x⟩ simp only [Function.comp_apply, coinducingCoprod] have : (fun (a : S) ↦ f.val.app ⟨LightProfinite.of PUnit⟩ (X.val.map (S.const a).op x)) = (fun (a : S) ↦ Y.val.map (S.const a).op (f.val.app ⟨S⟩ x)) := funext fun a ↦ NatTrans.naturality_apply f.val (S.const a).op x rw [this] exact continuous_coinducingCoprod _ _ /-- The functor `LightCondSet ⥤ TopCat`  -/ @[simps] def _root_.lightCondSetToTopCat : LightCondSet.{u} ⥤ TopCat.{u} where obj X := X.toTopCat map f := toTopCatMap f /-- The counit of the adjunction `lightCondSetToTopCat ⊣ topCatToLightCondSet` -/ def topCatAdjunctionCounit (X : TopCat.{u}) : X.toLightCondSet.toTopCat ⟶ X where toFun x := x.1 PUnit.unit continuous_toFun := by rw [continuous_coinduced_dom] continuity /-- The counit of the adjunction `lightCondSetToTopCat ⊣ topCatToLightCondSet` is always bijective, but not an isomorphism in general (the inverse isn't continuous unless `X` is sequential). -/ def topCatAdjunctionCounitEquiv (X : TopCat.{u}) : X.toLightCondSet.toTopCat ≃ X where toFun := topCatAdjunctionCounit X invFun x := ContinuousMap.const _ x left_inv _ := rfl right_inv _ := rfl lemma topCatAdjunctionCounit_bijective (X : TopCat.{u}) : Function.Bijective (topCatAdjunctionCounit X) := (topCatAdjunctionCounitEquiv X).bijective /-- The unit of the adjunction `lightCondSetToTopCat ⊣ topCatToLightCondSet` -/ @[simps val_app val_app_apply] def topCatAdjunctionUnit (X : LightCondSet.{u}) : X ⟶ X.toTopCat.toLightCondSet where val := { app := fun S x ↦ { toFun := fun s ↦ X.val.map (S.unop.const s).op x continuous_toFun := by suffices ∀ (i : (T : LightProfinite.{u}) × X.val.obj ⟨T⟩), Continuous (fun (a : i.fst) ↦ X.coinducingCoprod ⟨i, a⟩) from this ⟨_, _⟩ rw [← continuous_sigma_iff] apply continuous_coinduced_rng } naturality := fun _ _ _ ↦ by ext simp only [types_comp_apply, ContinuousMap.coe_mk, TopCat.toLightCondSet_val_map, ContinuousMap.comp_apply, ← FunctorToTypes.map_comp_apply] rfl } /-- The adjunction `lightCondSetToTopCat ⊣ topCatToLightCondSet` -/ noncomputable def topCatAdjunction : lightCondSetToTopCat.{u} ⊣ topCatToLightCondSet := Adjunction.mkOfUnitCounit { unit := { app := topCatAdjunctionUnit } counit := { app := topCatAdjunctionCounit } left_triangle := by ext Y change Y.val.map (𝟙 _) _ = _ simp } instance (X : TopCat) : Epi (topCatAdjunction.counit.app X) := by rw [TopCat.epi_iff_surjective] exact (topCatAdjunctionCounit_bijective _).2 instance : topCatToLightCondSet.Faithful := topCatAdjunction.faithful_R_of_epi_counit_app open Sequential instance (X : LightCondSet.{u}) : SequentialSpace X.toTopCat := by apply SequentialSpace.coinduced instance (X : LightCondSet.{u}) : SequentialSpace (lightCondSetToTopCat.obj X) := inferInstanceAs (SequentialSpace X.toTopCat) /-- The functor from light condensed sets to topological spaces lands in sequential spaces. -/ def lightCondSetToSequential : LightCondSet.{u} ⥤ Sequential.{u} where obj X := Sequential.of (lightCondSetToTopCat.obj X) map f := toTopCatMap f /-- The functor from topological spaces to light condensed sets restricted to sequential spaces. -/ noncomputable def sequentialToLightCondSet : Sequential.{u} ⥤ LightCondSet.{u} := sequentialToTop ⋙ topCatToLightCondSet /-- The adjunction `lightCondSetToTopCat ⊣ topCatToLightCondSet` restricted to sequential spaces. -/ noncomputable def sequentialAdjunction : lightCondSetToSequential ⊣ sequentialToLightCondSet := topCatAdjunction.restrictFullyFaithful (iC := 𝟭 _) (iD := sequentialToTop) (Functor.FullyFaithful.id _) fullyFaithfulSequentialToTop (Iso.refl _) (Iso.refl _) /-- The counit of the adjunction `lightCondSetToSequential ⊣ sequentialToLightCondSet` is a homeomorphism. Note: for now, we only have `ℕ∪{∞}` as a light profinite set at universe level 0, which is why we can only prove this for `X : TopCat.{0}`. -/ def sequentialAdjunctionHomeo (X : TopCat.{0}) [SequentialSpace X] : X.toLightCondSet.toTopCat ≃ₜ X where toEquiv := topCatAdjunctionCounitEquiv X continuous_toFun := (topCatAdjunctionCounit X).continuous continuous_invFun := by apply SeqContinuous.continuous unfold SeqContinuous intro f p h let g := (topCatAdjunctionCounitEquiv X).invFun ∘ (OnePoint.continuousMapMkNat f p h) change Filter.Tendsto (fun n : ℕ ↦ g n) _ _ erw [← OnePoint.continuous_iff_from_nat] let x : X.toLightCondSet.val.obj ⟨(ℕ∪{∞})⟩ := OnePoint.continuousMapMkNat f p h exact continuous_coinducingCoprod X.toLightCondSet x /-- The counit of the adjunction `lightCondSetToSequential ⊣ sequentialToLightCondSet` is an isomorphism. Note: for now, we only have `ℕ∪{∞}` as a light profinite set at universe level 0, which is why we can only prove this for `X : Sequential.{0}`. -/ noncomputable def sequentialAdjunctionCounitIso (X : Sequential.{0}) : lightCondSetToSequential.obj (sequentialToLightCondSet.obj X) ≅ X := isoOfHomeo (sequentialAdjunctionHomeo X.toTop) instance : IsIso sequentialAdjunction.{0}.counit := by rw [NatTrans.isIso_iff_isIso_app] intro X exact inferInstanceAs (IsIso (sequentialAdjunctionCounitIso X).hom) /-- The functor from topological spaces to light condensed sets restricted to sequential spaces is fully faithful. Note: for now, we only have `ℕ∪{∞}` as a light profinite set at universe level 0, which is why we can only prove this for the functor `Sequential.{0} ⥤ LightCondSet.{0}`. -/ noncomputable def fullyFaithfulSequentialToLightCondSet : sequentialToLightCondSet.{0}.FullyFaithful := sequentialAdjunction.fullyFaithfulROfIsIsoCounit end LightCondSet
Condensed\Light\TopComparison.lean
/- Copyright (c) 2023 Dagur Asgeirsson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Dagur Asgeirsson -/ import Mathlib.Condensed.Light.Explicit import Mathlib.Condensed.TopComparison /-! # The functor from topological spaces to light condensed sets We define the functor `topCatToLightCondSet : TopCat.{u} ⥤ LightCondSet.{u}`. -/ universe w w' v u open CategoryTheory Opposite Limits regularTopology ContinuousMap /-- Associate to a `u`-small topological space the corresponding light condensed set, given by `yonedaPresheaf`. -/ @[simps! val_obj val_map] noncomputable def TopCat.toLightCondSet (X : TopCat.{u}) : LightCondSet.{u} := @LightCondSet.ofSheafLightProfinite (yonedaPresheaf LightProfinite.toTopCat.{u} X) _ (by apply equalizerCondition_yonedaPresheaf LightProfinite.toTopCat.{u} X intro Z B π he rw [LightProfinite.effectiveEpi_iff_surjective] at he apply QuotientMap.of_surjective_continuous he π.continuous) /-- `TopCat.toLightCondSet` yields a functor from `TopCat.{u}` to `LightCondSet.{u}`. -/ @[simps] noncomputable def topCatToLightCondSet : TopCat.{u} ⥤ LightCondSet.{u} where obj X := X.toLightCondSet map f := ⟨⟨fun _ g ↦ f.comp g, by aesop⟩⟩
Control\Applicative.lean
/- Copyright (c) 2017 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import Mathlib.Algebra.Group.Defs import Mathlib.Control.Functor /-! # `applicative` instances This file provides `Applicative` instances for concrete functors: * `id` * `Functor.comp` * `Functor.const` * `Functor.add_const` -/ universe u v w section Lemmas open Function variable {F : Type u → Type v} variable [Applicative F] [LawfulApplicative F] variable {α β γ σ : Type u} theorem Applicative.map_seq_map (f : α → β → γ) (g : σ → β) (x : F α) (y : F σ) : f <$> x <*> g <$> y = ((· ∘ g) ∘ f) <$> x <*> y := by simp [flip, functor_norm] theorem Applicative.pure_seq_eq_map' (f : α → β) : ((pure f : F (α → β)) <*> ·) = (f <$> ·) := by ext; simp [functor_norm] theorem Applicative.ext {F} : ∀ {A1 : Applicative F} {A2 : Applicative F} [@LawfulApplicative F A1] [@LawfulApplicative F A2], (∀ {α : Type u} (x : α), @Pure.pure _ A1.toPure _ x = @Pure.pure _ A2.toPure _ x) → (∀ {α β : Type u} (f : F (α → β)) (x : F α), @Seq.seq _ A1.toSeq _ _ f (fun _ => x) = @Seq.seq _ A2.toSeq _ _ f (fun _ => x)) → A1 = A2 | { toFunctor := F1, seq := s1, pure := p1, seqLeft := sl1, seqRight := sr1 }, { toFunctor := F2, seq := s2, pure := p2, seqLeft := sl2, seqRight := sr2 }, L1, L2, H1, H2 => by obtain rfl : @p1 = @p2 := by funext α x apply H1 obtain rfl : @s1 = @s2 := by funext α β f x exact H2 f (x Unit.unit) obtain ⟨seqLeft_eq1, seqRight_eq1, pure_seq1, -⟩ := L1 obtain ⟨seqLeft_eq2, seqRight_eq2, pure_seq2, -⟩ := L2 obtain rfl : F1 = F2 := by apply Functor.ext intros exact (pure_seq1 _ _).symm.trans (pure_seq2 _ _) congr <;> funext α β x y · exact (seqLeft_eq1 _ (y Unit.unit)).trans (seqLeft_eq2 _ _).symm · exact (seqRight_eq1 _ (y Unit.unit)).trans (seqRight_eq2 _ (y Unit.unit)).symm end Lemmas -- Porting note: we have a monad instance for `Id` but not `id`, mathport can't tell -- which one is intended instance : CommApplicative Id where commutative_prod _ _ := rfl namespace Functor namespace Comp open Function hiding comp open Functor variable {F : Type u → Type w} {G : Type v → Type u} variable [Applicative F] [Applicative G] variable [LawfulApplicative F] [LawfulApplicative G] variable {α β γ : Type v} theorem map_pure (f : α → β) (x : α) : (f <$> pure x : Comp F G β) = pure (f x) := Comp.ext <| by simp theorem seq_pure (f : Comp F G (α → β)) (x : α) : f <*> pure x = (fun g : α → β => g x) <$> f := Comp.ext <| by simp [(· ∘ ·), functor_norm] theorem seq_assoc (x : Comp F G α) (f : Comp F G (α → β)) (g : Comp F G (β → γ)) : g <*> (f <*> x) = @Function.comp α β γ <$> g <*> f <*> x := Comp.ext <| by simp [(· ∘ ·), functor_norm] theorem pure_seq_eq_map (f : α → β) (x : Comp F G α) : pure f <*> x = f <$> x := Comp.ext <| by simp [Applicative.pure_seq_eq_map', functor_norm] -- TODO: the first two results were handled by `control_laws_tac` in mathlib3 instance instLawfulApplicativeComp : LawfulApplicative (Comp F G) where seqLeft_eq := by intros; rfl seqRight_eq := by intros; rfl pure_seq := Comp.pure_seq_eq_map map_pure := Comp.map_pure seq_pure := Comp.seq_pure seq_assoc := Comp.seq_assoc -- Porting note: mathport wasn't aware of the new implicit parameter omission in these `fun` binders theorem applicative_id_comp {F} [AF : Applicative F] [LawfulApplicative F] : @instApplicativeComp Id F _ _ = AF := @Applicative.ext F _ _ (instLawfulApplicativeComp (F := Id)) _ (fun _ => rfl) (fun _ _ => rfl) theorem applicative_comp_id {F} [AF : Applicative F] [LawfulApplicative F] : @Comp.instApplicativeComp F Id _ _ = AF := @Applicative.ext F _ _ (instLawfulApplicativeComp (G := Id)) _ (fun _ => rfl) (fun f x => show id <$> f <*> x = f <*> x by rw [id_map]) open CommApplicative instance {f : Type u → Type w} {g : Type v → Type u} [Applicative f] [Applicative g] [CommApplicative f] [CommApplicative g] : CommApplicative (Comp f g) where commutative_prod _ _ := by simp! [map, Seq.seq] rw [commutative_map] simp only [mk, flip, seq_map_assoc, Function.comp, map_map] congr funext x y rw [commutative_map] congr end Comp end Functor open Functor @[functor_norm] theorem Comp.seq_mk {α β : Type w} {f : Type u → Type v} {g : Type w → Type u} [Applicative f] [Applicative g] (h : f (g (α → β))) (x : f (g α)) : Comp.mk h <*> Comp.mk x = Comp.mk ((· <*> ·) <$> h <*> x) := rfl -- Porting note: There is some awkwardness in the following definition now that we have `HMul`. instance {α} [One α] [Mul α] : Applicative (Const α) where pure _ := (1 : α) seq f x := (show α from f) * (show α from x Unit.unit) -- Porting note: `(· <*> ·)` needed to change to `Seq.seq` in the `simp`. -- Also, `simp` didn't close `refl` goals. instance {α} [Monoid α] : LawfulApplicative (Const α) where map_pure _ _ := rfl seq_pure _ _ := by simp only [Seq.seq, pure, mul_one]; rfl pure_seq _ _ := by simp only [Seq.seq, pure, one_mul]; rfl seqLeft_eq _ _ := by simp only [Seq.seq]; rfl seqRight_eq _ _ := by simp only [Seq.seq]; rfl seq_assoc _ _ _ := by simp only [Seq.seq, mul_assoc]; rfl instance {α} [Zero α] [Add α] : Applicative (AddConst α) where pure _ := (0 : α) seq f x := (show α from f) + (show α from x Unit.unit) instance {α} [AddMonoid α] : LawfulApplicative (AddConst α) where map_pure _ _ := rfl seq_pure _ _ := by simp only [Seq.seq, pure, add_zero]; rfl pure_seq _ _ := by simp only [Seq.seq, pure, zero_add]; rfl seqLeft_eq _ _ := by simp only [Seq.seq]; rfl seqRight_eq _ _ := by simp only [Seq.seq]; rfl seq_assoc _ _ _ := by simp only [Seq.seq, add_assoc]; rfl
Control\Basic.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 Mathlib.Control.Combinators import Mathlib.Logic.Function.Defs import Mathlib.Tactic.CasesM import Mathlib.Tactic.Attr.Core /-! Extends the theory on functors, applicatives and monads. -/ universe u v w variable {α β γ : Type u} section Functor variable {f : Type u → Type v} [Functor f] [LawfulFunctor f] @[functor_norm] theorem Functor.map_map (m : α → β) (g : β → γ) (x : f α) : g <$> m <$> x = (g ∘ m) <$> x := (comp_map _ _ _).symm -- order of implicits -- order of implicits end Functor section Applicative variable {F : Type u → Type v} [Applicative F] /-- A generalization of `List.zipWith` which combines list elements with an `Applicative`. -/ def zipWithM {α₁ α₂ φ : Type u} (f : α₁ → α₂ → F φ) : ∀ (_ : List α₁) (_ : List α₂), F (List φ) | x :: xs, y :: ys => (· :: ·) <$> f x y <*> zipWithM f xs ys | _, _ => pure [] /-- Like `zipWithM` but evaluates the result as it traverses the lists using `*>`. -/ def zipWithM' (f : α → β → F γ) : List α → List β → F PUnit | x :: xs, y :: ys => f x y *> zipWithM' f xs ys | [], _ => pure PUnit.unit | _, [] => pure PUnit.unit variable [LawfulApplicative F] @[simp] theorem pure_id'_seq (x : F α) : (pure fun x => x) <*> x = x := pure_id_seq x @[functor_norm] theorem seq_map_assoc (x : F (α → β)) (f : γ → α) (y : F γ) : x <*> f <$> y = (· ∘ f) <$> x <*> y := by simp only [← pure_seq] simp only [seq_assoc, Function.comp, seq_pure, ← comp_map] simp [pure_seq] @[functor_norm] theorem map_seq (f : β → γ) (x : F (α → β)) (y : F α) : f <$> (x <*> y) = (f ∘ ·) <$> x <*> y := by simp only [← pure_seq]; simp [seq_assoc] end Applicative section Monad variable {m : Type u → Type v} [Monad m] [LawfulMonad m] theorem map_bind (x : m α) {g : α → m β} {f : β → γ} : f <$> (x >>= g) = x >>= fun a => f <$> g a := by rw [← bind_pure_comp, bind_assoc]; simp [bind_pure_comp] theorem seq_bind_eq (x : m α) {g : β → m γ} {f : α → β} : f <$> x >>= g = x >>= g ∘ f := show bind (f <$> x) g = bind x (g ∘ f) by rw [← bind_pure_comp, bind_assoc] simp [pure_bind, Function.comp_def] -- order of implicits and `Seq.seq` has a lazily evaluated second argument using `Unit` @[functor_norm] theorem fish_pure {α β} (f : α → m β) : f >=> pure = f := by simp (config := { unfoldPartialApp := true }) only [(· >=> ·), functor_norm] @[functor_norm] theorem fish_pipe {α β} (f : α → m β) : pure >=> f = f := by simp (config := { unfoldPartialApp := true }) only [(· >=> ·), functor_norm] -- note: in Lean 3 `>=>` is left-associative, but in Lean 4 it is right-associative. @[functor_norm] theorem fish_assoc {α β γ φ} (f : α → m β) (g : β → m γ) (h : γ → m φ) : (f >=> g) >=> h = f >=> g >=> h := by simp (config := { unfoldPartialApp := true }) only [(· >=> ·), functor_norm] variable {β' γ' : Type v} variable {m' : Type v → Type w} [Monad m'] /-- Takes a value `β` and `List α` and accumulates pairs according to a monadic function `f`. Accumulation occurs from the right (i.e., starting from the tail of the list). -/ def List.mapAccumRM (f : α → β' → m' (β' × γ')) : β' → List α → m' (β' × List γ') | a, [] => pure (a, []) | a, x :: xs => do let (a', ys) ← List.mapAccumRM f a xs let (a'', y) ← f x a' pure (a'', y :: ys) /-- Takes a value `β` and `List α` and accumulates pairs according to a monadic function `f`. Accumulation occurs from the left (i.e., starting from the head of the list). -/ def List.mapAccumLM (f : β' → α → m' (β' × γ')) : β' → List α → m' (β' × List γ') | a, [] => pure (a, []) | a, x :: xs => do let (a', y) ← f a x let (a'', ys) ← List.mapAccumLM f a' xs pure (a'', y :: ys) end Monad section variable {m : Type u → Type u} [Monad m] [LawfulMonad m] theorem joinM_map_map {α β : Type u} (f : α → β) (a : m (m α)) : joinM (Functor.map f <$> a) = f <$> joinM a := by simp only [joinM, (· ∘ ·), id, ← bind_pure_comp, bind_assoc, map_bind, pure_bind] theorem joinM_map_joinM {α : Type u} (a : m (m (m α))) : joinM (joinM <$> a) = joinM (joinM a) := by simp only [joinM, (· ∘ ·), id, map_bind, ← bind_pure_comp, bind_assoc, pure_bind] @[simp] theorem joinM_map_pure {α : Type u} (a : m α) : joinM (pure <$> a) = a := by simp only [joinM, (· ∘ ·), id, map_bind, ← bind_pure_comp, bind_assoc, pure_bind, bind_pure] @[simp] theorem joinM_pure {α : Type u} (a : m α) : joinM (pure a) = a := LawfulMonad.pure_bind a id end section Alternative variable {F : Type → Type v} [Alternative F] -- [todo] add notation for `Functor.mapConst` and port `Functor.mapConstRev` /-- Returns `pure true` if the computation succeeds and `pure false` otherwise. -/ def succeeds {α} (x : F α) : F Bool := Functor.mapConst true x <|> pure false /-- Attempts to perform the computation, but fails silently if it doesn't succeed. -/ def tryM {α} (x : F α) : F Unit := Functor.mapConst () x <|> pure () /-- Attempts to perform the computation, and returns `none` if it doesn't succeed. -/ def try? {α} (x : F α) : F (Option α) := some <$> x <|> pure none @[simp] theorem guard_true {h : Decidable True} : @guard F _ True h = pure () := by simp [guard, if_pos] @[simp] theorem guard_false {h : Decidable False} : @guard F _ False h = failure := by simp [guard, if_neg not_false] end Alternative namespace Sum variable {e : Type v} /-- The monadic `bind` operation for `Sum`. -/ protected def bind {α β} : e ⊕ α → (α → e ⊕ β) → e ⊕ β | inl x, _ => inl x | inr x, f => f x -- incorrectly marked as a bad translation by mathport, so we do not mark with `ₓ`. instance : Monad (Sum.{v, u} e) where pure := @Sum.inr e bind := @Sum.bind e instance : LawfulFunctor (Sum.{v, u} e) := by constructor <;> intros <;> (try casesm Sum _ _) <;> rfl instance : LawfulMonad (Sum.{v, u} e) where seqRight_eq := by intros casesm Sum _ _ <;> casesm Sum _ _ <;> rfl seqLeft_eq := by intros casesm Sum _ _ <;> rfl pure_seq := by intros rfl bind_assoc := by intros casesm Sum _ _ <;> rfl pure_bind := by intros rfl bind_pure_comp := by intros casesm Sum _ _ <;> rfl bind_map := by intros casesm Sum _ _ <;> rfl end Sum /-- A `CommApplicative` functor `m` is a (lawful) applicative functor which behaves identically on `α × β` and `β × α`, so computations can occur in either order. -/ class CommApplicative (m : Type u → Type v) [Applicative m] extends LawfulApplicative m : Prop where /-- Computations performed first on `a : α` and then on `b : β` are equal to those performed in the reverse order. -/ commutative_prod : ∀ {α β} (a : m α) (b : m β), Prod.mk <$> a <*> b = (fun (b : β) a => (a, b)) <$> b <*> a open Functor variable {m} theorem CommApplicative.commutative_map {m : Type u → Type v} [h : Applicative m] [CommApplicative m] {α β γ} (a : m α) (b : m β) {f : α → β → γ} : f <$> a <*> b = flip f <$> b <*> a := calc f <$> a <*> b = (fun p : α × β => f p.1 p.2) <$> (Prod.mk <$> a <*> b) := by simp only [map_seq, map_map, Function.comp_def] _ = (fun b a => f a b) <$> b <*> a := by rw [@CommApplicative.commutative_prod m h] simp [seq_map_assoc, map_seq, seq_assoc, seq_pure, map_map, (· ∘ ·)]
Control\Bifunctor.lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import Mathlib.Control.Functor import Mathlib.Tactic.Common import Batteries.Data.Sum.Basic /-! # Functors with two arguments This file defines bifunctors. A bifunctor is a function `F : Type* → Type* → Type*` along with a bimap which turns `F α β`into `F α' β'` given two functions `α → α'` and `β → β'`. It further * respects the identity: `bimap id id = id` * composes in the obvious way: `(bimap f' g') ∘ (bimap f g) = bimap (f' ∘ f) (g' ∘ g)` ## Main declarations * `Bifunctor`: A typeclass for the bare bimap of a bifunctor. * `LawfulBifunctor`: A typeclass asserting this bimap respects the bifunctor laws. -/ universe u₀ u₁ u₂ v₀ v₁ v₂ open Function /-- Lawless bifunctor. This typeclass only holds the data for the bimap. -/ class Bifunctor (F : Type u₀ → Type u₁ → Type u₂) where bimap : ∀ {α α' β β'}, (α → α') → (β → β') → F α β → F α' β' export Bifunctor (bimap) /-- Bifunctor. This typeclass asserts that a lawless `Bifunctor` is lawful. -/ class LawfulBifunctor (F : Type u₀ → Type u₁ → Type u₂) [Bifunctor F] : Prop where id_bimap : ∀ {α β} (x : F α β), bimap id id x = x bimap_bimap : ∀ {α₀ α₁ α₂ β₀ β₁ β₂} (f : α₀ → α₁) (f' : α₁ → α₂) (g : β₀ → β₁) (g' : β₁ → β₂) (x : F α₀ β₀), bimap f' g' (bimap f g x) = bimap (f' ∘ f) (g' ∘ g) x export LawfulBifunctor (id_bimap bimap_bimap) attribute [higher_order bimap_id_id] id_bimap attribute [higher_order bimap_comp_bimap] bimap_bimap export LawfulBifunctor (bimap_id_id bimap_comp_bimap) variable {F : Type u₀ → Type u₁ → Type u₂} [Bifunctor F] namespace Bifunctor /-- Left map of a bifunctor. -/ abbrev fst {α α' β} (f : α → α') : F α β → F α' β := bimap f id /-- Right map of a bifunctor. -/ abbrev snd {α β β'} (f : β → β') : F α β → F α β' := bimap id f variable [LawfulBifunctor F] @[higher_order fst_id] theorem id_fst : ∀ {α β} (x : F α β), fst id x = x := @id_bimap _ _ _ @[higher_order snd_id] theorem id_snd : ∀ {α β} (x : F α β), snd id x = x := @id_bimap _ _ _ @[higher_order fst_comp_fst] theorem comp_fst {α₀ α₁ α₂ β} (f : α₀ → α₁) (f' : α₁ → α₂) (x : F α₀ β) : fst f' (fst f x) = fst (f' ∘ f) x := by simp [fst, bimap_bimap] @[higher_order fst_comp_snd] theorem fst_snd {α₀ α₁ β₀ β₁} (f : α₀ → α₁) (f' : β₀ → β₁) (x : F α₀ β₀) : fst f (snd f' x) = bimap f f' x := by simp [fst, bimap_bimap] @[higher_order snd_comp_fst] theorem snd_fst {α₀ α₁ β₀ β₁} (f : α₀ → α₁) (f' : β₀ → β₁) (x : F α₀ β₀) : snd f' (fst f x) = bimap f f' x := by simp [snd, bimap_bimap] @[higher_order snd_comp_snd] theorem comp_snd {α β₀ β₁ β₂} (g : β₀ → β₁) (g' : β₁ → β₂) (x : F α β₀) : snd g' (snd g x) = snd (g' ∘ g) x := by simp [snd, bimap_bimap] attribute [functor_norm] bimap_bimap comp_snd comp_fst snd_comp_snd snd_comp_fst fst_comp_snd fst_comp_fst bimap_comp_bimap bimap_id_id fst_id snd_id end Bifunctor open Functor instance Prod.bifunctor : Bifunctor Prod where bimap := @Prod.map instance Prod.lawfulBifunctor : LawfulBifunctor Prod where id_bimap _ := rfl bimap_bimap _ _ _ _ _ := rfl instance Bifunctor.const : Bifunctor Const where bimap f _ := f instance LawfulBifunctor.const : LawfulBifunctor Const where id_bimap _ := rfl bimap_bimap _ _ _ _ _ := rfl instance Bifunctor.flip : Bifunctor (flip F) where bimap {_α α' _β β'} f f' x := (bimap f' f x : F β' α') instance LawfulBifunctor.flip [LawfulBifunctor F] : LawfulBifunctor (flip F) where id_bimap := by simp [bimap, functor_norm] bimap_bimap := by simp [bimap, functor_norm] instance Sum.bifunctor : Bifunctor Sum where bimap := @Sum.map instance Sum.lawfulBifunctor : LawfulBifunctor Sum where id_bimap := by aesop bimap_bimap := by aesop open Bifunctor Functor instance (priority := 10) Bifunctor.functor {α} : Functor (F α) where map f x := snd f x instance (priority := 10) Bifunctor.lawfulFunctor [LawfulBifunctor F] {α} : LawfulFunctor (F α) where -- Porting note: `mapConst` is required to prove new theorem id_map := by simp [Functor.map, functor_norm] comp_map := by simp [Functor.map, functor_norm] map_const := by simp [mapConst, Functor.map] section Bicompl variable (G : Type* → Type u₀) (H : Type* → Type u₁) [Functor G] [Functor H] instance Function.bicompl.bifunctor : Bifunctor (bicompl F G H) where bimap {_α α' _β β'} f f' x := (bimap (map f) (map f') x : F (G α') (H β')) instance Function.bicompl.lawfulBifunctor [LawfulFunctor G] [LawfulFunctor H] [LawfulBifunctor F] : LawfulBifunctor (bicompl F G H) := by constructor <;> intros <;> simp [bimap, map_id, map_comp_map, functor_norm] end Bicompl section Bicompr variable (G : Type u₂ → Type*) [Functor G] instance Function.bicompr.bifunctor : Bifunctor (bicompr G F) where bimap {_α α' _β β'} f f' x := (map (bimap f f') x : G (F α' β')) instance Function.bicompr.lawfulBifunctor [LawfulFunctor G] [LawfulBifunctor F] : LawfulBifunctor (bicompr G F) := by constructor <;> intros <;> simp [bimap, functor_norm] end Bicompr
Control\Combinators.lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura -/ /-! # Monad combinators, as in Haskell's Control.Monad. -/ universe u v w def joinM {m : Type u → Type u} [Monad m] {α : Type u} (a : m (m α)) : m α := bind a id def when {m : Type → Type} [Monad m] (c : Prop) [Decidable c] (t : m Unit) : m Unit := ite c t (pure ()) def condM {m : Type → Type} [Monad m] {α : Type} (mbool : m Bool) (tm fm : m α) : m α := do let b ← mbool cond b tm fm def whenM {m : Type → Type} [Monad m] (c : m Bool) (t : m Unit) : m Unit := condM c t (return ()) export List (mapM mapM' filterM foldlM) namespace Monad def mapM := @List.mapM def mapM' := @List.mapM' def join := @joinM def filter := @filterM def foldl := @List.foldlM def cond := @condM def sequence {m : Type u → Type v} [Monad m] {α : Type u} : List (m α) → m (List α) | [] => return [] | h :: t => do let h' ← h let t' ← sequence t return (h' :: t') def sequence' {m : Type → Type u} [Monad m] {α : Type} : List (m α) → m Unit | [] => return () | h :: t => h *> sequence' t def whenb {m : Type → Type} [Monad m] (b : Bool) (t : m Unit) : m Unit := _root_.cond b t (return ()) def unlessb {m : Type → Type} [Monad m] (b : Bool) (t : m Unit) : m Unit := _root_.cond b (return ()) t end Monad
Control\EquivFunctor.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 Mathlib.Logic.Equiv.Defs import Mathlib.Tactic.Convert /-! # Functions functorial with respect to equivalences An `EquivFunctor` is a function from `Type → Type` equipped with the additional data of coherently mapping equivalences to equivalences. In categorical language, it is an endofunctor of the "core" of the category `Type`. -/ universe u₀ u₁ u₂ v₀ v₁ v₂ open Function /-- An `EquivFunctor` is only functorial with respect to equivalences. To construct an `EquivFunctor`, it suffices to supply just the function `f α → f β` from an equivalence `α ≃ β`, and then prove the functor laws. It's then a consequence that this function is part of an equivalence, provided by `EquivFunctor.mapEquiv`. -/ class EquivFunctor (f : Type u₀ → Type u₁) where /-- The action of `f` on isomorphisms. -/ map : ∀ {α β}, α ≃ β → f α → f β /-- `map` of `f` preserves the identity morphism. -/ map_refl' : ∀ α, map (Equiv.refl α) = @id (f α) := by rfl /-- `map` is functorial on equivalences. -/ map_trans' : ∀ {α β γ} (k : α ≃ β) (h : β ≃ γ), map (k.trans h) = map h ∘ map k := by rfl attribute [simp] EquivFunctor.map_refl' namespace EquivFunctor section variable (f : Type u₀ → Type u₁) [EquivFunctor f] {α β : Type u₀} (e : α ≃ β) /-- An `EquivFunctor` in fact takes every equiv to an equiv. -/ def mapEquiv : f α ≃ f β where toFun := EquivFunctor.map e invFun := EquivFunctor.map e.symm left_inv x := by convert (congr_fun (EquivFunctor.map_trans' e e.symm) x).symm simp right_inv y := by convert (congr_fun (EquivFunctor.map_trans' e.symm e) y).symm simp @[simp] theorem mapEquiv_apply (x : f α) : mapEquiv f e x = EquivFunctor.map e x := rfl theorem mapEquiv_symm_apply (y : f β) : (mapEquiv f e).symm y = EquivFunctor.map e.symm y := rfl @[simp] theorem mapEquiv_refl (α) : mapEquiv f (Equiv.refl α) = Equiv.refl (f α) := by ext; simp [mapEquiv] @[simp] theorem mapEquiv_symm : (mapEquiv f e).symm = mapEquiv f e.symm := Equiv.ext <| mapEquiv_symm_apply f e /-- The composition of `mapEquiv`s is carried over the `EquivFunctor`. For plain `Functor`s, this lemma is named `map_map` when applied or `map_comp_map` when not applied. -/ @[simp] theorem mapEquiv_trans {γ : Type u₀} (ab : α ≃ β) (bc : β ≃ γ) : (mapEquiv f ab).trans (mapEquiv f bc) = mapEquiv f (ab.trans bc) := Equiv.ext fun x => by simp [mapEquiv, map_trans'] end instance (priority := 100) ofLawfulFunctor (f : Type u₀ → Type u₁) [Functor f] [LawfulFunctor f] : EquivFunctor f where map {α β} e := Functor.map e map_refl' α := by ext apply LawfulFunctor.id_map map_trans' {α β γ} k h := by ext x apply LawfulFunctor.comp_map k h x theorem mapEquiv.injective (f : Type u₀ → Type u₁) [Applicative f] [LawfulApplicative f] {α β : Type u₀} (h : ∀ γ, Function.Injective (pure : γ → f γ)) : Function.Injective (@EquivFunctor.mapEquiv f _ α β) := fun e₁ e₂ H => Equiv.ext fun x => h β (by simpa [EquivFunctor.map] using Equiv.congr_fun H (pure x)) end EquivFunctor
Control\Fix.lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import Mathlib.Data.Part import Mathlib.Data.Nat.Find import Mathlib.Data.Nat.Upto import Mathlib.Data.Stream.Defs import Mathlib.Tactic.Common /-! # Fixed point This module defines a generic `fix` operator for defining recursive computations that are not necessarily well-founded or productive. An instance is defined for `Part`. ## Main definition * class `Fix` * `Part.fix` -/ universe u v variable {α : Type*} {β : α → Type*} /-- `Fix α` provides a `fix` operator to define recursive computation via the fixed point of function of type `α → α`. -/ class Fix (α : Type*) where /-- `fix f` represents the computation of a fixed point for `f`. -/ fix : (α → α) → α namespace Part open Part Nat Nat.Upto section Basic variable (f : (∀ a, Part (β a)) → (∀ a, Part (β a))) /-- A series of successive, finite approximation of the fixed point of `f`, defined by `approx f n = f^[n] ⊥`. The limit of this chain is the fixed point of `f`. -/ def Fix.approx : Stream' (∀ a, Part (β a)) | 0 => ⊥ | Nat.succ i => f (Fix.approx i) /-- loop body for finding the fixed point of `f` -/ def fixAux {p : ℕ → Prop} (i : Nat.Upto p) (g : ∀ j : Nat.Upto p, i < j → ∀ a, Part (β a)) : ∀ a, Part (β a) := f fun x : α => (assert ¬p i.val) fun h : ¬p i.val => g (i.succ h) (Nat.lt_succ_self _) x /-- The least fixed point of `f`. If `f` is a continuous function (according to complete partial orders), it satisfies the equations: 1. `fix f = f (fix f)` (is a fixed point) 2. `∀ X, f X ≤ X → fix f ≤ X` (least fixed point) -/ protected def fix (x : α) : Part (β x) := (Part.assert (∃ i, (Fix.approx f i x).Dom)) fun h => WellFounded.fix.{1} (Nat.Upto.wf h) (fixAux f) Nat.Upto.zero x open Classical in protected theorem fix_def {x : α} (h' : ∃ i, (Fix.approx f i x).Dom) : Part.fix f x = Fix.approx f (Nat.succ (Nat.find h')) x := by let p := fun i : ℕ => (Fix.approx f i x).Dom have : p (Nat.find h') := Nat.find_spec h' generalize hk : Nat.find h' = k replace hk : Nat.find h' = k + (@Upto.zero p).val := hk rw [hk] at this revert hk dsimp [Part.fix]; rw [assert_pos h']; revert this generalize Upto.zero = z; intro _this hk suffices ∀ x', WellFounded.fix (Part.fix.proof_1 f x h') (fixAux f) z x' = Fix.approx f (succ k) x' from this _ induction k generalizing z with | zero => intro x' rw [Fix.approx, WellFounded.fix_eq, fixAux] congr ext x : 1 rw [assert_neg] · rfl · rw [Nat.zero_add] at _this simpa only [not_not, Coe] | succ n n_ih => intro x' rw [Fix.approx, WellFounded.fix_eq, fixAux] congr ext : 1 have hh : ¬(Fix.approx f z.val x).Dom := by apply Nat.find_min h' rw [hk, Nat.succ_add_eq_add_succ] apply Nat.lt_of_succ_le apply Nat.le_add_left rw [succ_add_eq_add_succ] at _this hk rw [assert_pos hh, n_ih (Upto.succ z hh) _this hk] theorem fix_def' {x : α} (h' : ¬∃ i, (Fix.approx f i x).Dom) : Part.fix f x = none := by dsimp [Part.fix] rw [assert_neg h'] end Basic end Part namespace Part instance hasFix : Fix (Part α) := ⟨fun f => Part.fix (fun x u => f (x u)) ()⟩ end Part open Sigma namespace Pi instance Part.hasFix {β} : Fix (α → Part β) := ⟨Part.fix⟩ end Pi
Control\Fold.lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Sean Leather -/ import Mathlib.Algebra.Group.Opposite import Mathlib.Algebra.FreeMonoid.Basic import Mathlib.Control.Traversable.Instances import Mathlib.Control.Traversable.Lemmas import Mathlib.CategoryTheory.Endomorphism import Mathlib.CategoryTheory.Types import Mathlib.CategoryTheory.Category.KleisliCat import Mathlib.Tactic.AdaptationNote /-! # List folds generalized to `Traversable` Informally, we can think of `foldl` as a special case of `traverse` where we do not care about the reconstructed data structure and, in a state monad, we care about the final state. The obvious way to define `foldl` would be to use the state monad but it is nicer to reason about a more abstract interface with `foldMap` as a primitive and `foldMap_hom` as a defining property. ``` def foldMap {α ω} [One ω] [Mul ω] (f : α → ω) : t α → ω := ... lemma foldMap_hom (α β) [Monoid α] [Monoid β] (f : α →* β) (g : γ → α) (x : t γ) : f (foldMap g x) = foldMap (f ∘ g) x := ... ``` `foldMap` uses a monoid ω to accumulate a value for every element of a data structure and `foldMap_hom` uses a monoid homomorphism to substitute the monoid used by `foldMap`. The two are sufficient to define `foldl`, `foldr` and `toList`. `toList` permits the formulation of specifications in terms of operations on lists. Each fold function can be defined using a specialized monoid. `toList` uses a free monoid represented as a list with concatenation while `foldl` uses endofunctions together with function composition. The definition through monoids uses `traverse` together with the applicative functor `const m` (where `m` is the monoid). As an implementation, `const` guarantees that no resource is spent on reconstructing the structure during traversal. A special class could be defined for `foldable`, similarly to Haskell, but the author cannot think of instances of `foldable` that are not also `Traversable`. -/ universe u v open ULift CategoryTheory MulOpposite namespace Monoid variable {m : Type u → Type u} [Monad m] variable {α β : Type u} /-- For a list, foldl f x [y₀,y₁] reduces as follows: ``` calc foldl f x [y₀,y₁] = foldl f (f x y₀) [y₁] : rfl ... = foldl f (f (f x y₀) y₁) [] : rfl ... = f (f x y₀) y₁ : rfl ``` with ``` f : α → β → α x : α [y₀,y₁] : List β ``` We can view the above as a composition of functions: ``` ... = f (f x y₀) y₁ : rfl ... = flip f y₁ (flip f y₀ x) : rfl ... = (flip f y₁ ∘ flip f y₀) x : rfl ``` We can use traverse and const to construct this composition: ``` calc const.run (traverse (fun y ↦ const.mk' (flip f y)) [y₀,y₁]) x = const.run ((::) <$> const.mk' (flip f y₀) <*> traverse (fun y ↦ const.mk' (flip f y)) [y₁]) x ... = const.run ((::) <$> const.mk' (flip f y₀) <*> ( (::) <$> const.mk' (flip f y₁) <*> traverse (fun y ↦ const.mk' (flip f y)) [] )) x ... = const.run ((::) <$> const.mk' (flip f y₀) <*> ( (::) <$> const.mk' (flip f y₁) <*> pure [] )) x ... = const.run ( ((::) <$> const.mk' (flip f y₁) <*> pure []) ∘ ((::) <$> const.mk' (flip f y₀)) ) x ... = const.run ( const.mk' (flip f y₁) ∘ const.mk' (flip f y₀) ) x ... = const.run ( flip f y₁ ∘ flip f y₀ ) x ... = f (f x y₀) y₁ ``` And this is how `const` turns a monoid into an applicative functor and how the monoid of endofunctions define `Foldl`. -/ abbrev Foldl (α : Type u) : Type u := (End α)ᵐᵒᵖ def Foldl.mk (f : α → α) : Foldl α := op f def Foldl.get (x : Foldl α) : α → α := unop x @[simps] def Foldl.ofFreeMonoid (f : β → α → β) : FreeMonoid α →* Monoid.Foldl β where toFun xs := op <| flip (List.foldl f) (FreeMonoid.toList xs) map_one' := rfl map_mul' := by intros #adaptation_note /-- nightly-2024-03-16: simp was simp only [FreeMonoid.toList_mul, flip, unop_op, List.foldl_append, op_inj] -/ simp only [FreeMonoid.toList_mul, unop_op, List.foldl_append, op_inj, Function.flip_def, List.foldl_append] rfl abbrev Foldr (α : Type u) : Type u := End α def Foldr.mk (f : α → α) : Foldr α := f def Foldr.get (x : Foldr α) : α → α := x @[simps] def Foldr.ofFreeMonoid (f : α → β → β) : FreeMonoid α →* Monoid.Foldr β where toFun xs := flip (List.foldr f) (FreeMonoid.toList xs) map_one' := rfl map_mul' _ _ := funext fun _ => List.foldr_append _ _ _ _ abbrev foldlM (m : Type u → Type u) [Monad m] (α : Type u) : Type u := MulOpposite <| End <| KleisliCat.mk m α def foldlM.mk (f : α → m α) : foldlM m α := op f def foldlM.get (x : foldlM m α) : α → m α := unop x @[simps] def foldlM.ofFreeMonoid [LawfulMonad m] (f : β → α → m β) : FreeMonoid α →* Monoid.foldlM m β where toFun xs := op <| flip (List.foldlM f) (FreeMonoid.toList xs) map_one' := rfl map_mul' := by intros; apply unop_injective; funext; apply List.foldlM_append abbrev foldrM (m : Type u → Type u) [Monad m] (α : Type u) : Type u := End <| KleisliCat.mk m α def foldrM.mk (f : α → m α) : foldrM m α := f def foldrM.get (x : foldrM m α) : α → m α := x @[simps] def foldrM.ofFreeMonoid [LawfulMonad m] (f : α → β → m β) : FreeMonoid α →* Monoid.foldrM m β where toFun xs := flip (List.foldrM f) (FreeMonoid.toList xs) map_one' := rfl map_mul' := by intros; funext; apply List.foldrM_append end Monoid namespace Traversable open Monoid Functor section Defs variable {α β : Type u} {t : Type u → Type u} [Traversable t] def foldMap {α ω} [One ω] [Mul ω] (f : α → ω) : t α → ω := traverse (Const.mk' ∘ f) def foldl (f : α → β → α) (x : α) (xs : t β) : α := (foldMap (Foldl.mk ∘ flip f) xs).get x def foldr (f : α → β → β) (x : β) (xs : t α) : β := (foldMap (Foldr.mk ∘ f) xs).get x /-- Conceptually, `toList` collects all the elements of a collection in a list. This idea is formalized by `lemma toList_spec (x : t α) : toList x = foldMap FreeMonoid.mk x`. The definition of `toList` is based on `foldl` and `List.cons` for speed. It is faster than using `foldMap FreeMonoid.mk` because, by using `foldl` and `List.cons`, each insertion is done in constant time. As a consequence, `toList` performs in linear. On the other hand, `foldMap FreeMonoid.mk` creates a singleton list around each element and concatenates all the resulting lists. In `xs ++ ys`, concatenation takes a time proportional to `length xs`. Since the order in which concatenation is evaluated is unspecified, nothing prevents each element of the traversable to be appended at the end `xs ++ [x]` which would yield a `O(n²)` run time. -/ def toList : t α → List α := List.reverse ∘ foldl (flip List.cons) [] def length (xs : t α) : ℕ := down <| foldl (fun l _ => up <| l.down + 1) (up 0) xs variable {m : Type u → Type u} [Monad m] def foldlm (f : α → β → m α) (x : α) (xs : t β) : m α := (foldMap (foldlM.mk ∘ flip f) xs).get x def foldrm (f : α → β → m β) (x : β) (xs : t α) : m β := (foldMap (foldrM.mk ∘ f) xs).get x end Defs section ApplicativeTransformation variable {α β γ : Type u} open Function hiding const def mapFold [Monoid α] [Monoid β] (f : α →* β) : ApplicativeTransformation (Const α) (Const β) where app _ := f preserves_seq' := by intros; simp only [Seq.seq, map_mul] preserves_pure' := by intros; simp only [map_one, pure] theorem Free.map_eq_map (f : α → β) (xs : List α) : f <$> xs = (FreeMonoid.toList (FreeMonoid.map f (FreeMonoid.ofList xs))) := rfl theorem foldl.unop_ofFreeMonoid (f : β → α → β) (xs : FreeMonoid α) (a : β) : unop (Foldl.ofFreeMonoid f xs) a = List.foldl f a (FreeMonoid.toList xs) := rfl variable (m : Type u → Type u) [Monad m] [LawfulMonad m] variable {t : Type u → Type u} [Traversable t] [LawfulTraversable t] open LawfulTraversable theorem foldMap_hom [Monoid α] [Monoid β] (f : α →* β) (g : γ → α) (x : t γ) : f (foldMap g x) = foldMap (f ∘ g) x := calc f (foldMap g x) = f (traverse (Const.mk' ∘ g) x) := rfl _ = (mapFold f).app _ (traverse (Const.mk' ∘ g) x) := rfl _ = traverse ((mapFold f).app _ ∘ Const.mk' ∘ g) x := naturality (mapFold f) _ _ _ = foldMap (f ∘ g) x := rfl theorem foldMap_hom_free [Monoid β] (f : FreeMonoid α →* β) (x : t α) : f (foldMap FreeMonoid.of x) = foldMap (f ∘ FreeMonoid.of) x := foldMap_hom f _ x end ApplicativeTransformation section Equalities open LawfulTraversable open List (cons) variable {α β γ : Type u} variable {t : Type u → Type u} [Traversable t] [LawfulTraversable t] @[simp] theorem foldl.ofFreeMonoid_comp_of (f : α → β → α) : Foldl.ofFreeMonoid f ∘ FreeMonoid.of = Foldl.mk ∘ flip f := rfl @[simp] theorem foldr.ofFreeMonoid_comp_of (f : β → α → α) : Foldr.ofFreeMonoid f ∘ FreeMonoid.of = Foldr.mk ∘ f := rfl @[simp] theorem foldlm.ofFreeMonoid_comp_of {m} [Monad m] [LawfulMonad m] (f : α → β → m α) : foldlM.ofFreeMonoid f ∘ FreeMonoid.of = foldlM.mk ∘ flip f := by ext1 x #adaptation_note /-- nightly-2024-03-16: simp was simp only [foldlM.ofFreeMonoid, flip, MonoidHom.coe_mk, OneHom.coe_mk, Function.comp_apply, FreeMonoid.toList_of, List.foldlM_cons, List.foldlM_nil, bind_pure, foldlM.mk, op_inj] -/ simp only [foldlM.ofFreeMonoid, Function.flip_def, MonoidHom.coe_mk, OneHom.coe_mk, Function.comp_apply, FreeMonoid.toList_of, List.foldlM_cons, List.foldlM_nil, bind_pure, foldlM.mk, op_inj] rfl @[simp] theorem foldrm.ofFreeMonoid_comp_of {m} [Monad m] [LawfulMonad m] (f : β → α → m α) : foldrM.ofFreeMonoid f ∘ FreeMonoid.of = foldrM.mk ∘ f := by ext #adaptation_note /-- nightly-2024-03-16: simp was simp [(· ∘ ·), foldrM.ofFreeMonoid, foldrM.mk, flip] -/ simp [(· ∘ ·), foldrM.ofFreeMonoid, foldrM.mk, Function.flip_def] theorem toList_spec (xs : t α) : toList xs = FreeMonoid.toList (foldMap FreeMonoid.of xs) := Eq.symm <| calc FreeMonoid.toList (foldMap FreeMonoid.of xs) = FreeMonoid.toList (foldMap FreeMonoid.of xs).reverse.reverse := by simp only [List.reverse_reverse] _ = FreeMonoid.toList (List.foldr cons [] (foldMap FreeMonoid.of xs).reverse).reverse := by simp only [List.foldr_eta] _ = (unop (Foldl.ofFreeMonoid (flip cons) (foldMap FreeMonoid.of xs)) []).reverse := by #adaptation_note /-- nightly-2024-03-16: simp was simp [flip, List.foldr_reverse, Foldl.ofFreeMonoid, unop_op] -/ simp [Function.flip_def, List.foldr_reverse, Foldl.ofFreeMonoid, unop_op] _ = toList xs := by rw [foldMap_hom_free (Foldl.ofFreeMonoid (flip <| @cons α))] simp only [toList, foldl, List.reverse_inj, Foldl.get, foldl.ofFreeMonoid_comp_of, Function.comp_apply] theorem foldMap_map [Monoid γ] (f : α → β) (g : β → γ) (xs : t α) : foldMap g (f <$> xs) = foldMap (g ∘ f) xs := by simp only [foldMap, traverse_map, Function.comp] theorem foldl_toList (f : α → β → α) (xs : t β) (x : α) : foldl f x xs = List.foldl f x (toList xs) := by rw [← FreeMonoid.toList_ofList (toList xs), ← foldl.unop_ofFreeMonoid] simp only [foldl, toList_spec, foldMap_hom_free, foldl.ofFreeMonoid_comp_of, Foldl.get, FreeMonoid.ofList_toList] theorem foldr_toList (f : α → β → β) (xs : t α) (x : β) : foldr f x xs = List.foldr f x (toList xs) := by change _ = Foldr.ofFreeMonoid _ (FreeMonoid.ofList <| toList xs) _ rw [toList_spec, foldr, Foldr.get, FreeMonoid.ofList_toList, foldMap_hom_free, foldr.ofFreeMonoid_comp_of] theorem toList_map (f : α → β) (xs : t α) : toList (f <$> xs) = f <$> toList xs := by simp only [toList_spec, Free.map_eq_map, foldMap_hom, foldMap_map, FreeMonoid.ofList_toList, FreeMonoid.map_of, (· ∘ ·)] @[simp] theorem foldl_map (g : β → γ) (f : α → γ → α) (a : α) (l : t β) : foldl f a (g <$> l) = foldl (fun x y => f x (g y)) a l := by #adaptation_note /-- nightly-2024-03-16: simp was simp only [foldl, foldMap_map, (· ∘ ·), flip] -/ simp only [foldl, foldMap_map, (· ∘ ·), Function.flip_def] @[simp] theorem foldr_map (g : β → γ) (f : γ → α → α) (a : α) (l : t β) : foldr f a (g <$> l) = foldr (f ∘ g) a l := by simp only [foldr, foldMap_map, (· ∘ ·), flip] @[simp] theorem toList_eq_self {xs : List α} : toList xs = xs := by simp only [toList_spec, foldMap, traverse] induction xs with | nil => rfl | cons _ _ ih => (conv_rhs => rw [← ih]); rfl theorem length_toList {xs : t α} : length xs = List.length (toList xs) := by unfold length rw [foldl_toList] generalize toList xs = ys rw [← Nat.add_zero ys.length] generalize 0 = n induction' ys with _ _ ih generalizing n · simp · simp_arith [ih] variable {m : Type u → Type u} [Monad m] [LawfulMonad m] theorem foldlm_toList {f : α → β → m α} {x : α} {xs : t β} : foldlm f x xs = List.foldlM f x (toList xs) := calc foldlm f x xs _ = unop (foldlM.ofFreeMonoid f (FreeMonoid.ofList <| toList xs)) x := by simp only [foldlm, toList_spec, foldMap_hom_free (foldlM.ofFreeMonoid f), foldlm.ofFreeMonoid_comp_of, foldlM.get, FreeMonoid.ofList_toList] _ = List.foldlM f x (toList xs) := by simp [foldlM.ofFreeMonoid, unop_op, flip] theorem foldrm_toList (f : α → β → m β) (x : β) (xs : t α) : foldrm f x xs = List.foldrM f x (toList xs) := by change _ = foldrM.ofFreeMonoid f (FreeMonoid.ofList <| toList xs) x simp only [foldrm, toList_spec, foldMap_hom_free (foldrM.ofFreeMonoid f), foldrm.ofFreeMonoid_comp_of, foldrM.get, FreeMonoid.ofList_toList] @[simp] theorem foldlm_map (g : β → γ) (f : α → γ → m α) (a : α) (l : t β) : foldlm f a (g <$> l) = foldlm (fun x y => f x (g y)) a l := by #adaptation_note /-- nightly-2024-03-16: simp was simp only [foldlm, foldMap_map, (· ∘ ·), flip] -/ simp only [foldlm, foldMap_map, (· ∘ ·), Function.flip_def] @[simp] theorem foldrm_map (g : β → γ) (f : γ → α → m α) (a : α) (l : t β) : foldrm f a (g <$> l) = foldrm (f ∘ g) a l := by simp only [foldrm, foldMap_map, (· ∘ ·), flip] end Equalities end Traversable
Control\Functor.lean
/- Copyright (c) 2017 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import Mathlib.Control.Basic import Mathlib.Init.Set import Mathlib.Tactic.TypeStar import Batteries.Tactic.Lint /-! # Functors This module provides additional lemmas, definitions, and instances for `Functor`s. ## Main definitions * `Functor.Const α` is the functor that sends all types to `α`. * `Functor.AddConst α` is `Functor.Const α` but for when `α` has an additive structure. * `Functor.Comp F G` for functors `F` and `G` is the functor composition of `F` and `G`. * `Liftp` and `Liftr` respectively lift predicates and relations on a type `α` to `F α`. Terms of `F α` are considered to, in some sense, contain values of type `α`. ## Tags functor, applicative -/ universe u v w section Functor variable {F : Type u → Type v} variable {α β γ : Type u} variable [Functor F] [LawfulFunctor F] theorem Functor.map_id : (id <$> ·) = (id : F α → F α) := funext id_map theorem Functor.map_comp_map (f : α → β) (g : β → γ) : ((g <$> ·) ∘ (f <$> ·) : F α → F γ) = ((g ∘ f) <$> ·) := funext fun _ => (comp_map _ _ _).symm -- Porting note: was `apply funext <;> intro <;> rw [comp_map]` but `rw` failed? theorem Functor.ext {F} : ∀ {F1 : Functor F} {F2 : Functor F} [@LawfulFunctor F F1] [@LawfulFunctor F F2], (∀ (α β) (f : α → β) (x : F α), @Functor.map _ F1 _ _ f x = @Functor.map _ F2 _ _ f x) → F1 = F2 | ⟨m, mc⟩, ⟨m', mc'⟩, H1, H2, H => by cases show @m = @m' by funext α β f x; apply H congr funext α β have E1 := @map_const _ ⟨@m, @mc⟩ H1 have E2 := @map_const _ ⟨@m, @mc'⟩ H2 exact E1.trans E2.symm end Functor /-- Introduce `id` as a quasi-functor. (Note that where a lawful `Monad` or `Applicative` or `Functor` is needed, `Id` is the correct definition). -/ def id.mk {α : Sort u} : α → id α := id namespace Functor /-- `Const α` is the constant functor, mapping every type to `α`. When `α` has a monoid structure, `Const α` has an `Applicative` instance. (If `α` has an additive monoid structure, see `Functor.AddConst`.) -/ @[nolint unusedArguments] def Const (α : Type*) (_β : Type*) := α /-- `Const.mk` is the canonical map `α → Const α β` (the identity), and it can be used as a pattern to extract this value. -/ @[match_pattern] def Const.mk {α β} (x : α) : Const α β := x /-- `Const.mk'` is `Const.mk` but specialized to map `α` to `Const α PUnit`, where `PUnit` is the terminal object in `Type*`. -/ def Const.mk' {α} (x : α) : Const α PUnit := x /-- Extract the element of `α` from the `Const` functor. -/ def Const.run {α β} (x : Const α β) : α := x namespace Const protected theorem ext {α β} {x y : Const α β} (h : x.run = y.run) : x = y := h /-- The map operation of the `Const γ` functor. -/ @[nolint unusedArguments] protected def map {γ α β} (_f : α → β) (x : Const γ β) : Const γ α := x instance functor {γ} : Functor (Const γ) where map := @Const.map γ instance lawfulFunctor {γ} : LawfulFunctor (Const γ) := by constructor <;> intros <;> rfl instance {α β} [Inhabited α] : Inhabited (Const α β) := ⟨(default : α)⟩ end Const /-- `AddConst α` is a synonym for constant functor `Const α`, mapping every type to `α`. When `α` has an additive monoid structure, `AddConst α` has an `Applicative` instance. (If `α` has a multiplicative monoid structure, see `Functor.Const`.) -/ def AddConst (α : Type*) := Const α /-- `AddConst.mk` is the canonical map `α → AddConst α β`, which is the identity, where `AddConst α β = Const α β`. It can be used as a pattern to extract this value. -/ @[match_pattern] def AddConst.mk {α β} (x : α) : AddConst α β := x /-- Extract the element of `α` from the constant functor. -/ def AddConst.run {α β} : AddConst α β → α := id instance AddConst.functor {γ} : Functor (AddConst γ) := @Const.functor γ instance AddConst.lawfulFunctor {γ} : LawfulFunctor (AddConst γ) := @Const.lawfulFunctor γ instance {α β} [Inhabited α] : Inhabited (AddConst α β) := ⟨(default : α)⟩ /-- `Functor.Comp` is a wrapper around `Function.Comp` for types. It prevents Lean's type class resolution mechanism from trying a `Functor (Comp F id)` when `Functor F` would do. -/ def Comp (F : Type u → Type w) (G : Type v → Type u) (α : Type v) : Type w := F <| G α /-- Construct a term of `Comp F G α` from a term of `F (G α)`, which is the same type. Can be used as a pattern to extract a term of `F (G α)`. -/ @[match_pattern] def Comp.mk {F : Type u → Type w} {G : Type v → Type u} {α : Type v} (x : F (G α)) : Comp F G α := x /-- Extract a term of `F (G α)` from a term of `Comp F G α`, which is the same type. -/ def Comp.run {F : Type u → Type w} {G : Type v → Type u} {α : Type v} (x : Comp F G α) : F (G α) := x namespace Comp variable {F : Type u → Type w} {G : Type v → Type u} protected theorem ext {α} {x y : Comp F G α} : x.run = y.run → x = y := id instance {α} [Inhabited (F (G α))] : Inhabited (Comp F G α) := ⟨(default : F (G α))⟩ variable [Functor F] [Functor G] /-- The map operation for the composition `Comp F G` of functors `F` and `G`. -/ protected def map {α β : Type v} (h : α → β) : Comp F G α → Comp F G β | Comp.mk x => Comp.mk ((h <$> ·) <$> x) instance functor : Functor (Comp F G) where map := @Comp.map F G _ _ @[functor_norm] theorem map_mk {α β} (h : α → β) (x : F (G α)) : h <$> Comp.mk x = Comp.mk ((h <$> ·) <$> x) := rfl @[simp] protected theorem run_map {α β} (h : α → β) (x : Comp F G α) : (h <$> x).run = (h <$> ·) <$> x.run := rfl variable [LawfulFunctor F] [LawfulFunctor G] variable {α β γ : Type v} protected theorem id_map : ∀ x : Comp F G α, Comp.map id x = x | Comp.mk x => by simp only [Comp.map, id_map, id_map']; rfl -- Porting note: `rfl` wasn't needed in mathlib3 protected theorem comp_map (g' : α → β) (h : β → γ) : ∀ x : Comp F G α, Comp.map (h ∘ g') x = Comp.map h (Comp.map g' x) | Comp.mk x => by simp [Comp.map, Comp.mk, Functor.map_comp_map, functor_norm] -- Porting note: `Comp.mk` wasn't needed in mathlib3 instance lawfulFunctor : LawfulFunctor (Comp F G) where map_const := rfl id_map := Comp.id_map comp_map := Comp.comp_map -- Porting note: had to use switch to `Id` from `id` because this has the `Functor` instance. theorem functor_comp_id {F} [AF : Functor F] [LawfulFunctor F] : @Comp.functor F Id _ _ = AF := @Functor.ext F _ AF (Comp.lawfulFunctor (G := Id)) _ fun _ _ _ _ => rfl -- Porting note: had to use switch to `Id` from `id` because this has the `Functor` instance. theorem functor_id_comp {F} [AF : Functor F] [LawfulFunctor F] : @Comp.functor Id F _ _ = AF := @Functor.ext F _ AF (Comp.lawfulFunctor (F := Id)) _ fun _ _ _ _ => rfl end Comp namespace Comp open Function hiding comp open Functor variable {F : Type u → Type w} {G : Type v → Type u} variable [Applicative F] [Applicative G] /-- The `<*>` operation for the composition of applicative functors. -/ protected def seq {α β : Type v} : Comp F G (α → β) → (Unit → Comp F G α) → Comp F G β | Comp.mk f, g => match g () with | Comp.mk x => Comp.mk <| (· <*> ·) <$> f <*> x -- `ₓ` because the type of `Seq.seq` doesn't match `has_seq.seq` instance : Pure (Comp F G) := ⟨fun x => Comp.mk <| pure <| pure x⟩ instance : Seq (Comp F G) := ⟨fun f x => Comp.seq f x⟩ @[simp] protected theorem run_pure {α : Type v} : ∀ x : α, (pure x : Comp F G α).run = pure (pure x) | _ => rfl @[simp] protected theorem run_seq {α β : Type v} (f : Comp F G (α → β)) (x : Comp F G α) : (f <*> x).run = (· <*> ·) <$> f.run <*> x.run := rfl instance instApplicativeComp : Applicative (Comp F G) := { map := @Comp.map F G _ _, seq := @Comp.seq F G _ _ } end Comp variable {F : Type u → Type u} [Functor F] /-- If we consider `x : F α` to, in some sense, contain values of type `α`, predicate `Liftp p x` holds iff every value contained by `x` satisfies `p`. -/ def Liftp {α : Type u} (p : α → Prop) (x : F α) : Prop := ∃ u : F (Subtype p), Subtype.val <$> u = x /-- If we consider `x : F α` to, in some sense, contain values of type `α`, then `Liftr r x y` relates `x` and `y` iff (1) `x` and `y` have the same shape and (2) we can pair values `a` from `x` and `b` from `y` so that `r a b` holds. -/ def Liftr {α : Type u} (r : α → α → Prop) (x y : F α) : Prop := ∃ u : F { p : α × α // r p.fst p.snd }, (fun t : { p : α × α // r p.fst p.snd } => t.val.fst) <$> u = x ∧ (fun t : { p : α × α // r p.fst p.snd } => t.val.snd) <$> u = y /-- If we consider `x : F α` to, in some sense, contain values of type `α`, then `supp x` is the set of values of type `α` that `x` contains. -/ def supp {α : Type u} (x : F α) : Set α := { y : α | ∀ ⦃p⦄, Liftp p x → p y } theorem of_mem_supp {α : Type u} {x : F α} {p : α → Prop} (h : Liftp p x) : ∀ y ∈ supp x, p y := fun _ hy => hy h /-- If `f` is a functor, if `fb : f β` and `a : α`, then `mapConstRev fb a` is the result of applying `f.map` to the constant function `β → α` sending everything to `a`, and then evaluating at `fb`. In other words it's `const a <$> fb`. -/ abbrev mapConstRev {f : Type u → Type v} [Functor f] {α β : Type u} : f β → α → f α := fun a b => Functor.mapConst b a /-- If `f` is a functor, if `fb : f β` and `a : α`, then `mapConstRev fb a` is the result of applying `f.map` to the constant function `β → α` sending everything to `a`, and then evaluating at `fb`. In other words it's `const a <$> fb`. -/ infix:100 " $> " => Functor.mapConstRev end Functor
Control\Lawful.lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ import Mathlib.Tactic.Basic /-! # Functor Laws, applicative laws, and monad Laws -/ universe u v namespace StateT section variable {σ : Type u} variable {m : Type u → Type v} variable {α : Type u} /- Porting note: In Lean 4, `StateT` doesn't require a constructor, but it appears confusing to declare the following theorem as a simp theorem. ```lean @[simp] theorem run_fun (f : σ → m (α × σ)) (st : σ) : StateT.run (fun s => f s) st = f st := rfl ``` If we declare this theorem as a simp theorem, `StateT.run f st` is simplified to `f st` by eta reduction. This breaks the structure of `StateT`. So, we declare a constructor-like definition `StateT.mk` and a simp theorem for it. -/ protected def mk (f : σ → m (α × σ)) : StateT σ m α := f @[simp] theorem run_mk (f : σ → m (α × σ)) (st : σ) : StateT.run (StateT.mk f) st = f st := rfl -- Porting note: `StateT.adapt` is removed. end end StateT namespace ExceptT variable {α β ε : Type u} {m : Type u → Type v} (x : ExceptT ε m α) -- Porting note: This is proven by proj reduction in Lean 3. @[simp] theorem run_mk (x : m (Except ε α)) : ExceptT.run (ExceptT.mk x) = x := rfl attribute [simp] run_bind @[simp] theorem run_monadLift {n} [Monad m] [MonadLiftT n m] (x : n α) : (monadLift x : ExceptT ε m α).run = Except.ok <$> (monadLift x : m α) := rfl @[simp] theorem run_monadMap {n} [MonadFunctorT n m] (f : ∀ {α}, n α → n α) : (monadMap (@f) x : ExceptT ε m α).run = monadMap (@f) x.run := rfl end ExceptT namespace ReaderT section variable {ρ : Type u} variable {m : Type u → Type v} variable {α σ : Type u} /- Porting note: In Lean 4, `ReaderT` doesn't require a constructor, but it appears confusing to declare the following theorem as a simp theorem. ```lean @[simp] theorem run_fun (f : σ → m α) (r : σ) : ReaderT.run (fun r' => f r') r = f r := rfl ``` If we declare this theorem as a simp theorem, `ReaderT.run f st` is simplified to `f st` by eta reduction. This breaks the structure of `ReaderT`. So, we declare a constructor-like definition `ReaderT.mk` and a simp theorem for it. -/ protected def mk (f : σ → m α) : ReaderT σ m α := f @[simp] theorem run_mk (f : σ → m α) (r : σ) : ReaderT.run (ReaderT.mk f) r = f r := rfl end end ReaderT namespace OptionT variable {α β : Type u} {m : Type u → Type v} (x : OptionT m α) @[ext] theorem ext {x x' : OptionT m α} (h : x.run = x'.run) : x = x' := h -- Porting note: This is proven by proj reduction in Lean 3. @[simp] theorem run_mk (x : m (Option α)) : OptionT.run (OptionT.mk x) = x := rfl section Monad variable [Monad m] @[simp] theorem run_pure (a) : (pure a : OptionT m α).run = pure (some a) := rfl @[simp] theorem run_bind (f : α → OptionT m β) : (x >>= f).run = x.run >>= fun | some a => OptionT.run (f a) | none => pure none := rfl @[simp] theorem run_map (f : α → β) [LawfulMonad m] : (f <$> x).run = Option.map f <$> x.run := by rw [← bind_pure_comp _ x.run] change x.run >>= (fun | some a => OptionT.run (pure (f a)) | none => pure none) = _ apply bind_congr intro a; cases a <;> simp [Option.map, Option.bind] @[simp] theorem run_monadLift {n} [MonadLiftT n m] (x : n α) : (monadLift x : OptionT m α).run = (monadLift x : m α) >>= fun a => pure (some a) := rfl end Monad @[simp] theorem run_monadMap {n} [MonadFunctorT n m] (f : ∀ {α}, n α → n α) : (monadMap (@f) x : OptionT m α).run = monadMap (@f) x.run := rfl end OptionT instance (m : Type u → Type v) [Monad m] [LawfulMonad m] : LawfulMonad (OptionT m) := LawfulMonad.mk' (id_map := by intros; apply OptionT.ext; simp only [OptionT.run_map] rw [map_congr, id_map] intro a; cases a <;> rfl) (bind_assoc := by intros; apply OptionT.ext; simp only [OptionT.run_bind, bind_assoc] rw [bind_congr] intro a; cases a <;> simp) (pure_bind := by intros; apply OptionT.ext; simp) /-! ### Lawfulness of `IO` At some point core intends to make `IO` opaque, which would break these proofs As discussed in https://github.com/leanprover/std4/pull/416, it should be possible for core to expose the lawfulness of `IO` as part of the opaque interface, which would remove the need for these proofs anyway. These are not in Batteries because Batteries does not want to deal with the churn from such a core refactor. -/ variable {ε σ : Type} instance : LawfulMonad (EIO ε) := inferInstanceAs <| LawfulMonad (EStateM _ _) instance : LawfulMonad BaseIO := inferInstanceAs <| LawfulMonad (EIO _) instance : LawfulMonad IO := inferInstance instance : LawfulMonad (EST ε σ) := inferInstanceAs <| LawfulMonad (EStateM _ _) instance : LawfulMonad (ST ε) := inferInstance
Control\LawfulFix.lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import Mathlib.Data.Stream.Init import Mathlib.Tactic.ApplyFun import Mathlib.Control.Fix import Mathlib.Order.OmegaCompletePartialOrder /-! # Lawful fixed point operators This module defines the laws required of a `Fix` instance, using the theory of omega complete partial orders (ωCPO). Proofs of the lawfulness of all `Fix` instances in `Control.Fix` are provided. ## Main definition * class `LawfulFix` -/ universe u v open scoped Classical variable {α : Type*} {β : α → Type*} open OmegaCompletePartialOrder /-- Intuitively, a fixed point operator `fix` is lawful if it satisfies `fix f = f (fix f)` for all `f`, but this is inconsistent / uninteresting in most cases due to the existence of "exotic" functions `f`, such as the function that is defined iff its argument is not, familiar from the halting problem. Instead, this requirement is limited to only functions that are `Continuous` in the sense of `ω`-complete partial orders, which excludes the example because it is not monotone (making the input argument less defined can make `f` more defined). -/ class LawfulFix (α : Type*) [OmegaCompletePartialOrder α] extends Fix α where fix_eq : ∀ {f : α →o α}, Continuous f → Fix.fix f = f (Fix.fix f) theorem LawfulFix.fix_eq' {α} [OmegaCompletePartialOrder α] [LawfulFix α] {f : α → α} (hf : Continuous' f) : Fix.fix f = f (Fix.fix f) := LawfulFix.fix_eq (hf.to_bundled _) namespace Part open Part Nat Nat.Upto namespace Fix variable (f : ((a : _) → Part <| β a) →o (a : _) → Part <| β a) theorem approx_mono' {i : ℕ} : Fix.approx f i ≤ Fix.approx f (succ i) := by induction i with | zero => dsimp [approx]; apply @bot_le _ _ _ (f ⊥) | succ _ i_ih => intro; apply f.monotone; apply i_ih theorem approx_mono ⦃i j : ℕ⦄ (hij : i ≤ j) : approx f i ≤ approx f j := by induction' j with j ih · cases hij exact le_rfl cases hij; · exact le_rfl exact le_trans (ih ‹_›) (approx_mono' f) theorem mem_iff (a : α) (b : β a) : b ∈ Part.fix f a ↔ ∃ i, b ∈ approx f i a := by by_cases h₀ : ∃ i : ℕ, (approx f i a).Dom · simp only [Part.fix_def f h₀] constructor <;> intro hh · exact ⟨_, hh⟩ have h₁ := Nat.find_spec h₀ rw [dom_iff_mem] at h₁ cases' h₁ with y h₁ replace h₁ := approx_mono' f _ _ h₁ suffices y = b by subst this exact h₁ cases' hh with i hh revert h₁; generalize succ (Nat.find h₀) = j; intro h₁ wlog case : i ≤ j · rcases le_total i j with H | H <;> [skip; symm] <;> apply_assumption <;> assumption replace hh := approx_mono f case _ _ hh apply Part.mem_unique h₁ hh · simp only [fix_def' (⇑f) h₀, not_exists, false_iff_iff, not_mem_none] simp only [dom_iff_mem, not_exists] at h₀ intro; apply h₀ theorem approx_le_fix (i : ℕ) : approx f i ≤ Part.fix f := fun a b hh ↦ by rw [mem_iff f] exact ⟨_, hh⟩ theorem exists_fix_le_approx (x : α) : ∃ i, Part.fix f x ≤ approx f i x := by by_cases hh : ∃ i b, b ∈ approx f i x · rcases hh with ⟨i, b, hb⟩ exists i intro b' h' have hb' := approx_le_fix f i _ _ hb obtain rfl := Part.mem_unique h' hb' exact hb · simp only [not_exists] at hh exists 0 intro b' h' simp only [mem_iff f] at h' cases' h' with i h' cases hh _ _ h' /-- The series of approximations of `fix f` (see `approx`) as a `Chain` -/ def approxChain : Chain ((a : _) → Part <| β a) := ⟨approx f, approx_mono f⟩ theorem le_f_of_mem_approx {x} : x ∈ approxChain f → x ≤ f x := by simp only [(· ∈ ·), forall_exists_index] rintro i rfl apply approx_mono' theorem approx_mem_approxChain {i} : approx f i ∈ approxChain f := Stream'.mem_of_get_eq rfl end Fix open Fix variable {α : Type*} variable (f : ((a : _) → Part <| β a) →o (a : _) → Part <| β a) open OmegaCompletePartialOrder open Part hiding ωSup open Nat open Nat.Upto OmegaCompletePartialOrder theorem fix_eq_ωSup : Part.fix f = ωSup (approxChain f) := by apply le_antisymm · intro x cases' exists_fix_le_approx f x with i hx trans approx f i.succ x · trans · apply hx · apply approx_mono' f apply le_ωSup_of_le i.succ dsimp [approx] rfl · apply ωSup_le _ _ _ simp only [Fix.approxChain, OrderHom.coe_mk] intro y x apply approx_le_fix f theorem fix_le {X : (a : _) → Part <| β a} (hX : f X ≤ X) : Part.fix f ≤ X := by rw [fix_eq_ωSup f] apply ωSup_le _ _ _ simp only [Fix.approxChain, OrderHom.coe_mk] intro i induction i with | zero => dsimp [Fix.approx]; apply bot_le | succ _ i_ih => trans f X · apply f.monotone i_ih · apply hX variable {f} theorem fix_eq (hc : Continuous f) : Part.fix f = f (Part.fix f) := by rw [fix_eq_ωSup f, hc] apply le_antisymm · apply ωSup_le_ωSup_of_le _ intro i exists i intro x -- intros x y hx, apply le_f_of_mem_approx _ ⟨i, rfl⟩ · apply ωSup_le_ωSup_of_le _ intro i exists i.succ end Part namespace Part /-- `toUnit` as a monotone function -/ @[simps] def toUnitMono (f : Part α →o Part α) : (Unit → Part α) →o Unit → Part α where toFun x u := f (x u) monotone' x y (h : x ≤ y) u := f.monotone <| h u theorem to_unit_cont (f : Part α →o Part α) (hc : Continuous f) : Continuous (toUnitMono f) | _ => by ext ⟨⟩ : 1 dsimp [OmegaCompletePartialOrder.ωSup] erw [hc, Chain.map_comp]; rfl instance lawfulFix : LawfulFix (Part α) := ⟨fun {f : Part α →o Part α} hc ↦ show Part.fix (toUnitMono f) () = _ by rw [Part.fix_eq (to_unit_cont f hc)]; rfl⟩ end Part open Sigma namespace Pi instance lawfulFix {β} : LawfulFix (α → Part β) := ⟨fun {_f} ↦ Part.fix_eq⟩ variable {γ : ∀ a : α, β a → Type*} section Monotone variable (α β γ) /-- `Sigma.curry` as a monotone function. -/ @[simps] def monotoneCurry [(x y : _) → Preorder <| γ x y] : (∀ x : Σa, β a, γ x.1 x.2) →o ∀ (a) (b : β a), γ a b where toFun := curry monotone' _x _y h a b := h ⟨a, b⟩ /-- `Sigma.uncurry` as a monotone function. -/ @[simps] def monotoneUncurry [(x y : _) → Preorder <| γ x y] : (∀ (a) (b : β a), γ a b) →o ∀ x : Σa, β a, γ x.1 x.2 where toFun := uncurry monotone' _x _y h a := h a.1 a.2 variable [(x y : _) → OmegaCompletePartialOrder <| γ x y] open OmegaCompletePartialOrder.Chain theorem continuous_curry : Continuous <| monotoneCurry α β γ := fun c ↦ by ext x y dsimp [curry, ωSup] rw [map_comp, map_comp] rfl theorem continuous_uncurry : Continuous <| monotoneUncurry α β γ := fun c ↦ by ext ⟨x, y⟩ dsimp [uncurry, ωSup] rw [map_comp, map_comp] rfl end Monotone open Fix instance hasFix [Fix <| (x : Sigma β) → γ x.1 x.2] : Fix ((x : _) → (y : β x) → γ x y) := ⟨fun f ↦ curry (fix <| uncurry ∘ f ∘ curry)⟩ variable [∀ x y, OmegaCompletePartialOrder <| γ x y] section Curry variable {f : ((x : _) → (y : β x) → γ x y) →o (x : _) → (y : β x) → γ x y} theorem uncurry_curry_continuous (hc : Continuous f) : Continuous <| (monotoneUncurry α β γ).comp <| f.comp <| monotoneCurry α β γ := continuous_comp _ _ (continuous_comp _ _ (continuous_curry _ _ _) hc) (continuous_uncurry _ _ _) end Curry instance lawfulFix' [LawfulFix <| (x : Sigma β) → γ x.1 x.2] : LawfulFix ((x y : _) → γ x y) where fix_eq {_f} hc := by dsimp [fix] conv_lhs => erw [LawfulFix.fix_eq (uncurry_curry_continuous hc)] rfl end Pi
Control\Random.lean
/- Copyright (c) 2022 Henrik Böving. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Henrik Böving -/ import Mathlib.Control.ULiftable import Mathlib.Order.Fin.Basic /-! # Rand Monad and Random Class This module provides tools for formulating computations guided by randomness and for defining objects that can be created randomly. ## Main definitions * `RandT` and `RandGT` monad transformers for computations guided by randomness; * `Rand` and `RandG` monads as special cases of the above * `Random` class for objects that can be generated randomly; * `random` to generate one object; * `BoundedRandom` class for objects that can be generated randomly inside a range; * `randomR` to generate one object inside a range; * `IO.runRand` to run a randomized computation inside any monad that has access to `stdGenRef`. ## References * Similar library in Haskell: https://hackage.haskell.org/package/MonadRandom -/ set_option autoImplicit true /-- A monad transformer to generate random objects using the generic generator type `g` -/ abbrev RandGT (g : Type) := StateT (ULift g) /-- A monad to generate random objects using the generator type `g`. -/ abbrev RandG (g : Type) := RandGT g Id /-- A monad transformer to generate random objects using the generator type `StdGen`. `RandT m α` should be thought of a random value in `m α`. -/ abbrev RandT := RandGT StdGen /-- A monad to generate random objects using the generator type `StdGen`. -/ abbrev Rand := RandG StdGen instance [MonadLift m n] : MonadLiftT (RandGT g m) (RandGT g n) where monadLift x := fun s => x s /-- `Random m α` gives us machinery to generate values of type `α` in the monad `m`. Note that `m` is a parameter as some types may only be sampleable with access to a certain monad. -/ class Random (m) (α : Type u) where random [RandomGen g] : RandGT g m α /-- `BoundedRandom m α` gives us machinery to generate values of type `α` between certain bounds in the monad `m`. -/ class BoundedRandom (m) (α : Type u) [Preorder α] where randomR {g : Type} (lo hi : α) (h : lo ≤ hi) [RandomGen g] : RandGT g m {a // lo ≤ a ∧ a ≤ hi} namespace Rand /-- Generate one more `Nat` -/ def next [RandomGen g] [Monad m] : RandGT g m Nat := do let rng := (← get).down let (res, new) := RandomGen.next rng set (ULift.up new) pure res /-- Create a new random number generator distinct from the one stored in the state -/ def split {g : Type} [RandomGen g] [Monad m] : RandGT g m g := do let rng := (← get).down let (r1, r2) := RandomGen.split rng set (ULift.up r1) pure r2 /-- Get the range of Nat that can be generated by the generator `g` -/ def range {g : Type} [RandomGen g] [Monad m] : RandGT g m (Nat × Nat) := do let rng := (← get).down pure <| RandomGen.range rng end Rand namespace Random open Rand variable [Monad m] /-- Generate a random value of type `α`. -/ def rand (α : Type u) [Random m α] [RandomGen g] : RandGT g m α := Random.random /-- Generate a random value of type `α` between `x` and `y` inclusive. -/ def randBound (α : Type u) [Preorder α] [BoundedRandom m α] (lo hi : α) (h : lo ≤ hi) [RandomGen g] : RandGT g m {a // lo ≤ a ∧ a ≤ hi} := (BoundedRandom.randomR lo hi h : RandGT g _ _) def randFin {n : Nat} [RandomGen g] : RandGT g m (Fin n.succ) := fun ⟨g⟩ ↦ pure <| randNat g 0 n |>.map Fin.ofNat ULift.up instance {n : Nat} : Random m (Fin n.succ) where random := randFin def randBool [RandomGen g] : RandGT g m Bool := return (← rand (Fin 2)) == 1 instance : Random m Bool where random := randBool instance {α : Type u} [ULiftable m m'] [Random m α] : Random m' (ULift.{v} α) where random := ULiftable.up random instance : BoundedRandom m Nat where randomR lo hi h _ := do let z ← rand (Fin (hi - lo).succ) pure ⟨ lo + z.val, Nat.le_add_right _ _, Nat.add_le_of_le_sub' h (Nat.le_of_succ_le_succ z.isLt) ⟩ instance : BoundedRandom m Int where randomR lo hi h _ := do let ⟨z, _, h2⟩ ← randBound Nat 0 (Int.natAbs <| hi - lo) (Nat.zero_le _) pure ⟨ z + lo, Int.le_add_of_nonneg_left (Int.ofNat_zero_le z), Int.add_le_of_le_sub_right <| Int.le_trans (Int.ofNat_le.mpr h2) (le_of_eq <| Int.natAbs_of_nonneg <| Int.sub_nonneg_of_le h)⟩ instance {n : Nat} : BoundedRandom m (Fin n) where randomR lo hi h _ := do let ⟨r, h1, h2⟩ ← randBound Nat lo.val hi.val h pure ⟨⟨r, Nat.lt_of_le_of_lt h2 hi.isLt⟩, h1, h2⟩ instance {α : Type u} [Preorder α] [ULiftable m m'] [BoundedRandom m α] [Monad m'] : BoundedRandom m' (ULift.{v} α) where randomR lo hi h := do let ⟨x⟩ ← ULiftable.up.{v} (BoundedRandom.randomR lo.down hi.down h) pure ⟨ULift.up x.val, x.prop⟩ end Random namespace IO variable {m : Type* → Type*} {m₀ : Type → Type} variable [Monad m] [MonadLiftT (ST RealWorld) m₀] [ULiftable m₀ m] /-- Computes a `RandT m α` using the global `stdGenRef` as RNG. Note that: - `stdGenRef` is not necessarily properly seeded on program startup as of now and will therefore be deterministic. - `stdGenRef` is not thread local, hence two threads accessing it at the same time will get the exact same generator. -/ def runRand (cmd : RandT m α) : m α := do let stdGen ← ULiftable.up (stdGenRef.get : m₀ _) let (res, new) ← StateT.run cmd stdGen let _ ← ULiftable.up (stdGenRef.set new.down : m₀ _) pure res def runRandWith (seed : Nat) (cmd : RandT m α) : m α := do pure <| (← cmd.run (ULift.up <| mkStdGen seed)).1 end IO
Control\ULift.lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Jannis Limperg -/ /-! # Monadic instances for `ULift` and `PLift` In this file we define `Monad` and `IsLawfulMonad` instances on `PLift` and `ULift`. -/ universe u v u' v' namespace PLift variable {α : Sort u} {β : Sort v} /-- Functorial action. -/ protected def map (f : α → β) (a : PLift α) : PLift β := PLift.up (f a.down) @[simp] theorem map_up (f : α → β) (a : α) : (PLift.up a).map f = PLift.up (f a) := rfl /-- Embedding of pure values. -/ @[simp] protected def pure : α → PLift α := up /-- Applicative sequencing. -/ protected def seq (f : PLift (α → β)) (x : Unit → PLift α) : PLift β := PLift.up (f.down (x ()).down) @[simp] theorem seq_up (f : α → β) (x : α) : (PLift.up f).seq (fun _ => PLift.up x) = PLift.up (f x) := rfl /-- Monadic bind. -/ protected def bind (a : PLift α) (f : α → PLift β) : PLift β := f a.down @[simp] theorem bind_up (a : α) (f : α → PLift β) : (PLift.up a).bind f = f a := rfl instance : Monad PLift where map := @PLift.map pure := @PLift.pure seq := @PLift.seq bind := @PLift.bind instance : LawfulFunctor PLift where id_map := @fun _ ⟨_⟩ => rfl comp_map := @fun _ _ _ _ _ ⟨_⟩ => rfl map_const := @fun _ _ => rfl instance : LawfulApplicative PLift where seqLeft_eq := @fun _ _ _ _ => rfl seqRight_eq := @fun _ _ _ _ => rfl pure_seq := @fun _ _ _ ⟨_⟩ => rfl map_pure := @fun _ _ _ _ => rfl seq_pure := @fun _ _ ⟨_⟩ _ => rfl seq_assoc := @fun _ _ _ ⟨_⟩ ⟨_⟩ ⟨_⟩ => rfl instance : LawfulMonad PLift where bind_pure_comp := @fun _ _ _ ⟨_⟩ => rfl bind_map := @fun _ _ ⟨_⟩ ⟨_⟩ => rfl pure_bind := @fun _ _ _ _ => rfl bind_assoc := @fun _ _ _ ⟨_⟩ _ _ => rfl @[simp] theorem rec.constant {α : Sort u} {β : Type v} (b : β) : (@PLift.rec α (fun _ => β) fun _ => b) = fun _ => b := rfl end PLift namespace ULift variable {α : Type u} {β : Type v} {f : α → β} /-- Functorial action. -/ protected def map (f : α → β) (a : ULift.{u'} α) : ULift.{v'} β := ULift.up.{v'} (f a.down) @[simp] theorem map_up (f : α → β) (a : α) : (ULift.up.{u'} a).map f = ULift.up.{v'} (f a) := rfl /-- Embedding of pure values. -/ @[simp] protected def pure : α → ULift α := up /-- Applicative sequencing. -/ protected def seq {α β} (f : ULift (α → β)) (x : Unit → ULift α) : ULift β := ULift.up.{u} (f.down (x ()).down) @[simp] theorem seq_up (f : α → β) (x : α) : (ULift.up f).seq (fun _ => ULift.up x) = ULift.up (f x) := rfl /-- Monadic bind. -/ protected def bind (a : ULift α) (f : α → ULift β) : ULift β := f a.down @[simp] theorem bind_up (a : α) (f : α → ULift β) : (ULift.up a).bind f = f a := rfl instance : Monad ULift where map := @ULift.map pure := @ULift.pure seq := @ULift.seq bind := @ULift.bind instance : LawfulFunctor ULift where id_map := @fun _ ⟨_⟩ => rfl comp_map := @fun _ _ _ _ _ ⟨_⟩ => rfl map_const := @fun _ _ => rfl instance : LawfulApplicative ULift where seqLeft_eq := @fun _ _ _ _ => rfl seqRight_eq := @fun _ _ _ _ => rfl pure_seq := @fun _ _ _ ⟨_⟩ => rfl map_pure := @fun _ _ _ _ => rfl seq_pure := @fun _ _ ⟨_⟩ _ => rfl seq_assoc := @fun _ _ _ ⟨_⟩ ⟨_⟩ ⟨_⟩ => rfl instance : LawfulMonad ULift where bind_pure_comp := @fun _ _ _ ⟨_⟩ => rfl bind_map := @fun _ _ ⟨_⟩ ⟨_⟩ => rfl pure_bind := @fun _ _ _ _ => rfl bind_assoc := @fun _ _ _ ⟨_⟩ _ _ => rfl @[simp] theorem rec.constant {α : Type u} {β : Sort v} (b : β) : (@ULift.rec α (fun _ => β) fun _ => b) = fun _ => b := rfl end ULift
Control\ULiftable.lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import Mathlib.Control.Monad.Basic import Mathlib.Control.Monad.Cont import Mathlib.Control.Monad.Writer import Mathlib.Logic.Equiv.Basic import Mathlib.Logic.Equiv.Functor import Mathlib.Control.Lawful /-! # Universe lifting for type families Some functors such as `Option` and `List` are universe polymorphic. Unlike type polymorphism where `Option α` is a function application and reasoning and generalizations that apply to functions can be used, `Option.{u}` and `Option.{v}` are not one function applied to two universe names but one polymorphic definition instantiated twice. This means that whatever works on `Option.{u}` is hard to transport over to `Option.{v}`. `ULiftable` is an attempt at improving the situation. `ULiftable Option.{u} Option.{v}` gives us a generic and composable way to use `Option.{u}` in a context that requires `Option.{v}`. It is often used in tandem with `ULift` but the two are purposefully decoupled. ## Main definitions * `ULiftable` class ## Tags universe polymorphism functor -/ universe v u₀ u₁ v₀ v₁ v₂ w w₀ w₁ variable {s : Type u₀} {s' : Type u₁} {r r' w w' : Type*} /-- Given a universe polymorphic type family `M.{u} : Type u₁ → Type u₂`, this class convert between instantiations, from `M.{u} : Type u₁ → Type u₂` to `M.{v} : Type v₁ → Type v₂` and back. `f` is an outParam, because `g` can almost always be inferred from the current monad. At any rate, the lift should be unique, as the intent is to only lift the same constants with different universe parameters. -/ class ULiftable (f : outParam (Type u₀ → Type u₁)) (g : Type v₀ → Type v₁) where congr {α β} : α ≃ β → f α ≃ g β namespace ULiftable /-- Not an instance as it is incompatible with `outParam`. In practice it seems not to be needed anyway. -/ abbrev symm (f : Type u₀ → Type u₁) (g : Type v₀ → Type v₁) [ULiftable f g] : ULiftable g f where congr e := (ULiftable.congr e.symm).symm instance refl (f : Type u₀ → Type u₁) [Functor f] [LawfulFunctor f] : ULiftable f f where congr e := Functor.mapEquiv _ e example : ULiftable IO IO := inferInstance /-- The most common practical use `ULiftable` (together with `down`), the function `up.{v}` takes `x : M.{u} α` and lifts it to `M.{max u v} (ULift.{v} α)` -/ abbrev up {f : Type u₀ → Type u₁} {g : Type max u₀ v → Type v₁} [ULiftable f g] {α} : f α → g (ULift.{v} α) := (ULiftable.congr Equiv.ulift.symm).toFun /-- The most common practical use of `ULiftable` (together with `up`), the function `down.{v}` takes `x : M.{max u v} (ULift.{v} α)` and lowers it to `M.{u} α` -/ abbrev down {f : Type u₀ → Type u₁} {g : Type max u₀ v → Type v₁} [ULiftable f g] {α} : g (ULift.{v} α) → f α := (ULiftable.congr Equiv.ulift.symm).invFun /-- convenient shortcut to avoid manipulating `ULift` -/ def adaptUp (F : Type v₀ → Type v₁) (G : Type max v₀ u₀ → Type u₁) [ULiftable F G] [Monad G] {α β} (x : F α) (f : α → G β) : G β := up x >>= f ∘ ULift.down.{u₀} /-- convenient shortcut to avoid manipulating `ULift` -/ def adaptDown {F : Type max u₀ v₀ → Type u₁} {G : Type v₀ → Type v₁} [L : ULiftable G F] [Monad F] {α β} (x : F α) (f : α → G β) : G β := @down.{max u₀ v₀} G F L β <| x >>= @up.{max u₀ v₀} G F L β ∘ f /-- map function that moves up universes -/ def upMap {F : Type u₀ → Type u₁} {G : Type max u₀ v₀ → Type v₁} [ULiftable F G] [Functor G] {α β} (f : α → β) (x : F α) : G β := Functor.map (f ∘ ULift.down.{v₀}) (up x) /-- map function that moves down universes -/ def downMap {F : Type max u₀ v₀ → Type u₁} {G : Type u₀ → Type v₁} [ULiftable G F] [Functor F] {α β} (f : α → β) (x : F α) : G β := down (Functor.map (ULift.up.{v₀} ∘ f) x : F (ULift β)) -- @[simp] -- Porting note (#10618): simp can prove this theorem up_down {f : Type u₀ → Type u₁} {g : Type max u₀ v₀ → Type v₁} [ULiftable f g] {α} (x : g (ULift.{v₀} α)) : up (down x : f α) = x := (ULiftable.congr Equiv.ulift.symm).right_inv _ -- @[simp] -- Porting note (#10618): simp can prove this theorem down_up {f : Type u₀ → Type u₁} {g : Type max u₀ v₀ → Type v₁} [ULiftable f g] {α} (x : f α) : down (up x : g (ULift.{v₀} α)) = x := (ULiftable.congr Equiv.ulift.symm).left_inv _ end ULiftable open ULift instance instULiftableId : ULiftable Id Id where congr F := F /-- for specific state types, this function helps to create a uliftable instance -/ def StateT.uliftable' {m : Type u₀ → Type v₀} {m' : Type u₁ → Type v₁} [ULiftable m m'] (F : s ≃ s') : ULiftable (StateT s m) (StateT s' m') where congr G := StateT.equiv <| Equiv.piCongr F fun _ => ULiftable.congr <| Equiv.prodCongr G F instance {m m'} [ULiftable m m'] : ULiftable (StateT s m) (StateT (ULift s) m') := StateT.uliftable' Equiv.ulift.symm instance StateT.instULiftableULiftULift {m m'} [ULiftable m m'] : ULiftable (StateT (ULift.{max v₀ u₀} s) m) (StateT (ULift.{max v₁ u₀} s) m') := StateT.uliftable' <| Equiv.ulift.trans Equiv.ulift.symm /-- for specific reader monads, this function helps to create a uliftable instance -/ def ReaderT.uliftable' {m m'} [ULiftable m m'] (F : s ≃ s') : ULiftable (ReaderT s m) (ReaderT s' m') where congr G := ReaderT.equiv <| Equiv.piCongr F fun _ => ULiftable.congr G instance {m m'} [ULiftable m m'] : ULiftable (ReaderT s m) (ReaderT (ULift s) m') := ReaderT.uliftable' Equiv.ulift.symm instance ReaderT.instULiftableULiftULift {m m'} [ULiftable m m'] : ULiftable (ReaderT (ULift.{max v₀ u₀} s) m) (ReaderT (ULift.{max v₁ u₀} s) m') := ReaderT.uliftable' <| Equiv.ulift.trans Equiv.ulift.symm /-- for specific continuation passing monads, this function helps to create a uliftable instance -/ def ContT.uliftable' {m m'} [ULiftable m m'] (F : r ≃ r') : ULiftable (ContT r m) (ContT r' m') where congr := ContT.equiv (ULiftable.congr F) instance {s m m'} [ULiftable m m'] : ULiftable (ContT s m) (ContT (ULift s) m') := ContT.uliftable' Equiv.ulift.symm instance ContT.instULiftableULiftULift {m m'} [ULiftable m m'] : ULiftable (ContT (ULift.{max v₀ u₀} s) m) (ContT (ULift.{max v₁ u₀} s) m') := ContT.uliftable' <| Equiv.ulift.trans Equiv.ulift.symm /-- for specific writer monads, this function helps to create a uliftable instance -/ def WriterT.uliftable' {m m'} [ULiftable m m'] (F : w ≃ w') : ULiftable (WriterT w m) (WriterT w' m') where congr G := WriterT.equiv <| ULiftable.congr <| Equiv.prodCongr G F instance {m m'} [ULiftable m m'] : ULiftable (WriterT s m) (WriterT (ULift s) m') := WriterT.uliftable' Equiv.ulift.symm instance WriterT.instULiftableULiftULift {m m'} [ULiftable m m'] : ULiftable (WriterT (ULift.{max v₀ u₀} s) m) (WriterT (ULift.{max v₁ u₀} s) m') := WriterT.uliftable' <| Equiv.ulift.trans Equiv.ulift.symm instance Except.instULiftable {ε : Type u₀} : ULiftable (Except.{u₀,v₁} ε) (Except.{u₀,v₂} ε) where congr e := { toFun := Except.map e invFun := Except.map e.symm left_inv := fun f => by cases f <;> simp [Except.map] right_inv := fun f => by cases f <;> simp [Except.map] } instance Option.instULiftable : ULiftable Option.{u₀} Option.{u₁} where congr e := { toFun := Option.map e invFun := Option.map e.symm left_inv := fun f => by cases f <;> simp right_inv := fun f => by cases f <;> simp }
Control\Bitraversable\Basic.lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import Mathlib.Control.Bifunctor import Mathlib.Control.Traversable.Basic /-! # Bitraversable type class Type class for traversing bifunctors. Simple examples of `Bitraversable` are `Prod` and `Sum`. A more elaborate example is to define an a-list as: ``` def AList (key val : Type) := List (key × val) ``` Then we can use `f : key → IO key'` and `g : val → IO val'` to manipulate the `AList`'s key and value respectively with `Bitraverse f g : AList key val → IO (AList key' val')`. ## Main definitions * `Bitraversable`: Bare typeclass to hold the `Bitraverse` function. * `LawfulBitraversable`: Typeclass for the laws of the `Bitraverse` function. Similar to `LawfulTraversable`. ## References The concepts and laws are taken from <https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Bitraversable.html> ## Tags traversable bitraversable iterator functor bifunctor applicative -/ universe u /-- Lawless bitraversable bifunctor. This only holds data for the bimap and bitraverse. -/ class Bitraversable (t : Type u → Type u → Type u) extends Bifunctor t where bitraverse : ∀ {m : Type u → Type u} [Applicative m] {α α' β β'}, (α → m α') → (β → m β') → t α β → m (t α' β') export Bitraversable (bitraverse) /-- A bitraversable functor commutes with all applicative functors. -/ def bisequence {t m} [Bitraversable t] [Applicative m] {α β} : t (m α) (m β) → m (t α β) := bitraverse id id open Functor /-- Bifunctor. This typeclass asserts that a lawless bitraversable bifunctor is lawful. -/ class LawfulBitraversable (t : Type u → Type u → Type u) [Bitraversable t] extends LawfulBifunctor t : Prop where -- Porting note: need to specify `m := Id` because `id` no longer has a `Monad` instance id_bitraverse : ∀ {α β} (x : t α β), bitraverse (m := Id) pure pure x = pure x comp_bitraverse : ∀ {F G} [Applicative F] [Applicative G] [LawfulApplicative F] [LawfulApplicative G] {α α' β β' γ γ'} (f : β → F γ) (f' : β' → F γ') (g : α → G β) (g' : α' → G β') (x : t α α'), bitraverse (Comp.mk ∘ map f ∘ g) (Comp.mk ∘ map f' ∘ g') x = Comp.mk (bitraverse f f' <$> bitraverse g g' x) bitraverse_eq_bimap_id : ∀ {α α' β β'} (f : α → β) (f' : α' → β') (x : t α α'), bitraverse (m := Id) (pure ∘ f) (pure ∘ f') x = pure (bimap f f' x) binaturality : ∀ {F G} [Applicative F] [Applicative G] [LawfulApplicative F] [LawfulApplicative G] (η : ApplicativeTransformation F G) {α α' β β'} (f : α → F β) (f' : α' → F β') (x : t α α'), η (bitraverse f f' x) = bitraverse (@η _ ∘ f) (@η _ ∘ f') x export LawfulBitraversable (id_bitraverse comp_bitraverse bitraverse_eq_bimap_id) open LawfulBitraversable attribute [higher_order bitraverse_id_id] id_bitraverse attribute [higher_order bitraverse_comp] comp_bitraverse attribute [higher_order] binaturality bitraverse_eq_bimap_id export LawfulBitraversable (bitraverse_id_id bitraverse_comp)
Control\Bitraversable\Instances.lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import Mathlib.Control.Bitraversable.Lemmas import Mathlib.Control.Traversable.Lemmas /-! # Bitraversable instances This file provides `Bitraversable` instances for concrete bifunctors: * `Prod` * `Sum` * `Functor.Const` * `flip` * `Function.bicompl` * `Function.bicompr` ## References * Hackage: <https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Bitraversable.html> ## Tags traversable bitraversable functor bifunctor applicative -/ universe u v w variable {t : Type u → Type u → Type u} [Bitraversable t] section variable {F : Type u → Type u} [Applicative F] /-- The bitraverse function for `α × β`. -/ def Prod.bitraverse {α α' β β'} (f : α → F α') (f' : β → F β') : α × β → F (α' × β') | (x, y) => Prod.mk <$> f x <*> f' y instance : Bitraversable Prod where bitraverse := @Prod.bitraverse instance : LawfulBitraversable Prod := by constructor <;> intros <;> casesm _ × _ <;> simp [bitraverse, Prod.bitraverse, functor_norm] <;> rfl open Functor /-- The bitraverse function for `α ⊕ β`. -/ def Sum.bitraverse {α α' β β'} (f : α → F α') (f' : β → F β') : α ⊕ β → F (α' ⊕ β') | Sum.inl x => Sum.inl <$> f x | Sum.inr x => Sum.inr <$> f' x instance : Bitraversable Sum where bitraverse := @Sum.bitraverse instance : LawfulBitraversable Sum := by constructor <;> intros <;> casesm _ ⊕ _ <;> simp [bitraverse, Sum.bitraverse, functor_norm] <;> rfl set_option linter.unusedVariables false in /-- The bitraverse function for `Const`. It throws away the second map. -/ @[nolint unusedArguments] def Const.bitraverse {F : Type u → Type u} [Applicative F] {α α' β β'} (f : α → F α') (f' : β → F β') : Const α β → F (Const α' β') := f instance Bitraversable.const : Bitraversable Const where bitraverse := @Const.bitraverse instance LawfulBitraversable.const : LawfulBitraversable Const := by constructor <;> intros <;> simp [bitraverse, Const.bitraverse, functor_norm] <;> rfl /-- The bitraverse function for `flip`. -/ nonrec def flip.bitraverse {α α' β β'} (f : α → F α') (f' : β → F β') : flip t α β → F (flip t α' β') := (bitraverse f' f : t β α → F (t β' α')) instance Bitraversable.flip : Bitraversable (flip t) where bitraverse := @flip.bitraverse t _ open LawfulBitraversable instance LawfulBitraversable.flip [LawfulBitraversable t] : LawfulBitraversable (flip t) := by constructor <;> intros <;> casesm LawfulBitraversable t <;> apply_assumption only [*] open Bitraversable Functor instance (priority := 10) Bitraversable.traversable {α} : Traversable (t α) where traverse := @tsnd t _ _ instance (priority := 10) Bitraversable.isLawfulTraversable [LawfulBitraversable t] {α} : LawfulTraversable (t α) := by constructor <;> intros <;> simp [traverse, comp_tsnd, functor_norm] · simp [tsnd_eq_snd_id, (· <$> ·), id.mk] · simp [tsnd, binaturality, Function.comp, functor_norm] end open Bifunctor Traversable LawfulTraversable LawfulBitraversable open Function (bicompl bicompr) section Bicompl variable (F G : Type u → Type u) [Traversable F] [Traversable G] /-- The bitraverse function for `bicompl`. -/ nonrec def Bicompl.bitraverse {m} [Applicative m] {α β α' β'} (f : α → m β) (f' : α' → m β') : bicompl t F G α α' → m (bicompl t F G β β') := (bitraverse (traverse f) (traverse f') : t (F α) (G α') → m _) instance : Bitraversable (bicompl t F G) where bitraverse := @Bicompl.bitraverse t _ F G _ _ instance [LawfulTraversable F] [LawfulTraversable G] [LawfulBitraversable t] : LawfulBitraversable (bicompl t F G) := by constructor <;> intros <;> simp [bitraverse, Bicompl.bitraverse, bimap, traverse_id, bitraverse_id_id, comp_bitraverse, functor_norm] · simp [traverse_eq_map_id', bitraverse_eq_bimap_id] · dsimp only [bicompl] simp [binaturality, naturality_pf] end Bicompl section Bicompr variable (F : Type u → Type u) [Traversable F] /-- The bitraverse function for `bicompr`. -/ nonrec def Bicompr.bitraverse {m} [Applicative m] {α β α' β'} (f : α → m β) (f' : α' → m β') : bicompr F t α α' → m (bicompr F t β β') := (traverse (bitraverse f f') : F (t α α') → m _) instance : Bitraversable (bicompr F t) where bitraverse := @Bicompr.bitraverse t _ F _ instance [LawfulTraversable F] [LawfulBitraversable t] : LawfulBitraversable (bicompr F t) := by constructor <;> intros <;> simp [bitraverse, Bicompr.bitraverse, bitraverse_id_id, functor_norm] · simp only [bitraverse_eq_bimap_id', traverse_eq_map_id', Function.comp_apply, Id.pure_eq]; rfl · dsimp only [bicompr] simp [naturality, binaturality'] end Bicompr