Lean / AbelCz/finite-semigroup-identity-bases / TarskiFiniteBasis.lean
Lean reader

TarskiFiniteBasis.lean

13,623 lines1362 declarationsno sorryimports Mathlib.Computability.Partrec Mathlib.Computability.PostTuringMachine Mathlib.Computability.Primrec Mathlib.Computability.TMToPartrec Mathlib.Data.Fintype.EquivFin Mathlib.Data.Fintype.Option +3

Showing the first 600 kB.

  1. import Mathlib.Computability.Partrec
  2. import Mathlib.Computability.PostTuringMachine
  3. import Mathlib.Computability.Primrec
  4. import Mathlib.Computability.TMToPartrec
  5. import Mathlib.Data.Fintype.EquivFin
  6. import Mathlib.Data.Fintype.Option
  7. import Mathlib.Data.Fintype.Prod
  8. import Mathlib.Data.List.FinRange
  9. import Std
  10. set_option maxErrors 1000
  11. set_option backward.isDefEq.respectTransparency.types false
  12. set_option maxHeartbeats 250000
  13. set_option linter.unusedSimpArgs false
  14. private theorem p455MapFinRange (n : ℕ) :
  15. (List.finRange n).map Fin.val = List.range n := by
  16. apply List.ext_getElem <;> simp
  17. /- Begin Problem455MachineLocal (from finite-semigroup-identity-bases). -/
  18. section
  19. namespace P455MachineLocal
  20. inductive Direction | left | stay | right
  21. deriving DecidableEq
  22. structure Ins (A Q : Type) where
  23. state : Q
  24. symbol : A
  25. dir : Direction
  26. deriving DecidableEq
  27. structure Cell (A Q : Type) where
  28. sym : A
  29. head : Option Q
  30. deriving DecidableEq
  31. def action (d : Q→A→Ins A Q) (c : Cell A Q) := c.head.map fun q=>d q c.sym
  32. def sends (i : Ins A Q) (toward : Direction) : Option Q := if i.dir=toward then some i.state else none
  33. def update (d : Q→A→Ins A Q) (l : Option (Cell A Q)) (c : Cell A Q) (r : Option (Cell A Q)) :
  34. Option (Cell A Q) :=
  35. match l.bind (action d), action d c, r.bind (action d) with
  36. | none,none,none => some ⟨c.sym,none⟩
  37. | some a,none,none => some ⟨c.sym,sends a .right⟩
  38. | none,none,some a => some ⟨c.sym,sends a .left⟩
  39. | none,some a,none =>
  40. if (a.dir=.left ∧ l.isNone=true) ∨ (a.dir=.right ∧ r.isNone=true) then none
  41. else some ⟨a.symbol,sends a .stay⟩
  42. | _,_,_ => none
  43. def atCell (tape : Nat→A) (p : Nat) (q : Q) (x : Nat) : Cell A Q :=
  44. ⟨tape x,if x=p then some q else none⟩
  45. def leftOf (row : Nat→α) (x : Nat) := if x=0 then none else some (row (x-1))
  46. def rightOf (row : Nat→α) (w x : Nat) := if x+1=w then none else some (row (x+1))
  47. def exits (dir : Direction) (w p : Nat) : Prop :=
  48. (dir=.left ∧ p=0) ∨ (dir=.right ∧ p+1=w)
  49. instance (dir : Direction) (w p : Nat) : Decidable (exits dir w p) := by unfold exits; infer_instance
  50. def dest (dir : Direction) (p : Nat) : Nat :=
  51. match dir with | .left => p-1 | .stay => p | .right => p+1
  52. def writeAt (tape : Nat→A) (p : Nat) (a : A) (x : Nat) := if x=p then a else tape x
  53. private theorem center_action (d : Q→A→Ins A Q) (tape : Nat→A) (p : Nat) (q : Q) (x : Nat) :
  54. action d (atCell tape p q x) = if x=p then some (d q (tape p)) else none := by
  55. by_cases e : x=p <;> simp [action,atCell,e]
  56. private theorem left_action (d : Q→A→Ins A Q) (tape : Nat→A) (p : Nat) (q : Q) (x : Nat) :
  57. (leftOf (atCell tape p q) x).bind (action d) =
  58. if x=p+1 then some (d q (tape p)) else none := by
  59. by_cases e : x=0
  60. · subst x; simp [leftOf]
  61. · have eq : (x-1=p) ↔ x=p+1 := by omega
  62. simp [leftOf,e,center_action,eq]
  63. private theorem right_action (d : Q→A→Ins A Q) (tape : Nat→A) (p w : Nat) (hp : p<w) (q : Q) (x : Nat) :
  64. (rightOf (atCell tape p q) w x).bind (action d) =
  65. if x+1=p then some (d q (tape p)) else none := by
  66. by_cases e : x+1=w
  67. · simp [rightOf,e,show w≠p by omega]
  68. · simp [rightOf,e,center_action]
  69. private theorem left_boundary (row : Nat→α) (x : Nat) : (leftOf row x).isNone=true ↔ x=0 := by
  70. by_cases e : x=0 <;> simp [leftOf,e]
  71. private theorem right_boundary (row : Nat→α) (w x : Nat) : (rightOf row w x).isNone=true ↔ x+1=w := by
  72. by_cases e : x+1=w <;> simp [rightOf,e]
  73. /-- When an entire bounded row has one head, the local rule at that head
  74. is defined precisely when the physical move remains in the interval. -/
  75. theorem defined_at_head (d : Q→A→Ins A Q) (tape : Nat→A) (w p : Nat) (q : Q) (hp : p<w) :
  76. update d (leftOf (atCell tape p q) p) (atCell tape p q p) (rightOf (atCell tape p q) w p)=none
  77. ↔ exits (d q (tape p)).dir w p := by
  78. unfold update
  79. rw [left_action,right_action _ _ _ _ hp,center_action]
  80. simp only [if_neg (show p≠p+1 by omega),if_neg (show p+1≠p by omega),if_pos rfl]
  81. simp only [left_boundary,right_boundary]
  82. change (if exits (d q (tape p)).dir w p then _ else _) = none ↔ _
  83. by_cases e : exits (d q (tape p)).dir w p <;> simp [e]
  84. /-- Every cell of a nonescaping row has its exact next physical value. -/
  85. theorem local_step (d : Q→A→Ins A Q) (tape : Nat→A) (w p : Nat) (q : Q)
  86. (hp : p<w) (safe : ¬exits (d q (tape p)).dir w p) (x : Nat) (hx : x<w) :
  87. let i := d q (tape p)
  88. update d (leftOf (atCell tape p q) x) (atCell tape p q x) (rightOf (atCell tape p q) w x)=
  89. some (atCell (writeAt tape p i.symbol) (dest i.dir p) i.state x) := by
  90. dsimp only
  91. unfold update
  92. rw [left_action,right_action _ _ _ _ hp,center_action]
  93. by_cases cp : x=p
  94. · subst x
  95. simp only [if_neg (show p≠p+1 by omega),if_neg (show p+1≠p by omega),if_pos rfl]
  96. change (if ((d q (tape p)).dir=.left ∧ (leftOf (atCell tape p q) p).isNone=true) ∨
  97. ((d q (tape p)).dir=.right ∧ (rightOf (atCell tape p q) w p).isNone=true)
  98. then none else some (Cell.mk (d q (tape p)).symbol (sends (d q (tape p)) .stay))) = _
  99. simp only [left_boundary,right_boundary]
  100. change (if exits (d q (tape p)).dir w p then _ else _) = _
  101. rw [if_neg safe]
  102. cases dir : (d q (tape p)).dir with
  103. | left =>
  104. have pos : p≠0 := by simpa [exits,dir] using safe
  105. simp [sends,dir,atCell,writeAt,dest,show p≠p-1 by omega]
  106. | stay => simp [sends,dir,atCell,writeAt,dest]
  107. | right => simp [sends,dir,atCell,writeAt,dest]
  108. · by_cases l : x=p+1
  109. · have r : x+1≠p := by omega
  110. simp only [if_pos l,if_neg cp,if_neg r]
  111. cases dir : (d q (tape p)).dir <;>
  112. simp [sends,dir,atCell,writeAt,dest,cp,show x≠p-1 by omega,l,show p+1≠p-1 by omega]
  113. · by_cases r : x+1=p
  114. · simp only [if_neg l,if_neg cp,if_pos r]
  115. cases dir : (d q (tape p)).dir <;>
  116. simp [sends,dir,atCell,writeAt,dest,cp,l,show x=p-1 by omega,show p-1≠p by omega,show p-1≠p+1 by omega]
  117. · simp only [if_neg l,if_neg cp,if_neg r]
  118. cases dir : (d q (tape p)).dir <;>
  119. simp [sends,dir,atCell,writeAt,dest,cp,l,show x≠p-1 by omega]
  120. end P455MachineLocal
  121. end
  122. /- Begin Problem455Quotient (from finite-semigroup-identity-bases). -/
  123. section
  124. namespace P455Quotient
  125. abbrev Word (α : Type) := List α
  126. inductive Walk {α : Type} (s : α → α → Prop) : α → α → Prop
  127. | refl (a) : Walk s a a
  128. | snoc {a b c} : Walk s a b → s b c → Walk s a c
  129. namespace Walk
  130. theorem trans {s : α → α → Prop} (h : Walk s x y) (k : Walk s y z) : Walk s x z := by
  131. induction k with
  132. | refl => exact h
  133. | snoc _ step ih => exact .snoc ih step
  134. theorem symm {s : α → α → Prop} (rev : ∀ {x y}, s x y → s y x) (h : Walk s x y) :
  135. Walk s y x := by
  136. induction h with
  137. | refl => exact .refl _
  138. | snoc _ step ih => exact (Walk.snoc (.refl _) (rev step)).trans ih
  139. theorem transport {s : α → α → Prop} {P : α → Prop} (h : Walk s x y) (px : P x)
  140. (step : ∀ {u v}, s u v → P u → P v) : P y := by
  141. induction h with
  142. | refl => exact px
  143. | snoc _ move ih => exact step move ih
  144. end Walk
  145. section
  146. variable {α : Type} [DecidableEq α]
  147. local notation "W" => Word α
  148. def Cap (r : Nat) (u : W) : Prop := ∀ a : α, u.count a ≤ r
  149. structure Rules (α : Type) [DecidableEq α] where
  150. r : Nat
  151. step : Word α → Word α → Prop
  152. reverse : ∀ {u v}, step u v → step v u
  153. counts : ∀ {u v}, step u v → ∀ a, u.count a = v.count a
  154. extend : ∀ {u v}, step u v → ∀ l t, Cap r (l ++ u ++ t) →
  155. step (l ++ u ++ t) (l ++ v ++ t)
  156. variable (R : Rules α)
  157. abbrev Variant (T v : W) := Walk R.step T v
  158. def Factor (u v : W) := ∃ l t : Word α, v = l ++ u ++ t
  159. def Good (T u : W) := ∃ v, Variant R T v ∧ Factor u v
  160. theorem count_walk {u v : W} (h : Walk R.step u v) (a : α) : u.count a = v.count a := by
  161. induction h with
  162. | refl => rfl
  163. | snoc _ step ih => exact ih.trans (R.counts step a)
  164. theorem contextual_walk {u v : W} (h : Walk R.step u v) (l t : Word α)
  165. (hc : Cap R.r (l ++ u ++ t)) : Walk R.step (l ++ u ++ t) (l ++ v ++ t) := by
  166. induction h with
  167. | refl => exact .refl _
  168. | snoc pre mv ih =>
  169. apply Walk.snoc ih (R.extend mv l t ?_)
  170. intro a
  171. have eq := count_walk R pre a
  172. have bound := hc a
  173. simp only [List.count_append] at *
  174. omega
  175. theorem good_context {T u v : W} (hc : Cap R.r T) (h : Walk R.step u v)
  176. (l t : Word α) : Good R T (l ++ u ++ t) ↔ Good R T (l ++ v ++ t) := by
  177. suffices f : ∀ {x y}, Walk R.step x y → Good R T (l ++ x ++ t) → Good R T (l ++ y ++ t) from
  178. ⟨f h, f (h.symm R.reverse)⟩
  179. intro x y path ⟨variant, reach, left, right, eq⟩
  180. subst variant
  181. have bound : Cap R.r ((left ++ l) ++ x ++ (t ++ right)) := by
  182. intro a
  183. have e := count_walk R reach a
  184. simp only [List.count_append] at *
  185. have := hc a
  186. omega
  187. have ext := contextual_walk R path (left ++ l) (t ++ right) bound
  188. simp only [List.append_assoc] at reach ext ⊢
  189. exact ⟨_, reach.trans ext, left, right, by simp [List.append_assoc]⟩
  190. theorem good_cap {T u : W} (hc : Cap R.r T) (h : Good R T u) : Cap R.r u := by
  191. obtain ⟨_, reach, l, t, rfl⟩ := h
  192. intro a
  193. have e := count_walk R reach a
  194. have b := hc a
  195. simp only [List.count_append] at e
  196. omega
  197. theorem factor_good {T u v : W} (g : Good R T v) (f : Factor u v) : Good R T u := by
  198. obtain ⟨w, path, l, t, hw⟩ := g
  199. obtain ⟨l', t', hv⟩ := f
  200. exact ⟨w, path, l ++ l', t' ++ t, by simp [hw, hv, List.append_assoc]⟩
  201. abbrev Raw (α : Type) := Option (Word α)
  202. def mulRaw : Raw α → Raw α → Raw α
  203. | some u, some v => some (u ++ v)
  204. | _, _ => none
  205. def Live (T : W) : Raw α → Prop
  206. | none => False
  207. | some u => Good R T u
  208. def Rel (T : W) (x y : Raw α) : Prop :=
  209. (¬ Live R T x ∧ ¬ Live R T y) ∨
  210. ∃ u v : W, x = some u ∧ y = some v ∧ Good R T u ∧ Good R T v ∧ Walk R.step u v
  211. theorem rel_refl (T : W) (x : Raw α) : Rel R T x x := by
  212. by_cases h : Live R T x
  213. · cases x with
  214. | none => exact h.elim
  215. | some u => exact Or.inr ⟨u,u,rfl,rfl,h,h,.refl _⟩
  216. · exact Or.inl ⟨h,h⟩
  217. theorem rel_symm {T : W} {x y : Raw α} : Rel R T x y → Rel R T y x := by
  218. rintro (⟨a,b⟩ | ⟨u,v,rfl,rfl,gu,gv,h⟩)
  219. · exact Or.inl ⟨b,a⟩
  220. · exact Or.inr ⟨v,u,rfl,rfl,gv,gu,h.symm R.reverse⟩
  221. theorem rel_trans {T : W} {x y z : Raw α} : Rel R T x y → Rel R T y z → Rel R T x z := by
  222. rintro (⟨a,b⟩ | ⟨u,v,rfl,rfl,gu,gv,h⟩) k
  223. · rcases k with ⟨_,c⟩ | ⟨v,w,rfl,rfl,gv,_,_⟩
  224. · exact Or.inl ⟨a,c⟩
  225. · exact (b gv).elim
  226. · rcases k with ⟨b,_⟩ | ⟨v',w,e,rfl,_,gw,h'⟩
  227. · exact (b gv).elim
  228. · cases e
  229. exact Or.inr ⟨u,w,rfl,rfl,gu,gw,h.trans h'⟩
  230. def setoid (T : W) : Setoid (Raw α) where
  231. r := Rel R T
  232. iseqv := ⟨rel_refl R T, rel_symm R, rel_trans R⟩
  233. abbrev Q (T : W) := Quotient (setoid R T)
  234. def context (l t : Word α) : Raw α → Raw α
  235. | none => none
  236. | some u => some (l ++ u ++ t)
  237. theorem dead_context {T : W} {x : Raw α} (d : ¬ Live R T x) (l t : Word α) :
  238. ¬ Live R T (context l t x) := by
  239. cases x with
  240. | none => exact id
  241. | some u => exact fun g => d (factor_good R g ⟨l,t,rfl⟩)
  242. theorem rel_context {T : W} (hc : Cap R.r T) {x y : Raw α} (h : Rel R T x y)
  243. (l t : Word α) : Rel R T (context l t x) (context l t y) := by
  244. rcases h with ⟨a,b⟩ | ⟨u,v,rfl,rfl,_,_,path⟩
  245. · exact Or.inl ⟨dead_context R a l t,dead_context R b l t⟩
  246. · have equiv := good_context R hc path l t
  247. by_cases gu : Good R T (l ++ u ++ t)
  248. · exact Or.inr ⟨_,_,rfl,rfl,gu,equiv.mp gu,contextual_walk R path l t (good_cap R hc gu)⟩
  249. · exact Or.inl ⟨gu,fun gv => gu (equiv.mpr gv)⟩
  250. theorem mul_compat {T : W} (hc : Cap R.r T) {x y z t : Raw α}
  251. (h : Rel R T x y) (k : Rel R T z t) : Rel R T (mulRaw x z) (mulRaw y t) := by
  252. apply rel_trans R (y := mulRaw y z)
  253. · cases z with
  254. | none => cases x <;> cases y <;> exact rel_refl R _ _
  255. | some w =>
  256. have e := rel_context R hc h [] w
  257. cases x <;> cases y <;> exact e
  258. · cases y with
  259. | none => exact rel_refl R _ _
  260. | some w =>
  261. have e := rel_context R hc k w []
  262. cases z <;> cases t <;> simpa only [context, mulRaw, List.append_nil] using e
  263. def cls (T : W) (x : Raw α) : Q R T := Quotient.mk _ x
  264. set_option backward.isDefEq.respectTransparency false in
  265. def mul {T : W} (hc : Cap R.r T) (x y : Q R T) : Q R T :=
  266. Quotient.liftOn₂ x y (fun a b => cls R T (mulRaw a b))
  267. (fun _ _ _ _ h k => Quotient.sound (mul_compat R hc h k))
  268. def zero (T : W) : Q R T := cls R T none
  269. def ofWord (T u : W) : Q R T := cls R T (some u)
  270. theorem mul_assoc {T : W} (hc : Cap R.r T) (x y z : Q R T) :
  271. mul R hc (mul R hc x y) z = mul R hc x (mul R hc y z) := by
  272. induction x using Quotient.inductionOn with | _ a =>
  273. induction y using Quotient.inductionOn with | _ b =>
  274. induction z using Quotient.inductionOn with | _ c =>
  275. change cls R T (mulRaw (mulRaw a b) c) = cls R T (mulRaw a (mulRaw b c))
  276. apply congrArg (cls R T)
  277. cases a <;> cases b <;> cases c <;> simp only [mulRaw, List.append_assoc]
  278. set_option backward.isDefEq.respectTransparency false in
  279. theorem unit_laws {T : W} (hc : Cap R.r T) (q : Q R T) :
  280. mul R hc (ofWord R T []) q = q ∧ mul R hc q (ofWord R T []) = q := by
  281. refine Quotient.inductionOn
  282. (motive := fun a : Q R T => mul R hc (ofWord R T []) a = a ∧ mul R hc a (ofWord R T []) = a)
  283. q ?_
  284. intro a
  285. change cls R T (mulRaw (some []) a) = cls R T a ∧ cls R T (mulRaw a (some [])) = cls R T a
  286. cases a <;> simp only [mulRaw, List.nil_append, List.append_nil, and_self]
  287. set_option backward.isDefEq.respectTransparency false in
  288. theorem absorbing {T : W} (hc : Cap R.r T) (q : Q R T) :
  289. mul R hc (zero R T) q = zero R T ∧ mul R hc q (zero R T) = zero R T := by
  290. induction q using Quotient.inductionOn with | _ a =>
  291. cases a <;> exact ⟨rfl,rfl⟩
  292. theorem nonzero_iff {T u : W} : ofWord R T u ≠ zero R T ↔ Good R T u := by
  293. constructor
  294. · intro h
  295. by_cases good : Good R T u
  296. · exact good
  297. · exact (h (Quotient.sound (Or.inl ⟨good,id⟩ : Rel R T (some u) none))).elim
  298. · intro good eq
  299. have e : Rel R T (some u) none := Quotient.exact eq
  300. rcases e with ⟨bad,_⟩ | ⟨_,_,_,e,_,_,_⟩
  301. · exact bad good
  302. · contradiction
  303. theorem good_empty (T : W) : Good R T [] :=
  304. ⟨T,.refl T,T,[],by simp⟩
  305. theorem same_nonzero_class {T u v : W} (g : Good R T u) :
  306. ofWord R T u = ofWord R T v ↔ Good R T v ∧ Walk R.step u v := by
  307. constructor
  308. · intro e
  309. have h : Rel R T (some u) (some v) := Quotient.exact e
  310. rcases h with ⟨bad,_⟩ | ⟨_,_,ea,eb,_,gv,path⟩
  311. · exact (bad g).elim
  312. · cases ea
  313. cases eb
  314. exact ⟨gv,path⟩
  315. · rintro ⟨gv,path⟩
  316. exact Quotient.sound (Or.inr ⟨u,v,rfl,rfl,g,gv,path⟩ : Rel R T (some u) (some v))
  317. theorem unit_rep_unique (T u : W) : ofWord R T u = ofWord R T [] ↔ u = [] := by
  318. constructor
  319. · intro eq
  320. have path := ((same_nonzero_class R (good_empty R T)).mp eq.symm).2
  321. exact (List.Perm.nil_eq (List.perm_iff_count.mpr (count_walk R path))).symm
  322. · rintro rfl; rfl
  323. theorem nonzero_representative {T : W} (q : Q R T) (nz : q ≠ zero R T) :
  324. ∃ u, Good R T u ∧ ofWord R T u = q := by
  325. induction q using Quotient.inductionOn with | _ a =>
  326. cases a with
  327. | none => exact (nz rfl).elim
  328. | some u => exact ⟨u,(nonzero_iff R).mp nz,rfl⟩
  329. def eval {T : W} (hc : Cap R.r T) (a : β → Q R T) : List β → Q R T
  330. | [] => ofWord R T []
  331. | x :: xs => mul R hc (a x) (eval hc a xs)
  332. theorem eval_rep {T : W} (hc : Cap R.r T) (a : β → Q R T)
  333. (v : List β) (h : β → Word α) (reps : ∀ x ∈ v, ofWord R T (h x) = a x) :
  334. eval R hc a v = ofWord R T (v.flatMap h) := by
  335. induction v with
  336. | nil => rfl
  337. | cons x xs ih =>
  338. rw [eval, ← reps x (by simp), ih (fun y hy => reps y (by simp [hy]))]
  339. rfl
  340. theorem arbitrary_representatives {T : W} (hc : Cap R.r T) (a : β → Q R T)
  341. (v : List β) (h : β → Word α) (reps : ∀ x ∈ v, ofWord R T (h x) = a x) :
  342. eval R hc a v ≠ zero R T ↔
  343. ∃ variant l t, Variant R T variant ∧ variant = l ++ v.flatMap h ++ t := by
  344. rw [eval_rep R hc a v h reps, nonzero_iff]
  345. constructor
  346. · rintro ⟨z,path,l,t,e⟩; exact ⟨z,l,t,path,e⟩
  347. · rintro ⟨z,l,t,path,e⟩; exact ⟨z,path,l,t,e⟩
  348. theorem live_inputs {T : W} (hc : Cap R.r T) (a : β → Q R T)
  349. (v : List β) (nz : eval R hc a v ≠ zero R T) : ∀ x ∈ v, a x ≠ zero R T := by
  350. induction v with
  351. | nil => simp
  352. | cons y ys ih =>
  353. have yn : a y ≠ zero R T := fun h => nz (by rw [eval,h,(absorbing R hc _).1])
  354. have ns : eval R hc a ys ≠ zero R T := fun h => nz (by rw [eval,h,(absorbing R hc _).2])
  355. intro x hx
  356. rcases List.mem_cons.mp hx with e | hx
  357. · exact e ▸ yn
  358. · exact ih ns x hx
  359. /-- For a fixed certificate, only preservation under ONE literal template move
  360. still has to be discharged. The certificate is read in the enclosing variant. -/
  361. theorem designated {T : W} (hc : Cap R.r T) (a : β → Q R T) (v : List β)
  362. (h : β → Word α) (reps : ∀ x ∈ v, ofWord R T (h x) = a x)
  363. (nz : eval R hc a v ≠ zero R T) (P : Word α → Prop)
  364. (initial : P T) (one : ∀ {x y}, R.step x y → P x → P y) :
  365. ∃ variant l t, Variant R T variant ∧ variant = l ++ v.flatMap h ++ t ∧ P variant := by
  366. obtain ⟨z,l,t,path,eq⟩ := (arbitrary_representatives R hc a v h reps).mp nz
  367. exact ⟨z,l,t,path,eq,path.transport initial one⟩
  368. end
  369. end P455Quotient
  370. end
  371. /- Begin Problem455Slots (from finite-semigroup-identity-bases). -/
  372. section
  373. namespace Problem455.Slots
  374. abbrev Word := List Nat
  375. abbrev Event := Nat × Nat
  376. def advance (n : Nat → Nat) (w : Word) : Nat → Nat :=
  377. fun a => n a + w.count a
  378. def stamp (n : Nat → Nat) : Word → List Event
  379. | [] => []
  380. | a :: w => (a, n a) :: stamp (advance n [a]) w
  381. def events (w : Word) := stamp (fun _ => 0) w
  382. theorem advance_append (n : Nat → Nat) (u v : Word) :
  383. advance (advance n u) v = advance n (u ++ v) := by
  384. funext a
  385. simp [advance, List.count_append, Nat.add_assoc]
  386. theorem stamp_append (n : Nat → Nat) (u v : Word) :
  387. stamp n (u ++ v) = stamp n u ++ stamp (advance n u) v := by
  388. induction u generalizing n with
  389. | nil =>
  390. have hn : advance n [] = n := by funext a; simp [advance]
  391. simp [stamp, hn]
  392. | cons a u ih =>
  393. simp only [List.cons_append, stamp, ih]
  394. rw [advance_append]
  395. rfl
  396. theorem stamp_at (n : Nat → Nat) (m : Nat) (u : Word)
  397. (nd : u.Nodup) (hm : ∀ a ∈ u, n a = m) :
  398. stamp n u = u.map (fun a => (a, m)) := by
  399. induction u generalizing n with
  400. | nil => rfl
  401. | cons a u ih =>
  402. obtain ⟨fresh, rest⟩ := List.nodup_cons.mp nd
  403. simp only [stamp, List.map_cons]
  404. rw [hm a (by simp), ih _ rest]
  405. intro b hb
  406. have hne : a ≠ b := by intro eq; exact fresh (eq ▸ hb)
  407. simp [advance, hne, Ne.symm hne, hm b (by simp [hb])]
  408. structure Move (m : Nat) where
  409. pre : Word
  410. p : Word
  411. q : Word
  412. post : Word
  413. dp : p.Nodup
  414. dq : q.Nodup
  415. disjoint : ∀ a ∈ p, a ∉ q
  416. indexP : ∀ a ∈ p, pre.count a = m
  417. indexQ : ∀ a ∈ q, pre.count a = m
  418. def before {m : Nat} (s : Move m) := s.pre ++ (s.p ++ (s.q ++ s.post))
  419. def after {m : Nat} (s : Move m) := s.pre ++ (s.q ++ (s.p ++ s.post))
  420. def tagged (m : Nat) (w : Word) : List Event := w.map (fun a => (a, m))
  421. theorem move_events {m : Nat} (s : Move m) :
  422. ∃ lo hi : List Event,
  423. events (before s) = lo ++ (tagged m s.p ++ (tagged m s.q ++ hi)) ∧
  424. events (after s) = lo ++ (tagged m s.q ++ (tagged m s.p ++ hi)) := by
  425. let n := fun a => s.pre.count a
  426. have hn : advance (fun _ => 0) s.pre = n := by funext a; simp [advance, n]
  427. have hp : stamp n s.p = tagged m s.p := stamp_at _ _ _ s.dp s.indexP
  428. have hq : stamp n s.q = tagged m s.q := stamp_at _ _ _ s.dq s.indexQ
  429. have hp' : stamp (advance n s.q) s.p = tagged m s.p := by
  430. apply stamp_at _ _ _ s.dp
  431. intro a ha
  432. simp [advance, List.count_eq_zero.mpr (s.disjoint a ha), n, s.indexP a ha]
  433. have hq' : stamp (advance n s.p) s.q = tagged m s.q := by
  434. apply stamp_at _ _ _ s.dq
  435. intro a ha
  436. have fresh : a ∉ s.p := fun hp => s.disjoint a hp ha
  437. simp [advance, List.count_eq_zero.mpr fresh, n, s.indexQ a ha]
  438. have merge : advance (advance n s.p) s.q = advance (advance n s.q) s.p := by
  439. funext a
  440. simp [advance, Nat.add_right_comm]
  441. refine ⟨events s.pre, stamp (advance (advance n s.q) s.p) s.post, ?_, ?_⟩
  442. · simp only [events, before, stamp_append, hn]
  443. change _ ++ (stamp n s.p ++ (stamp (advance n s.p) s.q ++ _)) = _
  444. rw [hp, hq', merge]
  445. · simp only [events, after, stamp_append, hn]
  446. change _ ++ (stamp n s.q ++ (stamp (advance n s.q) s.p ++ _)) = _
  447. rw [hq, hp']
  448. def select {α : Type} [DecidableEq α] (keep w : List α) : List α :=
  449. w.filter (fun e => decide (e ∈ keep))
  450. theorem select_append {α : Type} [DecidableEq α] (keep u v : List α) :
  451. select keep (u ++ v) = select keep u ++ select keep v := List.filter_append ..
  452. theorem select_nil {α : Type} [DecidableEq α] (keep w : List α)
  453. (h : ∀ a ∈ w, a ∉ keep) : select keep w = [] := by
  454. apply List.filter_eq_nil_iff.mpr
  455. simpa using h
  456. theorem selected_swap {α : Type} [DecidableEq α] (keep lo p q hi : List α)
  457. (nc : (∀ a ∈ p, a ∉ keep) ∨ (∀ a ∈ q, a ∉ keep)) :
  458. select keep (lo ++ (p ++ (q ++ hi))) = select keep (lo ++ (q ++ (p ++ hi))) := by
  459. rcases nc with h | h
  460. · simp [select_append, select_nil keep p h]
  461. · simp [select_append, select_nil keep q h]
  462. theorem protected_projection {m : Nat} (s : Move m) (keep : List Nat)
  463. (nc : (∀ a ∈ s.p, a ∉ keep) ∨ (∀ a ∈ s.q, a ∉ keep)) :
  464. select keep (before s) = select keep (after s) :=
  465. selected_swap keep _ _ _ _ nc
  466. theorem observed_events {m : Nat} (s : Move m) (keep : List Event)
  467. (nc : (∀ a ∈ s.p, (a,m) ∉ keep) ∨ (∀ a ∈ s.q, (a,m) ∉ keep)) :
  468. select keep (events (before s)) = select keep (events (after s)) := by
  469. obtain ⟨lo, hi, h, h'⟩ := move_events s
  470. rw [h, h']
  471. apply selected_swap
  472. simpa [tagged] using nc
  473. /- Observable order measured directly by the sublist relation on the word
  474. of indexed occurrences. The pattern need not consist of consecutive events. -/
  475. def sees (w : Word) (pattern : List Event) := pattern.Sublist (events w)
  476. theorem sublist_select_self {α : Type} [DecidableEq α] (t w : List α) :
  477. t.Sublist (select t w) ↔ t.Sublist w := by
  478. constructor
  479. · intro h
  480. exact h.trans (List.filter_sublist ..)
  481. · intro h
  482. have hf := h.filter (fun x => decide (x ∈ t))
  483. have self : t.filter (fun x => decide (x ∈ t)) = t := by
  484. apply List.filter_eq_self.mpr
  485. simp
  486. rwa [self] at hf
  487. theorem sees_invariant {m : Nat} (s : Move m) (t : List Event)
  488. (nc : (∀ a ∈ s.p, (a,m) ∉ t) ∨ (∀ a ∈ s.q, (a,m) ∉ t)) :
  489. sees (before s) t ↔ sees (after s) t := by
  490. unfold sees
  491. rw [← sublist_select_self t (events (before s)),
  492. ← sublist_select_self t (events (after s)), observed_events s t nc]
  493. theorem immutable_pattern {m : Nat} (s : Move m) (t : List Event)
  494. (hm : ∀ e ∈ t, e.2 ≠ m) :
  495. sees (before s) t ↔ sees (after s) t := by
  496. apply sees_invariant
  497. left
  498. exact fun a _ he => hm (a,m) he rfl
  499. /- An occupant can have mutable occurrence index. Only the two specified
  500. owner endpoints must be immutable. This covers unit-erasing as well as
  501. multiletter representatives once their literal product has been located. -/
  502. theorem open_slot_event {m : Nat} (s : Move m) (owner i j : Nat) (e : Event)
  503. (hi : i ≠ m) (hj : j ≠ m) :
  504. sees (before s) [(owner,i),e,(owner,j)] ↔
  505. sees (after s) [(owner,i),e,(owner,j)] := by
  506. apply sees_invariant
  507. by_cases h : e.1 ∈ s.p
  508. · right
  509. intro a ha
  510. have diff : (a,m) ≠ e := by
  511. intro eq
  512. have : a = e.1 := congrArg Prod.fst eq
  513. exact s.disjoint e.1 h (this ▸ ha)
  514. simp [diff, Ne.symm hi, Ne.symm hj]
  515. · left
  516. intro a ha
  517. have diff : (a,m) ≠ e := by
  518. intro eq
  519. have : a = e.1 := congrArg Prod.fst eq
  520. exact h (this ▸ ha)
  521. simp [diff, Ne.symm hi, Ne.symm hj]
  522. def slotStart (i : Nat) : Prop :=
  523. i = 0 ∨ i = 1 ∨ i = 3 ∨ i = 5 ∨ i = 7 ∨ i = 9 ∨ i = 11
  524. def occupies (w : Word) (owner i a : Nat) : Prop :=
  525. ∃ j, sees w [(owner,i),(a,j),(owner,i+1)]
  526. theorem seven_slots {k : Nat} (s : Move (14+k)) (owner i a : Nat)
  527. (hi : slotStart i) :
  528. occupies (before s) owner i a ↔ occupies (after s) owner i a := by
  529. have h1 : i ≠ 14+k := by unfold slotStart at hi; omega
  530. have h2 : i+1 ≠ 14+k := by unfold slotStart at hi; omega
  531. exact exists_congr (fun j => open_slot_event s owner i (i+1) (a,j) h1 h2)
  532. def pair (a b : Nat) (bit : Bool) : Word := if bit then [b,a] else [a,b]
  533. def profilePrefix (a b : Nat) (tag : List Bool) : Word :=
  534. [a,a,b,a,b,b] ++ (List.replicate 5 [a,b,a,b]).flatten ++
  535. tag.flatMap (pair a b) ++ [a,b]
  536. def profile (a b : Nat) (tag : List Bool) (bit : Bool) : Word :=
  537. profilePrefix a b tag ++ (pair a b bit ++ [a,b])
  538. def typed (w : Word) (a b : Nat) (tag : List Bool) : Prop :=
  539. ∃ bit, select [a,b] w = profile a b tag bit
  540. theorem tag_length (a b : Nat) (tag : List Bool) :
  541. (tag.flatMap (pair a b)).length = 2 * tag.length := by
  542. induction tag with
  543. | nil => rfl
  544. | cons bit t ih => cases bit <;> simp [pair, ih] <;> omega
  545. theorem profile_prefix_length (a b : Nat) (tag : List Bool) :
  546. (profilePrefix a b tag).length = 2 * (14+tag.length) := by
  547. unfold profilePrefix
  548. simp only [List.length_append, tag_length]
  549. change 6 + 20 + (2*tag.length) + 2 = _
  550. omega
  551. theorem length_select_pair (a b : Nat) (hab : a ≠ b) (w : Word) :
  552. (select [a,b] w).length = w.count a + w.count b := by
  553. induction w with
  554. | nil => rfl
  555. | cons c w ih =>
  556. unfold select at *
  557. simp at ih
  558. by_cases hca : c = a
  559. · subst c
  560. simp [List.count_cons, hab, Ne.symm hab, ih]; omega
  561. · by_cases hcb : c = b
  562. · subst c
  563. simp [List.count_cons, hab, Ne.symm hab, ih]; omega
  564. · simp [List.count_cons, hca, hcb, Ne.symm hca, Ne.symm hcb, ih]
  565. theorem select_lone (a b : Nat) (w : Word) (hd : w.Nodup)
  566. (ha : a ∈ w) (hb : b ∉ w) :
  567. select [a,b] w = [a] := by
  568. induction w with
  569. | nil => simp at ha
  570. | cons c w ih =>
  571. obtain ⟨hc,ht⟩ := List.nodup_cons.mp hd
  572. by_cases hca : c = a
  573. · subst c
  574. have hnil : select [a,b] w = [] := by
  575. apply select_nil
  576. intro x hx
  577. simp only [List.mem_cons, List.not_mem_nil, or_false, not_or]
  578. exact ⟨fun e => hc (e ▸ hx),fun e => hb (by simp [e ▸ hx])⟩
  579. simpa [select, List.filter_cons] using congrArg (List.cons a) hnil
  580. · have hc' : c ≠ b := fun h => hb (by simp [h])
  581. have ha' : a ∈ w := by simpa [Ne.symm hca] using ha
  582. have hb' : b ∉ w := fun h => hb (by simp [h])
  583. simpa [select, hca, hc'] using ih ht ha' hb'
  584. theorem select_pair_symm (a b : Nat) (w : Word) : select [b,a] w = select [a,b] w := by
  585. unfold select
  586. apply List.filter_congr
  587. intro x _
  588. simp [or_comm]
  589. private theorem exchange_at_split (a b : Nat) (lo hi fixed tail : Word)
  590. (len : lo.length = fixed.length) (bit : Bool) :
  591. (∃ b', lo ++ (pair a b bit ++ hi) = fixed ++ (pair a b b' ++ tail)) →
  592. (∃ b', lo ++ (pair a b (!bit) ++ hi) = fixed ++ (pair a b b' ++ tail)) := by
  593. rintro ⟨old,h⟩
  594. have eqPre : lo = fixed := by
  595. have ht := congrArg (List.take lo.length) h
  596. simpa [len] using ht
  597. subst fixed
  598. have he := List.append_cancel_left h
  599. have eqHi : hi = tail := by
  600. have hd := congrArg (List.drop 2) he
  601. cases bit <;> cases old <;> simpa [pair] using hd
  602. exact ⟨!bit,by rw [eqHi]⟩
  603. theorem type_forward {m : Nat} (s : Move m) (a b : Nat) (tag : List Bool)
  604. (hab : a ≠ b) (hm : m = 14 + tag.length) :
  605. typed (before s) a b tag → typed (after s) a b tag := by
  606. let keep := [a,b]
  607. by_cases hp : ∀ x ∈ s.p, x ∉ keep
  608. · intro e
  609. unfold typed at *
  610. rw [← protected_projection s [a,b] (.inl hp)]; exact e
  611. by_cases hq : ∀ x ∈ s.q, x ∉ keep
  612. · intro e
  613. unfold typed at *
  614. rw [← protected_projection s [a,b] (.inr hq)]; exact e
  615. have shape : (a ∈ s.p ∧ b ∈ s.q) ∨ (b ∈ s.p ∧ a ∈ s.q) := by
  616. by_cases hap : a ∈ s.p
  617. · left
  618. refine ⟨hap,?_⟩
  619. apply Classical.byContradiction
  620. intro hbn
  621. apply hq
  622. intro x hx
  623. simp only [keep, List.mem_cons, List.not_mem_nil, or_false, not_or]
  624. exact ⟨fun eq => s.disjoint a hap (eq ▸ hx), fun eq => hbn (eq ▸ hx)⟩
  625. · have hbp : b ∈ s.p := by
  626. apply Classical.byContradiction
  627. intro hbn
  628. apply hp
  629. intro x hx
  630. simp only [keep, List.mem_cons, List.not_mem_nil, or_false, not_or]
  631. exact ⟨fun eq => hap (eq ▸ hx), fun eq => hbn (eq ▸ hx)⟩
  632. right
  633. refine ⟨hbp,?_⟩
  634. apply Classical.byContradiction
  635. intro han
  636. apply hq
  637. intro x hx
  638. simp only [keep, List.mem_cons, List.not_mem_nil, or_false, not_or]
  639. exact ⟨fun eq => han (eq ▸ hx),fun eq => s.disjoint b hbp (eq ▸ hx)⟩
  640. obtain ⟨bit,hp1,hq1,ca,cb⟩ :
  641. ∃ bit : Bool, select [a,b] s.p ++ select [a,b] s.q = pair a b bit ∧
  642. select [a,b] s.q ++ select [a,b] s.p = pair a b (!bit) ∧
  643. s.pre.count a = m ∧ s.pre.count b = m := by
  644. rcases shape with ⟨pa,qb⟩ | ⟨pb,qa⟩
  645. · have p' := select_lone a b s.p s.dp pa (fun pb => s.disjoint b pb qb)
  646. have q' := select_lone b a s.q s.dq qb (s.disjoint a pa)
  647. rw [select_pair_symm] at q'
  648. exact ⟨false,by rw [p',q']; rfl,by rw [p',q']; rfl,s.indexP a pa,s.indexQ b qb⟩
  649. · have p' := select_lone b a s.p s.dp pb (fun pa => s.disjoint a pa qa)
  650. rw [select_pair_symm] at p'
  651. have q' := select_lone a b s.q s.dq qa (s.disjoint b pb)
  652. exact ⟨true,by rw [p',q']; rfl,by rw [p',q']; rfl,s.indexQ a qa,s.indexP b pb⟩
  653. have len : (select [a,b] s.pre).length = (profilePrefix a b tag).length := by
  654. rw [length_select_pair a b hab, ca, cb, hm, profile_prefix_length]; omega
  655. unfold typed before after profile
  656. simp only [select_append]
  657. rw [← List.append_assoc (select [a,b] s.p), hp1,
  658. ← List.append_assoc (select [a,b] s.q), hq1]
  659. exact exchange_at_split a b _ _ _ _ len bit
  660. end Problem455.Slots
  661. end
  662. /- Begin Problem455Closure (from finite-semigroup-identity-bases). -/
  663. section
  664. namespace P455Closure
  665. universe u
  666. variable {α : Type u} [DecidableEq α]
  667. def Cap (r : Nat) (w : List α) : Prop := ∀ a, w.count a ≤ r
  668. /-- false denotes block p and true denotes block q. -/
  669. def phasePair (b : Bool) : List Bool := [b, !b]
  670. def fixedPhases (tag : List Bool) : List Bool :=
  671. (List.replicate 5 [false,true,false,true]).flatten ++ tag.flatMap phasePair ++ phasePair false
  672. /-- The fillers before fixed phase tokens, before the mutable pair, and
  673. before the two final tokens may be arbitrary lists, including empty.
  674. A frame spans from the first p to the last q. -/
  675. structure Frame (α : Type u) where
  676. pHead : α
  677. pTail : List α
  678. qInit : List α
  679. qLast : α
  680. tag : List Bool
  681. middle : List (List α × Bool)
  682. beforeMutable : List α
  683. beforeFinalP : List α
  684. beforeFinalQ : List α
  685. namespace Frame
  686. variable (f : Frame α)
  687. def p := f.pHead :: f.pTail
  688. def q := f.qInit ++ [f.qLast]
  689. def pair (b : Bool) := if b then f.q ++ f.p else f.p ++ f.q
  690. def early := f.p ++ f.p ++ f.q ++ f.p ++ f.q ++ f.q
  691. def mid := f.middle.flatMap fun e => e.1 ++ (if e.2 then f.q else f.p)
  692. def core (b : Bool) := f.early ++ f.mid ++ f.beforeMutable ++ f.pair b ++
  693. f.beforeFinalP ++ f.p ++ f.beforeFinalQ ++ f.q
  694. /-- The count condition explicitly encodes that the r designated copies
  695. of each block exhaust its alphabet; all intervening fillers are inert
  696. for the two blocks. Mark may be stored in either order. -/
  697. def Valid (r : Nat) (Allowed : List Bool → Prop) (Mark : α → α → Prop) : Prop :=
  698. r = 16 + f.tag.length ∧ Allowed f.tag ∧ f.middle.map Prod.snd = fixedPhases f.tag ∧
  699. f.p.Nodup ∧ f.q.Nodup ∧ (∀ a ∈ f.p, a ∉ f.q) ∧
  700. (∀ a ∈ f.p, ∀ b ∈ f.q, ¬ Mark a b ∧ ¬ Mark b a) ∧
  701. (∀ a, a ∈ f.p ∨ a ∈ f.q → (f.core false).count a = r)
  702. theorem count_core (a : α) (b : Bool) : (f.core b).count a = (f.core (!b)).count a := by
  703. cases b <;> simp [core, pair, List.count_append] <;> omega
  704. omit [DecidableEq α] in
  705. theorem core_starts (b : Bool) : ∃ tail, f.core b = f.pHead :: tail := by
  706. simp [core, early, p]
  707. omit [DecidableEq α] in
  708. theorem core_ends (b : Bool) : ∃ ini, f.core b = ini ++ [f.qLast] := by
  709. unfold core q
  710. rw [← List.append_assoc]
  711. exact ⟨_, rfl⟩
  712. private theorem count_tag_pairs (tag : List Bool) (side : Bool) :
  713. (tag.flatMap phasePair).count side = tag.length := by
  714. induction tag with
  715. | nil => rfl
  716. | cons b bs ih =>
  717. cases b <;> cases side <;> simp_all [phasePair,List.count_cons,Nat.add_comm]
  718. private theorem fixed_count (tag : List Bool) (side : Bool) :
  719. (fixedPhases tag).count side = 11 + tag.length := by
  720. cases side <;> simp [fixedPhases,count_tag_pairs,phasePair,List.count_cons,Nat.add_comm,
  721. List.replicate_succ] <;> omega
  722. private theorem token_count_le (p q : List α) (a : α) (side : Bool)
  723. (has : 1 ≤ (if side then q else p).count a) (es : List (List α × Bool)) :
  724. (es.map Prod.snd).count side ≤
  725. (es.flatMap fun e => e.1 ++ (if e.2 then q else p)).count a := by
  726. induction es with
  727. | nil => simp
  728. | cons hd es ih =>
  729. obtain ⟨w,b⟩ := hd
  730. cases b <;> cases side <;>
  731. simp only [Bool.false_eq_true,if_false,if_true] at has <;>
  732. simp [List.count_cons] <;> omega
  733. private theorem index_of_order {r : Nat} (hr : r = 16 + f.tag.length)
  734. (hmid : f.middle.map Prod.snd = fixedPhases f.tag) (bit : Bool) (l t : List α)
  735. (hc : Cap r (l ++ f.core bit ++ t)) (a : α) (ha : a ∈ f.p ∨ a ∈ f.q) :
  736. (l ++ f.early ++ f.mid ++ f.beforeMutable).count a = 14 + f.tag.length := by
  737. have hcap := hc a
  738. have hpq : 1 ≤ f.p.count a ∨ 1 ≤ f.q.count a := ha.imp List.count_pos_iff.mpr List.count_pos_iff.mpr
  739. have h1 : 11 + f.tag.length ≤ f.mid.count a := by
  740. rcases hpq with hp | hq
  741. · have h := token_count_le f.p f.q a false (by simpa using hp) f.middle
  742. simpa [hmid,fixed_count,mid] using h
  743. · have h := token_count_le f.p f.q a true (by simpa using hq) f.middle
  744. simpa [hmid,fixed_count,mid] using h
  745. have h2 : 3 ≤ f.early.count a := by simp [early]; omega
  746. have h3 : 1 ≤ (f.pair bit).count a := by cases bit <;> simp [pair] <;> omega
  747. simp only [core,List.count_append] at hcap ⊢
  748. omega
  749. /-- Every block label has zero-based occurrence index 14+k at the mutable
  750. pair. Counts are derived from the actual profile and the cap; neither
  751. an index hypothesis nor any restriction on outsiders in context is needed. -/
  752. theorem mutable_index {r : Nat} {Allowed : List Bool → Prop} {Mark : α → α → Prop}
  753. (hf : f.Valid r Allowed Mark) (bit : Bool) (l t : List α)
  754. (hc : Cap r (l ++ f.core bit ++ t)) (a : α) (ha : a ∈ f.p ∨ a ∈ f.q) :
  755. (l ++ f.early ++ f.mid ++ f.beforeMutable).count a = 14 + f.tag.length := by
  756. exact f.index_of_order hf.1 hf.2.2.1 bit l t hc a ha
  757. /-- Literal occurrence exhaustion follows from the phase order and cap.
  758. This shows the saturation field in Valid cannot exclude any capped
  759. arrangement of the prescribed blocks, including arrangements with
  760. previously unrestricted fillers. -/
  761. theorem saturation_of_order {r : Nat} (hr : r = 16 + f.tag.length)
  762. (hmid : f.middle.map Prod.snd = fixedPhases f.tag) (bit : Bool) (l t : List α)
  763. (hc : Cap r (l ++ f.core bit ++ t)) (a : α) (ha : a ∈ f.p ∨ a ∈ f.q) :
  764. (f.core false).count a = r := by
  765. have hc' : Cap r ([] ++ f.core false ++ []) := by
  766. intro z
  767. have hh := hc z
  768. have hd : (f.core bit).count z = (f.core false).count z := by
  769. cases bit with
  770. | false => rfl
  771. | true => exact f.count_core z true
  772. simp only [List.count_append,hd, List.count_nil] at *
  773. omega
  774. have idx := f.index_of_order hr hmid false [] [] hc' a ha
  775. have bound := hc' a
  776. have sup : 1 ≤ f.p.count a ∨ 1 ≤ f.q.count a :=
  777. ha.imp List.count_pos_iff.mpr List.count_pos_iff.mpr
  778. simp only [List.nil_append,List.append_nil] at idx bound
  779. simp only [core,pair,Bool.false_eq_true,if_false,List.count_append] at idx bound ⊢
  780. omega
  781. theorem valid_of_capped_shape {r : Nat} {Allowed : List Bool → Prop} {Mark : α → α → Prop}
  782. (hr : r = 16 + f.tag.length) (ht : Allowed f.tag)
  783. (order : f.middle.map Prod.snd = fixedPhases f.tag)
  784. (dp : f.p.Nodup) (dq : f.q.Nodup) (apart : ∀ a ∈ f.p, a ∉ f.q)
  785. (unmarked : ∀ a ∈ f.p, ∀ b ∈ f.q, ¬ Mark a b ∧ ¬ Mark b a)
  786. (bit : Bool) (l t : List α) (hc : Cap r (l ++ f.core bit ++ t)) :
  787. f.Valid r Allowed Mark :=
  788. ⟨hr,ht,order,dp,dq,apart,unmarked,f.saturation_of_order hr order bit l t hc⟩
  789. /-- A capped enclosing context contributes no extra occurrence of any
  790. moved label, for either choice of the mutable order. -/
  791. theorem context_fresh {r : Nat} {Allowed : List Bool → Prop} {Mark : α → α → Prop}
  792. (hf : f.Valid r Allowed Mark) (bit : Bool) (l t : List α)
  793. (hc : Cap r (l ++ f.core bit ++ t)) (a : α) (ha : a ∈ f.p ∨ a ∈ f.q) :
  794. a ∉ l ∧ a ∉ t := by
  795. have hs := hf.2.2.2.2.2.2.2 a ha
  796. have hs' : (f.core bit).count a = r := by
  797. cases bit with
  798. | false => exact hs
  799. | true => exact (f.count_core a true).trans hs
  800. have hh := hc a
  801. simp only [List.count_append,hs'] at hh
  802. exact ⟨List.count_eq_zero.mp (by omega),List.count_eq_zero.mp (by omega)⟩
  803. def profileBits (tag : List Bool) (bit : Bool) : List Bool :=
  804. [false,false,true,false,true,true] ++ fixedPhases tag ++ phasePair bit ++ phasePair false
  805. def profileWord (x y : α) (tag : List Bool) (bit : Bool) : List α :=
  806. (profileBits tag bit).map (fun b => if b then y else x)
  807. omit [DecidableEq α] in
  808. private theorem middle_trace (p q : List α) {x y : α} (hx : x ∈ p) (hy : y ∈ q)
  809. (es : List (List α × Bool)) :
  810. ((es.map Prod.snd).map (fun b => if b then y else x)).Sublist
  811. (es.flatMap fun e => e.1 ++ if e.2 then q else p) := by
  812. induction es with
  813. | nil => exact .slnil
  814. | cons e es ih =>
  815. obtain ⟨w,b⟩ := e
  816. have one : [if b then y else x].Sublist (w ++ (if b then q else p)) := by
  817. apply List.sublist_append_of_sublist_right
  818. cases b <;> simp [hx,hy]
  819. exact one.append ih
  820. omit [DecidableEq α] in
  821. private theorem profile_trace (bit : Bool) (x y : α) (hx : x ∈ f.p) (hy : y ∈ f.q)
  822. (order : f.middle.map Prod.snd = fixedPhases f.tag) :
  823. (profileWord x y f.tag bit).Sublist (f.core bit) := by
  824. have px := List.singleton_sublist.mpr hx
  825. have qy := List.singleton_sublist.mpr hy
  826. have ea := ((((px.append px).append qy).append px).append qy).append qy
  827. have mi := middle_trace f.p f.q hx hy f.middle
  828. rw [order] at mi
  829. have swapped : ((phasePair bit).map (fun b => if b then y else x)).Sublist (f.pair bit) := by
  830. cases bit with
  831. | false => exact px.append qy
  832. | true => exact qy.append px
  833. have pref := (ea.append mi).append (List.nil_sublist f.beforeMutable)
  834. have whole := (((((pref.append swapped).append (List.nil_sublist f.beforeFinalP)).append px).append
  835. (List.nil_sublist f.beforeFinalQ)).append qy)
  836. simpa only [profileWord,profileBits,core,early,List.map_append,List.append_nil,
  837. phasePair,List.map_cons,List.map_nil,Bool.false_eq_true,if_false,if_true,
  838. List.append_assoc,List.cons_append,List.nil_append, mid, Bool.not_false] using whole
  839. omit [DecidableEq α] in
  840. private theorem pattern_length (x y : α) (tag : List Bool) (bit : Bool) :
  841. (profileWord x y tag bit).length = 2 * (16 + tag.length) := by
  842. have tl : (tag.flatMap phasePair).length = 2 * tag.length := by
  843. induction tag with
  844. | nil => rfl
  845. | cons b t ih => simp [phasePair,ih]; omega
  846. simp [profileWord,profileBits,fixedPhases,phasePair,List.replicate_succ,tl]
  847. omega
  848. private theorem select_length (x y : α) (w : List α) :
  849. (w.filter (fun a => decide (a = x ∨ a = y))).length ≤ w.count x + w.count y := by
  850. induction w with
  851. | nil => simp
  852. | cons a as ih =>
  853. by_cases hx : a = x <;> by_cases hy : a = y <;>
  854. simp [hx,hy,List.count_cons,beq_iff_eq] at ih ⊢ <;> omega
  855. theorem cross_projection {r : Nat} {Allowed : List Bool → Prop} {Mark : α → α → Prop}
  856. (hf : f.Valid r Allowed Mark) (bit : Bool) (l t : List α)
  857. (hc : Cap r (l ++ f.core bit ++ t)) (x y : α) (hx : x ∈ f.p) (hy : y ∈ f.q) :
  858. (l ++ f.core bit ++ t).filter (fun a => decide (a = x ∨ a = y)) =
  859. profileWord x y f.tag bit := by
  860. have tr := f.profile_trace bit x y hx hy hf.2.2.1
  861. have tr' : (profileWord x y f.tag bit).Sublist (l ++ f.core bit ++ t) :=
  862. List.sublist_append_of_sublist_left (List.sublist_append_of_sublist_right tr)
  863. let keep := fun (a : α) => decide (a = x ∨ a = y)
  864. have intact : (profileWord x y f.tag bit).filter keep = profileWord x y f.tag bit := by
  865. apply List.filter_eq_self.mpr
  866. intro a ha
  867. obtain ⟨b,_,rfl⟩ := List.mem_map.mp ha
  868. cases b <;> simp [keep]
  869. have tt := tr'.filter keep
  870. rw [intact] at tt
  871. apply Eq.symm
  872. apply tt.eq_of_length_le
  873. have h := select_length x y (l ++ f.core bit ++ t)
  874. have h1 := hc x
  875. have h2 := hc y
  876. have hr := hf.1
  877. change ((l ++ f.core bit ++ t).filter (fun a => decide (a = x ∨ a = y))).length ≤ _
  878. rw [pattern_length]
  879. omega
  880. end Frame
  881. /-- A single literal permitted swap, with both words written in the same
  882. external context. All r copies of p and q are in the frame. -/
  883. def Move (r : Nat) (Allowed : List Bool → Prop) (Mark : α → α → Prop)
  884. (u v : List α) : Prop :=
  885. ∃ (f : Frame α) (b : Bool) (l t : List α),
  886. f.Valid r Allowed Mark ∧ u = l ++ f.core b ++ t ∧
  887. v = l ++ f.core (!b) ++ t ∧ Cap r u
  888. variable {r : Nat} {Allowed : List Bool → Prop} {Mark : α → α → Prop} {u v : List α}
  889. namespace Move
  890. theorem count_eq (h : Move r Allowed Mark u v) (a : α) : u.count a = v.count a := by
  891. obtain ⟨f,b,l,t,_,hu,hv,_⟩ := h
  892. rw [hu,hv]
  893. simp only [List.count_append, f.count_core a b]
  894. theorem cap_left (h : Move r Allowed Mark u v) : Cap r u := by
  895. obtain ⟨_,_,_,_,_,_,_,hc⟩ := h
  896. exact hc
  897. theorem cap_right (h : Move r Allowed Mark u v) : Cap r v := by
  898. intro a
  899. rw [← h.count_eq]
  900. exact h.cap_left a
  901. theorem symm (h : Move r Allowed Mark u v) : Move r Allowed Mark v u := by
  902. have hc := h.cap_right
  903. obtain ⟨f,b,l,t,hf,hu,hv,_⟩ := h
  904. exact ⟨f,!b,l,t,hf,hv,by simpa using hu,hc⟩
  905. /-- Extending a factor-local move to any capped context uses the same
  906. literal frame. Cap excludes a new occurrence of either block's labels. -/
  907. theorem extend_of_cap (h : Move r Allowed Mark u v) (l t : List α)
  908. (hc : Cap r (l ++ u ++ t)) : Move r Allowed Mark (l ++ u ++ t) (l ++ v ++ t) := by
  909. obtain ⟨f,b,i,j,hf,hu,hv,_⟩ := h
  910. refine ⟨f,b,l ++ i,j ++ t,hf,?_,?_,hc⟩ <;> simp [hu,hv,List.append_assoc]
  911. end Move
  912. omit [DecidableEq α] in
  913. /-- Two splittings of a word, when the prefix on the left avoids the
  914. displayed occurrence on the right. The shorter prefix is on the left. -/
  915. private theorem stripBefore {a : α} {l p z s : List α}
  916. (h : l ++ z = p ++ a :: s) (ha : a ∉ l) :
  917. ∃ d, p = l ++ d ∧ z = d ++ a :: s := by
  918. induction l generalizing p with
  919. | nil => exact ⟨p, by simp, by simpa using h⟩
  920. | cons x l ih =>
  921. cases p with
  922. | nil =>
  923. have hx : x = a := (List.cons.inj h).1
  924. exact False.elim (ha (by simp [hx]))
  925. | cons y p =>
  926. obtain ⟨hxy,hrest⟩ := List.cons.inj h
  927. obtain ⟨d,hp,hz⟩ := ih hrest (fun hm => ha (by simp [hm]))
  928. exact ⟨d,by simp [hp,hxy],hz⟩
  929. omit [DecidableEq α] in
  930. /-- In two splittings of a word, the factor x contains the whole core
  931. whenever the left context avoids its first symbol and the right
  932. context avoids its last symbol. Either context may be empty. -/
  933. theorem containCore {l x t i c j : List α} {a b : α}
  934. (h : l ++ x ++ t = i ++ c ++ j)
  935. (ha : a ∉ l) (hb : b ∉ t)
  936. (hfirst : ∃ s, c = a :: s) (hlast : ∃ k, c = k ++ [b]) :
  937. ∃ d e, i = l ++ d ∧ j = e ++ t ∧ x = d ++ c ++ e := by
  938. obtain ⟨s,hs⟩ := hfirst
  939. have h1 : l ++ (x ++ t) = i ++ a :: (s ++ j) := by simpa [hs,List.append_assoc] using h
  940. obtain ⟨d,hi,hxt⟩ := stripBefore h1 ha
  941. obtain ⟨k,hk⟩ := hlast
  942. have h2 : t.reverse ++ x.reverse = j.reverse ++ b :: (k.reverse ++ d.reverse) := by
  943. have h' : x ++ t = d ++ c ++ j := by simpa [hs,List.append_assoc] using hxt
  944. simpa [hk,List.reverse_append,List.append_assoc] using congrArg List.reverse h'
  945. obtain ⟨e,hj,_⟩ := stripBefore h2 (by simpa using hb)
  946. have hj' : j = e.reverse ++ t := by
  947. simpa [List.reverse_append] using congrArg List.reverse hj
  948. have hx : l ++ (x ++ t) = l ++ ((d ++ c ++ e.reverse) ++ t) := by
  949. simpa [hi,hj',List.append_assoc] using h
  950. exact ⟨d,e.reverse,hi,hj',List.append_cancel_right (List.append_cancel_left hx)⟩
  951. /-- Restrict a witnessed global swap to a factor containing all copies
  952. of the boundary anchors. Saturation of the other moving labels is
  953. automatic once this entire frame has been recovered. -/
  954. theorem Frame.restrict_of_saturated (f : Frame α) (b : Bool)
  955. (hf : f.Valid r Allowed Mark) (l x t i j : List α)
  956. (whole : l ++ x ++ t = i ++ f.core b ++ j) (cap : Cap r (l ++ x ++ t))
  957. (hp : x.count f.pHead = r) (hq : x.count f.qLast = r) :
  958. ∃ y, Move r Allowed Mark x y ∧ l ++ y ++ t = i ++ f.core (!b) ++ j := by
  959. have hpl := cap f.pHead
  960. have hqt := cap f.qLast
  961. simp only [List.count_append,hp,hq] at hpl hqt
  962. have hpl' : l.count f.pHead = 0 := by omega
  963. have hqt' : t.count f.qLast = 0 := by omega
  964. obtain ⟨d,e,hi,hj,hx⟩ := containCore whole (List.count_eq_zero.mp hpl')
  965. (List.count_eq_zero.mp hqt') (f.core_starts b) (f.core_ends b)
  966. have hxcap : Cap r x := by
  967. intro a
  968. have hh := cap a
  969. simp only [List.count_append] at hh
  970. omega
  971. refine ⟨d ++ f.core (!b) ++ e,⟨f,b,d,e,hf,hx,rfl,hxcap⟩,?_⟩
  972. simp [hi,hj,List.append_assoc]
  973. end P455Closure
  974. end
  975. /- Begin Problem455Swap (from finite-semigroup-identity-bases). -/
  976. section
  977. namespace Problem455Swap
  978. abbrev Word := List Nat
  979. def occ (a : Nat) : Word → Nat
  980. | [] => 0
  981. | b :: w => (if a = b then 1 else 0) + occ a w
  982. def cap (r : Nat) (w : Word) : Prop := ∀ a, occ a w ≤ r
  983. def hit (x y : Nat) (left right : Option Nat) : Nat :=
  984. if left = some x ∧ right = some y then 1 else 0
  985. def bigram (x y : Nat) : Word → Nat
  986. | [] => 0
  987. | a :: w => hit x y (some a) w.head? + bigram x y w
  988. def Link (r : Nat) (w : Word) (x y : Nat) : Prop := bigram x y w = r
  989. theorem occ_append (a : Nat) (u v : Word) : occ a (u ++ v) = occ a u + occ a v := by
  990. induction u with
  991. | nil => simp [occ]
  992. | cons b u ih => simp [occ, ih, Nat.add_assoc]
  993. theorem bigram_append (x y : Nat) (u v : Word) :
  994. bigram x y (u ++ v) = bigram x y u + bigram x y v + hit x y u.getLast? v.head? := by
  995. induction u with
  996. | nil => simp [bigram, hit]
  997. | cons a u ih =>
  998. cases u with
  999. | nil => simp [bigram, hit, Nat.add_comm]
  1000. | cons b w =>
  1001. change hit x y (some a) (some b) + bigram x y ((b :: w) ++ v) = _
  1002. rw [ih]
  1003. simp [bigram, List.getLast?_cons_cons, Nat.add_assoc, Nat.add_left_comm, Nat.add_comm]
  1004. theorem out_bound (x y z : Nat) (hyz : y ≠ z) (w : Word) :
  1005. bigram x y w + bigram x z w ≤ occ x w := by
  1006. induction w with
  1007. | nil => simp [bigram, occ]
  1008. | cons a w ih =>
  1009. simp only [bigram, occ]
  1010. unfold hit
  1011. split <;> split <;> split <;> simp_all <;> omega
  1012. theorem in_bound (x z y : Nat) (hxz : x ≠ z) (w : Word) :
  1013. bigram x y w + bigram z y w ≤ occ y w.tail := by
  1014. induction w with
  1015. | nil => simp [bigram, occ]
  1016. | cons a w ih =>
  1017. cases w with
  1018. | nil => simp [bigram, hit, occ]
  1019. | cons b w =>
  1020. change hit x y (some a) (some b) + bigram x y (b :: w) +
  1021. (hit z y (some a) (some b) + bigram z y (b :: w)) ≤ occ y (b :: w)
  1022. simp only [List.tail_cons] at ih
  1023. simp only [occ]
  1024. unfold hit
  1025. split <;> split <;> split <;> simp_all <;> omega
  1026. theorem tail_occ_le (a : Nat) (w : Word) : occ a w.tail ≤ occ a w := by
  1027. cases w <;> simp [occ]
  1028. def Factor (u w : Word) : Prop := ∃ l t, w = l ++ u ++ t
  1029. theorem factor_pos (x y : Nat) {u w : Word} (hu : Factor u w)
  1030. (h : 0 < bigram x y u) : 0 < bigram x y w := by
  1031. obtain ⟨l,t,rfl⟩ := hu
  1032. rw [bigram_append, bigram_append]
  1033. omega
  1034. def privatePhase (p q : Word) := p ++ p ++ q ++ p ++ q ++ q
  1035. private theorem private_boundaries {p q w : Word} {i j s t : Nat}
  1036. (hf : Factor (privatePhase p q) w)
  1037. (hp : p.head? = some i) (hq : q.head? = some j)
  1038. (ep : p.getLast? = some s) (eq : q.getLast? = some t) :
  1039. 0 < bigram s i w ∧ 0 < bigram s j w ∧ 0 < bigram t i w ∧ 0 < bigram t j w := by
  1040. have pn : p ≠ [] := by intro e; simp [e] at hp
  1041. have qn : q ≠ [] := by intro e; simp [e] at hq
  1042. refine ⟨factor_pos _ _ hf ?_, factor_pos _ _ hf ?_, factor_pos _ _ hf ?_, factor_pos _ _ hf ?_⟩ <;>
  1043. simp only [privatePhase, bigram_append, List.getLast?_append, ep, eq, hp, hq] <;>
  1044. simp [hit] <;> omega
  1045. private theorem safe_ends {p q w : Word} {i j s t x y r : Nat}
  1046. (hc : cap r w) (hf : Factor (privatePhase p q) w)
  1047. (hp : p.head? = some i) (hq : q.head? = some j)
  1048. (ep : p.getLast? = some s) (eq : q.getLast? = some t)
  1049. (hij : i ≠ j) (hst : s ≠ t) (hxy : Link r w x y) :
  1050. x ≠ s ∧ x ≠ t ∧ y ≠ i ∧ y ≠ j := by
  1051. obtain ⟨hsi,hsj,hti,htj⟩ := private_boundaries hf hp hq ep eq
  1052. have outs (a : Nat) (hai : 0 < bigram a i w) (haj : 0 < bigram a j w) : x ≠ a := by
  1053. intro h; subst a
  1054. by_cases hy : y = i
  1055. · subst y
  1056. have b := out_bound x i j hij w
  1057. have c := hc x
  1058. unfold Link at hxy
  1059. omega
  1060. · have b := out_bound x y i hy w
  1061. have c := hc x
  1062. unfold Link at hxy
  1063. omega
  1064. have ins (a : Nat) (hsa : 0 < bigram s a w) (hta : 0 < bigram t a w) : y ≠ a := by
  1065. intro h; subst a
  1066. by_cases hx : x = s
  1067. · subst x
  1068. have b := in_bound s t y hst w
  1069. have c := hc y
  1070. have d := tail_occ_le y w
  1071. unfold Link at hxy
  1072. omega
  1073. · have b := in_bound x s y hx w
  1074. have c := hc y
  1075. have d := tail_occ_le y w
  1076. unfold Link at hxy
  1077. omega
  1078. exact ⟨outs s hsi hsj, outs t hti htj, ins i hsi hti, ins j hsj htj⟩
  1079. private theorem safe_count_swap {p q : Word} {i j s t x y : Nat} (l u : Word)
  1080. (hp : p.head? = some i) (hq : q.head? = some j)
  1081. (ep : p.getLast? = some s) (eq : q.getLast? = some t)
  1082. (h : x ≠ s ∧ x ≠ t ∧ y ≠ i ∧ y ≠ j) :
  1083. bigram x y (l ++ p ++ q ++ u) = bigram x y (l ++ q ++ p ++ u) := by
  1084. obtain ⟨xs,xt,yi,yj⟩ := h
  1085. simp only [bigram_append, List.getLast?_append, ep, eq, hp, hq]
  1086. simp [hit, Ne.symm xs, Ne.symm xt, Ne.symm yi, Ne.symm yj]
  1087. omega
  1088. theorem repeatedLink_swap {p q : Word} {i j s t r : Nat} (l u : Word)
  1089. (hp : p.head? = some i) (hq : q.head? = some j)
  1090. (ep : p.getLast? = some s) (eq : q.getLast? = some t)
  1091. (hij : i ≠ j) (hst : s ≠ t)
  1092. (hc : cap r (l ++ p ++ q ++ u))
  1093. (hf : Factor (privatePhase p q) (l ++ p ++ q ++ u))
  1094. (hg : Factor (privatePhase p q) (l ++ q ++ p ++ u)) (x y : Nat) :
  1095. Link r (l ++ p ++ q ++ u) x y ↔ Link r (l ++ q ++ p ++ u) x y := by
  1096. have hd : cap r (l ++ q ++ p ++ u) := by
  1097. intro a
  1098. have b := hc a
  1099. simp only [occ_append] at b ⊢
  1100. omega
  1101. constructor
  1102. · intro h
  1103. have good := safe_ends hc hf hp hq ep eq hij hst h
  1104. exact (safe_count_swap l u hp hq ep eq good).symm.trans h
  1105. · intro h
  1106. have good := safe_ends hd hg hp hq ep eq hij hst h
  1107. exact (safe_count_swap l u hp hq ep eq good).trans h
  1108. /-- Nonoriented finite paths generate the repeated-block partition on
  1109. saturated letters. Singletons occur as paths of length zero. -/
  1110. inductive Joined (edges : Nat → Nat → Prop) : Nat → Nat → Prop where
  1111. | refl (x) : Joined edges x x
  1112. | extend {x y z} : Joined edges x y → (edges y z ∨ edges z y) → Joined edges x z
  1113. def SameBlock (r : Nat) (w : Word) (x y : Nat) : Prop :=
  1114. occ x w = r ∧ occ y w = r ∧ Joined (Link r w) x y
  1115. theorem sameBlock_swap {p q : Word} {i j s t r : Nat} (l u : Word)
  1116. (hp : p.head? = some i) (hq : q.head? = some j)
  1117. (ep : p.getLast? = some s) (eq : q.getLast? = some t)
  1118. (hij : i ≠ j) (hst : s ≠ t)
  1119. (hc : cap r (l ++ p ++ q ++ u))
  1120. (hf : Factor (privatePhase p q) (l ++ p ++ q ++ u))
  1121. (hg : Factor (privatePhase p q) (l ++ q ++ p ++ u)) (x y : Nat) :
  1122. SameBlock r (l ++ p ++ q ++ u) x y ↔ SameBlock r (l ++ q ++ p ++ u) x y := by
  1123. have e : Link r (l ++ p ++ q ++ u) = Link r (l ++ q ++ p ++ u) :=
  1124. funext fun a => funext fun b => propext (repeatedLink_swap l u hp hq ep eq hij hst hc hf hg a b)
  1125. simp only [SameBlock, e, occ_append]
  1126. constructor <;> rintro ⟨h1,h2,h3⟩ <;> exact ⟨by omega, by omega, h3⟩
  1127. /-- Every repeated link inside a proper or improper literal factor remains
  1128. a link of a capped enclosing word. To pull a block distinction back
  1129. from the enclosing tester, only this direction is needed. -/
  1130. theorem link_factor {r x y : Nat} {w u : Word} (f : Factor u w)
  1131. (hc : cap r w) (h : Link r u x y) : Link r w x y := by
  1132. have bound := out_bound x y (y+1) (by omega) w
  1133. have ceil := hc x
  1134. obtain ⟨l,t,rfl⟩ := f
  1135. unfold Link at *
  1136. rw [bigram_append, bigram_append] at bound ⊢
  1137. omega
  1138. private theorem joined_of_imp {e d : Nat → Nat → Prop} {a b : Nat}
  1139. (h : ∀ x y, e x y → d x y) (j : Joined e a b) : Joined d a b := by
  1140. induction j with
  1141. | refl => exact .refl _
  1142. | extend walk last ih =>
  1143. exact .extend ih (last.imp (h _ _) (h _ _))
  1144. theorem sameBlock_factor {r x y : Nat} {w u : Word} (f : Factor u w)
  1145. (hc : cap r w) (h : SameBlock r u x y) : SameBlock r w x y := by
  1146. obtain ⟨hx,hy,hj⟩ := h
  1147. refine ⟨?_,?_,joined_of_imp (fun _ _ hh => link_factor f hc hh) hj⟩
  1148. all_goals
  1149. obtain ⟨l,t,rfl⟩ := f
  1150. have bx := hc x
  1151. have by' := hc y
  1152. simp only [occ_append] at bx by' ⊢
  1153. omega
  1154. end Problem455Swap
  1155. end
  1156. /- Begin Problem455DonorInterval (from finite-semigroup-identity-bases). -/
  1157. section
  1158. namespace P455DonorInterval
  1159. universe u v
  1160. variable {α : Type u} {β : Type v} [DecidableEq α] [DecidableEq β]
  1161. /-- Count the contributions of one chosen donor and all other variables
  1162. separately, with equality for every source word. -/
  1163. theorem split_contributions (h : α → List β) (w : List α) (x : α) (s : β) :
  1164. (w.flatMap h).count s = w.count x * (h x).count s +
  1165. ((w.filter (fun a => decide (a ≠ x))).flatMap h).count s := by
  1166. induction w with
  1167. | nil => simp
  1168. | cons a w ih =>
  1169. by_cases e : a = x
  1170. · subst a
  1171. simp [List.count_cons, Nat.add_mul, ih, Nat.add_comm, Nat.add_left_comm, Nat.add_assoc]
  1172. · simp [List.count_cons, e, Ne.symm e, ih, Nat.add_comm, Nat.add_left_comm, Nat.add_assoc]
  1173. /-- A label contributed by a positively saturated source variable is
  1174. contributed exactly once per occurrence, and by no other variable
  1175. present in the evaluated side. A global cap only on this label suffices. -/
  1176. theorem exclusive (h : α → List β) (w : List α) (x : α) (s : β) (r : Nat)
  1177. (hr : 0 < r) (hx : w.count x = r) (mem : s ∈ h x)
  1178. (bound : (w.flatMap h).count s ≤ r) :
  1179. (h x).count s = 1 ∧
  1180. (∀ y ∈ w, y ≠ x → s ∉ h y) ∧ (w.flatMap h).count s = r := by
  1181. have spl := split_contributions h w x s
  1182. rw [hx] at spl
  1183. have pos := List.count_pos_iff.mpr mem
  1184. have one : (h x).count s = 1 := by
  1185. apply Classical.byContradiction
  1186. intro diff
  1187. have two : 2 ≤ (h x).count s := by omega
  1188. have ge := Nat.mul_le_mul_left r two
  1189. rw [Nat.mul_two] at ge
  1190. omega
  1191. rw [one,Nat.mul_one] at spl
  1192. have none : s ∉ (w.filter (fun a => decide (a ≠ x))).flatMap h :=
  1193. List.count_eq_zero.mp (by omega)
  1194. refine ⟨one,?_,by omega⟩
  1195. intro y hy hne in_y
  1196. apply none
  1197. exact List.mem_flatMap.mpr ⟨y,List.mem_filter.mpr ⟨hy,by simpa using hne⟩,in_y⟩
  1198. /-- Within any chosen sublist of the evaluated source, occurrence numbers
  1199. for an exclusively supplied label agree with those of its source variable. -/
  1200. theorem count_on_subword (h : α → List β) (w u : List α) (x : α) (s : β)
  1201. (inside : ∀ y ∈ u, y ∈ w) (single : (h x).count s = 1)
  1202. (exclusive : ∀ y ∈ w, y ≠ x → s ∉ h y) :
  1203. (u.flatMap h).count s = u.count x := by
  1204. induction u with
  1205. | nil => simp
  1206. | cons a u ih =>
  1207. have rest := ih (fun y hy => inside y (by simp [hy]))
  1208. by_cases eq : a = x
  1209. · subst a; simp [List.count_cons,single,rest,Nat.add_comm]
  1210. · have na := exclusive a (inside a (by simp)) eq
  1211. simp [List.count_cons,eq,Ne.symm eq,List.count_eq_zero.mpr na,rest]
  1212. /-- The literal open interval between corresponding consecutive copies of s.
  1213. The final equality identifies the zero-based index of its left endpoint;
  1214. the absence clause certifies consecutiveness in the output word. -/
  1215. theorem consecutive_interval (h : α → List β) (U L I R : List α)
  1216. (x : α) (s : β) (p q : List β) (r : Nat)
  1217. (cut : U = L ++ [x] ++ I ++ [x] ++ R) (consecutive : x ∉ I)
  1218. (image : h x = p ++ [s] ++ q)
  1219. (saturated : U.count x = r) (bounded : (U.flatMap h).count s ≤ r) :
  1220. (∀ y ∈ U, y ≠ x → s ∉ h y) ∧ s ∉ p ∧ s ∉ q ∧
  1221. s ∉ q ++ I.flatMap h ++ p ∧
  1222. U.flatMap h = (L.flatMap h ++ p) ++ [s] ++ (q ++ I.flatMap h ++ p) ++
  1223. [s] ++ (q ++ R.flatMap h) ∧
  1224. (L.flatMap h ++ p).count s = L.count x ∧ (U.flatMap h).count s = r := by
  1225. have hr : 0 < r := by
  1226. rw [← saturated]
  1227. exact List.count_pos_iff.mpr (by simp [cut])
  1228. have hx : s ∈ h x := by simp [image]
  1229. obtain ⟨single,noOther,full⟩ := exclusive h U x s r hr saturated hx bounded
  1230. have single' := single
  1231. simp only [image,List.count_append,List.count_singleton_self] at single'
  1232. have hp : s ∉ p := List.count_eq_zero.mp (by omega)
  1233. have hq : s ∉ q := List.count_eq_zero.mp (by omega)
  1234. have inner : (I.flatMap h).count s = I.count x := count_on_subword h U I x s
  1235. (fun y hy => by simp [cut,hy]) single noOther
  1236. have hi : s ∉ I.flatMap h := List.count_eq_zero.mp (inner.trans (List.count_eq_zero.mpr consecutive))
  1237. have left := count_on_subword h U L x s (fun y hy => by simp [cut,hy]) single noOther
  1238. exact ⟨noOther,hp,hq,by simp [hp,hq,hi],by simp [cut,image,List.flatMap_append,List.append_assoc],
  1239. by simp [left,List.count_eq_zero.mpr hp],full⟩
  1240. omit [DecidableEq α] [DecidableEq β] in
  1241. /-- Once an occupant is excluded from the boundary donor's image, some
  1242. literal name of the open source slot supplies it. No global condition
  1243. on the other images or gap alphabets enters this inference. -/
  1244. theorem interior_supplier (h : α → List β) (I : List α) (x : α) (s t : β)
  1245. (p q : List β) (image : h x = p ++ [s] ++ q)
  1246. (occupies : t ∈ q ++ I.flatMap h ++ p) (other : t ∉ h x) :
  1247. ∃ y ∈ I, t ∈ h y := by
  1248. have nowhere := other
  1249. simp only [image,List.mem_append,List.mem_singleton,not_or] at nowhere
  1250. simp only [List.mem_append] at occupies
  1251. rcases occupies with (hq | hi) | hp
  1252. · exact False.elim (nowhere.2 hq)
  1253. · exact List.mem_flatMap.mp hi
  1254. · exact False.elim (nowhere.1.1 hp)
  1255. /-- If the literal output is a factor of a capped enclosing variant, every
  1256. copy of s occurs in that factor. In particular external context cannot
  1257. change the absolute occurrence indices of its two slot endpoints. -/
  1258. theorem enclosing_context (F left right : List β) (s : β) (r : Nat)
  1259. (saturated : F.count s = r) (capped : (left ++ F ++ right).count s ≤ r) :
  1260. s ∉ left ∧ s ∉ right := by
  1261. simp only [List.count_append,saturated] at capped
  1262. exact ⟨List.count_eq_zero.mp (by omega),List.count_eq_zero.mp (by omega)⟩
  1263. end P455DonorInterval
  1264. end
  1265. /- Begin Problem455MathlibCode (from finite-semigroup-identity-bases). -/
  1266. section
  1267. namespace P455MathlibCode
  1268. open Turing Turing.PartrecToTM2
  1269. def pos : List Bool → PosNum
  1270. | [] => .one
  1271. | true :: xs => .bit1 (pos xs)
  1272. | false :: xs => .bit0 (pos xs)
  1273. def wire (xs : List Bool) : Nat := pos xs.reverse
  1274. def letter : Bool → Γ' | false => .bit0 | true => .bit1
  1275. theorem trPos (xs : List Bool) : trPosNum (pos xs) = xs.map letter ++ [.bit1] := by
  1276. induction xs with
  1277. | nil => rfl
  1278. | cons b xs ih => cases b <;> simp [pos,trPosNum,letter,ih]
  1279. theorem raw_main (xs : List Bool) :
  1280. (trList [wire xs]).reverse = .cons :: .bit1 :: xs.map letter := by
  1281. simp [wire,trNat,PosNum.of_to_nat,trNum,trPos,← List.map_reverse]
  1282. theorem pos_injective : Function.Injective pos := by
  1283. intro xs
  1284. induction xs with
  1285. | nil => rintro (_|⟨_ | _,_⟩) h <;> simp [pos] at *
  1286. | cons b xs ih =>
  1287. rintro (_ | ⟨c,cs⟩) h
  1288. · cases b <;> simp [pos] at h
  1289. · cases b <;> cases c <;> simp [pos] at h ⊢ <;> exact ih h
  1290. theorem wire_injective : Function.Injective wire := by
  1291. intro x y h
  1292. have hn := congrArg (fun n : Nat => (n : Num)) h
  1293. simp only [wire,PosNum.of_to_nat,Num.pos.injEq] at hn
  1294. simpa using congrArg List.reverse (pos_injective hn)
  1295. def op (b : Bool) (n : Nat) := if b = true then (n+n)+1 else n+n
  1296. theorem pos_fold (xs : List Bool) : (pos xs : Nat) = xs.foldr op 1 := by
  1297. induction xs with
  1298. | nil => rfl
  1299. | cons b xs ih => cases b <;> simp [pos,op,List.foldr,PosNum.cast_bit0,PosNum.cast_bit1,ih]
  1300. theorem wire_prim : Primrec wire := by
  1301. have h : Primrec (fun z : Bool × Nat => op z.1 z.2) := by
  1302. exact Primrec.ite (Primrec.eq.comp Primrec.fst (.const true))
  1303. (Primrec.nat_add.comp (Primrec.nat_add.comp Primrec.snd Primrec.snd) (.const 1))
  1304. (Primrec.nat_add.comp Primrec.snd Primrec.snd)
  1305. exact (Primrec.list_foldr Primrec.list_reverse (.const 1) (h.comp Primrec.snd).to₂).of_eq
  1306. fun xs => (pos_fold xs.reverse).symm
  1307. def candidate (n : Nat) := (Encodable.decode (α := List Bool) n).getD []
  1308. def check (z n : Nat) : Option (List Bool) :=
  1309. if wire (candidate n) = z then some (candidate n) else none
  1310. theorem check_prim : Primrec₂ check := by
  1311. have h : Primrec candidate := Primrec.option_getD.comp Primrec.decode (.const [])
  1312. exact (Primrec.ite (Primrec.eq.comp (wire_prim.comp (h.comp Primrec.snd)) Primrec.fst)
  1313. (Primrec.option_some.comp (h.comp Primrec.snd)) (.const none)).to₂
  1314. theorem find_wire (x : List Bool) : x ∈ Nat.rfindOpt (check (wire x)) := by
  1315. have ok : check (wire x) (Encodable.encode x) = some x := by simp [check,candidate]
  1316. have d := Nat.rfindOpt_dom.mpr ⟨_,x,ok⟩
  1317. have h := Part.get_mem d
  1318. obtain ⟨n, hn⟩ := Nat.rfindOpt_spec h
  1319. unfold check at hn
  1320. split at hn
  1321. next ht => exact Eq.mp (congrArg (fun b => b ∈ Nat.rfindOpt (check (wire x)))
  1322. ((Option.some.inj hn).symm.trans (wire_injective ht))) h
  1323. next => contradiction
  1324. /-- One finite partial-recursive instruction tree, fixed before all inputs,
  1325. operates on the sentinel-terminated positive integer wire codes. -/
  1326. theorem compile {f : List Bool → List Bool} (hf : Computable f) :
  1327. ∃ c : ToPartrec.Code, ∀ x, [wire (f x)] ∈ c.eval [wire x] := by
  1328. let F : Nat →. Nat := fun n => (Nat.rfindOpt (check n)).map (fun x => wire (f x))
  1329. have hF : Partrec F := (Partrec.rfindOpt check_prim.to_comp).map (((wire_prim.to_comp.comp hf).comp Computable.snd).to₂)
  1330. obtain ⟨c,hc⟩ := ToPartrec.Code.exists_code (Nat.Partrec'.part_iff₁.mpr hF)
  1331. refine ⟨c,fun x => ?_⟩
  1332. let v : List.Vector Nat 1 := ⟨[wire x],rfl⟩
  1333. rw [show c.eval [wire x] = _ from hc v]
  1334. exact (Part.mem_map_iff _).mpr ⟨_,(Part.mem_map_iff _).mpr ⟨_,find_wire x,rfl⟩,rfl⟩
  1335. end P455MathlibCode
  1336. end
  1337. /- Begin Problem455MathlibMarker (from finite-semigroup-identity-bases). -/
  1338. section
  1339. namespace P455MathlibMarker
  1340. open Turing
  1341. variable {K : Type} {G : K → Type} {L V : Type} [DecidableEq K]
  1342. abbrev Track := TM2to1.Γ' K G
  1343. def safe : TM1.Stmt (Track (G := G)) L V → Prop
  1344. | .move _ s | .load _ s => safe s
  1345. | .write w s => (∀ a v, (w a v).1 = a.1) ∧ safe s
  1346. | .branch _ p q => safe p ∧ safe q
  1347. | .goto _ | .halt => True
  1348. omit [DecidableEq K] in
  1349. theorem trNormal_safe (s : TM2.Stmt G L V) : safe (TM2to1.trNormal s) := by
  1350. induction s <;> simp_all [TM2to1.trNormal,safe]
  1351. theorem tr_safe (M : L → TM2.Stmt G L V) (q) : safe (TM2to1.tr M q) := by
  1352. cases q with
  1353. | normal => exact trNormal_safe _
  1354. | ret => exact ⟨trNormal_safe _,True.intro⟩
  1355. | go k s q => cases s <;> simp [TM2to1.tr,TM2to1.trStAct,safe]
  1356. variable [Inhabited L] [Inhabited V]
  1357. variable (M : L → TM1.Stmt (Track (G := G)) L V)
  1358. def safeState (q : TM1to0.Λ' M) := ∀ p ∈ q.1, safe p
  1359. def preserves (a : Track (G := G)) : TM0.Stmt (Track (G := G)) → Prop
  1360. | .move _ => True
  1361. | .write b => b.1=a.1
  1362. variable (hm : ∀ l, safe (M l))
  1363. include hm
  1364. omit [DecidableEq K] [Inhabited L] [Inhabited V] in
  1365. theorem trAux_safe (a : Track (G := G)) (p : TM1.Stmt (Track (G := G)) L V)
  1366. (hp : safe p) (v) :
  1367. safeState M (TM1to0.trAux M a p v).1 ∧ preserves a (TM1to0.trAux M a p v).2 := by
  1368. induction p generalizing v with
  1369. | move _ q => simpa [TM1to0.trAux,safeState,preserves,safe] using hp
  1370. | write w q => exact ⟨fun _ h => Option.some.inj h ▸ hp.2, hp.1 _ _⟩
  1371. | load _ _ ih => exact ih hp _
  1372. | branch b p q ih₁ ih₂ =>
  1373. cases e : b a v <;> simp only [TM1to0.trAux,e,cond] <;> first | exact ih₁ hp.1 v | exact ih₂ hp.2 v
  1374. | goto l => simpa [TM1to0.trAux,safeState,preserves] using hm (l a v)
  1375. | halt => simp [TM1to0.trAux,safeState,preserves]
  1376. omit [DecidableEq K] in
  1377. theorem guarded {S : Finset (TM1to0.Λ' M)} (hs : TM0.Supports (TM1to0.tr M) ↑S) :
  1378. ∃ U : Finset (TM1to0.Λ' M), TM0.Supports (TM1to0.tr M) ↑U ∧
  1379. ∀ q ∈ U, ∀ a q' b, (TM1to0.tr M) q a = some (q',.write b) → b.1=a.1 := by
  1380. classical
  1381. refine ⟨S.filter (safeState M), ⟨?_,?_⟩,?_⟩
  1382. · apply Finset.mem_filter.mpr
  1383. refine ⟨hs.1, ?_⟩
  1384. intro p hp
  1385. change some (M default) = some p at hp
  1386. exact (Option.some.inj hp) ▸ hm default
  1387. · rintro ⟨_ | p,v⟩ a q' s step good
  1388. · contradiction
  1389. obtain ⟨mem,safeP⟩ := Finset.mem_filter.mp good
  1390. have hp := safeP p rfl
  1391. have h := (trAux_safe M hm a p hp v).1
  1392. exact Finset.mem_filter.mpr ⟨hs.2 step mem,(congrArg (safeState M) (congrArg Prod.fst (Option.some.inj step))).mp h⟩
  1393. · rintro ⟨_ | p,v⟩ good a q' b step
  1394. · contradiction
  1395. have hp := (Finset.mem_filter.mp good).2 p rfl
  1396. have h := (trAux_safe M hm a p hp v).2
  1397. exact (congrArg (preserves a) (congrArg Prod.snd (Option.some.inj step))).mp h
  1398. end P455MathlibMarker
  1399. end
  1400. /- Begin Problem455ObservationBridge (from finite-semigroup-identity-bases). -/
  1401. section
  1402. /- Literal profile-frame move and the observations of marked testers.
  1403. Names are natural numbers. All occurrence indices in this file are zero-based. -/
  1404. namespace P455Closure.Move
  1405. open Problem455
  1406. variable {r : Nat} {Allowed : List Bool → Prop} {Mark : Nat → Nat → Prop}
  1407. {u v : List Nat}
  1408. /-- Extract adjacent, commonly indexed block occurrences from a literal frame.
  1409. No position, marked projection, or protected-slot preservation is a premise. -/
  1410. theorem asSlotMove (h : P455Closure.Move r Allowed Mark u v) :
  1411. ∃ s : Slots.Move (r-2), u = Slots.before s ∧ v = Slots.after s ∧
  1412. (∀ a ∈ s.p, ∀ b ∈ s.q, ¬ Mark a b ∧ ¬ Mark b a) ∧ 16 ≤ r := by
  1413. obtain ⟨f,bit,l,t,hf,hu,hv,hc⟩ := h
  1414. have hr := hf.1
  1415. have hx : ∀ x, x ∈ f.p ∨ x ∈ f.q →
  1416. (l ++ f.early ++ f.mid ++ f.beforeMutable).count x = r-2 := by
  1417. intro x hx
  1418. have hh := f.mutable_index hf bit l t (hu ▸ hc) x hx
  1419. omega
  1420. obtain ⟨_,_,_,np,nq,dis,marks,_⟩ := hf
  1421. let s : Slots.Move (r-2) :=
  1422. { pre := l ++ f.early ++ f.mid ++ f.beforeMutable
  1423. p := f.p
  1424. q := f.q
  1425. post := f.beforeFinalP ++ f.p ++ f.beforeFinalQ ++ f.q ++ t
  1426. dp := np
  1427. dq := nq
  1428. disjoint := dis
  1429. indexP := fun x m => hx x (.inl m)
  1430. indexQ := fun x m => hx x (.inr m) }
  1431. cases bit with
  1432. | false =>
  1433. refine ⟨s,?_,?_,marks,by omega⟩ <;>
  1434. simp [s, hu, hv, Slots.before, Slots.after, Frame.core, Frame.pair, List.append_assoc]
  1435. | true =>
  1436. let t' : Slots.Move (r-2) :=
  1437. { pre := s.pre
  1438. p := s.q
  1439. q := s.p
  1440. post := s.post
  1441. dp := s.dq
  1442. dq := s.dp
  1443. disjoint := fun x hx hx' => s.disjoint x hx' hx
  1444. indexP := s.indexQ
  1445. indexQ := s.indexP }
  1446. refine ⟨t',?_,?_,(fun x hx y hy => (marks y hy x hx).symm),by omega⟩ <;>
  1447. simp [s, t', hu, hv, Slots.before, Slots.after, Frame.core, Frame.pair, List.append_assoc]
  1448. theorem order_iff (h : P455Closure.Move r Allowed Mark u v) (pat : List Slots.Event)
  1449. (idx : ∀ e ∈ pat, e.2 ≠ r-2) : Slots.sees u pat ↔ Slots.sees v pat := by
  1450. obtain ⟨s,rfl,rfl,_⟩ := asSlotMove h
  1451. exact Slots.immutable_pattern s pat idx
  1452. theorem slot_iff (h : P455Closure.Move r Allowed Mark u v) (owner i a : Nat)
  1453. (hi : Slots.slotStart i) : Slots.occupies u owner i a ↔ Slots.occupies v owner i a := by
  1454. obtain ⟨s,rfl,rfl,_,hr⟩ := asSlotMove h
  1455. have h1 : i ≠ r-2 := by unfold Slots.slotStart at hi; omega
  1456. have h2 : i+1 ≠ r-2 := by unfold Slots.slotStart at hi; omega
  1457. exact exists_congr (fun j => Slots.open_slot_event s owner i (i+1) (a,j) h1 h2)
  1458. theorem marked_proj (h : P455Closure.Move r Allowed Mark u v) (a b : Nat)
  1459. (hm : Mark a b) : Slots.select [a,b] u = Slots.select [a,b] v := by
  1460. obtain ⟨s,rfl,rfl,marks,_⟩ := asSlotMove h
  1461. apply Slots.protected_projection
  1462. by_cases hap : a ∈ s.p
  1463. · right
  1464. intro x hx
  1465. simp only [List.mem_cons, List.not_mem_nil, or_false, not_or]
  1466. exact ⟨fun eq => s.disjoint a hap (eq ▸ hx),
  1467. fun eq => (marks a hap b (eq ▸ hx)).1 hm⟩
  1468. · by_cases hbp : b ∈ s.p
  1469. · right
  1470. intro x hx
  1471. simp only [List.mem_cons, List.not_mem_nil, or_false, not_or]
  1472. exact ⟨fun eq => (marks b hbp a (eq ▸ hx)).2 hm,
  1473. fun eq => s.disjoint b hbp (eq ▸ hx)⟩
  1474. · left
  1475. intro x hx
  1476. simp only [List.mem_cons, List.not_mem_nil, or_false, not_or]
  1477. exact ⟨fun eq => hap (eq ▸ hx),fun eq => hbp (eq ▸ hx)⟩
  1478. theorem typed_iff (h : P455Closure.Move r Allowed Mark u v) (a b : Nat)
  1479. (tag : List Bool) (hne : a ≠ b) (hlen : tag.length+16 = r) :
  1480. Slots.typed u a b tag ↔ Slots.typed v a b tag := by
  1481. constructor
  1482. · obtain ⟨s,rfl,rfl,_⟩ := asSlotMove h
  1483. exact Slots.type_forward s a b tag hne (by omega)
  1484. · obtain ⟨s,hu,hv,_⟩ := asSlotMove h.symm
  1485. rw [hu,hv]
  1486. exact Slots.type_forward s a b tag hne (by omega)
  1487. end P455Closure.Move
  1488. end
  1489. /- Begin Problem455Finite (from finite-semigroup-identity-bases). -/
  1490. section
  1491. namespace Problem455Finite
  1492. def rules (r : Nat) (allow : List Bool → Prop) (mark : Nat → Nat → Prop) :
  1493. P455Quotient.Rules Nat where
  1494. r := r
  1495. step := P455Closure.Move r allow mark
  1496. reverse := P455Closure.Move.symm
  1497. counts := P455Closure.Move.count_eq
  1498. extend h l t := P455Closure.Move.extend_of_cap h l t
  1499. open P455Quotient
  1500. /-- Enumerate all words of length at most n on the input list alphabet.
  1501. Duplicates in the alphabet are harmless. -/
  1502. def wordsUpTo (alphabet : List α) : Nat → List (List α)
  1503. | 0 => [[]]
  1504. | n+1 => [] :: alphabet.flatMap (fun a => (wordsUpTo alphabet n).map (List.cons a))
  1505. theorem covered (a : List α) (n : Nat) (w : List α) (len : w.length ≤ n)
  1506. (names : ∀ x ∈ w, x ∈ a) : w ∈ wordsUpTo a n := by
  1507. induction n generalizing w with
  1508. | zero =>
  1509. cases w <;> simp_all [wordsUpTo]
  1510. | succ n ih =>
  1511. cases w with
  1512. | nil => simp [wordsUpTo]
  1513. | cons x w =>
  1514. have hx := names x (by simp)
  1515. have hl : w.length ≤ n := by simpa using len
  1516. have hw := ih w hl (fun z hz => names z (by simp [hz]))
  1517. apply List.mem_cons_of_mem
  1518. apply List.mem_flatMap.mpr
  1519. exact ⟨x,hx,List.mem_map.mpr ⟨w,hw,rfl⟩⟩
  1520. theorem good_bound [DecidableEq α] (R : Rules α) (T w : Word α)
  1521. (good : Good R T w) : w.length ≤ T.length ∧ ∀ x ∈ w, x ∈ T := by
  1522. obtain ⟨v,path,l,t,hv⟩ := good
  1523. have perm := List.perm_iff_count.mpr (count_walk R path)
  1524. have len := perm.length_eq
  1525. refine ⟨?_,?_⟩
  1526. · simp only [hv,List.length_append] at len
  1527. omega
  1528. · intro x hx
  1529. apply perm.mem_iff.mpr
  1530. simp [hv,hx]
  1531. /-- A list of every quotient element, possibly with repeated entries.
  1532. This enumerates the explicit zero even for an empty template. -/
  1533. def carrier [DecidableEq α] (R : Rules α) (T : Word α) : List (Q R T) :=
  1534. zero R T :: (wordsUpTo T T.length).map (ofWord R T)
  1535. theorem carrier_complete [DecidableEq α] (R : Rules α) (T : Word α) (q : Q R T) :
  1536. q ∈ carrier R T := by
  1537. by_cases dead : q = zero R T
  1538. · simp [carrier,dead]
  1539. · obtain ⟨w,good,e⟩ := nonzero_representative R q dead
  1540. obtain ⟨len,names⟩ := good_bound R T w good
  1541. exact List.mem_cons_of_mem _ (List.mem_map.mpr ⟨w, covered T T.length w len names, e⟩)
  1542. end Problem455Finite
  1543. end
  1544. /- Begin Problem455BlockBridge (from finite-semigroup-identity-bases). -/
  1545. section
  1546. namespace Problem455BlockBridge
  1547. open P455Closure
  1548. open Problem455Swap
  1549. theorem occ_count (a : Nat) (w : List Nat) : occ a w = w.count a := by
  1550. induction w with
  1551. | nil => rfl
  1552. | cons b w ih =>
  1553. by_cases h : a = b
  1554. · subst b; simp [occ, ih, List.count_cons, Nat.add_comm]
  1555. · simp [occ, ih, List.count_cons, h, Ne.symm h]
  1556. private def leftPart (f : Frame Nat) (l : List Nat) :=
  1557. l ++ f.early ++ f.mid ++ f.beforeMutable
  1558. private def rightPart (f : Frame Nat) (t : List Nat) :=
  1559. f.beforeFinalP ++ f.p ++ f.beforeFinalQ ++ f.q ++ t
  1560. private theorem frame_false (f : Frame Nat) (l t : List Nat) :
  1561. l ++ f.core false ++ t = leftPart f l ++ f.p ++ f.q ++ rightPart f t := by
  1562. simp [leftPart, rightPart, Frame.core, Frame.pair, List.append_assoc]
  1563. private theorem frame_true (f : Frame Nat) (l t : List Nat) :
  1564. l ++ f.core true ++ t = leftPart f l ++ f.q ++ f.p ++ rightPart f t := by
  1565. simp [leftPart, rightPart, Frame.core, Frame.pair, List.append_assoc]
  1566. private theorem early_factor (f : Frame Nat) (l t : List Nat) (b : Bool) :
  1567. Factor (privatePhase f.p f.q) (l ++ f.core b ++ t) := by
  1568. refine ⟨l, f.mid ++ f.beforeMutable ++ f.pair b ++ f.beforeFinalP ++ f.p ++
  1569. f.beforeFinalQ ++ f.q ++ t, ?_⟩
  1570. simp [Frame.core, Frame.early, privatePhase, List.append_assoc]
  1571. private theorem frameLink {r : Nat} {allow : List Bool → Prop} {mark : Nat → Nat → Prop}
  1572. (f : Frame Nat) (l t : List Nat) (wf : f.Valid r allow mark)
  1573. (hc : Cap r (l ++ f.core false ++ t)) (x y : Nat) :
  1574. Link r (l ++ f.core false ++ t) x y ↔ Link r (l ++ f.core true ++ t) x y := by
  1575. have pn : f.p ≠ [] := by simp [Frame.p]
  1576. have qn : f.q ≠ [] := by simp [Frame.q]
  1577. let i := f.pHead
  1578. let j := f.q.head qn
  1579. let s := f.p.getLast pn
  1580. let z := f.qLast
  1581. have hp : f.p.head? = some i := rfl
  1582. have hq : f.q.head? = some j := List.head?_eq_head qn
  1583. have ep : f.p.getLast? = some s := List.getLast?_eq_getLast pn
  1584. have eq : f.q.getLast? = some z := by simp [Frame.q,z]
  1585. have disj := wf.2.2.2.2.2.1
  1586. have hpMem : i ∈ f.p := by simp [i, Frame.p]
  1587. have hqMem : j ∈ f.q := List.head_mem _
  1588. have epMem : s ∈ f.p := List.getLast_mem _
  1589. have eqMem : z ∈ f.q := by simp [z,Frame.q]
  1590. have hij : i ≠ j := fun h => disj i hpMem (h ▸ hqMem)
  1591. have hsz : s ≠ z := fun h => disj s epMem (h ▸ eqMem)
  1592. have cf : cap r (l ++ f.core false ++ t) := by
  1593. intro a
  1594. rw [occ_count]
  1595. exact hc a
  1596. have ef := early_factor f l t false
  1597. have et := early_factor f l t true
  1598. rw [frame_false] at cf ef ⊢
  1599. rw [frame_true] at et ⊢
  1600. exact repeatedLink_swap _ _ hp hq ep eq hij hsz cf ef et x y
  1601. /-- Invariance of each repeated adjacent pair under the actual frame move. -/
  1602. theorem move_link {r : Nat} {allow : List Bool → Prop} {mark : Nat → Nat → Prop}
  1603. {u v : List Nat} (h : Move r allow mark u v) (x y : Nat) :
  1604. Link r u x y ↔ Link r v x y := by
  1605. have hd := h.cap_right
  1606. obtain ⟨f,b,l,t,hf,rfl,rfl,hc⟩ := h
  1607. cases b
  1608. · exact frameLink f l t hf hc x y
  1609. · exact (frameLink f l t hf hd x y).symm
  1610. /-- The repeated-block relation consists of saturated endpoints and paths
  1611. in the fixed graph of repeated links. -/
  1612. theorem move_sameBlock {r : Nat} {allow : List Bool → Prop} {mark : Nat → Nat → Prop}
  1613. {u v : List Nat} (h : Move r allow mark u v) (x y : Nat) :
  1614. SameBlock r u x y ↔ SameBlock r v x y := by
  1615. have rel : Link r u = Link r v := funext fun a => funext fun b => propext (move_link h a b)
  1616. simp only [SameBlock,rel,occ_count,h.count_eq]
  1617. end Problem455BlockBridge
  1618. end
  1619. /- Begin Problem455MathlibTM (from finite-semigroup-identity-bases). -/
  1620. section
  1621. /- The compilation fixes a finite machine before the input. Its exact
  1622. terminal tape equals the same physical encoding of the output list. -/
  1623. namespace P455MathlibTM
  1624. open Turing PartrecToTM2 P455MathlibCode
  1625. abbrev Track := TM2to1.Γ' K' (fun _ => Γ')
  1626. instance stackFinite : Fintype K' :=
  1627. ⟨{.main,.rev,.aux,.stack},fun k => by cases k <;> simp⟩
  1628. def cell (bottom : Bool) (s : Γ') : Track :=
  1629. (bottom, Function.update (fun _ => none) K'.main (some s))
  1630. def image (x : List Bool) : List Track :=
  1631. cell true .cons :: cell false .bit1 :: x.map (fun b => cell false (letter b))
  1632. theorem tr_input (x : List Bool) :
  1633. TM2to1.trInit (Γ := fun _ => Γ') K'.main (trList [wire x]) = image x := by
  1634. unfold TM2to1.trInit
  1635. rw [raw_main]
  1636. simp [image,cell,List.map_map,Function.comp_def,List.headI]
  1637. theorem unique_sim {K : Type} {G : K → Type} {L V : Type}
  1638. {u : TM2.Cfg G L V} {a b}
  1639. (ha : TM2to1.TrCfg u a) (hb : TM2to1.TrCfg u b) : a=b := by
  1640. cases ha with
  1641. | mk t ht =>
  1642. cases hb with
  1643. | mk s hs =>
  1644. have eq : t=s := by
  1645. apply ListBlank.ext
  1646. intro n
  1647. funext k
  1648. have h := congrArg (fun z => ListBlank.nth z n) ((ht k).trans (hs k).symm)
  1649. simpa only [proj_map_nth] using h
  1650. subst s
  1651. rfl
  1652. private theorem final_config {K : Type} {G : K → Type} {L V : Type}
  1653. {u : TM2.Cfg G L V} {a} (h : TM2to1.TrCfg u a) (val : V) :
  1654. TM2to1.TrCfg ⟨(none : Option L),val,u.stk⟩ ⟨none,val,a.Tape⟩ := by
  1655. cases h with
  1656. | mk t ht => exact .mk t ht
  1657. private theorem stack_update (x : List Γ') :
  1658. Function.update (fun _ : K' => ([] : List Γ')) .main x = K'.elim x [] [] [] := by
  1659. funext k
  1660. cases k <;> simp [K'.elim,Function.update]
  1661. /-- Finiteness of the actual alphabet, a finite support of reachable
  1662. control labels and full bilateral tape equality at a genuine halt. -/
  1663. theorem supported {f : List Bool → List Bool} (hf : Computable f) :
  1664. ∃ (L : Type) (_ : Inhabited L) (M : TM0.Machine Track L) (S : Finset L),
  1665. TM0.Supports M (S : Set L) ∧
  1666. (∀ q ∈ S, ∀ a q' b, M q a = some (q',.write b) → b.1=a.1) ∧
  1667. ∀ x, ∃ q, (⟨q,Tape.mk₁ (image (f x))⟩ : TM0.Cfg Track L) ∈
  1668. StateTransition.eval (TM0.step M) (TM0.init (image x)) := by
  1669. classical
  1670. obtain ⟨c, hc⟩ := compile hf
  1671. letI : Inhabited PartrecToTM2.Λ' := ⟨trNormal c .halt⟩
  1672. let M₁ := TM2to1.tr PartrecToTM2.tr
  1673. let M₀ := TM1to0.tr M₁
  1674. obtain ⟨S,hs,mark⟩ := P455MathlibMarker.guarded M₁ (P455MathlibMarker.tr_safe _)
  1675. (TM1to0.tr_supports M₁ (TM2to1.tr_supports _ (PartrecToTM2.tr_supports c .halt)))
  1676. refine ⟨_,inferInstance,M₀,S,hs,mark,?_⟩
  1677. intro x
  1678. let v := [wire x]
  1679. let w := [wire (f x)]
  1680. have run : PartrecToTM2.halt w ∈ StateTransition.eval (TM2.step PartrecToTM2.tr) (PartrecToTM2.init c v) := by
  1681. rw [PartrecToTM2.tr_eval]
  1682. exact (Part.mem_map_iff _).mpr ⟨_,hc x,rfl⟩
  1683. have e (u : List Nat) : PartrecToTM2.init c u = TM2.init (Λ := PartrecToTM2.Λ') (σ := Option Γ') K'.main (trList u) := by
  1684. simp [PartrecToTM2.init,TM2.init,stack_update]
  1685. rfl
  1686. rw [e] at run
  1687. obtain ⟨b, hb, rb⟩ := StateTransition.tr_eval (TM2to1.tr_respects PartrecToTM2.tr)
  1688. (TM2to1.trCfg_init (Γ := fun _ : K' => Γ') (Λ := PartrecToTM2.Λ') (σ := Option Γ') K'.main (trList v)) run
  1689. have standard := TM2to1.trCfg_init (Γ := fun _ : K' => Γ') (Λ := PartrecToTM2.Λ') (σ := Option Γ') K'.main (trList w)
  1690. have target := final_config standard (none : Option Γ')
  1691. simp only [TM2.init,stack_update,TM1.init] at target
  1692. have eq := unique_sim hb target
  1693. subst b
  1694. obtain ⟨d, hd, rd⟩ := StateTransition.tr_eval (TM1to0.tr_respects M₁) rfl rb
  1695. subst d
  1696. refine ⟨(none,none),?_⟩
  1697. dsimp only [v,w] at rd
  1698. rw [tr_input, tr_input] at rd
  1699. change (⟨(none, none), Tape.mk₁ (image (f x))⟩ : TM0.Cfg Track (TM1to0.Λ' M₁)) ∈
  1700. StateTransition.eval (TM0.step (TM1to0.tr M₁))
  1701. ⟨(some (M₁ default), none), Tape.mk₁ (image x)⟩
  1702. exact rd
  1703. end P455MathlibTM
  1704. end
  1705. /- Begin Problem455FactorSlots (from finite-semigroup-identity-bases). -/
  1706. section
  1707. namespace Problem455.Slots
  1708. def shift (n : Nat → Nat) (e : Event) : Event := (e.1, n e.1 + e.2)
  1709. def unshift (n : Nat → Nat) (e : Event) : Event := (e.1, e.2 - n e.1)
  1710. @[simp] theorem unshift_shift (n : Nat → Nat) (e : Event) :
  1711. unshift n (shift n e) = e := by cases e; simp [unshift, shift, Nat.add_sub_cancel_left]
  1712. theorem stamp_shift (extra n : Nat → Nat) (w : Word) :
  1713. stamp (fun x => extra x + n x) w = (stamp n w).map (shift extra) := by
  1714. induction w generalizing n with
  1715. | nil => rfl
  1716. | cons a w ih =>
  1717. have he : advance (fun x => extra x + n x) [a] =
  1718. (fun x => extra x + advance n [a] x) := by funext x; simp [advance, Nat.add_assoc]
  1719. simp only [stamp, List.map_cons, he, ih, shift]
  1720. theorem labels_of_stamp (n : Nat → Nat) (w : Word) :
  1721. (stamp n w).map Prod.fst = w := by
  1722. induction w generalizing n with
  1723. | nil => rfl
  1724. | cons a w ih => simp [stamp, ih]
  1725. theorem stamped_mem_label (n : Nat → Nat) (w : Word) (e : Event)
  1726. (h : e ∈ stamp n w) : e.1 ∈ w := by
  1727. rw [← labels_of_stamp n w]
  1728. exact List.mem_map_of_mem h
  1729. theorem events_of_factor (l f t : Word) :
  1730. events (l ++ f ++ t) =
  1731. events l ++ ((events f).map (shift (fun a => l.count a)) ++
  1732. stamp (fun a => l.count a + f.count a) t) := by
  1733. have hn : advance (fun _ => 0) l = (fun a => l.count a) := by funext a; simp [advance]
  1734. have hh := stamp_shift (fun a => l.count a) (fun _ => 0) f
  1735. simp only [Nat.add_zero] at hh
  1736. simp only [List.append_assoc, events, stamp_append, hn, hh]
  1737. rfl
  1738. private theorem trim_left {α : Type} {a : α} {pat u v : List α}
  1739. (ha : a ∉ u) (h : (a :: pat).Sublist (u ++ v)) : (a :: pat).Sublist v := by
  1740. induction u with
  1741. | nil => exact h
  1742. | cons c u ih =>
  1743. cases h with
  1744. | cons _ h => exact ih (fun hh => ha (by simp [hh])) h
  1745. | cons_cons _ _ => exact False.elim (ha (by simp))
  1746. private theorem trim_three {α : Type} {a e b : α} {l f t : List α}
  1747. (ha : a ∉ l) (hb : b ∉ t) :
  1748. [a,e,b].Sublist (l ++ (f ++ t)) ↔ [a,e,b].Sublist f := by
  1749. constructor
  1750. · intro h
  1751. have h' := (trim_left ha h).reverse
  1752. simp only [List.reverse_append, List.reverse_cons, List.reverse_nil, List.nil_append,
  1753. List.cons_append, List.singleton_append] at h'
  1754. have hh := (trim_left (by simpa using hb : b ∉ t.reverse) h').reverse
  1755. simpa using hh
  1756. · intro h
  1757. exact List.sublist_append_of_sublist_right (List.sublist_append_of_sublist_left h)
  1758. /-- No assumption on the number of outside copies of the occupant. Its
  1759. occurrence number is shifted on entering the surrounding word. -/
  1760. theorem factor_occupies (l f t : Word) (owner i a : Nat) (hl : owner ∉ l) (ht : owner ∉ t) :
  1761. occupies (l ++ f ++ t) owner i a ↔ occupies f owner i a := by
  1762. have hz := List.count_eq_zero.mpr hl
  1763. have left : (owner, i) ∉ events l := fun hm => hl (stamped_mem_label _ _ _ hm)
  1764. have right : (owner, i + 1) ∉ stamp (fun x => l.count x + f.count x) t :=
  1765. fun hm => ht (stamped_mem_label _ _ _ hm)
  1766. let n := fun x => l.count x
  1767. have shiftS : ∀ j, unshift n (owner,j) = (owner,j) := by simp [unshift, n, hz]
  1768. have shiftF : ∀ j, shift n (owner,j) = (owner,j) := by simp [shift,n,hz]
  1769. constructor
  1770. · rintro ⟨k,h⟩
  1771. unfold sees at h
  1772. rw [events_of_factor] at h
  1773. have hh := ((trim_three left right).mp h).map (unshift n)
  1774. refine ⟨k-n a,?_⟩
  1775. simpa [sees, List.map_map, Function.comp_def, Nat.add_sub_cancel_left, shiftS, unshift, shift, n, hz] using hh
  1776. · rintro ⟨k,h⟩
  1777. refine ⟨n a+k,?_⟩
  1778. unfold sees
  1779. rw [events_of_factor]
  1780. apply (trim_three left right).mpr
  1781. have hh := h.map (shift n)
  1782. simpa [shiftF, shift, n, hz] using hh
  1783. /-- In a capped variant, saturation in a factor supplies the owner hypothesis.
  1784. This also applies to non-consecutive arbitrary slot endpoints through the
  1785. underlying three-event trimming lemma. -/
  1786. theorem saturated_factor_occupies (l f t : Word) (owner i a r : Nat)
  1787. (cap : P455Closure.Cap r (l ++ f ++ t)) (sat : f.count owner = r) :
  1788. occupies (l ++ f ++ t) owner i a ↔ occupies f owner i a := by
  1789. have h := cap owner
  1790. simp only [List.count_append, sat] at h
  1791. exact factor_occupies l f t owner i a
  1792. (List.count_eq_zero.mp (by omega)) (List.count_eq_zero.mp (by omega))
  1793. theorem saturated_factor_sees (l f t : Word) (pat : List Event) (r : Nat)
  1794. (cap : P455Closure.Cap r (l ++ f ++ t))
  1795. (sat : ∀ e ∈ pat, f.count e.1 = r) :
  1796. sees (l ++ f ++ t) pat ↔ sees f pat := by
  1797. have fresh : ∀ e ∈ pat, l.count e.1 = 0 ∧ e.1 ∉ t := by
  1798. intro e he
  1799. have hh := cap e.1
  1800. simp only [List.count_append, sat e he] at hh
  1801. exact ⟨by omega,List.count_eq_zero.mp (by omega)⟩
  1802. let n := fun x => l.count x
  1803. have left : ∀ e ∈ pat, e ∉ events l := fun e he hc =>
  1804. (List.count_eq_zero.mp (fresh e he).1) (stamped_mem_label _ _ _ hc)
  1805. have right : ∀ e ∈ pat, e ∉ stamp (fun x => l.count x + f.count x) t := fun e he hc =>
  1806. (fresh e he).2 (stamped_mem_label _ _ _ hc)
  1807. have hs : pat.map (shift n) = pat := by
  1808. conv => rhs; rw [← List.map_id (l := pat)]
  1809. apply List.map_congr_left
  1810. intro e he
  1811. simp [shift,n,(fresh e he).1]
  1812. have hr : pat.map (unshift n) = pat := by
  1813. conv => rhs; rw [← List.map_id (l := pat)]
  1814. apply List.map_congr_left
  1815. intro e he
  1816. simp [unshift,n,(fresh e he).1]
  1817. unfold sees
  1818. rw [events_of_factor]
  1819. constructor
  1820. · intro h
  1821. have mid := (h.of_sublist_append_right left).of_sublist_append_left right
  1822. have hh := mid.map (unshift n)
  1823. simpa [hr, List.map_map, Function.comp_def, Nat.add_sub_cancel_left, unshift, shift, n] using hh
  1824. · intro h
  1825. have hh := h.map (shift n)
  1826. rw [hs] at hh
  1827. exact List.sublist_append_of_sublist_right (List.sublist_append_of_sublist_left hh)
  1828. /- If an occupant is not saturated, its occurrence number can change even
  1829. when the owner is saturated. Here 3 is the owner and the leading 7 is
  1830. outside the factor. These closed examples are separate from the lemmas. -/
  1831. example : sees [3,7,3] [(3,0),(7,0),(3,1)] := by unfold sees; decide
  1832. example : ¬ sees [7,3,7,3] [(3,0),(7,0),(3,1)] := by unfold sees; decide
  1833. example : sees [7,3,7,3] [(3,0),(7,1),(3,1)] := by unfold sees; decide
  1834. end Problem455.Slots
  1835. end
  1836. /- Begin Problem455Uncrossed (from finite-semigroup-identity-bases). -/
  1837. section
  1838. namespace P455Uncrossed
  1839. open P455Closure Problem455Finite
  1840. abbrev W := List Nat
  1841. abbrev Tags := List Bool → Prop
  1842. abbrev Marks := Nat → Nat → Prop
  1843. def side (f : Frame Nat) (l k : W) (bit : Bool) := l ++ f.core bit ++ k
  1844. def Unmarked (mark : Marks) (h : Nat → W) (x y : Nat) : Prop :=
  1845. ∀ a ∈ h x, ∀ b ∈ h y, ¬ mark a b ∧ ¬ mark b a
  1846. private theorem nodup_of_counts (w : W) (h : ∀ a ∈ w, w.count a ≤ 1) : w.Nodup := by
  1847. induction w with
  1848. | nil => simp
  1849. | cons a w ih =>
  1850. apply List.nodup_cons.mpr
  1851. have one := h a (by simp)
  1852. simp only [List.count_cons_self] at one
  1853. exact ⟨List.count_eq_zero.mp (by omega),
  1854. ih fun b hb => by have hh := h b (by simp [hb]); simp [List.count_cons] at hh; omega⟩
  1855. private theorem core_mem {r A M} (f : Frame Nat) (valid : f.Valid r A M)
  1856. (bit : Bool) (a : Nat) (mem : a ∈ f.p ∨ a ∈ f.q) : (f.core bit).count a = r := by
  1857. have base := valid.2.2.2.2.2.2.2 a mem
  1858. cases bit
  1859. · exact base
  1860. · exact (f.count_core a true).trans base
  1861. private def mappedFrame (f : Frame Nat) (h : Nat → W) (pHead : Nat) (pTail qInit : W)
  1862. (qLast : Nat) : Frame Nat where
  1863. pHead := pHead
  1864. pTail := pTail
  1865. qInit := qInit
  1866. qLast := qLast
  1867. tag := f.tag
  1868. middle := f.middle.map (fun e => (e.1.flatMap h, e.2))
  1869. beforeMutable := f.beforeMutable.flatMap h
  1870. beforeFinalP := f.beforeFinalP.flatMap h
  1871. beforeFinalQ := f.beforeFinalQ.flatMap h
  1872. private theorem mid_image (f : Frame Nat) (h : Nat → W) (phead : Nat) (pt qi : W) (qlast : Nat)
  1873. (hp : f.p.flatMap h = phead :: pt) (hq : f.q.flatMap h = qi ++ [qlast]) :
  1874. f.mid.flatMap h = (mappedFrame f h phead pt qi qlast).mid := by
  1875. simp only [Frame.mid,mappedFrame,List.flatMap_assoc,List.flatMap_map]
  1876. congr 1
  1877. funext z
  1878. obtain ⟨w,b⟩ := z
  1879. cases b <;> simp only [Function.comp_apply, Bool.false_eq_true, if_false, if_true,
  1880. List.flatMap_append, hp, hq] <;> rfl
  1881. private theorem core_image (f : Frame Nat) (h : Nat → W) (phead : Nat) (pt qi : W) (qlast : Nat)
  1882. (hp : f.p.flatMap h = phead :: pt) (hq : f.q.flatMap h = qi ++ [qlast]) (bit : Bool) :
  1883. (f.core bit).flatMap h = (mappedFrame f h phead pt qi qlast).core bit := by
  1884. have mid := mid_image f h phead pt qi qlast hp hq
  1885. cases bit <;> simp only [Frame.core,Frame.early,Frame.pair,Bool.false_eq_true,if_false,if_true,
  1886. List.flatMap_append, mid, hp, hq] <;> rfl
  1887. theorem equal_or_move {r allow mark} (f : Frame Nat) (l k : W) (bit : Bool) (x y : Nat)
  1888. (hp : f.p = [x]) (hq : f.q = [y]) (valid : f.Valid r allow (fun _ _ => False))
  1889. (h : Nat → W) (clear : Unmarked mark h x y)
  1890. (cap : Cap r ((side f l k bit).flatMap h)) :
  1891. (side f l k bit).flatMap h = (side f l k (!bit)).flatMap h ∨
  1892. Move r allow mark ((side f l k bit).flatMap h) ((side f l k (!bit)).flatMap h) := by
  1893. have xmap : f.p.flatMap h = h x := by simp [hp]
  1894. have ymap : f.q.flatMap h = h y := by simp [hq]
  1895. by_cases empty : h x = [] ∨ h y = []
  1896. · left
  1897. rcases empty with hx | hy <;> cases bit <;>
  1898. simp [side,Frame.core,Frame.pair,List.flatMap_append,xmap,ymap, *]
  1899. right
  1900. have nonX : h x ≠ [] := fun e => empty (Or.inl e)
  1901. have nonY : h y ≠ [] := fun e => empty (Or.inr e)
  1902. obtain ⟨phead,pt,p⟩ : ∃ a t, h x = a :: t := by cases hv : h x <;> simp_all
  1903. obtain ⟨qi,qlast,q⟩ : ∃ t a, h y = t ++ [a] := by
  1904. cases hv : (h y).reverse with
  1905. | nil => have e := congrArg List.reverse hv; simp_all
  1906. | cons a t => exact ⟨t.reverse,a,by simpa using congrArg List.reverse hv⟩
  1907. let g := mappedFrame f h phead pt qi qlast
  1908. have gp : g.p = h x := p.symm
  1909. have gq : g.q = h y := q.symm
  1910. have eq (b : Bool) :
  1911. (side f l k b).flatMap h = l.flatMap h ++ g.core b ++ k.flatMap h := by
  1912. simp only [side,List.flatMap_append,core_image f h _ _ _ _ (xmap.trans p) (ymap.trans q),g]
  1913. have capCore : Cap r ((f.core bit).flatMap h) := by
  1914. intro a; have hh := cap a; simp only [side,List.flatMap_append,List.count_append] at hh; omega
  1915. have xm : x ∈ f.p := by simp [hp]
  1916. have ym : y ∈ f.q := by simp [hq]
  1917. have ne : x ≠ y := fun e => valid.2.2.2.2.2.1 x xm (e ▸ ym)
  1918. have hr : 0 < r := by have := valid.1; omega
  1919. have cx := core_mem f valid bit x (.inl xm)
  1920. have cy := core_mem f valid bit y (.inr ym)
  1921. have usedY : y ∈ f.core bit := List.count_pos_iff.mp (cy.symm ▸ hr)
  1922. have excl (a : Nat) (ha : a ∈ h x) :=
  1923. P455DonorInterval.exclusive h (f.core bit) x a r hr cx ha (capCore a)
  1924. have capImage := eq bit ▸ cap
  1925. have gv : g.Valid r allow mark := by
  1926. apply g.valid_of_capped_shape valid.1 valid.2.1 _ _ _ _ _ bit (l.flatMap h) (k.flatMap h) capImage
  1927. · simpa [g,mappedFrame,List.map_map,Function.comp_def] using valid.2.2.1
  1928. · rw [gp]; apply nodup_of_counts
  1929. exact fun a ha => Nat.le_of_eq (excl a ha).1
  1930. · rw [gq]; apply nodup_of_counts
  1931. exact fun a ha => Nat.le_of_eq (P455DonorInterval.exclusive h (f.core bit) y a r hr cy ha (capCore a)).1
  1932. · rw [gp,gq]; exact fun a ha => (excl a ha).2.1 y usedY ne.symm
  1933. · simpa only [gp,gq,Unmarked] using clear
  1934. exact ⟨g,bit,l.flatMap h,k.flatMap h,gv,eq bit,eq (!bit),cap⟩
  1935. private theorem words_from_good {r allow mark T} (capT : P455Quotient.Cap r T)
  1936. (f : Frame Nat) (l k : W) (bit : Bool) (x y : Nat)
  1937. (hp : f.p = [x]) (hq : f.q = [y]) (valid : f.Valid r allow (fun _ _ => False))
  1938. (h : Nat → W) (clear : Unmarked mark h x y)
  1939. (good : P455Quotient.Good (rules r allow mark) T ((side f l k bit).flatMap h)) :
  1940. P455Quotient.ofWord (rules r allow mark) T ((side f l k bit).flatMap h) =
  1941. P455Quotient.ofWord (rules r allow mark) T ((side f l k (!bit)).flatMap h) := by
  1942. let R := rules r allow mark
  1943. have cap := P455Quotient.good_cap R capT good
  1944. rcases equal_or_move f l k bit x y hp hq valid h clear cap with e | move
  1945. · rw [e]
  1946. · have path := P455Quotient.Walk.snoc (s := R.step) (.refl _) move
  1947. have equiv := P455Quotient.good_context R capT path [] []
  1948. simp only [List.nil_append,List.append_nil] at equiv
  1949. exact (P455Quotient.same_nonzero_class R good).mpr ⟨equiv.mp good,path⟩
  1950. /-- Uncrossed literal representatives agree even if their product is zero.
  1951. Any nonzero side supplies the cap on its evaluated factor. -/
  1952. theorem uncrossed_words {r allow mark T} (capT : P455Quotient.Cap r T)
  1953. (f : Frame Nat) (l k : W) (bit : Bool) (x y : Nat)
  1954. (hp : f.p = [x]) (hq : f.q = [y]) (valid : f.Valid r allow (fun _ _ => False))
  1955. (h : Nat → W) (clear : Unmarked mark h x y) :
  1956. P455Quotient.ofWord (rules r allow mark) T ((side f l k bit).flatMap h) =
  1957. P455Quotient.ofWord (rules r allow mark) T ((side f l k (!bit)).flatMap h) := by
  1958. let R := rules r allow mark
  1959. by_cases g : P455Quotient.Good R T ((side f l k bit).flatMap h)
  1960. · exact words_from_good capT f l k bit x y hp hq valid h clear g
  1961. by_cases g' : P455Quotient.Good R T ((side f l k (!bit)).flatMap h)
  1962. · simpa using (words_from_good capT f l k (!bit) x y hp hq valid h clear g').symm
  1963. have dead (w : W) (h : ¬ P455Quotient.Good R T w) :
  1964. P455Quotient.ofWord R T w = P455Quotient.zero R T := by
  1965. apply Classical.byContradiction
  1966. intro nz; exact h ((P455Quotient.nonzero_iff R).mp nz)
  1967. exact (dead _ g).trans (dead _ g').symm
  1968. theorem same_letters (f : Frame Nat) (l k : W) (bit : Bool) (a : Nat) :
  1969. a ∈ side f l k bit ↔ a ∈ side f l k (!bit) := by
  1970. have c := f.count_core a bit
  1971. have perm : (side f l k bit).count a = (side f l k (!bit)).count a := by
  1972. simp only [side,List.count_append,c]
  1973. rw [←List.count_pos_iff,←List.count_pos_iff,perm]
  1974. /-- Arbitrarily chosen quotient representatives for all occurring variables
  1975. are enough for a decision for a fixed evaluation. -/
  1976. theorem uncrossed_eval {r allow mark T} (capT : P455Quotient.Cap r T)
  1977. (f : Frame Nat) (l k : W) (bit : Bool) (x y : Nat)
  1978. (hp : f.p = [x]) (hq : f.q = [y]) (valid : f.Valid r allow (fun _ _ => False))
  1979. (val : Nat → P455Quotient.Q (rules r allow mark) T) (h : Nat → W)
  1980. (reps : ∀ a ∈ side f l k bit, P455Quotient.ofWord (rules r allow mark) T (h a) = val a)
  1981. (clear : Unmarked mark h x y) :
  1982. P455Quotient.eval (rules r allow mark) capT val (side f l k bit) =
  1983. P455Quotient.eval (rules r allow mark) capT val (side f l k (!bit)) := by
  1984. rw [P455Quotient.eval_rep _ _ _ _ h reps,
  1985. P455Quotient.eval_rep _ _ _ _ h (fun a ha => reps a ((same_letters f l k bit a).mpr ha))]
  1986. exact uncrossed_words capT f l k bit x y hp hq valid h clear
  1987. /-- A distinguishing evaluation forces a cross-block mark in EVERY choice of
  1988. representatives of its occurring variables. Both stored orientations count. -/
  1989. theorem difference_crosses {r allow mark T} (capT : P455Quotient.Cap r T)
  1990. (f : Frame Nat) (l k : W) (bit : Bool) (x y : Nat)
  1991. (hp : f.p = [x]) (hq : f.q = [y]) (valid : f.Valid r allow (fun _ _ => False))
  1992. (val : Nat → P455Quotient.Q (rules r allow mark) T) (h : Nat → W)
  1993. (reps : ∀ a ∈ side f l k bit, P455Quotient.ofWord (rules r allow mark) T (h a) = val a)
  1994. (diff : P455Quotient.eval (rules r allow mark) capT val (side f l k bit) ≠
  1995. P455Quotient.eval (rules r allow mark) capT val (side f l k (!bit))) :
  1996. ∃ a ∈ h x, ∃ b ∈ h y, mark a b ∨ mark b a := by
  1997. apply Classical.byContradiction
  1998. intro none
  1999. apply diff
  2000. apply uncrossed_eval capT f l k bit x y hp hq valid val h reps
  2001. intro a ha b hb
  2002. exact ⟨fun e => none ⟨a,ha,b,hb,Or.inl e⟩,fun e => none ⟨a,ha,b,hb,Or.inr e⟩⟩
  2003. /-- A distinguishing valuation has a live orientation and simultaneous arbitrary
  2004. good-word representatives for its letters. Each such simultaneous choice
  2005. occurs as a literal factor of a variant, including arbitrary proper factors. -/
  2006. theorem difference_live_representatives {r allow mark T} (capT : P455Quotient.Cap r T)
  2007. (f : Frame Nat) (l k : W)
  2008. (val : Nat → P455Quotient.Q (rules r allow mark) T)
  2009. (diff : P455Quotient.eval (rules r allow mark) capT val (side f l k false) ≠
  2010. P455Quotient.eval (rules r allow mark) capT val (side f l k true)) :
  2011. ∃ bit : Bool,
  2012. P455Quotient.eval (rules r allow mark) capT val (side f l k bit) ≠
  2013. P455Quotient.zero (rules r allow mark) T ∧
  2014. (∃ h : Nat → W, ∀ a ∈ side f l k bit,
  2015. P455Quotient.Good (rules r allow mark) T (h a) ∧
  2016. P455Quotient.ofWord (rules r allow mark) T (h a) = val a) ∧
  2017. (∀ h : Nat → W, (∀ a ∈ side f l k bit,
  2018. P455Quotient.ofWord (rules r allow mark) T (h a) = val a) →
  2019. ∃ V left right, P455Quotient.Variant (rules r allow mark) T V ∧
  2020. V = left ++ (side f l k bit).flatMap h ++ right) := by
  2021. classical
  2022. let R := rules r allow mark
  2023. have live : ∃ bit, P455Quotient.eval R capT val (side f l k bit) ≠ P455Quotient.zero R T := by
  2024. by_cases nz : P455Quotient.eval R capT val (side f l k false) ≠ P455Quotient.zero R T
  2025. · exact ⟨false,nz⟩
  2026. · exact ⟨true,fun z => diff ((Classical.not_not.mp nz).trans z.symm)⟩
  2027. obtain ⟨bit,nz⟩ := live
  2028. refine ⟨bit,nz,?_,?_⟩
  2029. · have word (a) (ha : a ∈ side f l k bit) :=
  2030. P455Quotient.nonzero_representative R (val a) (P455Quotient.live_inputs R capT val _ nz a ha)
  2031. let h (a : Nat) := if ha : a ∈ side f l k bit then (word a ha).choose else []
  2032. refine ⟨h,fun a ha => ?_⟩
  2033. simpa only [h,dif_pos ha] using (word a ha).choose_spec
  2034. · intro h reps
  2035. exact (P455Quotient.arbitrary_representatives R capT val _ h reps).mp nz
  2036. end P455Uncrossed
  2037. end
  2038. /- Begin Problem455EffectiveQReach (from finite-semigroup-identity-bases). -/
  2039. section
  2040. namespace P455EffectiveQReach
  2041. open P455Quotient
  2042. variable {α : Type} [DecidableEq α]
  2043. def via (edge : α → α → Bool) : List α → α → α → Bool
  2044. | [], x, y => decide (x=y) || edge x y
  2045. | z::zs, x, y => via edge zs x y || (via edge zs x z && via edge zs z y)
  2046. private theorem initial (e : α → α → Bool) (s : List α) {a b : α} (h : a=b ∨ e a b=true) :
  2047. via e s a b = true := by
  2048. induction s with
  2049. | nil => simpa [via] using h
  2050. | cons z zs ih => simp [via,ih]
  2051. private theorem splice (e : α → α → Bool) (s : List α) {a b c : α} (mem : b∈s)
  2052. (p : via e s a b=true) (q : via e s b c=true) : via e s a c=true := by
  2053. induction s generalizing a b c with
  2054. | nil => simp at mem
  2055. | cons z zs ih =>
  2056. simp only [via,Bool.or_eq_true,Bool.and_eq_true] at p q ⊢
  2057. rcases List.mem_cons.mp mem with rfl|tail
  2058. · exact Or.inr ⟨p.elim id (·.1),q.elim id (·.2)⟩
  2059. · rcases p with p|⟨px,py⟩ <;> rcases q with q|⟨qx,qy⟩
  2060. · exact .inl (ih tail p q)
  2061. · exact .inr ⟨ih tail p qx,qy⟩
  2062. · exact .inr ⟨px,ih tail py q⟩
  2063. · exact .inr ⟨px,qy⟩
  2064. theorem sound {rel : α → α → Prop} (e : α → α → Bool) (ok : ∀ x y,e x y=true → rel x y)
  2065. (s : List α) {a b : α} (h : via e s a b = true) : Walk rel a b := by
  2066. induction s generalizing a b with
  2067. | nil =>
  2068. simp only [via,Bool.or_eq_true,decide_eq_true_eq] at h
  2069. rcases h with rfl|h
  2070. · exact .refl _
  2071. · exact .snoc (.refl _) (ok _ _ h)
  2072. | cons z zs ih =>
  2073. simp only [via,Bool.or_eq_true,Bool.and_eq_true] at h
  2074. exact h.elim ih (fun ⟨p,q⟩ => (ih p).trans (ih q))
  2075. theorem complete {rel : α → α → Prop} (e : α → α → Bool) (ok : ∀ x y,rel x y → e x y=true)
  2076. (s : List α) {a b : α} (cover : ∀ x, Walk rel a x → x∈s) (p : Walk rel a b) :
  2077. via e s a b = true := by
  2078. induction p with
  2079. | refl => exact initial _ _ (.inl rfl)
  2080. | snoc p step ih => exact splice _ _ (cover _ p) ih (initial _ _ (.inr (ok _ _ step)))
  2081. end P455EffectiveQReach
  2082. end
  2083. /- Begin Problem455Witness (from finite-semigroup-identity-bases). -/
  2084. section
  2085. namespace P455Witness
  2086. open Problem455.Slots
  2087. abbrev W := List Nat
  2088. abbrev Tag := List Bool
  2089. abbrev Marking := Nat → Nat → Prop
  2090. /- A finite conjunction/disjunction of observations on a single word.
  2091. A static test depends only on the chosen certificate and tile alphabet. -/
  2092. inductive Query where
  2093. | fixed (p : Prop)
  2094. | count (a n : Nat)
  2095. | deficient (a : Nat)
  2096. | record (a b : Nat) (tag : Tag)
  2097. | markedBit (a b : Nat) (tag : Tag) (bit : Bool)
  2098. | order (pattern : List Event)
  2099. | slot (owner i a : Nat)
  2100. | separate (a b : Nat)
  2101. | both (x y : Query)
  2102. | either (x y : Query)
  2103. def Holds (r : Nat) (allow : Tag → Prop) (mark : Marking) (w : W) : Query → Prop
  2104. | .fixed p => p
  2105. | .count a n => w.count a = n
  2106. | .deficient a => w.count a < r
  2107. | .record a b tag => a ≠ b ∧ tag.length + 16 = r ∧ allow tag ∧ typed w a b tag
  2108. | .markedBit a b tag bit => a ≠ b ∧ tag.length + 16 = r ∧ allow tag ∧ (mark a b ∨ mark b a) ∧
  2109. select [a,b] w = profile a b tag bit
  2110. | .order pat => (∀ e ∈ pat, e.2 ≠ r - 2) ∧ sees w pat
  2111. | .slot o i a => slotStart i ∧ occupies w o i a
  2112. | .separate a b => ¬ Problem455Swap.SameBlock r w a b
  2113. | .both x y => Holds r allow mark w x ∧ Holds r allow mark w y
  2114. | .either x y => Holds r allow mark w x ∨ Holds r allow mark w y
  2115. theorem unordered_projection {r allow mark u v} (h : P455Closure.Move r allow mark u v)
  2116. (a b : Nat) (hm : mark a b ∨ mark b a) : select [a,b] u = select [a,b] v := by
  2117. rcases hm with forward | reverse
  2118. · exact h.marked_proj a b forward
  2119. · simpa only [select_pair_symm b a] using h.marked_proj b a reverse
  2120. theorem query_invariant {r allow mark u v} (h : P455Closure.Move r allow mark u v) (q : Query) :
  2121. Holds r allow mark u q ↔ Holds r allow mark v q := by
  2122. induction q with
  2123. | fixed => rfl
  2124. | count a n => simp only [Holds, h.count_eq a]
  2125. | deficient a => simp only [Holds, h.count_eq a]
  2126. | record a b tag =>
  2127. simp only [Holds]
  2128. constructor <;> rintro ⟨ne,len,ok,t⟩
  2129. · exact ⟨ne,len,ok,(h.typed_iff a b tag ne len).mp t⟩
  2130. · exact ⟨ne,len,ok,(h.typed_iff a b tag ne len).mpr t⟩
  2131. | markedBit a b tag bit =>
  2132. simp only [Holds]
  2133. constructor <;> rintro ⟨ne,len,ok,mk,t⟩
  2134. · exact ⟨ne,len,ok,mk,(unordered_projection h a b mk) ▸ t⟩
  2135. · exact ⟨ne,len,ok,mk,(unordered_projection h a b mk).symm ▸ t⟩
  2136. | order pat =>
  2137. constructor <;> rintro ⟨imm,t⟩
  2138. · exact ⟨imm,(h.order_iff pat imm).mp t⟩
  2139. · exact ⟨imm,(h.order_iff pat imm).mpr t⟩
  2140. | slot o i a =>
  2141. constructor <;> rintro ⟨hi,t⟩
  2142. · exact ⟨hi,(h.slot_iff o i a hi).mp t⟩
  2143. · exact ⟨hi,(h.slot_iff o i a hi).mpr t⟩
  2144. | separate a b => exact not_congr (Problem455BlockBridge.move_sameBlock h a b)
  2145. | both _ _ ih jh => exact and_congr ih jh
  2146. | either _ _ ih jh => exact or_congr ih jh
  2147. def allQ : List Query → Query
  2148. | [] => .fixed True
  2149. | q :: qs => .both q (allQ qs)
  2150. def flagQ (b : Bool) (q : Query) : Query := if b then q else .fixed True
  2151. structure Node where
  2152. owner : Nat
  2153. mate : Nat
  2154. tag : Tag
  2155. deriving DecidableEq
  2156. def typedNode (n : Node) := Query.record n.owner n.mate n.tag
  2157. def markedNode (n : Node) (b : Bool) := Query.markedBit n.owner n.mate n.tag b
  2158. def earlier (a i b j : Nat) := Query.order [(a,i),(b,j)]
  2159. /-- Last early copy of every role on the left precedes the first of every role
  2160. on the right. Indices throughout are zero-based. -/
  2161. def earlyBefore (xs ys : W) := allQ (xs.flatMap fun x => ys.map fun y => earlier x 2 y 0)
  2162. def earlyDisjoint (xs ys : W) := Query.either (earlyBefore xs ys) (earlyBefore ys xs)
  2163. inductive ContactChoice where
  2164. | record (tag : Tag) (reverseRoles : Bool)
  2165. | port (phase : Fin 5) (reverseOrder : Bool)
  2166. def contact (r a b : Nat) : ContactChoice → Query
  2167. | .record tag rev => if rev then .record b a tag else .record a b tag
  2168. | .port port rev =>
  2169. let i := 3 + 2 * port.val
  2170. let x := if rev then b else a
  2171. let y := if rev then a else b
  2172. allQ [.fixed (a ≠ b), .count a r, .count b r, earlyDisjoint [a] [b],
  2173. .order [(x,i),(y,i),(x,i+1),(y,i+1)]]
  2174. def route (r start : Nat) (steps : List (Nat × ContactChoice)) (terminal : Nat → Query) : Query :=
  2175. match steps with
  2176. | [] => terminal start
  2177. | (b,c) :: rest => .both (contact r start b c) (route r b rest terminal)
  2178. inductive SlotDefect where
  2179. | deficient (a : Nat)
  2180. | overflow (occupants : List Nat)
  2181. def differentBlocks : W → Query
  2182. | [] => .fixed True
  2183. | a :: xs => .both (allQ (xs.map (Query.separate a))) (differentBlocks xs)
  2184. def terminalSlot (r owner i : Nat) : SlotDefect → Query
  2185. | .deficient a => .both (.slot owner i a) (.deficient a)
  2186. | .overflow xs =>
  2187. allQ [.fixed (xs.length = 5), differentBlocks (owner :: xs),
  2188. allQ (xs.map fun a => .both (.count a r) (.slot owner i a))]
  2189. structure SlotCertificate where
  2190. anchor : Node
  2191. bit : Bool
  2192. startAtMate : Bool
  2193. steps : List (Nat × ContactChoice)
  2194. terminalIndex : Nat
  2195. defect : SlotDefect
  2196. def SlotCertificate.query (s : SlotCertificate) (r : Nat) : Query :=
  2197. let start := if s.startAtMate then s.anchor.mate else s.anchor.owner
  2198. allQ [markedNode s.anchor s.bit, .fixed (s.steps.length ≤ 6),
  2199. route r start s.steps (fun o => terminalSlot r o s.terminalIndex s.defect)]
  2200. /-- All data from machine tiles are fixed independently of the word. -/
  2201. structure Tiles where
  2202. horizontal : Tag → Tag → Prop
  2203. vertical : Tag → Tag → Prop
  2204. left : Tag → Bool
  2205. right : Tag → Bool
  2206. top : Tag → Bool
  2207. bottom : Tag → Bool
  2208. oddColumn : Tag → Bool
  2209. oddRow : Tag → Bool
  2210. def orientedPort (phase : Nat) (a b : Node) : Query :=
  2211. let i := 3 + 2 * phase
  2212. let x := a.owner; let y := a.mate; let z := b.owner; let t := b.mate
  2213. allQ [typedNode a, typedNode b, earlyDisjoint [x,y] [z,t],
  2214. .order [(x,i),(y,i),(z,i),(t,i),(x,i+1),(y,i+1),(z,i+1),(t,i+1)]]
  2215. inductive Dir | right | left | down | up
  2216. def rightward (ts : Tiles) (a b : Node) :=
  2217. allQ [.fixed (ts.horizontal a.tag b.tag), orientedPort (if ts.oddColumn a.tag then 1 else 0) a b,
  2218. earlier a.owner (13+a.tag.length) b.owner (13+a.tag.length)]
  2219. def downward (ts : Tiles) (a b : Node) : Query :=
  2220. .both (.fixed (ts.vertical a.tag b.tag))
  2221. (orientedPort (if ts.oddRow a.tag then 3 else 2) a b)
  2222. def neighbor (ts : Tiles) (a b : Node) : Dir → Query
  2223. | .right => rightward ts a b
  2224. | .left => rightward ts b a
  2225. | .down => downward ts a b
  2226. | .up => downward ts b a
  2227. structure FunctionalityCertificate where
  2228. anchor : Node
  2229. bit : Bool
  2230. b : Node
  2231. c : Node
  2232. dir : Dir
  2233. distinguishMate : Bool
  2234. def FunctionalityCertificate.query (f : FunctionalityCertificate) (ts : Tiles) :=
  2235. let role := fun n : Node => if f.distinguishMate then n.mate else n.owner
  2236. allQ [markedNode f.anchor f.bit, neighbor ts f.anchor f.b f.dir,
  2237. neighbor ts f.anchor f.c f.dir, .separate (role f.b) (role f.c)]
  2238. structure EdgeCertificate where
  2239. a : Node
  2240. b : Node
  2241. right : Node
  2242. left : Node
  2243. down : Node
  2244. up : Node
  2245. diagonal : Node
  2246. def endOfRow (ts : Tiles) (a : Node) :=
  2247. if ts.oddRow a.tag then ts.left a.tag else ts.right a.tag
  2248. def localCert (ts : Tiles) (e : EdgeCertificate) :=
  2249. let a := e.a
  2250. allQ [flagQ (!ts.right a.tag) (rightward ts a e.right),
  2251. flagQ (!ts.left a.tag) (rightward ts e.left a),
  2252. flagQ (!ts.bottom a.tag) (downward ts a e.down),
  2253. flagQ (!ts.top a.tag) (downward ts e.up a),
  2254. flagQ (!ts.right a.tag && !ts.bottom a.tag)
  2255. (.both (downward ts e.right e.diagonal) (rightward ts e.down e.diagonal))]
  2256. def chosenSuccessor (ts : Tiles) (e : EdgeCertificate) : Query :=
  2257. let a := e.a; let b := e.b
  2258. if endOfRow ts a && ts.bottom a.tag then
  2259. allQ [.fixed ((ts.top b.tag && ts.left b.tag && !ts.oddRow b.tag && !ts.oddColumn b.tag) = true),
  2260. .either (orientedPort 4 a b) (orientedPort 4 b a), earlier b.owner 0 a.owner 0]
  2261. else
  2262. let next := if endOfRow ts a then e.down else if ts.oddRow a.tag then e.left else e.right
  2263. .both (.fixed (next = b)) (earlier a.owner 0 b.owner 0)
  2264. def EdgeCertificate.query (e : EdgeCertificate) (ts : Tiles) :=
  2265. allQ [markedNode e.a true, markedNode e.b false, localCert ts e, chosenSuccessor ts e]
  2266. inductive Certificate where
  2267. | slot (s : SlotCertificate)
  2268. | functionality (f : FunctionalityCertificate)
  2269. | edge (e : EdgeCertificate)
  2270. def Certificate.query (c : Certificate) (r : Nat) (ts : Tiles) :=
  2271. match c with
  2272. | .slot s => s.query r
  2273. | .functionality f => f.query ts
  2274. | .edge e => e.query ts
  2275. abbrev rules := Problem455Finite.rules
  2276. /-- Every enclosing variant keeps the same designated certificate, even when
  2277. a chosen literal representative (or the whole product) is a proper factor. -/
  2278. theorem every_variant {r allow mark T w} (path : P455Quotient.Variant (rules r allow mark) T w)
  2279. (c : Certificate) (ts : Tiles) :
  2280. Holds r allow mark T (c.query r ts) → Holds r allow mark w (c.query r ts) := by
  2281. intro h
  2282. exact path.transport h (fun mv old => (query_invariant mv _).mp old)
  2283. theorem arbitrary_reps_designated {r allow mark T} (cap : P455Quotient.Cap r T)
  2284. {β : Type} (val : β → P455Quotient.Q (rules r allow mark) T) (v : List β)
  2285. (h : β → W) (reps : ∀ x ∈ v, P455Quotient.ofWord (rules r allow mark) T (h x) = val x)
  2286. (live : P455Quotient.eval (rules r allow mark) cap val v ≠ P455Quotient.zero (rules r allow mark) T)
  2287. (c : Certificate) (ts : Tiles) (initial : Holds r allow mark T (c.query r ts)) :
  2288. ∃ w l t, P455Quotient.Variant (rules r allow mark) T w ∧
  2289. w = l ++ v.flatMap h ++ t ∧ Holds r allow mark w (c.query r ts) := by
  2290. apply P455Quotient.designated (rules r allow mark) cap val v h reps live _ initial
  2291. exact fun mv old => (query_invariant mv _).mp old
  2292. end P455Witness
  2293. end
  2294. /- Begin Problem455SameDonor (from finite-semigroup-identity-bases). -/
  2295. section
  2296. namespace Problem455SameDonor
  2297. open Problem455Swap
  2298. private theorem count_le_output {β : Type} [DecidableEq β] (h : β → Word)
  2299. (x : β) (a : Nat) (ha : a ∈ h x) (v : List β) :
  2300. v.count x ≤ occ a (v.flatMap h) := by
  2301. have pos : 0 < occ a (h x) := by
  2302. rw [Problem455BlockBridge.occ_count]
  2303. exact List.count_pos_iff.mpr ha
  2304. induction v with
  2305. | nil => simp [occ]
  2306. | cons b v ih =>
  2307. simp only [List.flatMap_cons, occ_append]
  2308. by_cases e : b = x
  2309. · subst b; simp [List.count_cons]; omega
  2310. · simp [List.count_cons, e]; omega
  2311. private theorem count_le_edge {β : Type} [DecidableEq β] (h : β → Word)
  2312. (x : β) (a b : Nat) (hab : 0 < bigram a b (h x)) (v : List β) :
  2313. v.count x ≤ bigram a b (v.flatMap h) := by
  2314. induction v with
  2315. | nil => simp [bigram]
  2316. | cons z v ih =>
  2317. simp only [List.flatMap_cons, bigram_append]
  2318. by_cases e : z = x
  2319. · subst z; simp [List.count_cons]; omega
  2320. · simp [List.count_cons, e]; omega
  2321. private theorem transJoined {e : Nat → Nat → Prop} {a b c : Nat}
  2322. (h1 : Joined e a b) (h2 : Joined e b c) : Joined e a c := by
  2323. induction h2 with
  2324. | refl => exact h1
  2325. | extend _ z ih => exact .extend ih z
  2326. private theorem symmJoined {e : Nat → Nat → Prop} {a b : Nat}
  2327. (h : Joined e a b) : Joined e b a := by
  2328. induction h with
  2329. | refl => exact .refl _
  2330. | extend _ z ih => exact transJoined (.extend (.refl _) z.symm) ih
  2331. private theorem headConnected (r : Nat) (F : Word) (a : Nat) (t : Word)
  2332. (links : ∀ i j, 0 < bigram i j (a :: t) → Link r F i j) :
  2333. ∀ b ∈ a :: t, Joined (Link r F) a b := by
  2334. induction t generalizing a with
  2335. | nil =>
  2336. intro b hb
  2337. have := List.mem_singleton.mp hb
  2338. subst b; exact .refl _
  2339. | cons c t ih =>
  2340. intro b hb
  2341. rcases List.mem_cons.mp hb with h | hb
  2342. · subst b; exact .refl _
  2343. · have ac : Link r F a c := links a c (by simp [bigram, hit] <;> omega)
  2344. have tailLinks : ∀ i j, 0 < bigram i j (c :: t) → Link r F i j := by
  2345. intro i j pos
  2346. apply links
  2347. change 0 < hit i j (some a) (some c) + bigram i j (c :: t)
  2348. omega
  2349. exact transJoined (.extend (.refl _) (.inl ac)) (ih c tailLinks b hb)
  2350. /-- Under the cap, every label in the image of an r-occurring source variable
  2351. is saturated and all such labels belong to one maximal repeated block.
  2352. There is no condition on substitutions of any other source variable. -/
  2353. theorem sameDonor {β : Type} [DecidableEq β] {r : Nat} (v : List β)
  2354. (h : β → Word) (x : β) (hx : v.count x = r)
  2355. (hc : ∀ a, (v.flatMap h).count a ≤ r) (a b : Nat) (ha : a ∈ h x) (hb : b ∈ h x) :
  2356. SameBlock r (v.flatMap h) a b := by
  2357. have cap' : cap r (v.flatMap h) := by
  2358. intro j; rw [Problem455BlockBridge.occ_count]; exact hc j
  2359. have sat (i : Nat) (hi : i ∈ h x) : occ i (v.flatMap h) = r := by
  2360. have lower := count_le_output h x i hi v
  2361. have upper := cap' i
  2362. omega
  2363. have links (i j : Nat) (ij : 0 < bigram i j (h x)) : Link r (v.flatMap h) i j := by
  2364. have lower := count_le_edge h x i j ij v
  2365. have upper := out_bound i j (j+1) (by omega) (v.flatMap h)
  2366. have ceiling := cap' i
  2367. unfold Link
  2368. omega
  2369. refine ⟨sat a ha,sat b hb,?_⟩
  2370. cases eq : h x with
  2371. | nil => simp [eq] at ha
  2372. | cons c t =>
  2373. rw [eq] at ha hb links
  2374. exact transJoined (symmJoined (headConnected r _ c t links a ha))
  2375. (headConnected r _ c t links b hb)
  2376. private theorem multiplicity_lower {β : Type} [DecidableEq β] (v : List β) (h : β → Word)
  2377. (x : β) (a : Nat) : v.count x * (h x).count a ≤ (v.flatMap h).count a := by
  2378. induction v with
  2379. | nil => simp
  2380. | cons b v ih =>
  2381. simp only [List.flatMap_cons, List.count_append]
  2382. by_cases e : b = x
  2383. · subst b
  2384. simp [List.count_cons, Nat.add_mul]
  2385. omega
  2386. · simp [List.count_cons, e]; omega
  2387. /-- A named letter donated by x appears exactly once in h(x), and no other
  2388. variable USED by v donates that letter. Variables absent from v are
  2389. legitimately unconstrained. -/
  2390. theorem uniqueDonor {β : Type} [DecidableEq β] {r : Nat} (v : List β)
  2391. (h : β → Word) (x : β) (rpos : 0 < r) (hx : v.count x = r)
  2392. (hc : ∀ a, (v.flatMap h).count a ≤ r) (a : Nat) (ha : a ∈ h x) :
  2393. (h x).count a = 1 ∧ ∀ y ∈ v, y ≠ x → a ∉ h y := by
  2394. constructor
  2395. · have m := multiplicity_lower v h x a
  2396. rw [hx] at m
  2397. have p := List.count_pos_iff.mpr ha
  2398. have c := hc a
  2399. by_cases hn : (h x).count a = 1
  2400. · exact hn
  2401. · exfalso
  2402. have two : 2 ≤ (h x).count a := by omega
  2403. have bad := Nat.mul_le_mul_left r two
  2404. omega
  2405. · intro y hy yx ay
  2406. obtain ⟨l,t,e⟩ := List.append_of_mem hy
  2407. have h1 := count_le_output h x a ha l
  2408. have h2 := count_le_output h x a ha t
  2409. rw [Problem455BlockBridge.occ_count] at h1 h2
  2410. have yPos := List.count_pos_iff.mpr ay
  2411. have c := hc a
  2412. simp only [e,List.flatMap_append,List.flatMap_cons,List.count_append] at c
  2413. simp [e,List.count_append,List.count_cons,yx] at hx
  2414. omega
  2415. end Problem455SameDonor
  2416. end
  2417. /- Begin Problem455MathlibFinite (from finite-semigroup-identity-bases). -/
  2418. section
  2419. namespace P455MathlibFinite
  2420. open Turing P455MathlibTM
  2421. /-- The states really form a finite type. Every instruction writing on
  2422. the tape preserves its Boolean marker track, on all symbols. -/
  2423. theorem finite_machine {f : List Bool → List Bool} (hf : Computable f) :
  2424. ∃ (Q : Type) (_ : Fintype Q) (_ : Inhabited Q) (M : TM0.Machine Track Q),
  2425. (∀ q a q' b, M q a = some (q',.write b) → b.1=a.1) ∧
  2426. ∀ x, ∃ q, (⟨q,Tape.mk₁ (image (f x))⟩ : TM0.Cfg Track Q) ∈
  2427. StateTransition.eval (TM0.step M) (TM0.init (image x)) := by
  2428. classical
  2429. obtain ⟨L,I,M,S,hs,guard,run⟩ := supported hf
  2430. let Q := {q : L // q ∈ S}
  2431. letI : Inhabited Q := ⟨⟨default,hs.1⟩⟩
  2432. let pick (q : L) : Q := if h : q ∈ S then ⟨q,h⟩ else default
  2433. have proj (q : L) (h : q ∈ S) : (pick q).val = q := by simp [pick,h]
  2434. let sym : PointedMap Track Track := ⟨id,rfl⟩
  2435. let N := M.map sym sym pick Subtype.val
  2436. refine ⟨Q,inferInstance,inferInstance,N,?_,?_⟩
  2437. · intro q a q' b step
  2438. change (M q.val a).map (Prod.map pick (TM0.Stmt.map sym)) = _ at step
  2439. obtain ⟨⟨r,s⟩,hr,he⟩ := Option.map_eq_some_iff.mp step
  2440. cases s with
  2441. | move d =>
  2442. change (pick r, TM0.Stmt.move d) = (q',TM0.Stmt.write b) at he
  2443. cases he
  2444. | write z =>
  2445. change (pick r,TM0.Stmt.write z) = (q',TM0.Stmt.write b) at he
  2446. have eq : z=b := TM0.Stmt.write.inj (congrArg Prod.snd he)
  2447. exact eq ▸ guard q.val q.property a r z hr
  2448. · intro x
  2449. obtain ⟨r,stop⟩ := run x
  2450. have sim := TM0.Machine.map_respects M sym sym (⟨pick,Subtype.ext (proj _ hs.1)⟩ : PointedMap L Q)
  2451. Subtype.val hs (fun _ => rfl) proj
  2452. have lift (q : L) (xs : List Track) :
  2453. TM0.Cfg.map sym pick (⟨q,Tape.mk₁ xs⟩ : TM0.Cfg Track L) = ⟨pick q,Tape.mk₁ xs⟩ := by
  2454. simp [TM0.Cfg.map,Tape.map_mk₁,sym]
  2455. have eq : TM0.Cfg.map sym pick (TM0.init (Λ := L) (image x)) = TM0.init (Λ := Q) (image x) := by
  2456. unfold TM0.init
  2457. rw [lift]
  2458. exact congrArg (fun q => TM0.Cfg.mk q (Tape.mk₁ (image x))) (Subtype.ext (proj _ hs.1))
  2459. obtain ⟨b,⟨_,equ⟩,ok⟩ := StateTransition.tr_eval sim ⟨hs.1,eq⟩ stop
  2460. subst b
  2461. rw [lift] at ok
  2462. exact ⟨_,ok⟩
  2463. end P455MathlibFinite
  2464. end
  2465. /- Begin Problem455SlotOrigin (from finite-semigroup-identity-bases). -/
  2466. section
  2467. namespace P455SlotOrigin
  2468. open Problem455.Slots
  2469. theorem event_bounds (n : Nat → Nat) (w : Word) (a j : Nat)
  2470. (hj : (a,j) ∈ stamp n w) : n a ≤ j ∧ j < n a + w.count a := by
  2471. induction w generalizing n with
  2472. | nil => simp [stamp] at hj
  2473. | cons b w ih =>
  2474. rcases List.mem_cons.mp hj with he | he
  2475. · obtain ⟨rfl,rfl⟩ := Prod.mk.inj he
  2476. simp [List.count_cons]
  2477. · have h := ih (advance n [b]) he
  2478. simp only [advance, List.count_cons, List.count_nil] at *
  2479. omega
  2480. /-- The i-th (zero-based) occurrence exists exactly when the count exceeds i.
  2481. This direction supplies a literal cut with its prefix count. -/
  2482. theorem occurrence_cut (w : Word) (x i : Nat) (hi : i < w.count x) :
  2483. ∃ l t, w = l ++ x :: t ∧ l.count x = i := by
  2484. induction w generalizing i with
  2485. | nil => simp at hi
  2486. | cons a w ih =>
  2487. by_cases h : a = x
  2488. · subst a
  2489. cases i with
  2490. | zero => exact ⟨[],w,rfl,rfl⟩
  2491. | succ i =>
  2492. have c : i < w.count x := by simpa [List.count_cons] using hi
  2493. obtain ⟨l,t,e,ei⟩ := ih i c
  2494. exact ⟨x::l,t,by simp [e],by simp [List.count_cons,ei]⟩
  2495. · have c : i < w.count x := by simpa [List.count_cons,h,Ne.symm h] using hi
  2496. obtain ⟨l,t,e,ei⟩ := ih i c
  2497. exact ⟨a::l,t,by simp [e],by simp [List.count_cons,h,Ne.symm h,ei]⟩
  2498. theorem slot_cut (w : Word) (x i : Nat) (hi : i+1 < w.count x) :
  2499. ∃ l mid t, w = l ++ [x] ++ mid ++ [x] ++ t ∧ l.count x = i ∧ x ∉ mid := by
  2500. obtain ⟨l,suffix,e,ei⟩ := occurrence_cut w x i (by omega)
  2501. have hs : x ∈ suffix := by
  2502. apply List.count_pos_iff.mp
  2503. rw [e,List.count_append,ei] at hi
  2504. simp only [List.count_cons_self] at hi
  2505. omega
  2506. obtain ⟨mid,t,et,hn⟩ := List.eq_append_cons_of_mem hs
  2507. exact ⟨l,mid,t,by simp [e,et,List.append_assoc],ei,hn⟩
  2508. private theorem trim_start {α : Type} (a : α) (xs l v : List α)
  2509. (h : a ∉ l) (sub : (a :: xs).Sublist (l ++ v)) : (a::xs).Sublist v := by
  2510. induction l with
  2511. | nil => simpa using sub
  2512. | cons b l ih =>
  2513. cases sub with
  2514. | cons _ sub => exact ih (fun m => h (by simp [m])) sub
  2515. | cons_cons _ _ => exact (h (by simp)).elim
  2516. private theorem framed_iff {α : Type} (l m t : List α) (a b y : α)
  2517. (ha : a ∉ l) (hb : b ∉ t) :
  2518. [a,y,b].Sublist (l ++ (a :: m ++ [b]) ++ t) ↔ y ∈ m := by
  2519. constructor
  2520. · intro sub
  2521. rw [List.append_assoc] at sub
  2522. have inner := (trim_start a _ l _ ha sub).reverse
  2523. simp only [List.reverse_append,List.reverse_cons,List.reverse_nil,
  2524. List.append_nil,List.nil_append,List.singleton_append,List.cons_append] at inner
  2525. rw [List.append_assoc] at inner
  2526. have back := (trim_start b _ t.reverse _ (by simpa using hb) inner).reverse
  2527. have mid : [a,y,b].Sublist (a :: (m ++ [b])) := by simpa using back
  2528. have last : ([y] ++ [b]).Sublist (m ++ [b]) := List.cons_sublist_cons.mp mid
  2529. simpa using (List.append_sublist_append_right [b]).mp last
  2530. · intro hy
  2531. have sub : ([y] : List α).Sublist m := by simpa using hy
  2532. have sub₂ := (List.append_sublist_append_right [b]).mpr sub
  2533. exact List.sublist_append_of_sublist_left (List.sublist_append_of_sublist_right (sub₂.cons₂ a))
  2534. /-- Slot membership in a fixed literal split, including a possibly deficient
  2535. occupant. The occupant's own occurrence number is existential. -/
  2536. theorem occupies_at_cut (l mid t : Word) (x y : Nat) (hn : x ∉ mid) :
  2537. occupies (l ++ [x] ++ mid ++ [x] ++ t) x (l.count x) y ↔ y ∈ mid := by
  2538. let n := advance (fun _ => 0) (l ++ [x])
  2539. let n' := advance (fun _ => 0) (l ++ [x] ++ mid ++ [x])
  2540. have nm : (advance n mid) x = l.count x+1 := by
  2541. simp [n,advance,List.count_append,List.count_eq_zero.mpr hn]
  2542. have ne : n' x = l.count x+2 := by
  2543. simp [n',advance,List.count_append,List.count_eq_zero.mpr hn]
  2544. have eq : events (l ++ [x] ++ mid ++ [x] ++ t) =
  2545. events l ++ ((x,l.count x) :: stamp n mid ++ [(x,l.count x+1)]) ++ stamp n' t := by
  2546. unfold events
  2547. simp only [stamp_append,stamp,List.append_nil,advance_append,n,n']
  2548. simp [advance,List.count_append,List.count_eq_zero.mpr hn,List.append_assoc, Nat.add_assoc]
  2549. have ha : (x,l.count x) ∉ events l := by
  2550. intro h
  2551. have hh := (event_bounds (fun _ => 0) l x _ h).2
  2552. omega
  2553. have hb : (x,l.count x+1) ∉ stamp n' t := by
  2554. intro h
  2555. have hh := (event_bounds n' t x _ h).1
  2556. omega
  2557. unfold occupies sees
  2558. rw [eq]
  2559. constructor
  2560. · rintro ⟨j,hj⟩
  2561. exact stamped_mem_label n mid (y,j) ((framed_iff _ _ _ _ _ _ ha hb).mp hj)
  2562. · intro hy
  2563. rw [← labels_of_stamp n mid] at hy
  2564. obtain ⟨⟨a,j⟩,he,rfl⟩ := List.mem_map.mp hy
  2565. exact ⟨j,(framed_iff _ _ _ _ _ _ ha hb).mpr he⟩
  2566. theorem supplier (v : Word) (h : Nat → Word) (l k : Word) (x s t i r : Nat)
  2567. (hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k))
  2568. (hx : v.count x = r) (hs : s ∈ h x) (hout : t ∉ h x)
  2569. (ho : occupies (l ++ v.flatMap h ++ k) s i t)
  2570. (guard : ∀ y, occupies v x i y → v.count y = r) :
  2571. ∃ y, occupies v x i y ∧ t ∈ h y ∧ v.count y = r ∧ x ≠ y := by
  2572. have cb : (v.flatMap h).count s ≤ r := by
  2573. have c := cap s
  2574. simp only [List.count_append] at c
  2575. omega
  2576. have sat := (P455DonorInterval.exclusive h v x s r hr hx hs cb).2.2
  2577. have hf := (saturated_factor_occupies l (v.flatMap h) k s i t r cap sat).mp ho
  2578. have bound : i+1 < v.count x := by
  2579. obtain ⟨j,hj⟩ := hf
  2580. have he : (s,i+1) ∈ events (v.flatMap h) := hj.mem (by simp)
  2581. have hh := (event_bounds (fun _ => 0) _ s _ he).2
  2582. omega
  2583. obtain ⟨L,I,R,cut,idx,cons⟩ := slot_cut v x i bound
  2584. obtain ⟨p,q,split,_⟩ := List.eq_append_cons_of_mem hs
  2585. have image : h x = p ++ [s] ++ q := by simpa [List.append_assoc] using split
  2586. obtain ⟨_,_,_,hni,hw,hi,_⟩ :=
  2587. P455DonorInterval.consecutive_interval h v L I R x s p q r cut cons image hx cb
  2588. have hit : t ∈ q ++ I.flatMap h ++ p := by
  2589. rw [← idx, ← hi, hw] at hf
  2590. exact (occupies_at_cut _ _ _ _ _ hni).mp hf
  2591. obtain ⟨y,hy,don⟩ := P455DonorInterval.interior_supplier h I x s t p q image hit hout
  2592. have occ : occupies v x i y := by
  2593. rw [cut,← idx]
  2594. exact (occupies_at_cut _ _ _ _ _ cons).mpr hy
  2595. exact ⟨y,occ,don,guard y occ,fun eq => hout (eq ▸ don)⟩
  2596. /-- A terminal slot may include the boundary donor. No contact or
  2597. separate-block assumption is needed for this disjunction. -/
  2598. theorem supplier_or_boundary (v : Word) (h : Nat → Word) (l k : Word) (x s t i r : Nat)
  2599. (hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k))
  2600. (hx : v.count x = r) (hs : s ∈ h x)
  2601. (ho : occupies (l ++ v.flatMap h ++ k) s i t)
  2602. (guard : ∀ y, occupies v x i y → v.count y = r) :
  2603. t ∈ h x ∨ ∃ y, occupies v x i y ∧ t ∈ h y ∧ v.count y = r ∧ x ≠ y := by
  2604. by_cases bound : t ∈ h x
  2605. · exact .inl bound
  2606. · exact .inr (supplier v h l k x s t i r hr cap hx hs bound ho guard)
  2607. end P455SlotOrigin
  2608. end
  2609. /- Begin Problem455EffectiveQ (from finite-semigroup-identity-bases). -/
  2610. section
  2611. namespace P455EffectiveQ
  2612. open P455Quotient Problem455Finite
  2613. abbrev W := List Nat
  2614. def words (u : W) := wordsUpTo u u.length
  2615. theorem subword {u v : W} (s : u.Sublist v) : u ∈ words v := covered v v.length u s.length_le s.subset
  2616. def factorB (u v : W) := (words v).any (fun l => (words v).any (fun t => decide (v=l++u++t)))
  2617. theorem factor_iff (u v : W) : factorB u v=true ↔ Factor u v := by
  2618. simp only [factorB,List.any_eq_true,decide_eq_true_eq]
  2619. constructor
  2620. · rintro ⟨l,_,t,_,h⟩; exact ⟨l,t,h⟩
  2621. · rintro ⟨l,t,rfl⟩
  2622. exact ⟨l,subword ((List.sublist_append_left l u).trans (List.sublist_append_left _ t)),
  2623. t,subword (List.sublist_append_right _ _),rfl⟩
  2624. def walkB (e : W → W → Bool) (u v : W) := P455EffectiveQReach.via e (words u) u v
  2625. theorem walk_iff (R : Rules Nat) (e : W → W → Bool) (ok : ∀ u v,e u v=true ↔ R.step u v)
  2626. (u v : W) : walkB e u v=true ↔ Walk R.step u v := by
  2627. constructor
  2628. · exact P455EffectiveQReach.sound _ (fun x y => (ok x y).mp) _
  2629. · intro path
  2630. apply P455EffectiveQReach.complete _ (fun x y => (ok x y).mpr) _ _ path
  2631. intro x reach
  2632. have perm := List.perm_iff_count.mpr (count_walk R reach)
  2633. exact covered _ _ _ (Nat.le_of_eq perm.length_eq.symm) (fun _ m => perm.mem_iff.mpr m)
  2634. def goodB (e : W → W → Bool) (T u : W) :=
  2635. (words T).any fun v => walkB e T v && factorB u v
  2636. theorem good_iff (R : Rules Nat) (e : W → W → Bool) (ok : ∀ u v,e u v=true ↔ R.step u v)
  2637. (T u : W) : goodB e T u=true ↔ Good R T u := by
  2638. simp only [goodB,List.any_eq_true,Bool.and_eq_true,walk_iff R e ok,factor_iff]
  2639. constructor
  2640. · rintro ⟨v,_,p,f⟩; exact ⟨v,p,f⟩
  2641. · rintro ⟨v,p,f⟩
  2642. have pe := List.perm_iff_count.mpr (count_walk R p)
  2643. exact ⟨v,covered _ _ _ (Nat.le_of_eq pe.length_eq.symm) (fun _ m => pe.mem_iff.mpr m),p,f⟩
  2644. def liveB (e : W → W → Bool) (T : W) : Raw Nat → Bool
  2645. | none => false
  2646. | some u => goodB e T u
  2647. def paired (e : W → W → Bool) (T : W) : Raw Nat → Raw Nat → Bool
  2648. | some u,some v => goodB e T u && goodB e T v && walkB e u v
  2649. | _,_ => false
  2650. def relB (e : W → W → Bool) (T : W) (a b : Raw Nat) :=
  2651. ((!liveB e T a) && (!liveB e T b)) || paired e T a b
  2652. theorem rel_iff (R : Rules Nat) (e : W → W → Bool) (ok : ∀ u v,e u v=true ↔ R.step u v)
  2653. (T : W) (a b : Raw Nat) : relB e T a b=true ↔ Rel R T a b := by
  2654. have live (x : Raw Nat) : liveB e T x=true ↔ Live R T x := by
  2655. cases x with
  2656. | none => simp [liveB,Live]
  2657. | some u => exact good_iff R e ok T u
  2658. have no (x : Raw Nat) : (!liveB e T x)=true ↔ ¬Live R T x := by
  2659. rw [←live]; cases liveB e T x <;> decide
  2660. simp only [relB,Bool.or_eq_true,Bool.and_eq_true,no,P455Quotient.Rel]
  2661. apply or_congr_right
  2662. cases a <;> cases b <;> simp [paired,good_iff R e ok,walk_iff R e ok,and_assoc,Option.some.injEq]
  2663. def eqB (R : Rules Nat) (e : W → W → Bool) (ok : ∀ u v,e u v=true ↔ R.step u v)
  2664. (T : W) (x y : Q R T) : Bool :=
  2665. Quotient.liftOn₂ x y (relB e T) (by
  2666. intro a b c d ac bd
  2667. apply Bool.eq_iff_iff.mpr
  2668. rw [rel_iff R e ok,rel_iff R e ok]
  2669. exact ⟨fun ab => rel_trans R (rel_symm R ac) (rel_trans R ab bd),
  2670. fun cd => rel_trans R ac (rel_trans R cd (rel_symm R bd))⟩)
  2671. theorem eq_iff (R : Rules Nat) (e : W → W → Bool) (ok : ∀ u v,e u v=true ↔ R.step u v)
  2672. (T : W) (x y : Q R T) : eqB R e ok T x y=true ↔ x=y := by
  2673. induction x,y using Quotient.inductionOn₂ with | _ a b =>
  2674. exact (rel_iff R e ok T a b).trans ⟨fun h => Quotient.sound (s := setoid R T) h,fun h => Quotient.exact h⟩
  2675. def decEq (R : Rules Nat) (e : W → W → Bool) (ok : ∀ u v,e u v=true ↔ R.step u v)
  2676. (T : W) : DecidableEq (Q R T) :=
  2677. fun x y => decidable_of_bool _ (eq_iff R e ok T x y)
  2678. end P455EffectiveQ
  2679. end
  2680. /- Begin Problem455PaddedTiles (from finite-semigroup-identity-bases). -/
  2681. section
  2682. namespace P455PaddedTiles
  2683. open P455Witness
  2684. structure Tile (n : Nat) where
  2685. left : Bool
  2686. right : Bool
  2687. top : Bool
  2688. bottom : Bool
  2689. oddRow : Bool
  2690. oddColumn : Bool
  2691. l : Option (Fin n)
  2692. c : Fin n
  2693. r : Option (Fin n)
  2694. b : Fin n
  2695. deriving DecidableEq
  2696. def digit (n k : Nat) : Tag := List.replicate k true ++ List.replicate (n-k) false
  2697. def letter : Option (Fin n) → Nat
  2698. | none => 0
  2699. | some a => a.val+1
  2700. def token {n : Nat} (s : Option (Fin n)) := digit (n+1) (letter s)
  2701. def code (p : Tile n) : Tag :=
  2702. p.left :: p.right :: p.top :: p.bottom :: p.oddRow :: p.oddColumn ::
  2703. (token p.l ++ (token (some p.c) ++ (token p.r ++ token (some p.b))))
  2704. def widthCode (n : Nat) := 6+4*(n+1)
  2705. private theorem token_length (s : Option (Fin n)) : (token s).length=n+1 := by
  2706. have lim : letter s ≤ n+1 := by cases s with
  2707. | none => simp [letter]
  2708. | some a => simp only [letter]; have := a.isLt; omega
  2709. simp [token,digit]; omega
  2710. theorem code_length (p : Tile n) : (code p).length = widthCode n := by
  2711. simp [code,widthCode,token_length]; omega
  2712. private theorem token_inj {a b : Option (Fin n)} (eq : token a = token b) : a=b := by
  2713. have ct := congrArg (List.count true) eq
  2714. have zero (k : Nat) : (List.replicate k false).count true=0 := by
  2715. apply List.count_eq_zero.mpr
  2716. intro m
  2717. have := List.eq_of_mem_replicate m
  2718. contradiction
  2719. simp [token,digit,zero] at ct
  2720. cases a <;> cases b <;> simp_all [letter,Fin.ext_iff]
  2721. theorem code_inj {p q : Tile n} (eq : code p = code q) : p=q := by
  2722. cases p with
  2723. | mk l r t b row col ll cc rr bb =>
  2724. cases q with
  2725. | mk l' r' t' b' row' col' ll' cc' rr' bb' =>
  2726. simp only [code,List.cons.injEq] at eq
  2727. obtain ⟨rfl,rfl,rfl,rfl,rfl,rfl,eq⟩ := eq
  2728. obtain ⟨e1,e⟩ := List.append_inj eq ((token_length _).trans (token_length _).symm)
  2729. obtain ⟨e2,e⟩ := List.append_inj e ((token_length _).trans (token_length _).symm)
  2730. obtain ⟨e3,e4⟩ := List.append_inj e ((token_length _).trans (token_length _).symm)
  2731. have z1 := token_inj e1; have z2 := Option.some.inj (token_inj e2)
  2732. have z3 := token_inj e3; have z4 := Option.some.inj (token_inj e4)
  2733. subst_vars; rfl
  2734. /-- Local alphabet of center symbols, including all possible head marks.
  2735. Undefined entries reject forbidden triples, including a head leaving the tape. -/
  2736. structure MachineTable (n : Nat) where
  2737. marker : Fin n → Bool
  2738. initial : Bool → Fin n
  2739. accept : Fin n
  2740. distinct : initial true ≠ accept
  2741. next : Option (Fin n) → Fin n → Option (Fin n) → Option (Fin n)
  2742. def Admitted (M : MachineTable n) (p : Tile n) :=
  2743. M.next p.l p.c p.r = some p.b ∧
  2744. p.left = p.l.isNone ∧ p.right = p.r.isNone ∧ M.marker p.c = p.left ∧
  2745. (p.left=true → p.oddColumn=false) ∧
  2746. (p.top=true → p.oddRow=false ∧ p.c=M.initial p.left) ∧
  2747. (p.bottom=true → p.left=true → p.c=M.accept)
  2748. def allowed (M : MachineTable n) (tag : Tag) := ∃ p, code p=tag ∧ Admitted M p
  2749. def Horizontal (p q : Tile n) :=
  2750. p.right=false ∧ q.left=false ∧ p.top=q.top ∧ p.bottom=q.bottom ∧
  2751. p.oddRow=q.oddRow ∧ p.oddColumn≠q.oddColumn ∧ q.l=some p.c ∧ p.r=some q.c
  2752. def Vertical (p q : Tile n) :=
  2753. p.bottom=false ∧ q.top=false ∧ p.left=q.left ∧ p.right=q.right ∧
  2754. p.oddColumn=q.oddColumn ∧ p.oddRow≠q.oddRow ∧ p.b=q.c
  2755. def system (n : Nat) : Tiles where
  2756. horizontal := fun x y => ∃ p q : Tile n, code p=x ∧ code q=y ∧ Horizontal p q
  2757. vertical := fun x y => ∃ p q : Tile n, code p=x ∧ code q=y ∧ Vertical p q
  2758. left := fun t => t[0]?.getD false
  2759. right := fun t => t[1]?.getD false
  2760. top := fun t => t[2]?.getD false
  2761. bottom := fun t => t[3]?.getD false
  2762. oddRow := fun t => t[4]?.getD false
  2763. oddColumn := fun t => t[5]?.getD false
  2764. def leftAt (row : Nat → Fin n) (x : Nat) := if x=0 then none else some (row (x-1))
  2765. def rightAt (row : Nat → Fin n) (w x : Nat) := if x+1=w then none else some (row (x+1))
  2766. def odd (i : Nat) : Bool := decide (i%2=1)
  2767. /-- Finite accepting trace through row s on w cells. The final local update
  2768. is checked once, including at both flagged boundaries. -/
  2769. structure Run (M : MachineTable n) (w s : Nat) where
  2770. positive : 0<w
  2771. rows : Nat → Nat → Fin n
  2772. start : ∀ x, x<w → rows 0 x=M.initial (decide (x=0))
  2773. marks : ∀ y, y≤s → ∀ x, x<w → M.marker (rows y x)=decide (x=0)
  2774. steps : ∀ y, y<s → ∀ x, x<w →
  2775. M.next (leftAt (rows y) x) (rows y x) (rightAt (rows y) w x)=some (rows (y+1) x)
  2776. accept : rows s 0=M.accept
  2777. stutter : ∀ x, x<w →
  2778. M.next (leftAt (rows s) x) (rows s x) (rightAt (rows s) w x)=some (rows s x)
  2779. variable {n w s : Nat} {M : MachineTable n}
  2780. theorem positive_time (R : Run M w s) : 0<s := by
  2781. cases s with
  2782. | zero =>
  2783. have z := (R.start 0 R.positive).symm.trans R.accept
  2784. exact False.elim (M.distinct (by simpa using z))
  2785. | succ => omega
  2786. def tileAt (R : Run M w s) (extra y x : Nat) : Tile n where
  2787. left := decide (x=0)
  2788. right := decide (x+1=w)
  2789. top := decide (y=0)
  2790. bottom := decide (y=s+extra)
  2791. oddRow := odd y
  2792. oddColumn := odd x
  2793. l := leftAt (R.rows (min y s)) x
  2794. c := R.rows (min y s) x
  2795. r := rightAt (R.rows (min y s)) w x
  2796. b := R.rows (min (y+1) s) x
  2797. theorem admits_tile (R : Run M w s) (extra y x : Nat) (hx : x<w) :
  2798. Admitted M (tileAt R extra y x) := by
  2799. refine ⟨?_,?_,?_,R.marks _ (Nat.min_le_right ..) _ hx,?_,?_,?_⟩
  2800. · by_cases h : y<s
  2801. · simpa [tileAt,Nat.min_eq_left (by omega : y≤s),Nat.min_eq_left (by omega : y+1≤s)] using R.steps y h x hx
  2802. · simpa [tileAt,Nat.min_eq_right (by omega : s≤y),Nat.min_eq_right (by omega : s≤y+1)] using R.stutter x hx
  2803. · by_cases e : x=0 <;> simp [tileAt,leftAt,e]
  2804. · by_cases e : x+1=w <;> simp [tileAt,rightAt,e]
  2805. · intro h; have e : x=0 := of_decide_eq_true h; simp [tileAt,odd,e]
  2806. · intro h; have e : y=0 := of_decide_eq_true h; simpa [tileAt,odd,e] using R.start x hx
  2807. · intro a b
  2808. have ey : y=s+extra := of_decide_eq_true a
  2809. have ex : x=0 := of_decide_eq_true b
  2810. simpa [tileAt,ex,ey,Nat.min_eq_right (by omega : s≤s+extra)] using R.accept
  2811. private theorem opposite (x : Nat) : odd x ≠ odd (x+1) := by
  2812. unfold odd
  2813. by_cases e : x%2=1
  2814. · have f : (x+1)%2 ≠ 1 := by omega
  2815. simp [e,f]
  2816. · have f : (x+1)%2 = 1 := by omega
  2817. simp [e,f]
  2818. theorem horizontal (R : Run M w s) (extra y x : Nat) (hx : x+1<w) :
  2819. Horizontal (tileAt R extra y x) (tileAt R extra y (x+1)) := by
  2820. refine ⟨?_,?_,rfl,rfl,rfl,opposite _,?_,?_⟩
  2821. · simp [tileAt,show x+1≠w by omega]
  2822. · simp [tileAt]
  2823. · simp [tileAt,leftAt]
  2824. · simp [tileAt,rightAt,show x+1≠w by omega]
  2825. theorem vertical (R : Run M w s) (extra y x : Nat) (hy : y<s+extra) :
  2826. Vertical (tileAt R extra y x) (tileAt R extra (y+1) x) := by
  2827. refine ⟨?_,?_,rfl,rfl,rfl,opposite _,rfl⟩
  2828. · simp [tileAt,show y≠s+extra by omega]
  2829. · simp [tileAt]
  2830. structure Rectangle (M : MachineTable n) (width height : Nat) where
  2831. positiveW : 0<width
  2832. positiveH : 0<height
  2833. tag : Nat → Nat → Tag
  2834. eligible : ∀ y, y<height → ∀ x, x<width → allowed M (tag y x)
  2835. flags : ∀ y, y<height → ∀ x, x<width →
  2836. (system n).left (tag y x)=decide (x=0) ∧ (system n).right (tag y x)=decide (x+1=width) ∧
  2837. (system n).top (tag y x)=decide (y=0) ∧ (system n).bottom (tag y x)=decide (y+1=height) ∧
  2838. (system n).oddRow (tag y x)=odd y ∧ (system n).oddColumn (tag y x)=odd x
  2839. right : ∀ y, y<height → ∀ x, x+1<width → (system n).horizontal (tag y x) (tag y (x+1))
  2840. down : ∀ y, y+1<height → ∀ x, x<width → (system n).vertical (tag y x) (tag (y+1) x)
  2841. def rectangle (R : Run M w s) (extra : Nat) : Rectangle M w (s+extra+1) where
  2842. positiveW := R.positive
  2843. positiveH := by omega
  2844. tag := fun y x => code (tileAt R extra y x)
  2845. eligible := fun y _ x hx => ⟨_,rfl,admits_tile R extra y x hx⟩
  2846. flags := by
  2847. intro y _ x _
  2848. simp [system,code,tileAt]
  2849. right := fun y _ x hx => ⟨_,_,rfl,rfl,horizontal R extra y x hx⟩
  2850. down := fun y hy x _ => ⟨_,_,rfl,rfl,vertical R extra y x (by omega)⟩
  2851. /-- The same tag alphabet, tag length and tile relations work at every
  2852. bound. Width one is allowed. The construction pads time alone. -/
  2853. theorem unbounded (R : Run M w s) (k : Nat) :
  2854. ∃ h, 1<h ∧ k<2*(w*h) ∧ Nonempty (Rectangle M w h) := by
  2855. have time := positive_time R
  2856. let h := s+k+1
  2857. have hw : 1≤w := R.positive
  2858. have size : h ≤ w*h := by simpa using Nat.mul_le_mul_right h hw
  2859. exact ⟨h,by dsimp [h]; omega,by dsimp [h] at *; omega,⟨rectangle R k⟩⟩
  2860. end P455PaddedTiles
  2861. end
  2862. /- Begin Problem455GadgetPaths (from finite-semigroup-identity-bases). -/
  2863. section
  2864. /- Routes are expressed in the same concrete contact predicates as the
  2865. certificate. Each step records its record or port orientation. -/
  2866. namespace P455Paths
  2867. open P455Witness Problem455.Slots
  2868. abbrev Step := Nat × ContactChoice
  2869. def Walk (r : Nat) (allow : Tag → Prop) (mark : Marking) (w : W) (s : Nat) :
  2870. List Step → Prop
  2871. | [] => True
  2872. | (b,c) :: rest => Holds r allow mark w (contact r s b c) ∧ Walk r allow mark w b rest
  2873. def endpoint (s : Nat) : List Step → Nat
  2874. | [] => s
  2875. | (b,_) :: rest => endpoint b rest
  2876. theorem route_iff {r allow mark w} (s : Nat) (p : List Step) (f : Nat → Query) :
  2877. Holds r allow mark w (route r s p f) ↔
  2878. Walk r allow mark w s p ∧ Holds r allow mark w (f (endpoint s p)) := by
  2879. induction p generalizing s with
  2880. | nil => simp [route, Walk, endpoint]
  2881. | cons p ps ih => rcases p with ⟨b,c⟩; simp only [route,Holds,Walk,endpoint,ih,and_assoc]
  2882. def Near (r : Nat) (allow : Tag → Prop) (mark : Marking) (w : W) (s b J : Nat) : Prop :=
  2883. ∃ p, Walk r allow mark w s p ∧ endpoint s p = b ∧ p.length ≤ J
  2884. theorem near_self {r allow mark w} (s J : Nat) : Near r allow mark w s s J :=
  2885. ⟨[],True.intro,rfl,Nat.zero_le _⟩
  2886. theorem near_one {r allow mark w s t} (c : ContactChoice)
  2887. (hc : Holds r allow mark w (contact r s t c)) : Near r allow mark w s t 1 :=
  2888. ⟨[(t,c)],⟨hc,True.intro⟩,rfl,Nat.le_refl _⟩
  2889. theorem near_mono {r allow mark w s b n m} (h : Near r allow mark w s b n) (le : n ≤ m) :
  2890. Near r allow mark w s b m := by
  2891. obtain ⟨p,v,e,len⟩ := h; exact ⟨p,v,e,Nat.le_trans len le⟩
  2892. theorem walk_append {r allow mark w} (a : Nat) (p q : List Step) :
  2893. Walk r allow mark w a (p++q) ↔ Walk r allow mark w a p ∧ Walk r allow mark w (endpoint a p) q := by
  2894. induction p generalizing a with
  2895. | nil => simp [Walk,endpoint]
  2896. | cons ab p ih => obtain ⟨b,c⟩ := ab; simp [Walk,endpoint,ih,and_assoc]
  2897. theorem endpoint_append (a : Nat) (p q : List Step) :
  2898. endpoint a (p++q) = endpoint (endpoint a p) q := by
  2899. induction p generalizing a with
  2900. | nil => rfl
  2901. | cons ab p ih => exact ih ab.1
  2902. theorem near_trans {r allow mark w a b c i j} (h : Near r allow mark w a b i)
  2903. (g : Near r allow mark w b c j) : Near r allow mark w a c (i+j) := by
  2904. obtain ⟨p,hp,ep,lp⟩ := h
  2905. obtain ⟨q,hq,eq,lq⟩ := g
  2906. exact ⟨p++q,(walk_append ..).mpr ⟨hp,ep.symm ▸ hq⟩,
  2907. by rw [endpoint_append,ep,eq], by simp; omega⟩
  2908. abbrev V (r : Nat) (allow : Tag → Prop) (mark : Marking) (w : W) := Holds r allow mark w
  2909. theorem allQ_iff {r allow mark w} (qs : List Query) :
  2910. V r allow mark w (allQ qs) ↔ ∀ q ∈ qs, V r allow mark w q := by
  2911. induction qs with
  2912. | nil => simp [allQ,V,Holds]
  2913. | cons x xs ih => change (_ ∧ V r allow mark w (allQ xs)) ↔ _; simp [ih]
  2914. theorem slot_route {r allow mark w} (s : SlotCertificate)
  2915. (ok : V r allow mark w (s.query r)) :
  2916. let a := if s.startAtMate then s.anchor.mate else s.anchor.owner
  2917. s.steps.length ≤ 6 ∧ Walk r allow mark w a s.steps ∧
  2918. V r allow mark w (terminalSlot r (endpoint a s.steps) s.terminalIndex s.defect) := by
  2919. simp only [SlotCertificate.query,allQ,Holds,V] at ok
  2920. exact ⟨ok.2.1,(route_iff ..).mp ok.2.2.1⟩
  2921. theorem record_counts {r allow mark w a b tag}
  2922. (bound : P455Closure.Cap r w) (recProof : V r allow mark w (.record a b tag)) :
  2923. w.count a = r ∧ w.count b = r := by
  2924. obtain ⟨ne,hl,_,bit,eq⟩ := recProof
  2925. have n := congrArg List.length eq
  2926. simp only [length_select_pair a b ne,profile,List.length_append,profile_prefix_length] at n
  2927. have ca := bound a; have cb := bound b
  2928. cases bit <;> simp [pair] at n <;> omega
  2929. theorem record_pair {r allow mark w} {n : Node} (recProof : V r allow mark w (typedNode n)) :
  2930. Near r allow mark w n.owner n.mate 1 ∧ Near r allow mark w n.mate n.owner 1 :=
  2931. ⟨near_one (.record n.tag false) recProof, near_one (.record n.tag true) recProof⟩
  2932. private theorem stamp_lower (n : Nat → Nat) (w : W) (a i : Nat)
  2933. (h : (a,i) ∈ stamp n w) : n a ≤ i := by
  2934. induction w generalizing n with
  2935. | nil => simp [stamp] at h
  2936. | cons b w ih =>
  2937. rcases List.mem_cons.mp h with he|hh
  2938. · cases he; exact Nat.le_refl _
  2939. · have z := ih (advance n [b]) hh; simp only [advance] at z; omega
  2940. theorem stamp_unique (n : Nat → Nat) (w : W) : (stamp n w).Nodup := by
  2941. induction w generalizing n with
  2942. | nil => simp [stamp]
  2943. | cons a w ih =>
  2944. apply List.nodup_cons.mpr
  2945. refine ⟨fun bad => ?_, ih _⟩
  2946. have low := stamp_lower (advance n [a]) w a (n a) bad
  2947. simp [advance] at low <;> omega
  2948. theorem owner_early {r allow mark w} (a b : Node)
  2949. (early : V r allow mark w (earlyDisjoint [a.owner,a.mate] [b.owner,b.mate])) :
  2950. V r allow mark w (earlyDisjoint [a.owner] [b.owner]) := by
  2951. rcases early with h|h
  2952. · left; exact ⟨h.1,True.intro⟩
  2953. · right; exact ⟨h.1,True.intro⟩
  2954. theorem owner_port {r allow mark w} (cap : P455Closure.Cap r w) (p : Fin 5) (a b : Node)
  2955. (ok : V r allow mark w (orientedPort p a b)) :
  2956. V r allow mark w (contact r a.owner b.owner (.port p false)) ∧
  2957. V r allow mark w (contact r b.owner a.owner (.port p true)) := by
  2958. obtain ⟨na,nb,early,order,_⟩ := ok
  2959. let i := 3 + 2*p.val
  2960. let pat := [(a.owner,i),(b.owner,i),(a.owner,i+1),(b.owner,i+1)]
  2961. have sub : pat.Sublist [(a.owner,i),(a.mate,i),(b.owner,i),(b.mate,i),
  2962. (a.owner,i+1),(a.mate,i+1),(b.owner,i+1),(b.mate,i+1)] := by
  2963. exact .cons₂ _ (.cons _ (.cons₂ _ (.cons _ (.cons₂ _ (.cons _ (.cons₂ _ (List.nil_sublist _)))))))
  2964. have obs : V r allow mark w (.order pat) :=
  2965. ⟨fun e he => order.1 e (sub.subset he),sub.trans order.2⟩
  2966. have nd := (stamp_unique (fun _ => 0) w).sublist obs.2
  2967. have ne : a.owner ≠ b.owner := by
  2968. intro eq
  2969. have := (List.nodup_cons.mp nd).1
  2970. exact this (by simp [eq])
  2971. have xa := (record_counts cap na).1
  2972. have xb := (record_counts cap nb).1
  2973. have ed := owner_early a b early
  2974. exact ⟨⟨ne,xa,xb,ed,obs,True.intro⟩,⟨Ne.symm ne,xb,xa,ed.symm,obs,True.intro⟩⟩
  2975. /-- One actual port yields an owner contact in both directions. -/
  2976. def Joined (r : Nat) (allow : Tag → Prop) (mark : Marking) (w : W) (a b : Node) :=
  2977. Near r allow mark w a.owner b.owner 1 ∧ Near r allow mark w b.owner a.owner 1
  2978. theorem port_joined {r allow mark w} (cap : P455Closure.Cap r w) (n : Nat) (hn : n < 5)
  2979. {a b : Node} (ok : V r allow mark w (orientedPort n a b)) : Joined r allow mark w a b := by
  2980. obtain ⟨f,g⟩ := owner_port cap ⟨n,hn⟩ a b ok
  2981. exact ⟨near_one _ f,near_one _ g⟩
  2982. theorem right_paths {r allow mark w ts a b} (cap : P455Closure.Cap r w)
  2983. (ok : V r allow mark w (rightward ts a b)) : Joined r allow mark w a b :=
  2984. port_joined cap _ (by split <;> decide) ok.2.1
  2985. theorem down_paths {r allow mark w ts a b} (cap : P455Closure.Cap r w)
  2986. (ok : V r allow mark w (downward ts a b)) : Joined r allow mark w a b :=
  2987. port_joined cap _ (by split <;> decide) ok.2
  2988. theorem neighbor_paths {r allow mark w ts a b} (cap : P455Closure.Cap r w) (d : Dir)
  2989. (ok : V r allow mark w (neighbor ts a b d)) : Joined r allow mark w a b := by
  2990. cases d with
  2991. | right => exact right_paths cap ok
  2992. | left => exact (right_paths cap ok).symm
  2993. | down => exact down_paths cap ok
  2994. | up => exact (down_paths cap ok).symm
  2995. theorem neighbor_target_record {r allow mark w ts a b d}
  2996. (ok : V r allow mark w (neighbor ts a b d)) : V r allow mark w (typedNode b) := by
  2997. cases d with
  2998. | right => exact ok.2.1.2.1
  2999. | left => exact ok.2.1.1
  3000. | down => exact ok.2.2.1
  3001. | up => exact ok.2.1
  3002. theorem marked_typed {r allow mark w a bit} (m : V r allow mark w (markedNode a bit)) :
  3003. V r allow mark w (typedNode a) := ⟨m.1,m.2.1,m.2.2.1,bit,m.2.2.2.2⟩
  3004. end P455Paths
  3005. end
  3006. /- Begin Problem455ContactGeometry (from finite-semigroup-identity-bases). -/
  3007. section
  3008. namespace P455ContactGeometry
  3009. open Problem455.Slots P455Witness
  3010. /-- Erasing unselected labels preserves the indices of selected labels. -/
  3011. theorem project_stamp (keep w : Word) (n n' : Nat → Nat)
  3012. (agree : ∀ a ∈ keep, n a = n' a) :
  3013. stamp n (select keep w) = (stamp n' w).filter (fun e => decide (e.1 ∈ keep)) := by
  3014. induction w generalizing n n' with
  3015. | nil => rfl
  3016. | cons a w ih =>
  3017. by_cases ha : a ∈ keep
  3018. · simp only [select, List.filter_cons, decide_eq_true ha, if_true, stamp]
  3019. rw [agree a ha]
  3020. congr 1
  3021. apply ih
  3022. intro b hb
  3023. simp [advance, agree b hb]
  3024. · simp only [select, List.filter_cons, decide_eq_false ha, Bool.false_eq_true, if_false, stamp]
  3025. apply ih
  3026. intro b hb
  3027. have ne : a ≠ b := fun e => ha (e ▸ hb)
  3028. simp [advance, ne, Ne.symm ne, agree b hb]
  3029. theorem projected_events_sublist (keep w : Word) : (events (select keep w)).Sublist (events w) := by
  3030. rw [events, project_stamp keep w (fun _ => 0) (fun _ => 0) (fun _ _ => rfl)]
  3031. exact List.filter_sublist ..
  3032. private theorem profile_initial {a b : Nat} (ab : a ≠ b) (tag : Tag) (bit : Bool) :
  3033. [(a,0),(a,1),(b,0),(a,2),(b,1),(b,2)].Sublist (events (profile a b tag bit)) := by
  3034. have shape : ∃ t : Word, profile a b tag bit = [a,a,b,a,b,b] ++ t := by
  3035. unfold profile profilePrefix
  3036. simp only [List.append_assoc]
  3037. exact ⟨_,rfl⟩
  3038. obtain ⟨t,e⟩ := shape
  3039. rw [e,events,stamp_append]
  3040. have pre : stamp (fun _ => 0) [a,a,b,a,b,b] = [(a,0),(a,1),(b,0),(a,2),(b,1),(b,2)] := by
  3041. simp [stamp,advance,ab,Ne.symm ab]
  3042. rw [pre]
  3043. exact List.sublist_append_left ..
  3044. /-- A record supplies the two open slot witnesses and an early order that
  3045. cannot occur between two labels donated by one uniform variable. -/
  3046. private theorem record_geometry {z : Word} {a b : Nat} {tag : Tag}
  3047. (ab : a ≠ b) (typ : typed z a b tag) :
  3048. occupies z a 1 b ∧ occupies z b 0 a ∧ sees z [(a,1),(b,0)] := by
  3049. obtain ⟨bit,eq⟩ := typ
  3050. have initial := profile_initial ab tag bit
  3051. rw [← eq] at initial
  3052. have sub := initial.trans (projected_events_sublist [a,b] z)
  3053. refine ⟨⟨0,?_⟩,⟨2,?_⟩,?_⟩
  3054. · exact (List.Sublist.cons _ (.cons₂ _ (.cons₂ _ (.cons₂ _ (List.nil_sublist _))))).trans sub
  3055. · exact (List.Sublist.cons _ (.cons _ (.cons₂ _ (.cons₂ _ (.cons₂ _ (List.nil_sublist _)))))).trans sub
  3056. · exact (List.Sublist.cons _ (.cons₂ _ (.cons₂ _ (List.nil_sublist _)))).trans sub
  3057. /-- The seven slots and the obstruction to a shared donor follow from
  3058. the actual record or port contact. The port can be read in either direction. -/
  3059. theorem geometry {r allow mark z a b c} (hc : Holds r allow mark z (contact r a b c)) :
  3060. (∃ i, slotStart i ∧ occupies z a i b) ∧
  3061. (∃ i, 0 < i ∧ (sees z [(a,i),(b,0)] ∨ sees z [(b,i),(a,0)])) := by
  3062. cases c with
  3063. | record tag rev =>
  3064. cases rev
  3065. · obtain ⟨ab,_,_,typ⟩ := hc
  3066. obtain ⟨slot,_,ord⟩ := record_geometry ab typ
  3067. exact ⟨⟨1,by simp [slotStart],slot⟩,⟨1,by decide,.inl ord⟩⟩
  3068. · obtain ⟨ba,_,_,typ⟩ := hc
  3069. obtain ⟨_,slot,ord⟩ := record_geometry ba typ
  3070. exact ⟨⟨0,by simp [slotStart],slot⟩,⟨1,by decide,.inr ord⟩⟩
  3071. | port phase rev =>
  3072. let i := 3+2*phase.val
  3073. have hi : slotStart i := by have := phase.isLt; unfold i slotStart; omega
  3074. have early : Holds r allow mark z (earlyDisjoint [a] [b]) := hc.2.2.2.1
  3075. have ord : sees z [(a,2),(b,0)] ∨ sees z [(b,2),(a,0)] := by
  3076. rcases early with e | e
  3077. · exact .inl e.1.2
  3078. · exact .inr e.1.2
  3079. refine ⟨⟨i,hi,?_⟩,⟨2,by decide,ord⟩⟩
  3080. cases rev
  3081. · have seq : sees z [(a,i),(b,i),(a,i+1),(b,i+1)] := hc.2.2.2.2.1.2
  3082. exact ⟨i,(List.Sublist.cons₂ _ (.cons₂ _ (.cons₂ _ (List.nil_sublist _)))).trans seq⟩
  3083. · have seq : sees z [(b,i),(a,i),(b,i+1),(a,i+1)] := hc.2.2.2.2.1.2
  3084. exact ⟨i+1,(List.Sublist.cons _ (.refl _)).trans seq⟩
  3085. theorem contact_slot {r allow mark z a b c} (hc : Holds r allow mark z (contact r a b c)) :
  3086. ∃ i, slotStart i ∧ occupies z a i b := (geometry hc).1
  3087. /-- Membership of a stamped occurrence gives inclusive lower and exclusive
  3088. upper bounds from the prefix counter and the number of copies in the segment. -/
  3089. theorem stamp_range (n : Nat → Nat) (w : Word) {a i : Nat} (h : (a,i) ∈ stamp n w) :
  3090. n a ≤ i ∧ i < n a + w.count a := by
  3091. induction w generalizing n with
  3092. | nil => simp [stamp] at h
  3093. | cons b w ih =>
  3094. rcases List.mem_cons.mp h with head | tail
  3095. · obtain ⟨rfl,rfl⟩ := Prod.mk.inj head
  3096. simp [List.count_cons]
  3097. · have z := ih _ tail
  3098. by_cases e : b = a
  3099. · subst b; simp [advance,List.count_cons] at z ⊢; omega
  3100. · simp [advance,List.count_cons,e,Ne.symm e] at z ⊢; omega
  3101. private theorem impossible_order {z f t : Word} {a b i : Nat} (eq : z = f ++ t)
  3102. (low : f.count a ≤ i) (positive : 0 < f.count b) : ¬ sees z [(a,i),(b,0)] := by
  3103. intro e
  3104. have h : [(a,i),(b,0)].Sublist (events f ++ stamp (advance (fun _ => 0) f) t) := by
  3105. simpa only [sees, eq, events, stamp_append] using e
  3106. have first : (a,i) ∉ events f := by
  3107. intro mem
  3108. have bad := (stamp_range (fun _ => 0) f mem).2
  3109. simp only [Nat.zero_add] at bad
  3110. omega
  3111. have last : (b,0) ∉ stamp (advance (fun _ => 0) f) t := by
  3112. intro mem
  3113. have := stamp_range (advance (fun _ => 0) f) t mem
  3114. simp [advance] at this
  3115. omega
  3116. have strip {α : Type} {x y : α} {l k : List α} (n : x ∉ l)
  3117. (s : [x,y].Sublist (l ++ k)) : [x,y].Sublist k := by
  3118. induction l with
  3119. | nil => exact s
  3120. | cons j l ih =>
  3121. cases s with
  3122. | cons _ rest => exact ih (fun e => n (by simp [e])) rest
  3123. | cons_cons _ _ => exact (n (by simp)).elim
  3124. exact last ((strip first h).subset (by simp))
  3125. /-- Initial source/prefix split at the first occurrence of one used name. -/
  3126. private theorem first_split (x : Nat) (v : Word) (occ : x ∈ v) :
  3127. ∃ l t, v = l ++ x :: t ∧ x ∉ l := by
  3128. induction v with
  3129. | nil => simp at occ
  3130. | cons a v ih =>
  3131. by_cases e : a = x
  3132. · subst a; exact ⟨[],v,rfl,by simp⟩
  3133. · obtain ⟨l,t,eq,nh⟩ := ih (by simpa [Ne.symm e] using occ)
  3134. exact ⟨a::l,t,by simp [eq],by simp [e,Ne.symm e,nh]⟩
  3135. /-- Two labels from the same donor each have exactly one occurrence in
  3136. the prefix ending at its first image, even if the labels coincide. -/
  3137. theorem same_image_no_early {r : Nat} {v : Word} {h : Nat → Word}
  3138. {l t : Word} {x a b i : Nat} (hr : 0 < r)
  3139. (bound : P455Closure.Cap r (l ++ v.flatMap h ++ t))
  3140. (hx : v.count x = r) (ha : a ∈ h x) (hb : b ∈ h x) (hi : 0 < i) :
  3141. ¬ sees (l ++ v.flatMap h ++ t) [(a,i),(b,0)] := by
  3142. have px : x ∈ v := List.count_pos_iff.mp (hx ▸ hr)
  3143. obtain ⟨pre,post,cut,avoid⟩ := first_split x v px
  3144. have bounds (j : Nat) (mem : j ∈ h x) : (l ++ pre.flatMap h ++ h x).count j = 1 := by
  3145. have bb := bound j
  3146. simp only [List.count_append] at bb
  3147. obtain ⟨one,exclusive,sat⟩ := P455DonorInterval.exclusive h v x j r hr hx mem (by omega)
  3148. have fresh : j ∉ pre.flatMap h := by
  3149. intro z
  3150. obtain ⟨y,hy,yj⟩ := List.mem_flatMap.mp z
  3151. exact exclusive y (by simp [cut,hy]) (fun e => avoid (e ▸ hy)) yj
  3152. have left : l.count j = 0 := by omega
  3153. simp [List.count_append,left,List.count_eq_zero.mpr fresh,one]
  3154. have eq : l ++ v.flatMap h ++ t = (l ++ pre.flatMap h ++ h x) ++ (post.flatMap h ++ t) := by
  3155. simp [cut,List.flatMap_append,List.append_assoc]
  3156. exact impossible_order eq (by rw [bounds a ha]; omega) (by rw [bounds b hb]; decide)
  3157. /-- An actual contact to a label donated by x cannot be another letter of
  3158. h(x). Saturation is required only of the owner donor. -/
  3159. theorem contact_excludes_image {r allow mark} {v : Word} {h : Nat → Word}
  3160. {l t : Word} {x a b c} (hr : 0 < r)
  3161. (bound : P455Closure.Cap r (l ++ v.flatMap h ++ t))
  3162. (hx : v.count x = r) (ha : a ∈ h x)
  3163. (hc : Holds r allow mark (l ++ v.flatMap h ++ t) (contact r a b c)) : b ∉ h x := by
  3164. intro hb
  3165. obtain ⟨i,hi,ord⟩ := (geometry hc).2
  3166. rcases ord with ord | ord
  3167. · exact same_image_no_early hr bound hx ha hb hi ord
  3168. · exact same_image_no_early hr bound hx hb ha hi ord
  3169. end P455ContactGeometry
  3170. end
  3171. /- Begin Problem455ContactReflection (from finite-semigroup-identity-bases). -/
  3172. section
  3173. namespace P455ContactReflection
  3174. open Problem455.Slots P455Witness
  3175. def eventMap (d : Nat → Nat) (e : Event) : Event := (d e.1, e.2)
  3176. theorem select_stamped (keep w : W) (n n' : Nat → Nat)
  3177. (eqn : ∀ a ∈ keep, n a = n' a) :
  3178. (stamp n w).filter (fun e => decide (e.1 ∈ keep)) = stamp n' (select keep w) := by
  3179. induction w generalizing n n' with
  3180. | nil => rfl
  3181. | cons a w ih =>
  3182. by_cases ha : a ∈ keep
  3183. · simp only [stamp, select, List.filter_cons, ha, decide_true, Bool.true_eq, if_true]
  3184. rw [eqn a ha]
  3185. congr 1
  3186. apply ih
  3187. intro b hb
  3188. simp only [advance, eqn b hb]
  3189. · simp only [stamp, select, List.filter_cons, ha, decide_false, Bool.false_eq_true, if_false]
  3190. apply ih
  3191. intro b hb
  3192. have ab : a ≠ b := fun e => ha (e ▸ hb)
  3193. simp [advance, eqn b hb, ab]
  3194. theorem sees_select (keep w : W) (pat : List Event) (support : ∀ e ∈ pat, e.1 ∈ keep)
  3195. (seen : sees w pat) : sees (select keep w) pat := by
  3196. have filtered := seen.filter (fun e => decide (e.1 ∈ keep))
  3197. have self : pat.filter (fun e => decide (e.1 ∈ keep)) = pat := by
  3198. apply List.filter_eq_self.mpr; simpa using support
  3199. rw [self] at filtered
  3200. unfold sees events at *
  3201. rw [select_stamped keep w _ (fun _ => 0) (fun _ _ => rfl)] at filtered
  3202. exact filtered
  3203. theorem select_sees (keep w : W) (pat : List Event) (seen : sees (select keep w) pat) :
  3204. sees w pat := by
  3205. unfold sees events at *
  3206. rw [← select_stamped keep w (fun _ => 0) _ (fun _ _ => rfl)] at seen
  3207. exact seen.trans (List.filter_sublist ..)
  3208. theorem stamp_map (d : Nat → Nat) (w keep : W) (n n' : Nat → Nat)
  3209. (inside : ∀ a ∈ w, a ∈ keep) (dinj : ∀ a ∈ keep, ∀ b ∈ keep, d a = d b → a = b)
  3210. (eqn : ∀ a ∈ keep, n a = n' (d a)) :
  3211. (stamp n w).map (eventMap d) = stamp n' (w.map d) := by
  3212. induction w generalizing n n' with
  3213. | nil => rfl
  3214. | cons a w ih =>
  3215. have ha := inside a (by simp)
  3216. simp only [stamp, List.map_cons, eventMap, eqn a ha, List.cons.injEq, true_and]
  3217. apply ih _ _ (fun b hb => inside b (by simp [hb]))
  3218. intro b hb
  3219. by_cases eq : a = b
  3220. · subst b; simp [advance,eqn a ha]
  3221. · have ne : d a ≠ d b := fun e => eq (dinj a ha b hb e)
  3222. simp [advance, eq, ne, eqn b hb]
  3223. theorem selected_donor_word {r : Nat} {v l k : W} {h : Nat → W}
  3224. (hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k))
  3225. (keep : W) (d : Nat → Nat)
  3226. (uniform : ∀ a ∈ keep, v.count (d a) = r ∧ a ∈ h (d a))
  3227. (dinj : ∀ a ∈ keep, ∀ b ∈ keep, d a = d b → a = b) :
  3228. (select keep (l ++ v.flatMap h ++ k)).map d = select (keep.map d) v := by
  3229. have exclusive (a) (ha : a ∈ keep) :=
  3230. P455DonorInterval.exclusive h v (d a) a r hr (uniform a ha).1 (uniform a ha).2
  3231. (by have := cap a; simp only [List.count_append] at this; omega)
  3232. have disjoint (a) (ha : a ∈ keep) := P455DonorInterval.enclosing_context
  3233. (v.flatMap h) l k a r (exclusive a ha).2.2 (cap a)
  3234. have sl := select_nil keep l (fun a hm ha => (disjoint a ha).1 hm)
  3235. have sk := select_nil keep k (fun a hm ha => (disjoint a ha).2 hm)
  3236. rw [select_append, select_append, sl, sk, List.nil_append, List.append_nil]
  3237. have owner (x) (hx : x ∈ v) (a) (ha : a ∈ keep) (in_h : a ∈ h x) : d a = x := by
  3238. by_cases eq : x = d a
  3239. · exact eq.symm
  3240. · exact ((exclusive a ha).2.1 x hx eq in_h).elim
  3241. have per (x) (hx : x ∈ v) :
  3242. (select keep (h x)).map d = select (keep.map d) [x] := by
  3243. by_cases mem : x ∈ keep.map d
  3244. · obtain ⟨a,ha,eq⟩ := List.mem_map.mp mem
  3245. have all_a (b) (hb : b ∈ select keep (h x)) : b = a := by
  3246. obtain ⟨in_h,keep_b⟩ := List.mem_filter.mp hb
  3247. have kb : b ∈ keep := by simpa using keep_b
  3248. exact dinj b kb a ha ((owner x hx b kb in_h).trans eq.symm)
  3249. have ct : (select keep (h x)).count a = 1 := by
  3250. rw [select, List.count_filter (by simpa using ha), ← eq, (exclusive a ha).1]
  3251. have len := List.count_eq_length.mpr (fun b hb => (all_a b hb).symm)
  3252. have one : select keep (h x) = List.replicate 1 a :=
  3253. List.eq_replicate_iff.mpr ⟨len.symm.trans ct, all_a⟩
  3254. rw [one]
  3255. simp only [select, List.filter_cons, mem, decide_true, if_true, List.filter_nil, List.replicate_succ, List.replicate_zero, List.map_cons, List.map_nil, eq]
  3256. · have none := select_nil keep (h x) (fun a in_h ha =>
  3257. mem (List.mem_map.mpr ⟨a,ha,owner x hx a ha in_h⟩))
  3258. rw [none]
  3259. simp only [select, List.filter_cons, mem, decide_false, Bool.false_eq_true, if_false, List.filter_nil, List.map_nil]
  3260. have fit (w : W) (sub : ∀ x ∈ w, x ∈ v) :
  3261. (select keep (w.flatMap h)).map d = select (keep.map d) w := by
  3262. induction w with
  3263. | nil => rfl
  3264. | cons a ws ih =>
  3265. change (select keep (h a ++ ws.flatMap h)).map d = select (keep.map d) ([a] ++ ws)
  3266. rw [select_append, List.map_append, select_append, per a (sub a (by simp)),
  3267. ih (fun b hb => sub b (by simp [hb]))]
  3268. exact fit v (fun _ hmem => hmem)
  3269. theorem reflect_order {r : Nat} {v l k : W} {h : Nat → W}
  3270. (hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k))
  3271. (keep : W) (d : Nat → Nat)
  3272. (uniform : ∀ a ∈ keep, v.count (d a) = r ∧ a ∈ h (d a))
  3273. (dinj : ∀ a ∈ keep, ∀ b ∈ keep, d a = d b → a = b)
  3274. (pat : List Event) (inside : ∀ e ∈ pat, e.1 ∈ keep)
  3275. (seen : sees (l ++ v.flatMap h ++ k) pat) : sees v (pat.map (eventMap d)) := by
  3276. have selected := sees_select keep _ pat inside seen
  3277. apply select_sees (keep.map d)
  3278. have named := selected.map (eventMap d)
  3279. unfold sees events at *
  3280. rw [stamp_map d _ keep _ (fun _ => 0)
  3281. (fun a ha => by have := (List.mem_filter.mp ha).2; simpa using this) dinj (fun _ _ => rfl),
  3282. selected_donor_word hr cap keep d uniform dinj] at named
  3283. exact named
  3284. theorem map_profile (d : Nat → Nat) (a b : Nat) (tag : Tag) (bit : Bool) :
  3285. (profile a b tag bit).map d = profile (d a) (d b) tag bit := by
  3286. have bp (c : Bool) : (pair a b c).map d = pair (d a) (d b) c := by cases c <;> rfl
  3287. have tp : (tag.flatMap (pair a b)).map d = tag.flatMap (pair (d a) (d b)) := by
  3288. induction tag with
  3289. | nil => rfl
  3290. | cons c tag ih => simp [bp, ih]
  3291. simp only [profile,profilePrefix,List.map_append,bp,tp]
  3292. rfl
  3293. private theorem two_labels {r : Nat} {v l k : W} {h : Nat → W} {x y s t : Nat}
  3294. (hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k))
  3295. (hx : v.count x = r) (hy : v.count y = r) (hxy : x ≠ y) (hs : s ∈ h x) (ht : t ∈ h y) :
  3296. ∃ d : Nat → Nat, d s = x ∧ d t = y ∧
  3297. (∀ a ∈ [s,t], v.count (d a) = r ∧ a ∈ h (d a)) ∧
  3298. (∀ a ∈ [s,t], ∀ b ∈ [s,t], d a = d b → a = b) := by
  3299. have hy' : y ∈ v := List.count_pos_iff.mp (by omega)
  3300. have diff : s ≠ t := by
  3301. intro eq
  3302. have excl := P455DonorInterval.exclusive h v x s r hr hx hs
  3303. (by have := cap s; simp only [List.count_append] at this; omega)
  3304. exact excl.2.1 y hy' (Ne.symm hxy) (eq ▸ ht)
  3305. let d := fun a => if a = s then x else y
  3306. have p : d s = x := by simp [d]
  3307. have q : d t = y := by simp [d, Ne.symm diff]
  3308. refine ⟨d,p,q,?_,?_⟩
  3309. · intro a mem
  3310. simp only [List.mem_cons, List.not_mem_nil, or_false] at mem
  3311. rcases mem with rfl | rfl
  3312. · exact p.symm ▸ And.intro hx hs
  3313. · exact q.symm ▸ And.intro hy ht
  3314. · intro a ha b hb e
  3315. simp only [List.mem_cons, List.not_mem_nil, or_false] at ha hb
  3316. rcases ha with rfl | rfl <;> rcases hb with rfl | rfl <;> simp_all
  3317. theorem reflect_profile {r : Nat} {v l k : W} {h : Nat → W} {x y s t : Nat}
  3318. (hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k))
  3319. (hx : v.count x = r) (hy : v.count y = r) (hxy : x ≠ y) (hs : s ∈ h x) (ht : t ∈ h y)
  3320. (tag : Tag) (bit : Bool) (eq : select [s,t] (l ++ v.flatMap h ++ k) = profile s t tag bit) :
  3321. select [x,y] v = profile x y tag bit := by
  3322. obtain ⟨d,p,q,uniform,inj⟩ := two_labels hr cap hx hy hxy hs ht
  3323. have e := selected_donor_word hr cap [s,t] d uniform inj
  3324. rw [eq,map_profile] at e
  3325. simpa only [List.map_cons,List.map_nil,p,q] using e.symm
  3326. theorem reflect_order_query {r : Nat} {v l k : W} {h : Nat → W}
  3327. {allow : Tag → Prop} {mark : Marking}
  3328. (hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k))
  3329. (keep : W) (d : Nat → Nat)
  3330. (uniform : ∀ a ∈ keep, v.count (d a) = r ∧ a ∈ h (d a))
  3331. (dinj : ∀ a ∈ keep, ∀ b ∈ keep, d a = d b → a = b)
  3332. (pat : List Event) (inside : ∀ e ∈ pat, e.1 ∈ keep)
  3333. (seen : Holds r allow mark (l ++ v.flatMap h ++ k) (.order pat)) :
  3334. Holds r allow mark v (.order (pat.map (eventMap d))) := by
  3335. obtain ⟨imm, order⟩ := seen
  3336. refine ⟨?_, reflect_order hr cap keep d uniform dinj pat inside order⟩
  3337. rintro e he
  3338. obtain ⟨a,ha,rfl⟩ := List.mem_map.mp he
  3339. exact imm a ha
  3340. theorem reflect_contact {r : Nat} {allow : Tag → Prop} {mark : Marking}
  3341. {v l k : W} {h : Nat → W} {x y s t : Nat}
  3342. (hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k))
  3343. (hx : v.count x = r) (hy : v.count y = r) (hxy : x ≠ y) (hs : s ∈ h x) (ht : t ∈ h y)
  3344. (c : ContactChoice) :
  3345. Holds r allow mark (l ++ v.flatMap h ++ k) (contact r s t c) →
  3346. Holds r allow mark v (contact r x y c) := by
  3347. cases c with
  3348. | record tag rev =>
  3349. cases rev
  3350. · rintro ⟨_,len,code,bit,eq⟩
  3351. exact ⟨hxy,len,code,bit,reflect_profile hr cap hx hy hxy hs ht tag bit eq⟩
  3352. · rintro ⟨_,len,code,bit,eq⟩
  3353. exact ⟨Ne.symm hxy,len,code,bit,reflect_profile hr cap hy hx (Ne.symm hxy) ht hs tag bit eq⟩
  3354. | port phase rev =>
  3355. obtain ⟨d,p,q,uniform,inj⟩ := two_labels hr cap hx hy hxy hs ht
  3356. have orders := @reflect_order_query r v l k h allow mark hr cap [s,t] d uniform inj
  3357. have left (i j : Nat) (sig : Holds r allow mark (l ++ v.flatMap h ++ k) (earlier s i t j)) :
  3358. Holds r allow mark v (earlier x i y j) := by
  3359. have o := orders [(s,i),(t,j)] (by simp) sig
  3360. simpa [eventMap,p,q,earlier] using o
  3361. have right (i j : Nat) (sig : Holds r allow mark (l ++ v.flatMap h ++ k) (earlier t i s j)) :
  3362. Holds r allow mark v (earlier y i x j) := by
  3363. have o := orders [(t,i),(s,j)] (by simp) sig
  3364. simpa [eventMap,p,q,earlier] using o
  3365. intro core
  3366. obtain ⟨_,_,_,early,ordered,_⟩ := core
  3367. refine ⟨hxy,hx,hy,?_,?_,True.intro⟩
  3368. · rcases early with ⟨o,_⟩ | ⟨o,_⟩
  3369. · exact Or.inl ⟨left 2 0 o,True.intro⟩
  3370. · exact Or.inr ⟨right 2 0 o,True.intro⟩
  3371. · let i := 3 + 2 * phase.val
  3372. cases rev with
  3373. | false =>
  3374. have o := orders [(s,i),(t,i),(s,i+1),(t,i+1)] (by simp) ordered
  3375. simpa [eventMap,p,q,i] using o
  3376. | true =>
  3377. have o := orders [(t,i),(s,i),(t,i+1),(s,i+1)] (by simp) ordered
  3378. simpa [eventMap,p,q,i] using o
  3379. end P455ContactReflection
  3380. end
  3381. /- Begin Problem455TerminalTransfer (from finite-semigroup-identity-bases). -/
  3382. section
  3383. namespace P455TerminalTransfer
  3384. open Problem455.Slots P455Witness
  3385. /-- In the overflow branch the assignment is specified only on the five
  3386. selected labels. Different source names are enough for the slot bound. -/
  3387. def Lift (v : Word) (h : Nat → Word) (x i r : Nat) : SlotDefect → Prop
  3388. | .deficient _ => False
  3389. | .overflow xs => ∃ assign : Nat → Nat, xs.length = 5 ∧ (x :: xs.map assign).Nodup ∧
  3390. ∀ a ∈ xs, occupies v x i (assign a) ∧ a ∈ h (assign a) ∧ v.count (assign a) = r
  3391. theorem holds_all {r allow mark z} (qs : List Query) :
  3392. Holds r allow mark z (allQ qs) ↔ ∀ q ∈ qs, Holds r allow mark z q := by
  3393. induction qs with
  3394. | nil => simp [allQ,Holds]
  3395. | cons q qs ih => simp [allQ,Holds,ih]
  3396. theorem block_separation {r allow mark z} (xs : List Nat) :
  3397. Holds r allow mark z (differentBlocks xs) ↔
  3398. xs.Pairwise (fun a b => ¬ Problem455Swap.SameBlock r z a b) := by
  3399. induction xs with
  3400. | nil => simp [differentBlocks,Holds]
  3401. | cons a xs ih =>
  3402. simp [differentBlocks,Holds,holds_all,ih,List.pairwise_cons]
  3403. theorem terminal (v : Word) (h : Nat → Word) (l k : Word) (x s i r : Nat)
  3404. (hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k)) (hx : v.count x = r)
  3405. (hs : s ∈ h x) (guard : ∀ y, occupies v x i y → v.count y = r) {allow mark}
  3406. (d : SlotDefect)
  3407. (obs : Holds r allow mark (l ++ v.flatMap h ++ k) (terminalSlot r s i d)) :
  3408. Lift v h x i r d := by
  3409. let z := l ++ v.flatMap h ++ k
  3410. have capF : ∀ j, (v.flatMap h).count j ≤ r := by
  3411. intro a
  3412. have c := cap a
  3413. simp only [List.count_append] at c
  3414. omega
  3415. have satZ (a y : Nat) (hy : v.count y = r) (ha : a ∈ h y) : z.count a = r := by
  3416. have full := (P455DonorInterval.exclusive h v y a r hr hy ha (capF a)).2.2
  3417. have c := cap a
  3418. simp only [z,List.count_append] at *
  3419. omega
  3420. have common (y a b : Nat) (hy : v.count y = r) (ha : a ∈ h y) (hb : b ∈ h y) :
  3421. Problem455Swap.SameBlock r z a b := by
  3422. have capZ : Problem455Swap.cap r z := by
  3423. intro c
  3424. rw [Problem455BlockBridge.occ_count]
  3425. exact cap c
  3426. exact Problem455Swap.sameBlock_factor ⟨l,k,rfl⟩ capZ
  3427. (Problem455SameDonor.sameDonor v h y hy capF a b ha hb)
  3428. cases d with
  3429. | deficient a =>
  3430. obtain ⟨⟨_,occ⟩,bad⟩ := obs
  3431. change z.count a < r at bad
  3432. rcases P455SlotOrigin.supplier_or_boundary v h l k x s a i r hr cap hx hs occ guard with
  3433. bnd | ⟨y,_,ay,hy,_⟩
  3434. · have := satZ a x hx bnd
  3435. omega
  3436. · have := satZ a y hy ay
  3437. omega
  3438. | overflow xs =>
  3439. change Holds r allow mark z (allQ _) at obs
  3440. have ob := (holds_all _).mp obs
  3441. have len : xs.length = 5 := ob (.fixed _) (by simp)
  3442. have sep := (block_separation (s::xs)).mp (ob _ (by simp))
  3443. obtain ⟨ownerSep,tailSep⟩ := List.pairwise_cons.mp sep
  3444. have rest : ∀ a ∈ xs, occupies z s i a := by
  3445. intro a ha
  3446. have htest : Holds r allow mark z
  3447. (allQ (xs.map fun a => .both (.count a r) (.slot s i a))) := ob _ (by simp)
  3448. have hin := (holds_all _).mp htest (.both (.count a r) (.slot s i a)) (List.mem_map.mpr ⟨a,ha,rfl⟩)
  3449. exact hin.2.2
  3450. classical
  3451. have supply (a : Nat) (ha : a ∈ xs) :
  3452. ∃ y, occupies v x i y ∧ a ∈ h y ∧ v.count y = r ∧ x ≠ y :=
  3453. P455SlotOrigin.supplier v h l k x s a i r hr cap hx hs
  3454. (fun shared => ownerSep a ha (common x s a hx hs shared)) (rest a ha) guard
  3455. let assign := fun a => if ha : a ∈ xs then (supply a ha).choose else x
  3456. have spec (a : Nat) (ha : a ∈ xs) :
  3457. occupies v x i (assign a) ∧ a ∈ h (assign a) ∧ v.count (assign a) = r ∧ x ≠ assign a := by
  3458. simpa [assign,ha] using (supply a ha).choose_spec
  3459. have nodup : (xs.map assign).Nodup := by
  3460. apply List.pairwise_map.mpr
  3461. apply tailSep.imp_of_mem
  3462. intro a b ha hb distinct e
  3463. have A := spec a ha
  3464. have B := spec b hb
  3465. exact distinct (common (assign a) a b A.2.2.1 A.2.1 (e ▸ B.2.1))
  3466. refine ⟨assign,len,List.nodup_cons.mpr ⟨?_,nodup⟩,?_⟩
  3467. · rintro member
  3468. obtain ⟨a,ha,e⟩ := List.mem_map.mp member
  3469. exact (spec a ha).2.2.2 e.symm
  3470. · intro a ha
  3471. have e := spec a ha
  3472. exact ⟨e.1,e.2.1,e.2.2.1⟩
  3473. end P455TerminalTransfer
  3474. end
  3475. /- Begin Problem455EffectiveQMove (from finite-semigroup-identity-bases). -/
  3476. section
  3477. namespace P455EffectiveQMove
  3478. open P455Closure P455EffectiveQ
  3479. abbrev W := List Nat
  3480. def capB (r : Nat) (u : W) := u.all fun a => decide (u.count a ≤ r)
  3481. theorem cap_iff (r : Nat) (u : W) : capB r u=true ↔ Cap r u := by
  3482. simp only [capB,List.all_eq_true,decide_eq_true_eq,Cap]
  3483. constructor
  3484. · intro h a; by_cases m : a∈u
  3485. · exact h a m
  3486. · simp [List.count_eq_zero_of_not_mem m]
  3487. · exact fun h a _ => h a
  3488. def validB (r : Nat) (tags : List (List Bool)) (marks : Nat → Nat → Bool) (f : Frame Nat) :=
  3489. decide (r = 16 + f.tag.length ∧ f.tag∈tags ∧ f.middle.map Prod.snd=fixedPhases f.tag ∧
  3490. f.p.Nodup ∧ f.q.Nodup ∧ (∀ a∈f.p, a∉f.q) ∧
  3491. (∀ a∈f.p, ∀ b∈f.q, marks a b=false ∧ marks b a=false) ∧
  3492. (∀ a∈f.p++f.q,(f.core false).count a=r))
  3493. theorem valid_iff {tags marks allow mark} (tag_ok : ∀ t, t∈tags ↔ allow t)
  3494. (mark_ok : ∀ a b,marks a b=true ↔ mark a b)
  3495. (r : Nat) (f : Frame Nat) : validB r tags marks f=true ↔ f.Valid r allow mark := by
  3496. have unmarked (a b) : marks a b=false ↔ ¬mark a b := by
  3497. rw [←mark_ok]; cases marks a b <;> decide
  3498. simp only [validB,decide_eq_true_eq,Frame.Valid,tag_ok,unmarked,List.mem_append]
  3499. def entries (u : W) := (words u).flatMap (fun g => [(g,false),(g,true)])
  3500. def frames (tags : List (List Bool)) (u : W) : List (Frame Nat) :=
  3501. tags.flatMap fun t => u.flatMap fun a => (words u).flatMap fun p =>
  3502. (words u).flatMap fun q => u.flatMap fun z =>
  3503. (Problem455Finite.wordsUpTo (entries u) (fixedPhases t).length).flatMap fun es =>
  3504. (words u).flatMap fun m => (words u).flatMap fun l =>
  3505. (words u).map fun n => ⟨a,p,q,z,t,es,m,l,n⟩
  3506. private theorem left {u a b : W} (h : u.Sublist a) : u.Sublist (a++b) :=
  3507. h.trans (List.sublist_append_left _ _)
  3508. private theorem right {u a b : W} (h : u.Sublist b) : u.Sublist (a++b) :=
  3509. h.trans (List.sublist_append_right _ _)
  3510. theorem frame_mem {tags allow r mark} (tag_ok : ∀ t,t∈tags ↔ allow t)
  3511. (f : Frame Nat) (b : Bool) (l t : W) (fv : f.Valid r allow mark) :
  3512. f ∈ frames tags (l++f.core b++t) := by
  3513. let u := l++f.core b++t
  3514. have core : (f.core b).Sublist u := left (right (List.Sublist.refl _))
  3515. have within (s : W) (hs : s.Sublist (f.core b)) : s.Sublist u := hs.trans core
  3516. have early : f.early.Sublist u := within _ (left (left (left (left (left (left (left (.refl _))))))))
  3517. have pp : f.p.Sublist u :=
  3518. (show f.p.Sublist f.early from left (left (left (left (left (.refl _)))))).trans early
  3519. have qq : f.q.Sublist u := (right (.refl _) : f.q.Sublist f.early).trans early
  3520. have a : f.pHead∈u := pp.subset (by simp [Frame.p])
  3521. have z : f.qLast∈u := qq.subset (by simp [Frame.q])
  3522. have pt : f.pTail∈words u := subword ((List.sublist_cons_self ..).trans pp)
  3523. have qi : f.qInit∈words u := subword ((List.sublist_append_left ..).trans qq)
  3524. have mid : f.mid.Sublist u := within _ (left (left (left (left (left (left (right (.refl _))))))))
  3525. have m : f.beforeMutable∈words u := subword (within _ (left (left (left (left (left (right (.refl _))))))))
  3526. have p : f.beforeFinalP∈words u := subword (within _ (left (left (left (right (.refl _))))))
  3527. have n : f.beforeFinalQ∈words u := subword (within _ (left (right (.refl _))))
  3528. have es : f.middle ∈ Problem455Finite.wordsUpTo (entries u) (fixedPhases f.tag).length := by
  3529. have sz := congrArg List.length fv.2.2.1
  3530. apply Problem455Finite.covered _ _ _ (by simpa using Nat.le_of_eq sz)
  3531. rintro ⟨g,v⟩ mem
  3532. have item : g.Sublist f.mid := by
  3533. let B := fun e : W×Bool => e.1 ++ (if e.2 then f.q else f.p)
  3534. have item : (B (g,v)).Sublist ((f.middle.map B).flatten) :=
  3535. List.sublist_flatten_of_mem (List.mem_map_of_mem mem)
  3536. exact (List.sublist_append_left g _).trans (by simpa [Frame.mid,List.flatMap_def,B] using item)
  3537. have gg := subword (item.trans mid)
  3538. apply List.mem_flatMap.mpr
  3539. exact ⟨g,gg,by cases v <;> simp⟩
  3540. change f ∈ frames tags u
  3541. simp only [frames,List.mem_flatMap,List.mem_map]
  3542. exact ⟨f.tag,(tag_ok _).mpr fv.2.1,f.pHead,a,f.pTail,pt,f.qInit,qi,f.qLast,z,f.middle,es,
  3543. f.beforeMutable,m,f.beforeFinalP,p,f.beforeFinalQ,n,rfl⟩
  3544. theorem min_length {r allow} {mark : Nat → Nat → Prop} {u v : W} (h : Move r allow mark u v) : r ≤ u.length := by
  3545. obtain ⟨f,b,l,t,valid,rfl,_,_⟩ := h
  3546. have sat := valid.2.2.2.2.2.2.2 f.pHead (.inl (by simp [Frame.p]))
  3547. have count : (f.core b).count f.pHead=r := by
  3548. cases b with
  3549. | false => exact sat
  3550. | true => exact (f.count_core f.pHead true).trans sat
  3551. have len := List.count_le_length (a := f.pHead) (l := f.core b)
  3552. simp only [List.length_append]
  3553. omega
  3554. def moveB (r : Nat) (tags : List (List Bool)) (marks : Nat → Nat → Bool) (u v : W) :=
  3555. decide (r ≤ u.length) && capB r u && (frames tags u).any fun f => validB r tags marks f && [false,true].any fun b =>
  3556. (words u).any fun l => (words u).any fun t =>
  3557. decide (u=l++f.core b++t ∧ v=l++f.core (!b)++t)
  3558. theorem move_iff {tags marks allow mark} (tag_ok : ∀ t,t∈tags ↔ allow t)
  3559. (mark_ok : ∀ a b,marks a b=true ↔ mark a b)
  3560. (r : Nat) (u v : W) : moveB r tags marks u v=true ↔ Move r allow mark u v := by
  3561. simp only [moveB,Bool.and_eq_true,List.any_eq_true,decide_eq_true_eq,
  3562. cap_iff,valid_iff tag_ok mark_ok]
  3563. constructor
  3564. · rintro ⟨⟨_,cap⟩,f,_,fv,b,_,l,_,t,_,src,dst⟩; exact ⟨f,b,l,t,fv,src,dst,cap⟩
  3565. · intro h
  3566. have len := min_length h
  3567. obtain ⟨f,b,l,t,fv,rfl,rfl,cp⟩ := h
  3568. exact ⟨⟨len,cp⟩,f,frame_mem tag_ok f b l t fv,fv,b,by cases b <;> simp,l,
  3569. subword (left (left (.refl _))),t,subword (right (.refl _)),rfl,rfl⟩
  3570. def markedEq {tags : List (List Bool)} {marks : Nat → Nat → Bool}
  3571. {allow : List Bool → Prop} {mark : Nat → Nat → Prop} (tag_ok : ∀ t,t∈tags ↔ allow t)
  3572. (mark_ok : ∀ a b,marks a b=true ↔ mark a b) (r : Nat) (T : W) :
  3573. DecidableEq (P455Quotient.Q (Problem455Finite.rules r allow mark) T) :=
  3574. P455EffectiveQ.decEq _ (moveB r tags marks) (move_iff tag_ok mark_ok r) T
  3575. end P455EffectiveQMove
  3576. end
  3577. /- Begin Problem455RealizerGraph (from finite-semigroup-identity-bases). -/
  3578. section
  3579. namespace P455RealizerGraph
  3580. open P455EffectiveQ
  3581. variable {α : Type} [DecidableEq α]
  3582. def joinAt (k : α) (m : List (α × α)) := m ++ m.flatMap fun p =>
  3583. if p.2=k then m.filterMap (fun q => if q.1=k then some (p.1,q.2) else none) else []
  3584. theorem mem_joinAt (k a b : α) (m : List (α × α)) :
  3585. (a,b)∈joinAt k m ↔ (a,b)∈m ∨ ((a,k)∈m ∧ (k,b)∈m) := by
  3586. simp only [joinAt,List.mem_append,List.mem_flatMap]
  3587. apply or_congr_right
  3588. constructor
  3589. · rintro ⟨⟨x,y⟩,px,h⟩
  3590. by_cases eq : y=k
  3591. · subst y
  3592. rw [if_pos rfl] at h
  3593. obtain ⟨⟨z,w⟩,qz,h⟩ := List.mem_filterMap.mp h
  3594. dsimp only at h
  3595. split at h
  3596. · rename_i hzk
  3597. obtain ⟨hxa,hwb⟩ := Prod.mk.inj (Option.some.inj h)
  3598. subst z; subst x; subst w
  3599. exact ⟨px,qz⟩
  3600. · contradiction
  3601. · simp [eq] at h
  3602. · rintro ⟨p,q⟩
  3603. refine ⟨(a,k),p,?_⟩
  3604. simp [List.mem_filterMap]
  3605. exact q
  3606. def initial (domain : List α) (edge : α → α → Bool) := domain.flatMap fun a =>
  3607. (domain.filter fun b => decide (a=b) || edge a b).map fun b => (a,b)
  3608. theorem mem_initial {domain : List α} (edge : α → α → Bool) {a b : α} (ha : a∈domain) (hb : b∈domain) :
  3609. (a,b)∈initial domain edge ↔ a=b ∨ edge a b=true := by
  3610. simp only [initial,List.mem_flatMap,List.mem_map,List.mem_filter,Bool.or_eq_true,decide_eq_true_eq,
  3611. Prod.mk.injEq]
  3612. constructor
  3613. · rintro ⟨x,_,y,⟨_,e⟩,rfl,rfl⟩; exact e
  3614. · intro h; exact ⟨a,ha,b,⟨hb,h⟩,rfl,rfl⟩
  3615. theorem mem_fold {domain : List α} (e : α → α → Bool) (pivots : List α)
  3616. (hp : ∀ x∈pivots,x∈domain) {a b : α} (ha : a∈domain) (hb : b∈domain) :
  3617. (a,b)∈pivots.foldr joinAt (initial domain e) ↔ P455EffectiveQReach.via e pivots a b=true := by
  3618. induction pivots generalizing a b with
  3619. | nil => simpa [P455EffectiveQReach.via] using mem_initial e ha hb
  3620. | cons k ks ih =>
  3621. have mem := hp k List.mem_cons_self
  3622. have rest : ∀ x∈ks,x∈domain := fun x h => hp x (List.mem_cons_of_mem _ h)
  3623. simp only [List.foldr_cons,mem_joinAt,P455EffectiveQReach.via,Bool.or_eq_true,Bool.and_eq_true,
  3624. ih rest ha hb,ih rest ha mem,ih rest mem hb]
  3625. def walk (e : W → W → Bool) (u v : W) :=
  3626. let pivots := words u
  3627. decide ((u,v)∈pivots.foldr joinAt (initial (u::v::pivots) e))
  3628. theorem walk_eq (e : W → W → Bool) (u v : W) : walk e u v=walkB e u v := by
  3629. apply Bool.eq_iff_iff.mpr
  3630. simp only [walk,decide_eq_true_eq,walkB]
  3631. exact mem_fold e _ (fun x h => by simp [h]) (by simp) (by simp)
  3632. end P455RealizerGraph
  3633. end
  3634. /- Begin Problem455PaddedReadback (from finite-semigroup-identity-bases). -/
  3635. section
  3636. namespace P455PaddedTiles
  3637. open P455Witness
  3638. variable {n w h : Nat} {M : MachineTable n}
  3639. private theorem clip {v : Nat} (hv : 0<v) (k : Nat) : min k (v-1)<v := by
  3640. have := Nat.min_le_right k (v-1)
  3641. omega
  3642. noncomputable def readTile (R : Rectangle M w h) (y x : Nat) : Tile n :=
  3643. (R.eligible (min y (h-1)) (clip R.positiveH _) (min x (w-1)) (clip R.positiveW _)).choose
  3644. theorem read_tile_data (R : Rectangle M w h) (y x : Nat) (hy : y<h) (hx : x<w) :
  3645. code (readTile R y x)=R.tag y x ∧ Admitted M (readTile R y x) := by
  3646. have d := (R.eligible (min y (h-1)) (clip R.positiveH _) (min x (w-1)) (clip R.positiveW _)).choose_spec
  3647. refine ⟨?_,d.2⟩
  3648. change code (readTile R y x) = R.tag (min y (h-1)) (min x (w-1)) ∧ _ at d
  3649. simpa only [Nat.min_eq_left (by omega : y≤h-1),Nat.min_eq_left (by omega : x≤w-1)] using d.1
  3650. private theorem read_flags (R : Rectangle M w h) (y x : Nat) (hy : y<h) (hx : x<w) :
  3651. (readTile R y x).left=decide (x=0) ∧ (readTile R y x).right=decide (x+1=w) ∧
  3652. (readTile R y x).top=decide (y=0) ∧ (readTile R y x).bottom=decide (y+1=h) := by
  3653. have f := R.flags y hy x hx
  3654. rw [← (read_tile_data R y x hy hx).1] at f
  3655. exact ⟨f.1,f.2.1,f.2.2.1,f.2.2.2.1⟩
  3656. theorem read_horizontal (R : Rectangle M w h) (y x : Nat) (hy : y<h) (hx : x+1<w) :
  3657. Horizontal (readTile R y x) (readTile R y (x+1)) := by
  3658. obtain ⟨a,b,pa,pb,H⟩ := R.right y hy x hx
  3659. have ea := code_inj (pa.trans (read_tile_data R y x hy (by omega)).1.symm)
  3660. have eb := code_inj (pb.trans (read_tile_data R y (x+1) hy hx).1.symm)
  3661. simpa only [ea,eb] using H
  3662. theorem read_vertical (R : Rectangle M w h) (y x : Nat) (hy : y+1<h) (hx : x<w) :
  3663. Vertical (readTile R y x) (readTile R (y+1) x) := by
  3664. obtain ⟨a,b,pa,pb,V⟩ := R.down y hy x hx
  3665. have ea := code_inj (pa.trans (read_tile_data R y x (by omega) hx).1.symm)
  3666. have eb := code_inj (pb.trans (read_tile_data R (y+1) x hy hx).1.symm)
  3667. simpa only [ea,eb] using V
  3668. noncomputable def centers (R : Rectangle M w h) (y x : Nat) := (readTile R y x).c
  3669. theorem read_triple (R : Rectangle M w h) (y x : Nat) (hy : y<h) (hx : x<w) :
  3670. (readTile R y x).l=leftAt (centers R y) x ∧
  3671. (readTile R y x).r=rightAt (centers R y) w x := by
  3672. have d := (read_tile_data R y x hy hx).2
  3673. have f := read_flags R y x hy hx
  3674. constructor
  3675. · by_cases e : x=0
  3676. · have b := d.2.1.symm.trans f.1
  3677. simp [e] at b
  3678. simpa [leftAt,e] using b
  3679. · have p := (read_horizontal R y (x-1) hy (by omega)).2.2.2.2.2.2.1
  3680. simpa [leftAt,e,centers,show x-1+1=x by omega] using p
  3681. · by_cases e : x+1=w
  3682. · have b := d.2.2.1.symm.trans f.2.1
  3683. simp [e] at b
  3684. simpa [rightAt,e] using b
  3685. · have p := (read_horizontal R y x hy (by omega)).2.2.2.2.2.2.2
  3686. simpa [rightAt,e,centers] using p
  3687. /-- A trace on w cells, ending with the accepting center at its leftmost
  3688. cell. Stuttering beyond the last row uses the specific machine table. -/
  3689. structure AcceptingTrace (M : MachineTable n) (w s : Nat) where
  3690. positive : 0<w
  3691. rows : Nat → Nat → Fin n
  3692. start : ∀ x, x<w → rows 0 x = M.initial (decide (x=0))
  3693. marks : ∀ y, y≤s → ∀ x, x<w → M.marker (rows y x)=decide (x=0)
  3694. steps : ∀ y, y<s → ∀ x, x<w →
  3695. M.next (leftAt (rows y) x) (rows y x) (rightAt (rows y) w x)=some (rows (y+1) x)
  3696. accept : rows s 0=M.accept
  3697. noncomputable def read_trace (R : Rectangle M w h) : AcceptingTrace M w (h-1) where
  3698. positive := R.positiveW
  3699. rows := centers R
  3700. start := by
  3701. intro x hx
  3702. have d := (read_tile_data R 0 x R.positiveH hx).2
  3703. have f := read_flags R 0 x R.positiveH hx
  3704. exact ((d.2.2.2.2.2.1 (by simpa using f.2.2.1)).2).trans (congrArg M.initial f.1)
  3705. marks := by
  3706. intro y hy x hx
  3707. have lt : y<h := by have := R.positiveH; omega
  3708. exact (read_tile_data R y x lt hx).2.2.2.2.1.trans (read_flags R y x lt hx).1
  3709. steps := by
  3710. intro y hy x hx
  3711. have lt : y<h := by omega
  3712. have upd := (read_tile_data R y x lt hx).2.1
  3713. have triple := read_triple R y x lt hx
  3714. rw [triple.1,triple.2] at upd
  3715. exact upd.trans (congrArg some (read_vertical R y x (by omega) hx).2.2.2.2.2.2)
  3716. accept := by
  3717. have hy : h-1<h := by have := R.positiveH; omega
  3718. have e : h-1+1=h := by have := R.positiveH; omega
  3719. have f := read_flags R (h-1) 0 hy R.positiveW
  3720. exact (read_tile_data R (h-1) 0 hy R.positiveW).2.2.2.2.2.2.2
  3721. (by simpa [e] using f.2.2.2) (by simpa using f.1)
  3722. theorem trace_iff_rectangles
  3723. (stationary : ∀ {w s}, (T : AcceptingTrace M w s) → ∀ x, x<w →
  3724. M.next (leftAt (T.rows s) x) (T.rows s x) (rightAt (T.rows s) w x)=some (T.rows s x)) :
  3725. (∃ w s, Nonempty (AcceptingTrace M w s)) ↔
  3726. (∃ w, ∀ k, ∃ h, 1<h ∧ k<2*(w*h) ∧ Nonempty (Rectangle M w h)) := by
  3727. constructor
  3728. · rintro ⟨w,s,⟨t⟩⟩
  3729. let r : Run M w s := ⟨t.positive,t.rows,t.start,t.marks,t.steps,t.accept,stationary t⟩
  3730. exact ⟨w,unbounded r⟩
  3731. · rintro ⟨w,rects⟩
  3732. obtain ⟨h,_,_,⟨r⟩⟩ := rects 0
  3733. exact ⟨w,h-1,⟨read_trace r⟩⟩
  3734. end P455PaddedTiles
  3735. end
  3736. /- Begin Problem455CertificateReach (from finite-semigroup-identity-bases). -/
  3737. section
  3738. namespace P455CertificateReach
  3739. open P455Witness P455Paths
  3740. inductive Active (ts : Tiles) (e : EdgeCertificate) : Node → Prop
  3741. | anchor : Active ts e e.a
  3742. | successor : Active ts e e.b
  3743. | right : ts.right e.a.tag = false → Active ts e e.right
  3744. | left : ts.left e.a.tag = false → Active ts e e.left
  3745. | down : ts.bottom e.a.tag = false → Active ts e e.down
  3746. | up : ts.top e.a.tag = false → Active ts e e.up
  3747. | diagonal : ts.right e.a.tag = false → ts.bottom e.a.tag = false → Active ts e e.diagonal
  3748. private theorem role_near {r allow mark w n label} (recProof : V r allow mark w (typedNode n))
  3749. (role : label = n.owner ∨ label = n.mate) : Near r allow mark w n.owner label 1 := by
  3750. rcases role with h|h
  3751. · simpa [h] using (near_self (r := r) (allow := allow) (mark := mark) (w := w) n.owner 1)
  3752. · exact h ▸ (record_pair recProof).1
  3753. theorem functionality_reach {r allow mark w} (cap : P455Closure.Cap r w)
  3754. (ts : Tiles) (f : FunctionalityCertificate) (ok : V r allow mark w (f.query ts))
  3755. {n : Node} {label : Nat} (node : n = f.anchor ∨ n = f.b ∨ n = f.c)
  3756. (role : label = n.owner ∨ label = n.mate) : Near r allow mark w f.anchor.owner label 2 := by
  3757. rcases node with h|h|h <;> subst n
  3758. · exact near_mono (role_near (marked_typed ok.1) role) (by decide)
  3759. · have port := ok.2.1
  3760. exact near_trans (neighbor_paths cap f.dir port).1 (role_near (neighbor_target_record port) role)
  3761. · have port := ok.2.2.1
  3762. exact near_trans (neighbor_paths cap f.dir port).1 (role_near (neighbor_target_record port) role)
  3763. private theorem on_guard {r allow mark w b q} (hb : b = false)
  3764. (h : V r allow mark w (flagQ (!b) q)) : V r allow mark w q := by
  3765. simpa [flagQ,hb] using h
  3766. private theorem local_right {r allow mark w ts e} (h : V r allow mark w (localCert ts e))
  3767. (b : ts.right e.a.tag = false) : V r allow mark w (rightward ts e.a e.right) :=
  3768. on_guard b h.1
  3769. private theorem local_left {r allow mark w ts e} (h : V r allow mark w (localCert ts e))
  3770. (b : ts.left e.a.tag = false) : V r allow mark w (rightward ts e.left e.a) :=
  3771. on_guard b h.2.1
  3772. private theorem local_down {r allow mark w ts e} (h : V r allow mark w (localCert ts e))
  3773. (b : ts.bottom e.a.tag = false) : V r allow mark w (downward ts e.a e.down) :=
  3774. on_guard b h.2.2.1
  3775. private theorem local_up {r allow mark w ts e} (h : V r allow mark w (localCert ts e))
  3776. (b : ts.top e.a.tag = false) : V r allow mark w (downward ts e.up e.a) :=
  3777. on_guard b h.2.2.2.1
  3778. private theorem local_square {r allow mark w ts e} (h : V r allow mark w (localCert ts e))
  3779. (b : ts.right e.a.tag = false) (d : ts.bottom e.a.tag = false) :
  3780. V r allow mark w (downward ts e.right e.diagonal) ∧
  3781. V r allow mark w (rightward ts e.down e.diagonal) := by
  3782. have sq := h.2.2.2.2.1
  3783. simpa [flagQ,b,d,V,Holds] using sq
  3784. /-- Either the selected local neighbor is the second endpoint, or the
  3785. certificate contains an actual return port in one of its two orientations. -/
  3786. theorem successor_joined {r allow mark w} {ts : Tiles} {e : EdgeCertificate} (cap : P455Closure.Cap r w)
  3787. (ok : V r allow mark w (e.query ts)) : Joined r allow mark w e.a e.b := by
  3788. have lc := ok.2.2.1
  3789. have succ := ok.2.2.2.1
  3790. unfold chosenSuccessor at succ
  3791. dsimp only at succ
  3792. split at succ
  3793. next ret =>
  3794. rcases succ.2.1 with f|b
  3795. · exact port_joined cap 4 (by decide) f
  3796. · exact (port_joined cap 4 (by decide) b).symm
  3797. next noReturn =>
  3798. have eq := succ.1
  3799. cases row : endOfRow ts e.a with
  3800. | true =>
  3801. have bottom : ts.bottom e.a.tag = false := by simpa [row] using noReturn
  3802. have target : e.down = e.b := by simpa [row,P455Witness.Holds] using eq
  3803. exact target ▸ down_paths cap (local_down lc bottom)
  3804. | false =>
  3805. cases odd : ts.oddRow e.a.tag with
  3806. | true =>
  3807. have left : ts.left e.a.tag = false := by simpa [endOfRow,odd] using row
  3808. have target : e.left = e.b := by simpa [row,odd,P455Witness.Holds] using eq
  3809. exact target ▸ (right_paths cap (local_left lc left)).symm
  3810. | false =>
  3811. have right : ts.right e.a.tag = false := by simpa [endOfRow,odd] using row
  3812. have target : e.right = e.b := by simpa [row,odd,P455Witness.Holds] using eq
  3813. exact target ▸ right_paths cap (local_right lc right)
  3814. theorem active_owner {r allow mark w} (cap : P455Closure.Cap r w)
  3815. (ts : Tiles) (e : EdgeCertificate) (ok : V r allow mark w (e.query ts))
  3816. {n : Node} (active : Active ts e n) :
  3817. Near r allow mark w e.a.owner n.owner 2 ∧ V r allow mark w (typedNode n) := by
  3818. have lc := ok.2.2.1
  3819. cases active with
  3820. | anchor => exact ⟨near_self _ _,marked_typed ok.1⟩
  3821. | successor => exact ⟨near_mono (successor_joined cap ok).1 (by decide),marked_typed ok.2.1⟩
  3822. | right b =>
  3823. have p := local_right lc b
  3824. exact ⟨near_mono (right_paths cap p).1 (by decide),neighbor_target_record (d := .right) p⟩
  3825. | left b =>
  3826. have p := local_left lc b
  3827. exact ⟨near_mono (right_paths cap p).2 (by decide),neighbor_target_record (d := .left) p⟩
  3828. | down b =>
  3829. have p := local_down lc b
  3830. exact ⟨near_mono (down_paths cap p).1 (by decide),neighbor_target_record (d := .down) p⟩
  3831. | up b =>
  3832. have p := local_up lc b
  3833. exact ⟨near_mono (down_paths cap p).2 (by decide),neighbor_target_record (d := .up) p⟩
  3834. | diagonal rr dd =>
  3835. have p := local_right lc rr
  3836. have q := (local_square lc rr dd).1
  3837. exact ⟨near_trans (right_paths cap p).1 (down_paths cap q).1,neighbor_target_record (d := .down) q⟩
  3838. /-- For either endpoint owner, every role genuinely used in the specified
  3839. edge certificate is within four actual record/port contacts. -/
  3840. theorem edge_reach {r allow mark w} (cap : P455Closure.Cap r w)
  3841. (ts : Tiles) (e : EdgeCertificate) (ok : V r allow mark w (e.query ts))
  3842. {n : Node} {label : Nat} (active : Active ts e n) (role : label = n.owner ∨ label = n.mate) :
  3843. Near r allow mark w e.a.owner label 4 ∧ Near r allow mark w e.b.owner label 4 := by
  3844. obtain ⟨reach,recProof⟩ := active_owner cap ts e ok active
  3845. have first := near_trans reach (role_near recProof role)
  3846. exact ⟨near_mono first (by decide),near_trans (successor_joined cap ok).2 first⟩
  3847. end P455CertificateReach
  3848. end
  3849. /- Begin Problem455ContactLift (from finite-semigroup-identity-bases). -/
  3850. section
  3851. namespace P455ContactLift
  3852. open Problem455.Slots P455Witness P455Paths
  3853. def Supplies (v : W) (h : Nat → W) (r x s : Nat) := v.count x = r ∧ s ∈ h x
  3854. noncomputable def donor (v : W) (h : Nat → W) (r s : Nat) : Nat := by
  3855. classical
  3856. exact if hs : ∃ x, Supplies v h r x s then hs.choose else 0
  3857. theorem factor_cap {v l k : W} {h : Nat → W} {r : Nat}
  3858. (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k)) : P455Closure.Cap r (v.flatMap h) := by
  3859. intro s; have hs := cap s; simp only [List.count_append] at hs; omega
  3860. theorem donor_eq {v h r x s} (hr : 0 < r) (cap : P455Closure.Cap r (v.flatMap h))
  3861. (supply : Supplies v h r x s) : donor v h r s = x := by
  3862. classical
  3863. have existsDonor : ∃ y, Supplies v h r y s := ⟨x,supply⟩
  3864. have other := existsDonor.choose_spec
  3865. have used : existsDonor.choose ∈ v := List.count_pos_iff.mp (other.1.symm ▸ hr)
  3866. have exc := (P455DonorInterval.exclusive h v x s r hr supply.1 supply.2 (cap s)).2.1
  3867. unfold donor; rw [dif_pos existsDonor]
  3868. exact Classical.byContradiction (fun ne => exc _ used ne other.2)
  3869. def Guard (r : Nat) (allow : Tag → Prop) (mark : Marking) (v : W) (seed J : Nat) : Prop :=
  3870. ∀ x, Near r allow mark v seed x J → ∀ i, slotStart i →
  3871. ∀ y, occupies v x i y → v.count y = r
  3872. theorem guard_uniform {r allow mark v seed J} (uniform : ∀ x ∈ v, v.count x = r) :
  3873. Guard r allow mark v seed J := by
  3874. intro _ _ _ _ y hy
  3875. obtain ⟨j,sub⟩ := hy
  3876. have hm : (y,j) ∈ events v := sub.subset (by simp)
  3877. exact uniform y (stamped_mem_label _ _ _ hm)
  3878. theorem contact_step {r allow mark v h l k x s t} (hr : 0 < r)
  3879. (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k)) (sup : Supplies v h r x s)
  3880. (guard : ∀ i, slotStart i → ∀ y, occupies v x i y → v.count y = r)
  3881. (c : ContactChoice) (hc : Holds r allow mark (l ++ v.flatMap h ++ k) (contact r s t c)) :
  3882. let y := donor v h r t
  3883. Supplies v h r y t ∧ x ≠ y ∧ Holds r allow mark v (contact r x y c) := by
  3884. obtain ⟨i,slot,occ⟩ := P455ContactGeometry.contact_slot hc
  3885. have ext := P455ContactGeometry.contact_excludes_image hr cap sup.1 sup.2 hc
  3886. obtain ⟨y,_,ht,hy,ne⟩ := P455SlotOrigin.supplier v h l k x s t i r hr cap sup.1 sup.2 ext occ (guard i slot)
  3887. have g : Supplies v h r y t := ⟨hy,ht⟩
  3888. have refl := P455ContactReflection.reflect_contact hr cap sup.1 hy ne sup.2 ht c hc
  3889. simpa only [donor_eq hr (factor_cap cap) g] using And.intro g (And.intro ne refl)
  3890. def relabel (d : Nat → Nat) (p : List Step) := p.map fun bc => (d bc.1,bc.2)
  3891. theorem endpoint_relabel (d : Nat → Nat) (s : Nat) (p : List Step) :
  3892. endpoint (d s) (relabel d p) = d (endpoint s p) := by
  3893. induction p generalizing s with
  3894. | nil => rfl
  3895. | cons head p ih => exact ih head.1
  3896. /-- Each step comes from the concrete record/port test in the enclosing word.
  3897. Induction keeps the length of the source prefix to which the guard applies. -/
  3898. theorem transfer_from {r allow mark v h l k seed J} (hr : 0 < r)
  3899. (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k)) (guard : Guard r allow mark v seed J)
  3900. (s : Nat) (p : List Step) (n : Nat) (sup : Supplies v h r (donor v h r s) s)
  3901. (near : Near r allow mark v seed (donor v h r s) n) (bound : n+p.length ≤ J)
  3902. (walk : Walk r allow mark (l ++ v.flatMap h ++ k) s p) :
  3903. Walk r allow mark v (donor v h r s) (relabel (donor v h r) p) ∧
  3904. Supplies v h r (donor v h r (endpoint s p)) (endpoint s p) := by
  3905. induction p generalizing n s with
  3906. | nil => exact ⟨True.intro,sup⟩
  3907. | cons bc rest ih =>
  3908. obtain ⟨b,c⟩ := bc
  3909. have len : n+1+rest.length ≤ J := by simpa [Nat.add_assoc,Nat.add_comm 1 rest.length] using bound
  3910. have g := guard _ (near_mono near (by omega))
  3911. obtain ⟨next,_,edge⟩ := contact_step hr cap sup g c walk.1
  3912. have more := near_trans near (near_one c edge)
  3913. obtain ⟨tail,last⟩ := ih b (n+1) next more len walk.2
  3914. exact ⟨⟨edge,tail⟩,last⟩
  3915. theorem lift_walk {r allow mark v h l k s seed J} (hr : 0 < r)
  3916. (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k)) (start : Supplies v h r seed s)
  3917. (guard : Guard r allow mark v seed J) (p : List Step) (bound : p.length ≤ J)
  3918. (walk : Walk r allow mark (l ++ v.flatMap h ++ k) s p) :
  3919. Walk r allow mark v seed (relabel (donor v h r) p) ∧
  3920. Supplies v h r (donor v h r (endpoint s p)) (endpoint s p) := by
  3921. have eq := donor_eq hr (factor_cap cap) start
  3922. simpa only [eq] using transfer_from hr cap guard s p 0 (eq.symm ▸ start)
  3923. (eq.symm ▸ near_self seed 0) (by simpa using bound) walk
  3924. theorem lift_near {r allow mark v h l k s seed J a n} (hr : 0 < r)
  3925. (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k)) (start : Supplies v h r seed s)
  3926. (guard : Guard r allow mark v seed J) (bound : n ≤ J)
  3927. (near : Near r allow mark (l ++ v.flatMap h ++ k) s a n) :
  3928. Supplies v h r (donor v h r a) a ∧ Near r allow mark v seed (donor v h r a) n := by
  3929. obtain ⟨p,w,ep,len⟩ := near
  3930. obtain ⟨sw,sup⟩ := lift_walk hr cap start guard p (Nat.le_trans len bound) w
  3931. rw [ep] at sup
  3932. refine ⟨sup,relabel (donor v h r) p,sw,?_,by simpa [relabel] using len⟩
  3933. have eq := donor_eq hr (factor_cap cap) start
  3934. rw [← eq,endpoint_relabel,ep]
  3935. end P455ContactLift
  3936. end
  3937. /- Begin Problem455PortReflection (from finite-semigroup-identity-bases). -/
  3938. section
  3939. namespace P455PortReflection
  3940. open Problem455.Slots P455Witness P455ContactReflection P455ContactGeometry
  3941. def roles (a : Node) : W := [a.owner,a.mate]
  3942. def sendNode (d : Nat → Nat) (a : Node) : Node := ⟨d a.owner,d a.mate,a.tag⟩
  3943. def UniformOn (r : Nat) (v : W) (h : Nat → W) (d : Nat → Nat) (xs : W) :=
  3944. ∀ a ∈ xs, v.count (d a) = r ∧ a ∈ h (d a)
  3945. theorem holds_all {r allow mark w} (xs : List Query) :
  3946. Holds r allow mark w (allQ xs) ↔ ∀ q ∈ xs, Holds r allow mark w q := by
  3947. induction xs with
  3948. | nil => simp [allQ,Holds]
  3949. | cons q qs ih => simp only [allQ,Holds,ih,List.forall_mem_cons]
  3950. theorem earlyBefore_iff {r allow mark w} (xs ys : W) :
  3951. Holds r allow mark w (earlyBefore xs ys) ↔
  3952. ∀ a ∈ xs, ∀ b ∈ ys, Holds r allow mark w (earlier a 2 b 0) := by
  3953. simp only [earlyBefore,holds_all,List.mem_flatMap,List.mem_map]
  3954. constructor
  3955. · intro h a ha b hb
  3956. exact h _ ⟨a,ha,b,hb,rfl⟩
  3957. · rintro h _ ⟨a,ha,b,hb,rfl⟩
  3958. exact h a ha b hb
  3959. section Uniform
  3960. variable {r : Nat} {v l k : W} {h : Nat → W} {d : Nat → Nat}
  3961. {allow : Tag → Prop} {mark : Marking}
  3962. theorem record_roles_distinct (hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k))
  3963. (a : Node) (uniform : UniformOn r v h d (roles a))
  3964. (recProof : Holds r allow mark (l ++ v.flatMap h ++ k) (typedNode a)) :
  3965. d a.owner ≠ d a.mate := by
  3966. intro eq
  3967. obtain ⟨hx,hs⟩ := uniform a.owner (by simp [roles])
  3968. obtain ⟨_,ht⟩ := uniform a.mate (by simp [roles])
  3969. have nc := contact_excludes_image hr cap hx hs
  3970. (c := .record a.tag false) (b := a.mate) recProof
  3971. exact nc (eq ▸ ht)
  3972. theorem reflect_typedNode (hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k))
  3973. (a : Node) (uniform : UniformOn r v h d (roles a))
  3974. (recProof : Holds r allow mark (l ++ v.flatMap h ++ k) (typedNode a)) :
  3975. Holds r allow mark v (typedNode (sendNode d a)) := by
  3976. obtain ⟨hx,hs⟩ := uniform a.owner (by simp [roles])
  3977. obtain ⟨hy,ht⟩ := uniform a.mate (by simp [roles])
  3978. exact reflect_contact hr cap hx hy (record_roles_distinct hr cap a uniform recProof)
  3979. hs ht (.record a.tag false) recProof
  3980. theorem reflect_markedNode (hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k))
  3981. (a : Node) (bit : Bool) (uniform : UniformOn r v h d (roles a)) (sourceMark : Marking)
  3982. (marked : sourceMark (d a.owner) (d a.mate) ∨ sourceMark (d a.mate) (d a.owner))
  3983. (recProof : Holds r allow mark (l ++ v.flatMap h ++ k) (markedNode a bit)) :
  3984. Holds r allow sourceMark v (markedNode (sendNode d a) bit) := by
  3985. obtain ⟨ne,len,code,_,eq⟩ := recProof
  3986. have rec' : Holds r allow mark (l ++ v.flatMap h ++ k) (typedNode a) :=
  3987. ⟨ne,len,code,bit,eq⟩
  3988. obtain ⟨hx,hs⟩ := uniform a.owner (by simp [roles])
  3989. obtain ⟨hy,ht⟩ := uniform a.mate (by simp [roles])
  3990. have diff := record_roles_distinct hr cap a uniform rec'
  3991. exact ⟨diff,len,code,marked,reflect_profile hr cap hx hy diff hs ht a.tag bit eq⟩
  3992. theorem port_injective (hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k))
  3993. (a b : Node) (phase : Nat) (uniform : UniformOn r v h d (roles a ++ roles b))
  3994. (port : Holds r allow mark (l ++ v.flatMap h ++ k) (orientedPort phase a b)) :
  3995. ∀ s ∈ roles a ++ roles b, ∀ t ∈ roles a ++ roles b, d s = d t → s = t := by
  3996. have each (n : Node) (uni : UniformOn r v h d (roles n))
  3997. (recProof : Holds r allow mark (l ++ v.flatMap h ++ k) (typedNode n)) :
  3998. ∀ z ∈ roles n, ∀ t ∈ roles n, d z = d t → z = t := by
  3999. have distinct := record_roles_distinct hr cap n uni recProof
  4000. intro z hz t ht eq
  4001. simp [roles] at hz ht
  4002. rcases hz with rfl | rfl <;> rcases ht with rfl | rfl <;> simp_all
  4003. have ua : UniformOn r v h d (roles a) := fun x hx => uniform x (by simp [hx])
  4004. have ub : UniformOn r v h d (roles b) := fun x hx => uniform x (by simp [hx])
  4005. have cross (s) (hs : s ∈ roles a) (t) (ht : t ∈ roles b) : d s ≠ d t := by
  4006. intro eq
  4007. obtain ⟨hx,sa⟩ := ua s hs
  4008. obtain ⟨_,tb⟩ := ub t ht
  4009. rw [← eq] at tb
  4010. have early : Holds r allow mark (l ++ v.flatMap h ++ k) (earlyDisjoint (roles a) (roles b)) :=
  4011. port.2.2.1
  4012. rcases early with e | e
  4013. · exact same_image_no_early hr cap hx sa tb (by decide : 0 < 2)
  4014. (((earlyBefore_iff _ _).mp e s hs t ht).2)
  4015. · exact same_image_no_early hr cap hx tb sa (by decide : 0 < 2)
  4016. (((earlyBefore_iff _ _).mp e t ht s hs).2)
  4017. intro s hs t ht eq
  4018. rcases List.mem_append.mp hs with hs | hs <;> rcases List.mem_append.mp ht with ht | ht
  4019. · exact each a ua port.1 s hs t ht eq
  4020. · exact (cross s hs t ht eq).elim
  4021. · exact (cross t ht s hs eq.symm).elim
  4022. · exact each b ub port.2.1 s hs t ht eq
  4023. theorem port_owner_order (hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k))
  4024. (a b : Node) (phase : Nat) (uniform : UniformOn r v h d (roles a ++ roles b))
  4025. (port : Holds r allow mark (l ++ v.flatMap h ++ k) (orientedPort phase a b))
  4026. (pat : List Event) (inside : ∀ e ∈ pat, e.1 ∈ roles a ++ roles b)
  4027. (order : Holds r allow mark (l ++ v.flatMap h ++ k) (.order pat)) :
  4028. Holds r allow mark v (.order (pat.map (eventMap d))) :=
  4029. reflect_order_query hr cap _ d uniform (port_injective hr cap a b phase uniform port)
  4030. pat inside order
  4031. theorem reflect_port (hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k))
  4032. (a b : Node) (phase : Nat) (uniform : UniformOn r v h d (roles a ++ roles b))
  4033. (port : Holds r allow mark (l ++ v.flatMap h ++ k) (orientedPort phase a b)) :
  4034. Holds r allow mark v (orientedPort phase (sendNode d a) (sendNode d b)) := by
  4035. have ua : UniformOn r v h d (roles a) := fun x hx => uniform x (by simp [hx])
  4036. have ub : UniformOn r v h d (roles b) := fun x hx => uniform x (by simp [hx])
  4037. have transfer := port_owner_order hr cap a b phase uniform port
  4038. have early (xs ys : W) (within : ∀ z ∈ xs ++ ys, z ∈ roles a ++ roles b)
  4039. (order : Holds r allow mark (l ++ v.flatMap h ++ k) (earlyBefore xs ys)) :
  4040. Holds r allow mark v (earlyBefore (xs.map d) (ys.map d)) := by
  4041. apply (earlyBefore_iff _ _).mpr
  4042. intro u hu v' hv
  4043. obtain ⟨i,hi,rfl⟩ := List.mem_map.mp hu
  4044. obtain ⟨j,hj,rfl⟩ := List.mem_map.mp hv
  4045. have pat := transfer [(i,2),(j,0)] (by
  4046. intro e he
  4047. simp only [List.mem_cons,List.not_mem_nil,or_false] at he
  4048. rcases he with rfl | rfl
  4049. · exact within i (by simp [hi])
  4050. · exact within j (by simp [hj]))
  4051. ((earlyBefore_iff _ _).mp order i hi j hj)
  4052. simpa [eventMap,earlier] using pat
  4053. refine ⟨reflect_typedNode hr cap a ua port.1,reflect_typedNode hr cap b ub port.2.1,?_,?_,True.intro⟩
  4054. · rcases port.2.2.1 with e | e
  4055. · exact Or.inl (early (roles a) (roles b) (fun _ hz => hz) e)
  4056. · exact Or.inr (early (roles b) (roles a) (fun z hz => by simpa [or_comm] using hz) e)
  4057. · let i := 3+2*phase
  4058. have pat := transfer [(a.owner,i),(a.mate,i),(b.owner,i),(b.mate,i),
  4059. (a.owner,i+1),(a.mate,i+1),(b.owner,i+1),(b.mate,i+1)] (by simp [roles]) port.2.2.2.1
  4060. simpa [eventMap, sendNode, i] using pat
  4061. theorem reflect_rightward (hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k))
  4062. (ts : Tiles) (a b : Node) (uniform : UniformOn r v h d (roles a ++ roles b))
  4063. (dir : Holds r allow mark (l ++ v.flatMap h ++ k) (rightward ts a b)) :
  4064. Holds r allow mark v (rightward ts (sendNode d a) (sendNode d b)) := by
  4065. have order := port_owner_order hr cap a b _ uniform dir.2.1
  4066. [(a.owner,13+a.tag.length),(b.owner,13+a.tag.length)] (by simp [roles]) dir.2.2.1
  4067. exact ⟨dir.1,reflect_port hr cap a b _ uniform dir.2.1,
  4068. by simpa [sendNode,eventMap,earlier] using order,True.intro⟩
  4069. theorem reflect_downward (hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k))
  4070. (ts : Tiles) (a b : Node) (uniform : UniformOn r v h d (roles a ++ roles b))
  4071. (dir : Holds r allow mark (l ++ v.flatMap h ++ k) (downward ts a b)) :
  4072. Holds r allow mark v (downward ts (sendNode d a) (sendNode d b)) :=
  4073. ⟨dir.1,reflect_port hr cap a b _ uniform dir.2⟩
  4074. theorem reflect_neighbor (hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k))
  4075. (ts : Tiles) (a b : Node) (dir : Dir) (uniform : UniformOn r v h d (roles a ++ roles b))
  4076. (port : Holds r allow mark (l ++ v.flatMap h ++ k) (neighbor ts a b dir)) :
  4077. Holds r allow mark v (neighbor ts (sendNode d a) (sendNode d b) dir) := by
  4078. have rev : UniformOn r v h d (roles b ++ roles a) := fun x hx =>
  4079. uniform x (by simpa [or_comm] using hx)
  4080. cases dir
  4081. · exact reflect_rightward hr cap ts a b uniform port
  4082. · exact reflect_rightward hr cap ts b a rev port
  4083. · exact reflect_downward hr cap ts a b uniform port
  4084. · exact reflect_downward hr cap ts b a rev port
  4085. end Uniform
  4086. /-- Structural independence of the ambient marking. Only a designated
  4087. marked-bit query reads it. The record and ordering parts of a port
  4088. can therefore be used with any source marking. -/
  4089. def markFree : Query → Bool
  4090. | .markedBit .. => false
  4091. | .both x y | .either x y => markFree x && markFree y
  4092. | _ => true
  4093. theorem remark {r w allow} {src dst : Marking} {q : Query} (free : markFree q = true)
  4094. (holds : Holds r allow src w q) : Holds r allow dst w q := by
  4095. induction q with
  4096. | fixed | count | deficient | record | order | slot | separate => exact holds
  4097. | markedBit => cases free
  4098. | both x y hx hy =>
  4099. have both := Bool.and_eq_true_iff.mp free
  4100. exact ⟨hx both.1 holds.1, hy both.2 holds.2⟩
  4101. | either x y hx hy =>
  4102. have both := Bool.and_eq_true_iff.mp free
  4103. exact holds.elim (fun a => Or.inl (hx both.1 a)) (fun b => Or.inr (hy both.2 b))
  4104. theorem free_port (i : Nat) (a b : Node) : markFree (orientedPort i a b) = true := rfl
  4105. theorem free_neighbor (ts : Tiles) (a b : Node) (dir : Dir) :
  4106. markFree (neighbor ts a b dir) = true := by cases dir <;> rfl
  4107. theorem port_remark {r w allow} {src dst : Marking} {i a b}
  4108. (holds : Holds r allow src w (orientedPort i a b)) : Holds r allow dst w (orientedPort i a b) :=
  4109. remark (free_port i a b) holds
  4110. theorem neighbor_remark {r w allow} {src dst : Marking} {ts a b dir}
  4111. (holds : Holds r allow src w (neighbor ts a b dir)) : Holds r allow dst w (neighbor ts a b dir) :=
  4112. remark (free_neighbor ts a b dir) holds
  4113. end P455PortReflection
  4114. end
  4115. /- Begin Problem455RealizerPrim (from finite-semigroup-identity-bases). -/
  4116. section
  4117. /- Encoded first-order subroutines for the #455 computation. -/
  4118. namespace P455GraphPrim
  4119. open P455EffectiveQ P455RealizerGraph
  4120. variable {A B C : Type} [Primcodable A] [Primcodable B] [Primcodable C]
  4121. theorem filter {l : A → List B} {p : A → B → Bool}
  4122. (hl : Primrec l) (hp : Primrec₂ p) : Primrec fun a => (l a).filter (p a) := by
  4123. have k : Primrec₂ (fun a (x : B) => if p a x then some x else none) :=
  4124. (Primrec.ite (show PrimrecPred (fun z : A×B => p z.1 z.2=true) by
  4125. simpa [PrimrecPred, Primrec₂] using hp) (Primrec.option_some.comp Primrec.snd) (.const none)).to₂
  4126. apply (Primrec.listFilterMap hl k).of_eq
  4127. intro a
  4128. induction l a with
  4129. | nil => rfl
  4130. | cons b bs ih => cases h : p a b <;> simp [h,ih]
  4131. theorem join [DecidableEq B] : Primrec₂ (@joinAt B _) := by
  4132. apply Primrec₂.mk
  4133. apply Primrec.list_append.comp Primrec.snd
  4134. apply Primrec.list_flatMap Primrec.snd
  4135. apply Primrec₂.mk
  4136. apply Primrec.ite (Primrec.eq.comp (Primrec.snd.comp Primrec.snd) (Primrec.fst.comp Primrec.fst))
  4137. · apply Primrec.listFilterMap (Primrec.snd.comp Primrec.fst)
  4138. apply Primrec₂.mk
  4139. apply Primrec.ite (Primrec.eq.comp (Primrec.fst.comp Primrec.snd) (Primrec.fst.comp (Primrec.fst.comp Primrec.fst)))
  4140. · exact Primrec.option_some.comp (Primrec.pair (Primrec.fst.comp (Primrec.snd.comp Primrec.fst))
  4141. (Primrec.snd.comp Primrec.snd))
  4142. · exact .const none
  4143. · exact .const []
  4144. theorem graphFold [DecidableEq B] {p : A → List B} {s : A → List (B×B)}
  4145. (hp : Primrec p) (hs : Primrec s) : Primrec fun a => (p a).foldr joinAt (s a) := by
  4146. exact Primrec.list_foldr (h := fun _ (ks : B × List (B×B)) => joinAt ks.1 ks.2) hp hs
  4147. (((join.comp Primrec.fst Primrec.snd).comp Primrec.snd).to₂)
  4148. theorem wordsUpTo : Primrec₂ (@Problem455Finite.wordsUpTo B) := by
  4149. let step (l : List B) (x : Nat × List (List B)) :=
  4150. [] :: l.flatMap (fun a => x.2.map (List.cons a))
  4151. have steprec : Primrec₂ step := by
  4152. apply Primrec₂.mk
  4153. apply Primrec.list_cons.comp (.const [])
  4154. apply Primrec.list_flatMap Primrec.fst
  4155. apply Primrec₂.mk
  4156. apply Primrec.list_map (Primrec.snd.comp (Primrec.snd.comp Primrec.fst))
  4157. exact (Primrec.list_cons.comp (Primrec.snd.comp Primrec.fst) Primrec.snd).to₂
  4158. apply (Primrec.nat_rec (Primrec.const [[]]) steprec).of_eq
  4159. intro l n
  4160. induction n with
  4161. | zero => rfl
  4162. | succ n ih => simp [Problem455Finite.wordsUpTo,step,ih]
  4163. theorem wordPool : Primrec words := (wordsUpTo.comp Primrec.id Primrec.list_length)
  4164. theorem initialized [DecidableEq B] {e : A → B → B → Bool}
  4165. (he : Primrec (fun x : A×(B×B) => e x.1 x.2.1 x.2.2))
  4166. {d : A → List B} (hd : Primrec d) :
  4167. Primrec fun a => initial (d a) (e a) := by
  4168. apply Primrec.list_flatMap hd
  4169. apply Primrec₂.mk
  4170. apply Primrec.list_map
  4171. · apply filter (hd.comp Primrec.fst)
  4172. apply Primrec₂.mk
  4173. apply Primrec.or.comp
  4174. · have same : PrimrecPred (fun z : (A × B) × B => z.1.2 = z.2) :=
  4175. (Primrec.eq (α := B)).comp (Primrec.snd.comp Primrec.fst) Primrec.snd
  4176. classical
  4177. exact same.decide
  4178. · exact he.comp (Primrec.pair (Primrec.fst.comp Primrec.fst)
  4179. (Primrec.pair (Primrec.snd.comp Primrec.fst) Primrec.snd))
  4180. · exact (Primrec.pair (Primrec.snd.comp Primrec.fst) Primrec.snd).to₂
  4181. theorem contains [DecidableEq B] {v : A → B} {xs : A → List B}
  4182. (hv : Primrec v) (hx : Primrec xs) : Primrec fun a => decide (v a∈xs a) := by
  4183. apply ((Primrec.nat_lt.comp (Primrec.list_idxOf.comp hv hx) (Primrec.list_length.comp hx)).decide).of_eq
  4184. intro a; simp [List.idxOf_lt_length_iff]
  4185. theorem reachable {e : A → W → W → Bool} (he : Primrec (fun x : A×(W×W) => e x.1 x.2.1 x.2.2))
  4186. {u v : A → W} (hu : Primrec u) (hv : Primrec v) :
  4187. Primrec fun a => walkB (e a) (u a) (v a) := by
  4188. have piv := wordPool.comp hu
  4189. have dom := Primrec.list_cons.comp hu (Primrec.list_cons.comp hv piv)
  4190. exact (contains (hu.pair hv) (graphFold piv (initialized he dom))).of_eq (fun a => by
  4191. rw [←walk_eq (e a) (u a) (v a)]
  4192. apply Bool.eq_iff_iff.mpr
  4193. simp only [walk,decide_eq_true_eq])
  4194. theorem anyB {l : A → List B} {p : A → B → Bool} (hl : Primrec l) (hp : Primrec₂ p) :
  4195. Primrec fun a => (l a).any (p a) := by
  4196. apply (Primrec.list_foldr hl (Primrec.const false)
  4197. (Primrec.or.comp (hp.comp Primrec.fst (Primrec.fst.comp Primrec.snd))
  4198. (Primrec.snd.comp Primrec.snd)).to₂).of_eq
  4199. intro a
  4200. induction l a with
  4201. | nil => rfl
  4202. | cons b bs ih => simp [ih]
  4203. theorem factor {u v : A → W} (hu : Primrec u) (hv : Primrec v) : Primrec fun a => factorB (u a) (v a) := by
  4204. apply anyB (wordPool.comp hv)
  4205. apply Primrec₂.mk
  4206. apply anyB (wordPool.comp (hv.comp Primrec.fst))
  4207. apply Primrec₂.mk
  4208. exact (Primrec.eq.comp (hv.comp (Primrec.fst.comp Primrec.fst))
  4209. (Primrec.list_append.comp (Primrec.list_append.comp (Primrec.snd.comp Primrec.fst)
  4210. (hu.comp (Primrec.fst.comp Primrec.fst))) Primrec.snd)).decide
  4211. theorem good {e : A → W → W → Bool} (he : Primrec (fun x : A×(W×W) => e x.1 x.2.1 x.2.2))
  4212. {t u : A → W} (ht : Primrec t) (hu : Primrec u) :
  4213. Primrec fun a => goodB (e a) (t a) (u a) := by
  4214. apply anyB (wordPool.comp ht)
  4215. apply Primrec₂.mk
  4216. exact Primrec.and.comp
  4217. (reachable (A := A × W) (e := fun p => e p.1) (he.comp (Primrec.pair (Primrec.fst.comp Primrec.fst) Primrec.snd))
  4218. (ht.comp Primrec.fst) Primrec.snd)
  4219. (factor (hu.comp Primrec.fst) Primrec.snd)
  4220. end P455GraphPrim
  4221. end
  4222. /- Begin Problem455MachineTable (from finite-semigroup-identity-bases). -/
  4223. section
  4224. namespace P455MachineTable
  4225. open P455MachineLocal P455PaddedTiles
  4226. structure TM (g q : Nat) where
  4227. marker : Fin g
  4228. blank : Fin g
  4229. blank_ne : blank≠marker
  4230. start : Fin q
  4231. accept : Fin q
  4232. distinct : start≠accept
  4233. delta : Fin q→Fin g→Ins (Fin g) (Fin q)
  4234. keeps : ∀ z a,(delta z a).symbol=marker ↔ a=marker
  4235. leftSafe : ∀ z,(delta z marker).dir≠.left
  4236. stationary : delta accept marker=⟨accept,marker,.stay⟩
  4237. abbrev C (g q : Nat) := Cell (Fin g) (Fin q)
  4238. def headIndex (p : Option (Fin q)) : Nat := match p with | none => 0 | some x => x.val+1
  4239. def enc (c : C g q) : Fin (g*(q+1)) :=
  4240. ⟨g*headIndex c.head+c.sym.val,by
  4241. have v := c.sym.isLt
  4242. have z : headIndex c.head ≤ q := by cases hh : c.head with
  4243. | none => simp [headIndex]
  4244. | some s => simp [headIndex]; have := s.isLt; omega
  4245. have m := Nat.mul_le_mul_left g z
  4246. rw [Nat.mul_add,Nat.mul_one]; omega⟩
  4247. def dec (M : TM g q) (x : Fin (g*(q+1))) : C g q :=
  4248. let h := x.val/g
  4249. let symbol := x.val%g
  4250. let head := if e : 0<h then some (⟨h-1,by
  4251. have gr := M.marker.isLt
  4252. have pos : 0<g := by omega
  4253. have div := (Nat.div_lt_iff_lt_mul pos).mpr (calc x.val < g*(q+1) := x.isLt
  4254. _ = _ := Nat.mul_comm ..)
  4255. dsimp [h] at *; omega⟩ : Fin q) else none
  4256. ⟨⟨symbol,Nat.mod_lt _ (by have := M.marker.isLt; omega)⟩,head⟩
  4257. theorem dec_enc (M : TM g q) (c : C g q) : dec M (enc c)=c := by
  4258. obtain ⟨s,h⟩ := c
  4259. have gpos : 0<g := by have := s.isLt; omega
  4260. cases h with
  4261. | none => simp [dec,enc,headIndex,Nat.div_eq_of_lt s.isLt,Nat.mod_eq_of_lt s.isLt]
  4262. | some p =>
  4263. simp [dec,enc,headIndex,Nat.mul_add_div gpos,Nat.div_eq_of_lt s.isLt,Nat.mul_add_mod,Nat.mod_eq_of_lt s.isLt]
  4264. theorem enc_inj (M : TM g q) {a b : C g q} (e : enc a=enc b) : a=b := by
  4265. simpa [dec_enc] using congrArg (dec M) e
  4266. def compile (M : TM g q) : MachineTable (g*(q+1)) where
  4267. marker := fun v=>decide ((dec M v).sym=M.marker)
  4268. initial := fun left=>if left then enc ⟨M.marker,some M.start⟩ else enc ⟨M.blank,none⟩
  4269. accept := enc ⟨M.marker,some M.accept⟩
  4270. distinct := by
  4271. intro eq
  4272. have h := congrArg Cell.head (enc_inj M eq)
  4273. exact M.distinct (Option.some.inj h)
  4274. next := fun l c r => (update M.delta (l.map (dec M)) (dec M c) (r.map (dec M))).map enc
  4275. structure Config (g q : Nat) where
  4276. tape : Nat→Fin g
  4277. pos : Nat
  4278. state : Fin q
  4279. def init (M : TM g q) : Config g q := ⟨(fun i=>if i=0 then M.marker else M.blank),0,M.start⟩
  4280. def step (M : TM g q) (c : Config g q) : Config g q :=
  4281. let ins := M.delta c.state (c.tape c.pos)
  4282. ⟨writeAt c.tape c.pos ins.symbol,dest ins.dir c.pos,ins.state⟩
  4283. def run (M : TM g q) : Nat→Config g q
  4284. | 0 => init M
  4285. | t+1 => step M (run M t)
  4286. def row (M : TM g q) (t x : Nat) := enc (atCell (run M t).tape (run M t).pos (run M t).state x)
  4287. theorem marker_iff (M : TM g q) (t x : Nat) : (run M t).tape x=M.marker ↔ x=0 := by
  4288. induction t with
  4289. | zero => by_cases e : x=0 <;> simp [run,init,e,M.blank_ne]
  4290. | succ t ih =>
  4291. change writeAt _ _ _ x=M.marker ↔ x=0
  4292. by_cases e : x=(run M t).pos
  4293. · rw [writeAt,if_pos e,M.keeps,←e]; exact ih
  4294. · simpa [writeAt,e] using ih
  4295. theorem head_bound (M : TM g q) (t : Nat) : (run M t).pos ≤ t := by
  4296. induction t with
  4297. | zero => exact Nat.le_refl _
  4298. | succ t ih =>
  4299. change dest (_ : Ins (Fin g) (Fin q)).dir (run M t).pos≤t+1
  4300. cases d : (M.delta (run M t).state ((run M t).tape (run M t).pos)).dir <;>
  4301. simp [dest] <;> omega
  4302. theorem physical_safe {t w : Nat} (M : TM g q) (wide : t+1<w) :
  4303. ¬ exits (M.delta (run M t).state ((run M t).tape (run M t).pos)).dir w (run M t).pos := by
  4304. intro bad
  4305. rcases bad with ⟨left,at0⟩|⟨_,edge⟩
  4306. · rw [at0,(marker_iff M t 0).mpr rfl] at left
  4307. exact M.leftSafe _ left
  4308. · have := head_bound M t; omega
  4309. theorem left_dec (M : TM g q) (t x : Nat) :
  4310. (leftAt (row M t) x).map (dec M)=leftOf (atCell (run M t).tape (run M t).pos (run M t).state) x := by
  4311. by_cases e : x=0 <;> simp [leftAt,leftOf,e,row,dec_enc]
  4312. theorem right_dec (M : TM g q) (t x w : Nat) :
  4313. (rightAt (row M t) w x).map (dec M)=rightOf (atCell (run M t).tape (run M t).pos (run M t).state) w x := by
  4314. by_cases e : x+1=w <;> simp [rightAt,rightOf,e,row,dec_enc]
  4315. theorem local_value (M : TM g q) (t w x : Nat) (head : (run M t).pos<w)
  4316. (safe : ¬exits (M.delta (run M t).state ((run M t).tape (run M t).pos)).dir w (run M t).pos)
  4317. (hx : x<w) :
  4318. (compile M).next (leftAt (row M t) x) (row M t x) (rightAt (row M t) w x)=some (row M (t+1) x) := by
  4319. change (update M.delta _ (dec M (enc _)) _).map enc=_
  4320. rw [left_dec,right_dec,dec_enc,local_step _ _ _ _ _ head safe _ hx]
  4321. rfl
  4322. end P455MachineTable
  4323. end
  4324. /- Begin Problem455Retained (from finite-semigroup-identity-bases). -/
  4325. section
  4326. namespace P455Retained
  4327. open Problem455.Slots P455Witness P455Paths P455ContactLift
  4328. structure Expansion (v : W) (e : Nat → W) (kept : Nat → Prop) : Prop where
  4329. literal : ∀ x ∈ v, kept x → e x = [x]
  4330. gaps : ∀ g ∈ v, ¬ kept g → v.count g = 1 ∧ e g ≠ [] ∧ ∀ a ∈ e g, ¬ kept a
  4331. /-- Projecting onto any chosen retained labels commutes with expansion. -/
  4332. theorem Expansion.select_eq {v e kept} (exp : Expansion v e kept)
  4333. (s keep : W) (sub : ∀ a ∈ s, a ∈ v) (hk : ∀ a ∈ keep, kept a) :
  4334. select keep (s.flatMap e) = select keep s := by
  4335. induction s with
  4336. | nil => rfl
  4337. | cons x xs ih =>
  4338. have hx := sub x (by simp)
  4339. have rs := ih (fun a ha => sub a (by simp [ha]))
  4340. change select keep (e x ++ xs.flatMap e) = select keep ([x] ++ xs)
  4341. rw [select_append,select_append,rs]
  4342. by_cases keep_x : kept x
  4343. · rw [exp.literal x hx keep_x]
  4344. · have gap := exp.gaps x hx keep_x
  4345. rw [select_nil keep (e x) (fun a ha ab => gap.2.2 a ha (hk a ab))]
  4346. have no : x ∉ keep := fun h => keep_x (hk x h)
  4347. simp [select,no]
  4348. theorem Expansion.count_eq {v e kept} (exp : Expansion v e kept)
  4349. (s : W) (sub : ∀ a ∈ s, a ∈ v) (x : Nat) (hx : kept x) :
  4350. (s.flatMap e).count x = s.count x := by
  4351. have h := congrArg (List.count x) (exp.select_eq s [x] sub (by simpa using hx))
  4352. simpa [select] using h
  4353. theorem Expansion.small_cap {v e kept r} (exp : Expansion v e kept) (hr : 1 < r)
  4354. (cap : P455Closure.Cap r (v.flatMap e)) : P455Closure.Cap r v := by
  4355. intro x
  4356. by_cases use : x ∈ v
  4357. · by_cases k : kept x
  4358. · rw [← exp.count_eq v (fun _ h => h) x k]; exact cap x
  4359. · rw [(exp.gaps x use k).1]; omega
  4360. · rw [List.count_eq_zero.mpr use]; omega
  4361. theorem contact_counts {r allow mark v x y c} (cap : P455Closure.Cap r v)
  4362. (h : Holds r allow mark v (contact r x y c)) : v.count x = r ∧ v.count y = r := by
  4363. cases c with
  4364. | record tag rev =>
  4365. cases rev
  4366. · exact record_counts cap h
  4367. · exact (record_counts cap h).symm
  4368. | port phase rev => exact ⟨h.2.1,h.2.2.1⟩
  4369. theorem Expansion.contact {v e kept r allow mark x y} (exp : Expansion v e kept) (hr : 1 < r)
  4370. (cap : P455Closure.Cap r (v.flatMap e)) (c : ContactChoice)
  4371. (edge : Holds r allow mark v (P455Witness.contact r x y c)) :
  4372. Holds r allow mark (v.flatMap e) (P455Witness.contact r x y c) := by
  4373. obtain ⟨xc,yc⟩ := contact_counts (exp.small_cap hr cap) edge
  4374. have used (a) (count : v.count a = r) : kept a := by
  4375. apply Classical.byContradiction
  4376. intro k
  4377. have hm : a ∈ v := List.count_pos_iff.mp (by omega)
  4378. have := (exp.gaps a hm k).1; omega
  4379. have xx := used x xc
  4380. have yy := used y yc
  4381. have eq (a b) (ha : kept a) (hb : kept b) : select [a,b] (v.flatMap e) = select [a,b] v :=
  4382. exp.select_eq v [a,b] (fun _ h => h) (by simpa using And.intro ha hb)
  4383. have ord (pat : List Event) (inside : ∀ a ∈ pat, a.1 ∈ [x,y])
  4384. (old : Holds r allow mark v (.order pat)) : Holds r allow mark (v.flatMap e) (.order pat) := by
  4385. refine ⟨old.1, P455ContactReflection.select_sees [x,y] _ pat ?_⟩
  4386. rw [eq x y xx yy]
  4387. exact P455ContactReflection.sees_select _ _ _ inside old.2
  4388. cases c with
  4389. | record tag rev =>
  4390. cases rev with
  4391. | false =>
  4392. obtain ⟨ne,len,tag,bit,hp⟩ := edge
  4393. exact ⟨ne,len,tag,bit,(eq x y xx yy).trans hp⟩
  4394. | true =>
  4395. obtain ⟨ne,len,tag,bit,hp⟩ := edge
  4396. exact ⟨ne,len,tag,bit,(eq y x yy xx).trans hp⟩
  4397. | port port rev =>
  4398. obtain ⟨ne,_,_,early,order,_⟩ := edge
  4399. refine ⟨ne,(exp.count_eq _ (fun _ h => h) x xx).trans xc,
  4400. (exp.count_eq _ (fun _ h => h) y yy).trans yc,?_,?_,True.intro⟩
  4401. · rcases early with l|rr
  4402. · exact .inl ⟨ord _ (by simp) l.1,True.intro⟩
  4403. · exact .inr ⟨ord _ (by simp) rr.1,True.intro⟩
  4404. · cases rev <;> exact ord _ (by simp) order
  4405. theorem Expansion.walk {v e kept r allow mark} (exp : Expansion v e kept) (hr : 1 < r)
  4406. (cap : P455Closure.Cap r (v.flatMap e)) (s : Nat) (p : List Step)
  4407. (walk : Walk r allow mark v s p) : Walk r allow mark (v.flatMap e) s p := by
  4408. induction p generalizing s with
  4409. | nil => exact True.intro
  4410. | cons step ps ih => exact ⟨exp.contact hr cap step.2 walk.1, ih _ walk.2⟩
  4411. theorem Expansion.near {v e kept r allow mark} (exp : Expansion v e kept) (hr : 1 < r)
  4412. (cap : P455Closure.Cap r (v.flatMap e)) {s t J : Nat} (near : Near r allow mark v s t J) :
  4413. Near r allow mark (v.flatMap e) s t J := by
  4414. obtain ⟨p,h,ep,le⟩ := near
  4415. exact ⟨p,exp.walk hr cap s p h,ep,le⟩
  4416. /-- An occurrence in a small open slot contributes every letter of its
  4417. expansion inside the corresponding literal open slot of the original.
  4418. For an unretained variable the nonempty gap gives a genuine occupant. -/
  4419. theorem Expansion.in_original_slot {v e kept} (exp : Expansion v e kept) (x i y : Nat) (kx : kept x)
  4420. (ho : occupies v x i y) (a : Nat) (ha : a ∈ e y) : occupies (v.flatMap e) x i a := by
  4421. obtain ⟨j,hj⟩ := ho
  4422. have hm : (x,i+1) ∈ events v := hj.mem (by simp)
  4423. have bound : i+1 < v.count x := by simpa using (P455SlotOrigin.event_bounds (fun _ => 0) _ x _ hm).2
  4424. obtain ⟨L,I,R,cut,idx,cons⟩ := P455SlotOrigin.slot_cut v x i bound
  4425. have hy : y ∈ I := by
  4426. apply (P455SlotOrigin.occupies_at_cut L I R x y cons).mp
  4427. rw [←cut,idx]; exact ⟨j,hj⟩
  4428. have hI : (I.flatMap e).count x = I.count x := exp.count_eq I (fun a h => by simp [cut,h]) x kx
  4429. have fresh : x ∉ I.flatMap e := List.count_eq_zero.mp (hI.trans (List.count_eq_zero.mpr cons))
  4430. have pref := exp.count_eq L (fun a h => by simp [cut,h]) x kx
  4431. have ex := exp.literal x (by simp [cut]) kx
  4432. have expanded : v.flatMap e =
  4433. (L.flatMap e) ++ [x] ++ I.flatMap e ++ [x] ++ R.flatMap e := by
  4434. simp [cut,ex,List.flatMap_append]
  4435. rw [expanded,←idx,←pref]
  4436. exact (P455SlotOrigin.occupies_at_cut _ _ _ _ _ fresh).mpr (List.mem_flatMap.mpr ⟨y,hy,ha⟩)
  4437. theorem Expansion.slot_guard {v e kept r} (exp : Expansion v e kept)
  4438. (x i : Nat) (kx : kept x)
  4439. (original : ∀ a, occupies (v.flatMap e) x i a → kept a ∧ (v.flatMap e).count a = r) :
  4440. ∀ y, occupies v x i y → v.count y = r := by
  4441. intro y ho
  4442. obtain ⟨j,obs⟩ := ho
  4443. have used : y ∈ v := stamped_mem_label _ _ (y,j) (obs.mem (by simp))
  4444. by_cases ky : kept y
  4445. · have mem : y ∈ e y := by rw [exp.literal y used ky]; simp
  4446. have claim := (original y (exp.in_original_slot x i y kx ⟨j,obs⟩ y mem)).2
  4447. exact (exp.count_eq v (fun _ h => h) y ky).symm.trans claim
  4448. · have gap := exp.gaps y used ky
  4449. obtain ⟨a,ha⟩ : ∃ a, a ∈ e y := by
  4450. cases he : e y with
  4451. | nil => exact (gap.2.1 he).elim
  4452. | cons a rest => exact ⟨a,by simp⟩
  4453. exact (gap.2.2 a ha (original a (exp.in_original_slot x i y kx ⟨j,obs⟩ a ha)).1).elim
  4454. /-- Derive the guard on the actual smaller rule from the retention of the
  4455. original radius-J contact ball and the uniformity of its slot occupants. -/
  4456. theorem Expansion.guard {v e kept r allow mark seed J} (exp : Expansion v e kept)
  4457. (hr : 1 < r) (cap : P455Closure.Cap r (v.flatMap e))
  4458. (original : ∀ x, Near r allow mark (v.flatMap e) seed x J →
  4459. kept x ∧ ∀ i, slotStart i → ∀ y, occupies (v.flatMap e) x i y →
  4460. kept y ∧ (v.flatMap e).count y = r) :
  4461. Guard r allow mark v seed J := by
  4462. intro x near i hi
  4463. obtain ⟨kx,slots⟩ := original x (exp.near hr cap near)
  4464. exact exp.slot_guard x i kx (slots i hi)
  4465. end P455Retained
  4466. end
  4467. /- Begin Problem455SourceFamilies (from finite-semigroup-identity-bases). -/
  4468. section
  4469. /- Source interpretations of the designated slot and duplicate-neighbor
  4470. certificates. Block distinctions require no repeated links to be read
  4471. literally back in the source. The weaker name/count conclusions do not. -/
  4472. namespace P455SourceFamilies
  4473. open P455Witness P455Paths P455ContactLift P455PortReflection Problem455.Slots
  4474. def markNode (a : Node) : Marking := fun x y => x = a.owner ∧ y = a.mate
  4475. def picked (s : SlotCertificate) := if s.startAtMate then s.anchor.mate else s.anchor.owner
  4476. def sendDefect (d : Nat → Nat) : SlotDefect → SlotDefect
  4477. | .deficient a => .deficient (d a)
  4478. | .overflow xs => .overflow (xs.map d)
  4479. def sendSlot (d : Nat → Nat) (s : SlotCertificate) : SlotCertificate :=
  4480. { s with anchor := sendNode d s.anchor, steps := relabel d s.steps, defect := sendDefect d s.defect }
  4481. def sendFunc (d : Nat → Nat) (f : FunctionalityCertificate) : FunctionalityCertificate :=
  4482. { f with anchor := sendNode d f.anchor, b := sendNode d f.b, c := sendNode d f.c }
  4483. def Compressed (r : Nat) (v : W) := ∀ a b, ¬ Problem455Swap.Link r v a b
  4484. theorem compressed_separates {r v} (cmp : Compressed r v) {a b : Nat} (ne : a ≠ b) :
  4485. ¬ Problem455Swap.SameBlock r v a b := by
  4486. intro same
  4487. have joined := same.2.2
  4488. cases joined with
  4489. | refl => exact ne rfl
  4490. | extend _ adj => rcases adj with f|b <;> exact cmp _ _ (by assumption)
  4491. private theorem remark_contact {r allow mark src w a b} (c : ContactChoice)
  4492. (obs : V r allow mark w (contact r a b c)) : V r allow src w (contact r a b c) := by
  4493. apply remark _ obs
  4494. cases c with
  4495. | record tag rev => cases rev <;> rfl
  4496. | port phase rev => rfl
  4497. theorem remark_walk {r allow mark src w} (a : Nat) (p : List Step)
  4498. (h : Walk r allow mark w a p) : Walk r allow src w a p := by
  4499. induction p generalizing a with
  4500. | nil => exact True.intro
  4501. | cons pair p ih => exact ⟨remark_contact pair.2 h.1,ih pair.1 h.2⟩
  4502. theorem valid_slot {r allow mark w o i} (d : SlotDefect)
  4503. (q : V r allow mark w (terminalSlot r o i d)) : slotStart i := by
  4504. cases d with
  4505. | deficient a => exact q.1.1
  4506. | overflow xs =>
  4507. cases xs with
  4508. | nil => have h : ([] : List Nat).length = 5 := q.1; contradiction
  4509. | cons a _ => exact q.2.2.1.1.2.1
  4510. theorem rebuild_terminal_in {r v u h x i} (d : Nat → Nat) (a : SlotDefect)
  4511. (slot : slotStart i) (cmp : Compressed r u)
  4512. (unique : ∀ {a y}, Supplies v h r y a → d a = y)
  4513. (inside : ∀ y, occupies v x i y → v.count y = r → occupies u x i y ∧ u.count y = r)
  4514. {allow mark} (lifted : P455TerminalTransfer.Lift v h x i r a) :
  4515. Holds r allow mark u (terminalSlot r x i (sendDefect d a)) := by
  4516. cases a with
  4517. | deficient s => exact lifted.elim
  4518. | overflow xs =>
  4519. obtain ⟨f,len,nd,spec⟩ := lifted
  4520. have eq (a : Nat) (inxs : a∈xs) : d a = f a :=
  4521. unique ⟨(spec a inxs).2.2,(spec a inxs).2.1⟩
  4522. have maps : xs.map d = xs.map f := List.map_congr_left eq
  4523. have bs : (x :: xs.map d).Pairwise (fun a b => ¬ Problem455Swap.SameBlock r u a b) := by
  4524. rw [maps]; exact nd.imp (fun ne => compressed_separates cmp ne)
  4525. refine ⟨by simpa [P455Witness.Holds] using len,(P455TerminalTransfer.block_separation _).mpr bs,?_,True.intro⟩
  4526. apply (allQ_iff _).mpr
  4527. intro q hq
  4528. obtain ⟨z,hz,rfl⟩ := List.mem_map.mp hq
  4529. obtain ⟨a,ha,rfl⟩ := List.mem_map.mp hz
  4530. have sp := spec a ha
  4531. have out := inside (f a) sp.1 sp.2.2
  4532. exact eq a ha ▸ And.intro out.2 (And.intro slot out.1)
  4533. theorem rebuild_terminal {r v h x i} (d : Nat → Nat) (a : SlotDefect)
  4534. (slot : slotStart i) (cmp : Compressed r v)
  4535. (unique : ∀ {a y}, Supplies v h r y a → d a = y)
  4536. {allow mark} (lifted : P455TerminalTransfer.Lift v h x i r a) :
  4537. Holds r allow mark v (terminalSlot r x i (sendDefect d a)) :=
  4538. rebuild_terminal_in d a slot cmp unique (fun _ o cnt => ⟨o,cnt⟩) lifted
  4539. def SlotResult (r : Nat) (allow : Tag → Prop) (v : W) (h : Nat → W) (seed : Nat)
  4540. (s : SlotCertificate) : Prop :=
  4541. let d := donor v h r
  4542. let s' := sendSlot d s
  4543. let m := markNode s'.anchor
  4544. Holds r allow m v (markedNode s'.anchor s.bit) ∧
  4545. Walk r allow m v seed s'.steps ∧
  4546. P455TerminalTransfer.Lift v h (d (endpoint (picked s) s.steps)) s.terminalIndex r s.defect ∧
  4547. (Compressed r v → Holds r allow m v (s'.query r))
  4548. theorem slot_source {r allow mark v h l k seed} (hr : 0 < r)
  4549. (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k)) (s : SlotCertificate)
  4550. (ok : V r allow mark (l ++ v.flatMap h ++ k) (s.query r))
  4551. (start : Supplies v h r seed (picked s)) (guard : Guard r allow mark v seed 6) :
  4552. SlotResult r allow v h seed s := by
  4553. let d := donor v h r
  4554. let m := markNode (sendNode d s.anchor)
  4555. have seedEq : d (picked s) = seed := donor_eq hr (factor_cap cap) start
  4556. have anch : V r allow mark (l ++ v.flatMap h ++ k) (markedNode s.anchor s.bit) := ok.1
  4557. have ports := record_pair (marked_typed anch)
  4558. have rolesU : UniformOn r v h d (roles s.anchor) := by
  4559. intro u mem
  4560. have links : Near r allow mark (l ++ v.flatMap h ++ k) (picked s) u 1 := by
  4561. rcases (show u=s.anchor.owner ∨ u=s.anchor.mate by simpa [roles] using mem) with rfl|rfl
  4562. · cases z : s.startAtMate <;> simp only [picked,z,Bool.false_eq_true,if_false,if_true]
  4563. · exact near_self _ _
  4564. · exact ports.2
  4565. · cases z : s.startAtMate <;> simp only [picked,z,Bool.false_eq_true,if_false,if_true]
  4566. · exact ports.1
  4567. · exact near_self _ _
  4568. exact (lift_near hr cap start guard (by decide : 1 ≤ 6) links).1
  4569. have bit := reflect_markedNode hr cap s.anchor s.bit rolesU m (.inl ⟨rfl,rfl⟩) anch
  4570. obtain ⟨len,outputWalk,terminal⟩ := slot_route s ok
  4571. have walks := lift_walk hr cap start guard s.steps len outputWalk
  4572. let endLabel := endpoint (picked s) s.steps
  4573. have ext : Near r allow mark (l ++ v.flatMap h ++ k) (picked s) endLabel 6 :=
  4574. ⟨s.steps,outputWalk,rfl,len⟩
  4575. obtain ⟨en,towards⟩ := lift_near hr cap start guard (Nat.le_refl _) ext
  4576. have slot := valid_slot s.defect terminal
  4577. have g := guard (d endLabel) towards s.terminalIndex slot
  4578. have lf := P455TerminalTransfer.terminal v h l k (d endLabel) endLabel s.terminalIndex r
  4579. hr cap en.1 en.2 g s.defect terminal
  4580. have sw : Walk r allow m v seed (relabel d s.steps) := remark_walk _ _ walks.1
  4581. refine ⟨bit,sw,lf,?_⟩
  4582. intro cmp
  4583. have term : V r allow m v (terminalSlot r (d endLabel) s.terminalIndex (sendDefect d s.defect)) :=
  4584. rebuild_terminal d s.defect slot cmp (fun hh => donor_eq hr (factor_cap cap) hh) lf
  4585. have pickEq : picked (sendSlot d s) = d (picked s) := by
  4586. cases z : s.startAtMate <;> simp [picked,sendSlot,sendNode,z]
  4587. refine ⟨bit,by simpa [sendSlot,relabel,P455Witness.Holds] using len,?_,True.intro⟩
  4588. apply (route_iff ..).mpr
  4589. change Walk r allow m v (picked (sendSlot d s)) (relabel d s.steps) ∧
  4590. V r allow m v (terminalSlot r (endpoint (picked (sendSlot d s)) (relabel d s.steps))
  4591. s.terminalIndex (sendDefect d s.defect))
  4592. rw [pickEq,endpoint_relabel]
  4593. exact ⟨seedEq.symm ▸ sw,term⟩
  4594. def roleOf (b : Bool) (n : Node) := if b then n.mate else n.owner
  4595. def FuncResult (r : Nat) (allow : Tag → Prop) (ts : Tiles) (v : W) (h : Nat → W)
  4596. (f : FunctionalityCertificate) : Prop :=
  4597. let f' := sendFunc (donor v h r) f
  4598. let m := markNode f'.anchor
  4599. Holds r allow m v (markedNode f'.anchor f'.bit) ∧
  4600. Holds r allow m v (neighbor ts f'.anchor f'.b f'.dir) ∧
  4601. Holds r allow m v (neighbor ts f'.anchor f'.c f'.dir) ∧
  4602. roleOf f'.distinguishMate f'.b ≠ roleOf f'.distinguishMate f'.c ∧
  4603. (Compressed r v → Holds r allow m v (f'.query ts))
  4604. theorem functionality_source {r allow mark v h l k seed} (hr : 0 < r)
  4605. (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k)) (ts : Tiles) (f : FunctionalityCertificate)
  4606. (ok : V r allow mark (l ++ v.flatMap h ++ k) (f.query ts))
  4607. (start : Supplies v h r seed f.anchor.owner) (guard : Guard r allow mark v seed 6) :
  4608. FuncResult r allow ts v h f := by
  4609. let d := donor v h r
  4610. let m := markNode (sendNode d f.anchor)
  4611. have supplies (n : Node) (use : n=f.anchor ∨ n=f.b ∨ n=f.c) : UniformOn r v h d (roles n) := by
  4612. intro a ha
  4613. have reach := P455CertificateReach.functionality_reach cap ts f ok use
  4614. (show a=n.owner ∨ a=n.mate by simpa [roles] using ha)
  4615. exact (lift_near hr cap start guard (by decide : 2 ≤ 6) reach).1
  4616. have union (n : Node) (use : n=f.anchor ∨ n=f.b ∨ n=f.c) :
  4617. UniformOn r v h d (roles f.anchor ++ roles n) := by
  4618. intro a ha
  4619. rcases List.mem_append.mp ha with h1|h2
  4620. · exact supplies _ (.inl rfl) _ h1
  4621. · exact supplies n use _ h2
  4622. have bit := reflect_markedNode hr cap f.anchor f.bit (supplies _ (.inl rfl)) m (.inl ⟨rfl,rfl⟩) ok.1
  4623. have b := neighbor_remark (dst := m) (reflect_neighbor hr cap ts f.anchor f.b f.dir (union _ (.inr (.inl rfl))) ok.2.1)
  4624. have c := neighbor_remark (dst := m) (reflect_neighbor hr cap ts f.anchor f.c f.dir (union _ (.inr (.inr rfl))) ok.2.2.1)
  4625. have rb (n : Node) : roleOf f.distinguishMate n ∈ roles n := by
  4626. cases e : f.distinguishMate <;> simp [roleOf,roles,e]
  4627. have sb := supplies f.b (.inr (.inl rfl)) _ (rb f.b)
  4628. have sc := supplies f.c (.inr (.inr rfl)) _ (rb f.c)
  4629. have neat : d (roleOf f.distinguishMate f.b) ≠ d (roleOf f.distinguishMate f.c) := by
  4630. intro eq
  4631. have same := Problem455SameDonor.sameDonor v h _ sb.1 (factor_cap cap) _ _ sb.2 (eq.symm ▸ sc.2)
  4632. apply ok.2.2.2.1
  4633. exact Problem455Swap.sameBlock_factor ⟨l,k,rfl⟩
  4634. (fun a => by rw [Problem455BlockBridge.occ_count]; exact cap a) same
  4635. have mapped (n : Node) : roleOf f.distinguishMate (sendNode d n) = d (roleOf f.distinguishMate n) := by
  4636. cases f.distinguishMate <;> rfl
  4637. have neq : roleOf f.distinguishMate (sendNode d f.b) ≠ roleOf f.distinguishMate (sendNode d f.c) := by
  4638. simpa only [mapped] using neat
  4639. exact ⟨bit,b,c,neq,fun cmp => ⟨bit,b,c,compressed_separates cmp neq,True.intro⟩⟩
  4640. end P455SourceFamilies
  4641. end
  4642. /- Begin Problem455EdgeSource (from finite-semigroup-identity-bases). -/
  4643. section
  4644. namespace P455EdgeSource
  4645. open P455Witness P455Paths P455CertificateReach P455PortReflection P455ContactReflection
  4646. open P455ContactLift
  4647. def sendEdge (d : Nat → Nat) (e : EdgeCertificate) : EdgeCertificate :=
  4648. ⟨sendNode d e.a, sendNode d e.b, sendNode d e.right, sendNode d e.left,
  4649. sendNode d e.down, sendNode d e.up, sendNode d e.diagonal⟩
  4650. def endpointMarks (d : Nat → Nat) (e : EdgeCertificate) (s t : Nat) : Prop :=
  4651. (s = d e.a.owner ∧ t = d e.a.mate) ∨ (s = d e.b.owner ∧ t = d e.b.mate)
  4652. private theorem when_true {r allow mark w b q} (f : b = true → Holds r allow mark w q) :
  4653. Holds r allow mark w (flagQ b q) := by
  4654. cases b
  4655. · exact True.intro
  4656. · exact f rfl
  4657. private theorem read_guard {r allow mark w b q} (hb : b = true)
  4658. (f : Holds r allow mark w (flagQ b q)) : Holds r allow mark w q := by simpa [flagQ,hb] using f
  4659. /-- Retain one real four-role port between the endpoints. This also supplies
  4660. the injectivity needed for the final first-owner comparison. -/
  4661. theorem endpoint_port {r allow mark w} (ts : Tiles) (e : EdgeCertificate)
  4662. (ok : Holds r allow mark w (e.query ts)) :
  4663. ∃ p, Holds r allow mark w (orientedPort p e.a e.b) ∨
  4664. Holds r allow mark w (orientedPort p e.b e.a) := by
  4665. have lc := ok.2.2.1
  4666. have succ := ok.2.2.2.1
  4667. unfold chosenSuccessor at succ
  4668. dsimp only at succ
  4669. split at succ
  4670. next ret => exact ⟨4,succ.2.1⟩
  4671. next noReturn =>
  4672. have eq := succ.1
  4673. cases row : endOfRow ts e.a with
  4674. | true =>
  4675. have down : ts.bottom e.a.tag = false := by simpa [row] using noReturn
  4676. have target : e.down = e.b := by simpa [row,P455Witness.Holds] using eq
  4677. have ok := read_guard (by simp [down]) lc.2.2.1
  4678. exact ⟨_,.inl (target ▸ ok.2)⟩
  4679. | false =>
  4680. cases odd : ts.oddRow e.a.tag with
  4681. | true =>
  4682. have left : ts.left e.a.tag = false := by simpa [endOfRow,odd] using row
  4683. have target : e.left = e.b := by simpa [row,odd,P455Witness.Holds] using eq
  4684. have ok := read_guard (by simp [left]) lc.2.1
  4685. exact ⟨_,.inr (target ▸ ok.2.1)⟩
  4686. | false =>
  4687. have right : ts.right e.a.tag = false := by simpa [endOfRow,odd] using row
  4688. have target : e.right = e.b := by simpa [row,odd,P455Witness.Holds] using eq
  4689. have ok := read_guard (by simp [right]) lc.1
  4690. exact ⟨_,.inl (target ▸ ok.2.1)⟩
  4691. theorem edge_source {r allow mark v h l k d} (hr : 0 < r)
  4692. (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k)) (ts : Tiles) (e : EdgeCertificate)
  4693. (supply : ∀ n, Active ts e n → UniformOn r v h d (roles n))
  4694. (ok : Holds r allow mark (l ++ v.flatMap h ++ k) (e.query ts)) :
  4695. Holds r allow (endpointMarks d e) v ((sendEdge d e).query ts) := by
  4696. have both {n m} (an : Active ts e n) (am : Active ts e m) :
  4697. UniformOn r v h d (roles n ++ roles m) := by
  4698. intro y hy
  4699. rcases List.mem_append.mp hy with h|h
  4700. · exact supply n an y h
  4701. · exact supply m am y h
  4702. have localRight (rr : ts.right e.a.tag = false) :=
  4703. read_guard (by simp [rr]) ok.2.2.1.1
  4704. have localLeft (ll : ts.left e.a.tag = false) :=
  4705. read_guard (by simp [ll]) ok.2.2.1.2.1
  4706. have localDown (dd : ts.bottom e.a.tag = false) :=
  4707. read_guard (by simp [dd]) ok.2.2.1.2.2.1
  4708. have localUp (uu : ts.top e.a.tag = false) :=
  4709. read_guard (by simp [uu]) ok.2.2.1.2.2.2.1
  4710. have localSq (rr : ts.right e.a.tag = false) (dd : ts.bottom e.a.tag = false) :=
  4711. read_guard (by simp [rr,dd]) ok.2.2.1.2.2.2.2.1
  4712. have hs : Holds r allow (endpointMarks d e) v (localCert ts (sendEdge d e)) := by
  4713. refine ⟨when_true (fun b => ?_),when_true (fun b => ?_),when_true (fun b => ?_),
  4714. when_true (fun b => ?_),when_true (fun b => ?_),True.intro⟩
  4715. · have rr : ts.right e.a.tag = false := by simpa [sendEdge,sendNode] using b
  4716. exact reflect_rightward hr cap ts _ _ (both .anchor (.right rr)) (localRight rr)
  4717. · have ll : ts.left e.a.tag = false := by simpa [sendEdge,sendNode] using b
  4718. exact reflect_rightward hr cap ts _ _ (both (.left ll) .anchor) (localLeft ll)
  4719. · have dd : ts.bottom e.a.tag = false := by simpa [sendEdge,sendNode] using b
  4720. exact reflect_downward hr cap ts _ _ (both .anchor (.down dd)) (localDown dd)
  4721. · have uu : ts.top e.a.tag = false := by simpa [sendEdge,sendNode] using b
  4722. exact reflect_downward hr cap ts _ _ (both (.up uu) .anchor) (localUp uu)
  4723. · obtain ⟨rr,dd⟩ : ts.right e.a.tag = false ∧ ts.bottom e.a.tag = false := by
  4724. simpa [sendEdge,sendNode] using b
  4725. exact ⟨reflect_downward hr cap ts _ _ (both (.right rr) (.diagonal rr dd)) (localSq rr dd).1,
  4726. reflect_rightward hr cap ts _ _ (both (.down dd) (.diagonal rr dd)) (localSq rr dd).2⟩
  4727. have aBit := reflect_markedNode hr cap e.a true (supply _ .anchor) (endpointMarks d e)
  4728. (Or.inl (Or.inl ⟨rfl,rfl⟩)) ok.1
  4729. have bBit := reflect_markedNode hr cap e.b false (supply _ .successor) (endpointMarks d e)
  4730. (Or.inl (Or.inr ⟨rfl,rfl⟩)) ok.2.1
  4731. refine ⟨aBit,bBit,hs,?_,True.intro⟩
  4732. have rel (pat) (mem : ∀ u ∈ pat, u.1 ∈ roles e.a ++ roles e.b) (ord :
  4733. Holds r allow mark (l ++ v.flatMap h ++ k) (.order pat)) :
  4734. Holds r allow mark v (.order (pat.map (eventMap d))) := by
  4735. obtain ⟨p,forward|back⟩ := endpoint_port ts e ok
  4736. · exact port_owner_order hr cap _ _ p (both .anchor .successor) forward pat mem ord
  4737. · exact port_owner_order hr cap _ _ p (both .successor .anchor) back pat
  4738. (fun u hu => by have := mem u hu; simpa [or_comm] using this) ord
  4739. have suc := ok.2.2.2.1
  4740. unfold chosenSuccessor at suc ⊢
  4741. dsimp only [sendEdge,sendNode] at suc ⊢
  4742. change Holds r allow _ v (if endOfRow ts e.a && ts.bottom e.a.tag then _ else _)
  4743. split at suc
  4744. next ret =>
  4745. rw [if_pos ret]
  4746. have ord := rel [(e.b.owner,0),(e.a.owner,0)] (by simp [roles]) suc.2.2.1
  4747. refine ⟨suc.1,?_,ord,True.intro⟩
  4748. rcases suc.2.1 with f|b
  4749. · exact .inl (reflect_port hr cap _ _ _ (both .anchor .successor) f)
  4750. · exact .inr (reflect_port hr cap _ _ _ (both .successor .anchor) b)
  4751. next noReturn =>
  4752. rw [if_neg noReturn]
  4753. have ord := rel [(e.a.owner,0),(e.b.owner,0)] (by simp [roles]) suc.2
  4754. refine ⟨?_,ord⟩
  4755. change (if endOfRow ts e.a then sendNode d e.down else
  4756. if ts.oddRow e.a.tag then sendNode d e.left else sendNode d e.right) = sendNode d e.b
  4757. have eq := suc.1
  4758. cases row : endOfRow ts e.a <;> cases parity : ts.oddRow e.a.tag <;>
  4759. simp only [row,parity,Bool.false_eq_true,if_false,if_true] at eq ⊢ <;>
  4760. exact congrArg (sendNode d) eq
  4761. /-- A guarded source seed on the owner of either marked endpoint supplies
  4762. every active record used above. No map of the tester alphabet is assumed. -/
  4763. theorem edge_source_of_seed {r allow mark v h l k seed J} (hr : 0 < r)
  4764. (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k)) (ts : Tiles) (e : EdgeCertificate)
  4765. (ok : Holds r allow mark (l ++ v.flatMap h ++ k) (e.query ts))
  4766. (startAtSecond : Bool)
  4767. (start : Supplies v h r seed (if startAtSecond then e.b.owner else e.a.owner))
  4768. (guard : Guard r allow mark v seed J) (budget : 4 ≤ J) :
  4769. Holds r allow (endpointMarks (donor v h r) e) v ((sendEdge (donor v h r) e).query ts) := by
  4770. apply edge_source hr cap ts e _ ok
  4771. intro n active y hy
  4772. have role : y = n.owner ∨ y = n.mate := by simpa [roles] using hy
  4773. obtain ⟨a,b⟩ := edge_reach cap ts e ok active role
  4774. have near : Near r allow mark (l ++ v.flatMap h ++ k)
  4775. (if startAtSecond then e.b.owner else e.a.owner) y 4 := by cases startAtSecond <;> assumption
  4776. exact (lift_near hr cap start guard budget near).1
  4777. /-- Starting at a mate rather than an owner costs one record contact.
  4778. Only a donor for this one chosen occurrence label is needed. -/
  4779. theorem edge_source_from_role {r allow mark v h l k seed J} (hr : 0 < r)
  4780. (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k)) (ts : Tiles) (e : EdgeCertificate)
  4781. (ok : Holds r allow mark (l ++ v.flatMap h ++ k) (e.query ts))
  4782. (atSecond atMate : Bool)
  4783. (start : let a := if atSecond then e.b else e.a
  4784. Supplies v h r seed (if atMate then a.mate else a.owner))
  4785. (guard : Guard r allow mark v seed J) (budget : (if atMate then 5 else 4) ≤ J) :
  4786. Holds r allow (endpointMarks (donor v h r) e) v ((sendEdge (donor v h r) e).query ts) := by
  4787. cases atMate with
  4788. | false =>
  4789. cases atSecond
  4790. · exact edge_source_of_seed hr cap ts e ok false start guard budget
  4791. · exact edge_source_of_seed hr cap ts e ok true start guard budget
  4792. | true =>
  4793. apply edge_source hr cap ts e _ ok
  4794. intro n active y hy
  4795. have role : y = n.owner ∨ y = n.mate := by simpa [roles] using hy
  4796. obtain ⟨a,b⟩ := edge_reach cap ts e ok active role
  4797. cases atSecond
  4798. · have step := (record_pair (marked_typed ok.1)).2
  4799. exact (lift_near hr cap start guard budget (near_trans step a)).1
  4800. · have step := (record_pair (marked_typed ok.2.1)).2
  4801. exact (lift_near hr cap start guard budget (near_trans step b)).1
  4802. end P455EdgeSource
  4803. end
  4804. /- Begin Problem455RealizerClass (from finite-semigroup-identity-bases). -/
  4805. section
  4806. namespace P455ClassPrim
  4807. open P455EffectiveQ P455GraphPrim
  4808. variable {A : Type} [Primcodable A]
  4809. abbrev Raw := Option W
  4810. theorem live {e : A → W → W → Bool} (he : Primrec (fun x : A×(W×W) => e x.1 x.2.1 x.2.2))
  4811. {T : A → W} {z : A → Raw} (ht : Primrec T) (hz : Primrec z) :
  4812. Primrec fun a => liveB (e a) (T a) (z a) := by
  4813. let h (a : A) (w : W) := goodB (e a) (T a) w
  4814. have recProof : Primrec₂ h :=
  4815. Primrec₂.mk (good (A := A × W) (e := fun q => e q.1)
  4816. (he.comp (Primrec.pair (Primrec.fst.comp Primrec.fst) Primrec.snd))
  4817. (ht.comp Primrec.fst) Primrec.snd)
  4818. exact (Primrec.option_casesOn hz (Primrec.const false) recProof).of_eq
  4819. (fun a => by cases z a <;> rfl)
  4820. theorem pairedRec {e : A → W → W → Bool} (he : Primrec (fun x : A×(W×W) => e x.1 x.2.1 x.2.2))
  4821. {T : A → W} {x y : A → Raw} (ht : Primrec T) (hx : Primrec x) (hy : Primrec y) :
  4822. Primrec fun a => paired (e a) (T a) (x a) (y a) := by
  4823. let inside (a : A) (u v : W) := goodB (e a) (T a) u && goodB (e a) (T a) v && walkB (e a) u v
  4824. have ep : Primrec (fun p : ((A×W)×W)×(W×W) => e p.1.1.1 p.2.1 p.2.2) :=
  4825. he.comp (Primrec.pair (Primrec.fst.comp (Primrec.fst.comp Primrec.fst)) Primrec.snd)
  4826. have rr : Primrec (fun p : (A×W)×W => inside p.1.1 p.1.2 p.2) :=
  4827. Primrec.and.comp (Primrec.and.comp
  4828. (good (A := (A×W)×W) (e := fun p => e p.1.1) ep (ht.comp (Primrec.fst.comp Primrec.fst))
  4829. (Primrec.snd.comp Primrec.fst))
  4830. (good (A := (A×W)×W) (e := fun p => e p.1.1) ep (ht.comp (Primrec.fst.comp Primrec.fst)) Primrec.snd))
  4831. (reachable (A := (A×W)×W) (e := fun p => e p.1.1) ep (Primrec.snd.comp Primrec.fst) Primrec.snd)
  4832. let tail (a : A) (u : W) : Bool := Option.casesOn (y a) false (inside a u)
  4833. have tr : Primrec₂ tail := Primrec₂.mk
  4834. (Primrec.option_casesOn (hy.comp Primrec.fst) (Primrec.const false) rr.to₂)
  4835. exact (Primrec.option_casesOn hx (Primrec.const false) tr).of_eq
  4836. (fun a => by cases x a <;> cases h : y a <;> simp [tail,inside,h,paired])
  4837. theorem relation {e : A → W → W → Bool} (he : Primrec (fun x : A×(W×W) => e x.1 x.2.1 x.2.2))
  4838. {T : A → W} {x y : A → Raw} (ht : Primrec T) (hx : Primrec x) (hy : Primrec y) :
  4839. Primrec fun a => relB (e a) (T a) (x a) (y a) :=
  4840. Primrec.or.comp (Primrec.and.comp (Primrec.not.comp (live he ht hx)) (Primrec.not.comp (live he ht hy)))
  4841. (pairedRec he ht hx hy)
  4842. end P455ClassPrim
  4843. end
  4844. /- Begin Problem455RealizerFrameOps (from finite-semigroup-identity-bases). -/
  4845. section
  4846. namespace P455FramePrim
  4847. open P455Closure P455EffectiveQ P455GraphPrim
  4848. abbrev Tag := List Bool
  4849. abbrev Marks := List (Nat×Nat)
  4850. abbrev PairList := List (List Nat×Bool)
  4851. abbrev FrameData := Nat × W × W × Nat × Tag × PairList × W × W × W
  4852. def packing : Frame Nat ≃ FrameData where
  4853. toFun f := (f.pHead,f.pTail,f.qInit,f.qLast,f.tag,f.middle,f.beforeMutable,f.beforeFinalP,f.beforeFinalQ)
  4854. invFun d := ⟨d.1,d.2.1,d.2.2.1,d.2.2.2.1,d.2.2.2.2.1,d.2.2.2.2.2.1,d.2.2.2.2.2.2.1,
  4855. d.2.2.2.2.2.2.2.1,d.2.2.2.2.2.2.2.2⟩
  4856. left_inv _ := rfl
  4857. right_inv _ := rfl
  4858. instance framePrimcodable : Primcodable (Frame Nat) := Primcodable.ofEquiv _ packing
  4859. theorem pack : Primrec packing := Primrec.of_equiv
  4860. theorem unpack : Primrec packing.symm := Primrec.of_equiv_symm
  4861. variable {A B C : Type} [Primcodable A] [Primcodable B] [Primcodable C]
  4862. theorem allB {l : A → List B} {p : A → B → Bool} (hl : Primrec l) (hp : Primrec₂ p) :
  4863. Primrec fun a => (l a).all (p a) := by
  4864. apply (Primrec.not.comp (anyB hl (Primrec.not.comp₂ hp))).of_eq
  4865. intro a; simp only [List.not_any_eq_all_not,Bool.not_not]
  4866. theorem countN {z : A → Nat} {l : A → W} (hz : Primrec z) (hl : Primrec l) :
  4867. Primrec fun a => (l a).count (z a) := by
  4868. apply (Primrec.list_length.comp (P455GraphPrim.filter hl
  4869. ((Primrec.beq.comp Primrec.snd (hz.comp Primrec.fst)).to₂))).of_eq
  4870. intro a
  4871. simp [List.count_eq_countP,List.countP_eq_length_filter,BEq.comm]
  4872. theorem nodup {l : A → W} (hl : Primrec l) : Primrec fun a => decide (l a).Nodup := by
  4873. apply (allB hl ((Primrec.eq.comp (countN Primrec.snd (hl.comp Primrec.fst)) (.const 1)).decide.to₂)).of_eq
  4874. intro a
  4875. apply Bool.eq_iff_iff.mpr
  4876. simp only [List.all_eq_true,decide_eq_true_eq,List.nodup_iff_count_eq_one]
  4877. theorem singleton {v : A → B} (hv : Primrec v) : Primrec fun a => [v a] := Primrec.list_cons.comp hv (.const [])
  4878. theorem pairs : Primrec phasePair :=
  4879. Primrec.list_cons.comp Primrec.id (singleton Primrec.not)
  4880. theorem phases : Primrec fixedPhases :=
  4881. Primrec.list_append.comp (Primrec.list_append.comp (.const _) (Primrec.list_flatMap Primrec.id (pairs.comp₂ .right))) (.const _)
  4882. theorem pHead : Primrec (@Frame.pHead Nat) := (Primrec.fst.comp pack)
  4883. theorem pTail : Primrec (@Frame.pTail Nat) := (Primrec.fst.comp (Primrec.snd.comp pack))
  4884. theorem qInit : Primrec (@Frame.qInit Nat) := (Primrec.fst.comp (Primrec.snd.comp (Primrec.snd.comp pack)))
  4885. theorem qLast : Primrec (@Frame.qLast Nat) := (Primrec.fst.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp pack))))
  4886. theorem tag : Primrec (@Frame.tag Nat) := (Primrec.fst.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp pack)))))
  4887. theorem middle : Primrec (@Frame.middle Nat) := (Primrec.fst.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp pack))))))
  4888. theorem beforeMutable : Primrec (@Frame.beforeMutable Nat) := (Primrec.fst.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp pack)))))))
  4889. theorem beforeFinalP : Primrec (@Frame.beforeFinalP Nat) := (Primrec.fst.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp pack))))))))
  4890. theorem beforeFinalQ : Primrec (@Frame.beforeFinalQ Nat) := (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp pack))))))))
  4891. theorem p : Primrec (@Frame.p Nat) := Primrec.list_cons.comp pHead pTail
  4892. theorem q : Primrec (@Frame.q Nat) := Primrec.list_append.comp qInit (singleton qLast)
  4893. theorem early : Primrec (@Frame.early Nat) :=
  4894. Primrec.list_append.comp (Primrec.list_append.comp (Primrec.list_append.comp (Primrec.list_append.comp
  4895. (Primrec.list_append.comp p p) q) p) q) q
  4896. theorem mid : Primrec (@Frame.mid Nat) := Primrec.list_flatMap middle <| Primrec₂.mk <|
  4897. Primrec.list_append.comp (Primrec.fst.comp Primrec.snd)
  4898. (Primrec.ite (Primrec.eq.comp (Primrec.snd.comp Primrec.snd) (.const true))
  4899. (q.comp Primrec.fst) (p.comp Primrec.fst))
  4900. theorem pairCore : Primrec₂ (@Frame.pair Nat) := Primrec₂.mk <|
  4901. Primrec.ite (Primrec.eq.comp Primrec.snd (.const true))
  4902. (Primrec.list_append.comp (q.comp Primrec.fst) (p.comp Primrec.fst))
  4903. (Primrec.list_append.comp (p.comp Primrec.fst) (q.comp Primrec.fst))
  4904. theorem core : Primrec₂ (@Frame.core Nat) := Primrec₂.mk <|
  4905. (Primrec.list_append.comp (Primrec.list_append.comp (Primrec.list_append.comp (Primrec.list_append.comp (Primrec.list_append.comp (Primrec.list_append.comp (Primrec.list_append.comp (early.comp Primrec.fst) (mid.comp Primrec.fst)) (beforeMutable.comp Primrec.fst)) (pairCore.comp Primrec.fst Primrec.snd)) (beforeFinalP.comp Primrec.fst)) (p.comp Primrec.fst)) (beforeFinalQ.comp Primrec.fst)) (q.comp Primrec.fst))
  4906. end P455FramePrim
  4907. end
  4908. /- Begin Problem455MachineTrace (from finite-semigroup-identity-bases). -/
  4909. section
  4910. namespace P455MachineTable
  4911. open P455MachineLocal P455PaddedTiles
  4912. private theorem left_agree {u v : Nat→Fin n} {w x : Nat} (hx : x<w) (eq : ∀ j,j<w→u j=v j) :
  4913. leftAt u x=leftAt v x := by
  4914. by_cases e : x=0 <;> simp [leftAt,e,eq (x-1) (by omega)]
  4915. private theorem right_agree {u v : Nat→Fin n} {w x : Nat} (hx : x<w) (eq : ∀ j,j<w→u j=v j) :
  4916. rightAt u w x=rightAt v w x := by
  4917. by_cases e : x+1=w
  4918. · simp [rightAt,e]
  4919. · simp [rightAt,e,eq _ (by omega : x+1<w)]
  4920. private theorem next_inside {d : Direction} {p w : Nat} (hp : p<w) (safe : ¬exits d w p) : dest d p<w := by
  4921. cases d <;> simp [exits,dest] at * <;> omega
  4922. theorem agrees (M : TM g q) {w s : Nat} (T : AcceptingTrace (compile M) w s) :
  4923. ∀ t,t≤s → (run M t).pos<w ∧ ∀ x,x<w → T.rows t x=row M t x := by
  4924. intro t; induction t with
  4925. | zero =>
  4926. intro _
  4927. refine ⟨T.positive,?_⟩
  4928. intro x hx
  4929. rw [T.start x hx]
  4930. by_cases e : x=0 <;> simp [compile,row,run,init,atCell,e]
  4931. | succ t ih =>
  4932. intro st
  4933. obtain ⟨hp,eq⟩ := ih (by omega)
  4934. have moves (x : Nat) (hx : x<w) :=
  4935. T.steps t (by omega) x hx
  4936. have atStep (x : Nat) (hx : x<w) :
  4937. (compile M).next (leftAt (row M t) x) (row M t x) (rightAt (row M t) w x)=some (T.rows (t+1) x) := by
  4938. simpa only [left_agree hx eq,right_agree hx eq,eq x hx] using moves x hx
  4939. let p := (run M t).pos
  4940. let z := (run M t).state
  4941. let tape := (run M t).tape
  4942. have safe : ¬exits (M.delta z (tape p)).dir w p := by
  4943. intro bad
  4944. have e := (defined_at_head M.delta tape w p z hp).mpr bad
  4945. have observed := atStep p hp
  4946. change (update M.delta _ (dec M (enc _)) _).map enc=_ at observed
  4947. rw [left_dec,right_dec,dec_enc] at observed
  4948. change (update M.delta (leftOf (atCell tape p z) p) (atCell tape p z p) (rightOf (atCell tape p z) w p)).map enc=_ at observed
  4949. rw [e] at observed
  4950. contradiction
  4951. refine ⟨next_inside hp safe,?_⟩
  4952. intro x hx
  4953. exact Option.some.inj ((atStep x hx).symm.trans (local_value M t w x hp safe hx))
  4954. def Genuine (M : TM g q) (t : Nat) := (run M t).pos=0 ∧ (run M t).state=M.accept
  4955. theorem genuine_of_trace (M : TM g q) {w s : Nat} (T : AcceptingTrace (compile M) w s) : Genuine M s := by
  4956. have eq := ((agrees M T s (by omega)).2 0 T.positive).symm.trans T.accept
  4957. have old := enc_inj M eq
  4958. change atCell (run M s).tape (run M s).pos (run M s).state 0=⟨M.marker,some M.accept⟩ at old
  4959. have head := congrArg Cell.head old
  4960. by_cases e : (run M s).pos=0
  4961. · exact ⟨e,by simpa [atCell,e] using head⟩
  4962. · simp [atCell,Ne.symm e] at head
  4963. theorem fixed_accept (M : TM g q) {s : Nat} (accepts : Genuine M s) : run M (s+1)=run M s := by
  4964. have fixedCfg (c : Config g q) (at0 : c.pos=0) (state : c.state=M.accept) (eq0 : c.tape 0=M.marker) :
  4965. step M c=c := by
  4966. cases c with
  4967. | mk tape pos st =>
  4968. change pos=0 at at0; change st=M.accept at state
  4969. subst pos; subst st
  4970. change tape 0=M.marker at eq0
  4971. have fixed : writeAt tape 0 M.marker=tape := by funext x; by_cases e : x=0 <;> simp [writeAt,e,eq0]
  4972. simp [step,eq0,M.stationary,dest,fixed]
  4973. exact fixedCfg (run M s) accepts.1 accepts.2 ((marker_iff M s 0).mpr rfl)
  4974. private theorem same_value (M : TM g q) {s : Nat} (genuine : Genuine M s) (x : Nat) :
  4975. row M (s+1) x=row M s x := by unfold row; rw [fixed_accept M genuine]
  4976. /-- Every accepting trace of a compiled machine supplies its own full-row
  4977. stutter, including the unwritten cells and both strip boundaries. -/
  4978. theorem trace_stutters (M : TM g q) {w s : Nat} (T : AcceptingTrace (compile M) w s) :
  4979. ∀ x,x<w → (compile M).next (leftAt (T.rows s) x) (T.rows s x) (rightAt (T.rows s) w x)=some (T.rows s x) := by
  4980. have ⟨hp,eq⟩ := agrees M T s (by omega)
  4981. have g := genuine_of_trace M T
  4982. have safe : ¬exits (M.delta (run M s).state ((run M s).tape (run M s).pos)).dir w (run M s).pos := by
  4983. simp [g.1,g.2,(marker_iff M s 0).mpr rfl,M.stationary,exits]
  4984. intro x hx
  4985. rw [left_agree hx eq,right_agree hx eq,eq x hx,local_value M s w x hp safe hx,same_value M g]
  4986. theorem trace_of_genuine (M : TM g q) {s : Nat} (g : Genuine M s) : Nonempty (AcceptingTrace (compile M) (s+2) s) := by
  4987. refine ⟨⟨by omega,row M,?_,?_,?_,?_⟩⟩
  4988. · intro x _; by_cases e : x=0 <;> simp [row,run,init,atCell,compile,e]
  4989. · intro y _ x _; simp only [compile,row,dec_enc,atCell]
  4990. by_cases e : x=0
  4991. · simp [e,(marker_iff M y 0).mpr rfl]
  4992. · have f : (run M y).tape x ≠ M.marker := fun h=>e ((marker_iff M y x).mp h)
  4993. simp [e,f]
  4994. · intro y hy x hx; exact local_value M _ _ _ (by have := head_bound M y; omega) (physical_safe M (by omega)) hx
  4995. · simp [row,compile,atCell,g.1,g.2,(marker_iff M s 0).mpr rfl]
  4996. theorem trace_iff (M : TM g q) : (∃ t,Genuine M t) ↔ ∃ w s, Nonempty (AcceptingTrace (compile M) w s) := by
  4997. constructor
  4998. · rintro ⟨s,g⟩; exact ⟨_,s,trace_of_genuine M g⟩
  4999. · rintro ⟨w,s,⟨T⟩⟩; exact ⟨s,genuine_of_trace M T⟩
  5000. theorem rectangles_iff (M : TM g q) : (∃ t,Genuine M t) ↔
  5001. ∃ w, ∀ k, ∃ h, 1<h ∧ k<2*(w*h) ∧ Nonempty (Rectangle (compile M) w h) :=
  5002. (trace_iff M).trans (trace_iff_rectangles (fun T => trace_stutters M T))
  5003. end P455MachineTable
  5004. end
  5005. /- Begin Problem455OriginalWalk (from finite-semigroup-identity-bases). -/
  5006. section
  5007. /- End-to-end transport of a designated marked-word path to its original
  5008. word after expanding the small rule's gaps. Both valuations may use the
  5009. same Nat name for unrelated alphabet entries. Only e expands the rule;
  5010. h supplies the actual tester representatives. -/
  5011. namespace P455OriginalWalk
  5012. open Problem455.Slots P455Witness P455Paths P455ContactLift P455Retained
  5013. def OriginalGuard (r : Nat) (allow : Tag → Prop) (mark : Marking) (u : W)
  5014. (kept : Nat → Prop) (seed J : Nat) : Prop :=
  5015. ∀ x, Near r allow mark u seed x J →
  5016. kept x ∧ ∀ i, slotStart i → ∀ y, occupies u x i y → kept y ∧ u.count y = r
  5017. /-- Every output step of the recorded list is read in the original once its
  5018. reached labels are replaced by their unique donors. No injectivity of the
  5019. entire reached-label map is asserted. -/
  5020. theorem lift_walk {v e kept r allow mark seed J h l k s}
  5021. (exp : Expansion v e kept) (hr : 1 < r) (capU : P455Closure.Cap r (v.flatMap e))
  5022. (original : OriginalGuard r allow mark (v.flatMap e) kept seed J)
  5023. (capZ : P455Closure.Cap r (l ++ v.flatMap h ++ k)) (start : Supplies v h r seed s)
  5024. (p : List Step) (len : p.length ≤ J)
  5025. (walk : Walk r allow mark (l ++ v.flatMap h ++ k) s p) :
  5026. let d := donor v h r
  5027. let y := d (endpoint s p)
  5028. Walk r allow mark (v.flatMap e) seed (relabel d p) ∧
  5029. endpoint seed (relabel d p) = y ∧ (relabel d p).length = p.length ∧ kept y ∧
  5030. Supplies v h r y (endpoint s p) ∧ Supplies (v.flatMap e) h r y (endpoint s p) := by
  5031. let d := donor v h r
  5032. have pos : 0 < r := by omega
  5033. have eq : d s = seed := donor_eq pos (factor_cap capZ) start
  5034. obtain ⟨small,supply⟩ := P455ContactLift.lift_walk pos capZ start (exp.guard hr capU original) p len walk
  5035. have large := exp.walk hr capU seed _ small
  5036. have ep : endpoint seed (relabel d p) = d (endpoint s p) := by rw [← eq,endpoint_relabel]
  5037. have lp : (relabel d p).length = p.length := by simp [relabel]
  5038. have reach : Near r allow mark (v.flatMap e) seed (d (endpoint s p)) J :=
  5039. ⟨relabel d p,large,ep,lp ▸ len⟩
  5040. have ky := (original _ reach).1
  5041. exact ⟨large,ep,lp,ky,supply,(exp.count_eq v (fun _ h => h) _ ky).trans supply.1,supply.2⟩
  5042. theorem lift_near {v e kept r allow mark seed J h l k s a n}
  5043. (exp : Expansion v e kept) (hr : 1 < r) (capU : P455Closure.Cap r (v.flatMap e))
  5044. (original : OriginalGuard r allow mark (v.flatMap e) kept seed J)
  5045. (capZ : P455Closure.Cap r (l ++ v.flatMap h ++ k)) (start : Supplies v h r seed s)
  5046. (bound : n ≤ J) (near : Near r allow mark (l ++ v.flatMap h ++ k) s a n) :
  5047. let y := donor v h r a
  5048. Near r allow mark (v.flatMap e) seed y n ∧ kept y ∧
  5049. Supplies v h r y a ∧ Supplies (v.flatMap e) h r y a := by
  5050. obtain ⟨p,walk,ea,len⟩ := near
  5051. obtain ⟨w,ep,lp,kp,small,full⟩ := lift_walk exp hr capU original capZ start p (Nat.le_trans len bound) walk
  5052. rw [ea] at ep kp small full
  5053. exact ⟨⟨_,w,ep,lp ▸ len⟩,kp,small,full⟩
  5054. end P455OriginalWalk
  5055. end
  5056. /- Begin Problem455OriginalEdges (from finite-semigroup-identity-bases). -/
  5057. section
  5058. namespace P455OriginalEdges
  5059. open Problem455.Slots P455Witness P455Paths P455Retained P455PortReflection
  5060. section
  5061. variable {r : Nat} {v : W} {e : Nat → W} {kept : Nat → Prop}
  5062. {allow : Tag → Prop} {mark : Marking}
  5063. theorem kept_roles (exp : Expansion v e kept) (hr : 1 < r) (cap : P455Closure.Cap r (v.flatMap e))
  5064. {a : Node} (recProof : Holds r allow mark v (typedNode a)) : ∀ x ∈ roles a, kept x := by
  5065. obtain ⟨cnt,cn'⟩ := record_counts (exp.small_cap hr cap) recProof
  5066. intro x hx
  5067. have ct : v.count x = r := by
  5068. rcases (show x = a.owner ∨ x = a.mate by simpa [roles] using hx) with eq|eq
  5069. · exact eq ▸ cnt
  5070. · exact eq ▸ cn'
  5071. apply Classical.byContradiction
  5072. intro gap
  5073. have := (exp.gaps x (List.count_pos_iff.mp (by omega)) gap).1
  5074. omega
  5075. theorem expand_markedNode (exp : Expansion v e kept) (hr : 1 < r) (cap : P455Closure.Cap r (v.flatMap e))
  5076. {a : Node} {bit : Bool} (recProof : Holds r allow mark v (markedNode a bit)) :
  5077. Holds r allow mark (v.flatMap e) (markedNode a bit) := by
  5078. have eq := exp.select_eq v (roles a) (fun _ h => h) (kept_roles exp hr cap (marked_typed recProof))
  5079. exact ⟨recProof.1,recProof.2.1,recProof.2.2.1,recProof.2.2.2.1,eq.trans recProof.2.2.2.2⟩
  5080. theorem expand_typedNode (exp : Expansion v e kept) (hr : 1 < r) (cap : P455Closure.Cap r (v.flatMap e))
  5081. {a : Node} (recProof : Holds r allow mark v (typedNode a)) : Holds r allow mark (v.flatMap e) (typedNode a) :=
  5082. exp.contact hr cap (.record a.tag false) recProof
  5083. theorem expand_order (exp : Expansion v e kept) {p : List Event}
  5084. (labels : ∀ ev ∈ p, kept ev.1) (ord : Holds r allow mark v (.order p)) :
  5085. Holds r allow mark (v.flatMap e) (.order p) := by
  5086. let ks := p.map Prod.fst
  5087. have all : ∀ a ∈ ks, kept a := by
  5088. intro a h
  5089. obtain ⟨ev,he,rfl⟩ := List.mem_map.mp h
  5090. exact labels ev he
  5091. refine ⟨ord.1,P455ContactReflection.select_sees ks _ p ?_⟩
  5092. rw [exp.select_eq v ks (fun _ h => h) all]
  5093. exact P455ContactReflection.sees_select ks _ p (fun ev he => List.mem_map_of_mem he) ord.2
  5094. theorem expand_earlier (exp : Expansion v e kept) {a i b j}
  5095. (ha : kept a) (hb : kept b) (ord : Holds r allow mark v (earlier a i b j)) :
  5096. Holds r allow mark (v.flatMap e) (earlier a i b j) :=
  5097. expand_order exp (by simp [ha,hb]) ord
  5098. theorem expand_port (exp : Expansion v e kept) (hr : 1 < r) (cap : P455Closure.Cap r (v.flatMap e))
  5099. {p : Nat} {a b : Node} (port : Holds r allow mark v (orientedPort p a b)) :
  5100. Holds r allow mark (v.flatMap e) (orientedPort p a b) := by
  5101. obtain ⟨ra,rb,early,order,_⟩ := port
  5102. have ka := kept_roles exp hr cap ra
  5103. have kb := kept_roles exp hr cap rb
  5104. have earl {xs ys : W} (kx : ∀ a ∈ xs, kept a) (ky : ∀ a ∈ ys, kept a)
  5105. (obs : Holds r allow mark v (earlyBefore xs ys)) :
  5106. Holds r allow mark (v.flatMap e) (earlyBefore xs ys) := by
  5107. apply (earlyBefore_iff _ _).mpr
  5108. exact fun a ha b hb => expand_earlier exp (kx a ha) (ky b hb) ((earlyBefore_iff _ _).mp obs a ha b hb)
  5109. refine ⟨expand_typedNode exp hr cap ra,expand_typedNode exp hr cap rb,?_,?_,True.intro⟩
  5110. · exact early.elim (fun h => Or.inl (earl ka kb h)) (fun h => Or.inr (earl kb ka h))
  5111. · have ka' : kept a.owner ∧ kept a.mate := by simpa [roles] using ka
  5112. have kb' : kept b.owner ∧ kept b.mate := by simpa [roles] using kb
  5113. exact expand_order exp (by simp [ka'.1,ka'.2,kb'.1,kb'.2]) order
  5114. theorem expand_right (exp : Expansion v e kept) (hr : 1 < r) (cap : P455Closure.Cap r (v.flatMap e))
  5115. {ts : Tiles} {a b : Node} (q : Holds r allow mark v (rightward ts a b)) :
  5116. Holds r allow mark (v.flatMap e) (rightward ts a b) := by
  5117. have p := q.2.1
  5118. exact ⟨q.1,expand_port exp hr cap p,expand_earlier exp (kept_roles exp hr cap p.1 _ (by simp [roles]))
  5119. (kept_roles exp hr cap p.2.1 _ (by simp [roles])) q.2.2.1,True.intro⟩
  5120. theorem expand_down (exp : Expansion v e kept) (hr : 1 < r) (cap : P455Closure.Cap r (v.flatMap e))
  5121. {ts : Tiles} {a b : Node} (q : Holds r allow mark v (downward ts a b)) :
  5122. Holds r allow mark (v.flatMap e) (downward ts a b) := ⟨q.1,expand_port exp hr cap q.2⟩
  5123. theorem expand_neighbor (exp : Expansion v e kept) (hr : 1 < r) (cap : P455Closure.Cap r (v.flatMap e))
  5124. {ts : Tiles} {a b : Node} (d : Dir) (q : Holds r allow mark v (neighbor ts a b d)) :
  5125. Holds r allow mark (v.flatMap e) (neighbor ts a b d) := by
  5126. cases d with
  5127. | right => exact expand_right exp hr cap q
  5128. | left => exact expand_right exp hr cap q
  5129. | down => exact expand_down exp hr cap q
  5130. | up => exact expand_down exp hr cap q
  5131. private theorem flag {b : Bool} {q : Query}
  5132. (f : Holds r allow mark v q → Holds r allow mark (v.flatMap e) q)
  5133. (h : Holds r allow mark v (flagQ b q)) : Holds r allow mark (v.flatMap e) (flagQ b q) := by
  5134. cases b
  5135. · exact True.intro
  5136. · exact f h
  5137. theorem expand_edge (exp : Expansion v e kept) (hr : 1 < r) (cap : P455Closure.Cap r (v.flatMap e))
  5138. {ts : Tiles} {edge : EdgeCertificate} (query : Holds r allow mark v (edge.query ts)) :
  5139. Holds r allow mark (v.flatMap e) (edge.query ts) := by
  5140. obtain ⟨a,b,localQ,succ,_⟩ := query
  5141. refine ⟨expand_markedNode exp hr cap a,expand_markedNode exp hr cap b,?_,?_,True.intro⟩
  5142. · exact ⟨flag (expand_right exp hr cap) localQ.1,flag (expand_right exp hr cap) localQ.2.1,
  5143. flag (expand_down exp hr cap) localQ.2.2.1,flag (expand_down exp hr cap) localQ.2.2.2.1,
  5144. flag (fun ⟨d,r⟩ => ⟨expand_down exp hr cap d,expand_right exp hr cap r⟩) localQ.2.2.2.2.1,
  5145. True.intro⟩
  5146. · have ka : kept edge.a.owner := kept_roles exp hr cap (marked_typed a) _ (by simp [roles])
  5147. have kb : kept edge.b.owner := kept_roles exp hr cap (marked_typed b) _ (by simp [roles])
  5148. unfold chosenSuccessor at succ ⊢
  5149. dsimp only at succ ⊢
  5150. split at succ
  5151. next ret =>
  5152. rw [if_pos ret]
  5153. exact ⟨succ.1,succ.2.1.elim (fun f => Or.inl (expand_port exp hr cap f))
  5154. (fun b => Or.inr (expand_port exp hr cap b)),expand_earlier exp kb ka succ.2.2.1,True.intro⟩
  5155. next notRet =>
  5156. rw [if_neg notRet]
  5157. exact ⟨succ.1,expand_earlier exp ka kb succ.2⟩
  5158. end
  5159. end P455OriginalEdges
  5160. end
  5161. /- Begin Problem455Compression (from finite-semigroup-identity-bases). -/
  5162. section
  5163. namespace P455Compression
  5164. open P455Witness P455Retained
  5165. inductive Piece where
  5166. | literal (a : Nat)
  5167. | gap (w : W)
  5168. deriving DecidableEq
  5169. def body : Piece → W | .literal a => [a] | .gap w => w
  5170. def prependOutside (a : Nat) : List Piece → List Piece
  5171. | .gap w :: tail => .gap (a::w) :: tail
  5172. | cs => .gap [a] :: cs
  5173. def pieces (names : W) : W → List Piece
  5174. | [] => []
  5175. | a :: u =>
  5176. let rest := pieces names u
  5177. if a ∈ names then .literal a :: rest else prependOutside a rest
  5178. def good (names : W) : Piece → Prop
  5179. | .literal a => a ∈ names
  5180. | .gap w => w ≠ [] ∧ ∀ a ∈ w, a ∉ names
  5181. /-- Adjacency of gap pieces is prohibited; with good and exact decoding this
  5182. expresses maximality of every omitted run, also at the two ends. -/
  5183. def noTouch : List Piece → Prop
  5184. | .gap _ :: .gap _ :: _ => False
  5185. | _ :: tail => noTouch tail
  5186. | [] => True
  5187. private theorem prepend_body (a : Nat) (cs : List Piece) :
  5188. (prependOutside a cs).flatMap body = a :: cs.flatMap body := by
  5189. cases cs with
  5190. | nil => rfl
  5191. | cons p tail => cases p <;> rfl
  5192. theorem decoded (names u : W) : (pieces names u).flatMap body = u := by
  5193. induction u with
  5194. | nil => rfl
  5195. | cons a u ih =>
  5196. by_cases c : a ∈ names
  5197. · simp [pieces,c,body,ih]
  5198. · simp [pieces,c,prepend_body,ih]
  5199. private theorem prepend_good {a : Nat} {cs : List Piece} {names : W} (ha : a ∉ names)
  5200. (all : ∀ c ∈ cs, good names c) : ∀ c ∈ prependOutside a cs, good names c := by
  5201. cases cs with
  5202. | nil => simp [prependOutside,good,ha]
  5203. | cons p tail =>
  5204. cases p with
  5205. | literal b => simp [prependOutside,good,ha] at *; exact all
  5206. | gap w =>
  5207. have h := all (.gap w) (by simp)
  5208. simp only [good] at h
  5209. simp only [prependOutside,List.forall_mem_cons,good,List.cons_ne_nil,not_false_eq_true,true_and]
  5210. exact ⟨⟨by simp,ha,h.2⟩,fun c hc => all c (by simp [hc])⟩
  5211. theorem pieces_good (names u : W) : ∀ c ∈ pieces names u, good names c := by
  5212. induction u with
  5213. | nil => simp [pieces]
  5214. | cons a u ih =>
  5215. by_cases k : a ∈ names
  5216. · simp only [pieces,if_pos k,List.forall_mem_cons]
  5217. exact ⟨k,ih⟩
  5218. · simpa only [pieces,if_neg k] using prepend_good k ih
  5219. private theorem prepend_sep {cs : List Piece} (a : Nat) (ok : noTouch cs) :
  5220. noTouch (prependOutside a cs) := by
  5221. cases cs with
  5222. | nil => exact True.intro
  5223. | cons p tail =>
  5224. cases p with
  5225. | literal b => exact ok
  5226. | gap w => cases tail with
  5227. | nil => exact True.intro
  5228. | cons p' rest => cases p' <;> exact ok
  5229. theorem maximal (names u : W) : noTouch (pieces names u) := by
  5230. induction u with
  5231. | nil => exact True.intro
  5232. | cons a u ih =>
  5233. by_cases k : a ∈ names
  5234. · simpa only [pieces,if_pos k,noTouch] using ih
  5235. · simpa only [pieces,if_neg k] using prepend_sep a ih
  5236. /-- The numerical bound counts even retained names not occurring in u. -/
  5237. def base (u names : W) := u.sum + names.sum + 1
  5238. private theorem le_sum {a : Nat} {w : W} (ha : a ∈ w) : a ≤ w.sum := by
  5239. induction w with
  5240. | nil => simp at ha
  5241. | cons b w ih =>
  5242. simp only [List.sum_cons]
  5243. rcases List.mem_cons.mp ha with h|h
  5244. · omega
  5245. · have := ih h; omega
  5246. def code : Nat → List Piece → W
  5247. | _,[] => []
  5248. | n,.literal a :: cs => a :: code (n+1) cs
  5249. | n,.gap _ :: cs => n :: code (n+1) cs
  5250. def lookup : Nat → List Piece → Nat → W
  5251. | _,[],a => [a]
  5252. | n,.literal _ :: cs,a => lookup (n+1) cs a
  5253. | n,.gap w :: cs,a => if a=n then w else lookup (n+1) cs a
  5254. def small (u names : W) := code (base u names) (pieces names u)
  5255. def expand (u names : W) := lookup (base u names) (pieces names u)
  5256. private theorem low_fixed (cs : List Piece) (a n : Nat) (low : a < n) :
  5257. lookup n cs a = [a] := by
  5258. induction cs generalizing n with
  5259. | nil => rfl
  5260. | cons p cs ih =>
  5261. cases p <;> simp [lookup,show a ≠ n by omega,ih (n+1) (by omega)]
  5262. private theorem low_kept (cs : List Piece) (names : W)
  5263. (all : ∀ c ∈ cs, good names c) (a n : Nat) (low : a < n) (use : a ∈ code n cs) :
  5264. a ∈ names := by
  5265. induction cs generalizing n with
  5266. | nil => cases use
  5267. | cons c cs ih =>
  5268. have rest := ih (fun c hc => all c (by simp [hc])) (n+1) (by omega)
  5269. cases c with
  5270. | literal b =>
  5271. rcases List.mem_cons.mp use with eq|mem
  5272. · obtain rfl := eq; exact all (.literal a) (by simp)
  5273. · exact rest mem
  5274. | gap w =>
  5275. rcases List.mem_cons.mp use with eq|mem
  5276. · omega
  5277. · exact rest mem
  5278. private theorem decode_code (cs : List Piece) (names : W) (n : Nat)
  5279. (all : ∀ c ∈ cs, good names c) (large : ∀ a ∈ names, a < n) :
  5280. (code n cs).flatMap (lookup n cs) = cs.flatMap body := by
  5281. induction cs generalizing n with
  5282. | nil => rfl
  5283. | cons c cs ih =>
  5284. have goodTail (p) (hp : p ∈ cs) : good names p := all _ (by simp [hp])
  5285. have tail := ih (n+1) goodTail (fun a ha => by have := large a ha; omega)
  5286. cases c with
  5287. | literal a =>
  5288. have low := large a (all (.literal a) (by simp))
  5289. simp [code,lookup,low_fixed cs a (n+1) (by omega),body,tail]
  5290. | gap w =>
  5291. have miss : n ∉ code (n+1) cs := by
  5292. intro h
  5293. have := large n (low_kept cs names goodTail n (n+1) (by omega) h)
  5294. omega
  5295. have eq : (code (n+1) cs).flatMap (lookup n (.gap w :: cs)) =
  5296. (code (n+1) cs).flatMap (lookup (n+1) cs) := by
  5297. simp only [List.flatMap_def]
  5298. apply congrArg List.flatten
  5299. exact List.map_congr_left (fun a ha => by
  5300. have dif : a ≠ n := fun d => miss (d ▸ ha)
  5301. simp [lookup,dif])
  5302. change lookup n (.gap w::cs) n ++ (code (n+1) cs).flatMap _ = w ++ cs.flatMap body
  5303. rw [eq,tail]
  5304. simp [lookup]
  5305. private theorem gap_code (cs : List Piece) (names : W) (n : Nat)
  5306. (all : ∀ c ∈ cs, good names c) (large : ∀ a ∈ names, a < n) :
  5307. ∀ g ∈ code n cs, g ∉ names →
  5308. (code n cs).count g = 1 ∧ lookup n cs g ≠ [] ∧ ∀ a ∈ lookup n cs g, a ∉ names := by
  5309. induction cs generalizing n with
  5310. | nil => simp [code]
  5311. | cons c cs ih =>
  5312. intro g use outside
  5313. have goodTail (p) (hp : p ∈ cs) : good names p := all _ (by simp [hp])
  5314. have tail := ih (n+1) goodTail (fun a ha => by have := large a ha; omega) g
  5315. cases c with
  5316. | literal a =>
  5317. have dif : g ≠ a := fun d => outside (d ▸ all (.literal a) (by simp))
  5318. have occurs : g ∈ code (n+1) cs := by simpa [code,dif] using use
  5319. simpa [code,lookup,List.count_cons,dif,Ne.symm dif] using tail occurs outside
  5320. | gap w =>
  5321. by_cases same : g=n
  5322. · subst g
  5323. have miss : n ∉ code (n+1) cs := fun u =>
  5324. outside (low_kept cs names goodTail n (n+1) (by omega) u)
  5325. have gw := all (.gap w) (by simp)
  5326. simpa [code,lookup,List.count_cons,List.count_eq_zero.mpr miss,good] using gw
  5327. · have occurs : g ∈ code (n+1) cs := by simpa [code,same] using use
  5328. simpa [code,lookup,List.count_cons,same,Ne.symm same] using tail occurs outside
  5329. theorem recover (u names : W) : (small u names).flatMap (expand u names) = u :=
  5330. (decode_code (pieces names u) names (base u names) (pieces_good names u)
  5331. (fun a h => by have := le_sum h; unfold base; omega)).trans (decoded names u)
  5332. theorem canonical (u names : W) : Expansion (small u names) (expand u names) (fun a => a ∈ names) where
  5333. literal x _ kept := low_fixed _ _ _ (by have := le_sum kept; unfold base; omega)
  5334. gaps := gap_code (pieces names u) names (base u names) (pieces_good names u)
  5335. (fun a h => by have := le_sum h; unfold base; omega)
  5336. /-- Every generated gap name lies outside the original alphabet. -/
  5337. theorem gap_fresh (u names : W) (g : Nat) (use : g ∈ small u names) (unkept : g ∉ names) : g ∉ u := by
  5338. intro orig
  5339. apply unkept
  5340. apply low_kept (pieces names u) names (pieces_good names u) g (base u names) _ use
  5341. have := le_sum orig
  5342. unfold base; omega
  5343. theorem counts_retained (u names : W) (x : Nat) (hx : x ∈ names) :
  5344. (small u names).count x = u.count x := by
  5345. have c := (canonical u names).count_eq (small u names) (fun _ h => h) x hx
  5346. rw [recover] at c
  5347. exact c.symm
  5348. end P455Compression
  5349. end
  5350. /- Begin Problem455DefectProjection (from finite-semigroup-identity-bases). -/
  5351. section
  5352. namespace P455DefectProjection
  5353. open P455Witness P455Paths P455SourceFamilies Problem455.Slots
  5354. theorem select_sub (keep smaller u : W) (hs : ∀ a ∈ smaller, a ∈ keep) :
  5355. select smaller (select keep u) = select smaller u := by
  5356. induction u with
  5357. | nil => rfl
  5358. | cons x u ih =>
  5359. by_cases hx : x ∈ keep
  5360. · by_cases hm : x ∈ smaller <;> simp_all [select]
  5361. · have hm : x ∉ smaller := fun h => hx (hs _ h)
  5362. simp_all [select]
  5363. theorem select_count (keep u : W) (a : Nat) (mem : a ∈ keep) :
  5364. (select keep u).count a = u.count a :=
  5365. List.count_filter (by simpa using mem)
  5366. theorem select_cap {r u} (keep : W) (cap : P455Closure.Cap r u) :
  5367. P455Closure.Cap r (select keep u) := by
  5368. intro a
  5369. by_cases mem : a ∈ keep
  5370. · simpa only [select_count keep u _ mem] using cap a
  5371. · have missing : a ∉ select keep u := by simp [select,mem]
  5372. simp [List.count_eq_zero.mpr missing]
  5373. theorem select_order {r allow mark u} (keep : W) (pat : List Event)
  5374. (hs : ∀ e ∈ pat, e.1 ∈ keep) (obs : Holds r allow mark u (.order pat)) :
  5375. Holds r allow mark (select keep u) (.order pat) :=
  5376. ⟨obs.1, P455ContactReflection.sees_select keep u pat hs obs.2⟩
  5377. theorem select_marked {r allow mark u} (keep : W) (n : Node) (b : Bool)
  5378. (ho : n.owner ∈ keep) (hm : n.mate ∈ keep) (obs : Holds r allow mark u (markedNode n b)) :
  5379. Holds r allow mark (select keep u) (markedNode n b) := by
  5380. obtain ⟨ne,len,tag,mk,eq⟩ := obs
  5381. refine ⟨ne,len,tag,mk,(select_sub keep [n.owner,n.mate] u ?_).trans eq⟩
  5382. simpa using And.intro ho hm
  5383. theorem select_record {r allow mark u} (keep : W) (a b : Nat) (tag : Tag) (ha : a ∈ keep)
  5384. (hb : b ∈ keep) (obs : Holds r allow mark u (.record a b tag)) :
  5385. Holds r allow mark (select keep u) (.record a b tag) := by
  5386. obtain ⟨ne,len,ok,bit,eq⟩ := obs
  5387. exact ⟨ne,len,ok,bit,(select_sub keep [a,b] u (by simpa using And.intro ha hb)).trans eq⟩
  5388. theorem select_contact {r allow mark u} (keep : W) (a b : Nat) (c : ContactChoice)
  5389. (ha : a ∈ keep) (hb : b ∈ keep) (obs : Holds r allow mark u (contact r a b c)) :
  5390. Holds r allow mark (select keep u) (contact r a b c) := by
  5391. cases c with
  5392. | record tag rev =>
  5393. cases rev with
  5394. | false => exact select_record keep a b tag ha hb obs
  5395. | true => exact select_record keep b a tag hb ha obs
  5396. | port phase rev =>
  5397. obtain ⟨ab,ac,bc,early,order,endQ⟩ := obs
  5398. refine ⟨ab,(select_count keep u a ha).trans ac,(select_count keep u b hb).trans bc,?_,?_,endQ⟩
  5399. · rcases early with ⟨f,_⟩|⟨f,_⟩
  5400. · exact .inl ⟨select_order keep _ (by simpa using And.intro ha hb) f,True.intro⟩
  5401. · exact .inr ⟨select_order keep _ (by simpa using And.intro hb ha) f,True.intro⟩
  5402. · cases rev <;> apply select_order keep _ _ order <;> simp [ha,hb]
  5403. theorem select_walk {r allow mark u} (keep : W) (a : Nat) (p : List Step)
  5404. (ha : a ∈ keep) (hs : ∀ m ∈ p, m.1 ∈ keep) (w : Walk r allow mark u a p) :
  5405. Walk r allow mark (select keep u) a p := by
  5406. induction p generalizing a with
  5407. | nil => trivial
  5408. | cons bc rest ih =>
  5409. obtain ⟨b,c⟩ := bc
  5410. have hb := hs (b,c) (by simp)
  5411. exact ⟨select_contact keep a b c ha hb w.1,ih b hb (fun s h => hs s (by simp [h])) w.2⟩
  5412. theorem endpoint_kept (keep : W) (a : Nat) (p : List Step) (ha : a ∈ keep)
  5413. (hs : ∀ m ∈ p, m.1 ∈ keep) : endpoint a p ∈ keep := by
  5414. induction p generalizing a with
  5415. | nil => exact ha
  5416. | cons bc p ih => exact ih bc.1 (hs bc (by simp)) (fun s h => hs s (by simp [h]))
  5417. theorem select_slot {u : W} (keep : W) (t i b : Nat)
  5418. (ht : t ∈ keep) (hb : b ∈ keep) (obs : occupies u t i b) :
  5419. occupies (select keep u) t i b := by
  5420. obtain ⟨j,h⟩ := obs
  5421. exact ⟨j,P455ContactReflection.sees_select keep u _ (by simp [hb,ht]) h⟩
  5422. /-- A genuine slot component of alphabet size at most nine suffices for a
  5423. deficient occupant. The cap and all unchanged occurrence indices are
  5424. derived in the projection. Both orientations and length-zero routes
  5425. are allowed; the keep list can repeat names. -/
  5426. theorem bounded_defect_kind {r allow mark u} (cap : P455Closure.Cap r u) (n : Node) (bit side : Bool)
  5427. (t i bad : Nat) (anchor : Holds r allow (markNode n) u (markedNode n bit))
  5428. (near : Near r allow mark u (if side then n.mate else n.owner) t 6)
  5429. (slot : slotStart i) (occ : occupies u t i bad) (deficient : u.count bad < r) :
  5430. ∃ (keep : W) (s : SlotCertificate), keep.length ≤ 9 ∧ n.owner ∈ keep ∧ n.mate ∈ keep ∧
  5431. bad ∈ keep ∧ s.defect = .deficient bad ∧ s.anchor = n ∧ s.bit = bit ∧ P455Closure.Cap r (select keep u) ∧
  5432. Holds r allow (markNode n) (select keep u) (s.query r) := by
  5433. let a := if side then n.mate else n.owner
  5434. obtain ⟨p,w,ep,len⟩ := near
  5435. let keep := n.owner :: n.mate :: bad :: p.map Prod.fst
  5436. have h1 : n.owner ∈ keep := by simp [keep]
  5437. have h2 : n.mate ∈ keep := by simp [keep]
  5438. have h3 : bad ∈ keep := by simp [keep]
  5439. have start : a ∈ keep := by cases side <;> simp [a,h1,h2]
  5440. have ins : ∀ m ∈ p, m.1 ∈ keep := fun m hm => by simp [keep,List.mem_map_of_mem hm]
  5441. have last : t ∈ keep := ep ▸ endpoint_kept keep a p start ins
  5442. let s : SlotCertificate := ⟨n,bit,side,p,i,.deficient bad⟩
  5443. refine ⟨keep,s,by simpa [keep] using (show p.length + 3 ≤ 9 by omega),h1,h2,h3,rfl,rfl,rfl,
  5444. select_cap keep cap,select_marked keep n bit h1 h2 anchor,len,?_,True.intro⟩
  5445. apply (route_iff ..).mpr
  5446. refine ⟨remark_walk _ _ (select_walk keep a p start ins w),?_⟩
  5447. change (slotStart i ∧ occupies (select keep u) (endpoint a p) i bad) ∧ (select keep u).count bad < r
  5448. rw [show endpoint a p = t from ep, select_count keep u bad h3]
  5449. exact ⟨⟨slot,select_slot keep t i bad last h3 occ⟩,deficient⟩
  5450. theorem bounded_defect {r allow mark u} (cap : P455Closure.Cap r u) (n : Node) (bit side : Bool)
  5451. (t i bad : Nat) (anchor : Holds r allow (markNode n) u (markedNode n bit))
  5452. (near : Near r allow mark u (if side then n.mate else n.owner) t 6)
  5453. (slot : slotStart i) (occ : occupies u t i bad) (deficient : u.count bad < r) :
  5454. ∃ (keep : W) (s : SlotCertificate), keep.length ≤ 9 ∧ n.owner ∈ keep ∧ n.mate ∈ keep ∧
  5455. s.anchor = n ∧ s.bit = bit ∧ P455Closure.Cap r (select keep u) ∧
  5456. Holds r allow (markNode n) (select keep u) (s.query r) := by
  5457. obtain ⟨keep,s,len,ho,hm,_,_,anc,bs,cp,h⟩ :=
  5458. bounded_defect_kind cap n bit side t i bad anchor near slot occ deficient
  5459. exact ⟨keep,s,len,ho,hm,anc,bs,cp,h⟩
  5460. end P455DefectProjection
  5461. end
  5462. /- Begin Problem455FirstRewrite (from finite-semigroup-identity-bases). -/
  5463. section
  5464. namespace P455FirstRewrite
  5465. abbrev W := List Nat
  5466. abbrev Sub := Nat → W
  5467. def Step (G : W → W → Prop) (A B : W) : Prop :=
  5468. ∃ (u v p q : W) (h : Sub), (G u v ∨ G v u) ∧ u ≠ [] ∧ v ≠ [] ∧
  5469. (∀ x, h x ≠ []) ∧ A = p ++ u.flatMap h ++ q ∧ B = p ++ v.flatMap h ++ q
  5470. abbrev Derives (G : W → W → Prop) := P455Quotient.Walk (Step G)
  5471. /-- A deduction entirely in a two-word class contains an actual one-step
  5472. instance from the initial to the other word. Self steps may occur anywhere. -/
  5473. theorem first_change {G : W → W → Prop} {A B : W} (ne : A ≠ B)
  5474. (two : ∀ w, Derives G A w → w = A ∨ w = B) (path : Derives G A B) : Step G A B := by
  5475. suffices go : ∀ w, Derives G A w → w = A ∨ Step G A B by
  5476. exact (go B path).resolve_left ne.symm
  5477. intro w walk
  5478. induction walk with
  5479. | refl => exact Or.inl rfl
  5480. | @snoc v w prev step ih =>
  5481. rcases ih with h | done
  5482. · rcases two w (.snoc prev step) with f | f
  5483. · exact Or.inl f
  5484. · exact Or.inr (h ▸ f ▸ step)
  5485. · exact Or.inr done
  5486. def proj (a b : Nat) (w : W) : W := w.filter (fun x => decide (x = a ∨ x = b))
  5487. private theorem proj_append (a b : Nat) (p q : W) :
  5488. proj a b (p ++ q) = proj a b p ++ proj a b q := List.filter_append p q
  5489. private theorem filter_erase (f : Nat → Bool) (a : Nat) (w : W) :
  5490. (w.erase a).filter f = (w.filter f).erase a := by
  5491. induction w with
  5492. | nil => rfl
  5493. | cons x xs ih =>
  5494. by_cases e : x = a
  5495. · subst x
  5496. by_cases h : f a = true
  5497. · simp [h]
  5498. · have n : a ∉ xs.filter f := by simp [h]
  5499. simp [h, List.erase_of_not_mem n]
  5500. · by_cases h : f x = true <;> simp [List.erase_cons, e, h, ih]
  5501. private theorem first_split {a : Nat} {v : W} (mem : a ∈ v) :
  5502. ∃ L R : W, v = L ++ a :: R ∧ a ∉ L := by
  5503. induction v with
  5504. | nil => simp at mem
  5505. | cons z zs ih =>
  5506. by_cases e : z = a
  5507. · subst z; exact ⟨[],zs,rfl,by simp⟩
  5508. · obtain ⟨l,r,f,n⟩ := ih ((List.mem_cons.mp mem).resolve_left (Ne.symm e))
  5509. exact ⟨z::l,r,by simp [f],by simp [Ne.symm e,n]⟩
  5510. private theorem prefix_head {a z : Nat} {L : W} (n : a ∉ L) (m : z ∈ L) :
  5511. ∃ t, proj a z L = z :: t := by
  5512. induction L with
  5513. | nil => simp at m
  5514. | cons c L ih =>
  5515. have ca : c ≠ a := fun e => n (e ▸ List.mem_cons_self)
  5516. by_cases cz : c = z
  5517. · subst c; exact ⟨proj a z L,by simp [proj]⟩
  5518. · have mz := (List.mem_cons.mp m).resolve_left (Ne.symm cz)
  5519. obtain ⟨t,e⟩ := ih (fun h => n (List.mem_cons_of_mem c h)) mz
  5520. exact ⟨t, by simpa [proj,ca,cz] using e⟩
  5521. private theorem flatten_commute (g : Sub) (a : Nat) (L : W)
  5522. (ok : ∀ z ∈ L, g a ++ g z = g z ++ g a) :
  5523. g a ++ L.flatMap g = L.flatMap g ++ g a := by
  5524. induction L with
  5525. | nil => simp
  5526. | cons z L ih =>
  5527. have tail := ih (fun x h => ok x (List.mem_cons_of_mem z h))
  5528. have head := ok z (List.mem_cons_self)
  5529. simp only [List.flatMap_cons]
  5530. calc
  5531. _ = (g a ++ g z) ++ L.flatMap g := (List.append_assoc ..).symm
  5532. _ = (g z ++ g a) ++ L.flatMap g := by rw [head]
  5533. _ = _ := by simp only [List.append_assoc,tail]
  5534. /-- Multiplicities and two-letter projections of all pairs with noncommuting
  5535. images determine the whole substituted word, even for erasing substitutions. -/
  5536. theorem trace {u v : W} (g : Sub) (counts : ∀ x, u.count x = v.count x)
  5537. (pairs : ∀ i j, g i ++ g j ≠ g j ++ g i → proj i j u = proj i j v) :
  5538. u.flatMap g = v.flatMap g := by
  5539. induction u generalizing v with
  5540. | nil =>
  5541. cases v with
  5542. | nil => rfl
  5543. | cons b t => simpa using counts b
  5544. | cons a u ih =>
  5545. have m : a ∈ v := List.count_pos_iff.mp (by rw [← counts]; simp)
  5546. obtain ⟨L,R,rfl,n⟩ := first_split m
  5547. have cross (z) (mz : z ∈ L) : g a ++ g z = g z ++ g a := by
  5548. apply Classical.byContradiction
  5549. intro bad
  5550. have pair := pairs a z bad
  5551. obtain ⟨t,eq⟩ := prefix_head n mz
  5552. rw [proj_append,eq] at pair
  5553. have az : a = z := by simpa [proj] using congrArg List.head? pair
  5554. exact n (az ▸ mz)
  5555. have er : (L ++ a :: R).erase a = L ++ R := by
  5556. rw [List.erase_append_right _ n, List.erase_cons_head]
  5557. have cnt (x) : u.count x = (L ++ R).count x := by
  5558. have orig := counts x
  5559. simp only [List.count_append,List.count_cons] at orig ⊢
  5560. omega
  5561. have rest (i j) (bad : g i ++ g j ≠ g j ++ g i) : proj i j u = proj i j (L ++ R) := by
  5562. have eq := congrArg (fun w : W => w.erase a) (pairs i j bad)
  5563. unfold proj at eq
  5564. rw [← filter_erase, ← filter_erase, List.erase_cons_head, er] at eq
  5565. exact eq
  5566. have sub := ih cnt rest
  5567. simp only [List.flatMap_cons,List.flatMap_append] at sub ⊢
  5568. calc
  5569. _ = g a ++ (L.flatMap g ++ R.flatMap g) := by rw [sub]
  5570. _ = _ := by rw [← List.append_assoc, flatten_commute g a L cross, List.append_assoc]
  5571. /-- The two tester consequences required of a rule in the chosen orientation.
  5572. Clipping at r+1 records the overflow class. -/
  5573. structure TesterRule (r : Nat) (u v : W) : Prop where
  5574. unary : ∀ x, min (u.count x) (r+1) = min (v.count x) (r+1)
  5575. binary : P455Quotient.Cap r u → P455Quotient.Cap r v →
  5576. ∀ i j, proj i j u ≠ proj i j v → u.count i = r ∧ u.count j = r
  5577. private theorem cap_rule {r : Nat} {p q u : W} {h : Sub} (ne : ∀ x, h x ≠ [])
  5578. (cap : P455Quotient.Cap r (p ++ u.flatMap h ++ q)) : P455Quotient.Cap r u := by
  5579. intro x
  5580. obtain ⟨a,hm⟩ : ∃ a, a ∈ h x := by
  5581. cases e : h x with
  5582. | nil => exact False.elim (ne x e)
  5583. | cons a t => exact ⟨a,List.mem_cons_self⟩
  5584. have pos := List.count_pos_iff.mpr hm
  5585. have mul := Nat.mul_le_mul_left (u.count x) pos
  5586. have ct := P455DonorInterval.split_contributions h u x a
  5587. have bound := cap a
  5588. simp only [List.count_append] at bound
  5589. simp only [Nat.mul_one] at mul
  5590. omega
  5591. private theorem counted_edge (h : Sub) (x a b : Nat)
  5592. (pos : 0 < Problem455Swap.bigram a b (h x)) (u : W) :
  5593. u.count x ≤ Problem455Swap.bigram a b (u.flatMap h) := by
  5594. induction u with
  5595. | nil => simp [Problem455Swap.bigram]
  5596. | cons z u ih =>
  5597. simp only [List.flatMap_cons,Problem455Swap.bigram_append]
  5598. by_cases e : z = x
  5599. · subst z; simp [List.count_cons]; omega
  5600. · simp [List.count_cons,e]; omega
  5601. private theorem singleton {r : Nat} {p q u : W} {h : Sub}
  5602. (ne : ∀ x, h x ≠ []) (cap : P455Quotient.Cap r (p ++ u.flatMap h ++ q))
  5603. (compressed : P455SourceFamilies.Compressed r (p ++ u.flatMap h ++ q))
  5604. {x : Nat} (sat : u.count x = r) : ∃ a, h x = [a] := by
  5605. cases e : h x with
  5606. | nil => exact False.elim (ne x e)
  5607. | cons a t =>
  5608. cases t with
  5609. | nil => exact ⟨a,rfl⟩
  5610. | cons b tail =>
  5611. have edge : 0 < Problem455Swap.bigram a b (h x) := by
  5612. rw [e]; simp [Problem455Swap.bigram,Problem455Swap.hit] <;> omega
  5613. have lo := counted_edge h x a b edge u
  5614. let U := p ++ u.flatMap h ++ q
  5615. have lower : r ≤ Problem455Swap.bigram a b U := by
  5616. dsimp [U]; rw [Problem455Swap.bigram_append,Problem455Swap.bigram_append]; omega
  5617. have upper := Problem455Swap.out_bound a b (b+1) (by omega) U
  5618. rw [Problem455BlockBridge.occ_count] at upper
  5619. have hc : U.count a ≤ r := cap a
  5620. exact False.elim (compressed a b (by change Problem455Swap.bigram a b U = r; omega))
  5621. private theorem project_images (a b : Nat) (u : W) (h : Sub) :
  5622. proj a b (u.flatMap h) = u.flatMap (fun x => proj a b (h x)) := by
  5623. induction u with
  5624. | nil => rfl
  5625. | cons x u ih => simp only [List.flatMap_cons,proj_append,ih]
  5626. private theorem projected_commutes_without (a b c d : Nat) (ca : c ≠ a) (da : d ≠ a) :
  5627. proj a b [c] ++ proj a b [d] = proj a b [d] ++ proj a b [c] := by
  5628. by_cases cb : c = b <;> by_cases db : d = b <;> simp_all [proj]
  5629. /-- Every literal name in a changed binary projection is the singleton image
  5630. of an actual matched-side rule variable. This uses no occurrence indexing. -/
  5631. theorem changed_name {r : Nat} (hr : 0 < r) {p q u v : W} {h : Sub}
  5632. (ne : ∀ x, h x ≠ []) (cap : P455Quotient.Cap r (p ++ u.flatMap h ++ q))
  5633. (compressed : P455SourceFamilies.Compressed r (p ++ u.flatMap h ++ q))
  5634. (rule : TesterRule r u v) (a b : Nat)
  5635. (changed : proj a b (p ++ u.flatMap h ++ q) ≠ proj a b (p ++ v.flatMap h ++ q)) :
  5636. ∃ x ∈ u, h x = [a] := by
  5637. have cu := cap_rule ne cap
  5638. have counts (x) : u.count x = v.count x := by
  5639. have eq := rule.unary x
  5640. have bound := cu x
  5641. omega
  5642. have cv : P455Quotient.Cap r v := fun x => counts x ▸ cu x
  5643. let g : Sub := fun x => proj a b (h x)
  5644. apply Classical.byContradiction
  5645. intro absent
  5646. apply changed
  5647. simp only [proj_append,project_images]
  5648. have pair (i j) (bad : g i ++ g j ≠ g j ++ g i) : proj i j u = proj i j v := by
  5649. apply Classical.byContradiction
  5650. intro diff
  5651. obtain ⟨ci,cj⟩ := rule.binary cu cv i j diff
  5652. obtain ⟨c,ec⟩ := singleton ne cap compressed ci
  5653. obtain ⟨d,ed⟩ := singleton ne cap compressed cj
  5654. have mi : i ∈ u := List.count_pos_iff.mp (ci ▸ hr)
  5655. have mj : j ∈ u := List.count_pos_iff.mp (cj ▸ hr)
  5656. have ca : c ≠ a := fun e => absent ⟨i,mi,ec.trans (e ▸ rfl)⟩
  5657. have da : d ≠ a := fun e => absent ⟨j,mj,ed.trans (e ▸ rfl)⟩
  5658. apply bad
  5659. simpa [g,ec,ed] using projected_commutes_without a b c d ca da
  5660. rw [show u.flatMap (fun x => proj a b (h x)) = v.flatMap (fun x => proj a b (h x))
  5661. from trace g counts pair]
  5662. /-- A list of distinct names included in an arbitrary covering list gives a
  5663. numeric lower bound on its length, even if that covering list contains repeats. -/
  5664. theorem size_le {D C : W} (uniq : D.Nodup) (sub : ∀ a ∈ D, a ∈ C) : D.length ≤ C.length := by
  5665. induction D generalizing C with
  5666. | nil => simp
  5667. | cons a t ih =>
  5668. obtain ⟨fresh,tail⟩ := List.nodup_cons.mp uniq
  5669. have mem := sub a List.mem_cons_self
  5670. have le := ih tail (C := C.erase a) (fun x hx =>
  5671. (List.mem_erase_of_ne (a := x) (b := a) (fun e => fresh (e ▸ hx))).mpr (sub x (List.mem_cons_of_mem _ hx)))
  5672. have len := List.length_erase_of_mem mem
  5673. have pos : 0 < C.length := by cases C <;> simp_all
  5674. simp only [List.length_cons]
  5675. omega
  5676. /-- Any explicit list of rule variables covering the matched side must have
  5677. at least as many entries as there are distinct literal participants. -/
  5678. theorem instance_rank {r : Nat} (hr : 0 < r) {p q u v D C : W} {h : Sub}
  5679. (ne : ∀ x, h x ≠ []) (cap : P455Quotient.Cap r (p ++ u.flatMap h ++ q))
  5680. (compressed : P455SourceFamilies.Compressed r (p ++ u.flatMap h ++ q))
  5681. (rule : TesterRule r u v) (uniq : D.Nodup) (cover : ∀ x ∈ u, x ∈ C)
  5682. (changes : ∀ a ∈ D, ∃ b, proj a b (p ++ u.flatMap h ++ q) ≠
  5683. proj a b (p ++ v.flatMap h ++ q)) : D.length ≤ C.length := by
  5684. have sub (a) (ma : a ∈ D) : a ∈ C.map (fun x => (h x).headD 0) := by
  5685. obtain ⟨b,diff⟩ := changes a ma
  5686. obtain ⟨x,mx,e⟩ := changed_name hr ne cap compressed rule a b diff
  5687. exact List.mem_map.mpr ⟨x,cover x mx,by simp [e]⟩
  5688. simpa using size_le uniq sub
  5689. /-- The list of distinct variables of an oriented rule pair. -/
  5690. def names : W → W
  5691. | [] => []
  5692. | x :: w => if x ∈ w then names w else x :: names w
  5693. @[simp] theorem mem_names (a : Nat) (w : W) : a ∈ names w ↔ a ∈ w := by
  5694. induction w with
  5695. | nil => simp [names]
  5696. | cons x w ih =>
  5697. by_cases e : x ∈ w
  5698. · simp only [names,if_pos e,ih,List.mem_cons]
  5699. exact ⟨Or.inr, fun h => h.elim (fun eq => eq ▸ e) id⟩
  5700. · simp [names,e,ih]
  5701. theorem names_distinct (w : W) : (names w).Nodup := by
  5702. induction w with
  5703. | nil => simp [names]
  5704. | cons x w ih => by_cases e : x ∈ w <;> simp [names,e,ih]
  5705. def rank (u v : W) := (names (u ++ v)).length
  5706. theorem rank_swap (u v : W) : rank u v = rank v u := by
  5707. apply Nat.le_antisymm
  5708. · apply size_le (names_distinct _)
  5709. simp [List.mem_append,Or.comm]
  5710. · apply size_le (names_distinct _)
  5711. simp [List.mem_append,Or.comm]
  5712. /-- This is the usual semigroup-word semantics in a monoid. The operation
  5713. alone occurs in rule terms. Empty contexts use the unit when evaluated. -/
  5714. structure Model (A : Type) where
  5715. op : A → A → A
  5716. unit : A
  5717. assoc : ∀ x y z, op (op x y) z = op x (op y z)
  5718. oneL : ∀ x, op unit x = x
  5719. oneR : ∀ x, op x unit = x
  5720. namespace Model
  5721. variable {A : Type} (M : Model A)
  5722. def eval (f : Nat → A) : W → A
  5723. | [] => M.unit
  5724. | x :: xs => M.op (f x) (eval f xs)
  5725. def Valid (u v : W) := ∀ f, M.eval f u = M.eval f v
  5726. theorem eval_append (f : Nat → A) (u v : W) :
  5727. M.eval f (u ++ v) = M.op (M.eval f u) (M.eval f v) := by
  5728. induction u with
  5729. | nil => simp [eval,M.oneL]
  5730. | cons x t ih => simp [eval,ih,M.assoc]
  5731. theorem eval_instance (f : Nat → A) (h : Sub) (w : W) :
  5732. M.eval f (w.flatMap h) = M.eval (fun x => M.eval f (h x)) w := by
  5733. induction w with
  5734. | nil => rfl
  5735. | cons x t ih => simp [eval,eval_append,ih]
  5736. theorem step_sound {G : W → W → Prop} (valid : ∀ u v, G u v → M.Valid u v)
  5737. {U V : W} (s : Step G U V) : M.Valid U V := by
  5738. obtain ⟨u,v,p,q,h,orient,_,_,_,rfl,rfl⟩ := s
  5739. intro f
  5740. simp only [M.eval_append,M.eval_instance]
  5741. rcases orient with g | g
  5742. · rw [valid u v g]
  5743. · rw [valid v u g]
  5744. theorem derives_sound {G : W → W → Prop} (valid : ∀ u v, G u v → M.Valid u v)
  5745. {U V : W} (walk : Derives G U V) : M.Valid U V := by
  5746. induction walk with
  5747. | refl => intro _; rfl
  5748. | snoc _ st ih => exact fun f => (ih f).trans (M.step_sound valid st f)
  5749. end Model
  5750. /-- Hypotheses on one actual pair of witness words; validity of the
  5751. distinguished identity and exhaustion of its semantic class are separate. -/
  5752. structure RankWitness {A : Type} (M : Model A) (r : Nat) (U V D : W) : Prop where
  5753. nonempty : U ≠ [] ∧ V ≠ []
  5754. different : U ≠ V
  5755. identity : M.Valid U V
  5756. two : ∀ w, M.Valid U w → w = U ∨ w = V
  5757. cap : P455Quotient.Cap r U
  5758. compressed : P455SourceFamilies.Compressed r U
  5759. distinct : D.Nodup
  5760. participants : ∀ a ∈ D, ∃ b, proj a b U ≠ proj a b V
  5761. /-- Every actual step which first leaves U has rule rank at least |D|. -/
  5762. theorem step_rank {A : Type} {M : Model A} {r : Nat} (hr : 0 < r)
  5763. {U V D : W} (wit : RankWitness M r U V D)
  5764. (testers : ∀ u v, M.Valid u v → TesterRule r u v)
  5765. {G : W → W → Prop} (valid : ∀ u v, G u v → M.Valid u v) {T : W}
  5766. (s : Step G U T) (diff : U ≠ T) :
  5767. ∃ u v, G u v ∧ D.length ≤ rank u v := by
  5768. have iden := M.step_sound valid s
  5769. have direct := (wit.two T iden).resolve_left diff.symm
  5770. subst T
  5771. obtain ⟨u,v,p,q,h,oriented,_,_,ne,eq1,eq2⟩ := s
  5772. have vr : M.Valid u v := oriented.elim (valid u v) (fun rev f => (valid v u rev f).symm)
  5773. have cover (x) (m : x ∈ u) : x ∈ names (u ++ v) := by simp [m]
  5774. have bound : D.length ≤ rank u v := by
  5775. apply instance_rank hr ne (eq1 ▸ wit.cap) (eq1 ▸ wit.compressed) (testers _ _ vr)
  5776. wit.distinct cover
  5777. simpa only [← eq1, ← eq2] using wit.participants
  5778. rcases oriented with forward | backward
  5779. · exact ⟨u,v,forward,bound⟩
  5780. · exact ⟨v,u,backward,rank_swap u v ▸ bound⟩
  5781. theorem derivation_rank {A : Type} {M : Model A} {r : Nat} (hr : 0 < r)
  5782. {U V D : W} (wit : RankWitness M r U V D)
  5783. (testers : ∀ u v, M.Valid u v → TesterRule r u v)
  5784. {G : W → W → Prop} (valid : ∀ u v, G u v → M.Valid u v) (path : Derives G U V) :
  5785. ∃ u v, G u v ∧ D.length ≤ rank u v :=
  5786. step_rank hr wit testers valid (first_change wit.different
  5787. (fun w walk => wit.two w (M.derives_sound valid walk)) path) wit.different
  5788. /-- The monoid M is fixed before the padding bound is chosen. No assumption
  5789. about the existence of an accepting computation or rectangle is encoded. -/
  5790. theorem no_finite_basis_of_witnesses {A : Type} (M : Model A) (r : Nat) (hr : 0 < r)
  5791. (testers : ∀ u v, M.Valid u v → TesterRule r u v)
  5792. (witnesses : ∀ k : Nat, ∃ U V D, RankWitness M r U V D ∧ k < D.length)
  5793. (G : List (W × W)) (valid : ∀ u v, (u,v) ∈ G → M.Valid u v) :
  5794. ∃ U V, U ≠ [] ∧ V ≠ [] ∧ M.Valid U V ∧ ¬ Derives (fun u v => (u,v) ∈ G) U V := by
  5795. let sizes := G.map (fun t => rank t.1 t.2)
  5796. obtain ⟨U,V,D,w,large⟩ := witnesses sizes.sum
  5797. refine ⟨U,V,w.nonempty.1,w.nonempty.2,w.identity,?_⟩
  5798. intro derivation
  5799. obtain ⟨u,v,mem,bound⟩ := derivation_rank hr w testers valid derivation
  5800. have inSizes : rank u v ∈ sizes := List.mem_map.mpr ⟨(u,v),mem,rfl⟩
  5801. have less (s : List Nat) (n) (m : n ∈ s) : n ≤ s.sum := by
  5802. induction s with
  5803. | nil => simp at m
  5804. | cons z t ih =>
  5805. simp only [List.sum_cons]
  5806. rcases List.mem_cons.mp m with e | m
  5807. · omega
  5808. · have := ih m; omega
  5809. have := less sizes (rank u v) inSizes
  5810. omega
  5811. end P455FirstRewrite
  5812. end
  5813. /- Begin Problem455LiteralMovePrim (from finite-semigroup-identity-bases). -/
  5814. section
  5815. /- Primitive recursive literal-move search on standard natural-number
  5816. encodings, uniformly in the cap, tags and finitely stored mark relation. -/
  5817. namespace P455FrameProof
  5818. set_option maxHeartbeats 450000
  5819. open P455Closure P455EffectiveQ P455GraphPrim P455FramePrim
  5820. open P455EffectiveQMove (capB frames entries validB moveB)
  5821. variable {A B : Type} [Primcodable A] [Primcodable B]
  5822. private theorem same_decision {p : Prop} (a b : Decidable p) : @decide p a = @decide p b := by
  5823. rw [Subsingleton.elim a b]
  5824. theorem forNames {l : A → List B} {pr : A → B → Prop} [d : ∀ a, DecidablePred (pr a)]
  5825. (hl : Primrec l) (hp : Primrec₂ fun a b => decide (pr a b)) : PrimrecPred fun a => ∀ b∈l a,pr a b := by
  5826. apply Primrec.primrecPred
  5827. apply (allB hl hp).of_eq
  5828. intro a
  5829. apply Bool.eq_iff_iff.mpr
  5830. simp only [List.all_eq_true,decide_eq_true_eq]
  5831. theorem capCheck {r : A → Nat} {w : A → W} (hr : Primrec r) (hw : Primrec w) :
  5832. Primrec fun a => capB (r a) (w a) := by
  5833. apply allB hw
  5834. exact (Primrec.nat_le.comp (countN Primrec.snd (hw.comp Primrec.fst)) (hr.comp Primrec.fst)).decide.to₂
  5835. theorem validity {r : A → Nat} {tags : A → List Tag} {marks : A → Marks} {f : A → Frame Nat}
  5836. (hr : Primrec r) (ht : Primrec tags) (hm : Primrec marks) (hf : Primrec f) :
  5837. Primrec fun a => validB (r a) (tags a) (fun x y => decide ((x,y)∈marks a)) (f a) := by
  5838. unfold validB
  5839. apply PrimrecPred.decide
  5840. let Fp := P455FramePrim.p.comp hf
  5841. let Fq := P455FramePrim.q.comp hf
  5842. let Ft := P455FramePrim.tag.comp hf
  5843. let Fm := P455FramePrim.middle.comp hf
  5844. have apart : PrimrecPred (fun a => ∀ x∈(f a).p, x∉(f a).q) := by
  5845. apply forNames Fp
  5846. exact (PrimrecPred.not (contains Primrec.snd (Fq.comp Primrec.fst)).primrecPred).decide.to₂
  5847. have marksOK : PrimrecPred (fun a => ∀ x∈(f a).p, ∀ y∈(f a).q,
  5848. decide ((x,y)∈marks a)=false ∧ decide ((y,x)∈marks a)=false) := by
  5849. apply forNames Fp
  5850. apply Primrec₂.mk
  5851. apply PrimrecPred.decide
  5852. apply forNames (Fq.comp Primrec.fst)
  5853. apply Primrec₂.mk
  5854. have old : Primrec (fun s : (A×Nat)×Nat => marks s.1.1) := (hm.comp Primrec.fst).comp Primrec.fst
  5855. have xy : Primrec (fun s : (A×Nat)×Nat => decide ((s.1.2,s.2)∈marks s.1.1)) :=
  5856. (contains (Primrec.pair (Primrec.snd.comp Primrec.fst) Primrec.snd) old).of_eq (fun _ => same_decision _ _)
  5857. have yx : Primrec (fun s : (A×Nat)×Nat => decide ((s.2,s.1.2)∈marks s.1.1)) :=
  5858. (contains (Primrec.pair Primrec.snd (Primrec.snd.comp Primrec.fst)) old).of_eq (fun _ => same_decision _ _)
  5859. exact (PrimrecPred.and (Primrec.eq.comp xy (.const false)) (Primrec.eq.comp yx (.const false))).decide
  5860. have saturated : PrimrecPred (fun a => ∀ x∈(f a).p++(f a).q, ((f a).core false).count x = r a) := by
  5861. apply forNames (Primrec.list_append.comp Fp Fq)
  5862. exact (Primrec.eq.comp (countN Primrec.snd ((P455FramePrim.core.comp hf (.const false)).comp Primrec.fst))
  5863. (hr.comp Primrec.fst)).decide.to₂
  5864. apply PrimrecPred.and (Primrec.eq.comp hr (Primrec.nat_add.comp (.const 16) (Primrec.list_length.comp Ft)))
  5865. have member : Primrec (fun a => decide ((f a).tag ∈ tags a)) := (contains Ft ht).of_eq (fun _ => same_decision _ _)
  5866. apply PrimrecPred.and member.primrecPred
  5867. apply PrimrecPred.and (Primrec.eq.comp (Primrec.list_map Fm (Primrec.snd.comp₂ Primrec₂.right)) (phases.comp Ft))
  5868. apply PrimrecPred.and (nodup Fp).primrecPred
  5869. apply PrimrecPred.and (nodup Fq).primrecPred
  5870. apply PrimrecPred.and apart
  5871. apply PrimrecPred.and marksOK
  5872. exact saturated
  5873. theorem entriesRec {w : A → W} (hw : Primrec w) : Primrec fun a => entries (w a) := by
  5874. apply Primrec.list_flatMap (wordPool.comp hw)
  5875. apply Primrec₂.mk
  5876. exact Primrec.list_cons.comp (Primrec.pair Primrec.snd (.const false))
  5877. (singleton (Primrec.pair Primrec.snd (.const true)))
  5878. private def choices {X Y : Type} (xs : List X) (ys : List Y) : List (X × Y) :=
  5879. xs.flatMap fun x => ys.map fun y => (x,y)
  5880. private theorem map_choices {X Y Z : Type} (xs : List X) (ys : List Y) (f : X × Y → Z) :
  5881. (choices xs ys).map f = xs.flatMap fun x => ys.map fun y => f (x,y) := by
  5882. simp only [choices, List.map_flatMap, List.map_map, Function.comp_def]
  5883. private theorem choices_rec {X Y : Type} [Primcodable X] [Primcodable Y]
  5884. {xs : A → List X} {ys : A → List Y} (hx : Primrec xs) (hy : Primrec ys) :
  5885. Primrec fun a => choices (xs a) (ys a) := by
  5886. apply Primrec.list_flatMap hx
  5887. apply Primrec₂.mk
  5888. apply Primrec.list_map (hy.comp Primrec.fst)
  5889. exact (Primrec.pair (Primrec.snd.comp Primrec.fst) Primrec.snd).to₂
  5890. private abbrev Body := Nat × W × W × Nat × PairList × W × W × W
  5891. private def insertTag (t : Tag) (b : Body) : FrameData :=
  5892. (b.1,b.2.1,b.2.2.1,b.2.2.2.1,t,b.2.2.2.2)
  5893. private theorem insert_rec : Primrec₂ insertTag := by
  5894. apply Primrec₂.mk
  5895. have tail1 : Primrec (fun s : Tag × Body => s.2.2) := Primrec.snd.comp Primrec.snd
  5896. have tail2 := Primrec.snd.comp tail1
  5897. have tail3 := Primrec.snd.comp tail2
  5898. have tail4 := Primrec.snd.comp tail3
  5899. exact Primrec.pair (Primrec.fst.comp Primrec.snd) (Primrec.pair (Primrec.fst.comp tail1)
  5900. (Primrec.pair (Primrec.fst.comp tail2) (Primrec.pair (Primrec.fst.comp tail3)
  5901. (Primrec.pair Primrec.fst tail4))))
  5902. theorem frameList {tags : A → List Tag} {w : A → W} (ht : Primrec tags) (hw : Primrec w) :
  5903. Primrec fun a => frames (tags a) (w a) := by
  5904. apply Primrec.list_flatMap ht
  5905. apply Primrec₂.mk
  5906. let U : (A × Tag) → W := fun s => w s.1
  5907. let S : (A × Tag) → List W := fun s => P455EffectiveQ.words (U s)
  5908. let E : (A × Tag) → List PairList := fun s =>
  5909. Problem455Finite.wordsUpTo (entries (U s)) (fixedPhases s.2).length
  5910. have hU : Primrec U := hw.comp Primrec.fst
  5911. have hS : Primrec S := wordPool.comp hU
  5912. have hE : Primrec E := wordsUpTo.comp (entriesRec hU) (Primrec.list_length.comp (phases.comp Primrec.snd))
  5913. have bodies := choices_rec hU (choices_rec hS (choices_rec hS (choices_rec hU
  5914. (choices_rec hE (choices_rec hS (choices_rec hS hS))))))
  5915. have attach : Primrec₂ (fun (s : A × Tag) (b : Body) => packing.symm (insertTag s.2 b)) :=
  5916. unpack.comp₂ (insert_rec.comp₂ (Primrec.snd.comp₂ Primrec₂.left) Primrec₂.right)
  5917. apply (Primrec.list_map bodies attach).of_eq
  5918. intro s
  5919. simp only [map_choices, insertTag, packing]
  5920. rfl
  5921. theorem literalMove {r : A → Nat} {tags : A → List Tag} {marks : A → Marks} {u v : A → W}
  5922. (hr : Primrec r) (ht : Primrec tags) (hm : Primrec marks) (hu : Primrec u) (hv : Primrec v) :
  5923. Primrec fun a => moveB (r a) (tags a) (fun x y => decide ((x,y)∈marks a)) (u a) (v a) := by
  5924. apply Primrec.and.comp (Primrec.and.comp (Primrec.nat_le.comp hr (Primrec.list_length.comp hu)).decide (capCheck hr hu))
  5925. apply anyB (frameList ht hu)
  5926. apply Primrec₂.mk
  5927. apply Primrec.and.comp (validity (hr.comp Primrec.fst) (ht.comp Primrec.fst) (hm.comp Primrec.fst) Primrec.snd)
  5928. apply anyB (Primrec.const [false,true])
  5929. apply Primrec₂.mk
  5930. apply anyB (wordPool.comp ((hu.comp Primrec.fst).comp Primrec.fst))
  5931. apply Primrec₂.mk
  5932. apply anyB (wordPool.comp (((hu.comp Primrec.fst).comp Primrec.fst).comp Primrec.fst))
  5933. apply Primrec₂.mk
  5934. let C := ((((A × Frame Nat) × Bool) × W) × W)
  5935. have f : Primrec (fun x : C => x.1.1.1.2) := (((Primrec.snd.comp Primrec.fst).comp Primrec.fst).comp Primrec.fst)
  5936. have b : Primrec (fun x : C => x.1.1.2) := ((Primrec.snd.comp Primrec.fst).comp Primrec.fst)
  5937. have l : Primrec (fun x : C => x.1.2) := (Primrec.snd.comp Primrec.fst)
  5938. have t : Primrec (fun x : C => x.2) := Primrec.snd
  5939. apply PrimrecPred.decide
  5940. exact PrimrecPred.and
  5941. (Primrec.eq.comp ((((hu.comp Primrec.fst).comp Primrec.fst).comp Primrec.fst).comp Primrec.fst) (Primrec.list_append.comp (Primrec.list_append.comp l (P455FramePrim.core.comp f b)) t))
  5942. (Primrec.eq.comp ((((hv.comp Primrec.fst).comp Primrec.fst).comp Primrec.fst).comp Primrec.fst) (Primrec.list_append.comp (Primrec.list_append.comp l (P455FramePrim.core.comp f (Primrec.not.comp b))) t))
  5943. end P455FrameProof
  5944. end
  5945. /- Begin Problem455MachineCleanup (from finite-semigroup-identity-bases). -/
  5946. section
  5947. namespace P455MachineCleanup
  5948. open P455MachineLocal P455MachineTable P455PaddedTiles
  5949. structure Ordinary (g q : Nat) where
  5950. marker : Fin g
  5951. blank : Fin g
  5952. blank_ne : blank≠marker
  5953. start : Fin q
  5954. delta : Fin q→Fin g→Option (Ins (Fin g) (Fin q))
  5955. keeps : ∀ z a ins, delta z a=some ins → (ins.symbol=marker ↔ a=marker)
  5956. leftSafe : ∀ z ins, delta z marker=some ins → ins.dir≠.left
  5957. def old (z : Fin q) : Fin (q+2) := ⟨z.val,by have := z.isLt; omega⟩
  5958. def cleanState (q : Nat) : Fin (q+2) := ⟨q,by omega⟩
  5959. def acceptState (q : Nat) : Fin (q+2) := ⟨q+1,by omega⟩
  5960. def extend (ins : Ins (Fin g) (Fin q)) : Ins (Fin g) (Fin (q+2)) :=
  5961. ⟨old ins.state,ins.symbol,ins.dir⟩
  5962. def trans (M : Ordinary g q) (z : Fin (q+2)) (a : Fin g) : Ins (Fin g) (Fin (q+2)) :=
  5963. if h : z.val<q then
  5964. match M.delta ⟨z.val,h⟩ a with
  5965. | none => ⟨cleanState q,a,.stay⟩
  5966. | some i => extend i
  5967. else if z.val=q then
  5968. if a=M.marker then ⟨acceptState q,a,.stay⟩ else ⟨cleanState q,a,.left⟩
  5969. else ⟨acceptState q,a,.stay⟩
  5970. theorem old_step (M : Ordinary g q) (z : Fin q) (a : Fin g) : trans M (old z) a =
  5971. match M.delta z a with
  5972. | none => ⟨cleanState q,a,.stay⟩
  5973. | some i => extend i := by simp [trans,old,z.isLt]
  5974. theorem clean_step (M : Ordinary g q) (a : Fin g) : trans M (cleanState q) a =
  5975. if a=M.marker then ⟨acceptState q,a,.stay⟩ else ⟨cleanState q,a,.left⟩ := by
  5976. simp [trans,cleanState]
  5977. def normalized (M : Ordinary g q) : TM g (q+2) where
  5978. marker := M.marker
  5979. blank := M.blank
  5980. blank_ne := M.blank_ne
  5981. start := old M.start
  5982. accept := acceptState q
  5983. distinct := by intro e; have v := congrArg Fin.val e; change M.start.val=q+1 at v; have := M.start.isLt; omega
  5984. delta := trans M
  5985. keeps := by
  5986. intro z a
  5987. unfold trans
  5988. split
  5989. next bound =>
  5990. cases e : M.delta ⟨z.val,bound⟩ a with
  5991. | none => rfl
  5992. | some i => exact M.keeps _ _ _ e
  5993. next =>
  5994. split
  5995. · split <;> rfl
  5996. · rfl
  5997. leftSafe := by
  5998. intro z
  5999. unfold trans
  6000. split
  6001. next bound =>
  6002. cases e : M.delta ⟨z.val,bound⟩ M.marker with
  6003. | none => simp
  6004. | some i => exact M.leftSafe _ _ e
  6005. next =>
  6006. split <;> simp
  6007. stationary := by simp [trans,acceptState,show ¬q+1<q by omega]
  6008. def config₀ (M : Ordinary g q) : Config g q :=
  6009. ⟨fun x=>if x=0 then M.marker else M.blank,0,M.start⟩
  6010. def instruction (M : Ordinary g q) (c : Config g q) := M.delta c.state (c.tape c.pos)
  6011. def once (M : Ordinary g q) (c : Config g q) : Config g q :=
  6012. match instruction M c with
  6013. | none => c
  6014. | some ins => ⟨writeAt c.tape c.pos ins.symbol,dest ins.dir c.pos,ins.state⟩
  6015. def original (M : Ordinary g q) : Nat→Config g q
  6016. | 0 => config₀ M
  6017. | t+1 => once M (original M t)
  6018. def stopped (M : Ordinary g q) (t : Nat) := instruction M (original M t)=none
  6019. def lift (c : Config g q) : Config g (q+2) := ⟨c.tape,c.pos,old c.state⟩
  6020. theorem simulates (M : Ordinary g q) (t : Nat) (prior : ∀ j,j<t→¬stopped M j) :
  6021. run (normalized M) t=lift (original M t) := by
  6022. induction t with
  6023. | zero => rfl
  6024. | succ t ih =>
  6025. have now := prior t (by omega)
  6026. change step (normalized M) (run (normalized M) t) = lift (once M (original M t))
  6027. rw [ih (fun j lt=>prior j (by omega))]
  6028. cases eq : instruction M (original M t) with
  6029. | none => exact (now eq).elim
  6030. | some ins =>
  6031. have instr : trans M (old (original M t).state) ((original M t).tape (original M t).pos)=extend ins := by
  6032. rw [old_step]; change (match instruction M (original M t) with | none => _ | some i => extend i) = _
  6033. rw [eq]
  6034. simp [step,normalized,lift,instr,once,eq,extend]
  6035. private theorem eventually_clean (M : Ordinary g q) (p : Nat) :
  6036. ∀ t, (run (normalized M) t).pos=p → (run (normalized M) t).state=cleanState q →
  6037. ∃ s,Genuine (normalized M) s := by
  6038. induction p with
  6039. | zero =>
  6040. intro t pos state
  6041. have marker := (marker_iff (normalized M) t 0).mpr rfl
  6042. change (run (normalized M) t).tape 0=M.marker at marker
  6043. refine ⟨t+1,?_⟩
  6044. change dest (trans M _ _).dir _=0 ∧ (trans M _ _).state=acceptState q
  6045. rw [state,pos,marker,clean_step]
  6046. simp [dest]
  6047. | succ p ih =>
  6048. intro t pos state
  6049. have neq : (run (normalized M) t).tape (p+1)≠M.marker := by
  6050. intro e; have z := (marker_iff (normalized M) t (p+1)).mp e; omega
  6051. apply ih (t+1)
  6052. · change dest (trans M _ _).dir _=p
  6053. rw [state,pos,clean_step,if_neg neq]; simp [dest]
  6054. · change (trans M _ _).state=cleanState q
  6055. rw [state,pos,clean_step,if_neg neq]
  6056. private theorem first_stop (M : Ordinary g q) (t : Nat) (h : stopped M t) :
  6057. ∃ j, stopped M j ∧ (∀ i,i<j→¬stopped M i) := by
  6058. induction t using Nat.strongRecOn with
  6059. | ind t ih =>
  6060. by_cases early : ∃ i,i<t ∧ stopped M i
  6061. · obtain ⟨i,lt,yes⟩ := early; exact ih i lt yes
  6062. · exact ⟨t,h,fun i lt st=>early ⟨i,lt,st⟩⟩
  6063. theorem halts_iff_genuine (M : Ordinary g q) :
  6064. (∃ t,stopped M t) ↔ ∃ s,Genuine (normalized M) s := by
  6065. constructor
  6066. · rintro ⟨t,yes⟩
  6067. obtain ⟨j,st,prior⟩ := first_stop M t yes
  6068. have exactAt := simulates M j prior
  6069. have instr : trans M (old (original M j).state) ((original M j).tape (original M j).pos) =
  6070. ⟨cleanState q,(original M j).tape (original M j).pos,.stay⟩ := by
  6071. rw [old_step]; unfold stopped instruction at st; rw [st]
  6072. apply eventually_clean M (original M j).pos (j+1)
  6073. · change (step (normalized M) (run (normalized M) j)).pos=_
  6074. rw [exactAt]; simp [normalized,step,lift,instr,dest]
  6075. · change (step (normalized M) (run (normalized M) j)).state=_
  6076. rw [exactAt]; simp [normalized,step,lift,instr]
  6077. · rintro ⟨s,_,accept⟩
  6078. apply Classical.byContradiction
  6079. intro none
  6080. have eq := simulates M s (fun j _ h=>none ⟨j,h⟩)
  6081. rw [eq] at accept
  6082. have indices := congrArg Fin.val accept
  6083. change (original M s).state.val=q+1 at indices
  6084. have := (original M s).state.isLt; omega
  6085. /-- Compilation targets the very same numerical tile system as the word
  6086. testers. The halt may occur at *any* tape position, including at time zero. -/
  6087. theorem halts_iff_trace (M : Ordinary g q) : (∃ t,stopped M t) ↔
  6088. ∃ w s, Nonempty (AcceptingTrace (compile (normalized M)) w s) :=
  6089. (halts_iff_genuine M).trans (trace_iff (normalized M))
  6090. theorem halts_iff_rectangles (M : Ordinary g q) : (∃ t,stopped M t) ↔
  6091. ∃ w, ∀ k, ∃ h, 1<h ∧ k<2*(w*h) ∧ Nonempty (Rectangle (compile (normalized M)) w h) :=
  6092. (halts_iff_genuine M).trans (rectangles_iff (normalized M))
  6093. end P455MachineCleanup
  6094. end
  6095. /- Begin Problem455OriginalTerminal (from finite-semigroup-identity-bases). -/
  6096. section
  6097. /- Endpoint obstruction in the actual original source word after all gap
  6098. variables of the smaller rule have been expanded. -/
  6099. namespace P455OriginalTerminal
  6100. open Problem455.Slots P455Witness P455Retained P455TerminalTransfer
  6101. /-- Keep the identical five selected output names and the identical five
  6102. donor variables when an overflow obstruction is taken back to the
  6103. original word. Deficiency already gives a contradiction. -/
  6104. theorem expand {r : Nat} {v : Word} {e h : Nat → Word} {kept : Nat → Prop} {x i : Nat}
  6105. (exp : Expansion v e kept) (hr : 1 < r) (kx : kept x)
  6106. (d : SlotDefect) (small : Lift v h x i r d) :
  6107. Lift (v.flatMap e) h x i r d := by
  6108. cases d with
  6109. | deficient a => exact small
  6110. | overflow xs =>
  6111. obtain ⟨assign,len,nd,valid⟩ := small
  6112. refine ⟨assign,len,nd,?_⟩
  6113. intro a ha
  6114. obtain ⟨obs,ha',cnt⟩ := valid a ha
  6115. have used : assign a ∈ v := List.count_pos_iff.mp (by omega)
  6116. have keep : kept (assign a) := by
  6117. apply Classical.byContradiction
  6118. intro gap
  6119. have := (exp.gaps (assign a) used gap).1
  6120. omega
  6121. have hx : assign a ∈ e (assign a) := by rw [exp.literal _ used keep]; simp
  6122. exact ⟨exp.in_original_slot x i _ kx obs _ hx,ha',(exp.count_eq _ (fun _ h => h) _ keep).trans cnt⟩
  6123. end P455OriginalTerminal
  6124. end
  6125. /- Begin Problem455CompressedFrame (from finite-semigroup-identity-bases). -/
  6126. section
  6127. namespace P455CompressedFrame
  6128. open P455Closure P455Compression P455Uncrossed
  6129. private theorem prepend_cut (a x : Nat) (cs tail : List Piece) :
  6130. prependOutside a (cs ++ .literal x :: tail) =
  6131. prependOutside a cs ++ .literal x :: tail := by
  6132. cases cs with
  6133. | nil => rfl
  6134. | cons p cs => cases p <;> rfl
  6135. private theorem pieces_cut (names u v : W) (x : Nat) (hx : x ∈ names) :
  6136. pieces names (u ++ x :: v) = pieces names u ++ .literal x :: pieces names v := by
  6137. induction u with
  6138. | nil => simp [pieces,hx]
  6139. | cons a u ih =>
  6140. by_cases k : a ∈ names
  6141. · simp [pieces,k,ih]
  6142. · simp [pieces,k,ih,prepend_cut]
  6143. private theorem code_append (n : Nat) (p q : List Piece) :
  6144. code n (p ++ q) = code n p ++ code (n+p.length) q := by
  6145. induction p generalizing n with
  6146. | nil => simp [code]
  6147. | cons e p ih => cases e <;> simp [code,ih,Nat.add_assoc,Nat.add_comm,Nat.add_left_comm]
  6148. private def enc (names : W) (n : Nat) (w : W) := code n (pieces names w)
  6149. private def span (names w : W) := (pieces names w).length
  6150. private theorem enc_cut {names : W} {x : Nat} (hx : x ∈ names) (n : Nat) (u v : W) :
  6151. enc names n (u ++ x :: v) = enc names n u ++ x :: enc names (n+span names u+1) v := by
  6152. simp only [enc,span,pieces_cut _ _ _ _ hx,code_append,code]
  6153. private theorem enc_cons {names : W} {x : Nat} (hx : x ∈ names) (n : Nat) (v : W) :
  6154. enc names n (x :: v) = x :: enc names (n+1) v := by simp [enc,pieces,hx,code]
  6155. private def pick (x y : Nat) (b : Bool) := if b then y else x
  6156. private def middleWord (x y : Nat) (es : List (W × Bool)) : W :=
  6157. es.flatMap fun e => e.1 ++ [pick x y e.2]
  6158. private def encodeMiddle (names : W) (n : Nat) : List (W × Bool) → List (W × Bool)
  6159. | [] => []
  6160. | (u,b)::es => (enc names n u,b) :: encodeMiddle names (n+span names u+1) es
  6161. private def finish (names : W) (n : Nat) : List (W × Bool) → Nat
  6162. | [] => n
  6163. | (u,_)::es => finish names (n+span names u+1) es
  6164. private theorem enc_middle {names : W} {x y : Nat} (hx : x ∈ names) (hy : y ∈ names)
  6165. (n : Nat) (es : List (W × Bool)) (tail : W) :
  6166. enc names n (middleWord x y es ++ tail) =
  6167. middleWord x y (encodeMiddle names n es) ++ enc names (finish names n es) tail := by
  6168. induction es generalizing n with
  6169. | nil => simp [middleWord,encodeMiddle,finish]
  6170. | cons e es ih =>
  6171. obtain ⟨gap,b⟩ := e
  6172. have hk : pick x y b ∈ names := by cases b <;> simp [pick,hx,hy]
  6173. change enc names n (((gap ++ [pick x y b]) ++ middleWord x y es) ++ tail) =
  6174. (((enc names n gap ++ [pick x y b]) ++ middleWord x y (encodeMiddle names _ es)) ++
  6175. enc names (finish names _ es) tail)
  6176. simp only [List.append_assoc,List.singleton_append,enc_cut hk,ih,List.cons_append,List.nil_append]
  6177. private theorem mid_tags (names : W) (n : Nat) (es : List (W × Bool)) :
  6178. (encodeMiddle names n es).map Prod.snd = es.map Prod.snd := by
  6179. induction es generalizing n with
  6180. | nil => rfl
  6181. | cons e es ih => cases e; simp [encodeMiddle,ih]
  6182. private theorem singleton_mid (f : Frame Nat) {x y : Nat} (hp : f.p = [x]) (hq : f.q = [y]) :
  6183. f.mid = middleWord x y f.middle := by
  6184. unfold Frame.mid middleWord
  6185. congr 1
  6186. funext e
  6187. cases e.2 <;> simp [hp,hq,pick]
  6188. private def firstSuffix (f : Frame Nat) (l : W) (x y : Nat) :=
  6189. l ++ [x,x,y,x,y,y] ++ middleWord x y f.middle ++ f.beforeMutable
  6190. private def lastSuffix (f : Frame Nat) (k : W) (x y : Nat) :=
  6191. f.beforeFinalP ++ x :: (f.beforeFinalQ ++ y :: k)
  6192. private theorem literal_pair (f : Frame Nat) (l k : W) {x y : Nat} (hp : f.p = [x])
  6193. (hq : f.q = [y]) (b : Bool) :
  6194. side f l k b = firstSuffix f l x y ++ pick x y b :: pick x y (!b) :: lastSuffix f k x y := by
  6195. cases b <;> simp [side,Frame.core,Frame.early,Frame.pair,firstSuffix,lastSuffix,hp,hq,
  6196. singleton_mid f hp hq,pick,List.append_assoc]
  6197. private theorem sum_append (a b : W) : (a++b).sum = a.sum+b.sum := by
  6198. induction a with
  6199. | nil => simp
  6200. | cons x a ih => simp [ih,Nat.add_assoc]
  6201. private theorem same_base (f : Frame Nat) (l k names : W) {x y : Nat} (hp : f.p = [x])
  6202. (hq : f.q = [y]) (b : Bool) :
  6203. base (side f l k b) names = base (side f l k false) names := by
  6204. cases b <;> simp [literal_pair f l k hp hq,base,sum_append,pick,Nat.add_comm,
  6205. Nat.add_left_comm,Nat.add_assoc]
  6206. private def make (f : Frame Nat) (names : W) (x y head : Nat) : Frame Nat :=
  6207. let n := finish names head f.middle
  6208. let p := n+span names f.beforeMutable+2
  6209. { pHead := x, pTail := [], qInit := [], qLast := y, tag := f.tag,
  6210. middle := encodeMiddle names head f.middle, beforeMutable := enc names n f.beforeMutable,
  6211. beforeFinalP := enc names p f.beforeFinalP,
  6212. beforeFinalQ := enc names (p+span names f.beforeFinalP+1) f.beforeFinalQ }
  6213. private theorem enc_frame (f : Frame Nat) (l k names : W) {x y : Nat} (hx : x ∈ names)
  6214. (hy : y ∈ names) (hp : f.p = [x]) (hq : f.q = [y]) (start : Nat) :
  6215. let head := start+span names l+6
  6216. let n := finish names head f.middle
  6217. let p := n+span names f.beforeMutable+2
  6218. let q := p+span names f.beforeFinalP+1
  6219. let g := make f names x y head
  6220. ∀ b, enc names start (side f l k b) =
  6221. side g (enc names start l) (enc names (q+span names f.beforeFinalQ+1) k) b := by
  6222. dsimp only
  6223. intro b
  6224. let head := start+span names l+6
  6225. let g := make f names x y head
  6226. have gp : g.p = [x] := rfl
  6227. have gq : g.q = [y] := rfl
  6228. change _ = side g _ _ b
  6229. cases b <;>
  6230. simp only [literal_pair f l k hp hq,literal_pair g _ _ gp gq,firstSuffix,lastSuffix,
  6231. pick,Bool.not_false,Bool.not_true,Bool.false_eq_true,if_false,if_true,
  6232. List.append_assoc,List.cons_append,List.nil_append] <;>
  6233. rw [enc_cut hx,enc_cons hx,enc_cons hy,enc_cons hx,enc_cons hy,enc_cons hy,
  6234. enc_middle hx hy] <;>
  6235. first
  6236. | rw [enc_cut hx,enc_cons hy,enc_cut hx,enc_cut hy]
  6237. | rw [enc_cut hy,enc_cons hx,enc_cut hx,enc_cut hy]
  6238. all_goals rfl
  6239. private theorem lookup_congr (pre p q : List Piece)
  6240. (same : ∀ n, lookup n p = lookup n q) (n : Nat) :
  6241. lookup n (pre ++ p) = lookup n (pre ++ q) := by
  6242. induction pre generalizing n with
  6243. | nil => exact same n
  6244. | cons c cs ih =>
  6245. cases c with
  6246. | literal a => exact ih (n+1)
  6247. | gap w => funext a; simp [lookup,congrFun (ih (n+1)) a]
  6248. /-- Both smaller words use the same expansion, including corresponding gap
  6249. variables on either side of the mutable pair. -/
  6250. theorem same_expansion (f : Frame Nat) (l k names : W) {x y : Nat} (hx : x ∈ names)
  6251. (hy : y ∈ names) (hp : f.p = [x]) (hq : f.q = [y]) (b : Bool) :
  6252. expand (side f l k b) names = expand (side f l k false) names := by
  6253. unfold expand
  6254. rw [same_base f l k names hp hq b]
  6255. cases b with
  6256. | false => rfl
  6257. | true =>
  6258. rw [literal_pair f l k hp hq true,literal_pair f l k hp hq false]
  6259. simp only [pick,Bool.not_true,Bool.not_false,Bool.false_eq_true,if_false,if_true,
  6260. pieces_cut _ _ _ _ hx,pieces_cut _ _ _ _ hy,pieces,hx,hy,if_true]
  6261. apply lookup_congr
  6262. intro n
  6263. rfl
  6264. /-- For any common retained list containing x and y, both canonical shorter
  6265. words form one common valid literal singleton frame with equal contexts.
  6266. Its one expansion simultaneously recovers the two original words. -/
  6267. theorem canonical_pair {r allow} (f : Frame Nat) (l k names : W) {x y : Nat}
  6268. (hx : x ∈ names) (hy : y ∈ names) (hp : f.p = [x]) (hq : f.q = [y])
  6269. (valid : f.Valid r allow (fun _ _ => False)) (origBit : Bool)
  6270. (cap : Cap r (side f l k origBit)) :
  6271. ∃ (g : Frame Nat) (left right : W),
  6272. g.p = [x] ∧ g.q = [y] ∧ g.Valid r allow (fun _ _ => False) ∧
  6273. (∀ b, small (side f l k b) names = side g left right b) ∧
  6274. (∀ b, (side g left right b).flatMap (expand (side f l k origBit) names) = side f l k b) := by
  6275. let start := base (side f l k false) names
  6276. let head := start+span names l+6
  6277. let n := finish names head f.middle
  6278. let p := n+span names f.beforeMutable+2
  6279. let q := p+span names f.beforeFinalP+1
  6280. let g := make f names x y head
  6281. let left := enc names start l
  6282. let right := enc names (q+span names f.beforeFinalQ+1) k
  6283. have gp : g.p = [x] := rfl
  6284. have gq : g.q = [y] := rfl
  6285. have eq (b : Bool) : small (side f l k b) names = side g left right b := by
  6286. unfold small
  6287. rw [same_base f l k names hp hq b]
  6288. exact enc_frame f l k names hx hy hp hq start b
  6289. have bound : Cap r (side g left right origBit) := by
  6290. rw [← eq]
  6291. apply (canonical (side f l k origBit) names).small_cap (by have := valid.1; omega)
  6292. rw [recover]
  6293. exact cap
  6294. have v : g.Valid r allow (fun _ _ => False) := by
  6295. apply g.valid_of_capped_shape valid.1 valid.2.1 _ _ _ _ _ origBit left right bound
  6296. · exact (mid_tags names head f.middle).trans valid.2.2.1
  6297. · simpa only [gp,← hp] using valid.2.2.2.1
  6298. · simpa only [gq,← hq] using valid.2.2.2.2.1
  6299. · simpa only [gp,gq,← hp,← hq] using valid.2.2.2.2.2.1
  6300. · simp
  6301. refine ⟨g,left,right,gp,gq,v,eq,?_⟩
  6302. intro b
  6303. rw [← eq,(same_expansion f l k names hx hy hp hq origBit).trans
  6304. (same_expansion f l k names hx hy hp hq b).symm]
  6305. exact recover _ _
  6306. end P455CompressedFrame
  6307. end
  6308. /- Begin Problem455DefectRename (from finite-semigroup-identity-bases). -/
  6309. section
  6310. namespace P455DefectRename
  6311. open P455Witness P455Paths P455ContactLift P455SourceFamilies
  6312. open P455ContactReflection P455PortReflection P455DefectProjection Problem455.Slots
  6313. def decode (keep : W) (i : Nat) : Nat := (keep[i]?).getD 0
  6314. theorem decode_idx (keep : W) {a : Nat} (h : a ∈ keep) : decode keep (keep.idxOf a) = a := by
  6315. induction keep with
  6316. | nil => contradiction
  6317. | cons b keep ih =>
  6318. by_cases eq : b = a
  6319. · subst b; simp [decode]
  6320. · have ha : a ∈ keep := (List.mem_cons.mp h).resolve_left (Ne.symm eq)
  6321. simpa [decode,List.idxOf_cons,cond_eq_if,beq_iff_eq,eq] using ih ha
  6322. theorem decode_map {keep w : W} (hs : ∀ a ∈ w, a ∈ keep) :
  6323. (w.map keep.idxOf).map (decode keep) = w := by
  6324. rw [List.map_map]
  6325. calc
  6326. _ = w.map id := List.map_congr_left (fun a ha => decode_idx keep (hs a ha))
  6327. _ = w := List.map_id w
  6328. def extend (keep : W) (a : Nat) := if a ∈ keep then keep.idxOf a else keep.length + a
  6329. theorem extend_inj (keep : W) {a b : Nat} (h : extend keep a = extend keep b) : a = b := by
  6330. by_cases ha : a ∈ keep <;> by_cases hb : b ∈ keep <;> simp only [extend,ha,hb,if_true,if_false] at h
  6331. · simpa only [decode_idx keep ha, decode_idx keep hb] using congrArg (decode keep) h
  6332. · have := List.idxOf_lt_length_of_mem ha; omega
  6333. · have := List.idxOf_lt_length_of_mem hb; omega
  6334. · omega
  6335. abbrev Injects (d : Nat → Nat) := ∀ {a b}, d a = d b → a = b
  6336. theorem select_map_inj (d : Nat → Nat) (inj : Injects d) (keep w : W) :
  6337. select (keep.map d) (w.map d) = (select keep w).map d := by
  6338. induction w with
  6339. | nil => rfl
  6340. | cons a w ih =>
  6341. have iff : d a ∈ keep.map d ↔ a ∈ keep := by
  6342. constructor
  6343. · intro h; obtain ⟨b,hb,eq⟩ := List.mem_map.mp h; exact inj eq ▸ hb
  6344. · exact List.mem_map_of_mem
  6345. by_cases ha : a ∈ keep <;> simp_all [select]
  6346. theorem kept {keep w : W} {a : Nat} (h : a ∈ select keep w) : a ∈ keep := by
  6347. simpa using (List.mem_filter.mp h).2
  6348. theorem extend_map {keep w : W} (hs : ∀ a ∈ w, a ∈ keep) :
  6349. w.map (extend keep) = w.map keep.idxOf :=
  6350. List.map_congr_left (fun a ha => by simp [extend, hs a ha])
  6351. theorem binary_select_map (keep w : W) {x y : Nat} (hx : x ∈ keep) (hy : y ∈ keep) :
  6352. (select [x,y] w).map keep.idxOf =
  6353. select [keep.idxOf x,keep.idxOf y] ((select keep w).map keep.idxOf) := by
  6354. have h := select_map_inj (extend keep) (extend_inj keep) [x,y] (select keep w)
  6355. rw [select_sub keep [x,y] w (by simpa using And.intro hx hy),
  6356. extend_map (fun _ ha => kept ha),
  6357. extend_map (keep := keep) (w := select [x,y] w) (by
  6358. intro a ha; have hxy : a = x ∨ a = y := by simpa using kept ha
  6359. rcases hxy with rfl|rfl <;> assumption)] at h
  6360. simpa [extend,hx,hy] using h.symm
  6361. theorem count_rename (d : Nat → Nat) (inj : Injects d) (w : W) (a : Nat) :
  6362. (w.map d).count (d a) = w.count a := by
  6363. induction w with
  6364. | nil => rfl
  6365. | cons b w ih =>
  6366. by_cases eq : b = a
  6367. · subst b; simp [ih]
  6368. · have ne : d b ≠ d a := fun e => eq (inj e)
  6369. simp [eq,ne,ih, List.count_cons, beq_iff_eq]
  6370. theorem cap_rename {r w} (d : Nat → Nat) (inj : Injects d) (cp : P455Closure.Cap r w) :
  6371. P455Closure.Cap r (w.map d) := by
  6372. intro a
  6373. by_cases mem : a ∈ w.map d
  6374. · obtain ⟨b,_,rfl⟩ := List.mem_map.mp mem
  6375. simpa only [count_rename d inj] using cp b
  6376. · simp [List.count_eq_zero.mpr mem]
  6377. theorem rename_sees (d : Nat → Nat) (inj : Injects d) {w pat} (obs : sees w pat) :
  6378. sees (w.map d) (pat.map (eventMap d)) := by
  6379. unfold sees events at *
  6380. rw [← stamp_map d w w (fun _ => 0) (fun _ => 0) (fun _ h => h) (fun _ _ _ _ h => inj h) (fun _ _ => rfl)]
  6381. exact obs.map _
  6382. theorem rename_order {r allow src dst w} (d : Nat → Nat) (inj : Injects d) (pat : List Event)
  6383. (h : Holds r allow src w (.order pat)) :
  6384. Holds r allow dst (w.map d) (.order (pat.map (eventMap d))) := by
  6385. refine ⟨?_,rename_sees d inj h.2⟩
  6386. intro e he; obtain ⟨f,hf,rfl⟩ := List.mem_map.mp he; exact h.1 f hf
  6387. theorem rename_pattern (d : Nat → Nat) (inj : Injects d) {w a b tag bit}
  6388. (h : select [a,b] w = profile a b tag bit) :
  6389. select [d a,d b] (w.map d) = profile (d a) (d b) tag bit := by
  6390. rw [← map_profile d a b tag bit, ← h, ← select_map_inj d inj [a,b] w]
  6391. rfl
  6392. theorem rename_marked {r allow src w} (d : Nat → Nat) (inj : Injects d) (n : Node) (bit : Bool)
  6393. (h : Holds r allow src w (markedNode n bit)) :
  6394. Holds r allow (markNode (sendNode d n)) (w.map d) (markedNode (sendNode d n) bit) :=
  6395. ⟨fun e => h.1 (inj e),h.2.1,h.2.2.1,.inl ⟨rfl,rfl⟩,rename_pattern d inj h.2.2.2.2⟩
  6396. theorem rename_record {r allow src dst w a b tag} (d : Nat → Nat) (inj : Injects d)
  6397. (h : Holds r allow src w (.record a b tag)) :
  6398. Holds r allow dst (w.map d) (.record (d a) (d b) tag) := by
  6399. obtain ⟨ne,len,ok,bit,pr⟩ := h
  6400. exact ⟨fun e => ne (inj e),len,ok,bit,rename_pattern d inj pr⟩
  6401. theorem rename_contact {r allow src dst w} (d : Nat → Nat) (inj : Injects d) (a b : Nat) (c : ContactChoice)
  6402. (h : Holds r allow src w (contact r a b c)) :
  6403. Holds r allow dst (w.map d) (contact r (d a) (d b) c) := by
  6404. cases c with
  6405. | record tag rev => cases rev <;> exact rename_record d inj h
  6406. | port phase rev =>
  6407. obtain ⟨ab,ac,bc,early,obs,last⟩ := h
  6408. refine ⟨fun e => ab (inj e),(count_rename d inj w a).trans ac,(count_rename d inj w b).trans bc,?_,?_,last⟩
  6409. · rcases early with ⟨h,_⟩|⟨h,_⟩
  6410. · exact .inl ⟨rename_order d inj [(a,2),(b,0)] h,True.intro⟩
  6411. · exact .inr ⟨rename_order d inj [(b,2),(a,0)] h,True.intro⟩
  6412. · cases rev <;> exact rename_order d inj _ obs
  6413. theorem rename_walk {r allow src dst w} (d : Nat → Nat) (inj : Injects d) (a : Nat) (p : List Step)
  6414. (h : Walk r allow src w a p) :
  6415. Walk r allow dst (w.map d) (d a) (relabel d p) := by
  6416. induction p generalizing a with
  6417. | nil => trivial
  6418. | cons bc p ih => exact ⟨rename_contact d inj a bc.1 bc.2 h.1,ih _ h.2⟩
  6419. theorem rename_deficient {r allow w} (d : Nat → Nat) (inj : Injects d) (s : SlotCertificate)
  6420. (b : Nat) (kind : s.defect = .deficient b) (h : Holds r allow (markNode s.anchor) w (s.query r)) :
  6421. Holds r allow (markNode (sendSlot d s).anchor) (w.map d) ((sendSlot d s).query r) := by
  6422. obtain ⟨len,walk,term⟩ := slot_route s h
  6423. let start := picked s
  6424. have start' : picked (sendSlot d s) = d start := by
  6425. cases side : s.startAtMate <;> simp [sendSlot,picked,sendNode,start,side]
  6426. rw [kind] at term
  6427. obtain ⟨⟨slot,j,seen⟩,cnt⟩ := term
  6428. refine ⟨rename_marked d inj s.anchor s.bit h.1,by simpa [sendSlot,relabel,P455Witness.Holds] using len,?_,True.intro⟩
  6429. apply (route_iff ..).mpr
  6430. change Walk _ _ _ _ (picked (sendSlot d s)) (relabel d s.steps) ∧ Holds _ _ _ _
  6431. (terminalSlot r (endpoint (picked (sendSlot d s)) (relabel d s.steps)) s.terminalIndex (sendDefect d s.defect))
  6432. rw [start',endpoint_relabel,kind]
  6433. exact ⟨rename_walk d inj start s.steps walk,⟨slot,j,rename_sees d inj seen⟩,by simpa only [Holds,count_rename d inj] using cnt⟩
  6434. theorem canonical_defect {r allow mark u} (cap : P455Closure.Cap r u) (n : Node) (bit side : Bool)
  6435. (t i bad : Nat) (anchor : Holds r allow (markNode n) u (markedNode n bit))
  6436. (near : Near r allow mark u (if side then n.mate else n.owner) t 6)
  6437. (slot : slotStart i) (occ : occupies u t i bad) (deficient : u.count bad < r) :
  6438. ∃ (keep : W) (s : SlotCertificate), keep.length ≤ 9 ∧ n.owner ∈ keep ∧ n.mate ∈ keep ∧
  6439. s.anchor.owner = keep.idxOf n.owner ∧ s.anchor.mate = keep.idxOf n.mate ∧ s.bit = bit ∧
  6440. s.defect = .deficient (keep.idxOf bad) ∧ (∀ a ∈ (select keep u).map keep.idxOf, a < 9) ∧
  6441. P455Closure.Cap r ((select keep u).map keep.idxOf) ∧
  6442. Holds r allow (markNode s.anchor) ((select keep u).map keep.idxOf) (s.query r) := by
  6443. obtain ⟨keep,s,len,ho,hm,hb,kind,anc,bs,cp,h⟩ :=
  6444. bounded_defect_kind cap n bit side t i bad anchor near slot occ deficient
  6445. let d := extend keep
  6446. have mapEq := extend_map (keep := keep) (w := select keep u) (fun _ ha => kept ha)
  6447. have valid := rename_deficient d (extend_inj keep) s bad kind (by simpa only [anc] using h)
  6448. refine ⟨keep,sendSlot d s,len,ho,hm,by simp [sendSlot,sendNode,d,extend,anc,ho],
  6449. by simp [sendSlot,sendNode,d,extend,anc,hm],bs,by simp [sendSlot,sendDefect,kind,d,extend,hb],?_,?_,?_⟩
  6450. · intro a ha; obtain ⟨b,bm,rfl⟩ := List.mem_map.mp ha
  6451. exact Nat.lt_of_lt_of_le (List.idxOf_lt_length_of_mem (kept bm)) len
  6452. · rw [← mapEq]; exact cap_rename d (extend_inj keep) cp
  6453. · rw [← mapEq]; exact valid
  6454. end P455DefectRename
  6455. end
  6456. /- Begin Problem455BlockSeparators (from finite-semigroup-identity-bases). -/
  6457. section
  6458. namespace P455BlockSeparators
  6459. open P455Witness Problem455.Slots Problem455Swap
  6460. /-- A directed path of the literal repeated bigrams. -/
  6461. inductive Directed (e : Nat → Nat → Prop) : Nat → Nat → Prop
  6462. | refl (a) : Directed e a a
  6463. | snoc {a b c} : Directed e a b → e b c → Directed e a c
  6464. theorem prepend {e a b c} (h : e a b) (p : Directed e b c) : Directed e a c := by
  6465. induction p with
  6466. | refl => exact .snoc (.refl _) h
  6467. | snoc _ last ih => exact .snoc ih last
  6468. theorem split_first {e a b} (p : Directed e a b) :
  6469. a = b ∨ ∃ c, e a c ∧ Directed e c b := by
  6470. induction p with
  6471. | refl => exact .inl rfl
  6472. | @snoc y z _ last ih =>
  6473. rcases ih with eq|⟨c,first,rest⟩
  6474. · exact .inr ⟨z, eq ▸ last,.refl z⟩
  6475. · exact .inr ⟨c,first,.snoc rest last⟩
  6476. theorem orient {e a b} (outgoing : ∀ {x y z}, e x y → e x z → y = z)
  6477. (incoming : ∀ {x y z}, e y x → e z x → y = z) (p : Joined e a b) :
  6478. Directed e a b ∨ Directed e b a := by
  6479. induction p with
  6480. | refl => exact .inl (.refl _)
  6481. | @extend y z prev h ih =>
  6482. rcases ih with f|b
  6483. · rcases h with f'|b'
  6484. · exact .inl (.snoc f f')
  6485. · cases f with
  6486. | refl => exact .inr (.snoc (.refl _) b')
  6487. | snoc rest last => exact .inl (incoming last b' ▸ rest)
  6488. · rcases h with f'|b'
  6489. · rcases split_first b with eq|⟨c,first,rest⟩
  6490. · exact .inl (eq ▸ Directed.snoc (.refl _) f')
  6491. · exact .inr (outgoing first f' ▸ rest)
  6492. · exact .inr (prepend b' b)
  6493. theorem directed_of_same {r w a b} (hr : 0 < r) (cap : P455Closure.Cap r w)
  6494. (same : SameBlock r w a b) : Directed (Link r w) a b ∨ Directed (Link r w) b a := by
  6495. apply orient _ _ same.2.2
  6496. · intro x y z xy xz
  6497. apply Classical.byContradiction; intro ne
  6498. have h := out_bound x y z ne w
  6499. rw [show bigram x y w = r from xy,show bigram x z w = r from xz,Problem455BlockBridge.occ_count] at h
  6500. have hx := cap x; omega
  6501. · intro x y z yx zx
  6502. apply Classical.byContradiction; intro ne
  6503. have h := Nat.le_trans (in_bound y z x ne w) (tail_occ_le x w)
  6504. rw [show bigram y x w = r from yx,show bigram z x w = r from zx,Problem455BlockBridge.occ_count] at h
  6505. have hx := cap x; omega
  6506. /-- Suffixes starting at each occurrence, listed in word order. -/
  6507. def rows (a : Nat) : W → List W
  6508. | [] => []
  6509. | b :: w => if a = b then (b :: w) :: rows a w else rows a w
  6510. theorem rows_length (a : Nat) (w : W) : (rows a w).length = w.count a := by
  6511. induction w with
  6512. | nil => rfl
  6513. | cons b w ih => by_cases eq : a = b <;> simp_all [rows,List.count_cons,beq_iff_eq,Ne.symm]
  6514. /-- Each row can be shifted exactly one position across a repeated
  6515. link. This includes equality of the entire remaining suffix, rather
  6516. than a numerical comparison of positions. -/
  6517. private def edgeRows (a b : Nat) : W → List W
  6518. | [] => []
  6519. | c :: w => if c = a ∧ w.head? = some b then w :: edgeRows a b w else edgeRows a b w
  6520. private theorem edgeRows_length (a b : Nat) (w : W) : (edgeRows a b w).length = bigram a b w := by
  6521. induction w with
  6522. | nil => rfl
  6523. | cons c w ih =>
  6524. by_cases test : c = a ∧ w.head? = some b <;> simp [edgeRows,bigram,hit,test,ih,Nat.add_comm]
  6525. private theorem edge_sub_left (a b : Nat) (w : W) :
  6526. ((edgeRows a b w).map (List.cons a)).Sublist (rows a w) := by
  6527. induction w with
  6528. | nil => exact .slnil
  6529. | cons c w ih =>
  6530. by_cases k : c = a
  6531. · subst c
  6532. by_cases h : w.head? = some b
  6533. · simpa [edgeRows,rows,h] using ih.cons₂ (a::w)
  6534. · simpa [edgeRows,rows,h] using ih.cons (a::w)
  6535. · simpa [rows,edgeRows,k,Ne.symm k] using ih
  6536. private theorem edge_sub_right (a b : Nat) (w : W) :
  6537. (edgeRows a b w).Sublist (rows b w.tail) := by
  6538. induction w with
  6539. | nil => exact .slnil
  6540. | cons c w ih =>
  6541. cases w with
  6542. | nil => simp [rows,edgeRows]
  6543. | cons x t =>
  6544. by_cases mem : x = b
  6545. · subst x
  6546. by_cases yes : c = a
  6547. · simpa [rows,edgeRows,yes] using ih.cons₂ (b::t)
  6548. · simpa [rows,edgeRows,yes] using ih.cons (b::t)
  6549. · simpa [rows,edgeRows,mem,Ne.symm mem] using ih
  6550. theorem link_rows {r a b w} (cap : P455Closure.Cap r w) (link : Link r w a b) :
  6551. rows a w = (rows b w).map (List.cons a) := by
  6552. have l := edge_sub_left a b w
  6553. have f := edge_sub_right a b w
  6554. have s : (rows b w.tail).Sublist (rows b w) := by
  6555. cases w with
  6556. | nil => exact .slnil
  6557. | cons x t =>
  6558. by_cases eq : b=x
  6559. · simp [rows,eq]
  6560. · simp [rows,eq]
  6561. have t := f.trans s
  6562. have len : (edgeRows a b w).length = r := (edgeRows_length ..).trans link
  6563. have e := t.eq_of_length_le (by rw [rows_length,len]; exact cap b)
  6564. have g := l.eq_of_length_le (by rw [List.length_map,rows_length,len]; exact cap a)
  6565. rw [← g,e]
  6566. theorem directed_prefix {r w a b} (cap : P455Closure.Cap r w) (p : Directed (Link r w) a b) :
  6567. ∃ pre : W, rows a w = (rows b w).map (pre ++ ·) := by
  6568. induction p with
  6569. | refl => exact ⟨[],by simp⟩
  6570. | @snoc y z prev edge ih =>
  6571. obtain ⟨pre,h⟩ := ih
  6572. refine ⟨pre ++ [y],?_⟩
  6573. rw [h,link_rows cap edge,List.map_map]
  6574. apply List.map_congr_left
  6575. intro row _; simp
  6576. theorem row_head {a : Nat} {w row : W} (h : row ∈ rows a w) : row.head? = some a := by
  6577. induction w with
  6578. | nil => contradiction
  6579. | cons x w ih =>
  6580. by_cases eq : a=x
  6581. · subst x; rcases (show row = a::w ∨ row ∈ rows a w by simpa [rows] using h) with rfl|old
  6582. · rfl
  6583. · exact ih old
  6584. · exact ih (by simpa [rows,eq] using h)
  6585. theorem all_next {w : W} (a b : Nat)
  6586. (h : ∀ z ∈ rows a w, z.tail.head? = some b) : bigram a b w = w.count a := by
  6587. induction w with
  6588. | nil => rfl
  6589. | cons x w ih =>
  6590. by_cases eq : x=a
  6591. · subst x
  6592. have next := h (a::w) (by simp [rows])
  6593. have recProof := ih (fun z hz => h z (by simp [rows,hz]))
  6594. simp [bigram,hit,show w.head? = some b from next,recProof,Nat.add_comm]
  6595. · have recProof := ih (fun z hz => h z (by simp [rows,Ne.symm eq,hz]))
  6596. simp [bigram,hit,eq,recProof,List.count_cons,beq_iff_eq]
  6597. theorem directed_of_prefix {r w b} (hr : 0 < r) (cap : P455Closure.Cap r w)
  6598. (cb : w.count b = r) (pre : W) (a : Nat)
  6599. (eq : rows a w = (rows b w).map (pre ++ ·)) : Directed (Link r w) a b := by
  6600. have non : rows b w ≠ [] := by
  6601. intro z; have h := rows_length b w; rw [z,cb] at h; simp at h; omega
  6602. obtain ⟨z,hz⟩ := List.exists_mem_of_ne_nil _ non
  6603. induction pre generalizing a with
  6604. | nil =>
  6605. have e : rows a w = rows b w := by simpa using eq
  6606. have ma := row_head (e ▸ hz : z ∈ rows a w)
  6607. exact (show a=b by simpa [row_head hz] using ma.symm) ▸ Directed.refl _
  6608. | cons c p ih =>
  6609. have ma := row_head (w := w) (a := a) (row := (c::p)++z)
  6610. (eq ▸ List.mem_map_of_mem hz)
  6611. have ac : c=a := by simpa using ma
  6612. subst c
  6613. let next := p.head?.getD b
  6614. have all (v) (hv : v ∈ rows b w) : (p ++ v).head? = some next := by
  6615. cases p with
  6616. | nil => simpa [next] using row_head hv
  6617. | cons x xs => rfl
  6618. have ct : w.count a = r := by simpa [rows_length,cb] using congrArg List.length eq
  6619. have li : Link r w a next := by
  6620. apply Eq.trans _ ct; apply all_next
  6621. intro t ht
  6622. rw [eq] at ht
  6623. obtain ⟨v,hv,rfl⟩ := List.mem_map.mp ht
  6624. exact all v hv
  6625. apply prepend li
  6626. apply ih
  6627. have strip := congrArg (List.map List.tail) ((link_rows cap li).symm.trans eq)
  6628. simpa [List.map_map,Function.comp_def] using strip
  6629. theorem directed_joined {e a b} (p : Directed e a b) : Joined e a b := by
  6630. induction p with
  6631. | refl => exact .refl _
  6632. | snoc _ last ih => exact .extend ih (.inl last)
  6633. theorem reversed_joined {e a b} (p : Directed e a b) : Joined e b a := by
  6634. induction p with
  6635. | refl => exact .refl _
  6636. | snoc _ last ih =>
  6637. have cat {x y z} (p : Joined e x y) (q : Joined e y z) : Joined e x z := by
  6638. induction q with
  6639. | refl => exact p
  6640. | extend _ t j => exact .extend j t
  6641. exact cat (.extend (.refl _) (.inr last)) ih
  6642. theorem project_rows (keep : W) {a : Nat} (ha : a ∈ keep) (w : W) :
  6643. rows a (select keep w) = (rows a w).map (select keep) := by
  6644. induction w with
  6645. | nil => rfl
  6646. | cons b w ih =>
  6647. by_cases eq : a=b
  6648. · subst b; simp [rows,select,ha,ih] at *
  6649. · by_cases hb : b ∈ keep <;> simp [rows,select,ha,hb,eq,ih] at *
  6650. theorem pair_ext {w v : W} (pairs : ∀ c d : Nat, select [c,d] w = select [c,d] v) : w = v := by
  6651. induction w generalizing v with
  6652. | nil =>
  6653. cases v with
  6654. | nil => rfl
  6655. | cons b v => simpa [select] using pairs b b
  6656. | cons a w ih =>
  6657. cases v with
  6658. | nil => simpa [select] using pairs a a
  6659. | cons b v =>
  6660. have eq : a = b := by simpa [select] using congrArg List.head? (pairs a b)
  6661. subst b
  6662. apply congrArg (List.cons a)
  6663. apply ih
  6664. intro c d
  6665. by_cases ac : a = c <;> by_cases ad : a = d <;> simpa [select,ac,ad] using pairs c d
  6666. theorem rowmaps_ext {as bs : List W} (pairs : ∀ c d : Nat,
  6667. as.map (select [c,d]) = bs.map (select [c,d])) : as = bs := by
  6668. induction as generalizing bs with
  6669. | nil => cases bs with
  6670. | nil => rfl
  6671. | cons b bs => simpa using pairs 0 0
  6672. | cons a as ih =>
  6673. cases bs with
  6674. | nil => simpa using pairs 0 0
  6675. | cons b bs =>
  6676. have h (c d) := List.cons.inj (show select [c,d] a :: as.map (select [c,d]) =
  6677. select [c,d] b :: bs.map (select [c,d]) from pairs c d)
  6678. exact List.cons.injEq _ _ _ _ |>.mpr ⟨pair_ext fun c d => (h c d).1,ih fun c d => (h c d).2⟩
  6679. theorem row_suffix {a : Nat} {w row : W} (m : row ∈ rows a w) : row <:+ w := by
  6680. induction w with
  6681. | nil => contradiction
  6682. | cons x w ih =>
  6683. by_cases eq : a=x
  6684. · subst x; rcases (show row = a::w ∨ row ∈ rows a w by simpa [rows] using m) with rfl|old
  6685. · exact List.suffix_refl _
  6686. · exact (ih old).trans (List.suffix_cons _ _)
  6687. · exact (ih (by simpa [rows,eq] using m)).trans (List.suffix_cons _ _)
  6688. theorem project_prefix (keep : W) (pre : W) (bs : List W) :
  6689. (bs.map (pre ++ ·)).map (select keep) =
  6690. (bs.map (select keep)).map (select keep pre ++ ·) := by
  6691. simp [List.map_map, Function.comp_def, select, List.filter_append]
  6692. /-- A putative merger in every extension of some two extra names
  6693. recovers an actual directed repeated block in the original word.
  6694. The orientation is fixed by the first rows in the original word. -/
  6695. private theorem reconstruct {r w a b} (hr : 0 < r) (cp : P455Closure.Cap r w)
  6696. (cb : w.count b = r) (ne : a ≠ b) (A B : W) (As Bs : List W)
  6697. (aa : rows a w = A::As) (bb : rows b w = B::Bs) (pre : W) (first : A = pre ++ B)
  6698. (merges : ∀ c d : Nat, ∃ keep : W, a ∈ keep ∧ b ∈ keep ∧ c ∈ keep ∧ d ∈ keep ∧
  6699. SameBlock r (select keep w) a b) : Directed (Link r w) a b := by
  6700. have ma : A ∈ rows a w := by simp [aa]
  6701. have mb : B ∈ rows b w := by simp [bb]
  6702. have headA := row_head ma
  6703. have headB := row_head mb
  6704. have pre_head : pre.head? = some a := by
  6705. cases pre with
  6706. | nil => simp_all
  6707. | cons x p => simpa [first] using headA
  6708. apply directed_of_prefix hr cp cb pre
  6709. apply rowmaps_ext
  6710. intro c d
  6711. obtain ⟨keep,ha,hb,hc,hd,sm⟩ := merges c d
  6712. have not_empty : select keep pre ≠ [] := by
  6713. cases pre with
  6714. | nil => contradiction
  6715. | cons x p =>
  6716. have eq : x=a := by simpa using pre_head
  6717. simp [select,eq,ha]
  6718. have rx := project_rows keep ha w
  6719. have ry := project_rows keep hb w
  6720. have capK := P455DefectProjection.select_cap keep cp
  6721. have hdir := directed_of_same hr capK sm
  6722. have orient' : ∃ k : W, rows a (select keep w) = (rows b (select keep w)).map (k ++ ·) := by
  6723. rcases hdir with f|g
  6724. · exact directed_prefix capK f
  6725. · obtain ⟨k,h⟩ := directed_prefix capK g
  6726. rw [rx,ry,aa,bb] at h
  6727. have eq := (List.cons.inj h).1
  6728. have len := congrArg List.length eq
  6729. simp only [first,select_append,List.length_append] at len
  6730. have pos := List.length_pos_iff.mpr not_empty
  6731. omega
  6732. obtain ⟨k,h⟩ := orient'
  6733. rw [rx,ry] at h
  6734. have fst := h
  6735. rw [aa,bb] at fst
  6736. have eq := (List.cons.inj fst).1
  6737. change select keep A = k ++ select keep B at eq
  6738. rw [first,select_append] at eq
  6739. have := List.append_cancel_right eq
  6740. subst k
  6741. rw [← project_prefix] at h
  6742. let f := select [c,d]
  6743. have nested : ∀ z : W, f (select keep z) = f z := fun z =>
  6744. P455DefectProjection.select_sub keep [c,d] z (by simpa using And.intro hc hd)
  6745. have proj := congrArg (List.map f) h
  6746. simpa only [List.map_map, Function.comp_def,nested] using proj
  6747. theorem robust_separators {r w a b} (hr : 0 < r) (cp : P455Closure.Cap r w)
  6748. (ca : w.count a = r) (cb : w.count b = r) (apart : ¬ SameBlock r w a b) :
  6749. ∃ c d : Nat, ∀ keep : W, a ∈ keep → b ∈ keep → c ∈ keep → d ∈ keep →
  6750. ¬ SameBlock r (select keep w) a b := by
  6751. classical
  6752. apply Classical.byContradiction
  6753. intro contra
  6754. have merges : ∀ c d : Nat, ∃ keep : W, a ∈ keep ∧ b ∈ keep ∧ c ∈ keep ∧ d ∈ keep ∧
  6755. SameBlock r (select keep w) a b := by
  6756. intro c d
  6757. apply Classical.byContradiction; intro miss
  6758. apply contra; refine ⟨c,d,?_⟩
  6759. intro keep ha hb hc hd hm
  6760. exact miss ⟨keep,ha,hb,hc,hd,hm⟩
  6761. have oba : occ a w = r := (Problem455BlockBridge.occ_count ..).trans ca
  6762. have obb : occ b w = r := (Problem455BlockBridge.occ_count ..).trans cb
  6763. have ne : a ≠ b := by rintro rfl; exact apart ⟨oba,obb,.refl _⟩
  6764. apply apart
  6765. refine ⟨oba,obb,?_⟩
  6766. have split (z : Nat) (cz : w.count z = r) : ∃ h t, rows z w = h::t := by
  6767. cases eq : rows z w with
  6768. | nil => have := rows_length z w; rw [eq,cz] at this; simp at this; omega
  6769. | cons h t => exact ⟨h,t,rfl⟩
  6770. obtain ⟨A,As,aa⟩ := split a ca
  6771. obtain ⟨B,Bs,bb⟩ := split b cb
  6772. rcases List.suffix_or_suffix_of_suffix (row_suffix (a := b) (by simp [bb] : B ∈ rows b w))
  6773. (row_suffix (a := a) (by simp [aa] : A ∈ rows a w)) with ⟨pre,h⟩|⟨pre,h⟩
  6774. · exact directed_joined (reconstruct hr cp cb ne A B As Bs aa bb pre h.symm merges)
  6775. · apply reversed_joined (reconstruct hr cp ca ne.symm B A Bs As bb aa pre h.symm ?_)
  6776. intro c d
  6777. obtain ⟨keep,ha,hb,hc,hd,m⟩ := merges c d
  6778. refine ⟨keep,hb,ha,hc,hd,m.2.1,m.1,?_⟩
  6779. rcases directed_of_same hr (P455DefectProjection.select_cap keep cp) m with f|g
  6780. · exact reversed_joined f
  6781. · exact directed_joined g
  6782. end P455BlockSeparators
  6783. end
  6784. /- Begin Problem455FirstTesters (from finite-semigroup-identity-bases). -/
  6785. section
  6786. namespace P455FirstTesters
  6787. open P455FirstRewrite P455Quotient
  6788. def plain (r : Nat) : Rules Nat where
  6789. r := r
  6790. step := fun _ _ => False
  6791. reverse := False.elim
  6792. counts := False.elim
  6793. extend := False.elim
  6794. def power (r : Nat) : W := List.replicate r 0
  6795. def Binary (r : Nat) (T : W) := (∀ x ∈ T, x = 0 ∨ x = 1) ∧
  6796. Cap r T ∧ 0 < T.count 0 ∧ 0 < T.count 1 ∧ (T.count 0 < r ∨ T.count 1 < r)
  6797. abbrev Index (r : Nat) := { T : W // T = power r ∨ Binary r T }
  6798. def Index.cap {r : Nat} (i : Index r) : Cap (plain r).r i.val := by
  6799. rcases i.property with e | b
  6800. · intro x; rw [e,power,List.count_replicate]; split <;> simp [plain]
  6801. · exact b.2.1
  6802. private theorem binary_length {T : W} (letters : ∀ x ∈ T, x = 0 ∨ x = 1) :
  6803. T.length = T.count 0 + T.count 1 := by
  6804. induction T with
  6805. | nil => rfl
  6806. | cons x t ih =>
  6807. have tail := ih (fun y m => letters y (List.mem_cons_of_mem _ m))
  6808. rcases letters x List.mem_cons_self with rfl | rfl <;> simp [List.count_cons] <;> omega
  6809. theorem index_covered {r : Nat} (i : Index r) : i.val ∈ Problem455Finite.wordsUpTo [0, 1] (2*r) := by
  6810. apply Problem455Finite.covered
  6811. · rcases i.property with e | b
  6812. · rw [e,power,List.length_replicate]; omega
  6813. · have cnt := binary_length b.1
  6814. have l := b.2.1 0
  6815. have h := b.2.1 1
  6816. omega
  6817. · intro x m
  6818. rcases i.property with e | b
  6819. · rw [e] at m; have := List.eq_of_mem_replicate m; simp_all [power]
  6820. · simpa using b.1 x m
  6821. abbrev Carrier (r : Nat) := (i : Index r) → Q (plain r) i.val
  6822. def product (r : Nat) : Model (Carrier r) where
  6823. op := fun x y i => mul (plain r) i.cap (x i) (y i)
  6824. unit := fun i => ofWord (plain r) i.val []
  6825. assoc := fun x y z => funext (fun i => mul_assoc (plain r) i.cap (x i) (y i) (z i))
  6826. oneL := fun x => funext (fun i => (unit_laws (plain r) i.cap (x i)).1)
  6827. oneR := fun x => funext (fun i => (unit_laws (plain r) i.cap (x i)).2)
  6828. theorem observed {r u v} (h : (product r).Valid u v) (i : Index r) (f : Sub) :
  6829. ofWord (plain r) i.val (u.flatMap f) = ofWord (plain r) i.val (v.flatMap f) := by
  6830. let val : Nat → Carrier r := fun x j => ofWord (plain r) j.val (f x)
  6831. have comp (w : W) : (product r).eval val w i = ofWord (plain r) i.val (w.flatMap f) := by
  6832. induction w with
  6833. | nil => rfl
  6834. | cons x xs ih =>
  6835. change mul (plain r) i.cap (ofWord (plain r) i.val (f x)) ((product r).eval val xs i) = _
  6836. rw [ih]; rfl
  6837. exact (comp u).symm.trans ((congrFun (h val) i).trans (comp v))
  6838. private theorem reflect {r : Nat} {T A B : W} (factor : Factor A T)
  6839. (eq : ofWord (plain r) T A = ofWord (plain r) T B) : A = B := by
  6840. have good : Good (plain r) T A := ⟨T,.refl T,factor⟩
  6841. have path := ((same_nonzero_class (plain r) good).mp eq).2
  6842. induction path with
  6843. | refl => rfl
  6844. | snoc _ f _ => exact False.elim f
  6845. def unaryImage (x z : Nat) : W := if z = x then [0] else []
  6846. private theorem unary_word (x : Nat) (w : W) :
  6847. w.flatMap (unaryImage x) = power (w.count x) := by
  6848. induction w with
  6849. | nil => rfl
  6850. | cons z t ih =>
  6851. by_cases e : z = x <;> simp [List.flatMap_cons,unaryImage,e,List.count_cons,ih,power,
  6852. List.replicate_succ]
  6853. private theorem small_count {r u v} (h : (product r).Valid u v) {x : Nat} (bd : u.count x ≤ r) :
  6854. u.count x = v.count x := by
  6855. let i : Index r := ⟨power r,Or.inl rfl⟩
  6856. have eq := observed h i (unaryImage x)
  6857. simp only [unary_word] at eq
  6858. have fac : Factor (power (u.count x)) (power r) := by
  6859. refine ⟨[], power (r-u.count x), ?_⟩
  6860. simp only [List.nil_append,power,List.replicate_append_replicate]
  6861. congr 1; omega
  6862. simpa [power] using congrArg List.length (reflect fac eq)
  6863. def code (i j x : Nat) : W := if x = i then [0] else if x = j then [1] else []
  6864. private theorem code_letters (i j : Nat) (w : W) (x : Nat) (m : x ∈ w.flatMap (code i j)) :
  6865. x = 0 ∨ x = 1 := by
  6866. obtain ⟨y,_,m⟩ := List.mem_flatMap.mp m
  6867. unfold code at m
  6868. split at m
  6869. · exact Or.inl (List.mem_singleton.mp m)
  6870. · split at m
  6871. · exact Or.inr (List.mem_singleton.mp m)
  6872. · simp at m
  6873. private theorem code_counts (i j : Nat) (ne : i ≠ j) (w : W) :
  6874. (w.flatMap (code i j)).count 0 = w.count i ∧ (w.flatMap (code i j)).count 1 = w.count j := by
  6875. induction w with
  6876. | nil => simp
  6877. | cons x xs ih =>
  6878. by_cases xi : x=i <;> by_cases xj : x=j <;>
  6879. simp_all [List.flatMap_cons,code,List.count_cons]
  6880. private theorem decode (i j : Nat) (w : W) :
  6881. (w.flatMap (code i j)).map (fun z => if z = 0 then i else j) = proj i j w := by
  6882. induction w with
  6883. | nil => rfl
  6884. | cons x t ih =>
  6885. by_cases e : x=i <;> by_cases f : x=j <;> simp_all [List.flatMap_cons,code,proj]
  6886. private theorem only_one {i j : Nat} (u : W) (miss : j ∉ u) :
  6887. proj i j u = List.replicate (u.count i) i := by
  6888. induction u with
  6889. | nil => rfl
  6890. | cons x t ih =>
  6891. have nx : x ≠ j := fun e => miss (e ▸ List.mem_cons_self)
  6892. have tail := ih (fun m => miss (List.mem_cons_of_mem x m))
  6893. by_cases xi : x=i <;> simp_all [proj,List.count_cons,List.replicate_succ]
  6894. private theorem proj_swap (i j : Nat) (w : W) : proj i j w = proj j i w := by
  6895. simp only [proj,Or.comm]
  6896. private theorem identical_letter (i : Nat) (w : W) :
  6897. proj i i w = List.replicate (w.count i) i := by
  6898. induction w with
  6899. | nil => rfl
  6900. | cons z t ih => by_cases eq : z = i <;> simp_all [proj,List.count_cons,List.replicate_succ]
  6901. /-- Every identity in this fixed finite tester product satisfies the actual
  6902. clipped unary and binary restrictions used by the first-change proof. -/
  6903. theorem tester_rule {r u v} (h : (product r).Valid u v) : TesterRule r u v := by
  6904. have clipped (x) : min (u.count x) (r+1) = min (v.count x) (r+1) := by
  6905. by_cases a : u.count x ≤ r
  6906. · rw [small_count h a]
  6907. · by_cases b : v.count x ≤ r
  6908. · rw [small_count (fun f => (h f).symm) b]
  6909. · omega
  6910. refine ⟨clipped,?_⟩
  6911. intro cu cv i j diff
  6912. have counts (x) : u.count x = v.count x := by have := clipped x; have := cu x; omega
  6913. have ne : i ≠ j := by
  6914. intro e; subst j; apply diff; rw [identical_letter, identical_letter, counts]
  6915. have positive (a b) (d : proj a b u ≠ proj a b v) : 0 < u.count b := by
  6916. apply Nat.pos_of_ne_zero; intro zero; apply d
  6917. have zv : v.count b = 0 := (counts b).symm.trans zero
  6918. rw [only_one u (List.count_eq_zero.mp zero),only_one v (List.count_eq_zero.mp zv),counts]
  6919. have pj := positive i j diff
  6920. have pi := positive j i (by simpa only [proj_swap j i] using diff)
  6921. apply Classical.byContradiction
  6922. intro fail
  6923. have low : u.count i < r ∨ u.count j < r := by
  6924. have := cu i; have := cu j; omega
  6925. let T := u.flatMap (code i j)
  6926. obtain ⟨c0,c1⟩ := code_counts i j ne u
  6927. have letters := code_letters i j u
  6928. have cap : Cap r T := by
  6929. intro x
  6930. by_cases mem : x ∈ T
  6931. · rcases letters x mem with rfl | rfl
  6932. · exact c0 ▸ cu i
  6933. · exact c1 ▸ cu j
  6934. · rw [List.count_eq_zero_of_not_mem mem]; omega
  6935. let ix : Index r := ⟨T,Or.inr ⟨letters,cap,c0 ▸ pi,c1 ▸ pj,by simpa only [T,c0,c1] using low⟩⟩
  6936. have eq := observed h ix (code i j)
  6937. have fac : Factor T T := ⟨[],[],by simp⟩
  6938. have ee := reflect fac eq
  6939. dsimp [T] at ee
  6940. apply diff
  6941. rw [← decode i j u,← decode i j v,ee]
  6942. /-- Extra components of the final direct product are arbitrary. Including the
  6943. unmarked testers forces their consequences for every valid multiplication identity. -/
  6944. def combine {A B : Type} (M : Model A) (N : Model B) : Model (A × B) where
  6945. op := fun x y => (M.op x.1 y.1,N.op x.2 y.2)
  6946. unit := (M.unit,N.unit)
  6947. assoc := fun _ _ _ => Prod.ext (M.assoc ..) (N.assoc ..)
  6948. oneL := fun _ => Prod.ext (M.oneL _) (N.oneL _)
  6949. oneR := fun _ => Prod.ext (M.oneR _) (N.oneR _)
  6950. theorem valid_left {A B : Type} (M : Model A) (N : Model B) {u v}
  6951. (h : (combine M N).Valid u v) : M.Valid u v := by
  6952. intro f
  6953. let g := fun x => (f x,N.unit)
  6954. have fst (w : W) : ((combine M N).eval g w).1 = M.eval f w := by
  6955. induction w with
  6956. | nil => rfl
  6957. | cons x t ih => exact congrArg (M.op (f x)) ih
  6958. exact (fst u).symm.trans ((congrArg Prod.fst (h g)).trans (fst v))
  6959. theorem first_change_no_finite_basis {A : Type} (N : Model A) (r : Nat) (hr : 0 < r)
  6960. (witnesses : ∀ k, ∃ U V D, RankWitness (combine (product r) N) r U V D ∧ k < D.length)
  6961. (G : List (W × W)) (valid : ∀ u v, (u,v) ∈ G → (combine (product r) N).Valid u v) :
  6962. ∃ U V, U ≠ [] ∧ V ≠ [] ∧ (combine (product r) N).Valid U V ∧
  6963. ¬ Derives (fun u v => (u,v) ∈ G) U V :=
  6964. no_finite_basis_of_witnesses _ r hr (fun _ _ h => tester_rule (valid_left _ _ h))
  6965. witnesses G valid
  6966. end P455FirstTesters
  6967. end
  6968. /- Begin Problem455Schedule (from finite-semigroup-identity-bases). -/
  6969. section
  6970. namespace P455Schedule
  6971. abbrev Edges := Nat → Nat → Prop
  6972. abbrev Bits := Nat → Bool
  6973. inductive Path (R : Edges) : Nat → Nat → Prop
  6974. | edge {x y} (e : R x y) : Path R x y
  6975. | join {x y z} (l : Path R x y) (r : Path R y z) : Path R x z
  6976. def induced (C : List Nat) (E : Edges) : Edges := fun a b => a ∈ C ∧ b ∈ C ∧ E a b
  6977. def Acyclic (C : List Nat) (E : Edges) := ∀ a, ¬Path (induced C E) a a
  6978. def Good (C : List Nat) (E : Edges) (s : Bits) :=
  6979. ∀ a b, E a b → (a ∈ C ∨ b ∈ C) → s a = true → s b = true
  6980. def Flip (C : List Nat) (E : Edges) (available : Nat → Prop) (s t : Bits) :=
  6981. Good C E s ∧ Good C E t ∧ ∃ a ∈ C, available a ∧ s a ≠ t a ∧ ∀ b, b ≠ a → s b = t b
  6982. def Down (C : List Nat) (E : Edges) (available : Nat → Prop) (s t : Bits) :=
  6983. Flip C E available s t ∧ ∀ a, t a = true → s a = true
  6984. def meet (A B : Bits) : Bits := fun a => A a && B a
  6985. private theorem minimal {R : Edges} (no : ∀ a, ¬ R a a)
  6986. (tr : ∀ {a b c}, R a b → R b c → R a c) (xs : List Nat) (ne : xs ≠ []) :
  6987. ∃ a ∈ xs, ∀ b ∈ xs, ¬ R b a := by
  6988. induction xs with
  6989. | nil => exact (ne rfl).elim
  6990. | cons x xs ih =>
  6991. by_cases emp : xs = []
  6992. · subst xs
  6993. refine ⟨x,List.mem_cons_self,?_⟩
  6994. intro b hb
  6995. obtain rfl := List.mem_singleton.mp hb
  6996. exact no b
  6997. obtain ⟨a,mem,first⟩ := ih emp
  6998. by_cases e : R x a
  6999. · refine ⟨x,List.mem_cons_self,?_⟩
  7000. intro b hb
  7001. rcases List.mem_cons.mp hb with eq|hit
  7002. · exact eq ▸ no x
  7003. · exact fun k => first b hit (tr k e)
  7004. · refine ⟨a,List.mem_cons_of_mem _ mem,?_⟩
  7005. intro b hb
  7006. rcases List.mem_cons.mp hb with eq|hit
  7007. · exact eq ▸ e
  7008. · exact first b hit
  7009. private theorem switch {C E} (acy : Acyclic C E) (available : Nat → Prop) (s t : Bits)
  7010. (sOK : Good C E s) (tOK : Good C E t) (todo : List Nat)
  7011. (uniq : todo.Nodup)
  7012. (all : ∀ a ∈ todo, a ∈ C ∧ available a ∧ s a = true ∧ t a = false)
  7013. (cover : ∀ a, s a ≠ t a → a ∈ todo) :
  7014. P455Quotient.Walk (Down C E available) s t := by
  7015. classical
  7016. by_cases empty : todo = []
  7017. · have eq : s = t := by
  7018. funext a; apply Classical.byContradiction; intro diff
  7019. exact List.not_mem_nil (empty ▸ cover a diff)
  7020. rw [eq]; exact .refl _
  7021. obtain ⟨a,am,first⟩ :=
  7022. minimal (R := Path (induced C E)) acy (fun m n => .join m n) todo empty
  7023. obtain ⟨ac,ch,sa,ta⟩ := all a am
  7024. let v : Bits := fun j => if j=a then false else s j
  7025. have change : v a = false := by simp [v]
  7026. have fixed (j) (h : j ≠ a) : v j = s j := by simp [v,h]
  7027. have vOK : Good C E v := by
  7028. intro i j edge touch on
  7029. have si : s i = true := by
  7030. by_cases eq : i = a
  7031. · subst i; simp [change] at on
  7032. · exact (fixed i eq).symm.trans on
  7033. by_cases eq : j = a
  7034. · subst j
  7035. have off : t i = false := by
  7036. cases e : t i with
  7037. | false => rfl
  7038. | true => have impossible := tOK i a edge (.inr ac) e; simp [ta] at impossible
  7039. have active := cover i (by simp [si,off])
  7040. exact False.elim (first i active (.edge ⟨(all i active).1,ac,edge⟩))
  7041. · exact (fixed j eq).trans (sOK i j edge touch si)
  7042. have single : Down C E available s v := by
  7043. refine ⟨⟨sOK,vOK,a,ac,ch,by simp [sa,change],fun j ne => (fixed j ne).symm⟩,?_⟩
  7044. intro j h
  7045. by_cases eq : j=a
  7046. · subst j; simp [change] at h
  7047. · exact (fixed j eq).symm.trans h
  7048. have next (j) (hj : j ∈ todo.erase a) :
  7049. j ∈ C ∧ available j ∧ v j = true ∧ t j = false := by
  7050. obtain ⟨ne,hit⟩ := uniq.mem_erase_iff.mp hj
  7051. obtain ⟨h1,h2,h3,h4⟩ := all j hit
  7052. exact ⟨h1,h2,(fixed j ne).trans h3,h4⟩
  7053. have rem (j) (diff : v j ≠ t j) : j ∈ todo.erase a := by
  7054. by_cases eq : j=a
  7055. · subst j; exact False.elim (diff (change.trans ta.symm))
  7056. · exact uniq.mem_erase_iff.mpr ⟨eq,cover j (fun h => diff ((fixed j eq).trans h))⟩
  7057. have tail := switch acy available v t vOK tOK (todo.erase a) (uniq.erase a) next rem
  7058. exact (P455Quotient.Walk.snoc (.refl _) single).trans tail
  7059. termination_by todo.length
  7060. decreasing_by
  7061. have n := List.length_erase_of_mem am
  7062. have pos : 0 < todo.length := List.length_pos_iff.mpr empty
  7063. omega
  7064. private theorem down_to_meet {C E} (acy : Acyclic C E) (A B : Bits) (gA : Good C E A) (gB : Good C E B)
  7065. (fixed : ∀ a, A a ≠ B a → a ∈ C) :
  7066. P455Quotient.Walk (Down C E (fun a => A a=true ∧ B a=false)) A (meet A B) := by
  7067. let todo := (P455FirstRewrite.names C).filter (fun a => A a && !B a)
  7068. have inTodo (a) : a ∈ todo ↔ a ∈ C ∧ A a = true ∧ B a = false := by
  7069. simp [todo,P455FirstRewrite.mem_names]
  7070. have ok : Good C E (meet A B) := by
  7071. intro i j edge hit h
  7072. obtain ⟨a,b⟩ := Bool.and_eq_true_iff.mp h
  7073. exact Bool.and_eq_true_iff.mpr ⟨gA i j edge hit a,gB i j edge hit b⟩
  7074. apply switch acy _ _ _ gA ok todo ((P455FirstRewrite.names_distinct C).sublist List.filter_sublist)
  7075. · intro a ha
  7076. obtain ⟨hc,h1,h2⟩ := (inTodo a).mp ha
  7077. exact ⟨hc,⟨h1,h2⟩,h1,by simp [meet,h2]⟩
  7078. · intro a diff
  7079. cases ha : A a <;> cases hb : B a <;> simp [meet,ha,hb] at diff
  7080. exact (inTodo a).mpr ⟨fixed a (by simp [ha,hb]),ha,hb⟩
  7081. /-- Explicit two phases. Within each phase every changed vertex moves in a
  7082. single direction. The starting-only and target-only vertex sets are disjoint. -/
  7083. theorem phases {C E} (acy : Acyclic C E) (A B : Bits) (gA : Good C E A) (gB : Good C E B)
  7084. (fixed : ∀ a, A a ≠ B a → a ∈ C) :
  7085. P455Quotient.Walk (Down C E (fun a => A a=true ∧ B a=false)) A (meet A B) ∧
  7086. P455Quotient.Walk (Down C E (fun a => B a=true ∧ A a=false)) B (meet A B) := by
  7087. have eq : meet B A = meet A B := by funext a; exact Bool.and_comm ..
  7088. exact ⟨down_to_meet acy A B gA gB fixed,eq ▸ down_to_meet acy B A gB gA (fun a d => fixed a (Ne.symm d))⟩
  7089. def Toward (C : List Nat) (E : Edges) (goal : Bits) (s t : Bits) :=
  7090. Flip C E (fun a => t a = goal a) s t
  7091. private theorem map_walk {R S : Bits → Bits → Prop} {a b : Bits}
  7092. (path : P455Quotient.Walk R a b) (one : ∀ {u v}, R u v → S u v) : P455Quotient.Walk S a b := by
  7093. induction path with
  7094. | refl => exact .refl _
  7095. | snoc _ m ih => exact .snoc ih (one m)
  7096. private theorem reverse_path {R : Bits → Bits → Prop} {a b : Bits}
  7097. (h : P455Quotient.Walk (fun s t => R t s) a b) : P455Quotient.Walk R b a := by
  7098. induction h with
  7099. | refl => exact .refl _
  7100. | snoc _ m ih => exact (P455Quotient.Walk.snoc (.refl _) m).trans ih
  7101. theorem schedule {C E} (acy : Acyclic C E) (A B : Bits) (gA : Good C E A) (gB : Good C E B)
  7102. (fixed : ∀ a, A a ≠ B a → a ∈ C) :
  7103. P455Quotient.Walk (Toward C E B) A B := by
  7104. obtain ⟨lhs,rhs⟩ := phases acy A B gA gB fixed
  7105. apply (map_walk lhs (S := Toward C E B) ?_).trans
  7106. · exact reverse_path (map_walk rhs (S := fun s t => Toward C E B t s) (by
  7107. intro s t st
  7108. obtain ⟨⟨ok1,ok2,a,hc,ab,ne,unch⟩,down⟩ := st
  7109. have ons : s a = true := by cases h : s a <;> cases k : t a <;> simp_all
  7110. exact ⟨ok2,ok1,a,hc,ons.trans ab.1.symm,Ne.symm ne,fun j h => (unch j h).symm⟩))
  7111. · intro s t st
  7112. obtain ⟨⟨ok1,ok2,a,hc,ab,ne,unch⟩,down⟩ := st
  7113. have off : t a = false := by cases h : s a <;> cases k : t a <;> simp_all
  7114. exact ⟨ok1,ok2,a,hc,off.trans ab.2.symm,ne,unch⟩
  7115. /-- Realizing the safe Boolean singletons by bounded-rank word steps produces
  7116. an ordinary multiplication-only equational deduction for the two words. -/
  7117. theorem derivation {C E} (acy : Acyclic C E) (A B : Bits) (gA : Good C E A) (gB : Good C E B)
  7118. (fixed : ∀ a, A a ≠ B a → a ∈ C) (word : Bits → P455FirstRewrite.W)
  7119. {M : P455FirstRewrite.Model α} (k : Nat)
  7120. (one : ∀ s t, Toward C E B s t →
  7121. P455FirstRewrite.Step (fun u v => M.Valid u v ∧ P455FirstRewrite.rank u v ≤ k) (word s) (word t)) :
  7122. P455FirstRewrite.Derives (fun u v => M.Valid u v ∧ P455FirstRewrite.rank u v ≤ k) (word A) (word B) := by
  7123. have lift {a b : Bits} (path : P455Quotient.Walk (Toward C E B) a b) :
  7124. P455FirstRewrite.Derives (fun u v => M.Valid u v ∧ P455FirstRewrite.rank u v ≤ k)
  7125. (word a) (word b) := by
  7126. induction path with
  7127. | refl => exact .refl _
  7128. | snoc _ move ih => exact .snoc ih (one _ _ move)
  7129. exact lift (schedule acy A B gA gB fixed)
  7130. end P455Schedule
  7131. end
  7132. /- Begin Problem455EffectiveMachineCode (from finite-semigroup-identity-bases). -/
  7133. section
  7134. /- Explicit finite instruction arrays for the machines of the reduction. -/
  7135. namespace P455EffectiveMachine
  7136. open P455MachineLocal P455MachineCleanup
  7137. structure Code (g q : Nat) where
  7138. marker : Fin g
  7139. blank : Fin g
  7140. start : Fin q
  7141. rows : Vector (Vector (Option (Ins (Fin g) (Fin q))) g) q
  7142. def Code.read (C : Code g q) (s : Fin q) (a : Fin g) := (C.rows.get s).get a
  7143. def Code.Safe (C : Code g q) : Prop := C.blank ≠ C.marker ∧ ∀ s a,
  7144. match C.read s a with
  7145. | none => True
  7146. | some i => (i.symbol=C.marker ↔ a=C.marker) ∧ (a=C.marker → i.dir≠.left)
  7147. def finiteAll (p : Fin n → Prop) (d : ∀ i,Decidable (p i)) : Decidable (∀ i,p i) := by
  7148. let f (i : Fin n) := @decide (p i) (d i)
  7149. apply decidable_of_iff ((List.finRange n).all f=true)
  7150. rw [List.all_eq_true]
  7151. constructor
  7152. · intro h i
  7153. have mem : i∈List.finRange n := by
  7154. have bound : i.val < (List.finRange n).length := by simp
  7155. simpa using (List.getElem_mem (l:=List.finRange n) bound)
  7156. exact of_decide_eq_true (h i mem)
  7157. · intro h i _
  7158. exact @decide_eq_true (p i) (d i) (h i)
  7159. instance (C : Code g q) : Decidable C.Safe := by
  7160. let p (s : Fin q) (a : Fin g) : Prop := match C.read s a with
  7161. | none => True
  7162. | some i => (i.symbol=C.marker ↔ a=C.marker) ∧ (a=C.marker → i.dir≠.left)
  7163. let check (s : Fin q) (a : Fin g) : Decidable (p s a) := by
  7164. unfold p; split <;> infer_instance
  7165. letI alld : Decidable (∀ s a,p s a) := finiteAll _ (fun s => finiteAll _ (check s))
  7166. change Decidable (C.blank≠C.marker ∧ ∀ s a,p s a)
  7167. infer_instance
  7168. def Code.machine (C : Code g q) (v : C.Safe) : Ordinary g q where
  7169. marker := C.marker
  7170. blank := C.blank
  7171. blank_ne := v.1
  7172. start := C.start
  7173. delta := C.read
  7174. keeps := by
  7175. intro s a i e
  7176. have h := v.2 s a
  7177. rw [e] at h
  7178. exact h.1
  7179. leftSafe := by
  7180. intro s i e
  7181. have h := v.2 s C.marker
  7182. rw [e] at h
  7183. exact h.2 rfl
  7184. def Code.decode (C : Code g q) : Option (Ordinary g q) :=
  7185. if h : C.Safe then some (C.machine h) else none
  7186. def quote (M : Ordinary g q) : Code g q :=
  7187. ⟨M.marker,M.blank,M.start,Vector.ofFn (fun s => Vector.ofFn (M.delta s))⟩
  7188. @[simp] theorem read_quote (M : Ordinary g q) (s a) : (quote M).read s a=M.delta s a := by
  7189. simp [Code.read,quote,Vector.get]
  7190. theorem safe_quote (M : Ordinary g q) : (quote M).Safe := by
  7191. refine ⟨M.blank_ne,fun s a => ?_⟩
  7192. rw [read_quote]
  7193. cases e : M.delta s a with
  7194. | none => trivial
  7195. | some i =>
  7196. exact ⟨M.keeps s a i e, fun h => M.leftSafe s i (by change a=M.marker at h; simpa [h] using e)⟩
  7197. @[simp] theorem quote_decode (M : Ordinary g q) : (quote M).decode=some M := by
  7198. rw [Code.decode,dif_pos (safe_quote M)]
  7199. congr 1
  7200. have ext (X Y : Ordinary g q) (mr : X.marker=Y.marker) (bl : X.blank=Y.blank)
  7201. (st : X.start=Y.start) (dt : X.delta=Y.delta) : X=Y := by
  7202. cases X; cases Y; simp_all
  7203. exact ext _ _ rfl rfl rfl (funext fun s => funext fun a => read_quote M s a)
  7204. /-- Names and a rectangular array of ordinary natural numbers give the public
  7205. machine-code payload. 0 is an undefined instruction. 1+3*(g*s+a)+d codes
  7206. a next state s, write symbol a and direction d (left/stay/right). -/
  7207. def dirCode : Direction → Nat | .left => 0 | .stay => 1 | .right => 2
  7208. def entryCode (g : Nat) (i : Option (Ins (Fin g) (Fin q))) : Nat :=
  7209. match i with
  7210. | none => 0
  7211. | some x => 1+3*(g*x.state.val+x.symbol.val)+dirCode x.dir
  7212. def Code.numerals (C : Code g q) : List Nat :=
  7213. [g,q,C.marker.val,C.blank.val,C.start.val] ++
  7214. C.rows.toList.flatMap (fun row => row.toList.map (entryCode g))
  7215. def unary (n : Nat) := List.replicate n true ++ [false]
  7216. def Code.bits (C : Code g q) : List Bool := C.numerals.flatMap unary
  7217. end P455EffectiveMachine
  7218. end
  7219. /- Begin Problem455SourceTheorem (from finite-semigroup-identity-bases). -/
  7220. section
  7221. namespace P455SourceTheorem
  7222. open P455Witness P455Paths P455ContactLift P455SourceFamilies P455PortReflection
  7223. open P455EdgeSource P455Retained P455OriginalWalk Problem455.Slots
  7224. def startLabel (c : Certificate) (second mate : Bool) : Nat :=
  7225. match c with
  7226. | .slot s => picked s
  7227. | .functionality f => f.anchor.owner
  7228. | .edge e =>
  7229. let n := if second then e.b else e.a
  7230. if mate then n.mate else n.owner
  7231. def transferred (d : Nat → Nat) : Certificate → Certificate
  7232. | .slot s => .slot (sendSlot d s)
  7233. | .functionality f => .functionality (sendFunc d f)
  7234. | .edge e => .edge (sendEdge d e)
  7235. def sourceMarks (d : Nat → Nat) : Certificate → Marking
  7236. | .slot s => markNode (sendNode d s.anchor)
  7237. | .functionality f => markNode (sendNode d f.anchor)
  7238. | .edge e => endpointMarks d e
  7239. def SourceEvidence (r : Nat) (allow : Tag → Prop) (ts : Tiles) (v : W) (h : Nat → W)
  7240. (seed : Nat) : Certificate → Prop
  7241. | .slot s => SlotResult r allow v h seed s
  7242. | .functionality f => FuncResult r allow ts v h f
  7243. | .edge e => Holds r allow (endpointMarks (donor v h r) e) v ((sendEdge (donor v h r) e).query ts)
  7244. theorem in_source {r allow mark v h l k seed} (hr : 0 < r)
  7245. (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k)) (ts : Tiles) (c : Certificate)
  7246. (second mate : Bool) (ok : Holds r allow mark (l ++ v.flatMap h ++ k) (c.query r ts))
  7247. (start : Supplies v h r seed (startLabel c second mate)) (guard : Guard r allow mark v seed 6) :
  7248. SourceEvidence r allow ts v h seed c := by
  7249. cases c with
  7250. | slot s => exact slot_source hr cap s ok start guard
  7251. | functionality f => exact functionality_source hr cap ts f ok start guard
  7252. | edge e => exact edge_source_from_role hr cap ts e ok second mate start guard (by split <;> decide)
  7253. theorem compressed_query {r allow ts v h seed c} (ev : SourceEvidence r allow ts v h seed c)
  7254. (cmp : Compressed r v) :
  7255. Holds r allow (sourceMarks (donor v h r) c) v ((transferred (donor v h r) c).query r ts) := by
  7256. cases c with
  7257. | slot s => exact ev.2.2.2 cmp
  7258. | functionality f => exact ev.2.2.2.2 cmp
  7259. | edge e => exact ev
  7260. /-- Form in the evaluated rule word. Each bounded literal contact walk is
  7261. transported with the identical sequence of choices. -/
  7262. theorem arbitrary_reps_source_gadget {r allow mark T} (capT : P455Quotient.Cap r T)
  7263. (val : Nat → P455Quotient.Q (rules r allow mark) T) (v : W) (h : Nat → W)
  7264. (reps : ∀ x ∈ v, P455Quotient.ofWord (rules r allow mark) T (h x) = val x)
  7265. (live : P455Quotient.eval (rules r allow mark) capT val v ≠ P455Quotient.zero (rules r allow mark) T)
  7266. (ts : Tiles) (c : Certificate) (initial : Holds r allow mark T (c.query r ts))
  7267. (second mate : Bool) (seed : Nat) (hr : 0 < r)
  7268. (start : Supplies v h r seed (startLabel c second mate)) (guard : Guard r allow mark v seed 6) :
  7269. ∃ z l k, P455Quotient.Variant (rules r allow mark) T z ∧ z = l ++ v.flatMap h ++ k ∧
  7270. Holds r allow mark z (c.query r ts) ∧ SourceEvidence r allow ts v h seed c ∧
  7271. ∀ p : List Step, p.length ≤ 6 → Walk r allow mark z (startLabel c second mate) p →
  7272. Walk r allow mark v seed (relabel (donor v h r) p) ∧
  7273. Supplies v h r (donor v h r (endpoint (startLabel c second mate) p))
  7274. (endpoint (startLabel c second mate) p) := by
  7275. obtain ⟨z,l,k,path,eq,ok⟩ := arbitrary_reps_designated capT val v h reps live c ts initial
  7276. subst z
  7277. have cap : P455Closure.Cap r (l ++ v.flatMap h ++ k) :=
  7278. fun s => (P455Quotient.count_walk _ path s) ▸ capT s
  7279. exact ⟨_,l,k,path,rfl,ok,in_source hr cap ts c second mate ok start guard,
  7280. fun p bp wp => P455ContactLift.lift_walk hr cap start guard p bp wp⟩
  7281. theorem expanded_query {r allow mark ts v h e kept seed c second mate T}
  7282. (exp : Expansion v e kept) (hr : 1 < r) (capU : P455Closure.Cap r (v.flatMap e))
  7283. (capF : P455Closure.Cap r (v.flatMap h))
  7284. (original : OriginalGuard r allow mark (v.flatMap e) kept seed 6)
  7285. (start : Supplies v h r seed (startLabel c second mate))
  7286. (ev : SourceEvidence r allow ts v h seed c)
  7287. (initial : Holds r allow mark T (c.query r ts)) (cmp : Compressed r (v.flatMap e)) :
  7288. let d := donor v h r
  7289. Holds r allow (sourceMarks d c) (v.flatMap e) ((transferred d c).query r ts) := by
  7290. let d := donor v h r
  7291. have pos : 0 < r := by omega
  7292. cases c with
  7293. | edge ed =>
  7294. exact P455OriginalEdges.expand_edge exp hr capU ev
  7295. | functionality f =>
  7296. obtain ⟨bit,b,c,dist,_⟩ := ev
  7297. exact ⟨P455OriginalEdges.expand_markedNode exp hr capU bit,
  7298. P455OriginalEdges.expand_neighbor exp hr capU f.dir b,
  7299. P455OriginalEdges.expand_neighbor exp hr capU f.dir c,compressed_separates cmp dist,True.intro⟩
  7300. | slot s =>
  7301. obtain ⟨bit,walk,terminal,_⟩ := ev
  7302. have eq : d (picked s) = seed := donor_eq pos capF start
  7303. have big := exp.walk hr capU _ _ walk
  7304. let m := markNode (sendNode d s.anchor)
  7305. let finalLabel := endpoint (picked s) s.steps
  7306. have ep : endpoint seed (relabel d s.steps) = d finalLabel := by rw [← eq,endpoint_relabel]
  7307. have pickEq : picked (sendSlot d s) = d (picked s) := by
  7308. cases z : s.startAtMate <;> simp [picked,sendSlot,sendNode,z]
  7309. obtain ⟨len,_,termT⟩ := slot_route s initial
  7310. have valid := valid_slot s.defect termT
  7311. have bigWalk : Walk r allow mark (v.flatMap e) seed (relabel d s.steps) :=
  7312. remark_walk _ _ big
  7313. have reach : Near r allow mark (v.flatMap e) seed (d finalLabel) 6 :=
  7314. ⟨relabel d s.steps,bigWalk,ep,by simpa [relabel] using len⟩
  7315. have ownerKept := (original _ reach).1
  7316. have transfer (y : Nat) (inside : occupies v (d finalLabel) s.terminalIndex y) (cnt : v.count y = r) :
  7317. occupies (v.flatMap e) (d finalLabel) s.terminalIndex y ∧ (v.flatMap e).count y = r := by
  7318. have present : y ∈ v := List.count_pos_iff.mp (by omega)
  7319. have ky : kept y := by
  7320. apply Classical.byContradiction
  7321. intro absent
  7322. have := (exp.gaps y present absent).1
  7323. omega
  7324. have mem : y ∈ e y := by rw [exp.literal y present ky]; simp
  7325. exact ⟨exp.in_original_slot _ _ _ ownerKept inside y mem,(exp.count_eq _ (fun _ h => h) y ky).trans cnt⟩
  7326. have term : Holds r allow m (v.flatMap e)
  7327. (terminalSlot r (d finalLabel) s.terminalIndex (sendDefect d s.defect)) :=
  7328. rebuild_terminal_in d s.defect valid cmp (fun hh => donor_eq pos capF hh) transfer terminal
  7329. refine ⟨P455OriginalEdges.expand_markedNode exp hr capU bit,by simpa [sendSlot,relabel,P455Witness.Holds] using len,?_,True.intro⟩
  7330. apply (route_iff ..).mpr
  7331. change Walk r allow m (v.flatMap e) (picked (sendSlot d s)) (relabel d s.steps) ∧
  7332. Holds r allow m (v.flatMap e) (terminalSlot r (endpoint (picked (sendSlot d s)) (relabel d s.steps))
  7333. s.terminalIndex (sendDefect d s.defect))
  7334. rw [pickEq,endpoint_relabel]
  7335. exact ⟨eq.symm ▸ big,term⟩
  7336. /-- The complete quotient-to-original-word result. The evaluation substitutes h
  7337. in the smaller word v. Independently e expands the fresh gaps of v to the
  7338. original source word U. No equality between these two substitutions is used. -/
  7339. theorem arbitrary_reps_original_gadget {r allow mark T} (capT : P455Quotient.Cap r T)
  7340. (val : Nat → P455Quotient.Q (rules r allow mark) T) (v : W) (h : Nat → W)
  7341. (reps : ∀ x ∈ v, P455Quotient.ofWord (rules r allow mark) T (h x) = val x)
  7342. (live : P455Quotient.eval (rules r allow mark) capT val v ≠ P455Quotient.zero (rules r allow mark) T)
  7343. (ts : Tiles) (c : Certificate) (initial : Holds r allow mark T (c.query r ts))
  7344. (second mate : Bool) (seed : Nat) (hr : 1 < r)
  7345. (start : Supplies v h r seed (startLabel c second mate))
  7346. {e kept} (exp : Expansion v e kept) (capU : P455Closure.Cap r (v.flatMap e))
  7347. (original : OriginalGuard r allow mark (v.flatMap e) kept seed 6) :
  7348. let d := donor v h r
  7349. let u := v.flatMap e
  7350. let a := startLabel c second mate
  7351. ∃ z l k, P455Quotient.Variant (rules r allow mark) T z ∧ z = l ++ v.flatMap h ++ k ∧
  7352. Holds r allow mark z (c.query r ts) ∧ SourceEvidence r allow ts v h seed c ∧
  7353. (Compressed r u → Holds r allow (sourceMarks d c) u ((transferred d c).query r ts)) ∧
  7354. ∀ p : List Step, p.length ≤ 6 → Walk r allow mark z a p →
  7355. Walk r allow mark u seed (relabel d p) ∧ endpoint seed (relabel d p) = d (endpoint a p) ∧
  7356. (relabel d p).length = p.length ∧ kept (d (endpoint a p)) ∧
  7357. Supplies v h r (d (endpoint a p)) (endpoint a p) ∧ Supplies u h r (d (endpoint a p)) (endpoint a p) := by
  7358. obtain ⟨z,l,k,path,eq,ok,source,_⟩ := arbitrary_reps_source_gadget capT val v h reps live ts c initial
  7359. second mate seed (by omega) start (exp.guard hr capU original)
  7360. subst z
  7361. have cap : P455Closure.Cap r (l ++ v.flatMap h ++ k) :=
  7362. fun s => (P455Quotient.count_walk _ path s) ▸ capT s
  7363. exact ⟨_,l,k,path,rfl,ok,source,expanded_query exp hr capU (factor_cap cap) original start source initial,
  7364. fun p len walk => P455OriginalWalk.lift_walk exp hr capU original cap start p len walk⟩
  7365. end P455SourceTheorem
  7366. end
  7367. /- Begin Problem455SmallRank (from finite-semigroup-identity-bases). -/
  7368. section
  7369. namespace P455SmallRank
  7370. open P455Closure P455Compression P455Uncrossed
  7371. open P455FirstRewrite (names rank size_le mem_names names_distinct Step Model)
  7372. private def lits : List Piece → W
  7373. | [] => []
  7374. | .literal a :: t => a :: lits t
  7375. | .gap _ :: t => lits t
  7376. private def gaps (n : Nat) : List Piece → W
  7377. | [] => []
  7378. | .literal _ :: t => gaps (n+1) t
  7379. | .gap _ :: t => n :: gaps (n+1) t
  7380. private theorem gap_bound (n : Nat) : ∀ (cs : List Piece), noTouch cs →
  7381. (gaps n cs).length ≤ (lits cs).length + 1
  7382. | [],_ => by simp [gaps,lits]
  7383. | .literal _ :: cs,ok => by
  7384. have := gap_bound (n+1) cs ok
  7385. simpa [gaps,lits] using Nat.le_step this
  7386. | [.gap _],_ => by simp [gaps,lits]
  7387. | .gap _ :: .literal _ :: cs,ok => by
  7388. have h := gap_bound (n+1+1) cs ok
  7389. simp only [gaps,lits,List.length_cons]
  7390. omega
  7391. | .gap _ :: .gap _ :: _,ok => False.elim ok
  7392. private theorem lit_subset (cs : List Piece) : (lits cs).Sublist (cs.flatMap body) := by
  7393. induction cs with
  7394. | nil => exact .slnil
  7395. | cons p cs ih =>
  7396. cases p with
  7397. | literal a => exact ih.cons₂ a
  7398. | gap w => exact ih.trans (List.sublist_append_right _ _)
  7399. private theorem cover (keep : W) (n : Nat) (cs : List Piece)
  7400. (all : ∀ c ∈ cs,good keep c) (a : Nat) (ha : a ∈ code n cs) :
  7401. a ∈ keep ∨ a ∈ gaps n cs := by
  7402. induction cs generalizing n with
  7403. | nil => cases ha
  7404. | cons c cs ih =>
  7405. have tail (p) (hp : p ∈ cs) := all p (List.mem_cons_of_mem _ hp)
  7406. cases c with
  7407. | literal x =>
  7408. rcases List.mem_cons.mp ha with e|m
  7409. · exact .inl (e ▸ all (.literal x) List.mem_cons_self)
  7410. · exact ih (n+1) tail m
  7411. | gap w =>
  7412. rcases List.mem_cons.mp ha with e|m
  7413. · exact .inr (List.mem_cons.mpr (.inl e))
  7414. · exact (ih (n+1) tail m).imp_right (List.mem_cons_of_mem _)
  7415. private theorem lit_mem {keep : W} (cs : List Piece) (all : ∀ c ∈ cs,good keep c) :
  7416. ∀ a ∈ lits cs, a ∈ keep := by
  7417. induction cs with
  7418. | nil => simp [lits]
  7419. | cons c cs ih =>
  7420. have tail (p) (hp : p ∈ cs) := all p (List.mem_cons_of_mem _ hp)
  7421. cases c with
  7422. | literal x =>
  7423. intro a m; rcases List.mem_cons.mp m with e|h
  7424. · exact e ▸ all (.literal x) List.mem_cons_self
  7425. · exact ih tail a h
  7426. | gap _ => exact ih tail
  7427. private theorem count_away (a : Nat) (w : W) :
  7428. w.length = w.count a + (w.filter (· != a)).length := by
  7429. induction w with
  7430. | nil => rfl
  7431. | cons b w ih =>
  7432. by_cases e : b = a <;> simp [e,List.count_cons] <;> omega
  7433. private theorem length_bound (r : Nat) (C w : W) (cap : Cap r w)
  7434. (covered : ∀ a ∈ w, a ∈ C) : w.length ≤ r*C.length := by
  7435. induction C generalizing w with
  7436. | nil =>
  7437. cases w with
  7438. | nil => simp
  7439. | cons a t => exact (List.not_mem_nil (covered a List.mem_cons_self)).elim
  7440. | cons a C ih =>
  7441. let t := w.filter (· != a)
  7442. have subset : t.Sublist w := List.filter_sublist
  7443. have ht : Cap r t := fun b => Nat.le_trans (subset.count_le b) (cap b)
  7444. have tc (b) (hb : b ∈ t) : b ∈ C := by
  7445. obtain ⟨bw,ba⟩ := List.mem_filter.mp hb
  7446. exact (List.mem_cons.mp (covered b bw)).resolve_left (by simpa using ba)
  7447. have h := ih t ht tc
  7448. have split := count_away a w
  7449. have c := cap a
  7450. simp only [List.length_cons,Nat.mul_succ]
  7451. dsimp [t] at h; omega
  7452. private theorem literal_bound {r : Nat} (u keep : W) (cap : Cap r u) :
  7453. (lits (pieces keep u)).length ≤ r*(names keep).length := by
  7454. have sub := lit_subset (pieces keep u)
  7455. rw [decoded] at sub
  7456. apply length_bound
  7457. · exact fun a => Nat.le_trans (sub.count_le a) (cap a)
  7458. · exact fun a h => (mem_names a keep).mpr (lit_mem _ (pieces_good keep u) a h)
  7459. private theorem code_length (n : Nat) (cs : List Piece) :
  7460. (code n cs).length = (lits cs).length + (gaps n cs).length := by
  7461. induction cs generalizing n with
  7462. | nil => rfl
  7463. | cons c cs ih => cases c <;> simp [code,lits,gaps,ih,Nat.add_assoc,Nat.add_comm,Nat.add_left_comm]
  7464. theorem small_length {r : Nat} (u keep : W) (cap : Cap r u) :
  7465. (small u keep).length ≤ 2*(r*(names keep).length)+1 := by
  7466. have l := literal_bound u keep cap
  7467. have g := gap_bound (base u keep) (pieces keep u) (maximal keep u)
  7468. unfold small; rw [code_length]; omega
  7469. /-- Covers the joint rank of both sides when they have identical support,
  7470. counting each kept name only once even when the given list contains repeats. -/
  7471. theorem joint_rank {r : Nat} (u keep v : W) (cap : Cap r u)
  7472. (same : ∀ a ∈ v, a ∈ small u keep) :
  7473. rank (small u keep) v ≤ (names keep).length + r*(names keep).length + 1 := by
  7474. let cs := pieces keep u
  7475. let n := base u keep
  7476. have l := literal_bound u keep cap
  7477. have g := gap_bound n cs (maximal keep u)
  7478. have le : rank (small u keep) v ≤ ((names keep) ++ gaps n cs).length := by
  7479. apply size_le (names_distinct _)
  7480. intro a ha
  7481. have ma := (List.mem_append.mp ((mem_names _ _).mp ha)).elim id (same a)
  7482. have mem := cover keep n cs (pieces_good keep u) a ma
  7483. exact List.mem_append.mpr (mem.imp_left (mem_names a keep).mpr)
  7484. simp only [List.length_append] at le
  7485. dsimp only [cs] at g; dsimp only [cs] at le; omega
  7486. private theorem lookup_nonempty (keep : W) (cs : List Piece) (all : ∀ c ∈ cs,good keep c)
  7487. (n a : Nat) : lookup n cs a ≠ [] := by
  7488. induction cs generalizing n with
  7489. | nil => simp [lookup]
  7490. | cons c cs ih =>
  7491. have tail (p) (hp : p ∈ cs) := all p (List.mem_cons_of_mem _ hp)
  7492. cases c with
  7493. | literal x => exact ih tail (n+1)
  7494. | gap w =>
  7495. by_cases e : a=n
  7496. · simpa only [lookup,if_pos e] using (all (.gap w) List.mem_cons_self).1
  7497. · simpa only [lookup,if_neg e] using ih tail (n+1)
  7498. theorem expansion_nonempty (u keep : W) (a : Nat) : expand u keep a ≠ [] :=
  7499. lookup_nonempty keep _ (pieces_good keep u) _ a
  7500. /-- The literal source flip is one step using a semantically valid identity on
  7501. at most N + r*N + 1 variables. All substitution images, even for unused
  7502. variables, are nonempty semigroup words. -/
  7503. theorem bounded_step {A : Type} (M : Model A) {r allowed} (f : Frame Nat)
  7504. (l k keep : W) {x y : Nat} (hx : x ∈ keep) (hy : y ∈ keep)
  7505. (hp : f.p = [x]) (hq : f.q = [y]) (valid : f.Valid r allowed (fun _ _ => False))
  7506. (b : Bool) (cap : Cap r (side f l k b))
  7507. (semantic : M.Valid (small (side f l k b) keep) (small (side f l k (!b)) keep)) :
  7508. let N := (names keep).length
  7509. Step (fun u v => M.Valid u v ∧ rank u v ≤ N+r*N+1)
  7510. (side f l k b) (side f l k (!b)) := by
  7511. dsimp only
  7512. obtain ⟨g,left,right,gp,_,_,eq,expanded⟩ :=
  7513. P455CompressedFrame.canonical_pair f l k keep hx hy hp hq valid b cap
  7514. have letters (a) (ha : a ∈ small (side f l k (!b)) keep) : a ∈ small (side f l k b) keep := by
  7515. rw [eq] at ha ⊢
  7516. exact (P455Uncrossed.same_letters g left right b a).mpr ha
  7517. have nonempty (c : Bool) : small (side f l k c) keep ≠ [] := by
  7518. rw [eq]; obtain ⟨t,e⟩ := g.core_starts c
  7519. simp [side,e]
  7520. refine ⟨_,_,[],[],expand (side f l k b) keep,.inl ⟨semantic,joint_rank _ _ _ cap letters⟩,
  7521. nonempty b,nonempty (!b),expansion_nonempty _ _,?_,?_⟩
  7522. all_goals simp only [List.nil_append,List.append_nil,eq,expanded]
  7523. end P455SmallRank
  7524. end
  7525. /- Begin Problem455OtherProjection (from finite-semigroup-identity-bases). -/
  7526. section
  7527. namespace P455OtherProjection
  7528. open P455Witness P455Paths P455SourceFamilies P455PortReflection P455DefectProjection Problem455.Slots
  7529. open Problem455Swap (SameBlock)
  7530. def Covers (keep xs : W) := ∀ a ∈ xs, a ∈ keep
  7531. private theorem fan {r w} (hr : 0 < r) (cp : P455Closure.Cap r w) (a : Nat) (xs : W)
  7532. (ca : w.count a = r) (sat : ∀ b ∈ xs, w.count b = r)
  7533. (diff : ∀ b ∈ xs, ¬ SameBlock r w a b) :
  7534. ∃ aux : W, aux.length ≤ 2*xs.length ∧ ∀ keep : W, a ∈ keep → Covers keep xs → Covers keep aux →
  7535. ∀ b ∈ xs, ¬ SameBlock r (select keep w) a b := by
  7536. induction xs with
  7537. | nil => exact ⟨[],by simp,by simp⟩
  7538. | cons x xs ih =>
  7539. obtain ⟨c,d,wit⟩ := P455BlockSeparators.robust_separators hr cp ca (sat x (by simp)) (diff x (by simp))
  7540. obtain ⟨more,len,win⟩ := ih (fun b h => sat b (by simp [h])) (fun b h => diff b (by simp [h]))
  7541. refine ⟨c::d::more,by simp; omega,?_⟩
  7542. intro keep ha members extra b hb
  7543. rcases List.mem_cons.mp hb with rfl|hx
  7544. · exact wit keep ha (members _ (by simp)) (extra _ (by simp)) (extra _ (by simp))
  7545. · exact win keep ha (fun j hj => members j (by simp [hj])) (fun j hj => extra j (by simp [hj])) b hx
  7546. theorem simultaneous {r w} (hr : 0 < r) (cp : P455Closure.Cap r w) (xs : W)
  7547. (sat : ∀ a ∈ xs, w.count a = r) (diff : xs.Pairwise (fun a b => ¬ SameBlock r w a b)) :
  7548. ∃ aux : W, aux.length ≤ xs.length * (xs.length-1) ∧ ∀ keep : W, Covers keep xs → Covers keep aux →
  7549. xs.Pairwise (fun a b => ¬ SameBlock r (select keep w) a b) := by
  7550. induction xs with
  7551. | nil => exact ⟨[],by simp,by simp⟩
  7552. | cons a xs ih =>
  7553. obtain ⟨ds,pw⟩ := List.pairwise_cons.mp diff
  7554. have st (b) (h : b ∈ xs) := sat b (by simp [h])
  7555. obtain ⟨xs₁,n₁,k₁⟩ := fan hr cp a xs (sat a (by simp)) st ds
  7556. obtain ⟨xs₂,n₂,k₂⟩ := ih st pw
  7557. refine ⟨xs₁ ++ xs₂,?_,?_⟩
  7558. · simp only [List.length_append,List.length_cons,Nat.add_sub_cancel]
  7559. have le := Nat.add_le_add n₁ n₂
  7560. cases n : xs.length with
  7561. | zero => simpa only [n,Nat.mul_zero,Nat.zero_mul] using le
  7562. | succ m =>
  7563. simp [n,Nat.add_mul,Nat.mul_add,Nat.succ_mul,Nat.mul_succ] at *
  7564. omega
  7565. · intro keep mem more
  7566. have keepX (b) (h : b ∈ xs) := mem b (by simp [h])
  7567. exact List.pairwise_cons.mpr ⟨k₁ keep (mem a (by simp)) keepX (fun z h => more z (by simp [h])),
  7568. k₂ keep keepX (fun z h => more z (by simp [h]))⟩
  7569. theorem walk_count {r allow mark w} (cap : P455Closure.Cap r w) (a : Nat) (p : List Step)
  7570. (ct : w.count a = r) (walk : Walk r allow mark w a p) : w.count (endpoint a p) = r := by
  7571. induction p generalizing a with
  7572. | nil => exact ct
  7573. | cons bc p ih =>
  7574. obtain ⟨b,c⟩ := bc
  7575. apply ih b _ walk.2
  7576. cases c with
  7577. | record tag rev =>
  7578. cases rev with
  7579. | false => exact (record_counts cap walk.1).2
  7580. | true => exact (record_counts cap walk.1).1
  7581. | port phase rev => exact walk.1.2.2.1
  7582. theorem bounded_overflow {r allow u} (hr : 0 < r) (cap : P455Closure.Cap r u) (s : SlotCertificate)
  7583. (xs : W) (kind : s.defect = .overflow xs) (ok : Holds r allow (markNode s.anchor) u (s.query r)) :
  7584. ∃ keep : W, keep.length ≤ 43 ∧ s.anchor.owner ∈ keep ∧ s.anchor.mate ∈ keep ∧
  7585. Covers keep (s.steps.map Prod.fst ++ xs) ∧ P455Closure.Cap r (select keep u) ∧
  7586. Holds r allow (markNode s.anchor) (select keep u) (s.query r) := by
  7587. let a := picked s
  7588. let t := endpoint a s.steps
  7589. obtain ⟨bound,walk,term⟩ := slot_route s ok
  7590. rw [kind] at term
  7591. obtain ⟨len,diff,all,_⟩ := term
  7592. have members (b : Nat) (h : b ∈ xs) :
  7593. u.count b = r ∧ slotStart s.terminalIndex ∧ occupies u t s.terminalIndex b :=
  7594. (allQ_iff _).mp all _ (List.mem_map_of_mem h)
  7595. have ct := record_counts cap (marked_typed (a := s.anchor) (bit := s.bit) ok.1)
  7596. have start : u.count a = r := by
  7597. cases side : s.startAtMate <;> simp [a,picked,side,ct]
  7598. have termCount := walk_count cap a s.steps start walk
  7599. have st : ∀ b ∈ t::xs, u.count b = r := by
  7600. intro b h; rcases List.mem_cons.mp h with rfl|h
  7601. · exact termCount
  7602. · exact (members b h).1
  7603. obtain ⟨more,n,apart⟩ := simultaneous hr cap (t::xs) st ((P455TerminalTransfer.block_separation _).mp diff)
  7604. let keep := s.anchor.owner :: s.anchor.mate :: (s.steps.map Prod.fst ++ xs ++ more)
  7605. have owner : s.anchor.owner ∈ keep := by simp [keep]
  7606. have mate : s.anchor.mate ∈ keep := by simp [keep]
  7607. have used (z) (hz : z ∈ s.steps.map Prod.fst ++ xs) : z ∈ keep :=
  7608. List.mem_cons_of_mem _ (List.mem_cons_of_mem _ (List.mem_append_left _ hz))
  7609. have keptOcc (b) (hb : b ∈ xs) := used b (List.mem_append_right _ hb)
  7610. have path (m : Step) (hm : m ∈ s.steps) : m.1 ∈ keep :=
  7611. used _ (List.mem_append_left _ (List.mem_map_of_mem hm))
  7612. have pickedKept : a ∈ keep := by cases side : s.startAtMate <;> simp [a,picked,side,owner,mate]
  7613. have last := endpoint_kept keep a s.steps pickedKept path
  7614. have allSep := apart keep (by simpa [Covers] using And.intro last keptOcc)
  7615. (fun z h => by simp [keep,h])
  7616. refine ⟨keep,?_,owner,mate,used,select_cap keep cap,select_marked keep _ _ owner mate ok.1,bound,?_,True.intro⟩
  7617. · change xs.length = 5 at len
  7618. simp only [List.length_cons,len] at n
  7619. simp [keep,len]
  7620. omega
  7621. · apply (route_iff ..).mpr
  7622. refine ⟨select_walk keep a s.steps pickedKept path walk,?_⟩
  7623. rw [kind]
  7624. refine ⟨len,(P455TerminalTransfer.block_separation _).mpr allSep,?_,True.intro⟩
  7625. apply (allQ_iff _).mpr
  7626. intro q hq; obtain ⟨b,h,rfl⟩ := List.mem_map.mp hq
  7627. have m := members b h
  7628. exact ⟨(select_count keep u b (keptOcc b h)).trans m.1,m.2.1,select_slot keep t _ b last (keptOcc b h) m.2.2⟩
  7629. theorem select_early {r allow mark u} (keep xs ys : W) (hx : Covers keep xs) (hy : Covers keep ys)
  7630. (obs : Holds r allow mark u (earlyBefore xs ys)) : Holds r allow mark (select keep u) (earlyBefore xs ys) := by
  7631. apply (earlyBefore_iff _ _).mpr
  7632. intro a ha b hb
  7633. apply select_order keep _ _ ((earlyBefore_iff _ _).mp obs a ha b hb)
  7634. simp [hx a ha,hy b hb]
  7635. theorem select_port {r allow mark u} (keep : W) (a b : Node) (i : Nat)
  7636. (keepA : Covers keep (roles a)) (keepB : Covers keep (roles b))
  7637. (obs : Holds r allow mark u (orientedPort i a b)) : Holds r allow mark (select keep u) (orientedPort i a b) := by
  7638. have ao := keepA a.owner (by simp [roles]); have am := keepA a.mate (by simp [roles])
  7639. have bo := keepB b.owner (by simp [roles]); have bm := keepB b.mate (by simp [roles])
  7640. obtain ⟨ra,rb,early,order,_⟩ := obs
  7641. refine ⟨select_record keep _ _ _ ao am ra,select_record keep _ _ _ bo bm rb,?_,?_,True.intro⟩
  7642. · rcases early with e|e
  7643. · exact .inl (select_early keep _ _ keepA keepB e)
  7644. · exact .inr (select_early keep _ _ keepB keepA e)
  7645. · apply select_order keep _ _ order; simp [ao,am,bo,bm]
  7646. theorem select_neighbor {r allow mark u} (keep : W) (ts : Tiles) (a b : Node) (dir : Dir)
  7647. (keepA : Covers keep (roles a)) (keepB : Covers keep (roles b))
  7648. (obs : Holds r allow mark u (neighbor ts a b dir)) :
  7649. Holds r allow mark (select keep u) (neighbor ts a b dir) := by
  7650. have ao := keepA a.owner (by simp [roles]); have bo := keepB b.owner (by simp [roles])
  7651. cases dir with
  7652. | down => exact ⟨obs.1,select_port keep _ _ _ keepA keepB obs.2⟩
  7653. | up => exact ⟨obs.1,select_port keep _ _ _ keepB keepA obs.2⟩
  7654. | right => exact ⟨obs.1,select_port keep _ _ _ keepA keepB obs.2.1,
  7655. select_order keep _ (by simp [ao,bo]) obs.2.2.1,True.intro⟩
  7656. | left => exact ⟨obs.1,select_port keep _ _ _ keepB keepA obs.2.1,
  7657. select_order keep _ (by simp [ao,bo]) obs.2.2.1,True.intro⟩
  7658. theorem bounded_functionality {r allow u} (hr : 0 < r) (cap : P455Closure.Cap r u)
  7659. (ts : Tiles) (f : FunctionalityCertificate)
  7660. (ok : Holds r allow (markNode f.anchor) u (f.query ts)) :
  7661. ∃ keep : W, keep.length ≤ 8 ∧ Covers keep (roles f.anchor ++ roles f.b ++ roles f.c) ∧
  7662. P455Closure.Cap r (select keep u) ∧ Holds r allow (markNode f.anchor) (select keep u) (f.query ts) := by
  7663. obtain ⟨anchor,nb,nc,apart,_⟩ := ok
  7664. let role := roleOf f.distinguishMate
  7665. have sat (n : Node) (obs : Holds r allow (markNode f.anchor) u (neighbor ts f.anchor n f.dir)) :
  7666. u.count (role n) = r := by
  7667. have ct := record_counts cap (neighbor_target_record obs)
  7668. cases side : f.distinguishMate <;> simp [role,roleOf,side,ct]
  7669. obtain ⟨x,y,diff⟩ := P455BlockSeparators.robust_separators hr cap (sat _ nb) (sat _ nc) apart
  7670. let names := roles f.anchor ++ roles f.b ++ roles f.c
  7671. let keep := x::y::names
  7672. have k : Covers keep names := fun z hz => by simp [keep,hz]
  7673. have ka : Covers keep (roles f.anchor) := fun z h => k z (by simp [names,h])
  7674. have kb : Covers keep (roles f.b) := fun z h => k z (by simp [names,h])
  7675. have kc : Covers keep (roles f.c) := fun z h => k z (by simp [names,h])
  7676. have kr (n : Node) (h : Covers keep (roles n)) : role n ∈ keep := by
  7677. apply h
  7678. cases side : f.distinguishMate <;> simp [roles,role,roleOf,side]
  7679. refine ⟨keep,by simp [keep,names,roles],k,select_cap keep cap,
  7680. select_marked keep _ _ (ka _ (by simp [roles])) (ka _ (by simp [roles])) anchor,
  7681. select_neighbor keep ts _ _ _ ka kb nb,select_neighbor keep ts _ _ _ ka kc nc,
  7682. diff keep (kr _ kb) (kr _ kc) (by simp [keep]) (by simp [keep]),True.intro⟩
  7683. end P455OtherProjection
  7684. end
  7685. /- Begin Problem455StructuralWords (from finite-semigroup-identity-bases). -/
  7686. section
  7687. namespace P455Structural
  7688. open P455Witness P455Quotient P455Closure P455Uncrossed Problem455.Slots
  7689. open P455SourceFamilies P455FirstTesters
  7690. abbrev W := List Nat
  7691. def Rec (T : W) (r : Nat) (allow : Tag → Prop) (a b : Nat) :=
  7692. ∃ tag, Holds r allow (fun _ _ => False) T (.record a b tag)
  7693. def Edge (T : W) (r : Nat) (allow : Tag → Prop) (a b : Nat) :=
  7694. Rec T r allow a b ∨ Rec T r allow b a
  7695. def Width (k : Nat) (T : W) := ∃ C : W, C.length ≤ k ∧ ∀ x ∈ T, x ∈ C
  7696. def Overlap (T : W) (r : Nat) (allow : Tag → Prop) :=
  7697. ∃ o p q, o ≠ p ∧ o ≠ q ∧ p ≠ q ∧ Edge T r allow o p ∧ Edge T r allow o q
  7698. def Intrusion (T : W) (r : Nat) (allow : Tag → Prop) :=
  7699. ∃ o p z j, o ≠ p ∧ z ≠ o ∧ z ≠ p ∧ Rec T r allow o p ∧ sees T [(o,0),(z,j),(p,2)]
  7700. def Structural (T : W) (r : Nat) (allow : Tag → Prop) :=
  7701. (Width 4 T ∧ Overlap T r allow) ∨ (Width 3 T ∧ Intrusion T r allow)
  7702. def early (a b : Nat) : W := [a,a,b,a,b,b]
  7703. def Closed (T : W) (a b : Nat) :=
  7704. a ≠ b ∧ ∃ L R : W, T = L ++ early a b ++ R ∧ a ∉ L ∧ b ∉ L
  7705. private theorem only_z (x z : Nat) (L : W) (nx : x ∉ L) :
  7706. select [x,z] L = List.replicate (L.count z) z := by
  7707. induction L with
  7708. | nil => rfl
  7709. | cons c t ih =>
  7710. have nt : x ∉ t := fun h => nx (List.mem_cons_of_mem _ h)
  7711. have cx : c ≠ x := fun e => nx (e ▸ List.mem_cons_self)
  7712. by_cases cz : c = z <;> simp_all [select,List.count_cons,List.replicate_succ]
  7713. private theorem early_projection {a b x z : Nat} {T : W} (closed : Closed T a b)
  7714. (inPair : x = a ∨ x = b) (outside : z ≠ a ∧ z ≠ b) :
  7715. ∃ n R, select [x,z] T = List.replicate n z ++ [x,x,x] ++ R := by
  7716. obtain ⟨ab,L,R,rfl,na,nb⟩ := closed
  7717. refine ⟨L.count z,select [x,z] R,?_⟩
  7718. rcases inPair with rfl|rfl <;> rw [select_append,select_append,only_z _ _ _ (by assumption)] <;>
  7719. simp [select,early,ab,Ne.symm ab,Ne.symm outside.1,Ne.symm outside.2]
  7720. private theorem not_record_tail {x z : Nat} (xz : x ≠ z) (n : Nat) (tail : W) (tag : Tag) (bit : Bool) :
  7721. List.replicate n z ++ [x,x,x] ++ tail ≠ profile x z tag bit ∧
  7722. List.replicate n z ++ [x,x,x] ++ tail ≠ profile z x tag bit := by
  7723. cases n with
  7724. | zero => simp [profile,profilePrefix,xz]
  7725. | succ n =>
  7726. cases n with
  7727. | zero => simp [profile,profilePrefix,xz,Ne.symm xz,List.replicate_succ]
  7728. | succ n =>
  7729. cases n with
  7730. | zero => simp [profile,profilePrefix,xz,Ne.symm xz,List.replicate_succ]
  7731. | succ n => simp [profile,profilePrefix,xz,Ne.symm xz,List.replicate_succ]
  7732. theorem no_external_record {r allow a b T} (closed : Closed T a b) {x z : Nat}
  7733. (inside : x = a ∨ x = b) (out : z ≠ a ∧ z ≠ b) : ¬ Edge T r allow x z := by
  7734. obtain ⟨n,tail,eq⟩ := early_projection closed inside out
  7735. have nz : x ≠ z := by omega
  7736. rintro (⟨t,_,_,_,bit,profileEq⟩|⟨t,_,_,_,bit,profileEq⟩)
  7737. · exact (not_record_tail nz n tail t bit).1 (eq.symm.trans profileEq)
  7738. · exact (not_record_tail nz n tail t bit).2 (eq.symm.trans ((select_pair_symm x z T).symm.trans profileEq))
  7739. private theorem early_bound {T : W} {a b o p z j : Nat} (closed : Closed T a b)
  7740. (oi : o=a ∨ o=b) (pi' : p=a ∨ p=b) (out : z ≠ a ∧ z ≠ b) :
  7741. ¬ sees T [(o,0),(z,j),(p,2)] := by
  7742. obtain ⟨ab,L,R,rfl,na,nb⟩ := closed
  7743. intro obs
  7744. have no : o ∉ L := oi.elim (fun e => e ▸ na) (fun e => e ▸ nb)
  7745. have cp : (early a b).count p = 3 := by
  7746. rcases pi' with rfl|rfl <;> simp [early,List.count_cons,ab,Ne.symm ab]
  7747. let inner := (events (early a b)).map (shift (fun x => L.count x))
  7748. let right := stamp (fun x => L.count x + (early a b).count x) R
  7749. have h : [(o,0),(z,j),(p,2)].Sublist (events L ++ (inner ++ right)) := by
  7750. simpa only [sees,events_of_factor,inner,right] using obs
  7751. have nl : (o,0) ∉ events L := fun m => no (stamped_mem_label _ _ _ m)
  7752. have nr : (p,2) ∉ right := by
  7753. intro m
  7754. have low := (P455ContactGeometry.stamp_range (fun x => L.count x + (early a b).count x) R m).1
  7755. omega
  7756. have strip {α : Type} (x : α) (pat u v : List α) (nx : x ∉ u)
  7757. (sub : (x::pat).Sublist (u++v)) : (x::pat).Sublist v := by
  7758. induction u with
  7759. | nil => exact sub
  7760. | cons c u ih =>
  7761. cases sub with
  7762. | cons _ s => exact ih (fun m => nx (List.mem_cons_of_mem _ m)) s
  7763. | cons_cons => exact False.elim (nx List.mem_cons_self)
  7764. have h1 := (strip _ _ _ _ nl h).reverse
  7765. simp only [List.reverse_append,List.reverse_cons,List.reverse_nil,List.nil_append,List.cons_append] at h1
  7766. have h2 := (strip _ _ right.reverse inner.reverse (by simpa using nr) h1).reverse
  7767. have mid : (z,j) ∈ inner := by simpa using h2.subset (show (z,j) ∈ ([(p,2),(z,j),(o,0)] : List Event).reverse by simp)
  7768. obtain ⟨e,me,eq⟩ := List.mem_map.mp mid
  7769. have ze : e.1 = z := congrArg Prod.fst eq
  7770. have is := stamped_mem_label _ _ _ me
  7771. simp [early,ze,out.1,out.2] at is
  7772. private theorem rec_mem {T r allow a b} (h : Rec T r allow a b) : a ∈ T ∧ b ∈ T := by
  7773. obtain ⟨t,_,_,_,bit,eq⟩ := h
  7774. have f (x : Nat) (hx : x=a ∨ x=b) : x ∈ T := by
  7775. have mm : x ∈ profile a b t bit := by rcases hx with rfl|rfl <;> simp [profile,profilePrefix]
  7776. rw [← eq] at mm
  7777. exact (List.mem_filter.mp mm).1
  7778. exact ⟨f a (.inl rfl),f b (.inr rfl)⟩
  7779. private theorem edge_mem {T r allow a b} (h : Edge T r allow a b) : a ∈ T ∧ b ∈ T :=
  7780. h.elim rec_mem (fun q => (rec_mem q).symm)
  7781. private theorem closed_mem {T a b} (h : Closed T a b) : a ∈ T ∧ b ∈ T := by
  7782. obtain ⟨_,l,t,rfl,_,_⟩ := h
  7783. simp [early]
  7784. private theorem separated_core {T r allow a b o p} (c : Closed T a b) (edge : Edge T r allow o p) :
  7785. (o=a ∨ o=b) ↔ (p=a ∨ p=b) := by
  7786. constructor
  7787. · intro h
  7788. apply Classical.byContradiction; intro n
  7789. exact no_external_record c h ⟨fun e => n (.inl e),fun e => n (.inr e)⟩ edge
  7790. · intro h
  7791. apply Classical.byContradiction; intro n
  7792. exact no_external_record c h ⟨fun e => n (.inl e),fun e => n (.inr e)⟩ edge.symm
  7793. theorem structural_excludes_closed {r allow T a b} (stest : Structural T r allow) (c : Closed T a b) : False := by
  7794. obtain ⟨ma,mb⟩ := closed_mem c
  7795. have ab := c.1
  7796. rcases stest with ⟨⟨C,len,Cmem⟩,o,p,q,op,oq,pq,e1,e2⟩|⟨⟨C,len,Cmem⟩,o,p,z,j,op,zo,zp,rec',seen⟩
  7797. · have linkP := separated_core c e1
  7798. have linkQ := separated_core c e2
  7799. by_cases h : o=a ∨ o=b
  7800. · have hp := linkP.mp h; have hq := linkQ.mp h; omega
  7801. · have A := edge_mem e1; have B := edge_mem e2
  7802. have uniq : [a,b,o,p,q].Nodup := by simp [List.nodup_cons]; omega
  7803. have sub (x) (m : x ∈ [a,b,o,p,q]) : x ∈ C := by
  7804. simp only [List.mem_cons,List.not_mem_nil,or_false] at m
  7805. rcases m with rfl|rfl|rfl|rfl|rfl <;> apply Cmem <;> simp_all
  7806. have := P455FirstRewrite.size_le uniq sub
  7807. simp at this; omega
  7808. · have link := separated_core c (Or.inl rec' : Edge T r allow o p)
  7809. by_cases h : o=a ∨ o=b
  7810. · have hp := link.mp h
  7811. apply early_bound c h hp _ seen
  7812. omega
  7813. · have A := rec_mem rec'
  7814. have uniq : [a,b,o,p].Nodup := by simp [List.nodup_cons]; omega
  7815. have sub (x) (m : x ∈ [a,b,o,p]) : x ∈ C := by
  7816. simp only [List.mem_cons,List.not_mem_nil,or_false] at m
  7817. rcases m with rfl|rfl|rfl|rfl <;> apply Cmem <;> simp_all
  7818. have := P455FirstRewrite.size_le uniq sub
  7819. simp at this; omega
  7820. end P455Structural
  7821. end
  7822. /- Begin Problem455RectangleRank (from finite-semigroup-identity-bases). -/
  7823. section
  7824. namespace P455RectangleRank
  7825. open P455FirstRewrite
  7826. def owner (i : Nat) := 2*i
  7827. def mate (i : Nat) := 2*i+1
  7828. def privateCell (i : Nat) : W := [owner i,owner i,mate i,owner i,mate i,mate i]
  7829. def mutableCell (bit : Nat → Bool) (i : Nat) : W :=
  7830. if bit i then [mate i,owner i] else [owner i,mate i]
  7831. def word (t : Nat) (middle tail : W) (bit : Nat → Bool) :=
  7832. (List.range t).flatMap privateCell ++ middle ++ (List.range t).flatMap (mutableCell bit) ++ tail
  7833. def constant (b : Bool) : Nat → Bool := fun _ => b
  7834. private theorem within {t i : Nat} (m : i ∈ List.range t) {x : Nat}
  7835. (member : x = owner i ∨ x = mate i) : x < 2*t := by
  7836. have := List.mem_range.mp m
  7837. unfold owner mate at member
  7838. omega
  7839. theorem word_names {t : Nat} {middle tail : W} (bit : Nat → Bool)
  7840. (small : ∀ x ∈ middle ++ tail, x < 2*t) (x) (hx : x ∈ word t middle tail bit) : x < 2*t := by
  7841. simp only [word,List.mem_append,List.mem_flatMap] at hx
  7842. rcases hx with ((⟨i,mi,m⟩|m)|⟨i,mi,m⟩)|m
  7843. · apply within mi
  7844. simp only [privateCell,List.mem_cons,List.mem_nil_iff,or_false] at m
  7845. rcases m with h|h|h|h|h|h <;> simp [h]
  7846. · exact small x (List.mem_append_left _ m)
  7847. · apply within mi
  7848. unfold mutableCell at m
  7849. split at m <;> simp_all [Or.comm]
  7850. · exact small x (List.mem_append_right _ m)
  7851. private theorem private_factor {t i : Nat} (ix : i < t) (middle tail : W) (bit : Nat → Bool) :
  7852. P455Quotient.Factor (privateCell i) (word t middle tail bit) := by
  7853. obtain ⟨l,r,e⟩ := List.append_of_mem (List.mem_range.mpr ix)
  7854. refine ⟨l.flatMap privateCell,r.flatMap privateCell ++ middle ++
  7855. (List.range t).flatMap (mutableCell bit) ++ tail,?_⟩
  7856. unfold word
  7857. conv => lhs; arg 1; arg 1; arg 1; rw [e]
  7858. simp [List.flatMap_cons,List.append_assoc]
  7859. private theorem positive_factor {a b : Nat} {f u : W} (factor : P455Quotient.Factor f u)
  7860. (pos : 0 < Problem455Swap.bigram a b f) : 0 < Problem455Swap.bigram a b u := by
  7861. obtain ⟨p,q,rfl⟩ := factor
  7862. rw [Problem455Swap.bigram_append,Problem455Swap.bigram_append]
  7863. omega
  7864. theorem no_links {r t : Nat} (hr : 0 < r) {middle tail : W} (bit : Nat → Bool)
  7865. (small : ∀ x ∈ middle ++ tail, x < 2*t)
  7866. (cap : P455Quotient.Cap r (word t middle tail bit)) :
  7867. P455SourceFamilies.Compressed r (word t middle tail bit) := by
  7868. let U := word t middle tail bit
  7869. intro x y link
  7870. change Problem455Swap.bigram x y U = r at link
  7871. have bound := Problem455Swap.out_bound x y (y+1) (by omega) U
  7872. rw [Problem455BlockBridge.occ_count] at bound
  7873. have mem : x ∈ U := List.count_pos_iff.mp (by omega)
  7874. have smallX := word_names bit small x mem
  7875. let i := x/2
  7876. have ix : i < t := by dsimp [i]; omega
  7877. have either : x = owner i ∨ x = mate i := by simp only [owner,mate,i]; omega
  7878. have ne : owner i ≠ mate i := by simp [owner,mate]
  7879. have fac := private_factor ix middle tail bit
  7880. have aPos : 0 < Problem455Swap.bigram x (owner i) U := by
  7881. apply positive_factor fac
  7882. rcases either with e|e <;> conv => rhs; arg 1; rw [e]
  7883. all_goals simp [privateCell,Problem455Swap.bigram,Problem455Swap.hit,ne,Ne.symm ne] <;> omega
  7884. have bPos : 0 < Problem455Swap.bigram x (mate i) U := by
  7885. apply positive_factor fac
  7886. rcases either with e|e <;> conv => rhs; arg 1; rw [e]
  7887. all_goals simp [privateCell,Problem455Swap.bigram,Problem455Swap.hit,ne,Ne.symm ne] <;> omega
  7888. obtain ⟨z,ny,pz⟩ : ∃ z, y ≠ z ∧ 0 < Problem455Swap.bigram x z U := by
  7889. by_cases e : y = owner i
  7890. · exact ⟨mate i,e ▸ ne,bPos⟩
  7891. · exact ⟨owner i,e,aPos⟩
  7892. have upper := Problem455Swap.out_bound x y z ny U
  7893. rw [Problem455BlockBridge.occ_count] at upper
  7894. have cx : U.count x ≤ r := cap x
  7895. omega
  7896. private theorem project_mutable (cells : W) (nd : cells.Nodup) (bit : Nat → Bool) (i : Nat) :
  7897. proj (owner i) (mate i) (cells.flatMap (mutableCell bit)) =
  7898. (if i ∈ cells then mutableCell bit i else []) := by
  7899. induction cells with
  7900. | nil => rfl
  7901. | cons j t ih =>
  7902. have tail := ih (List.nodup_cons.mp nd).2
  7903. by_cases e : i=j
  7904. · subst j
  7905. have out := (List.nodup_cons.mp nd).1
  7906. have one : proj (owner i) (mate i) (mutableCell bit i) = mutableCell bit i := by
  7907. cases hb : bit i <;> simp [proj,mutableCell,hb]
  7908. simp only [List.flatMap_cons,proj,List.filter_append] at tail one ⊢
  7909. rw [one,tail]
  7910. simp [out]
  7911. · have eqs : owner j ≠ owner i ∧ owner j ≠ mate i ∧ mate j ≠ owner i ∧ mate j ≠ mate i := by
  7912. unfold owner mate; omega
  7913. have no : proj (owner i) (mate i) (mutableCell bit j) = [] := by
  7914. cases b : bit j <;> simp [proj,mutableCell,b,eqs.1,eqs.2.1,eqs.2.2.1,eqs.2.2.2]
  7915. simp only [List.flatMap_cons,proj,List.filter_append] at tail no ⊢
  7916. rw [no,tail]
  7917. simp [e]
  7918. theorem participants {t : Nat} (middle tail : W) :
  7919. ∀ x ∈ List.range (2*t), ∃ y,
  7920. proj x y (word t middle tail (constant false)) ≠ proj x y (word t middle tail (constant true)) := by
  7921. intro x m
  7922. have lt := List.mem_range.mp m
  7923. let i := x/2
  7924. have mi : i ∈ List.range t := List.mem_range.mpr (by dsimp [i]; omega)
  7925. have pairDiff : proj (owner i) (mate i) (word t middle tail (constant false)) ≠
  7926. proj (owner i) (mate i) (word t middle tail (constant true)) := by
  7927. intro eq
  7928. simp only [word,proj,List.filter_append,List.append_cancel_right_eq,List.append_cancel_left_eq] at eq
  7929. change proj (owner i) (mate i) ((List.range t).flatMap (mutableCell (constant false))) =
  7930. proj (owner i) (mate i) ((List.range t).flatMap (mutableCell (constant true))) at eq
  7931. rw [project_mutable _ List.nodup_range,project_mutable _ List.nodup_range] at eq
  7932. simp [mi,mutableCell,constant,owner,mate] at eq
  7933. have either : x = owner i ∨ x = mate i := by simp only [owner,mate,i]; omega
  7934. rcases either with e|e
  7935. · exact ⟨mate i,e ▸ pairDiff⟩
  7936. · refine ⟨owner i,?_⟩
  7937. rw [e]
  7938. simpa only [proj,Or.comm] using pairDiff
  7939. /-- Local inequalities along the numbered snake and its wrap force a
  7940. constant bit on all cells. There is no assumption on bits outside the array. -/
  7941. theorem cycle_constant {t : Nat} (bit : Nat → Bool) (next : ∀ i, i+1 < t →
  7942. bit i = true → bit (i+1) = true) (wrap : 0 < t → bit (t-1) = true → bit 0 = true) :
  7943. ∃ b, ∀ i < t, bit i = b := by
  7944. have onward (i j : Nat) (le : i ≤ j) (lt : j < t) (yes : bit i = true) : bit j = true := by
  7945. induction j with
  7946. | zero => have := Nat.eq_zero_of_le_zero le; simpa [this] using yes
  7947. | succ j ih =>
  7948. by_cases e : i=j+1
  7949. · exact e ▸ yes
  7950. · exact next j lt (ih (by omega) (by omega))
  7951. by_cases existsTrue : ∃ i < t, bit i = true
  7952. · obtain ⟨i,lt,active⟩ := existsTrue
  7953. have first := wrap (by omega) (onward i (t-1) (by omega) (by omega) active)
  7954. exact ⟨true,fun j lj => onward 0 j (by omega) lj first⟩
  7955. · exact ⟨false,fun i li => by cases eq : bit i <;> simp_all⟩
  7956. theorem word_constant {t : Nat} (middle tail : W) (bit : Nat → Bool) (b : Bool)
  7957. (all : ∀ i < t, bit i = b) : word t middle tail bit = word t middle tail (constant b) := by
  7958. have m : (List.range t).flatMap (mutableCell bit) = (List.range t).flatMap (mutableCell (constant b)) := by
  7959. have go (xs : W) (small : ∀ i ∈ xs, i < t) : xs.flatMap (mutableCell bit) = xs.flatMap (mutableCell (constant b)) := by
  7960. induction xs with
  7961. | nil => rfl
  7962. | cons x xs ih =>
  7963. have tailEq := ih (fun i hi => small i (List.mem_cons_of_mem _ hi))
  7964. simp [List.flatMap_cons,tailEq,mutableCell,constant,all x (small x List.mem_cons_self)]
  7965. exact go _ (fun _ => List.mem_range.mp)
  7966. simp only [word,m]
  7967. /-- The remaining semantic inputs are the constant identity, representation
  7968. of every identical word by cell bits, and detection of each descending
  7969. snake (including wrap) edge. The two-word class is proved from these. -/
  7970. theorem witness {A : Type} {M : Model A} {r t : Nat} (hr : 0 < r) (ht : 0 < t) (middle tail : W)
  7971. (small : ∀ x ∈ middle ++ tail, x < 2*t)
  7972. (cap : P455Quotient.Cap r (word t middle tail (constant false)))
  7973. (identity : M.Valid (word t middle tail (constant false)) (word t middle tail (constant true)))
  7974. (represent : ∀ w, M.Valid (word t middle tail (constant false)) w →
  7975. ∃ bit, w = word t middle tail bit)
  7976. (edge : ∀ bit, M.Valid (word t middle tail (constant false)) (word t middle tail bit) →
  7977. (∀ i, i+1 < t → bit i = true → bit (i+1) = true) ∧
  7978. (0 < t → bit (t-1) = true → bit 0 = true)) :
  7979. RankWitness M r (word t middle tail (constant false)) (word t middle tail (constant true))
  7980. (List.range (2*t)) := by
  7981. have m0 : 0 ∈ List.range (2*t) := List.mem_range.mpr (by omega)
  7982. obtain ⟨y,change0⟩ := participants middle tail 0 m0
  7983. have ne : word t middle tail (constant false) ≠ word t middle tail (constant true) :=
  7984. fun e => change0 (congrArg (proj 0 y) e)
  7985. have nonempty (bit : Nat → Bool) : word t middle tail bit ≠ [] := by
  7986. obtain ⟨p,q,eq⟩ := private_factor (i:=0) ht middle tail bit
  7987. rw [eq]; simp [privateCell]
  7988. refine ⟨⟨nonempty _,nonempty _⟩,ne,identity,?_,cap,no_links hr _ small cap,
  7989. List.nodup_range,participants middle tail⟩
  7990. intro w valid
  7991. obtain ⟨bit,rfl⟩ := represent w valid
  7992. obtain ⟨nx,wrap⟩ := edge bit valid
  7993. obtain ⟨b,all⟩ := cycle_constant bit nx wrap
  7994. cases b with
  7995. | false => exact Or.inl (word_constant middle tail bit false all)
  7996. | true => exact Or.inr (word_constant middle tail bit true all)
  7997. end P455RectangleRank
  7998. end
  7999. /- Begin Problem455EffectiveMachineDiagonal (from finite-semigroup-identity-bases). -/
  8000. section
  8001. /- A diagonal argument for actual deterministic finite-control one-head
  8002. machines. Input is a finite Boolean word over two tape symbols. -/
  8003. namespace P455EffectiveMachine
  8004. open P455MachineLocal P455MachineCleanup P455MachineTable
  8005. structure Alphabet (M : Ordinary g q) where
  8006. bit : Bool → Fin g
  8007. away : ∀ b, bit b ≠ M.marker
  8008. ink : ∀ b, bit b ≠ M.blank
  8009. distinct : bit false ≠ bit true
  8010. /-- Position zero holds the permanent marker. Input occupies positions
  8011. 1 through length. All further cells are initially blank. -/
  8012. def inputTape (M : Ordinary g q) (A : Alphabet M) (w : List Bool) : Nat → Fin g
  8013. | 0 => M.marker
  8014. | x+1 => (w[x]?).elim M.blank A.bit
  8015. def inputConfig (M : Ordinary g q) (A : Alphabet M) (w : List Bool) : Config g q :=
  8016. ⟨inputTape M A w,0,M.start⟩
  8017. def follow (M : Ordinary g q) (c : Config g q) : Nat → Config g q
  8018. | 0 => c
  8019. | t+1 => once M (follow M c t)
  8020. def HALT (M : Ordinary g q) (c : Config g q) := ∃ t, instruction M (follow M c t)=none
  8021. def selfBits (M : Ordinary g q) (A : Alphabet M) : List Bool :=
  8022. unary (A.bit false).val ++ unary (A.bit true).val ++ (quote M).bits
  8023. def SelfHalt (M : Ordinary g q) (A : Alphabet M) :=
  8024. HALT M (inputConfig M A (selfBits M A))
  8025. theorem inputTape_blank (M : Ordinary g q) (A : Alphabet M) :
  8026. inputConfig M A [] = config₀ M := by
  8027. have tape : inputTape M A [] = fun x => if x=0 then M.marker else M.blank := by
  8028. funext x; cases x <;> simp [inputTape]
  8029. simp [inputConfig,config₀,tape]
  8030. theorem blank_run (M : Ordinary g q) (t : Nat) : follow M (config₀ M) t = original M t := by
  8031. induction t with
  8032. | zero => rfl
  8033. | succ t ih => simp only [follow,original,ih]
  8034. theorem blank_halts (M : Ordinary g q) : HALT M (config₀ M) ↔ ∃ t, stopped M t := by
  8035. simp only [HALT,stopped,blank_run]
  8036. theorem rest (M : Ordinary g q) (c : Config g q) {t} (h : instruction M (follow M c t)=none) (k) :
  8037. follow M c (t+k)=follow M c t := by
  8038. induction k with
  8039. | zero => rfl
  8040. | succ k ih => simp [Nat.add_succ,follow,ih,once,h]
  8041. theorem unique_halt (M : Ordinary g q) (c : Config g q) {a b}
  8042. (ha : instruction M (follow M c a)=none) (hb : instruction M (follow M c b)=none) :
  8043. follow M c a=follow M c b := by
  8044. by_cases le : a≤b
  8045. · have e := rest M c ha (b-a)
  8046. rw [show a+(b-a)=b by omega] at e
  8047. exact e.symm
  8048. · have e := rest M c hb (a-b)
  8049. rw [show b+(a-b)=a by omega] at e
  8050. exact e
  8051. def trap (M : Ordinary g q) (answer : Fin q → Bool) : Ordinary g q where
  8052. marker := M.marker
  8053. blank := M.blank
  8054. blank_ne := M.blank_ne
  8055. start := M.start
  8056. delta := fun s a =>
  8057. match M.delta s a with
  8058. | some i => some i
  8059. | none => if answer s then some ⟨s,a,.stay⟩ else none
  8060. keeps := by
  8061. intro s a i eq
  8062. cases h : M.delta s a with
  8063. | some j => simp only [h,Option.some.injEq] at eq; exact M.keeps s a i (eq ▸ h)
  8064. | none =>
  8065. simp only [h] at eq
  8066. split at eq <;> simp_all <;> subst i <;> simp
  8067. leftSafe := by
  8068. intro s i eq
  8069. cases h : M.delta s M.marker with
  8070. | some j => simp only [h,Option.some.injEq] at eq; exact M.leftSafe s i (eq ▸ h)
  8071. | none =>
  8072. simp only [h] at eq
  8073. split at eq <;> simp_all <;> subst i <;> simp
  8074. def liftAlphabet (M : Ordinary g q) (A : Alphabet M) (answer : Fin q → Bool) : Alphabet (trap M answer) :=
  8075. ⟨A.bit,A.away,A.ink,A.distinct⟩
  8076. theorem write_same (f : Nat → Fin g) (p) : writeAt f p (f p) = f := by
  8077. funext i; by_cases h : i=p <;> simp [writeAt,h]
  8078. theorem once_trap (M : Ordinary g q) (ans) (c : Config g q) : once (trap M ans) c = once M c := by
  8079. cases c with
  8080. | mk tape pos state =>
  8081. cases e : M.delta state (tape pos) with
  8082. | some i => simp [once,instruction,trap,e]
  8083. | none => cases h : ans state <;> simp [once,instruction,trap,e,h,dest,write_same]
  8084. theorem follow_trap (M : Ordinary g q) (ans) (c : Config g q) (t) :
  8085. follow (trap M ans) c t = follow M c t := by
  8086. induction t with
  8087. | zero => rfl
  8088. | succ t ih => simp only [follow,ih,once_trap]
  8089. theorem stop_trap (M : Ordinary g q) (ans) (c : Config g q) :
  8090. instruction (trap M ans) c=none ↔ instruction M c=none ∧ ans c.state=false := by
  8091. cases e : M.delta c.state (c.tape c.pos) <;> cases h : ans c.state <;> simp [instruction,trap,e,h]
  8092. theorem halt_trap_iff (M : Ordinary g q) (ans) (c : Config g q) {t}
  8093. (ended : instruction M (follow M c t)=none) :
  8094. HALT (trap M ans) c ↔ ans (follow M c t).state=false := by
  8095. constructor
  8096. · rintro ⟨i,hi⟩
  8097. rw [follow_trap,stop_trap] at hi
  8098. exact unique_halt M c hi.1 ended ▸ hi.2
  8099. · intro h
  8100. exact ⟨t,by rw [follow_trap,stop_trap]; exact ⟨ended,h⟩⟩
  8101. /-- A decider may have any finite work alphabet and arbitrary finite
  8102. control. On the code of a binary-input machine it must halt and its
  8103. Boolean output is read from the final control state. No behavior on
  8104. ill-formed encodings is required. -/
  8105. def DecidesSelf (D : Ordinary g q) (A : Alphabet D) (answer : Fin q→Bool) : Prop :=
  8106. ∀ {g' q'} (P : Ordinary g' q') (B : Alphabet P),
  8107. let c := inputConfig D A (selfBits P B)
  8108. ∃ t, instruction D (follow D c t)=none ∧
  8109. (answer (follow D c t).state=true ↔ SelfHalt P B)
  8110. theorem no_self_decider (D : Ordinary g q) (A : Alphabet D) (answer : Fin q → Bool) :
  8111. ¬DecidesSelf D A answer := by
  8112. intro correct
  8113. let P := trap D answer
  8114. let B := liftAlphabet D A answer
  8115. let c := inputConfig D A (selfBits P B)
  8116. have same : inputConfig P B (selfBits P B)=c := rfl
  8117. obtain ⟨t,halt,ok⟩ := correct P B
  8118. change instruction D (follow D c t)=none at halt
  8119. change (answer (follow D c t).state=true ↔ HALT P (inputConfig P B (selfBits P B))) at ok
  8120. rw [same] at ok
  8121. have contradiction := ok.trans (halt_trap_iff D answer c halt)
  8122. cases e : answer (follow D c t).state <;> simp [e] at contradiction
  8123. end P455EffectiveMachine
  8124. end
  8125. /- Begin Problem455CrossedSupport (from finite-semigroup-identity-bases). -/
  8126. section
  8127. /- The guard used for a crossed flip is constructed from the two actual
  8128. source names. The remaining geometric premise concerns only the counts
  8129. of literal original-slot occupants in the indicated radius. -/
  8130. namespace P455CrossedSupport
  8131. open P455Witness P455Paths P455ContactLift P455SourceFamilies
  8132. open P455OriginalWalk P455SourceTheorem Problem455.Slots
  8133. def ClosedFlip (r : Nat) (allow : Tag → Prop) (u : W) (x y : Nat) : Prop :=
  8134. ∃ (f : P455Closure.Frame Nat) (b : Bool) (l k : W),
  8135. f.p = [x] ∧ f.q = [y] ∧ f.Valid r allow (fun _ _ => False) ∧ u = l ++ f.core b ++ k
  8136. theorem flip_counts {r allow u x y} (cap : P455Closure.Cap r u) (flip : ClosedFlip r allow u x y) :
  8137. 1 < r ∧ u.count x = r ∧ u.count y = r ∧ x ≠ y := by
  8138. obtain ⟨f,b,l,k,hp,hq,v,rfl⟩ := flip
  8139. have one (a : Nat) (mem : a ∈ f.p ∨ a ∈ f.q) : (l ++ f.core b ++ k).count a = r := by
  8140. have sat := v.2.2.2.2.2.2.2 a mem
  8141. have bit : (f.core b).count a = r := by cases b <;> first | exact sat | exact (f.count_core a true).trans sat
  8142. have bound := cap a; simp only [List.count_append,bit] at bound ⊢; omega
  8143. have xp : x ∈ f.p := by simp [hp]
  8144. have yq : y ∈ f.q := by simp [hq]
  8145. exact ⟨by have := v.1; omega,one _ (.inl xp),one _ (.inr yq),
  8146. fun e => v.2.2.2.2.2.1 _ xp (e ▸ yq)⟩
  8147. def markedRecord (c : Certificate) (second : Bool) : Node :=
  8148. match c with
  8149. | .slot s => s.anchor
  8150. | .functionality f => f.anchor
  8151. | .edge e => if second then e.b else e.a
  8152. /-- Either orientation of the chosen unordered pair across the two images. -/
  8153. def Crosses (n : Node) (h : Nat → W) (x y : Nat) : Prop :=
  8154. (n.owner ∈ h x ∧ n.mate ∈ h y) ∨ (n.owner ∈ h y ∧ n.mate ∈ h x)
  8155. theorem start_role (c : Certificate) (second mate : Bool) :
  8156. startLabel c second mate = (markedRecord c second).owner ∨
  8157. startLabel c second mate = (markedRecord c second).mate := by
  8158. cases c with
  8159. | slot s => cases e : s.startAtMate <;> simp [picked,startLabel,markedRecord,e]
  8160. | functionality f => exact .inl rfl
  8161. | edge e => cases mate <;> simp [startLabel,markedRecord]
  8162. theorem choose_seed {h x y} (c : Certificate) (second mate : Bool)
  8163. (cross : Crosses (markedRecord c second) h x y) :
  8164. ∃ seed, (seed = x ∨ seed = y) ∧ startLabel c second mate ∈ h seed := by
  8165. rcases start_role c second mate with owner|other
  8166. · rcases cross with c1|c2
  8167. · exact ⟨x,.inl rfl,owner.symm ▸ c1.1⟩
  8168. · exact ⟨y,.inr rfl,owner.symm ▸ c2.1⟩
  8169. · rcases cross with c1|c2
  8170. · exact ⟨y,.inr rfl,other.symm ▸ c1.2⟩
  8171. · exact ⟨x,.inl rfl,other.symm ▸ c2.2⟩
  8172. def InBall (r : Nat) (allow : Tag → Prop) (mark : Marking) (u : W) (x y t : Nat) :=
  8173. Near r allow mark u x t 6 ∨ Near r allow mark u y t 6
  8174. def UniformSlots (r : Nat) (allow : Tag → Prop) (mark : Marking) (u : W) (x y : Nat) :=
  8175. ∀ t, InBall r allow mark u x y t → ∀ i, slotStart i → ∀ b, occupies u t i b → u.count b = r
  8176. def Needed (r : Nat) (allow : Tag → Prop) (mark : Marking) (u : W) (x y b : Nat) : Prop :=
  8177. InBall r allow mark u x y b ∨ ∃ t i, InBall r allow mark u x y t ∧ slotStart i ∧ occupies u t i b
  8178. /-- Finite retained support. Repetitions in the carrier list u do not affect
  8179. membership. Tile compatibility and allowed tags can be arbitrary predicates. -/
  8180. noncomputable def retained (r : Nat) (allow : Tag → Prop) (mark : Marking) (u : W) (x y : Nat) : W := by
  8181. classical
  8182. exact u.filter (fun b => decide (Needed r allow mark u x y b))
  8183. theorem mem_retained {r allow mark u x y b} :
  8184. b ∈ retained r allow mark u x y ↔ b ∈ u ∧ Needed r allow mark u x y b := by
  8185. classical
  8186. simp [retained]
  8187. theorem walked_name {r allow mark u} (hr : 0 < r) (cap : P455Closure.Cap r u) (a : Nat)
  8188. (p : List Step) (ha : a ∈ u) (w : Walk r allow mark u a p) : endpoint a p ∈ u := by
  8189. induction p generalizing a with
  8190. | nil => exact ha
  8191. | cons step ps ih =>
  8192. obtain ⟨b,c⟩ := step
  8193. have count := (P455Retained.contact_counts cap w.1).2
  8194. exact ih b (List.count_pos_iff.mp (count.symm ▸ hr)) w.2
  8195. theorem actual_guard {r allow mark u x y seed} (hr : 0 < r) (cap : P455Closure.Cap r u)
  8196. (hx : x ∈ u) (hy : y ∈ u) (side : seed = x ∨ seed = y) (unif : UniformSlots r allow mark u x y) :
  8197. OriginalGuard r allow mark u (fun a => a ∈ retained r allow mark u x y) seed 6 := by
  8198. intro t near
  8199. have ball : InBall r allow mark u x y t := side.elim (fun a => .inl (a ▸ near)) (fun a => .inr (a ▸ near))
  8200. have hs : seed ∈ u := side.elim (fun a => a.symm ▸ hx) (fun a => a.symm ▸ hy)
  8201. obtain ⟨p,w,eq,_⟩ := near
  8202. have ht := eq ▸ walked_name hr cap seed p hs w
  8203. refine ⟨mem_retained.mpr ⟨ht,.inl ball⟩,?_⟩
  8204. intro i hi b between
  8205. have inside : b ∈ u := by
  8206. obtain ⟨j,events⟩ := between
  8207. exact stamped_mem_label _ _ (b,j) (events.subset (by simp))
  8208. exact ⟨mem_retained.mpr ⟨inside,.inr ⟨t,i,ball,hi,between⟩⟩,unif t ball i hi b between⟩
  8209. end P455CrossedSupport
  8210. end
  8211. /- Begin Problem455EdgeProjection (from finite-semigroup-identity-bases). -/
  8212. section
  8213. namespace P455EdgeProjection
  8214. open P455Witness P455Paths P455SourceFamilies P455CertificateReach P455PortReflection P455EdgeSource
  8215. open P455DefectProjection P455OtherProjection P455DefectRename Problem455.Slots
  8216. def candidates (ts : Tiles) (e : EdgeCertificate) : List (Node × Bool) :=
  8217. [(e.a,true),(e.b,true),(e.right,!ts.right e.a.tag),(e.left,!ts.left e.a.tag),
  8218. (e.down,!ts.bottom e.a.tag),(e.up,!ts.top e.a.tag),
  8219. (e.diagonal,!ts.right e.a.tag && !ts.bottom e.a.tag)]
  8220. def nodes (ts : Tiles) (e : EdgeCertificate) :=
  8221. ((candidates ts e).filter Prod.snd).map Prod.fst
  8222. def names (ts : Tiles) (e : EdgeCertificate) := (nodes ts e).flatMap roles
  8223. theorem nodes_exact {ts e n} : n ∈ nodes ts e ↔ Active ts e n := by
  8224. constructor
  8225. · intro h; obtain ⟨⟨j,b⟩,m,rfl⟩ := List.mem_map.mp h
  8226. obtain ⟨cand,bok⟩ := List.mem_filter.mp m
  8227. change b = true at bok; subst b
  8228. simp only [candidates,List.mem_cons,List.not_mem_nil,or_false,Prod.mk.injEq,
  8229. true_and,and_true] at cand
  8230. rcases cand with h|h|⟨h,p⟩|⟨h,p⟩|⟨h,p⟩|⟨h,p⟩|⟨h,p⟩ <;> subst j
  8231. · exact .anchor
  8232. · exact .successor
  8233. · exact .right (by simpa using p.symm)
  8234. · exact .left (by simpa using p.symm)
  8235. · exact .down (by simpa using p.symm)
  8236. · exact .up (by simpa using p.symm)
  8237. · have two : ts.right e.a.tag = false ∧ ts.bottom e.a.tag = false := by simpa using p.symm
  8238. exact .diagonal two.1 two.2
  8239. · intro active
  8240. apply List.mem_map.mpr
  8241. refine ⟨(_,true),List.mem_filter.mpr ⟨?_,rfl⟩,rfl⟩
  8242. cases active <;> simp_all [candidates]
  8243. theorem names_exact {ts e x} : x ∈ names ts e ↔ ∃ n, Active ts e n ∧ x ∈ roles n := by
  8244. simp [names,List.mem_flatMap,nodes_exact]
  8245. theorem names_bound (ts : Tiles) (e : EdgeCertificate) : (names ts e).length ≤ 14 := by
  8246. have rep (ls : List Node) : (ls.flatMap roles).length = ls.length * 2 := by
  8247. induction ls with
  8248. | nil => rfl
  8249. | cons x ls ih => simp [roles,List.flatMap_cons,ih,Nat.add_mul, Nat.add_comm] at *; omega
  8250. have bound : (nodes ts e).length ≤ 7 := by
  8251. simpa [nodes,candidates] using (List.length_filter_le Prod.snd (candidates ts e))
  8252. rw [names,rep]; omega
  8253. theorem covered {ts e n} (ac : Active ts e n) : Covers (names ts e) (roles n) :=
  8254. fun _ h => names_exact.mpr ⟨n,ac,h⟩
  8255. theorem saturated {r allow mark u} (cap : P455Closure.Cap r u) (ts : Tiles) (e : EdgeCertificate)
  8256. (ok : Holds r allow mark u (e.query ts)) {x : Nat} (mem : x ∈ names ts e) : u.count x = r := by
  8257. obtain ⟨n,ac,role⟩ := names_exact.mp mem
  8258. have ct := record_counts cap (active_owner cap ts e ok ac).2
  8259. rcases (show x = n.owner ∨ x = n.mate by simpa [roles] using role) with rfl|rfl
  8260. · exact ct.1
  8261. · exact ct.2
  8262. private theorem flag {r allow mark u} (keep : W) (b : Bool) (q : Query)
  8263. (transfer : b = true → Holds r allow mark u q → Holds r allow mark (select keep u) q)
  8264. (h : Holds r allow mark u (flagQ b q)) : Holds r allow mark (select keep u) (flagQ b q) := by
  8265. cases b
  8266. · exact True.intro
  8267. · exact transfer rfl h
  8268. theorem project_edge {r allow mark u} (ts : Tiles) (e : EdgeCertificate)
  8269. (ok : Holds r allow mark u (e.query ts)) : Holds r allow mark (select (names ts e) u) (e.query ts) := by
  8270. let keep := names ts e
  8271. have ka : Covers keep (roles e.a) := covered .anchor
  8272. have kb : Covers keep (roles e.b) := covered .successor
  8273. have ao := ka e.a.owner (by simp [roles]); have am := ka e.a.mate (by simp [roles])
  8274. have bo := kb e.b.owner (by simp [roles]); have bm := kb e.b.mate (by simp [roles])
  8275. obtain ⟨ma,mb,lc,succ,_⟩ := ok
  8276. refine ⟨select_marked keep _ _ ao am ma,select_marked keep _ _ bo bm mb,?_,?_,True.intro⟩
  8277. · refine ⟨flag keep _ _ (fun b q => ?_) lc.1,flag keep _ _ (fun b q => ?_) lc.2.1,
  8278. flag keep _ _ (fun b q => ?_) lc.2.2.1,flag keep _ _ (fun b q => ?_) lc.2.2.2.1,
  8279. flag keep _ _ (fun b q => ?_) lc.2.2.2.2.1,True.intro⟩
  8280. · exact select_neighbor keep ts e.a e.right .right ka (covered (.right (by simpa using b))) q
  8281. · exact select_neighbor keep ts e.a e.left .left ka (covered (.left (by simpa using b))) q
  8282. · exact select_neighbor keep ts e.a e.down .down ka (covered (.down (by simpa using b))) q
  8283. · exact select_neighbor keep ts e.a e.up .up ka (covered (.up (by simpa using b))) q
  8284. · have pair : ts.right e.a.tag = false ∧ ts.bottom e.a.tag = false := by simpa using b
  8285. have dg := covered (e := e) (.diagonal pair.1 pair.2)
  8286. exact ⟨select_neighbor keep ts e.right e.diagonal .down (covered (.right pair.1)) dg q.1,
  8287. select_neighbor keep ts e.down e.diagonal .right (covered (.down pair.2)) dg q.2⟩
  8288. · unfold chosenSuccessor at succ ⊢
  8289. dsimp only at succ ⊢
  8290. split at succ
  8291. next ret =>
  8292. rw [if_pos ret]
  8293. refine ⟨succ.1,succ.2.1.elim (fun q => .inl (select_port keep _ _ _ ka kb q))
  8294. (fun q => .inr (select_port keep _ _ _ kb ka q)),
  8295. select_order keep _ (by simp [bo,ao]) succ.2.2.1,True.intro⟩
  8296. next other =>
  8297. rw [if_neg other]
  8298. exact ⟨succ.1,select_order keep _ (by simp [bo,ao]) succ.2⟩
  8299. def template (ts : Tiles) (e : EdgeCertificate) (u : W) :=
  8300. (select (names ts e) u).map (names ts e).idxOf
  8301. /-- The only source assumptions are the cap and an actual 1,0 edge
  8302. certificate in the observed side. The other side is unrestricted.
  8303. Marking the two endpoint records retains the bit of either one. -/
  8304. theorem canonical_edge {r allow mark u} (cap : P455Closure.Cap r u) (ts : Tiles) (e : EdgeCertificate)
  8305. (ok : Holds r allow mark u (e.query ts)) :
  8306. let keep := names ts e
  8307. let T := template ts e u
  8308. P455Closure.Cap r T ∧ (∀ x ∈ T, x < 14 ∧ T.count x = r) ∧
  8309. Holds r allow (endpointMarks keep.idxOf e) T ((sendEdge keep.idxOf e).query ts) := by
  8310. let keep := names ts e
  8311. let w := select keep u
  8312. let T := template ts e u
  8313. let d := keep.idxOf
  8314. have hr : 0 < r := by have h : e.a.tag.length + 16 = r := ok.1.2.1; omega
  8315. have sat {x : Nat} (hx : x ∈ keep) : w.count x = r :=
  8316. (select_count keep u x hx).trans (saturated cap ts e ok hx)
  8317. have small (x) (m : x ∈ w) : x ∈ keep := kept m
  8318. have ext : w.map (extend keep) = T := extend_map small
  8319. have cp : P455Closure.Cap r T := ext ▸ cap_rename (extend keep) (extend_inj keep) (select_cap keep cap)
  8320. have ct {x : Nat} (hx : x ∈ keep) : T.count (d x) = r := by
  8321. rw [← ext,show d x = extend keep x by simp [d,extend,hx],count_rename _ (extend_inj keep),sat hx]
  8322. refine ⟨cp,?_,?_⟩
  8323. · intro y hy; obtain ⟨x,xm,rfl⟩ := List.mem_map.mp hy
  8324. exact ⟨Nat.lt_of_lt_of_le (List.idxOf_lt_length_of_mem (small x xm)) (names_bound ts e),ct (small x xm)⟩
  8325. · let h := fun j => [decode keep j]
  8326. have back : ([] : W) ++ T.flatMap h ++ [] = w := by
  8327. have single (v : W) : v.flatMap h = v.map (decode keep) := by
  8328. induction v with
  8329. | nil => rfl
  8330. | cons a v ih => simp [h,List.flatMap_cons,ih] at *
  8331. simpa only [List.nil_append,List.append_nil,single,T,template,keep,w] using decode_map small
  8332. have uniform (n : Node) (ac : Active ts e n) : UniformOn r T h d (roles n) := by
  8333. intro x hx; have k := covered ac x hx
  8334. exact ⟨ct k,by simp [h,d,decode_idx keep k]⟩
  8335. exact edge_source (mark := mark) (l := []) (k := []) hr (by rw [back]; exact select_cap keep cap)
  8336. ts e uniform (by rw [back]; exact project_edge ts e ok)
  8337. end P455EdgeProjection
  8338. end
  8339. /- Begin Problem455Structural (from finite-semigroup-identity-bases). -/
  8340. section
  8341. namespace P455Structural
  8342. open P455Witness P455Quotient P455Closure P455Uncrossed Problem455.Slots
  8343. open P455SourceFamilies P455FirstTesters
  8344. private theorem image_edge (h : Nat → W) (x a b : Nat)
  8345. (pos : 0 < Problem455Swap.bigram a b (h x)) (u : W) :
  8346. u.count x ≤ Problem455Swap.bigram a b (u.flatMap h) := by
  8347. induction u with
  8348. | nil => simp [Problem455Swap.bigram]
  8349. | cons z u ih =>
  8350. simp only [List.flatMap_cons,Problem455Swap.bigram_append]
  8351. by_cases e : z=x
  8352. · subst z; simp [List.count_cons]; omega
  8353. · simp [List.count_cons,e]; omega
  8354. private theorem singleton_in_template {r : Nat} {T p q u : W} {h : Nat → W} {x : Nat}
  8355. (eq : T = p ++ u.flatMap h ++ q) (cap : P455Closure.Cap r T) (cmp : Compressed r T)
  8356. (cx : u.count x = r) (nonempty : h x ≠ []) : ∃ a, h x = [a] := by
  8357. cases z : h x with
  8358. | nil => exact False.elim (nonempty z)
  8359. | cons a t =>
  8360. cases t with
  8361. | nil => exact ⟨a,rfl⟩
  8362. | cons b t =>
  8363. have pair : 0 < Problem455Swap.bigram a b (h x) := by
  8364. rw [z]; simp [Problem455Swap.bigram,Problem455Swap.hit] <;> omega
  8365. have base := image_edge h x a b pair u
  8366. have low : r ≤ Problem455Swap.bigram a b T := by
  8367. rw [eq,Problem455Swap.bigram_append,Problem455Swap.bigram_append]; omega
  8368. have top := Problem455Swap.out_bound a b (b+1) (by omega) T
  8369. rw [Problem455BlockBridge.occ_count] at top
  8370. have high := cap a
  8371. exact False.elim (cmp a b (by unfold Problem455Swap.Link; omega))
  8372. private theorem image_count {r : Nat} (h : Nat → W) (u : W) (x a : Nat)
  8373. (c : u.count x = r) (img : h x = [a]) : r ≤ (u.flatMap h).count a := by
  8374. have h := P455DonorInterval.split_contributions h u x a
  8375. simp [img,c] at h
  8376. omega
  8377. /-- Under any substitution, a live factor in a structural tester gives
  8378. literal equality of the two substituted words. All other images may be
  8379. empty or arbitrarily long and may use shared names. -/
  8380. theorem structural_factor {r T allow} (cap : P455Closure.Cap r T) (cmp : Compressed r T)
  8381. (stest : Structural T r allow) (f : Frame Nat) (l k : W) (bit : Bool) (x y : Nat)
  8382. (hp : f.p = [x]) (hq : f.q = [y]) (valid : f.Valid r allow (fun _ _ => False))
  8383. (h : Nat → W) (fac : Factor ((side f l k bit).flatMap h) T) :
  8384. (side f l k bit).flatMap h = (side f l k (!bit)).flatMap h := by
  8385. obtain ⟨pre,post,eq⟩ := fac
  8386. have eqCore : T = (pre ++ l.flatMap h) ++ (f.core bit).flatMap h ++ (k.flatMap h ++ post) := by
  8387. simpa [side,List.flatMap_append,List.append_assoc] using eq
  8388. have count (z : Nat) (role : z = x ∨ z = y) : (f.core bit).count z = r := by
  8389. have has : z ∈ f.p ∨ z ∈ f.q := by simpa [hp,hq] using role
  8390. have orig := valid.2.2.2.2.2.2.2 z has
  8391. cases bit with
  8392. | false => exact orig
  8393. | true => exact (f.count_core z true).trans orig
  8394. have commute : h x ++ h y = h y ++ h x := by
  8395. by_cases nx : h x = []
  8396. · simp [nx]
  8397. by_cases ny : h y = []
  8398. · simp [ny]
  8399. obtain ⟨a,ax⟩ := singleton_in_template eqCore cap cmp (count x (.inl rfl)) nx
  8400. obtain ⟨b,by'⟩ := singleton_in_template eqCore cap cmp (count y (.inr rfl)) ny
  8401. by_cases ab : a=b
  8402. · simp [ax,by',ab]
  8403. exfalso
  8404. apply structural_excludes_closed stest
  8405. let L := pre ++ l.flatMap h
  8406. have fresh (z s : Nat) (kind : z=x ∨ z=y) (im : h z = [s]) : s ∉ L := by
  8407. have bound := cap s
  8408. rw [eqCore] at bound
  8409. have ct := image_count h (f.core bit) z s (count z kind) im
  8410. apply List.count_eq_zero.mp
  8411. dsimp [L]
  8412. simp only [List.count_append] at bound ⊢
  8413. omega
  8414. let tail := f.mid ++ f.beforeMutable ++ f.pair bit ++ f.beforeFinalP ++ f.p ++ f.beforeFinalQ ++ f.q
  8415. have shape : f.core bit = f.early ++ tail := by simp [Frame.core,tail,List.append_assoc]
  8416. refine ⟨ab,L,tail.flatMap h ++ (k.flatMap h ++ post),?_,fresh x a (.inl rfl) ax,fresh y b (.inr rfl) by'⟩
  8417. rw [eqCore,shape]
  8418. simp [L,Frame.early,hp,hq,List.flatMap_append,List.flatMap_cons,ax,by',List.append_assoc,early]
  8419. cases bit <;>
  8420. simp only [side,Frame.core,Frame.pair,List.flatMap_append,List.flatMap_cons,List.flatMap_nil,
  8421. Bool.false_eq_true,if_false,if_true,Bool.not_false,Bool.not_true,hp,hq,List.append_nil] <;>
  8422. rw [commute]
  8423. private theorem plain_factor {r : Nat} {T u : W} (g : Good (plain r) T u) : Factor u T := by
  8424. obtain ⟨v,walk,fac⟩ := g
  8425. have e : T=v := by induction walk with
  8426. | refl => rfl
  8427. | snoc _ impossible _ => exact False.elim impossible
  8428. exact e ▸ fac
  8429. /-- Universal equality in the actual Rees factor monoid of each structural
  8430. template. Zero evaluations, either live orientation and arbitrary good
  8431. representatives are handled through the quotient evaluation. -/
  8432. theorem structural_eval {r T allow} (cap : P455Closure.Cap r T) (cmp : Compressed r T)
  8433. (stest : Structural T r allow) (f : Frame Nat) (l k : W) (x y : Nat)
  8434. (hp : f.p=[x]) (hq : f.q=[y]) (valid : f.Valid r allow (fun _ _ => False))
  8435. (val : Nat → Q (plain r) T) :
  8436. eval (plain r) cap val (side f l k false) = eval (plain r) cap val (side f l k true) := by
  8437. classical
  8438. apply Classical.byContradiction
  8439. intro d
  8440. let R := plain r
  8441. have live : ∃ b : Bool, eval R cap val (side f l k b) ≠ zero R T := by
  8442. by_cases nz : eval R cap val (side f l k false) ≠ zero R T
  8443. · exact ⟨false,nz⟩
  8444. · exact ⟨true,fun eq => d ((Classical.not_not.mp nz).trans eq.symm)⟩
  8445. obtain ⟨b,nz⟩ := live
  8446. let u := side f l k b
  8447. have existsRep (a : Nat) (ha : a ∈ u) :=
  8448. nonzero_representative R (val a) (live_inputs R cap val _ nz a ha)
  8449. let h (a : Nat) := if yes : a ∈ u then (existsRep a yes).choose else []
  8450. have rep (a) (mem : a ∈ u) : ofWord R T (h a) = val a := by
  8451. simpa only [h,dif_pos mem] using (existsRep a mem).choose_spec.2
  8452. have original := eval_rep R cap val u h rep
  8453. have separated := structural_factor cap cmp stest f l k b x y hp hq valid h
  8454. (plain_factor ((nonzero_iff R).mp (original ▸ nz)))
  8455. have other := eval_rep R cap val (side f l k (!b)) h
  8456. (fun a ha => rep a ((same_letters f l k b a).mpr ha))
  8457. have done := original.trans ((congrArg (ofWord R T) separated).trans other.symm)
  8458. cases b
  8459. · exact d done
  8460. · exact d done.symm
  8461. end P455Structural
  8462. end
  8463. /- Begin Problem455PaddedPorts (from finite-semigroup-identity-bases). -/
  8464. section
  8465. namespace P455PaddedPorts
  8466. open P455RectangleRank Problem455.Slots
  8467. abbrev W := List Nat
  8468. inductive Block where
  8469. | single (i : Nat)
  8470. | pair (i j : Nat)
  8471. deriving DecidableEq
  8472. def cells : Block → W
  8473. | .single i => [i]
  8474. | .pair i j => [i,j]
  8475. def phase (bs : List Block) := bs.flatMap fun b => cells b ++ cells b
  8476. def roles (i : Nat) := [owner i,mate i]
  8477. def letters (bs : List Block) := (phase bs).flatMap roles
  8478. private theorem singleton_head {i j u : Nat} {p : W} (ne : i≠j)
  8479. (eq : u :: u :: p = [i,j,i,j]) : False := by
  8480. obtain ⟨rfl,e⟩ := List.cons.inj eq
  8481. exact ne (List.cons.inj e).1
  8482. private theorem only_pair (bs : List Block) (i j : Nat) (ne : i≠j)
  8483. (obs : select [i,j] (phase bs)=[i,j,i,j]) : Block.pair i j ∈ bs := by
  8484. induction bs with
  8485. | nil => simp [phase,select] at obs
  8486. | cons b bs ih =>
  8487. change select [i,j] ((cells b ++ cells b) ++ phase bs) = _ at obs
  8488. rw [select_append,select_append] at obs
  8489. cases b with
  8490. | single u =>
  8491. by_cases hu : u=i ∨ u=j
  8492. · have su : select [i,j] [u]=[u] := by simp [select,hu]
  8493. simp only [cells,su,List.cons_append,List.nil_append] at obs
  8494. exact (singleton_head ne obs).elim
  8495. · have su : select [i,j] [u]=[] := by simp [select,hu]
  8496. simp only [cells,su,List.nil_append] at obs
  8497. exact List.mem_cons_of_mem _ (ih obs)
  8498. | pair u v =>
  8499. by_cases hu : u=i ∨ u=j <;> by_cases hv : v=i ∨ v=j
  8500. · have sv : select [i,j] [u,v]=[u,v] := by simp [select,hu,hv]
  8501. simp only [cells,sv,List.cons_append,List.nil_append,List.cons.injEq] at obs
  8502. obtain ⟨rfl,rfl,_⟩ := obs
  8503. exact List.mem_cons_self
  8504. · have sv : select [i,j] [u,v]=[u] := by simp [select,hu,hv]
  8505. simp only [cells,sv,List.cons_append,List.nil_append] at obs
  8506. exact (singleton_head ne obs).elim
  8507. · have sv : select [i,j] [u,v]=[v] := by simp [select,hu,hv]
  8508. simp only [cells,sv,List.cons_append,List.nil_append] at obs
  8509. exact (singleton_head ne obs).elim
  8510. · have sv : select [i,j] [u,v]=[] := by simp [select,hu,hv]
  8511. simp only [cells,sv,List.nil_append] at obs
  8512. exact List.mem_cons_of_mem _ (ih obs)
  8513. private theorem phase_mem (bs : List Block) (x : Nat) : x∈phase bs ↔ x∈bs.flatMap cells := by
  8514. simp [phase,List.mem_flatMap]
  8515. private theorem pair_present {bs : List Block} (nd : (bs.flatMap cells).Nodup)
  8516. (i j : Nat) (present : Block.pair i j ∈ bs) : select [i,j] (phase bs)=[i,j,i,j] := by
  8517. obtain ⟨pre,post,eq⟩ := List.append_of_mem present
  8518. subst bs
  8519. change ((_ ++ (.pair i j :: post)).flatMap cells).Nodup at nd
  8520. simp only [List.flatMap_append,List.flatMap_cons,cells,List.cons_append,List.nil_append] at nd
  8521. have parts := List.pairwise_append.mp nd
  8522. have hits (x : Nat) (m : x∈pre.flatMap cells) : x∉[i,j] := by
  8523. intro e
  8524. have no := parts.2.2 x m x (by simpa using List.mem_append_left (post.flatMap cells) e : x∈i::j::post.flatMap cells)
  8525. exact no rfl
  8526. have ends (x : Nat) (m : x∈post.flatMap cells) : x∉[i,j] := by
  8527. have hi := (List.nodup_cons.mp parts.2.1).1
  8528. have hj := (List.nodup_cons.mp (List.nodup_cons.mp parts.2.1).2).1
  8529. intro e
  8530. rcases (show x=i ∨ x=j by simpa using e) with rfl|rfl
  8531. · exact hi (List.mem_cons_of_mem _ m)
  8532. · exact hj m
  8533. have s1 := select_nil [i,j] (phase pre) (fun x m => hits x ((phase_mem ..).mp m))
  8534. have s2 := select_nil [i,j] (phase post) (fun x m => ends x ((phase_mem ..).mp m))
  8535. change select [i,j] ((pre ++ .pair i j :: post).flatMap _) = _
  8536. rw [List.flatMap_append,List.flatMap_cons,select_append]
  8537. change select [i,j] (phase pre) ++ select [i,j] (([i,j] ++ [i,j]) ++ phase post)=_
  8538. rw [s1,select_append,s2]
  8539. simp [select]
  8540. theorem phase_exact {bs : List Block} (nd : (bs.flatMap cells).Nodup)
  8541. (i j : Nat) (ne : i≠j) :
  8542. select [i,j] (phase bs)=[i,j,i,j] ↔ Block.pair i j∈bs :=
  8543. ⟨only_pair bs i j ne,pair_present nd i j⟩
  8544. private theorem roles_inj {s t : W} (eq : s.flatMap roles=t.flatMap roles) : s=t := by
  8545. induction s generalizing t with
  8546. | nil => cases t <;> simp_all [roles]
  8547. | cons i s ih =>
  8548. cases t with
  8549. | nil => simp [roles] at eq
  8550. | cons j t =>
  8551. simp only [List.flatMap_cons,roles,List.cons_append,List.nil_append,List.cons.injEq] at eq
  8552. have e : i=j := by have := eq.1; unfold owner at this; omega
  8553. rw [e,ih eq.2.2]
  8554. private theorem role_selection (s : W) (i j : Nat) :
  8555. select (roles i ++ roles j) (s.flatMap roles) = (select [i,j] s).flatMap roles := by
  8556. induction s with
  8557. | nil => rfl
  8558. | cons a s ih =>
  8559. by_cases h : a=i ∨ a=j
  8560. · have kept : select (roles i ++ roles j) (roles a)=roles a := by
  8561. rcases h with rfl|rfl <;> simp [roles,select]
  8562. have er : select [i,j] (a::s)=a::select [i,j] s := by simp [select,h]
  8563. simp only [List.flatMap_cons,select_append,kept,ih,er]
  8564. · have hf : a≠i ∧ a≠j := by simpa using h
  8565. have non : ∀ b∈roles a, b∉roles i ++ roles j := by
  8566. intro b m n
  8567. simp only [roles,List.cons_append,List.nil_append,List.mem_cons,List.not_mem_nil,or_false] at m n
  8568. unfold owner mate at m n
  8569. omega
  8570. have erased := select_nil _ _ non
  8571. have er : select [i,j] (a::s)=select [i,j] s := by simp [select,h]
  8572. simp only [List.flatMap_cons,select_append,erased,ih,er,List.nil_append]
  8573. /-- In the literal eight-occurrence projection on the four actual roles,
  8574. the oriented interleaving exists exactly for an intended matching edge.
  8575. This is independent of block order and permits unmatched boundary cells. -/
  8576. theorem literal_phase_exact {bs : List Block} (nd : (bs.flatMap cells).Nodup)
  8577. (i j : Nat) (ne : i≠j) :
  8578. select (roles i ++ roles j) (letters bs) =
  8579. [owner i,mate i,owner j,mate j,owner i,mate i,owner j,mate j] ↔
  8580. Block.pair i j∈bs := by
  8581. unfold letters
  8582. rw [role_selection,← phase_exact nd i j ne]
  8583. change _ = [i,j,i,j].flatMap roles ↔ _
  8584. exact ⟨roles_inj,congrArg (List.flatMap roles)⟩
  8585. end P455PaddedPorts
  8586. end
  8587. /- Begin Problem455EffectiveMachinePrefix (from finite-semigroup-identity-bases). -/
  8588. section
  8589. /- Compile a finite straight-line initialization script into ordinary finite
  8590. control, preserving halting from arbitrary tapes and positions. -/
  8591. namespace P455EffectivePrefix
  8592. open P455EffectiveMachine P455MachineLocal P455MachineTable P455MachineCleanup
  8593. inductive Cmd (g : Nat) | right | left | putRight (v : Fin g)
  8594. structure Env (g : Nat) where
  8595. tape : Nat → Fin g
  8596. pos : Nat
  8597. def Env.start (env : Env g) (M : Ordinary g q) : Config g q := ⟨env.tape,env.pos,M.start⟩
  8598. def write (mark : Fin g) (cmd : Cmd g) (a : Fin g) :=
  8599. match cmd with
  8600. | .putRight v => if a=mark ∨ v=mark then a else v
  8601. | _ => a
  8602. def motion (mark : Fin g) (cmd : Cmd g) (a : Fin g) : Direction :=
  8603. match cmd with
  8604. | .left => if a=mark then .stay else .left
  8605. | _ => .right
  8606. def effect (mark : Fin g) (cmd : Cmd g) (env : Env g) : Env g :=
  8607. let a := env.tape env.pos
  8608. ⟨writeAt env.tape env.pos (write mark cmd a),dest (motion mark cmd a) env.pos⟩
  8609. theorem write_marker (mark : Fin g) (cmd : Cmd g) (a) :
  8610. write mark cmd a=mark ↔ a=mark := by
  8611. cases cmd <;> simp [write]
  8612. split <;> simp_all
  8613. theorem safe_motion (mark : Fin g) (cmd : Cmd g) : motion mark cmd mark ≠ .left := by
  8614. cases cmd <;> simp [motion]
  8615. def old (s : Fin q) : Fin (q+1) := ⟨s.val,by have := s.isLt; omega⟩
  8616. def head (q) : Fin (q+1) := ⟨q,by omega⟩
  8617. def liftIns (i : Ins (Fin g) (Fin q)) : Ins (Fin g) (Fin (q+1)) := ⟨old i.state,i.symbol,i.dir⟩
  8618. def push (M : Ordinary g q) (cmd : Cmd g) : Ordinary g (q+1) where
  8619. marker := M.marker
  8620. blank := M.blank
  8621. blank_ne := M.blank_ne
  8622. start := head q
  8623. delta s a := if h : s.val<q then (M.delta ⟨s.val,h⟩ a).map liftIns
  8624. else some ⟨old M.start,write M.marker cmd a,motion M.marker cmd a⟩
  8625. keeps := by
  8626. intro s a i eq
  8627. split at eq
  8628. next h =>
  8629. cases e : M.delta ⟨s.val,h⟩ a with
  8630. | none => simp [e] at eq
  8631. | some j => rw [e] at eq; change some (liftIns j) = some i at eq; obtain rfl := Option.some.inj eq; exact M.keeps _ _ _ e
  8632. next =>
  8633. simp only [Option.some.injEq] at eq
  8634. subst i; exact write_marker ..
  8635. leftSafe := by
  8636. intro s i eq
  8637. split at eq
  8638. next h =>
  8639. cases e : M.delta ⟨s.val,h⟩ M.marker with
  8640. | none => simp [e] at eq
  8641. | some j => rw [e] at eq; change some (liftIns j) = some i at eq; obtain rfl := Option.some.inj eq; exact M.leftSafe _ _ e
  8642. next =>
  8643. simp only [Option.some.injEq] at eq
  8644. subst i; exact safe_motion M.marker cmd
  8645. def liftConfig (c : Config g q) : Config g (q+1) := ⟨c.tape,c.pos,old c.state⟩
  8646. theorem old_ins (M : Ordinary g q) (cmd) (s a) :
  8647. (push M cmd).delta (old s) a=(M.delta s a).map liftIns := by
  8648. simp [push,old,s.isLt]
  8649. theorem head_ins (M : Ordinary g q) (cmd) (a) :
  8650. (push M cmd).delta (head q) a=some ⟨old M.start,write M.marker cmd a,motion M.marker cmd a⟩ := by
  8651. simp [push,head]
  8652. theorem once_old (M : Ordinary g q) (cmd) (c : Config g q) :
  8653. once (push M cmd) (liftConfig c)=liftConfig (once M c) := by
  8654. cases c with
  8655. | mk tape pos s =>
  8656. cases h : M.delta s (tape pos) <;> simp [once,instruction,liftConfig,old_ins,h,liftIns]
  8657. theorem after_one (M : Ordinary g q) (cmd) (e : Env g) (t) :
  8658. follow (push M cmd) (e.start (push M cmd)) (t+1)=
  8659. liftConfig (follow M ((effect M.marker cmd e).start M) t) := by
  8660. induction t with
  8661. | zero =>
  8662. change once (push M cmd) ⟨e.tape,e.pos,head q⟩=_
  8663. simp [once,instruction,head_ins,follow,liftConfig,effect,Env.start]
  8664. | succ t ih => rw [follow,ih,once_old,follow]
  8665. theorem push_iff (M : Ordinary g q) (cmd) (e : Env g) :
  8666. HALT (push M cmd) (e.start (push M cmd)) ↔ HALT M ((effect M.marker cmd e).start M) := by
  8667. constructor
  8668. · rintro ⟨t,fin⟩
  8669. cases t with
  8670. | zero =>
  8671. change (push M cmd).delta (head q) (e.tape e.pos)=none at fin
  8672. simp [head_ins] at fin
  8673. | succ t =>
  8674. refine ⟨t,?_⟩
  8675. rw [after_one] at fin
  8676. simp only [instruction,liftConfig,old_ins,Option.map_eq_none_iff] at fin
  8677. exact fin
  8678. · rintro ⟨t,fin⟩
  8679. refine ⟨t+1,?_⟩
  8680. rw [after_one]
  8681. simpa only [instruction,liftConfig,old_ins,Option.map_eq_none_iff] using fin
  8682. def install (M : Ordinary g q) : List (Cmd g) → (s : Nat) × Ordinary g s
  8683. | [] => ⟨q,M⟩
  8684. | c::cs => let N := install M cs; ⟨N.1+1,push N.2 c⟩
  8685. theorem installed_marker (M : Ordinary g q) (cs) : (install M cs).2.marker=M.marker := by
  8686. induction cs with
  8687. | nil => rfl
  8688. | cons c cs ih => exact ih
  8689. theorem installed_blank (M : Ordinary g q) (cs) : (install M cs).2.blank=M.blank := by
  8690. induction cs with
  8691. | nil => rfl
  8692. | cons c cs ih => exact ih
  8693. def perform (mark : Fin g) (cs : List (Cmd g)) (e : Env g) := cs.foldl (fun z c => effect mark c z) e
  8694. theorem install_iff (M : Ordinary g q) (cs) (e : Env g) :
  8695. HALT (install M cs).2 (e.start (install M cs).2) ↔ HALT M ((perform M.marker cs e).start M) := by
  8696. induction cs generalizing e with
  8697. | nil => rfl
  8698. | cons c cs ih =>
  8699. exact (push_iff (install M cs).2 c e).trans (by rw [installed_marker]; exact ih _)
  8700. end P455EffectivePrefix
  8701. end
  8702. /- Begin Problem455EffectiveMachineChain (from finite-semigroup-identity-bases). -/
  8703. section
  8704. /- An executable finite-control composition of a tape transducer and a
  8705. decision machine. The transition at the writer's terminal configuration
  8706. changes control to the reader and leaves the entire tape unchanged. -/
  8707. namespace P455EffectiveChain
  8708. open P455EffectiveMachine P455MachineLocal P455MachineCleanup P455MachineTable
  8709. def left (r) (s : Fin q) : Fin (q+r) := ⟨s.val,by have := s.isLt; omega⟩
  8710. def right (q) (s : Fin r) : Fin (q+r) := ⟨q+s.val,by have := s.isLt; omega⟩
  8711. def insMap (f : Fin q → Fin r) (i : Ins (Fin g) (Fin q)) : Ins (Fin g) (Fin r) := ⟨f i.state,i.symbol,i.dir⟩
  8712. def rename (f : Fin q → Fin r) (c : Config g q) : Config g r := ⟨c.tape,c.pos,f c.state⟩
  8713. def seqDelta (W : Ordinary g q) (D : Ordinary g r) (s : Fin (q+r)) (a : Fin g) :
  8714. Option (Ins (Fin g) (Fin (q+r))) :=
  8715. if h : s.val<q then
  8716. match W.delta ⟨s.val,h⟩ a with
  8717. | some i => some (insMap (left r) i)
  8718. | none => some ⟨right q D.start,a,.stay⟩
  8719. else (D.delta ⟨s.val-q,by have := s.isLt; omega⟩ a).map (insMap (right q))
  8720. theorem left_delta (W : Ordinary g q) (D : Ordinary g r) (s a) :
  8721. seqDelta W D (left r s) a = match W.delta s a with
  8722. | some i => some (insMap (left r) i)
  8723. | none => some ⟨right q D.start,a,.stay⟩ := by simp [seqDelta,left,s.isLt]
  8724. theorem right_delta (W : Ordinary g q) (D : Ordinary g r) (s a) :
  8725. seqDelta W D (right q s) a=(D.delta s a).map (insMap (right q)) := by
  8726. have h : ¬ q+s.val<q := by omega
  8727. simp [seqDelta,right,h,Nat.add_sub_cancel_left]
  8728. def chain (W : Ordinary g q) (D : Ordinary g r) (mark : W.marker=D.marker) : Ordinary g (q+r) where
  8729. marker := W.marker
  8730. blank := W.blank
  8731. blank_ne := W.blank_ne
  8732. start := left r W.start
  8733. delta := seqDelta W D
  8734. keeps := by
  8735. intro s a i eq
  8736. by_cases h : s.val<q
  8737. · let j : Fin q := ⟨s.val,h⟩
  8738. have e : s=left r j := rfl
  8739. rw [e,left_delta] at eq
  8740. cases d : W.delta j a with
  8741. | none => rw [d] at eq; obtain rfl := Option.some.inj eq; rfl
  8742. | some z => rw [d] at eq; obtain rfl := Option.some.inj eq; exact W.keeps _ _ _ d
  8743. · let j : Fin r := ⟨s.val-q,by have := s.isLt; omega⟩
  8744. have e : s=right q j := Fin.ext (by dsimp [j,right]; omega)
  8745. rw [e,right_delta] at eq
  8746. cases d : D.delta j a with
  8747. | none => simp [d] at eq
  8748. | some z =>
  8749. rw [d] at eq; obtain rfl := Option.some.inj eq
  8750. exact mark ▸ D.keeps _ _ _ d
  8751. leftSafe := by
  8752. intro s i eq
  8753. by_cases h : s.val<q
  8754. · let j : Fin q := ⟨s.val,h⟩
  8755. have e : s=left r j := rfl
  8756. rw [e,left_delta] at eq
  8757. cases d : W.delta j W.marker with
  8758. | none => rw [d] at eq; obtain rfl := Option.some.inj eq; exact Direction.noConfusion
  8759. | some z => rw [d] at eq; obtain rfl := Option.some.inj eq; exact W.leftSafe _ _ d
  8760. · let j : Fin r := ⟨s.val-q,by have := s.isLt; omega⟩
  8761. have e : s=right q j := Fin.ext (by dsimp [j,right]; omega)
  8762. rw [e,right_delta,mark] at eq
  8763. cases d : D.delta j D.marker with
  8764. | none => simp [d] at eq
  8765. | some z => rw [d] at eq; obtain rfl := Option.some.inj eq; exact D.leftSafe _ _ d
  8766. def liftAlphabet (W : Ordinary g q) (D : Ordinary g r) (mark) (A : Alphabet W) : Alphabet (chain W D mark) :=
  8767. ⟨A.bit,A.away,A.ink,A.distinct⟩
  8768. def out (q) (ans : Fin r→Bool) (s : Fin (q+r)) : Bool :=
  8769. if h : s.val<q then false else ans ⟨s.val-q,by have := s.isLt; omega⟩
  8770. theorem out_right (q) (ans : Fin r→Bool) (s) : out q ans (right q s)=ans s := by
  8771. have h : ¬ q+s.val<q := by omega
  8772. simp [out,right,h,Nat.add_sub_cancel_left]
  8773. theorem left_step (W : Ordinary g q) (D : Ordinary g r) (mark) (c : Config g q)
  8774. (live : instruction W c≠none) :
  8775. once (chain W D mark) (rename (left r) c)=rename (left r) (once W c) := by
  8776. cases c with
  8777. | mk tape pos s =>
  8778. cases e : W.delta s (tape pos) with
  8779. | none => exact False.elim (live e)
  8780. | some i => simp [once,instruction,chain,rename,left_delta,e,insMap]
  8781. theorem shift_control (W : Ordinary g q) (D : Ordinary g r) (mark) (c : Config g q)
  8782. (halt : instruction W c=none) :
  8783. once (chain W D mark) (rename (left r) c)=rename (right q) ⟨c.tape,c.pos,D.start⟩ := by
  8784. change W.delta c.state (c.tape c.pos)=none at halt
  8785. simp [once,instruction,chain,rename,left_delta,halt,write_same,dest]
  8786. theorem right_step (W : Ordinary g q) (D : Ordinary g r) (mark) (c : Config g r) :
  8787. once (chain W D mark) (rename (right q) c)=rename (right q) (once D c) := by
  8788. cases c with
  8789. | mk tape pos s => cases e : D.delta s (tape pos) <;> simp [once,instruction,chain,rename,right_delta,e,insMap]
  8790. theorem follows_left (W : Ordinary g q) (D : Ordinary g r) (mark) (c : Config g q) (t)
  8791. (before : ∀ j, j<t → instruction W (follow W c j)≠none) :
  8792. follow (chain W D mark) (rename (left r) c) t=rename (left r) (follow W c t) := by
  8793. induction t with
  8794. | zero => rfl
  8795. | succ t ih =>
  8796. rw [follow,ih (fun j h => before j (by omega)),left_step _ _ _ _ (before t (by omega)),follow]
  8797. theorem follows_right (W : Ordinary g q) (D : Ordinary g r) (mark) (c : Config g r) (t) :
  8798. follow (chain W D mark) (rename (right q) c) t=rename (right q) (follow D c t) := by
  8799. induction t with
  8800. | zero => rfl
  8801. | succ t ih => simp only [follow,ih,right_step]
  8802. theorem follow_add (M : Ordinary g q) (c : Config g q) (t k) :
  8803. follow M c (t+k)=follow M (follow M c t) k := by
  8804. induction k with
  8805. | zero => rfl
  8806. | succ k ih => exact congrArg (once M) ih
  8807. theorem earliest (P : Nat→Prop) (t : Nat) (hit : P t) : ∃ j, P j ∧ ∀ i, i<j → ¬P i := by
  8808. induction t using Nat.strongRecOn with
  8809. | ind t ih =>
  8810. by_cases h : ∃ j, j<t ∧ P j
  8811. · obtain ⟨j,lt,yes⟩ := h; exact ih j lt yes
  8812. · exact ⟨t,hit,fun i lt yes => h ⟨i,lt,yes⟩⟩
  8813. def Delivers (W : Ordinary g q) (A : Alphabet W) (x : List Bool) (D : Ordinary g r)
  8814. (B : Alphabet D) (y : List Bool) : Prop :=
  8815. ∃ t, let c := follow W (inputConfig W A x) t
  8816. instruction W c=none ∧ c.pos=0 ∧ c.tape=inputTape D B y
  8817. def Answers (D : Ordinary g q) (B : Alphabet D) (ans : Fin q → Bool) (y : List Bool) (v : Bool) : Prop :=
  8818. ∃ t, let c := follow D (inputConfig D B y) t
  8819. instruction D c=none ∧ ans c.state=v
  8820. theorem answers_chain (W : Ordinary g q) (D : Ordinary g r) (mark : W.marker=D.marker)
  8821. (A : Alphabet W) (B : Alphabet D) (ans : Fin r→Bool) {x y v}
  8822. (produces : Delivers W A x D B y) (reads : Answers D B ans y v) :
  8823. Answers (chain W D mark) (liftAlphabet W D mark A) (out q ans) x v := by
  8824. obtain ⟨t,atT,pos,tape⟩ := produces
  8825. obtain ⟨k,stopped,verdict⟩ := reads
  8826. let c := inputConfig W A x
  8827. let C := chain W D mark
  8828. obtain ⟨j,atJ,before⟩ := earliest (fun i => instruction W (follow W c i)=none) t atT
  8829. have eq : follow W c j=follow W c t := unique_halt W c atJ atT
  8830. have env : (⟨(follow W c j).tape,(follow W c j).pos,D.start⟩ : Config g r)=inputConfig D B y := by
  8831. rw [eq]; change (⟨(follow W (inputConfig W A x) t).tape,(follow W (inputConfig W A x) t).pos,D.start⟩ : Config g r)=_
  8832. rw [pos,tape]; rfl
  8833. let ini := inputConfig C (liftAlphabet W D mark A) x
  8834. have ini_eq : ini=rename (left r) c := rfl
  8835. have start : follow C ini (j+1)=rename (right q) (inputConfig D B y) := by
  8836. rw [ini_eq,follow,follows_left _ _ _ _ _ before,shift_control _ _ _ _ atJ,env]
  8837. have final : follow C ini (j+1+k)=rename (right q) (follow D (inputConfig D B y) k) := by
  8838. rw [follow_add,start,follows_right]
  8839. refine ⟨j+1+k,?_⟩
  8840. change instruction C (follow C ini (j+1+k))=none ∧ out q ans (follow C ini (j+1+k)).state=v
  8841. rw [final]
  8842. constructor
  8843. · simpa only [instruction,C,chain,rename,right_delta,Option.map_eq_none_iff] using stopped
  8844. · exact (out_right ..).trans verdict
  8845. end P455EffectiveChain
  8846. end
  8847. /- Begin Problem455MarkedPath (from finite-semigroup-identity-bases). -/
  8848. section
  8849. namespace P455MarkedPath
  8850. open P455Witness P455Paths P455ContactLift P455SourceFamilies P455SourceTheorem
  8851. open P455CrossedSupport P455OriginalWalk P455Compression
  8852. noncomputable def ruleWord (r : Nat) (allow : Tag → Prop) (mark : Marking) (u : W) (x y : Nat) :=
  8853. small u (retained r allow mark u x y)
  8854. /-- A source statement independent of any arbitrary donor map or proposed
  8855. walk in the source. All ordered comparisons and all witness labels in its
  8856. query are the result of the three concrete tester proofs. -/
  8857. theorem crossed_gadget {r allow mark T} (capT : P455Quotient.Cap r T)
  8858. (u : W) (capU : P455Closure.Cap r u) (x y : Nat) (flip : ClosedFlip r allow u x y)
  8859. (uniform : UniformSlots r allow mark u x y)
  8860. (h : Nat → W) (val : Nat → P455Quotient.Q (rules r allow mark) T)
  8861. (reps : ∀ a ∈ ruleWord r allow mark u x y, P455Quotient.ofWord (rules r allow mark) T (h a) = val a)
  8862. (live : P455Quotient.eval (rules r allow mark) capT val (ruleWord r allow mark u x y) ≠
  8863. P455Quotient.zero (rules r allow mark) T)
  8864. (ts : Tiles) (c : Certificate) (valid : Holds r allow mark T (c.query r ts))
  8865. (second mate : Bool) (cross : Crosses (markedRecord c second) h x y) :
  8866. let names := retained r allow mark u x y
  8867. let v := ruleWord r allow mark u x y
  8868. let d := donor v h r
  8869. let a := startLabel c second mate
  8870. ∃ seed z l k, (seed = x ∨ seed = y) ∧ Supplies v h r seed a ∧
  8871. P455Quotient.Variant (rules r allow mark) T z ∧ z = l ++ v.flatMap h ++ k ∧
  8872. Holds r allow mark z (c.query r ts) ∧ SourceEvidence r allow ts v h seed c ∧
  8873. (Compressed r u → Holds r allow (sourceMarks d c) u ((transferred d c).query r ts)) ∧
  8874. ∀ p : List Step, p.length ≤ 6 → Walk r allow mark z a p →
  8875. Walk r allow mark u seed (relabel d p) ∧ endpoint seed (relabel d p) = d (endpoint a p) ∧
  8876. (relabel d p).length = p.length ∧ d (endpoint a p) ∈ names ∧
  8877. Supplies v h r (d (endpoint a p)) (endpoint a p) ∧ Supplies u h r (d (endpoint a p)) (endpoint a p) := by
  8878. let names := retained r allow mark u x y
  8879. let v := ruleWord r allow mark u x y
  8880. let e := expand u names
  8881. have exp : P455Retained.Expansion v e (fun a => a ∈ names) := canonical u names
  8882. have orig : v.flatMap e = u := recover u names
  8883. obtain ⟨hr,cx,cy,_⟩ := flip_counts capU flip
  8884. have pos : 0 < r := by omega
  8885. have hx : x ∈ u := List.count_pos_iff.mp (cx.symm ▸ pos)
  8886. have hy : y ∈ u := List.count_pos_iff.mp (cy.symm ▸ pos)
  8887. obtain ⟨seed,side,img⟩ := choose_seed c second mate cross
  8888. have guard := actual_guard pos capU hx hy side uniform
  8889. have ks := (guard seed (near_self _ _)).1
  8890. have count : u.count seed = r := side.elim (fun eq => eq.symm ▸ cx) (fun eq => eq.symm ▸ cy)
  8891. have start : Supplies v h r seed (startLabel c second mate) := ⟨(counts_retained u names seed ks).trans count,img⟩
  8892. have cap : P455Closure.Cap r (v.flatMap e) := orig.symm ▸ capU
  8893. have guard' : OriginalGuard r allow mark (v.flatMap e) (fun a => a ∈ names) seed 6 := orig.symm ▸ guard
  8894. obtain ⟨z,l,k,path,eq,vw,ev,cmp,walks⟩ :=
  8895. arbitrary_reps_original_gadget capT val v h reps live ts c valid second mate seed hr start exp cap guard'
  8896. rw [orig] at cmp walks
  8897. exact ⟨seed,z,l,k,side,start,path,eq,vw,ev,cmp,walks⟩
  8898. end P455MarkedPath
  8899. end
  8900. /- Begin Problem455SupportBound (from finite-semigroup-identity-bases). -/
  8901. section
  8902. namespace P455SupportBound
  8903. open P455Witness P455Paths P455ContactGeometry P455CrossedSupport Problem455.Slots
  8904. open P455FirstRewrite (names mem_names names_distinct size_le)
  8905. noncomputable def occupants (u : W) (t i : Nat) : W := by
  8906. classical
  8907. exact (names u).filter (fun a => decide (occupies u t i a))
  8908. theorem mem_occupants {u : W} {t i a : Nat} : a ∈ occupants u t i ↔ occupies u t i a := by
  8909. classical
  8910. simp only [occupants,List.mem_filter,mem_names,decide_eq_true_eq,and_iff_right_iff_imp]
  8911. rintro ⟨j,seen⟩
  8912. exact stamped_mem_label _ _ (a,j) (seen.subset (by simp))
  8913. def Capacity (r : Nat) (allow : Tag → Prop) (mark : Marking) (u : W) (x y K : Nat) :=
  8914. ∀ t, InBall r allow mark u x y t → ∀ i, slotStart i → (occupants u t i).length ≤ K
  8915. private def starts : W := [0,1,3,5,7,9,11]
  8916. private theorem in_starts (i : Nat) : i ∈ starts ↔ slotStart i := by simp [starts,slotStart]
  8917. private theorem flat_bound (u : W) (F : Nat → W) (K : Nat) (b : ∀ t ∈ u, (F t).length ≤ K) :
  8918. (u.flatMap F).length ≤ u.length*K := by
  8919. induction u with
  8920. | nil => simp
  8921. | cons a u ih =>
  8922. have v := ih (fun t ht => b t (List.mem_cons_of_mem _ ht))
  8923. have h := b a List.mem_cons_self
  8924. simp only [List.flatMap_cons,List.length_append,List.length_cons,Nat.succ_mul]
  8925. omega
  8926. /-- Includes all seven literal slots of a reached vertex. It may overcount
  8927. non-neighbors. Outside the radius-six ball there is no outgoing list. -/
  8928. noncomputable def next (r : Nat) (allow : Tag → Prop) (mark : Marking) (u : W) (x y t : Nat) : W := by
  8929. classical
  8930. exact if InBall r allow mark u x y t then starts.flatMap (occupants u t) else []
  8931. private theorem next_bound {r allow mark u x y K} (cap : Capacity r allow mark u x y K)
  8932. (t : Nat) : (next r allow mark u x y t).length ≤ 7*K := by
  8933. classical
  8934. by_cases ball : InBall r allow mark u x y t
  8935. · rw [next,if_pos ball]
  8936. exact flat_bound starts (occupants u t) K (fun i hi => cap t ball i ((in_starts i).mp hi))
  8937. · simp [next,ball]
  8938. private theorem next_slot {r allow mark u x y t i a} (ball : InBall r allow mark u x y t)
  8939. (slot : slotStart i) (o : occupies u t i a) : a ∈ next r allow mark u x y t := by
  8940. classical
  8941. rw [next,if_pos ball]
  8942. exact List.mem_flatMap.mpr ⟨i,(in_starts i).mpr slot,mem_occupants.mpr o⟩
  8943. /-- 1 + D + ... + D^j. -/
  8944. def geometric (D : Nat) : Nat → Nat | 0 => 1 | j+1 => 1+D*geometric D j
  8945. private def explore (F : Nat → W) : Nat → Nat → W
  8946. | 0, t => [t]
  8947. | j+1, t => t :: (F t).flatMap (explore F j)
  8948. private theorem seed_mem (F : Nat → W) (j t : Nat) : t ∈ explore F j t := by
  8949. cases j <;> exact List.mem_cons_self
  8950. private theorem explore_bound (F : Nat → W) (D : Nat) (bound : ∀ t, (F t).length ≤ D) (j t : Nat) :
  8951. (explore F j t).length ≤ geometric D j := by
  8952. induction j generalizing t with
  8953. | zero => simp [geometric,explore]
  8954. | succ j ih =>
  8955. have s := flat_bound (F t) (explore F j) (geometric D j) (fun a _ => ih a)
  8956. have b := Nat.mul_le_mul_right (geometric D j) (bound t)
  8957. simp only [geometric,explore,List.length_cons]; omega
  8958. private theorem walked {r allow mark u x y} (source t : Nat) (seed : source=x ∨ source=y)
  8959. (n j : Nat) (budget : n+j ≤ 6) (pre : Near r allow mark u source t n)
  8960. (p : List Step) (walk : Walk r allow mark u t p) (len : p.length ≤ j) :
  8961. endpoint t p ∈ explore (next r allow mark u x y) j t := by
  8962. induction p generalizing t n j with
  8963. | nil => exact seed_mem _ _ _
  8964. | cons e p ih =>
  8965. obtain ⟨a,c⟩ := e
  8966. cases j with
  8967. | zero => simp at len
  8968. | succ j =>
  8969. have ball : InBall r allow mark u x y t :=
  8970. seed.elim (fun eq => .inl (eq ▸ near_mono pre (by omega))) (fun eq => .inr (eq ▸ near_mono pre (by omega)))
  8971. obtain ⟨i,slot,occ⟩ := contact_slot walk.1
  8972. have into := next_slot ball slot occ
  8973. have more := near_trans pre (near_one c walk.1)
  8974. have cont := ih a (n+1) j (by omega) more walk.2 (by simp_all)
  8975. exact List.mem_cons_of_mem _ (List.mem_flatMap.mpr ⟨a,into,cont⟩)
  8976. theorem retained_bound {r allow mark u x y K} (cap : Capacity r allow mark u x y K) :
  8977. (names (retained r allow mark u x y)).length ≤
  8978. 2*(1+7*K)*geometric (7*K) 6 := by
  8979. let F := next r allow mark u x y
  8980. let D := 7*K
  8981. let ball := explore F 6 x ++ explore F 6 y
  8982. let covered := ball ++ ball.flatMap F
  8983. have all (b) (hb : InBall r allow mark u x y b) : b ∈ ball := by
  8984. have mem (s) (origin : s=x ∨ s=y) (near : Near r allow mark u s b 6) : b ∈ explore F 6 s := by
  8985. obtain ⟨p,wp,eq,len⟩ := near
  8986. exact eq ▸ walked s s origin 0 6 (by decide) (near_self s 0) p wp len
  8987. exact List.mem_append.mpr (hb.imp (mem x (.inl rfl)) (mem y (.inr rfl)))
  8988. have included (a) (ha : a ∈ names (retained r allow mark u x y)) : a ∈ covered := by
  8989. obtain ⟨_,needs⟩ := mem_retained.mp ((mem_names _ _).mp ha)
  8990. unfold covered
  8991. apply List.mem_append.mpr
  8992. rcases needs with b | ⟨t,i,reach,slot,occ⟩
  8993. · exact .inl (all a b)
  8994. · exact .inr (List.mem_flatMap.mpr ⟨t,all t reach,next_slot reach slot occ⟩)
  8995. have fb (a) : (F a).length ≤ D := next_bound cap a
  8996. have count := size_le (names_distinct _) included
  8997. have size : ball.length ≤ 2*geometric D 6 := by
  8998. have bx := explore_bound F D fb 6 x
  8999. have by' := explore_bound F D fb 6 y
  9000. dsimp only [ball]; rw [List.length_append]; omega
  9001. have more := flat_bound ball F D (fun t _ => fb t)
  9002. have gross : covered.length ≤ ball.length*(1+D) := by
  9003. dsimp only [covered]; rw [List.length_append,Nat.mul_add,Nat.mul_one]; omega
  9004. have lim := Nat.mul_le_mul_right (1+D) size
  9005. have fin := Nat.le_trans count (Nat.le_trans gross lim)
  9006. simpa only [D,Nat.mul_assoc,Nat.mul_left_comm,Nat.mul_comm] using fin
  9007. theorem retained_bound_four {r allow mark u x y} (cap : Capacity r allow mark u x y 4) :
  9008. (names (retained r allow mark u x y)).length ≤ 2*(1+28)*geometric 28 6 := retained_bound cap
  9009. /-- The owner cannot itself be a literal occupant between two consecutive
  9010. indexed copies, whether or not the containing word is capped. -/
  9011. theorem owner_absent (u : W) (t i : Nat) : ¬ occupies u t i t := by
  9012. intro occ
  9013. obtain ⟨j,hj⟩ := occ
  9014. have mem : (t,i+1) ∈ events u := hj.mem (by simp)
  9015. have b := (P455SlotOrigin.event_bounds (fun _ => 0) u t (i+1) mem).2
  9016. obtain ⟨l,mid,k,cut,index,fresh⟩ := P455SlotOrigin.slot_cut u t i (by omega)
  9017. have occ' : occupies u t i t := ⟨j,hj⟩
  9018. rw [cut,←index] at occ'
  9019. exact fresh ((P455SlotOrigin.occupies_at_cut l mid k t t fresh).mp occ')
  9020. /-- An overfull genuine protected slot supplies five distinct saturated
  9021. occupants and their literal terminal witness in a compressed source. -/
  9022. theorem overflow_of_more {r allow mark u x y t i}
  9023. (uniform : UniformSlots r allow mark u x y) (cmp : P455SourceFamilies.Compressed r u)
  9024. (ball : InBall r allow mark u x y t) (slot : slotStart i)
  9025. (over : 4 < (occupants u t i).length) :
  9026. ∃ xs, Holds r allow mark u (terminalSlot r t i (.overflow xs)) := by
  9027. classical
  9028. let xs := (occupants u t i).take 5
  9029. have inside (a) (ha : a ∈ xs) : occupies u t i a :=
  9030. mem_occupants.mp ((List.take_sublist _ _).subset ha)
  9031. have nodup : xs.Nodup :=
  9032. (names_distinct u).sublist (List.Sublist.trans (List.take_sublist _ _) List.filter_sublist)
  9033. have uniq : (t::xs).Nodup := List.nodup_cons.mpr ⟨fun h => owner_absent u t i (inside t h),nodup⟩
  9034. refine ⟨xs,List.length_take_of_le (by omega),
  9035. (P455TerminalTransfer.block_separation _).mpr
  9036. (uniq.imp (fun ne => P455SourceFamilies.compressed_separates cmp ne)),?_,True.intro⟩
  9037. apply (allQ_iff _).mpr
  9038. intro q mem
  9039. obtain ⟨a,ha,rfl⟩ := List.mem_map.mp mem
  9040. have occ := inside a ha
  9041. exact ⟨uniform t ball i slot a occ,slot,occ⟩
  9042. theorem capacity_of_no_overflow {r allow mark u x y}
  9043. (uniform : UniformSlots r allow mark u x y) (cmp : P455SourceFamilies.Compressed r u)
  9044. (none : ∀ t, InBall r allow mark u x y t → ∀ i, slotStart i →
  9045. ∀ xs, ¬ Holds r allow mark u (terminalSlot r t i (.overflow xs))) :
  9046. Capacity r allow mark u x y 4 := by
  9047. intro t ball i slot
  9048. exact Nat.le_of_not_lt (fun h => by
  9049. obtain ⟨xs,w⟩ := overflow_of_more uniform cmp ball slot h
  9050. exact none t ball i slot xs w)
  9051. /-- Uniform one-step rank under the actual source geometric guard and validity
  9052. of the canonical smaller identity. Bound depends only on the fixed r. -/
  9053. theorem bounded_step_of_capacity {A : Type} (M : P455FirstRewrite.Model A)
  9054. {r allow mark} (f : P455Closure.Frame Nat) (l k : W) {x y : Nat}
  9055. (hp : f.p = [x]) (hq : f.q = [y]) (valid : f.Valid r allow (fun _ _ => False))
  9056. (b : Bool) (cap : P455Closure.Cap r (P455Uncrossed.side f l k b))
  9057. (capacity : Capacity r allow mark (P455Uncrossed.side f l k b) x y 4)
  9058. (semantic :
  9059. let keep := retained r allow mark (P455Uncrossed.side f l k b) x y
  9060. M.Valid (P455Compression.small (P455Uncrossed.side f l k b) keep)
  9061. (P455Compression.small (P455Uncrossed.side f l k (!b)) keep)) :
  9062. let N := 2*(1+28)*geometric 28 6
  9063. P455FirstRewrite.Step (fun u v => M.Valid u v ∧ P455FirstRewrite.rank u v ≤ N+r*N+1)
  9064. (P455Uncrossed.side f l k b) (P455Uncrossed.side f l k (!b)) := by
  9065. let u := P455Uncrossed.side f l k b
  9066. let keep := retained r allow mark u x y
  9067. have flip : ClosedFlip r allow u x y := ⟨f,b,l,k,hp,hq,valid,rfl⟩
  9068. obtain ⟨hr,cx,cy,_⟩ := flip_counts cap flip
  9069. have hx : x ∈ keep := mem_retained.mpr
  9070. ⟨List.count_pos_iff.mp (cx.symm ▸ (by omega : 0 < r)),.inl (.inl (near_self x 6))⟩
  9071. have hy : y ∈ keep := mem_retained.mpr
  9072. ⟨List.count_pos_iff.mp (cy.symm ▸ (by omega : 0 < r)),.inl (.inr (near_self y 6))⟩
  9073. have step := P455SmallRank.bounded_step M f l k keep hx hy hp hq valid b cap semantic
  9074. have small : (names keep).length ≤ 2*(1+28)*geometric 28 6 := retained_bound_four capacity
  9075. have scaled := Nat.mul_le_mul_left r small
  9076. obtain ⟨U,V,L,R,h,hyp,nu,nv,ne,src,dst⟩ := step
  9077. refine ⟨U,V,L,R,h,?_,nu,nv,ne,src,dst⟩
  9078. rcases hyp with ⟨val,rnk⟩|⟨val,rnk⟩
  9079. · exact .inl ⟨val,by omega⟩
  9080. · exact .inr ⟨val,by omega⟩
  9081. end P455SupportBound
  9082. end
  9083. /- Begin Problem455StructuralProduct (from finite-semigroup-identity-bases). -/
  9084. section
  9085. namespace P455StructuralProduct
  9086. open P455Structural P455Witness P455Quotient P455Closure P455Uncrossed
  9087. open P455SourceFamilies P455FirstTesters P455FirstRewrite
  9088. def templates (r : Nat) := Problem455Finite.wordsUpTo (List.range 4) (4*r)
  9089. structure Index (r : Nat) (allow : Tag → Prop) where
  9090. pos : Fin (templates r).length
  9091. cap : P455Closure.Cap r ((templates r).get pos)
  9092. cmp : Compressed r ((templates r).get pos)
  9093. test : Structural ((templates r).get pos) r allow
  9094. def Index.T (i : Index r allow) := (templates r).get i.pos
  9095. abbrev Carrier (r : Nat) (allow : Tag → Prop) := (i : Index r allow) → Q (plain r) i.T
  9096. def product (r : Nat) (allow : Tag → Prop) : Model (Carrier r allow) where
  9097. op := fun x y i => mul (plain r) i.cap (x i) (y i)
  9098. unit := fun i => ofWord (plain r) i.T []
  9099. assoc := fun x y z => funext (fun i => mul_assoc (plain r) i.cap (x i) (y i) (z i))
  9100. oneL := fun x => funext (fun i => (unit_laws (plain r) i.cap (x i)).1)
  9101. oneR := fun x => funext (fun i => (unit_laws (plain r) i.cap (x i)).2)
  9102. theorem coordinate (f : Nat → Carrier r allow) (w : List Nat) (i : Index r allow) :
  9103. (product r allow).eval f w i = eval (plain r) i.cap (fun x => f x i) w := by
  9104. induction w with
  9105. | nil => rfl
  9106. | cons x xs ih => exact congrArg (mul (plain r) i.cap (f x i)) ih
  9107. theorem identity {r allow} (f : Frame Nat) (l k : List Nat) (x y : Nat)
  9108. (hp : f.p=[x]) (hq : f.q=[y]) (valid : f.Valid r allow (fun _ _ => False)) :
  9109. (product r allow).Valid (side f l k false) (side f l k true) := by
  9110. intro val
  9111. funext i
  9112. rw [coordinate,coordinate]
  9113. exact structural_eval i.cap i.cmp i.test f l k x y hp hq valid _
  9114. /-- The actual shared canonical words of the positional gap construction
  9115. satisfy the structural subproduct identity for every retained-name list
  9116. containing the marked roles. -/
  9117. theorem small_identity {r allow} (f : Frame Nat) (l k names : List Nat) (x y : Nat)
  9118. (hx : x ∈ names) (hy : y ∈ names) (hp : f.p=[x]) (hq : f.q=[y])
  9119. (valid : f.Valid r allow (fun _ _ => False)) (bit : Bool)
  9120. (cap : P455Closure.Cap r (side f l k bit)) :
  9121. (product r allow).Valid (P455Compression.small (side f l k false) names)
  9122. (P455Compression.small (side f l k true) names) := by
  9123. obtain ⟨g,L,K,gp,gq,gv,eq,_⟩ :=
  9124. P455CompressedFrame.canonical_pair f l k names hx hy hp hq valid bit cap
  9125. rw [eq,eq]
  9126. exact identity g L K x y gp gq gv
  9127. end P455StructuralProduct
  9128. end
  9129. /- Begin Problem455PaddedMatchings (from finite-semigroup-identity-bases). -/
  9130. section
  9131. namespace P455PaddedMatchings
  9132. open P455PaddedPorts P455PaddedTiles
  9133. def idAt (w y x : Nat) := w*y + (if odd y then w-1-x else x)
  9134. private theorem offset_lt {w x : Nat} (y : Nat) (hx : x<w) :
  9135. (if odd y then w-1-x else x)<w := by split <;> omega
  9136. theorem id_inj {w y x z q : Nat} (hx : x<w) (hq : q<w) (eq : idAt w y x=idAt w z q) :
  9137. y=z ∧ x=q := by
  9138. have wt : 0<w := by omega
  9139. have div := congrArg (· / w) eq
  9140. simp only [idAt,Nat.mul_add_div wt,Nat.div_eq_of_lt (offset_lt y hx),
  9141. Nat.div_eq_of_lt (offset_lt z hq),Nat.add_zero] at div
  9142. subst z
  9143. simp only [idAt,Nat.add_left_cancel_iff] at eq
  9144. split at eq <;> omega
  9145. theorem id_bound {w h y x : Nat} (hy : y<h) (hx : x<w) : idAt w y x < w*h := by
  9146. have le := Nat.mul_le_mul_left w (show y+1≤h by omega)
  9147. rw [Nat.mul_add,Nat.mul_one] at le
  9148. have off := offset_lt y hx
  9149. unfold idAt; omega
  9150. theorem id_covers {w h i : Nat} (lt : i<w*h) :
  9151. ∃ y<h, ∃ x<w, idAt w y x=i := by
  9152. have wpos : 0<w := by
  9153. cases w with
  9154. | zero => simp at lt
  9155. | succ => omega
  9156. let y := i/w
  9157. let j := i%w
  9158. have jo : j<w := Nat.mod_lt _ wpos
  9159. have ex := Nat.mod_add_div i w
  9160. have yl : y<h := by
  9161. by_cases e : y<h
  9162. · exact e
  9163. · have mul := Nat.mul_le_mul_left w (show h≤y by omega)
  9164. change w*h≤w*(i/w) at mul
  9165. omega
  9166. refine ⟨y,yl,if odd y then w-1-j else j,offset_lt y jo,?_⟩
  9167. unfold idAt
  9168. by_cases e : odd y=true
  9169. · simp [e]
  9170. have z : w-1-(w-1-j)=j := by omega
  9171. rw [z]
  9172. dsimp [y,j]; omega
  9173. · simp [e]
  9174. dsimp [y,j]; omega
  9175. def pairs (f : Nat → Nat) (start : Nat) : Nat → List Block
  9176. | 0 => []
  9177. | 1 => [.single (f start)]
  9178. | n+2 => .pair (f start) (f (start+1)) :: pairs f (start+2) n
  9179. def line (skip : Bool) (f : Nat → Nat) (size : Nat) :=
  9180. if skip then match size with
  9181. | 0 => []
  9182. | k+1 => .single (f 0) :: pairs f 1 k
  9183. else pairs f 0 size
  9184. private theorem pair_cells (f : Nat→Nat) (s n : Nat) :
  9185. (pairs f s n).flatMap cells = (List.range' s n).map f := by
  9186. induction n using Nat.strongRecOn generalizing s with
  9187. | ind n ih =>
  9188. cases n with
  9189. | zero => rfl
  9190. | succ n => cases n with
  9191. | zero => rfl
  9192. | succ n =>
  9193. simp [pairs,cells,ih n (by omega) (s+2),List.range'_succ]
  9194. theorem line_cells (skip : Bool) (f : Nat→Nat) (n : Nat) :
  9195. (line skip f n).flatMap cells=(List.range n).map f := by
  9196. cases skip
  9197. · simp [line,pair_cells,List.range_eq_range']
  9198. · cases n with
  9199. | zero => rfl
  9200. | succ n => simp [line,cells,pair_cells,List.range_eq_range',List.range'_succ]
  9201. private theorem pair_edge (f : Nat → Nat) (s n a b : Nat) :
  9202. Block.pair a b ∈ pairs f s n ↔
  9203. ∃ k, k+1<n ∧ k%2=0 ∧ a=f (s+k) ∧ b=f (s+k+1) := by
  9204. induction n using Nat.strongRecOn generalizing s with
  9205. | ind n ih =>
  9206. cases n with
  9207. | zero => simp [pairs]
  9208. | succ n => cases n with
  9209. | zero => simp [pairs]
  9210. | succ n =>
  9211. simp only [pairs,List.mem_cons,Block.pair.injEq]
  9212. rw [ih n (by omega)]
  9213. constructor
  9214. · rintro (⟨ea,eb⟩|⟨k,lt,par,ea,eb⟩)
  9215. · exact ⟨0,by omega,rfl,by simpa using ea,by simpa using eb⟩
  9216. · exact ⟨k+2,by omega,by omega,by simpa [Nat.add_assoc,Nat.add_comm,Nat.add_left_comm] using ea,
  9217. by simpa [Nat.add_assoc,Nat.add_comm,Nat.add_left_comm] using eb⟩
  9218. · rintro ⟨k,lt,par,ea,eb⟩
  9219. by_cases e : k=0
  9220. · subst k; exact .inl ⟨by simpa using ea,by simpa using eb⟩
  9221. · have kk : s+2+(k-2)=s+k := by omega
  9222. exact .inr ⟨k-2,by omega,by omega,by simpa only [kk] using ea,by simpa only [kk] using eb⟩
  9223. theorem line_edge (skip : Bool) (f : Nat→Nat) (size a b : Nat) :
  9224. Block.pair a b ∈ line skip f size ↔
  9225. ∃ k, k+1<size ∧ odd k=skip ∧ a=f k ∧ b=f (k+1) := by
  9226. cases skip
  9227. · simp only [line,Bool.false_eq_true,if_false,pair_edge,Nat.zero_add]
  9228. constructor
  9229. · rintro ⟨k,lt,p,u,v⟩; exact ⟨k,lt,by simp [odd,p],u,v⟩
  9230. · rintro ⟨k,lt,p,u,v⟩; exact ⟨k,lt,by simp [odd] at p; omega,u,v⟩
  9231. · cases size with
  9232. | zero => simp [line]
  9233. | succ n =>
  9234. simp only [line,if_true,List.mem_cons,Block.noConfusion,reduceCtorEq,false_or,pair_edge]
  9235. constructor
  9236. · rintro ⟨k,lt,p,u,v⟩
  9237. refine ⟨k+1,by omega,?_,?_,?_⟩
  9238. · simp [odd,show (k+1)%2=1 by omega]
  9239. · simpa [Nat.add_comm] using u
  9240. · simpa [Nat.add_assoc,Nat.add_comm,Nat.add_left_comm] using v
  9241. · rintro ⟨k,lt,p,u,v⟩; simp [odd] at p
  9242. exact ⟨k-1,by omega,by omega,by simpa [show 1+(k-1)=k by omega] using u,
  9243. by simpa [show 1+(k-1)=k by omega] using v⟩
  9244. def lines (m n : Nat) (skip : Bool) (f : Nat→Nat→Nat) :=
  9245. (List.range m).flatMap fun z=>line skip (f z) n
  9246. private theorem flatten_lines (m n : Nat) (skip : Bool) (f : Nat→Nat→Nat) :
  9247. (lines m n skip f).flatMap cells=(List.range m).flatMap (fun z=>(List.range n).map (f z)) := by
  9248. simp [lines,List.flatMap_assoc,line_cells]
  9249. theorem lines_unique (m n : Nat) (skip : Bool) (f : Nat→Nat→Nat)
  9250. (inj : ∀ z<m, ∀ x<n, ∀ t<m, ∀ j<n, f z x=f t j → z=t ∧ x=j) :
  9251. ((lines m n skip f).flatMap cells).Nodup := by
  9252. rw [flatten_lines]
  9253. apply List.pairwise_flatMap.mpr
  9254. constructor
  9255. · intro z hz
  9256. apply List.pairwise_map.mpr
  9257. exact List.nodup_range.imp_of_mem (fun hx hj ne eq => ne
  9258. (inj z (List.mem_range.mp hz) _ (List.mem_range.mp hx) z (List.mem_range.mp hz) _ (List.mem_range.mp hj) eq).2)
  9259. · apply List.nodup_range.imp_of_mem
  9260. intro z t hz ht ne a ha b hb eq
  9261. obtain ⟨x,hx,rfl⟩ := List.mem_map.mp ha
  9262. obtain ⟨j,hj,rfl⟩ := List.mem_map.mp hb
  9263. exact ne (inj z (List.mem_range.mp hz) x (List.mem_range.mp hx) t (List.mem_range.mp ht) j (List.mem_range.mp hj) eq).1
  9264. def horizontal (h w : Nat) (skip : Bool) := lines h w skip (idAt w)
  9265. def vertical (h w : Nat) (skip : Bool) := lines w h skip (fun x y=>idAt w y x)
  9266. theorem horizontal_unique (h w : Nat) (skip : Bool) :
  9267. ((horizontal h w skip).flatMap cells).Nodup :=
  9268. lines_unique _ _ _ _ (fun _ _ _ hx _ _ _ hj eq=>id_inj hx hj eq)
  9269. theorem vertical_unique (h w : Nat) (skip : Bool) :
  9270. ((vertical h w skip).flatMap cells).Nodup :=
  9271. lines_unique _ _ _ _ (fun _ hx _ _ _ hj _ _ eq=>And.symm (id_inj hx hj eq))
  9272. theorem horizontal_cells (h w i : Nat) (skip : Bool) :
  9273. i∈(horizontal h w skip).flatMap cells ↔ i<w*h := by
  9274. rw [horizontal,flatten_lines]
  9275. constructor
  9276. · intro m; obtain ⟨y,hy,mx⟩ := List.mem_flatMap.mp m
  9277. obtain ⟨x,hx,rfl⟩ := List.mem_map.mp mx
  9278. exact id_bound (List.mem_range.mp hy) (List.mem_range.mp hx)
  9279. · intro lt; obtain ⟨y,hy,x,hx,eq⟩ := id_covers lt
  9280. exact List.mem_flatMap.mpr ⟨y,List.mem_range.mpr hy,List.mem_map.mpr ⟨x,List.mem_range.mpr hx,eq⟩⟩
  9281. theorem vertical_cells (h w i : Nat) (skip : Bool) :
  9282. i∈(vertical h w skip).flatMap cells ↔ i<w*h := by
  9283. rw [vertical,flatten_lines]
  9284. constructor
  9285. · intro m; obtain ⟨x,hx,my⟩ := List.mem_flatMap.mp m
  9286. obtain ⟨y,hy,rfl⟩ := List.mem_map.mp my
  9287. exact id_bound (List.mem_range.mp hy) (List.mem_range.mp hx)
  9288. · intro lt; obtain ⟨y,hy,x,hx,eq⟩ := id_covers lt
  9289. exact List.mem_flatMap.mpr ⟨x,List.mem_range.mpr hx,List.mem_map.mpr ⟨y,List.mem_range.mpr hy,eq⟩⟩
  9290. theorem horizontal_edge (h w a b : Nat) (skip : Bool) :
  9291. Block.pair a b∈horizontal h w skip ↔
  9292. ∃ y<h, ∃ x, x+1<w ∧ odd x=skip ∧ a=idAt w y x ∧ b=idAt w y (x+1) := by
  9293. simp [horizontal,lines,List.mem_flatMap,line_edge]
  9294. theorem vertical_edge (h w a b : Nat) (skip : Bool) :
  9295. Block.pair a b∈vertical h w skip ↔
  9296. ∃ x<w, ∃ y, y+1<h ∧ odd y=skip ∧ a=idAt w y x ∧ b=idAt w (y+1) x := by
  9297. simp [vertical,lines,List.mem_flatMap,line_edge]
  9298. def wrap (t : Nat) : List Block :=
  9299. .pair (t-1) 0 :: ((List.range t).filter fun i=>0<i && i<t-1).map Block.single
  9300. theorem wrap_edge (t a b : Nat) : Block.pair a b ∈ wrap t ↔ a=t-1 ∧ b=0 := by
  9301. simp [wrap,List.mem_map]
  9302. private theorem flatten_singles (xs : List Nat) : (xs.map Block.single).flatMap cells=xs := by
  9303. induction xs with
  9304. | nil => rfl
  9305. | cons a xs ih => simp [cells,ih]
  9306. theorem wrap_unique {t : Nat} (ht : 1<t) : ((wrap t).flatMap cells).Nodup := by
  9307. simp only [wrap,List.flatMap_cons,cells,flatten_singles,List.cons_append,List.nil_append]
  9308. simp [List.nodup_cons,show t-1≠0 by omega]
  9309. exact List.Pairwise.filter _ List.nodup_range
  9310. theorem wrap_cells {t : Nat} (ht : 1<t) (i : Nat) : i∈(wrap t).flatMap cells ↔ i<t := by
  9311. simp only [wrap,List.flatMap_cons,cells,flatten_singles,List.cons_append,List.nil_append,List.mem_cons,List.mem_filter,
  9312. List.mem_range,Bool.and_eq_true,decide_eq_true_eq]
  9313. omega
  9314. end P455PaddedMatchings
  9315. end
  9316. /- Begin Problem455PaddedIndexed (from finite-semigroup-identity-bases). -/
  9317. section
  9318. namespace P455PaddedPorts
  9319. open P455RectangleRank Problem455.Slots
  9320. theorem count_one {ks : W} (nd : ks.Nodup) {a : Nat} (m : a∈ks) : ks.count a=1 := by
  9321. induction ks with
  9322. | nil => simp at m
  9323. | cons x ks ih =>
  9324. obtain ⟨out,tail⟩ := List.nodup_cons.mp nd
  9325. by_cases e : a=x
  9326. · subst x; simp [List.count_cons,List.count_eq_zero.mpr out]
  9327. · have z : a∈ks := by simpa [e] using m
  9328. simp [List.count_cons,e,Ne.symm e,ih tail z]
  9329. theorem count_phase (bs : List Block) (c : Nat) :
  9330. (phase bs).count c = 2*(bs.flatMap cells).count c := by
  9331. induction bs with
  9332. | nil => rfl
  9333. | cons b bs ih =>
  9334. change ((cells b ++ cells b) ++ phase bs).count c=2*((cells b) ++ bs.flatMap cells).count c
  9335. simp only [List.count_append,ih]; omega
  9336. theorem count_role (s : W) (c a : Nat) (target : a=owner c ∨ a=mate c) :
  9337. (s.flatMap roles).count a=s.count c := by
  9338. induction s with
  9339. | nil => rfl
  9340. | cons k s ih =>
  9341. simp only [List.flatMap_cons,List.count_append,ih]
  9342. by_cases eq : k=c
  9343. · subst k
  9344. rcases target with rfl|rfl <;> simp [roles,List.count_cons,owner,mate] <;> omega
  9345. · have non : a∉roles k := by
  9346. unfold roles
  9347. simp only [List.mem_cons,List.not_mem_nil,or_false]
  9348. unfold owner mate at target ⊢; omega
  9349. simp [List.count_eq_zero.mpr non,List.count_cons,eq,Ne.symm eq]
  9350. /-- Context can contribute arbitrarily many other events, including earlier
  9351. or later copies of the four observed roles. Only the counts at the actual
  9352. phase boundary are relevant. -/
  9353. theorem indexed_window {ks pre mid post : W} {k : Nat} (nd : ks.Nodup)
  9354. (before : ∀ a∈ks, pre.count a=k) (inside : ∀ a∈ks, mid.count a=2) :
  9355. sees (pre++mid++post) (stamp (fun _=>k) (ks++ks)) ↔ select ks mid=ks++ks := by
  9356. let active (e : Event) := decide (e.1∈ks ∧ k≤e.2 ∧ e.2<k+2)
  9357. let zero : Nat → Nat := fun _=>0
  9358. let p : Nat → Nat := fun a=>pre.count a
  9359. let q : Nat → Nat := fun a=>pre.count a+mid.count a
  9360. have whole : events (pre++mid++post)=stamp zero pre ++ (stamp p mid ++ stamp q post) := by
  9361. simp only [List.append_assoc,events,stamp_append]
  9362. have e : advance (fun _=>0) pre=p := by funext a; simp [advance,p]
  9363. have f : advance p mid=q := by rfl
  9364. rw [e,f]
  9365. have none₁ : (stamp zero pre).filter active=[] := by
  9366. apply List.filter_eq_nil_iff.mpr
  9367. rintro ⟨a,i⟩ mem yes
  9368. obtain ⟨m,lo,_⟩ := of_decide_eq_true yes
  9369. have lim := (P455ContactGeometry.stamp_range zero pre mem).2
  9370. change i<0+pre.count a at lim
  9371. have := before a m; omega
  9372. have none₂ : (stamp q post).filter active=[] := by
  9373. apply List.filter_eq_nil_iff.mpr
  9374. rintro ⟨a,i⟩ mem yes
  9375. obtain ⟨m,_,hi⟩ := of_decide_eq_true yes
  9376. have lim := (P455ContactGeometry.stamp_range q post mem).1
  9377. change pre.count a+mid.count a≤i at lim
  9378. have := before a m; have := inside a m; omega
  9379. have middle : (stamp p mid).filter active=stamp (fun _=>k) (select ks mid) := by
  9380. rw [P455ContactGeometry.project_stamp ks mid (fun _=>k) p (fun a m => (before a m).symm)]
  9381. apply List.filter_congr
  9382. rintro ⟨a,i⟩ mem
  9383. by_cases m : a∈ks
  9384. · have lim := P455ContactGeometry.stamp_range p mid mem
  9385. change pre.count a≤i ∧ i<pre.count a+mid.count a at lim
  9386. have := before a m; have := inside a m
  9387. simp [active,m,show k≤i by omega,show i<k+2 by omega]
  9388. · simp [active,m]
  9389. have observed : (events (pre++mid++post)).filter active=stamp (fun _=>k) (select ks mid) := by
  9390. simp only [whole,List.filter_append,none₁,none₂,middle,List.append_nil,List.nil_append]
  9391. have full : (stamp (fun _=>k) (ks++ks)).filter active = stamp (fun _=>k) (ks++ks) := by
  9392. apply List.filter_eq_self.mpr
  9393. rintro ⟨x,i⟩ m
  9394. have mem := stamped_mem_label (fun _=>k) (ks++ks) _ m
  9395. have mx : x∈ks := by simpa using mem
  9396. have lim := P455ContactGeometry.stamp_range (fun _=>k) (ks++ks) m
  9397. simp only [List.count_append,count_one nd mx] at lim
  9398. exact decide_eq_true ⟨mx,lim.1,by omega⟩
  9399. constructor
  9400. · intro seq
  9401. have sub := seq.filter active
  9402. change ((stamp (fun _=>k) (ks++ks)).filter active).Sublist ((events (pre++mid++post)).filter active) at sub
  9403. rw [full,observed] at sub
  9404. have words := sub.map Prod.fst
  9405. simp only [labels_of_stamp] at words
  9406. have perm : (select ks mid).Perm (ks++ks) := by
  9407. apply List.perm_iff_count.mpr
  9408. intro a
  9409. by_cases m : a∈ks
  9410. · unfold select
  9411. rw [List.count_filter (p:=fun e => decide (e ∈ ks)) (decide_eq_true m),List.count_append,inside a m,count_one nd m]
  9412. · have no : a∉select ks mid := by simp [select,m]
  9413. simp [List.count_eq_zero.mpr no,List.count_eq_zero.mpr m]
  9414. exact (words.eq_of_length perm.length_eq.symm).symm
  9415. · intro eq
  9416. rw [←eq,←observed]
  9417. exact List.filter_sublist ..
  9418. def portPattern (i j k : Nat) : List Event :=
  9419. [(owner i,k),(mate i,k),(owner j,k),(mate j,k),
  9420. (owner i,k+1),(mate i,k+1),(owner j,k+1),(mate j,k+1)]
  9421. theorem indexed_port_exact {bs : List Block} {pre post : W} {i j k : Nat} (ne : i≠j)
  9422. (nd : (bs.flatMap cells).Nodup) (mi : i∈bs.flatMap cells) (mj : j∈bs.flatMap cells)
  9423. (prefixCount : ∀ a∈roles i ++ roles j, pre.count a=k) :
  9424. sees (pre++letters bs++post) (portPattern i j k) ↔ Block.pair i j∈bs := by
  9425. let ks := roles i ++ roles j
  9426. have dis : owner i≠mate i ∧ owner j≠mate j ∧ owner i≠owner j ∧ owner i≠mate j ∧
  9427. mate i≠owner j ∧ mate i≠mate j := by unfold owner mate; omega
  9428. have nod : ks.Nodup := by simp [ks,roles,dis.1,dis.2.1,dis.2.2.1,dis.2.2.2.1,dis.2.2.2.2.1,dis.2.2.2.2.2]
  9429. have window (a) (used : a∈ks) : (letters bs).count a=2 := by
  9430. have ea : (a=owner i ∨ a=mate i) ∨ (a=owner j ∨ a=mate j) := by
  9431. simpa only [ks,roles,List.mem_append,List.mem_cons,List.not_mem_nil,or_false] using used
  9432. rcases ea with ai|aj
  9433. · rw [letters,count_role _ i a ai,count_phase,count_one nd mi]
  9434. · rw [letters,count_role _ j a aj,count_phase,count_one nd mj]
  9435. have ev : stamp (fun _=>k) (ks++ks)=portPattern i j k := by
  9436. rw [stamp_append,stamp_at (fun _=>k) k ks nod (fun _ _ => rfl),
  9437. stamp_at (advance (fun _=>k) ks) (k+1) ks nod (fun a m=>by simp [advance,count_one nod m])]
  9438. rfl
  9439. rw [← ev,indexed_window nod prefixCount window]
  9440. exact literal_phase_exact nd i j ne
  9441. /-- The original tester query, without any hypothesis that it holds. The
  9442. static typed-record and early-disjoint requirements are displayed separately
  9443. from the geometric matching criterion. -/
  9444. theorem oriented_port_iff {r : Nat} (hr : 16≤r) (allow : P455Witness.Tag → Prop)
  9445. (mark : P455Witness.Marking) (port : Fin 5) (tagI tagJ : P455Witness.Tag)
  9446. {bs : List Block} {pre post : W} {i j : Nat} (ne : i≠j)
  9447. (nd : (bs.flatMap cells).Nodup) (mi : i∈bs.flatMap cells) (mj : j∈bs.flatMap cells)
  9448. (prefixCount : ∀ a∈roles i ++ roles j, pre.count a=3+2*port.val) :
  9449. let a : P455Witness.Node := ⟨owner i,mate i,tagI⟩
  9450. let b : P455Witness.Node := ⟨owner j,mate j,tagJ⟩
  9451. let H := P455Witness.Holds r allow mark (pre++letters bs++post)
  9452. H (P455Witness.orientedPort port.val a b) ↔ H (P455Witness.typedNode a) ∧
  9453. H (P455Witness.typedNode b) ∧ H (P455Witness.earlyDisjoint (roles i) (roles j)) ∧
  9454. Block.pair i j∈bs := by
  9455. dsimp only
  9456. have obs := indexed_port_exact (post:=post) ne nd mi mj prefixCount
  9457. constructor
  9458. · rintro ⟨ta,tb,ear,ord,_⟩
  9459. exact ⟨ta,tb,ear,obs.mp ord.2⟩
  9460. · rintro ⟨ta,tb,ear,matchEdge⟩
  9461. refine ⟨ta,tb,ear,⟨?_,obs.mpr matchEdge⟩,True.intro⟩
  9462. intro e m
  9463. have lt := port.isLt
  9464. simp only [List.mem_cons,List.not_mem_nil,or_false] at m
  9465. rcases m with h|h|h|h|h|h|h|h <;> rw [h] <;> dsimp <;> omega
  9466. end P455PaddedPorts
  9467. end
  9468. /- Begin Problem455WriterFrontier (from finite-semigroup-identity-bases). -/
  9469. section
  9470. /- A simulated blank and a never-scanned blank have different physical codes.
  9471. Thus the used interval can be erased even if it contains arbitrary blank gaps. -/
  9472. namespace P455WriterFrontier
  9473. open P455MachineLocal P455MachineTable P455MachineCleanup P455EffectiveMachine
  9474. def ink (a : Fin g) : Fin (g+1) := ⟨a.val, by have := a.isLt; omega⟩
  9475. def fresh (g : Nat) : Fin (g+1) := ⟨g, by omega⟩
  9476. theorem ink_inj {a b : Fin g} : ink a=ink b ↔ a=b := ⟨fun h => Fin.ext (congrArg (fun z : Fin (g+1) => z.val) h),congrArg ink⟩
  9477. theorem ink_ne_fresh (a : Fin g) : ink a ≠ fresh g := by
  9478. intro h; have v := congrArg Fin.val h; change a.val=g at v; exact (Nat.ne_of_lt a.isLt) v
  9479. def eraseTag (blank : Fin g) (a : Fin (g+1)) : Fin g :=
  9480. if h : a.val<g then ⟨a.val,h⟩ else blank
  9481. @[simp] theorem erase_ink (blank a : Fin g) : eraseTag blank (ink a)=a := by simp [eraseTag,ink,a.isLt]
  9482. @[simp] theorem erase_fresh (blank : Fin g) : eraseTag blank (fresh g)=blank := by simp [eraseTag,fresh]
  9483. theorem erase_marker (M : Ordinary g q) (a : Fin (g+1)) :
  9484. eraseTag M.blank a=M.marker ↔ a=ink M.marker := by
  9485. by_cases h : a.val<g
  9486. · simp only [eraseTag,h,↓reduceDIte]
  9487. constructor
  9488. · intro e; exact Fin.ext (congrArg (fun z : Fin g => z.val) e)
  9489. · intro e; exact Fin.ext (congrArg (fun z : Fin (g+1) => z.val) e)
  9490. · have ne : a≠ink M.marker := by
  9491. intro eq; subst a; exact h M.marker.isLt
  9492. simp [eraseTag,h,M.blank_ne,ne]
  9493. def tagIns (i : Ins (Fin g) (Fin q)) : Ins (Fin (g+1)) (Fin q) :=
  9494. ⟨i.state,ink i.symbol,i.dir⟩
  9495. def monitor (M : Ordinary g q) : Ordinary (g+1) q where
  9496. marker := ink M.marker
  9497. blank := fresh g
  9498. blank_ne := Ne.symm (ink_ne_fresh _)
  9499. start := M.start
  9500. delta z a := (M.delta z (eraseTag M.blank a)).map tagIns
  9501. keeps := by
  9502. intro z a i e
  9503. cases h : M.delta z (eraseTag M.blank a) with
  9504. | none => simp [h] at e
  9505. | some j =>
  9506. rw [h] at e
  9507. change some (tagIns j)=some i at e
  9508. have e := Option.some.inj e
  9509. subst i; exact ink_inj.trans ((M.keeps _ _ _ h).trans (erase_marker M a))
  9510. leftSafe := by
  9511. intro z i e
  9512. simp only [erase_ink] at e
  9513. cases h : M.delta z M.marker with
  9514. | none => simp [h] at e
  9515. | some j =>
  9516. rw [h] at e
  9517. change some (tagIns j)=some i at e
  9518. have e := Option.some.inj e
  9519. subst i; exact M.leftSafe _ _ h
  9520. def alphabet (M : Ordinary g q) (A : Alphabet M) : Alphabet (monitor M) where
  9521. bit b := ink (A.bit b)
  9522. away b h := A.away b (ink_inj.mp h)
  9523. ink b := ink_ne_fresh (A.bit b)
  9524. distinct h := A.distinct (ink_inj.mp h)
  9525. def tape (n : Nat) (f : Nat → Fin g) (j : Nat) := if j≤n then ink (f j) else fresh g
  9526. def liftCfg (n : Nat) (c : Config g q) : Config (g+1) q := ⟨tape n c.tape,c.pos,c.state⟩
  9527. def Good (M : Ordinary g q) (c : Config g q) (n : Nat) : Prop :=
  9528. c.pos≤n+1 ∧ (∀ j, n<j → c.tape j=M.blank) ∧ (∀ j, c.tape j=M.marker ↔ j=0)
  9529. theorem input_good (M : Ordinary g q) (A : Alphabet M) (x : List Bool) :
  9530. Good M (inputConfig M A x) x.length := by
  9531. refine ⟨Nat.zero_le _,?_,?_⟩
  9532. · intro j h; cases j with
  9533. | zero => omega
  9534. | succ i => simp [inputConfig,inputTape,List.getElem?_eq_none (show x.length≤i by omega)]
  9535. · intro j; cases j with
  9536. | zero => simp [inputConfig,inputTape]
  9537. | succ i =>
  9538. change (x[i]?).elim M.blank A.bit=M.marker ↔ i+1=0
  9539. cases x[i]? with
  9540. | none => simp [M.blank_ne]
  9541. | some b => simp [A.away]
  9542. theorem input_eq (M : Ordinary g q) (A : Alphabet M) (x : List Bool) :
  9543. inputConfig (monitor M) (alphabet M A) x=liftCfg x.length (inputConfig M A x) := by
  9544. suffices h : inputTape (monitor M) (alphabet M A) x=tape x.length (inputTape M A x) by
  9545. change (⟨_,0,M.start⟩ : Config (g+1) q)=⟨_,0,M.start⟩
  9546. rw [h]
  9547. rfl
  9548. funext j
  9549. cases j with
  9550. | zero => simp [inputTape,tape,monitor]
  9551. | succ i =>
  9552. by_cases h : i<x.length
  9553. · simp [inputTape,tape,show i+1≤x.length by omega,List.getElem?_eq_getElem h,alphabet]
  9554. · simp [inputTape,tape,show ¬ i+1≤x.length by omega,List.getElem?_eq_none (show x.length≤i by omega),monitor]
  9555. theorem ins_eq (M : Ordinary g q) {c : Config g q} {n} (h : Good M c n) :
  9556. instruction (monitor M) (liftCfg n c)=(instruction M c).map tagIns := by
  9557. change (M.delta c.state (eraseTag M.blank (tape n c.tape c.pos))).map _=_
  9558. by_cases p : c.pos≤n
  9559. · simp [tape,p,instruction]
  9560. · simp [tape,p,instruction,h.2.1 c.pos (by omega)]
  9561. theorem good_step (M : Ordinary g q) {c : Config g q} {n} (h : Good M c n) {i}
  9562. (e : instruction M c=some i) :
  9563. Good M (once M c) (max n c.pos) := by
  9564. have pos := h.1
  9565. have p : c.pos ≤ max n c.pos := Nat.le_max_right _ _
  9566. simp only [once,e,Good]
  9567. refine ⟨?_,?_,?_⟩
  9568. · cases i.dir <;> simp [dest] <;> omega
  9569. · intro j lt
  9570. have ne : j≠c.pos := by omega
  9571. simp [writeAt,ne,h.2.1 j (by omega)]
  9572. · intro j
  9573. by_cases eq : j=c.pos
  9574. · subst j; simpa [writeAt] using (M.keeps _ _ _ e).trans (h.2.2 c.pos)
  9575. · simp [writeAt,eq,h.2.2]
  9576. theorem step_eq (M : Ordinary g q) {c : Config g q} {n} (h : Good M c n) {i}
  9577. (e : instruction M c=some i) :
  9578. once (monitor M) (liftCfg n c)=liftCfg (max n c.pos) (once M c) := by
  9579. have k : writeAt (tape n c.tape) c.pos (ink i.symbol)=
  9580. tape (max n c.pos) (writeAt c.tape c.pos i.symbol) := by
  9581. funext j
  9582. by_cases eq : j=c.pos
  9583. · subst j; simp [tape,writeAt,Nat.le_max_right]
  9584. · have pos := h.1
  9585. have iff : j≤max n c.pos ↔ j≤n := by omega
  9586. simp [writeAt,tape,eq,iff]
  9587. have s := ins_eq M h
  9588. rw [e] at s
  9589. change instruction (monitor M) (liftCfg n c)=some (tagIns i) at s
  9590. rw [once,s]
  9591. simp only [once,e,liftCfg,tagIns,k]
  9592. theorem simulates (M : Ordinary g q) (A : Alphabet M) (x : List Bool) (t : Nat) :
  9593. ∃ n, Good M (follow M (inputConfig M A x) t) n ∧
  9594. follow (monitor M) (inputConfig (monitor M) (alphabet M A) x) t=
  9595. liftCfg n (follow M (inputConfig M A x) t) := by
  9596. induction t with
  9597. | zero => exact ⟨_,input_good M A x,input_eq M A x⟩
  9598. | succ t ih =>
  9599. obtain ⟨n,ok,sim⟩ := ih
  9600. let c := follow M (inputConfig M A x) t
  9601. change ∃ k, Good M (once M c) k ∧ once (monitor M) _=liftCfg k (once M c)
  9602. rw [sim]
  9603. cases e : instruction M c with
  9604. | none =>
  9605. have stop := ins_eq M ok
  9606. change instruction (monitor M) (liftCfg n c)=(instruction M c).map tagIns at stop
  9607. rw [e] at stop
  9608. exact ⟨n,by simpa [once,e] using ok,by simp [once,e,stop,c] at *⟩
  9609. | some i => exact ⟨_,good_step M ok e,step_eq M ok e⟩
  9610. end P455WriterFrontier
  9611. end
  9612. /- Begin Problem455EffectiveMachineRelabel (from finite-semigroup-identity-bases). -/
  9613. section
  9614. namespace P455EffectiveRelabel
  9615. open P455MachineLocal P455MachineCleanup P455MachineTable P455EffectiveMachine
  9616. open P455EffectiveChain
  9617. structure Emb (g h : Nat) where
  9618. enc : Fin g → Fin h
  9619. back : Fin h → Fin g
  9620. undo : ∀ a, back (enc a)=a
  9621. theorem Emb.inj (e : Emb g h) (a b) : e.enc a=e.enc b ↔ a=b := by
  9622. constructor
  9623. · intro eq; simpa only [e.undo] using congrArg e.back eq
  9624. · intro eq; rw [eq]
  9625. def mapped (e : Emb g h) (i : Ins (Fin g) (Fin q)) : Ins (Fin h) (Fin q) :=
  9626. ⟨i.state,e.enc i.symbol,i.dir⟩
  9627. def expand (M : Ordinary g q) (e : Emb g h) : Ordinary h q where
  9628. marker := e.enc M.marker
  9629. blank := e.enc M.blank
  9630. blank_ne := fun equ => M.blank_ne ((e.inj ..).mp equ)
  9631. start := M.start
  9632. delta s x := if x=e.enc (e.back x) then (M.delta s (e.back x)).map (mapped e) else none
  9633. keeps := by
  9634. intro s x i yes
  9635. split at yes
  9636. next right =>
  9637. cases st : M.delta s (e.back x) with
  9638. | none => simp [st] at yes
  9639. | some z =>
  9640. rw [st] at yes; obtain rfl := Option.some.inj yes
  9641. change e.enc z.symbol=e.enc M.marker ↔ x=e.enc M.marker
  9642. exact (e.inj ..).trans ((M.keeps _ _ _ st).trans
  9643. ⟨fun eq => right.trans (congrArg e.enc eq), fun eq =>
  9644. (e.inj ..).mp (right.symm.trans eq)⟩)
  9645. next => contradiction
  9646. leftSafe := by
  9647. intro s i yes
  9648. simp only [e.undo,if_true] at yes
  9649. cases st : M.delta s M.marker with
  9650. | none => simp [st] at yes
  9651. | some z =>
  9652. rw [st] at yes; obtain rfl := Option.some.inj yes
  9653. exact M.leftSafe _ _ st
  9654. def alpha (M : Ordinary g q) (A : Alphabet M) (e : Emb g h) : Alphabet (expand M e) where
  9655. bit b := e.enc (A.bit b)
  9656. away b eq := A.away b ((e.inj ..).mp eq)
  9657. ink b eq := A.ink b ((e.inj ..).mp eq)
  9658. distinct eq := A.distinct ((e.inj ..).mp eq)
  9659. def conf (e : Emb g h) (c : Config g q) : Config h q := ⟨fun j => e.enc (c.tape j),c.pos,c.state⟩
  9660. theorem input_tape (M : Ordinary g q) (A : Alphabet M) (e : Emb g h) (w : List Bool) (j) :
  9661. inputTape (expand M e) (alpha M A e) w j = e.enc (inputTape M A w j) := by
  9662. cases j with
  9663. | zero => rfl
  9664. | succ j => cases eq : w[j]? <;> simp [inputTape,eq,expand,alpha]
  9665. theorem exp_instruction (M : Ordinary g q) (e : Emb g h) (c : Config g q) :
  9666. instruction (expand M e) (conf e c)=(instruction M c).map (mapped e) := by
  9667. simp [instruction,expand,conf,e.undo]
  9668. theorem exp_once (M : Ordinary g q) (e : Emb g h) (c : Config g q) :
  9669. once (expand M e) (conf e c)=conf e (once M c) := by
  9670. unfold once; rw [exp_instruction]
  9671. cases st : instruction M c with
  9672. | none => rfl
  9673. | some z =>
  9674. have tape : writeAt (conf e c).tape c.pos (e.enc z.symbol)=fun j=>e.enc (writeAt c.tape c.pos z.symbol j) := by
  9675. funext j; by_cases eq : j=c.pos <;> simp [conf,writeAt,eq]
  9676. exact congrArg (fun f => Config.mk f (dest z.dir c.pos) z.state) tape
  9677. theorem exp_run (M : Ordinary g q) (A : Alphabet M) (e : Emb g h) (w t) :
  9678. follow (expand M e) (inputConfig (expand M e) (alpha M A e) w) t=
  9679. conf e (follow M (inputConfig M A w) t) := by
  9680. induction t with
  9681. | zero =>
  9682. exact congrArg (fun f => Config.mk f 0 M.start) (funext (input_tape M A e w))
  9683. | succ t ih => simp only [follow,ih,exp_once]
  9684. theorem exp_answers (M : Ordinary g q) (A : Alphabet M) (e : Emb g h) {ans w b}
  9685. (out : Answers M A ans w b) : Answers (expand M e) (alpha M A e) ans w b := by
  9686. obtain ⟨t,stop,ok⟩ := out
  9687. refine ⟨t,?_⟩
  9688. simp only [exp_run]
  9689. constructor
  9690. · rw [exp_instruction,stop]; rfl
  9691. · exact ok
  9692. /-- The distinguished four symbols occupy exactly 0 (marker), 1 (blank),
  9693. 2 (false) and 3 (true). Other symbols retain their index at the chosen
  9694. offset. This allows two unrelated scratch alphabets to coexist. -/
  9695. def number (M : Ordinary g q) (A : Alphabet M) (base : Nat) (a : Fin g) :=
  9696. if a=M.marker then 0 else if a=M.blank then 1 else if a=A.bit false then 2 else if a=A.bit true then 3 else base+a.val
  9697. def denumber (M : Ordinary g q) (A : Alphabet M) (base y : Nat) :=
  9698. if y=0 then M.marker else if y=1 then M.blank else if y=2 then A.bit false else if y=3 then A.bit true
  9699. else if h : y-base<g then (⟨y-base,h⟩ : Fin g) else M.blank
  9700. theorem number_lt (M : Ordinary g q) (A : Alphabet M) (lo : 4≤base) (hi : base+g ≤ h) (a : Fin g) :
  9701. number M A base a < h := by
  9702. have small := a.isLt
  9703. unfold number
  9704. split <;> (first | omega | split <;> (first | omega | split <;> (first | omega | split <;> omega)))
  9705. theorem denumber_number (M : Ordinary g q) (A : Alphabet M) (lo : 4≤base) (a : Fin g) :
  9706. denumber M A base (number M A base a)=a := by
  9707. unfold number
  9708. split
  9709. next eq => simp [denumber,eq]
  9710. next =>
  9711. split
  9712. next eq => simp [denumber,eq]
  9713. next =>
  9714. split
  9715. next eq => simp [denumber,eq]
  9716. next =>
  9717. split
  9718. next eq => simp [denumber,eq]
  9719. next =>
  9720. have zero : base+a.val≠0 := by omega
  9721. have one : base+a.val≠1 := by omega
  9722. have two : base+a.val≠2 := by omega
  9723. have three : base+a.val≠3 := by omega
  9724. simp [denumber,zero,one,two,three,Nat.add_sub_cancel_left,a.isLt] <;> omega
  9725. def common (M : Ordinary g q) (A : Alphabet M) (lo : 4≤base) (hi : base+g≤h) : Emb g h :=
  9726. ⟨fun a => ⟨number M A base a,number_lt M A lo hi a⟩,fun a => denumber M A base a.val,denumber_number M A lo⟩
  9727. @[simp] theorem mark_number (M : Ordinary g q) (A : Alphabet M) (base) : number M A base M.marker=0 := by
  9728. simp [number]
  9729. @[simp] theorem blank_number (M : Ordinary g q) (A : Alphabet M) (base) : number M A base M.blank=1 := by
  9730. simp [number,M.blank_ne]
  9731. @[simp] theorem bit_number (M : Ordinary g q) (A : Alphabet M) (base) (b : Bool) :
  9732. number M A base (A.bit b)=if b then 3 else 2 := by
  9733. cases b <;> simp [number,A.away,A.ink,Ne.symm A.distinct]
  9734. end P455EffectiveRelabel
  9735. end
  9736. /- Begin Problem455SlotProduct (from finite-semigroup-identity-bases). -/
  9737. section
  9738. namespace P455SlotProduct
  9739. open P455Witness P455Paths P455SourceFamilies P455CrossedSupport Problem455.Slots
  9740. def alphabet := List.range 9
  9741. def templates (r : Nat) := Problem455Finite.wordsUpTo alphabet (9*r)
  9742. def pairMark (a b : Nat) : Marking := fun x y => x = a ∧ y = b
  9743. structure Index (r : Nat) (allow : Tag → Prop) where
  9744. num : Fin (templates r).length
  9745. a : Fin 9
  9746. b : Fin 9
  9747. cap : P455Closure.Cap r ((templates r).get num)
  9748. test : ∃ (s : SlotCertificate) (d : Nat), s.defect = .deficient d ∧
  9749. s.anchor.owner = a.val ∧ s.anchor.mate = b.val ∧
  9750. Holds r allow (pairMark a.val b.val) ((templates r).get num) (s.query r)
  9751. def Index.T (i : Index r allow) := (templates r).get i.num
  9752. def Index.R (i : Index r allow) := rules r allow (pairMark i.a i.b)
  9753. abbrev Carrier (r : Nat) (allow : Tag → Prop) := (i : Index r allow) → P455Quotient.Q i.R i.T
  9754. def evalP (v : Nat → Carrier r allow) (w : W) : Carrier r allow :=
  9755. fun i => P455Quotient.eval i.R i.cap (fun x => v x i) w
  9756. def Identity (r : Nat) (allow : Tag → Prop) (u w : W) :=
  9757. ∀ v : Nat → Carrier r allow, evalP v u = evalP v w
  9758. theorem index_injective {i j : Index r allow} (n : i.num = j.num) (a : i.a = j.a)
  9759. (b : i.b = j.b) : i = j := by cases i; cases j; cases n; cases a; cases b; rfl
  9760. theorem coordinate_finite (i : Index r allow) (q : P455Quotient.Q i.R i.T) :
  9761. q ∈ Problem455Finite.carrier i.R i.T := Problem455Finite.carrier_complete ..
  9762. private theorem remove_count (w : W) (a : Nat) :
  9763. (w.filter (· != a)).length + w.count a = w.length := by
  9764. induction w with
  9765. | nil => rfl
  9766. | cons b t ih =>
  9767. by_cases eq : a = b
  9768. · subst b; simp [List.count_cons] at ih ⊢; omega
  9769. · simp [List.count_cons,eq,Ne.symm eq,beq_iff_eq] at ih ⊢; omega
  9770. theorem capped_length {r : Nat} (k : Nat) (w : W) (cap : P455Closure.Cap r w)
  9771. (names : ∀ x ∈ w, x < k) : w.length ≤ k*r := by
  9772. induction k generalizing w with
  9773. | zero => cases w with
  9774. | nil => simp
  9775. | cons x xs => exact False.elim (Nat.not_lt_zero _ (names x (by simp)))
  9776. | succ k ih =>
  9777. have cp : P455Closure.Cap r (w.filter (· != k)) :=
  9778. fun x => Nat.le_trans (List.Sublist.count_le x List.filter_sublist) (cap x)
  9779. have low := ih _ cp (fun x hx => by
  9780. obtain ⟨mem,p⟩ := List.mem_filter.mp hx
  9781. have h := names x mem
  9782. have e : x ≠ k := by simpa [bne_iff_ne] using p
  9783. omega)
  9784. have ct := cap k
  9785. have tot := remove_count w k
  9786. rw [Nat.succ_mul]; omega
  9787. def image (keep : W) (a : Nat) : W := if a ∈ keep then [keep.idxOf a] else []
  9788. theorem image_word (keep w : W) :
  9789. w.flatMap (image keep) = (select keep w).map keep.idxOf := by
  9790. induction w with
  9791. | nil => rfl
  9792. | cons a t ih => by_cases h : a ∈ keep <;> simp [image,select,h,ih, List.flatMap_cons] at *
  9793. /-- A true identity at the finite product specializes simultaneously at
  9794. the coordinatewise erasing-and-renaming valuation, even if other
  9795. coordinates send some of its one-letter words to zero. -/
  9796. theorem marked_test {r allow u w} (valid : Identity r allow u w) (keep : W)
  9797. (i : Index r allow) (eq : (select keep u).map keep.idxOf = i.T) :
  9798. select [i.a.val,i.b.val] ((select keep u).map keep.idxOf) =
  9799. select [i.a.val,i.b.val] ((select keep w).map keep.idxOf) := by
  9800. let v : Nat → Carrier r allow := fun x j => P455Quotient.ofWord j.R j.T (image keep x)
  9801. have comp := congrFun (valid v) i
  9802. change P455Quotient.eval i.R i.cap _ u = P455Quotient.eval i.R i.cap _ w at comp
  9803. rw [P455Quotient.eval_rep i.R i.cap (fun x => v x i) u (image keep) (fun _ _ => rfl),
  9804. P455Quotient.eval_rep i.R i.cap (fun x => v x i) w (image keep) (fun _ _ => rfl),image_word,image_word,eq] at comp
  9805. have good : P455Quotient.Good i.R i.T i.T := ⟨i.T,.refl _,[],[],by simp⟩
  9806. have path := ((P455Quotient.same_nonzero_class i.R good).mp comp).2
  9807. rw [eq]
  9808. apply P455Quotient.Walk.transport (P := fun z => select [i.a.val,i.b.val] i.T = select [i.a.val,i.b.val] z) path rfl
  9809. intro z z' mv old
  9810. exact old.trans (mv.marked_proj _ _ ⟨rfl,rfl⟩)
  9811. private theorem tag_map (x y : Nat) (t : Tag) :
  9812. (t.flatMap P455Closure.phasePair).map (fun b => if b then y else x) = t.flatMap (pair x y) := by
  9813. induction t with
  9814. | nil => rfl
  9815. | cons b t ih => cases b <;> simp [List.flatMap_cons,P455Closure.phasePair,pair,ih]
  9816. theorem profile_eq (x y : Nat) (t : Tag) (b : Bool) :
  9817. P455Closure.Frame.profileWord x y t b = profile x y t b := by
  9818. cases b <;> simp [P455Closure.Frame.profileWord,P455Closure.Frame.profileBits,
  9819. P455Closure.fixedPhases,P455Closure.phasePair,profile,profilePrefix,pair,
  9820. List.replicate_succ,tag_map,List.append_assoc]
  9821. theorem flip_anchor {r allow u x y} (cap : P455Closure.Cap r u)
  9822. (flip : ClosedFlip r allow u x y) : ∃ tag bit,
  9823. Holds r allow (markNode ⟨x,y,tag⟩) u (markedNode ⟨x,y,tag⟩ bit) := by
  9824. obtain ⟨_,_,_,ne⟩ := flip_counts cap flip
  9825. obtain ⟨f,b,l,k,hp,hq,ok,rfl⟩ := flip
  9826. refine ⟨f.tag,b,ne,by change f.tag.length + 16 = r; have h := ok.1; omega,ok.2.1,.inl ⟨rfl,rfl⟩,?_⟩
  9827. have h := f.cross_projection ok b l k cap x y (by simp [hp]) (by simp [hq])
  9828. simpa [select,profile_eq] using h
  9829. end P455SlotProduct
  9830. end
  9831. /- Begin Problem455PaddedSnake (from finite-semigroup-identity-bases). -/
  9832. section
  9833. namespace P455PaddedMatchings
  9834. open P455PaddedTiles
  9835. def rowEnd (w y x : Nat) : Prop := if odd y then x=0 else x+1=w
  9836. def Next (w y x v z : Nat) : Prop :=
  9837. (odd y=false ∧ v=y ∧ z=x+1) ∨
  9838. (odd y=true ∧ v=y ∧ z+1=x) ∨
  9839. (v=y+1 ∧ z=x ∧ rowEnd w y x)
  9840. theorem odd_succ (y : Nat) : odd (y+1)= !odd y := by
  9841. by_cases e : y%2=1
  9842. · simp [odd,e,show (y+1)%2≠1 by omega]
  9843. · simp [odd,e,show (y+1)%2=1 by omega]
  9844. theorem first_id (w : Nat) : idAt w 0 0=0 := by simp [idAt,odd]
  9845. theorem end_id {w y x : Nat} (hx : x<w) (endRow : rowEnd w y x) :
  9846. idAt w y x+1=w*(y+1) := by
  9847. cases par : odd y <;> simp [rowEnd,par] at endRow <;> simp [idAt,par,Nat.mul_add] <;> omega
  9848. theorem down_id {w y x : Nat} (hx : x<w) (endRow : rowEnd w y x) :
  9849. idAt w (y+1) x=idAt w y x+1 := by
  9850. rw [end_id hx endRow]
  9851. cases par : odd y <;> simp [rowEnd,par] at endRow <;> simp [idAt,odd_succ,par] <;> omega
  9852. theorem stepping {w h i : Nat} (bound : i+1<w*h) :
  9853. ∃ y<h, ∃ x<w, ∃ v<h, ∃ z<w, idAt w y x=i ∧ idAt w v z=i+1 ∧ Next w y x v z := by
  9854. obtain ⟨y,hy,x,hx,eq⟩ := id_covers (show i<w*h by omega)
  9855. refine ⟨y,hy,x,hx,?_⟩
  9856. by_cases b : rowEnd w y x
  9857. · have jy : y+1<h := by
  9858. by_cases strict : y+1<h
  9859. · exact strict
  9860. · have e : y+1=h := by omega
  9861. have endPos := end_id hx b
  9862. rw [e,eq] at endPos; omega
  9863. exact ⟨y+1,jy,x,hx,eq,(down_id hx b).trans (congrArg (·+1) eq),.inr (.inr ⟨rfl,rfl,b⟩)⟩
  9864. · cases par : odd y with
  9865. | false =>
  9866. simp [rowEnd,par] at b
  9867. refine ⟨y,hy,x+1,by omega,eq,?_,.inl ⟨par,rfl,rfl⟩⟩
  9868. simp [idAt,par] at eq ⊢; omega
  9869. | true =>
  9870. simp [rowEnd,par] at b
  9871. refine ⟨y,hy,x-1,by omega,eq,?_,.inr (.inl ⟨par,rfl,by omega⟩)⟩
  9872. simp [idAt,par] at eq ⊢; omega
  9873. theorem last_cell {w h : Nat} (pos : 0<w*h) :
  9874. ∃ y<h, ∃ x<w, y+1=h ∧ rowEnd w y x ∧ idAt w y x=w*h-1 := by
  9875. have wy : 0<w := by cases w with | zero => simp at pos | succ => omega
  9876. have hy : 0<h := by cases h with | zero => simp at pos | succ => omega
  9877. let y := h-1
  9878. let x := if odd y then 0 else w-1
  9879. have hx : x<w := by dsimp [x]; split <;> omega
  9880. have b : rowEnd w y x := by cases p : odd y <;> simp [rowEnd,x,p] <;> omega
  9881. have e : y+1=h := by dsimp [y]; omega
  9882. have z := end_id hx b
  9883. rw [e] at z
  9884. exact ⟨y,by dsimp [y]; omega,x,hx,e,b,by omega⟩
  9885. def decodeRow (w i : Nat) := i/w
  9886. def decodeCol (w i : Nat) := if odd (decodeRow w i) then w-1-(i%w) else i%w
  9887. theorem decode_id {w y x : Nat} (hx : x<w) :
  9888. decodeRow w (idAt w y x)=y ∧ decodeCol w (idAt w y x)=x := by
  9889. have wt : 0<w := by omega
  9890. have off : (if odd y then w-1-x else x)<w := by split <;> omega
  9891. have yr : decodeRow w (idAt w y x)=y := by
  9892. simp [decodeRow,idAt,Nat.mul_add_div wt,Nat.div_eq_of_lt off]
  9893. refine ⟨yr,?_⟩
  9894. unfold decodeCol
  9895. rw [yr]
  9896. simp only [idAt,Nat.mul_add_mod,Nat.mod_eq_of_lt off]
  9897. cases p : odd y <;> simp <;> omega
  9898. def tagAt (w : Nat) (tile : Nat→Nat→List Bool) (i : Nat) :=
  9899. tile (decodeRow w i) (decodeCol w i)
  9900. theorem tag_id (tile : Nat→Nat→List Bool) {w y x : Nat} (hx : x<w) :
  9901. tagAt w tile (idAt w y x)=tile y x := by simp [tagAt,(decode_id hx).1,(decode_id hx).2]
  9902. end P455PaddedMatchings
  9903. end
  9904. /- Begin Problem455PaddedSlots (from finite-semigroup-identity-bases). -/
  9905. section
  9906. namespace P455PaddedPorts
  9907. open P455RectangleRank Problem455.Slots
  9908. def Covered (w : W) (a k : Nat) := ∃ small : W, small.length≤4 ∧
  9909. ∀ z, occupies w a k z → z∈small
  9910. private theorem trim {α : Type} (a : α) (t l m : List α) (h : a∉l)
  9911. (sub : (a::t).Sublist (l++m)) : (a::t).Sublist m := by
  9912. induction l with
  9913. | nil => exact sub
  9914. | cons z l ih =>
  9915. cases sub with
  9916. | cons _ s => exact ih (fun mem=>h (List.mem_cons_of_mem _ mem)) s
  9917. | cons_cons _ _ => exact (h List.mem_cons_self).elim
  9918. /-- If the two bounding indexed occurrences are in one literal factor,
  9919. the occupant occurs in that factor, even if other copies occur elsewhere. -/
  9920. theorem occupant_in_factor (l m t : W) (a k z : Nat) (start : l.count a≤k)
  9921. (finish : k+1<l.count a+m.count a) (occ : occupies (l++m++t) a k z) : z∈m := by
  9922. obtain ⟨j,sub⟩ := occ
  9923. unfold sees at sub
  9924. rw [events_of_factor] at sub
  9925. have nl : (a,k)∉events l := by
  9926. intro e; have := (P455ContactGeometry.stamp_range (fun _=>0) l e).2
  9927. omega
  9928. have nt : (a,k+1) ∉ stamp (fun x=>l.count x+m.count x) t := by
  9929. intro e; have := (P455ContactGeometry.stamp_range (fun x=>l.count x+m.count x) t e).1
  9930. omega
  9931. have rest := trim _ _ _ _ nl sub
  9932. have back := rest.reverse
  9933. simp only [List.reverse_append,List.reverse_cons,List.reverse_nil,List.nil_append,
  9934. List.cons_append,List.singleton_append] at back
  9935. have small := (trim _ _ _ _ (by simpa using nt : (a,k+1) ∉ (stamp (fun x=>l.count x+m.count x) t).reverse) back).reverse
  9936. have mid : [(a,k),(z,j),(a,k+1)].Sublist ((events m).map (shift (fun x=>l.count x))) := by simpa using small
  9937. obtain ⟨e,em,ev⟩ := List.mem_map.mp (mid.subset (by simp : (z,j)∈[(a,k),(z,j),(a,k+1)]))
  9938. have lab := congrArg Prod.fst ev
  9939. change e.1=z at lab
  9940. rw [←lab]; exact stamped_mem_label (fun _=>0) m e em
  9941. theorem private_slot_bound (l t : W) (c a k : Nat) (role : a∈roles c) (lo : l.count a=0)
  9942. (early : k=0 ∨ k=1) : Covered (l++privateCell c++t) a k := by
  9943. refine ⟨roles c,by simp [roles],?_⟩
  9944. intro z occ
  9945. have ne : owner c≠mate c := by simp [owner,mate]
  9946. have count : (privateCell c).count a=3 := by
  9947. rcases (show a=owner c ∨ a=mate c by simpa [roles] using role) with rfl|rfl <;>
  9948. simp [privateCell,List.count_cons,ne,Ne.symm ne]
  9949. have mem := occupant_in_factor l (privateCell c) t a k z (by omega) (by omega) occ
  9950. simpa [privateCell,roles,or_assoc,or_left_comm,or_comm] using mem
  9951. private theorem letters_split (l t : List Block) :
  9952. letters (l++t)=letters l++letters t := by simp [letters,phase,List.flatMap_append]
  9953. private theorem block_letters (b : Block) (t : List Block) :
  9954. letters (b::t)=(cells b).flatMap roles ++ (cells b).flatMap roles ++ letters t := by
  9955. simp [letters,phase,List.flatMap_cons,List.flatMap_append,List.append_assoc]
  9956. private theorem role_from (x a c : Nat) (m : a∈roles c) (same : a∈roles x) : c=x := by
  9957. simp only [roles,List.mem_cons,List.not_mem_nil,or_false] at m same
  9958. unfold owner mate at m same; omega
  9959. private theorem index_mem (bs : List Block) (a c : Nat) (role : a∈roles c)
  9960. (m : a∈letters bs) : c∈bs.flatMap cells := by
  9961. obtain ⟨x,hx,mx⟩ := List.mem_flatMap.mp m
  9962. have eq := role_from _ _ _ role mx
  9963. rw [eq]
  9964. obtain ⟨b,hb,inBlock⟩ := List.mem_flatMap.mp hx
  9965. exact List.mem_flatMap.mpr ⟨b,hb,by simpa using inBlock⟩
  9966. theorem matching_slot_bound {bs : List Block} (nd : (bs.flatMap cells).Nodup)
  9967. {l t : W} (c a k : Nat) (role : a∈roles c) (present : c∈bs.flatMap cells)
  9968. (index : l.count a=k) : Covered (l++letters bs++t) a k := by
  9969. obtain ⟨b,inBs,inBlock⟩ := List.mem_flatMap.mp present
  9970. obtain ⟨pre,post,e⟩ := List.append_of_mem inBs
  9971. subst bs
  9972. simp only [List.flatMap_append,List.flatMap_cons] at nd
  9973. have ds := (List.pairwise_append.mp nd).2.2
  9974. have noPre : a∉letters pre := by
  9975. intro hm
  9976. exact ds c (index_mem pre a c role hm) c (List.mem_append_left _ inBlock) rfl
  9977. let names := (cells b).flatMap roles
  9978. have has : a∈names := List.mem_flatMap.mpr ⟨c,inBlock,role⟩
  9979. have size : names.length≤4 := by cases b <;> simp [names,cells,roles]
  9980. have positive := List.count_pos_iff.mpr has
  9981. have cut : l++letters (pre++b::post)++t=(l++letters pre)++(names++names)++(letters post++t) := by
  9982. rw [letters_split,block_letters]; simp [names,List.append_assoc]
  9983. have left : (l++letters pre).count a=k := by simp [List.count_eq_zero.mpr noPre,index]
  9984. refine ⟨names,size,?_⟩
  9985. intro z occ
  9986. rw [cut] at occ
  9987. have hit := occupant_in_factor (l++letters pre) (names++names) (letters post++t) a k z
  9988. (by omega) (by simp only [List.count_append] at left ⊢; omega) occ
  9989. simpa using hit
  9990. end P455PaddedPorts
  9991. end
  9992. /- Begin Problem455WriterSweep (from finite-semigroup-identity-bases). -/
  9993. section
  9994. namespace P455WriterSweep
  9995. open P455MachineLocal P455MachineTable P455MachineCleanup P455EffectiveMachine
  9996. open P455EffectiveChain P455WriterFrontier
  9997. def reach (M : Ordinary g q) (c d : Config g q) := ∃ t, follow M c t=d
  9998. theorem trans {M : Ordinary g q} {a b c} (h : reach M a b) (k : reach M b c) : reach M a c := by
  9999. obtain ⟨u,rfl⟩ := h; obtain ⟨v,hv⟩ := k
  10000. exact ⟨u+v,by rw [follow_add,hv]⟩
  10001. theorem single {M : Ordinary g q} {c d} (h : once M c=d) : reach M c d := ⟨1,h⟩
  10002. def cleanSym (M : Ordinary g q) (O : Alphabet M) (read : Fin g → Option Bool)
  10003. (a : Fin (g+1)) : Fin (g+1) :=
  10004. if a=ink M.marker then ink M.marker else
  10005. if a=fresh g then fresh g else
  10006. (read (eraseTag M.blank a)).elim (fresh g) (fun b => ink (O.bit b))
  10007. theorem clean_mark (M : Ordinary g q) (O : Alphabet M) (read) (a) :
  10008. cleanSym M O read a=ink M.marker ↔ a=ink M.marker := by
  10009. have freshNe := Ne.symm (ink_ne_fresh M.marker)
  10010. by_cases h : a=ink M.marker
  10011. · simp [cleanSym,h]
  10012. · simp only [cleanSym,h,↓reduceIte,iff_false]
  10013. split
  10014. · exact freshNe
  10015. · cases read (eraseTag M.blank a) with
  10016. | none => exact freshNe
  10017. | some b => exact fun e => O.away b (ink_inj.mp e)
  10018. def control (M : Ordinary g q) (O : Alphabet M) (read : Fin g→Option Bool)
  10019. (s : Fin 3) (a : Fin (g+1)) : Option (Ins (Fin (g+1)) (Fin 3)) :=
  10020. if s=0 then
  10021. if a=ink M.marker then some ⟨1,a,.right⟩ else some ⟨0,a,.left⟩
  10022. else if s=1 then
  10023. if a=fresh g then some ⟨2,a,.left⟩ else some ⟨1,cleanSym M O read a,.right⟩
  10024. else if a=ink M.marker then none else some ⟨2,a,.left⟩
  10025. def sweep (M : Ordinary g q) (O : Alphabet M) (read : Fin g→Option Bool) : Ordinary (g+1) 3 where
  10026. marker := ink M.marker
  10027. blank := fresh g
  10028. blank_ne := Ne.symm (ink_ne_fresh _)
  10029. start := 0
  10030. delta := control M O read
  10031. keeps := by
  10032. intro s a i e
  10033. unfold control at e
  10034. split at e <;> split at e
  10035. · cases e; rfl
  10036. · cases e; rfl
  10037. · split at e
  10038. · cases e; rfl
  10039. · cases e; exact clean_mark ..
  10040. · split at e
  10041. · contradiction
  10042. · cases e; rfl
  10043. leftSafe := by
  10044. intro s i e
  10045. simp only [control,if_pos rfl,ink_ne_fresh,↓reduceIte] at e
  10046. split at e
  10047. · cases e; exact Direction.noConfusion
  10048. · split at e
  10049. · cases e; exact Direction.noConfusion
  10050. · contradiction
  10051. def mix (src dst : Nat→Fin k) (p i : Nat) := if i<p then dst i else src i
  10052. theorem mix_next (src dst : Nat→Fin k) (p) :
  10053. writeAt (mix src dst p) p (dst p)=mix src dst (p+1) := by
  10054. funext i; by_cases e : i=p
  10055. · subst i; simp [writeAt,mix]
  10056. · have same : i<p+1 ↔ i<p := by omega
  10057. simp [writeAt,mix,e,same]
  10058. theorem rewind (M : Ordinary g q) (O : Alphabet M) (read) (src : Nat → Fin (g+1))
  10059. (proper : ∀ j, src j=ink M.marker ↔ j=0) (s : Fin 3) (mode : s=0 ∨ s=2) (p) :
  10060. reach (sweep M O read) ⟨src,p,s⟩ ⟨src,0,s⟩ := by
  10061. induction p with
  10062. | zero => exact ⟨0,rfl⟩
  10063. | succ p ih =>
  10064. apply trans _ ih
  10065. apply single
  10066. have ne : src (p+1)≠ink M.marker := fun e => Nat.succ_ne_zero p ((proper _).mp e)
  10067. rcases mode with rfl|rfl <;> simp [once,instruction,sweep,control,ne,write_same,dest]
  10068. theorem sweep_run (M : Ordinary g q) (O : Alphabet M) (read) (src dst : Nat → Fin (g+1))
  10069. (n : Nat) (used : ∀ i, i≤n → src i≠fresh g)
  10070. (tailBlank : ∀ i, n<i → src i=fresh g)
  10071. (clean : ∀ i, dst i=cleanSym M O read (src i))
  10072. (p k : Nat) (bound : p+k=n+1) :
  10073. reach (sweep M O read) ⟨mix src dst p,p,1⟩ ⟨dst,n,2⟩ := by
  10074. induction k generalizing p with
  10075. | zero =>
  10076. have e : p=n+1 := by omega
  10077. subst p
  10078. have ne := Ne.symm (ink_ne_fresh M.marker)
  10079. have whole : mix src dst (n+1)=dst := by
  10080. funext i; by_cases le : i<n+1
  10081. · simp [mix,le]
  10082. · have blank := tailBlank i (by omega)
  10083. simp [mix,le,clean i,blank,cleanSym,ne]
  10084. have blank : dst (n+1)=fresh g := by
  10085. rw [clean,tailBlank _ (by omega)]
  10086. simp [cleanSym,ne]
  10087. rw [whole]; apply single
  10088. have stop : instruction (sweep M O read) ⟨dst,n+1,1⟩=some ⟨2,dst (n+1),.left⟩ := by
  10089. simp [instruction,sweep,control,blank]
  10090. rw [once,stop]; simp [write_same,dest]
  10091. | succ k ih =>
  10092. have le : p≤n := by omega
  10093. apply trans _ (ih (p+1) (by omega))
  10094. apply single
  10095. have atp : mix src dst p p=src p := by simp [mix]
  10096. have ins : instruction (sweep M O read) ⟨mix src dst p,p,1⟩=
  10097. some ⟨1,dst p,.right⟩ := by
  10098. simp [instruction,sweep,control,atp,used _ le,clean p]
  10099. rw [once,ins]
  10100. simp [mix_next,dest]
  10101. theorem finish (M : Ordinary g q) (O : Alphabet M) (read) (src : Nat→Fin (g+1)) (p n)
  10102. (proper : ∀ j, src j=ink M.marker ↔ j=0)
  10103. (used : ∀ i, i≤n → src i≠fresh g) (tailBlank : ∀ i, n<i → src i=fresh g) :
  10104. let dst := fun j => cleanSym M O read (src j)
  10105. reach (sweep M O read) ⟨src,p,0⟩ ⟨dst,0,2⟩ ∧
  10106. instruction (sweep M O read) ⟨dst,0,2⟩=none := by
  10107. let dst := fun j => cleanSym M O read (src j)
  10108. have mp : ∀ j, dst j=ink M.marker ↔ j=0 := fun j => (clean_mark ..).trans (proper j)
  10109. have origin := (proper 0).mpr rfl
  10110. have start : mix src dst 1=src := by
  10111. funext i; cases i with
  10112. | zero => simp [mix,dst,origin,cleanSym]
  10113. | succ i => simp [mix]
  10114. constructor
  10115. · apply trans (rewind M O read src proper 0 (Or.inl rfl) p)
  10116. have first : reach (sweep M O read) ⟨src,0,0⟩ ⟨mix src dst 1,1,1⟩ := by
  10117. rw [start]; apply single
  10118. have i : instruction (sweep M O read) ⟨src,0,0⟩=some ⟨1,src 0,.right⟩ := by
  10119. simp [instruction,sweep,control,origin]
  10120. rw [once,i]; simp [dest,write_same]
  10121. exact trans first (trans (sweep_run M O read src dst n used tailBlank (fun _ => rfl) 1 n (by omega))
  10122. (rewind M O read dst mp 2 (Or.inr rfl) n))
  10123. · change control M O read 2 (dst 0)=none
  10124. simp [control,(mp 0).mpr rfl]
  10125. end P455WriterSweep
  10126. end
  10127. /- Begin Problem455EffectiveMachineRelabelChain (from finite-semigroup-identity-bases). -/
  10128. section
  10129. /- A single concrete writer suffices for every numerical-table decider,
  10130. without any requirement tying their work alphabets or bit conventions. -/
  10131. namespace P455RelabeledChain
  10132. open P455MachineLocal P455MachineCleanup P455MachineTable P455EffectiveMachine
  10133. open P455EffectiveChain P455EffectiveRelabel
  10134. def writerEmb (W : Ordinary g q) (O : Alphabet W) (h : Nat) : Emb g (4+g+h) :=
  10135. common W O (base:=4) (by decide) (by omega)
  10136. def readerEmb (g : Nat) (D : Ordinary h r) (B : Alphabet D) : Emb h (4+g+h) :=
  10137. common D B (base:=4+g) (by omega) (by omega)
  10138. theorem marker_agrees (W : Ordinary g q) (O : Alphabet W) (D : Ordinary h r) (B : Alphabet D) :
  10139. (expand W (writerEmb W O h)).marker=(expand D (readerEmb g D B)).marker := by
  10140. apply Fin.ext
  10141. exact (mark_number W O 4).trans (mark_number D B (4+g)).symm
  10142. theorem tapes_agree (W : Ordinary g q) (O : Alphabet W) (D : Ordinary h r) (B : Alphabet D) (w : List Bool) :
  10143. (fun j => (writerEmb W O h).enc (inputTape W O w j))=
  10144. inputTape (expand D (readerEmb g D B)) (alpha D B (readerEmb g D B)) w := by
  10145. funext j; rw [input_tape]; apply Fin.ext
  10146. cases j with
  10147. | zero => exact (mark_number W O 4).trans (mark_number D B (4+g)).symm
  10148. | succ j =>
  10149. cases eq : w[j]? with
  10150. | none => simpa only [inputTape,eq,Option.elim_none,writerEmb,readerEmb,common] using
  10151. (blank_number W O 4).trans (blank_number D B (4+g)).symm
  10152. | some b => simpa only [inputTape,eq,Option.elim_some,writerEmb,readerEmb,common] using
  10153. (bit_number W O 4 b).trans (bit_number D B (4+g) b).symm
  10154. def combined (W : Ordinary g q) (O : Alphabet W) (D : Ordinary h r) (B : Alphabet D) :
  10155. Ordinary (4+g+h) (q+r) :=
  10156. chain (expand W (writerEmb W O h)) (expand D (readerEmb g D B)) (marker_agrees W O D B)
  10157. def inputs (W : Ordinary g q) (A O : Alphabet W) (D : Ordinary h r) (B : Alphabet D) :
  10158. Alphabet (combined W O D B) :=
  10159. P455EffectiveChain.liftAlphabet _ _ _ (alpha W A (writerEmb W O h))
  10160. theorem expands_delivery (W : Ordinary g q) (A O : Alphabet W) (D : Ordinary h r) (B : Alphabet D) {x y}
  10161. (writing : Delivers W A x W O y) :
  10162. Delivers (expand W (writerEmb W O h)) (alpha W A (writerEmb W O h)) x
  10163. (expand D (readerEmb g D B)) (alpha D B (readerEmb g D B)) y := by
  10164. obtain ⟨t,stopped,pos,tape⟩ := writing
  10165. refine ⟨t,?_⟩
  10166. simp only [exp_run]
  10167. constructor
  10168. · rw [exp_instruction,stopped]; rfl
  10169. · refine ⟨pos,?_⟩
  10170. change (fun j => (writerEmb W O h).enc ((follow W (inputConfig W A x) t).tape j))=_
  10171. rw [tape]; exact tapes_agree W O D B y
  10172. /-- Physical composition on one one-sided tape. The writer may use two
  10173. different bit alphabets for input and output. The reader's original
  10174. alphabet and final-state convention are unrestricted. The fresh common
  10175. alphabet and all transition tables are computed from the two programs. -/
  10176. theorem answers_combined (W : Ordinary g q) (A O : Alphabet W) (D : Ordinary h r)
  10177. (B : Alphabet D) (ans : Fin r→Bool) {x y b}
  10178. (writing : Delivers W A x W O y) (reading : Answers D B ans y b) :
  10179. Answers (combined W O D B) (inputs W A O D B) (out q ans) x b :=
  10180. answers_chain _ _ (marker_agrees W O D B) _ _ ans
  10181. (expands_delivery W A O D B writing) (exp_answers D B (readerEmb g D B) reading)
  10182. end P455RelabeledChain
  10183. end
  10184. /- Begin Problem455SlotSaturation (from finite-semigroup-identity-bases). -/
  10185. section
  10186. namespace P455SlotSaturation
  10187. open P455Witness P455Paths P455ContactLift P455OriginalWalk P455CrossedSupport
  10188. open P455SlotProduct P455SourceFamilies P455SourceTheorem P455MarkedPath
  10189. open P455DefectRename Problem455.Slots
  10190. theorem uniform_of_identity {r allow mark u w x y} (cap : P455Closure.Cap r u)
  10191. (valid : Identity r allow u w) (flip : ClosedFlip r allow u x y)
  10192. (changed : select [x,y] u ≠ select [x,y] w) : UniformSlots r allow mark u x y := by
  10193. obtain ⟨tag,bit,marked⟩ := flip_anchor cap flip
  10194. let n : Node := ⟨x,y,tag⟩
  10195. intro t near i slot bad occ
  10196. apply Classical.byContradiction
  10197. intro ne
  10198. have defic : u.count bad < r := by have := cap bad; omega
  10199. have route : ∃ side : Bool, Near r allow mark u (if side then n.mate else n.owner) t 6 := by
  10200. rcases near with hx | hy
  10201. · exact ⟨false,hx⟩
  10202. · exact ⟨true,hy⟩
  10203. obtain ⟨side,rt⟩ := route
  10204. obtain ⟨keep,s,len,ho,hm,sx,sy,_,kind,labels,capT,test⟩ :=
  10205. canonical_defect cap n bit side t i bad marked rt slot occ defic
  10206. let T := (select keep u).map keep.idxOf
  10207. have mem : T ∈ templates r := Problem455Finite.covered _ _ _
  10208. (capped_length 9 T capT labels) (fun a ha => List.mem_range.mpr (labels a ha))
  10209. obtain ⟨j,eq⟩ := List.get_of_mem mem
  10210. let a : Fin 9 := ⟨keep.idxOf x, Nat.lt_of_lt_of_le (List.idxOf_lt_length_of_mem ho) len⟩
  10211. let b : Fin 9 := ⟨keep.idxOf y, Nat.lt_of_lt_of_le (List.idxOf_lt_length_of_mem hm) len⟩
  10212. have xa : s.anchor.owner = a.val := sx
  10213. have yb : s.anchor.mate = b.val := sy
  10214. have fm : markNode s.anchor = pairMark a b := by
  10215. unfold markNode pairMark
  10216. rw [xa,yb]
  10217. have tc : Holds r allow (pairMark a b) T (s.query r) := fm ▸ test
  10218. let idx : Index r allow := ⟨j,a,b,eq.symm ▸ capT,
  10219. s, keep.idxOf bad,kind,xa,yb,eq.symm ▸ tc⟩
  10220. have proj := marked_test valid keep idx eq.symm
  10221. change select [keep.idxOf x, keep.idxOf y] _ = select [keep.idxOf x, keep.idxOf y] _ at proj
  10222. rw [← binary_select_map keep u ho hm, ← binary_select_map keep w ho hm] at proj
  10223. have kept' (word : W) (c : Nat) (hc : c ∈ select [x,y] word) : c ∈ keep := by
  10224. rcases (by simpa using kept hc : c = x ∨ c = y) with h|h
  10225. · exact h ▸ ho
  10226. · exact h ▸ hm
  10227. have decoded := congrArg (List.map (decode keep)) proj
  10228. dsimp only [n] at decoded
  10229. exact changed (by simpa only [decode_map (kept' u),decode_map (kept' w)] using decoded)
  10230. abbrev noMark : Marking := fun _ _ => False
  10231. theorem pull_walk {r allow mark u v} (mv : P455Closure.Move r allow noMark u v)
  10232. (t : Nat) (p : List Step) (w : Walk r allow mark v t p) : Walk r allow mark u t p := by
  10233. have w0 : Walk r allow noMark v t p := remark_walk t p w
  10234. apply remark_walk (mark := noMark) t p
  10235. clear w
  10236. induction p generalizing t with
  10237. | nil => trivial
  10238. | cons bc tail ih => exact ⟨(query_invariant mv _).mpr w0.1, ih _ w0.2⟩
  10239. theorem uniform_variant {r allow mark u v x y}
  10240. (path : P455Quotient.Walk (P455Closure.Move r allow noMark) u v)
  10241. (uf : UniformSlots r allow mark u x y) : UniformSlots r allow mark v x y := by
  10242. apply path.transport uf
  10243. intro w z mv old t near i slot b occ
  10244. have pull {s} (h : Near r allow mark z s t 6) : Near r allow mark w s t 6 := by
  10245. obtain ⟨p,wa,ep,len⟩ := h
  10246. exact ⟨p,pull_walk mv s p wa,ep,len⟩
  10247. exact (mv.count_eq b).symm.trans (old t (near.imp pull pull) i slot b ((mv.slot_iff t i b slot).mpr occ))
  10248. theorem crossed_at_variant {r allow mark T} (capT : P455Quotient.Cap r T)
  10249. (u : W) (capU : P455Closure.Cap r u) (x y : Nat) (flip : ClosedFlip r allow u x y)
  10250. (u₀ w : W) (cap₀ : P455Closure.Cap r u₀) (identity : Identity r allow u₀ w)
  10251. (flip₀ : ClosedFlip r allow u₀ x y) (changed : select [x,y] u₀ ≠ select [x,y] w)
  10252. (path : P455Quotient.Walk (P455Closure.Move r allow noMark) u₀ u)
  10253. (h : Nat → W) (val : Nat → P455Quotient.Q (rules r allow mark) T)
  10254. (reps : ∀ a ∈ ruleWord r allow mark u x y, P455Quotient.ofWord (rules r allow mark) T (h a) = val a)
  10255. (live : P455Quotient.eval (rules r allow mark) capT val (ruleWord r allow mark u x y) ≠
  10256. P455Quotient.zero (rules r allow mark) T)
  10257. (ts : Tiles) (c : Certificate) (valid : Holds r allow mark T (c.query r ts))
  10258. (second mate : Bool) (cross : Crosses (markedRecord c second) h x y) :
  10259. let names := retained r allow mark u x y
  10260. let v := ruleWord r allow mark u x y
  10261. let d := donor v h r
  10262. let a := startLabel c second mate
  10263. ∃ seed z l k, (seed = x ∨ seed = y) ∧ Supplies v h r seed a ∧
  10264. P455Quotient.Variant (rules r allow mark) T z ∧ z = l ++ v.flatMap h ++ k ∧
  10265. Holds r allow mark z (c.query r ts) ∧ SourceEvidence r allow ts v h seed c ∧
  10266. (Compressed r u → Holds r allow (sourceMarks d c) u ((transferred d c).query r ts)) ∧
  10267. ∀ p : List Step, p.length ≤ 6 → Walk r allow mark z a p →
  10268. Walk r allow mark u seed (relabel d p) ∧ endpoint seed (relabel d p) = d (endpoint a p) ∧
  10269. (relabel d p).length = p.length ∧ d (endpoint a p) ∈ names ∧
  10270. Supplies v h r (d (endpoint a p)) (endpoint a p) ∧ Supplies u h r (d (endpoint a p)) (endpoint a p) :=
  10271. crossed_gadget capT u capU x y flip
  10272. (uniform_variant path (uniform_of_identity cap₀ identity flip₀ changed))
  10273. h val reps live ts c valid second mate cross
  10274. end P455SlotSaturation
  10275. end
  10276. /- Begin Problem455EdgeProduct (from finite-semigroup-identity-bases). -/
  10277. section
  10278. namespace P455EdgeProduct
  10279. open P455Witness P455Paths P455EdgeSource P455EdgeProjection P455PortReflection P455CertificateReach
  10280. open P455DefectRename P455SlotProduct Problem455.Slots
  10281. open P455FirstRewrite (Model)
  10282. abbrev W := List Nat
  10283. def words (r : Nat) := Problem455Finite.wordsUpTo (List.range 14) (14*r)
  10284. def marks (a b c d : Nat) (x y : Nat) := (x = a ∧ y = b) ∨ (x = c ∧ y = d)
  10285. structure Index (r : Nat) (allow : Tag → Prop) (ts : Tiles) where
  10286. num : Fin (words r).length
  10287. a : Fin 14
  10288. b : Fin 14
  10289. c : Fin 14
  10290. d : Fin 14
  10291. cap : P455Closure.Cap r ((words r).get num)
  10292. test : ∃ e : EdgeCertificate, e.a.owner = a.val ∧ e.a.mate = b.val ∧
  10293. e.b.owner = c.val ∧ e.b.mate = d.val ∧
  10294. (∀ x : Nat, x ∈ (words r).get num ↔ x ∈ names ts e) ∧
  10295. Holds r allow (marks a b c d) ((words r).get num) (e.query ts)
  10296. def Index.T (i : Index r allow ts) := (words r).get i.num
  10297. def Index.R (i : Index r allow ts) := rules r allow (marks i.a i.b i.c i.d)
  10298. abbrev Carrier (r : Nat) (allow : Tag → Prop) (ts : Tiles) :=
  10299. (i : Index r allow ts) → P455Quotient.Q i.R i.T
  10300. def product (r : Nat) (allow : Tag → Prop) (ts : Tiles) : Model (Carrier r allow ts) where
  10301. op := fun u v i => P455Quotient.mul i.R i.cap (u i) (v i)
  10302. unit := fun i => P455Quotient.ofWord i.R i.T []
  10303. assoc := fun u v w => funext (fun i => P455Quotient.mul_assoc i.R i.cap (u i) (v i) (w i))
  10304. oneL := fun u => funext (fun i => (P455Quotient.unit_laws i.R i.cap (u i)).1)
  10305. oneR := fun u => funext (fun i => (P455Quotient.unit_laws i.R i.cap (u i)).2)
  10306. theorem observed {r allow ts u w} (valid : (product r allow ts).Valid u w)
  10307. (i : Index r allow ts) (h : Nat → W) :
  10308. P455Quotient.ofWord i.R i.T (u.flatMap h) = P455Quotient.ofWord i.R i.T (w.flatMap h) := by
  10309. let val : Nat → Carrier r allow ts := fun x j => P455Quotient.ofWord j.R j.T (h x)
  10310. have comp (z : W) : (product r allow ts).eval val z i = P455Quotient.ofWord i.R i.T (z.flatMap h) := by
  10311. induction z with
  10312. | nil => rfl
  10313. | cons a z ih =>
  10314. change P455Quotient.mul i.R i.cap (val a i) _ = _
  10315. rw [ih]; rfl
  10316. exact (comp u).symm.trans ((congrFun (valid val) i).trans (comp w))
  10317. theorem names_send (f : Nat → Nat) (ts : Tiles) (e : EdgeCertificate) :
  10318. names ts (sendEdge f e) = (names ts e).map f := by
  10319. cases rr : ts.right e.a.tag <;> cases dd : ts.bottom e.a.tag <;>
  10320. cases ll : ts.left e.a.tag <;> cases uu : ts.top e.a.tag <;>
  10321. simp [names,nodes,candidates,sendEdge,sendNode,roles,rr,dd,ll,uu,List.filter_cons]
  10322. /-- At either endpoint of a true identity the complete 1,0 edge test
  10323. forces both marked binary projections to agree with the opposite
  10324. word. The opposite word is arbitrary. -/
  10325. theorem endpoint_observed {r allow mark ts u w} (cap : P455Closure.Cap r u)
  10326. (valid : (product r allow ts).Valid u w) (e : EdgeCertificate)
  10327. (ok : Holds r allow mark u (e.query ts)) :
  10328. select [e.a.owner,e.a.mate] u = select [e.a.owner,e.a.mate] w ∧
  10329. select [e.b.owner,e.b.mate] u = select [e.b.owner,e.b.mate] w := by
  10330. let keep := names ts e
  10331. let T := template ts e u
  10332. let f := keep.idxOf
  10333. obtain ⟨ct,namesT,cert⟩ := canonical_edge cap ts e ok
  10334. have hr : 0 < r := by have h : e.a.tag.length + 16 = r := ok.1.2.1; omega
  10335. have exactT (x : Nat) : x ∈ T ↔ x ∈ names ts (sendEdge f e) := by
  10336. rw [names_send]
  10337. constructor
  10338. · intro h; obtain ⟨z,hz,rfl⟩ := List.mem_map.mp h
  10339. exact List.mem_map_of_mem (kept hz)
  10340. · intro h; obtain ⟨z,hz,rfl⟩ := List.mem_map.mp h
  10341. apply List.mem_map_of_mem
  10342. apply List.count_pos_iff.mp
  10343. change 0 < (select keep u).count z
  10344. rw [P455DefectProjection.select_count keep u z hz,saturated cap ts e ok hz]
  10345. exact hr
  10346. have low (a : Nat) (h : a ∈ keep) : f a < 14 :=
  10347. Nat.lt_of_lt_of_le (List.idxOf_lt_length_of_mem h) (names_bound ts e)
  10348. have ao := covered (ts := ts) (e := e) .anchor e.a.owner (by simp [roles])
  10349. have am := covered (ts := ts) (e := e) .anchor e.a.mate (by simp [roles])
  10350. have bo := covered (ts := ts) (e := e) .successor e.b.owner (by simp [roles])
  10351. have bm := covered (ts := ts) (e := e) .successor e.b.mate (by simp [roles])
  10352. let a : Fin 14 := ⟨_,low _ ao⟩
  10353. let b : Fin 14 := ⟨_,low _ am⟩
  10354. let c : Fin 14 := ⟨_,low _ bo⟩
  10355. let d : Fin 14 := ⟨_,low _ bm⟩
  10356. have lowT (x : Nat) (h : x ∈ T) := (namesT x h).1
  10357. obtain ⟨j,eq⟩ := List.get_of_mem (Problem455Finite.covered (List.range 14) _ T
  10358. (capped_length _ T ct lowT) (fun x h => List.mem_range.mpr (lowT x h)))
  10359. let i : Index r allow ts := ⟨j,a,b,c,d,eq.symm ▸ ct,sendEdge f e,rfl,rfl,rfl,rfl,
  10360. eq.symm ▸ exactT,eq.symm ▸ cert⟩
  10361. have comp := observed valid i (image keep)
  10362. rw [image_word,image_word] at comp
  10363. have sameT : T = i.T := eq.symm
  10364. change P455Quotient.ofWord i.R i.T T = _ at comp
  10365. rw [sameT] at comp
  10366. have good : P455Quotient.Good i.R i.T i.T := ⟨_,.refl _,[],[],by simp⟩
  10367. have path := ((P455Quotient.same_nonzero_class i.R good).mp comp).2
  10368. have recover (x y : Nat) (hx : x ∈ keep) (hy : y ∈ keep) (markPair : marks a b c d (f x) (f y)) :
  10369. select [x,y] u = select [x,y] w := by
  10370. have pr := path.transport (P := fun z => select [f x,f y] i.T = select [f x,f y] z) rfl
  10371. (fun mv old => old.trans (mv.marked_proj _ _ markPair))
  10372. rw [← sameT] at pr
  10373. change select [keep.idxOf x,keep.idxOf y] ((select keep u).map keep.idxOf) = _ at pr
  10374. rw [← binary_select_map keep u hx hy,← binary_select_map keep w hx hy] at pr
  10375. have k (z : W) (j : Nat) (mem : j ∈ select [x,y] z) : j ∈ keep := by
  10376. rcases (by simpa using kept mem : j=x ∨ j=y) with rfl|rfl <;> assumption
  10377. simpa only [decode_map (k u),decode_map (k w)] using congrArg (List.map (decode keep)) pr
  10378. exact ⟨recover _ _ ao am (.inl ⟨rfl,rfl⟩),recover _ _ bo bm (.inr ⟨rfl,rfl⟩)⟩
  10379. end P455EdgeProduct
  10380. end
  10381. /- Begin Problem455PaddedWord (from finite-semigroup-identity-bases). -/
  10382. section
  10383. namespace P455PaddedWord
  10384. open P455PaddedPorts P455PaddedMatchings P455RectangleRank
  10385. abbrev W := List Nat
  10386. def matching (h w : Nat) : Nat → List Block
  10387. | 0 => horizontal h w false
  10388. | 1 => horizontal h w true
  10389. | 2 => vertical h w false
  10390. | 3 => vertical h w true
  10391. | _+4 => wrap (w*h)
  10392. def portChunks (h w n : Nat) :=
  10393. (List.range n).flatMap fun k => letters (matching h w k)
  10394. def tagPhase (t : Nat) (tag : Nat → List Bool) (k : Nat) :=
  10395. (List.range t).flatMap (mutableCell fun i => (tag i)[k]?.getD false)
  10396. def columnCells (h w : Nat) := (List.range h).flatMap fun y => (List.range w).map (idAt w y)
  10397. def suffix (h w k : Nat) (tag : Nat → List Bool) : W :=
  10398. (List.range k).flatMap (tagPhase (w*h) tag) ++ (columnCells h w).flatMap roles
  10399. def middle (h w k : Nat) (tag : Nat → List Bool) : W := portChunks h w 5 ++ suffix h w k tag
  10400. def tail (t : Nat) : W := (List.range t).flatMap (mutableCell (constant false))
  10401. theorem matching_unique {h w : Nat} (size : 1<w*h) (k : Nat) :
  10402. ((matching h w k).flatMap cells).Nodup := by
  10403. cases k with
  10404. | zero => exact horizontal_unique ..
  10405. | succ k => cases k with
  10406. | zero => exact horizontal_unique ..
  10407. | succ k => cases k with
  10408. | zero => exact vertical_unique ..
  10409. | succ k => cases k with
  10410. | zero => exact vertical_unique ..
  10411. | succ k => exact wrap_unique size
  10412. theorem matching_cells {h w : Nat} (size : 1<w*h) (k i : Nat) :
  10413. i∈(matching h w k).flatMap cells ↔ i<w*h := by
  10414. cases k with
  10415. | zero => exact horizontal_cells ..
  10416. | succ k => cases k with
  10417. | zero => exact horizontal_cells ..
  10418. | succ k => cases k with
  10419. | zero => exact vertical_cells ..
  10420. | succ k => cases k with
  10421. | zero => exact vertical_cells ..
  10422. | succ k => exact wrap_cells size i
  10423. theorem columns_eq (h w : Nat) :
  10424. columnCells h w=(horizontal h w false).flatMap cells := by
  10425. change _ = (lines h w false (idAt w)).flatMap cells
  10426. simp [columnCells,lines,List.flatMap_assoc,line_cells]
  10427. theorem columns_unique (h w : Nat) : (columnCells h w).Nodup := by
  10428. rw [columns_eq]; exact horizontal_unique ..
  10429. theorem columns_cells (h w i : Nat) : i∈columnCells h w ↔ i<w*h := by
  10430. rw [columns_eq]; exact horizontal_cells ..
  10431. end P455PaddedWord
  10432. end
  10433. /- Begin Problem455RetainedVariant (from finite-semigroup-identity-bases). -/
  10434. section
  10435. /- Retention is relative to the chosen marked component only through
  10436. mark-independent contact observations. Both live orientations use
  10437. exactly the same literal names and the same numerical gap naming. -/
  10438. namespace P455RetainedVariant
  10439. open P455Witness P455Paths P455CrossedSupport P455SlotSaturation P455Compression
  10440. open Problem455.Slots
  10441. theorem near_move {r allow mark u v} (mv : P455Closure.Move r allow noMark u v) (a t J : Nat) :
  10442. Near r allow mark u a t J ↔ Near r allow mark v a t J := by
  10443. constructor
  10444. · rintro ⟨p,w,e,len⟩; exact ⟨p,pull_walk mv.symm _ _ w,e,len⟩
  10445. · rintro ⟨p,w,e,len⟩; exact ⟨p,pull_walk mv _ _ w,e,len⟩
  10446. theorem needed_move {r allow mark u v} (mv : P455Closure.Move r allow noMark u v) (x y b : Nat) :
  10447. Needed r allow mark u x y b ↔ Needed r allow mark v x y b := by
  10448. have ball (t) : InBall r allow mark u x y t ↔ InBall r allow mark v x y t :=
  10449. or_congr (near_move mv x t 6) (near_move mv y t 6)
  10450. apply or_congr (ball b)
  10451. constructor
  10452. · rintro ⟨t,i,nb,sl,oc⟩; exact ⟨t,i,(ball t).mp nb,sl,(mv.slot_iff t i b sl).mp oc⟩
  10453. · rintro ⟨t,i,nb,sl,oc⟩; exact ⟨t,i,(ball t).mpr nb,sl,(mv.slot_iff t i b sl).mpr oc⟩
  10454. theorem same_retained {r allow mark u v} (mv : P455Closure.Move r allow noMark u v) (x y : Nat) :
  10455. (retained r allow mark u x y).Perm (retained r allow mark v x y) := by
  10456. classical
  10457. have perm : u.Perm v := List.perm_iff_count.mpr mv.count_eq
  10458. unfold retained
  10459. have pred : (fun b => decide (Needed r allow mark u x y b)) =
  10460. (fun b => decide (Needed r allow mark v x y b)) := by
  10461. funext b; simp [(needed_move mv x y b : Needed r allow mark u x y b ↔ _)]
  10462. rw [pred]
  10463. exact perm.filter _
  10464. theorem sum_perm {s t : W} (h : s.Perm t) : s.sum = t.sum := by
  10465. induction h with
  10466. | nil => rfl
  10467. | cons _ _ ih => simp [ih]
  10468. | swap => simp [List.sum_cons]; omega
  10469. | trans _ _ ih jh => exact ih.trans jh
  10470. theorem pieces_perm (w : W) {s t : W} (perm : s.Perm t) : pieces s w = pieces t w := by
  10471. induction w with
  10472. | nil => rfl
  10473. | cons a w ih =>
  10474. by_cases h : a ∈ s
  10475. · simp [pieces,h,perm.mem_iff.mp h,ih]
  10476. · have ht : a ∉ t := fun m => h (perm.mem_iff.mpr m)
  10477. simp [pieces,h,ht,ih]
  10478. theorem small_congr_names (w : W) {s t : W} (perm : s.Perm t) : small w s = small w t := by
  10479. simp only [small,base,sum_perm perm,pieces_perm w perm]
  10480. theorem retained_remark {r allow mark mark' u x y} :
  10481. retained r allow mark u x y = retained r allow mark' u x y := by
  10482. classical
  10483. have near (a b : Nat) (m m' : Marking) (h : Near r allow m u a b 6) : Near r allow m' u a b 6 := by
  10484. obtain ⟨p,w,ep,len⟩ := h
  10485. exact ⟨p,P455SourceFamilies.remark_walk a p w,ep,len⟩
  10486. have ball (b : Nat) (m m' : Marking) (h : InBall r allow m u x y b) : InBall r allow m' u x y b :=
  10487. h.imp (near _ _ _ _) (near _ _ _ _)
  10488. have need (a : Nat) (m m' : Marking) (h : Needed r allow m u x y a) : Needed r allow m' u x y a := by
  10489. rcases h with h|⟨t,i,h,hi,occ⟩
  10490. · exact .inl (ball _ _ _ h)
  10491. · exact .inr ⟨t,i,ball _ _ _ h,hi,occ⟩
  10492. unfold retained
  10493. apply List.filter_congr
  10494. intro b _
  10495. simp [show Needed r allow mark u x y b ↔ Needed r allow mark' u x y b from ⟨need _ _ _,need _ _ _⟩]
  10496. end P455RetainedVariant
  10497. end
  10498. /- Begin Problem455ProfileComponent (from finite-semigroup-identity-bases). -/
  10499. section
  10500. namespace P455ProfileComponent
  10501. open P455Witness P455Closure P455SlotProduct P455SlotSaturation Problem455.Slots
  10502. abbrev W := List Nat
  10503. theorem profile_support (a b : Nat) (tag : Tag) (bit : Bool) {z : Nat}
  10504. (m : z ∈ profile a b tag bit) : z = a ∨ z = b := by
  10505. rw [← profile_eq] at m
  10506. obtain ⟨c,_,rfl⟩ := List.mem_map.mp m
  10507. cases c <;> simp
  10508. theorem profile_length (a b : Nat) (tag : Tag) (bit : Bool) :
  10509. (profile a b tag bit).length = 2 * (tag.length + 16) := by
  10510. cases bit <;> simp [profile,pair,profile_prefix_length] <;> omega
  10511. theorem profile_cap {a b : Nat} (ne : a ≠ b) (tag : Tag) (bit : Bool) :
  10512. Cap (tag.length + 16) (profile a b tag bit) := by
  10513. intro x
  10514. have tagct (x : Nat) : (tag.flatMap (pair a b)).count x ≤ tag.length := by
  10515. induction tag with
  10516. | nil => simp
  10517. | cons f tag ih =>
  10518. cases f <;> by_cases xa : a=x <;> by_cases xb : b=x <;>
  10519. simp [List.flatMap_cons,pair,List.count_cons,beq_iff_eq,xa,xb,ne,Ne.symm ne] at * <;> omega
  10520. have cp := tagct x
  10521. cases bit <;> by_cases xa : a=x <;> by_cases xb : b=x <;>
  10522. simp [profile,profilePrefix,pair,List.replicate_succ,List.count_cons,beq_iff_eq,xa,xb,ne,Ne.symm ne] at * <;> omega
  10523. def frame (a b : Nat) (tag : Tag) : Frame Nat :=
  10524. ⟨a,[],[],b,tag,(fixedPhases tag).map (fun token => ([],token)),[],[],[]⟩
  10525. theorem frame_core (a b : Nat) (tag : Tag) (bit : Bool) :
  10526. (frame a b tag).core bit = profile a b tag bit := by
  10527. have md (ls : List Bool) : (ls.map (fun token => (([] : W),token))).flatMap
  10528. (fun e => e.1 ++ (if e.2 then [b] else [a])) = ls.map (fun k => if k then b else a) := by
  10529. induction ls with
  10530. | nil => rfl
  10531. | cons c ls ih => cases c <;> simp [List.flatMap_cons, ih] at *
  10532. rw [← profile_eq]
  10533. cases bit <;> simp [Frame.core,Frame.early,Frame.mid,Frame.pair,Frame.p,Frame.q,frame,
  10534. Frame.profileWord,Frame.profileBits,md,phasePair,List.append_assoc]
  10535. theorem forward {r allow a b tag} (ne : a ≠ b) (length : tag.length+16 = r)
  10536. (allowed : allow tag) (bit : Bool) :
  10537. Move r allow noMark (profile a b tag bit) (profile a b tag (!bit)) := by
  10538. let f := frame a b tag
  10539. have cp : Cap r (profile a b tag bit) := length ▸ profile_cap ne tag bit
  10540. have cf : Cap r ([] ++ f.core bit ++ []) := by simpa [f,frame_core] using cp
  10541. refine ⟨f,bit,[],[],f.valid_of_capped_shape (by change r = 16+tag.length; omega) allowed
  10542. (by simp [f,frame,List.map_map,Function.comp_def]) (by simp [f,frame,Frame.p])
  10543. (by simp [f,frame,Frame.q]) (by simpa [f,frame,Frame.p,Frame.q] using ne)
  10544. (by simp [noMark]) bit [] [] cf,by simp [f,frame_core],by simp [f,frame_core],cp⟩
  10545. theorem variants {r allow a b tag} (ne : a ≠ b) (length : tag.length+16 = r)
  10546. (allowed : allow tag) (bit : Bool) (u : W) :
  10547. P455Quotient.Variant (rules r allow noMark) (profile a b tag bit) u ↔
  10548. ∃ v : Bool, u = profile a b tag v := by
  10549. constructor
  10550. · intro path
  10551. have supp (x : Nat) (inU : x ∈ u) : x=a ∨ x=b := by
  10552. have ct := P455Quotient.count_walk (rules r allow noMark) path x
  10553. exact profile_support a b tag bit (List.count_pos_iff.mp (ct ▸ List.count_pos_iff.mpr inU))
  10554. have selfU : select [a,b] u = u := by apply List.filter_eq_self.mpr; simpa using supp
  10555. have selfT : select [a,b] (profile a b tag bit) = profile a b tag bit := by
  10556. apply List.filter_eq_self.mpr
  10557. intro x h; simpa using profile_support a b tag bit h
  10558. have typed' := path.transport (P := fun z => typed z a b tag) ⟨bit,selfT⟩
  10559. (fun mv yes => (mv.typed_iff a b tag ne length).mp yes)
  10560. simpa [typed,selfU] using typed'
  10561. · rintro ⟨v,rfl⟩
  10562. cases bit <;> cases v
  10563. · exact .refl _
  10564. · exact .snoc (.refl _) (forward ne length allowed false)
  10565. · exact .snoc (.refl _) (forward ne length allowed true)
  10566. · exact .refl _
  10567. theorem factors {r allow a b tag} (ne : a ≠ b) (length : tag.length+16 = r)
  10568. (allowed : allow tag) (bit : Bool) (u : W) :
  10569. P455Quotient.Good (rules r allow noMark) (profile a b tag bit) u ↔
  10570. ∃ v : Bool, P455Quotient.Factor u (profile a b tag v) := by
  10571. constructor
  10572. · rintro ⟨w,p,f⟩; obtain ⟨v,rfl⟩ := (variants ne length allowed bit w).mp p; exact ⟨v,f⟩
  10573. · rintro ⟨v,f⟩; exact ⟨_,(variants ne length allowed bit _).mpr ⟨v,rfl⟩,f⟩
  10574. theorem move_size {r allow mark} {u v : W} (h : Move r allow mark u v) : 2*r ≤ u.length := by
  10575. obtain ⟨f,t,l,k,ok,rfl,_,cp⟩ := h
  10576. have pr := f.cross_projection ok t l k cp f.pHead f.qLast (by simp [Frame.p]) (by simp [Frame.q])
  10577. have small := List.length_filter_le (fun a => decide (a=f.pHead ∨ a=f.qLast)) (l ++ f.core t ++ k)
  10578. rw [pr,profile_eq,profile_length] at small
  10579. have eq := ok.1
  10580. omega
  10581. theorem proper_singleton {r allow a b tag bit u v} (live : P455Quotient.Good (rules r allow noMark)
  10582. (profile a b tag bit) u) (short : u.length < 2*r) :
  10583. P455Quotient.ofWord (rules r allow noMark) (profile a b tag bit) u =
  10584. P455Quotient.ofWord (rules r allow noMark) (profile a b tag bit) v ↔ u=v := by
  10585. constructor
  10586. · intro eq
  10587. have path := ((P455Quotient.same_nonzero_class _ live).mp eq).2
  10588. exact path.transport (P := fun z => u=z) rfl (fun mv e => by
  10589. subst_vars; have := move_size mv; omega)
  10590. · rintro rfl; rfl
  10591. theorem classes {r allow a b tag} (ne : a ≠ b) (length : tag.length+16 = r)
  10592. (allowed : allow tag) (bit : Bool) (u v : W) :
  10593. let R := rules r allow noMark
  10594. let T := profile a b tag bit
  10595. P455Quotient.ofWord R T u = P455Quotient.ofWord R T v ↔ u=v ∨
  10596. ((∃ i : Bool, u = profile a b tag i) ∧ (∃ j : Bool, v = profile a b tag j)) ∨
  10597. (¬ (∃ i : Bool, P455Quotient.Factor u (profile a b tag i)) ∧
  10598. ¬ (∃ j : Bool, P455Quotient.Factor v (profile a b tag j))) := by
  10599. let R := rules r allow noMark
  10600. let T := profile a b tag bit
  10601. change P455Quotient.ofWord R T u = P455Quotient.ofWord R T v ↔ _
  10602. constructor
  10603. · intro eq
  10604. by_cases valid : P455Quotient.Good R T u
  10605. · by_cases short : u.length < 2*r
  10606. · exact .inl ((proper_singleton valid short).mp eq)
  10607. · obtain ⟨i,L,K,e⟩ := (factors ne length allowed bit u).mp valid
  10608. have lens := congrArg List.length e
  10609. simp only [profile_length,length,List.length_append] at lens
  10610. have lk : L=[] ∧ K=[] := ⟨List.length_eq_zero_iff.mp (by omega),List.length_eq_zero_iff.mp (by omega)⟩
  10611. have full : u = profile a b tag i := by simpa [lk.1,lk.2] using e.symm
  10612. have path := ((P455Quotient.same_nonzero_class _ valid).mp eq).2
  10613. rw [full] at path
  10614. exact .inr (.inl ⟨⟨i,full⟩,(variants ne length allowed i v).mp path⟩)
  10615. · have dead : ¬ P455Quotient.Good R T v := by
  10616. intro g; exact valid (((P455Quotient.same_nonzero_class _ g).mp eq.symm).1)
  10617. exact .inr (.inr ⟨fun h => valid ((factors ne length allowed bit u).mpr h),
  10618. fun h => dead ((factors ne length allowed bit v).mpr h)⟩)
  10619. · rintro (rfl|⟨⟨i,rfl⟩,⟨j,rfl⟩⟩|⟨du,dv⟩)
  10620. · rfl
  10621. · have live (b' : Bool) : P455Quotient.Good R T (profile a b tag b') :=
  10622. (factors ne length allowed bit _).mpr ⟨b',[],[],by simp⟩
  10623. exact (P455Quotient.same_nonzero_class _ (live i)).mpr
  10624. ⟨live j,(variants ne length allowed i _).mpr ⟨j,rfl⟩⟩
  10625. · apply Quotient.sound; exact .inl ⟨fun gu => du ((factors ne length allowed bit u).mp gu),
  10626. fun gv => dv ((factors ne length allowed bit v).mp gv)⟩
  10627. end P455ProfileComponent
  10628. end
  10629. /- Begin Problem455GridRows (from finite-semigroup-identity-bases). -/
  10630. section
  10631. namespace P455GridRows
  10632. open P455Witness P455Paths Problem455.Slots
  10633. /-- Horizontal and vertical compatible tile pairs obey the flags in the
  10634. machine construction. The bare `Tiles` structure does not impose them. -/
  10635. structure Laws (ts : Tiles) : Prop where
  10636. horiz : ∀ a b, ts.horizontal a b →
  10637. ts.right a=false ∧ ts.left b=false ∧ ts.top a=ts.top b ∧
  10638. ts.bottom a=ts.bottom b ∧ ts.oddRow a=ts.oddRow b ∧ ts.oddColumn b= !ts.oddColumn a
  10639. vert : ∀ a b, ts.vertical a b →
  10640. ts.bottom a=false ∧ ts.top b=false ∧ ts.left b=ts.left a ∧
  10641. ts.right b=ts.right a ∧ ts.oddColumn b=ts.oddColumn a ∧ ts.oddRow b= !ts.oddRow a
  10642. def Arrow (r : Nat) (allow : Tag → Prop) (mark : Marking) (w : W) (ts : Tiles) (e : EdgeCertificate) :=
  10643. Holds r allow mark w (typedNode e.a) ∧ Holds r allow mark w (typedNode e.b) ∧
  10644. Holds r allow mark w (localCert ts e) ∧ Holds r allow mark w (chosenSuccessor ts e)
  10645. def Functional (r : Nat) (allow : Tag → Prop) (mark : Marking) (w : W) (ts : Tiles) (a : Node) :=
  10646. ∀ (d : Dir) (b c : Node), Holds r allow mark w (neighbor ts a b d) →
  10647. Holds r allow mark w (neighbor ts a c d) → b=c
  10648. private theorem active {r allow mark w q b} (h : Holds r allow mark w (flagQ (!b) q))
  10649. (off : b=false) : Holds r allow mark w q := by simpa only [off,Bool.not_false,flagQ,if_true] using h
  10650. /-- The diagonal must be the down-neighbor of the already visited right-hand
  10651. upper cell. No functionality on either of the two proposed lower cells. -/
  10652. theorem descend_pair {r allow mark w ts} (law : Laws ts) (x y : EdgeCertificate)
  10653. (hX : Holds r allow mark w (localCert ts x)) (hY : Holds r allow mark w (localCert ts y))
  10654. (fx : Functional r allow mark w ts x.a) (fy : Functional r allow mark w ts y.a)
  10655. (edge : Holds r allow mark w (rightward ts x.a y.a)) (nb : ts.bottom x.a.tag=false) :
  10656. Holds r allow mark w (downward ts x.a x.down) ∧
  10657. Holds r allow mark w (downward ts y.a y.down) ∧
  10658. Holds r allow mark w (rightward ts x.down y.down) := by
  10659. have lawH := law.horiz _ _ edge.1
  10660. have nr := lawH.1
  10661. have ny : ts.bottom y.a.tag=false := lawH.2.2.2.1.symm.trans nb
  10662. have square : Holds r allow mark w (downward ts x.right x.diagonal) ∧
  10663. Holds r allow mark w (rightward ts x.down x.diagonal) := by
  10664. simpa [flagQ,nr,nb,Holds] using hX.2.2.2.2.1
  10665. have toY := fx .right x.right y.a (active hX.1 nr) edge
  10666. have downY := active hY.2.2.1 ny
  10667. have d : x.diagonal = y.down := fy .down _ _ (toY ▸ square.1) downY
  10668. exact ⟨active hX.2.2.1 nb,downY,d ▸ square.2⟩
  10669. theorem enters_down {r allow mark w ts} (e : EdgeCertificate) (arr : Arrow r allow mark w ts e)
  10670. (endRow : endOfRow ts e.a = true) (notBottom : ts.bottom e.a.tag = false) : e.b = e.down := by
  10671. have suc := arr.2.2.2
  10672. simp only [chosenSuccessor,endRow,notBottom,Bool.and_false,Bool.false_eq_true,if_false,if_true] at suc
  10673. exact suc.1.symm
  10674. private theorem goes_right {r allow mark w ts} (e : EdgeCertificate) (arr : Arrow r allow mark w ts e)
  10675. (odd : ts.oddRow e.a.tag=false) (right : ts.right e.a.tag=false) :
  10676. Holds r allow mark w (rightward ts e.a e.b) := by
  10677. have endRow : endOfRow ts e.a = false := by simp [endOfRow,odd,right]
  10678. have suc := arr.2.2.2
  10679. simp only [chosenSuccessor,endRow,Bool.false_and,Bool.false_eq_true,if_false,odd] at suc
  10680. exact suc.1 ▸ active arr.2.2.1.1 right
  10681. private theorem goes_left {r allow mark w ts} (e : EdgeCertificate) (arr : Arrow r allow mark w ts e)
  10682. (odd : ts.oddRow e.a.tag=true) (left : ts.left e.a.tag=false) :
  10683. Holds r allow mark w (rightward ts e.b e.a) := by
  10684. have endRow : endOfRow ts e.a = false := by simp [endOfRow,odd,left]
  10685. have suc := arr.2.2.2
  10686. simp only [chosenSuccessor,endRow,Bool.false_and,Bool.false_eq_true,if_false,odd,if_true] at suc
  10687. exact suc.1 ▸ active arr.2.2.1.2.1 left
  10688. /-- An arbitrary candidate row is forced onto the cycle once its first cell
  10689. is known to lie there. Induction obtains functionality from the trace
  10690. before identifying its next cell. Width one is n=0. -/
  10691. theorem trace_row {r allow mark w ts} (law : Laws ts) (atCell : Nat → EdgeCertificate)
  10692. (arrow : ∀ i, Arrow r allow mark w ts (atCell i))
  10693. (continuous : ∀ i, (atCell i).b=(atCell (i+1)).a)
  10694. (functional : ∀ i, Functional r allow mark w ts (atCell i).a)
  10695. (row : Nat → Node) (n start : Nat) (odd : Bool)
  10696. (init : (atCell start).a=row 0)
  10697. (rowOdd : ∀ j, j≤n → ts.oddRow (row j).tag=odd)
  10698. (links : ∀ j, j<n → Holds r allow mark w
  10699. (if odd then rightward ts (row (j+1)) (row j) else rightward ts (row j) (row (j+1)))) :
  10700. ∀ j, j≤n → (atCell (start+j)).a=row j := by
  10701. intro j
  10702. induction j with
  10703. | zero => intro _; exact init
  10704. | succ j ih =>
  10705. intro le
  10706. have here := ih (by omega)
  10707. have p : ts.oddRow (atCell (start+j)).a.tag=odd := here ▸ rowOdd j (by omega)
  10708. have one := links j (by omega)
  10709. have eq : (atCell (start+j)).b=row (j+1) := by
  10710. cases odd with
  10711. | false =>
  10712. have R : Holds r allow mark w (rightward ts (atCell (start+j)).a (row (j+1))) := here ▸ one
  10713. have next := goes_right _ (arrow (start+j)) p (law.horiz _ _ R.1).1
  10714. exact functional _ .right _ _ next R
  10715. | true =>
  10716. have L : Holds r allow mark w (rightward ts (row (j+1)) (atCell (start+j)).a) := here ▸ one
  10717. have next := goes_left _ (arrow (start+j)) p (law.horiz _ _ L.1).2.1
  10718. exact functional _ .left _ _ next L
  10719. exact (continuous _).symm.trans eq
  10720. /-- Positive left-to-right ordering of a nonbottom upper row; its cells are
  10721. given by positions in the trace. This yields the entire lower right chain
  10722. and its vertical links, even before the new row is known to be on the trace. -/
  10723. theorem lower_row {r allow mark w ts} (law : Laws ts) (atCell : Nat → EdgeCertificate)
  10724. (arrow : ∀ i, Arrow r allow mark w ts (atCell i))
  10725. (functional : ∀ i, Functional r allow mark w ts (atCell i).a)
  10726. (index : Nat → Nat) (n : Nat)
  10727. (edges : ∀ j, j<n → Holds r allow mark w (rightward ts (atCell (index j)).a (atCell (index (j+1))).a))
  10728. (nonbottom : ∀ j, j≤n → ts.bottom (atCell (index j)).a.tag=false) :
  10729. (∀ j, j≤n → Holds r allow mark w (downward ts (atCell (index j)).a (atCell (index j)).down)) ∧
  10730. (∀ j, j<n → Holds r allow mark w (rightward ts (atCell (index j)).down (atCell (index (j+1))).down)) := by
  10731. refine ⟨fun j hj => active (arrow (index j)).2.2.1.2.2.1 (nonbottom _ hj),?_⟩
  10732. intro j hj
  10733. exact (descend_pair law _ _ (arrow _).2.2.1 (arrow _).2.2.1
  10734. (functional _) (functional _) (edges j hj) (nonbottom j (by omega))).2.2
  10735. /-- Turn a directed indexed comparison in the actual word into a strict
  10736. numerical rank. Every stamped occurrence appears in just one position. -/
  10737. private theorem idx_lt (a b : Event) (ls : List Event) (nd : ls.Nodup)
  10738. (sub : [a,b].Sublist ls) : ls.idxOf a < ls.idxOf b := by
  10739. induction ls with
  10740. | nil => cases sub
  10741. | cons x ls ih =>
  10742. obtain ⟨fresh,distinct⟩ := List.nodup_cons.mp nd
  10743. cases sub with
  10744. | cons _ sub =>
  10745. have hitA : a ∈ ls := sub.subset (by simp)
  10746. have hitB : b ∈ ls := sub.subset (by simp)
  10747. have xa : x ≠ a := fun eq => fresh (eq ▸ hitA)
  10748. have xb : x ≠ b := fun eq => fresh (eq ▸ hitB)
  10749. simpa only [List.idxOf_cons,cond_eq_if,beq_iff_eq,if_neg xa,if_neg xb,
  10750. if_neg (Ne.symm xa),if_neg (Ne.symm xb),Nat.add_lt_add_iff_right] using ih distinct sub
  10751. | cons_cons _ sub =>
  10752. have hit : b ∈ ls := sub.subset List.mem_cons_self
  10753. have ab : a ≠ b := fun eq => fresh (eq ▸ hit)
  10754. simp [List.idxOf_cons,cond_eq_if,beq_iff_eq,ab,Ne.symm ab]
  10755. def position (w : W) (a : Node) := (events w).idxOf (a.owner,0)
  10756. def Return (ts : Tiles) (e : EdgeCertificate) :=
  10757. endOfRow ts e.a && ts.bottom e.a.tag
  10758. theorem forward_increases {r allow mark w ts} (e : EdgeCertificate)
  10759. (arr : Arrow r allow mark w ts e) (forward : Return ts e=false) :
  10760. position w e.a < position w e.b := by
  10761. have h := arr.2.2.2
  10762. change (endOfRow ts e.a && ts.bottom e.a.tag)=false at forward
  10763. simp only [chosenSuccessor,forward,Bool.false_eq_true,if_false] at h
  10764. exact idx_lt _ _ _ (stamp_unique _ _) h.2.2
  10765. /-- On an indefinitely continued trace of genuine arrows (in particular a
  10766. repeated directed cycle), a return occurs beyond every starting index. -/
  10767. theorem later_return {r allow mark w ts} (atCell : Nat → EdgeCertificate)
  10768. (arrow : ∀ i, Arrow r allow mark w ts (atCell i))
  10769. (continuous : ∀ i, (atCell i).b=(atCell (i+1)).a) (start : Nat) :
  10770. ∃ offset, Return ts (atCell (start+offset))=true := by
  10771. apply Classical.byContradiction
  10772. intro none
  10773. have forward (j) : Return ts (atCell (start+j))=false := by
  10774. cases e : Return ts (atCell (start+j)) with
  10775. | false => rfl
  10776. | true => exact (none ⟨j,e⟩).elim
  10777. have grows (j) : j ≤ position w (atCell (start+j)).a := by
  10778. induction j with
  10779. | zero => exact Nat.zero_le _
  10780. | succ j ih =>
  10781. have inc := forward_increases _ (arrow _) (forward j)
  10782. rw [continuous] at inc
  10783. exact Nat.lt_of_le_of_lt ih inc
  10784. have impossible := grows ((events w).length+1)
  10785. have bound (z : Event) : (events w).idxOf z ≤ (events w).length := by
  10786. by_cases h : z ∈ events w
  10787. · exact Nat.le_of_lt (List.idxOf_lt_length_of_mem h)
  10788. · exact Nat.le_of_eq (List.idxOf_eq_length h)
  10789. have c := bound ((atCell (start+((events w).length+1))).a.owner,0)
  10790. unfold position at impossible
  10791. omega
  10792. theorem return_target {r allow mark w ts} (e : EdgeCertificate) (arr : Arrow r allow mark w ts e)
  10793. (back : Return ts e=true) :
  10794. ts.top e.b.tag=true ∧ ts.left e.b.tag=true ∧ ts.oddRow e.b.tag=false ∧ ts.oddColumn e.b.tag=false := by
  10795. have h := arr.2.2.2
  10796. change (endOfRow ts e.a && ts.bottom e.a.tag)=true at back
  10797. simp only [chosenSuccessor,back,if_true] at h
  10798. simpa [and_assoc,P455Witness.Holds] using h.1
  10799. /-- Column reached after j snake steps in a row with last column n. -/
  10800. def column (n : Nat) (odd : Bool) (j : Nat) := if odd then n-j else j
  10801. /-- Descend from the traveled end of a nonbottom row, reverse direction, and
  10802. identify each prospective cell in the lower row with its actual trace
  10803. index. Only the old row is initially known to be on the trace. -/
  10804. theorem advance_row {r allow mark w ts} (law : Laws ts) (atCell : Nat → EdgeCertificate)
  10805. (arrow : ∀ i, Arrow r allow mark w ts (atCell i))
  10806. (continuous : ∀ i, (atCell i).b=(atCell (i+1)).a)
  10807. (functional : ∀ i, Functional r allow mark w ts (atCell i).a)
  10808. (index : Nat → Nat) (n : Nat) (odd : Bool)
  10809. (edges : ∀ j, j<n → Holds r allow mark w (rightward ts (atCell (index j)).a (atCell (index (j+1))).a))
  10810. (nonbottom : ∀ j, j≤n → ts.bottom (atCell (index j)).a.tag=false)
  10811. (parity : ∀ j, j≤n → ts.oddRow (atCell (index j)).a.tag=odd)
  10812. (left : ts.left (atCell (index 0)).a.tag=true) (right : ts.right (atCell (index n)).a.tag=true) :
  10813. let last := column n (!odd) 0
  10814. let start := index last+1
  10815. ∀ j, j≤n → (atCell (start+column n (!odd) j)).a=(atCell (index j)).down := by
  10816. let last := column n (!odd) 0
  10817. let start := index last+1
  10818. let row (j : Nat) := (atCell (index (column n (!odd) j))).down
  10819. have lastBound : last≤n := by cases odd <;> simp [last,column]
  10820. have ending : endOfRow ts (atCell (index last)).a=true := by
  10821. rw [endOfRow,parity last lastBound]
  10822. cases odd <;> simp_all only [last,column,Bool.not_false,Bool.not_true,if_true,
  10823. Bool.false_eq_true,if_false,Nat.sub_zero]
  10824. obtain ⟨v,h⟩ := lower_row law atCell arrow functional index n edges nonbottom
  10825. have init : (atCell start).a=row 0 :=
  10826. (continuous _).symm.trans (enters_down _ (arrow _) ending (nonbottom _ lastBound))
  10827. have rowOdd (j) (le : j≤n) : ts.oddRow (row j).tag= !odd := by
  10828. have c : column n (!odd) j ≤ n := by cases odd <;> simp [column,le,Nat.sub_le]
  10829. exact (law.vert _ _ (v _ c).1).2.2.2.2.2.trans (congrArg Bool.not (parity _ c))
  10830. have adjacent (j) (le : j<n) : Holds r allow mark w
  10831. (if !odd then rightward ts (row (j+1)) (row j) else rightward ts (row j) (row (j+1))) := by
  10832. cases odd with
  10833. | true => exact h j le
  10834. | false =>
  10835. have u := h (n-(j+1)) (by omega)
  10836. have ix : n-(j+1)+1=n-j := by omega
  10837. simpa only [row,column,Bool.not_false,if_true,ix] using u
  10838. have trace := trace_row law atCell arrow continuous functional row n start (!odd) init rowOdd adjacent
  10839. dsimp only
  10840. intro j le
  10841. have c : column n (!odd) j ≤ n := by cases odd <;> simp [column,le,Nat.sub_le]
  10842. have twice : column n (!odd) (column n (!odd) j)=j := by cases odd <;> simp [column] <;> omega
  10843. simpa only [row,twice,start,last] using trace (column n (!odd) j) c
  10844. end P455GridRows
  10845. end
  10846. /- Begin Problem455CatalogueBounds (from finite-semigroup-identity-bases). -/
  10847. section
  10848. /- Exact finite witness search for the two-mark catalogue. Syntactically
  10849. unused fields are unbounded in the Lean index. Every successful
  10850. witness has a representative using only occurring names and admitted
  10851. tags, even when nodes and labels alias. -/
  10852. namespace P455CatalogueBounds
  10853. open P455Witness P455Paths P455CertificateReach P455EdgeProjection Problem455.Slots
  10854. abbrev W := List Nat
  10855. def canonical (ts : Tiles) (e : EdgeCertificate) : EdgeCertificate :=
  10856. ⟨e.a,e.b,if ts.right e.a.tag then e.a else e.right,
  10857. if ts.left e.a.tag then e.a else e.left,if ts.bottom e.a.tag then e.a else e.down,
  10858. if ts.top e.a.tag then e.a else e.up,
  10859. if ts.right e.a.tag || ts.bottom e.a.tag then e.a else e.diagonal⟩
  10860. theorem query_canonical (ts : Tiles) (e : EdgeCertificate) :
  10861. (canonical ts e).query ts = e.query ts := by
  10862. cases rr : ts.right e.a.tag <;> cases ll : ts.left e.a.tag <;>
  10863. cases dd : ts.bottom e.a.tag <;> cases uu : ts.top e.a.tag <;> cases oo : ts.oddRow e.a.tag <;>
  10864. simp [canonical,EdgeCertificate.query,localCert,chosenSuccessor,endOfRow,flagQ,rr,ll,dd,uu,oo]
  10865. theorem names_canonical (ts : Tiles) (e : EdgeCertificate) : names ts (canonical ts e)=names ts e := by
  10866. cases rr : ts.right e.a.tag <;> cases ll : ts.left e.a.tag <;>
  10867. cases dd : ts.bottom e.a.tag <;> cases uu : ts.top e.a.tag <;>
  10868. simp [canonical,names,nodes,candidates,rr,ll,dd,uu,List.filter_cons]
  10869. def fields (e : EdgeCertificate) := [e.a,e.b,e.right,e.left,e.down,e.up,e.diagonal]
  10870. theorem original_active (ts : Tiles) (e : EdgeCertificate) {a : Node}
  10871. (h : a∈fields (canonical ts e)) : Active ts e a := by
  10872. simp only [fields,canonical,List.mem_cons,List.not_mem_nil,or_false] at h
  10873. rcases h with eq|eq|eq|eq|eq|eq|eq <;> rw [eq]
  10874. · exact .anchor
  10875. · exact .successor
  10876. · cases f : ts.right e.a.tag <;> simp only [f,Bool.false_eq_true,if_false,if_true]
  10877. · exact .right f
  10878. · exact .anchor
  10879. · cases f : ts.left e.a.tag <;> simp only [f,Bool.false_eq_true,if_false,if_true]
  10880. · exact .left f
  10881. · exact .anchor
  10882. · cases f : ts.bottom e.a.tag <;> simp only [f,Bool.false_eq_true,if_false,if_true]
  10883. · exact .down f
  10884. · exact .anchor
  10885. · cases f : ts.top e.a.tag <;> simp only [f,Bool.false_eq_true,if_false,if_true]
  10886. · exact .up f
  10887. · exact .anchor
  10888. · cases rr : ts.right e.a.tag <;> cases dd : ts.bottom e.a.tag <;>
  10889. simp only [rr,dd,Bool.or_false,Bool.or_true,Bool.false_eq_true,if_false,if_true]
  10890. · exact .diagonal rr dd
  10891. all_goals exact .anchor
  10892. def pool (w : W) (tags : List Tag) := w.flatMap (fun x => w.flatMap (fun y => tags.map (Node.mk x y)))
  10893. theorem record_in_pool {r allow mark w} (tags : List Tag) (finiteTags : ∀ t,allow t → t ∈ tags)
  10894. (node : Node) (valid : Holds r allow mark w (typedNode node)) : node ∈ pool w tags := by
  10895. obtain ⟨_,_,yes,bit,pr⟩ := valid
  10896. have mem (z : Nat) (side : z=node.owner ∨ z=node.mate) : z∈w := by
  10897. have m : z ∈ select [node.owner,node.mate] w := by
  10898. rw [pr]; rcases side with rfl|rfl <;> simp [profile,profilePrefix]
  10899. exact (List.mem_filter.mp m).1
  10900. exact List.mem_flatMap.mpr ⟨node.owner,mem _ (.inl rfl),List.mem_flatMap.mpr
  10901. ⟨node.mate,mem _ (.inr rfl),List.mem_map.mpr ⟨node.tag,finiteTags _ yes,rfl⟩⟩⟩
  10902. /-- The exact name-set side condition and both marked name-pairs are
  10903. kept. Arbitrary unused original nodes need not be encoded or bounded. -/
  10904. theorem bounded_edge {r allow mark ts w} (cap : P455Closure.Cap r w)
  10905. (tags : List Tag) (finiteTags : ∀ t,allow t → t∈tags) (e : EdgeCertificate)
  10906. (read : Holds r allow mark w (e.query ts)) :
  10907. ∃ c : EdgeCertificate, c.a=e.a ∧ c.b=e.b ∧ names ts c=names ts e ∧
  10908. Holds r allow mark w (c.query ts) ∧ ∀ n ∈ fields c, n ∈ pool w tags := by
  10909. exact ⟨canonical ts e,rfl,rfl,names_canonical ..,(query_canonical ts e) ▸ read,
  10910. fun n mem => record_in_pool tags finiteTags n (active_owner cap ts e read (original_active ts e mem)).2⟩
  10911. /-- A catalogue position and its literal template are interchangeable for
  10912. duplicate-free finite alphabets, including all five alphabets used by
  10913. the concrete model. Distinct isomorphic templates remain separate. -/
  10914. theorem words_nodup {α : Type} (alphabet : List α) (nd : alphabet.Nodup) (bound : Nat) :
  10915. (Problem455Finite.wordsUpTo alphabet bound).Nodup := by
  10916. induction bound with
  10917. | zero => simp [Problem455Finite.wordsUpTo]
  10918. | succ n ih =>
  10919. apply List.nodup_cons.mpr
  10920. constructor
  10921. · simp [List.mem_flatMap]
  10922. · apply List.pairwise_flatMap.mpr
  10923. constructor
  10924. · intro a _
  10925. exact ih.map (fun _ _ eq => (List.cons.inj eq).2)
  10926. · apply nd.imp
  10927. intro a b ab x hx y hy same
  10928. obtain ⟨u,_,rfl⟩ := List.mem_map.mp hx
  10929. obtain ⟨v,_,rfl⟩ := List.mem_map.mp hy
  10930. exact ab (List.cons.inj same).1
  10931. theorem bounded_functionality {r allow ts mark w} (tags : List Tag)
  10932. (finiteTags : ∀ t,allow t → t∈tags) (f : FunctionalityCertificate)
  10933. (ok : Holds r allow mark w (f.query ts)) :
  10934. f.anchor ∈ pool w tags ∧ f.b ∈ pool w tags ∧ f.c ∈ pool w tags := by
  10935. exact ⟨record_in_pool tags finiteTags _ (marked_typed ok.1),
  10936. record_in_pool tags finiteTags _ (neighbor_target_record ok.2.1),
  10937. record_in_pool tags finiteTags _ (neighbor_target_record ok.2.2.1)⟩
  10938. end P455CatalogueBounds
  10939. end
  10940. /- Begin Problem455PaddedCounts (from finite-semigroup-identity-bases). -/
  10941. section
  10942. namespace P455PaddedWord
  10943. open P455PaddedMatchings P455PaddedPorts P455RectangleRank Problem455.Slots
  10944. private theorem cell_role {i a : Nat} (h : a∈roles i) : a=owner i ∨ a=mate i := by simpa [roles] using h
  10945. theorem absent_other {i j a : Nat} (r : a∈roles i) (different : i≠j) : a∉roles j := by
  10946. intro m; have p := cell_role r; have q := cell_role m; unfold owner mate at p q; omega
  10947. private theorem range_count (i t : Nat) : (List.range t).count i=(if i<t then 1 else 0) := by
  10948. by_cases h : i<t
  10949. · simp [h,count_one List.nodup_range (List.mem_range.mpr h)]
  10950. · simp [h,List.count_eq_zero.mpr (fun m=>h (List.mem_range.mp m))]
  10951. private theorem weighted (f : Nat→List Nat) (i a v : Nat) (s : List Nat)
  10952. (w : ∀ j,(f j).count a=(if j=i then v else 0)) : (s.flatMap f).count a=v*s.count i := by
  10953. induction s with
  10954. | nil => simp
  10955. | cons j s ih =>
  10956. by_cases e : j=i
  10957. · subst j; simp [List.flatMap_cons,List.count_append,w,ih,List.count_cons,Nat.mul_add,Nat.add_comm]
  10958. · simp [List.flatMap_cons,List.count_append,w,ih,List.count_cons,e,Ne.symm e]
  10959. theorem private_counts (i a : Nat) (role : a∈roles i) (t : Nat) :
  10960. ((List.range t).flatMap privateCell).count a=if i<t then 3 else 0 := by
  10961. have ne : owner i≠mate i := by unfold owner mate; omega
  10962. have ct (j : Nat) : (privateCell j).count a=if j=i then 3 else 0 := by
  10963. by_cases e : j=i
  10964. · subst j; rcases cell_role role with rfl|rfl <;> simp [privateCell,List.count_cons,ne,Ne.symm ne]
  10965. · have no := absent_other role (Ne.symm e)
  10966. have no' : a∉privateCell j := by simpa [roles,privateCell,or_assoc,or_left_comm,or_comm] using no
  10967. simp [List.count_eq_zero.mpr no',e]
  10968. rw [weighted _ _ _ _ _ ct,range_count]; split <;> simp
  10969. theorem mutable_counts (i a : Nat) (role : a∈roles i) (bits : Nat→Bool) (t : Nat) :
  10970. ((List.range t).flatMap (mutableCell bits)).count a=if i<t then 1 else 0 := by
  10971. have ne : owner i≠mate i := by unfold owner mate; omega
  10972. have ct (j : Nat) : (mutableCell bits j).count a=if j=i then 1 else 0 := by
  10973. by_cases e : j=i
  10974. · subst j; rcases cell_role role with rfl|rfl <;> cases b : bits i <;> simp [mutableCell,b,List.count_cons,ne,Ne.symm ne]
  10975. · have no := absent_other role (Ne.symm e)
  10976. have no' : a∉mutableCell bits j := by cases b : bits j <;> simpa [roles,mutableCell,b,or_comm] using no
  10977. simp [List.count_eq_zero.mpr no',e]
  10978. rw [weighted _ _ _ _ _ ct,range_count,Nat.one_mul]
  10979. theorem port_count {h w : Nat} (size : 1<w*h) (q i a : Nat) (role : a∈roles i) :
  10980. (letters (matching h w q)).count a=if i<w*h then 2 else 0 := by
  10981. rw [letters,count_role _ i a (cell_role role),count_phase]
  10982. by_cases e : i<w*h
  10983. · simp [e,count_one (matching_unique size q) ((matching_cells size q i).mpr e)]
  10984. · simp [e,List.count_eq_zero.mpr (fun m=> e ((matching_cells size q i).mp m))]
  10985. private theorem select_roles (s : List Nat) (i : Nat) :
  10986. select (roles i) (s.flatMap roles)=(List.replicate (s.count i) (roles i)).flatten := by
  10987. induction s with
  10988. | nil => rfl
  10989. | cons a s ih =>
  10990. rw [List.flatMap_cons,select_append,ih]
  10991. by_cases e : a=i
  10992. · subst a; simp [roles,select,List.count_cons,List.replicate_succ]
  10993. · have no := select_nil (roles i) (roles a) (fun _ h => absent_other h e)
  10994. simp [no,List.count_cons,e,Ne.symm e]
  10995. theorem match_projection {h w : Nat} (size : 1<w*h) (q i : Nat) (lt : i<w*h) :
  10996. select (roles i) (letters (matching h w q))=roles i++roles i := by
  10997. rw [letters,select_roles,count_phase,count_one (matching_unique size q) ((matching_cells size q i).mpr lt)]
  10998. simp
  10999. private theorem count_uniform (xs : List Nat) (a v : Nat) (f : Nat→List Nat)
  11000. (each : ∀ j∈xs,(f j).count a=v) : (xs.flatMap f).count a=xs.length*v := by
  11001. induction xs with
  11002. | nil => simp
  11003. | cons j t ih =>
  11004. simp [List.flatMap_cons,List.count_append,each j List.mem_cons_self,
  11005. ih (fun x hx=>each x (List.mem_cons_of_mem _ hx)),Nat.add_mul,Nat.add_comm]
  11006. theorem chunks_count {h w : Nat} (size : 1<w*h) (q i a : Nat) (role : a∈roles i) :
  11007. (portChunks h w q).count a=q*(if i<w*h then 2 else 0) := by
  11008. unfold portChunks
  11009. rw [count_uniform _ _ _ _ (fun j _ => port_count size j i a role),List.length_range]
  11010. theorem suffix_count {h w k : Nat} (tag : Nat→List Bool) (i a : Nat) (role : a∈roles i) :
  11011. (suffix h w k tag).count a=if i<w*h then k+1 else 0 := by
  11012. unfold suffix
  11013. have ct (j : Nat) : (tagPhase (w*h) tag j).count a = if i<w*h then 1 else 0 := mutable_counts i a role _ _
  11014. rw [List.count_append,count_uniform (List.range k) a _ (tagPhase (w*h) tag) (fun j _ => ct j),
  11015. List.length_range,count_role _ i a (cell_role role)]
  11016. by_cases e : i<w*h
  11017. · simp [e,count_one (columns_unique h w) ((columns_cells h w i).mpr e)]
  11018. · simp [e,List.count_eq_zero.mpr (fun m=> e ((columns_cells h w i).mp m))]
  11019. theorem word_count {h w k : Nat} (size : 1<w*h) (tag : Nat→List Bool) (bits : Nat→Bool)
  11020. (i a : Nat) (role : a∈roles i) :
  11021. (word (w*h) (middle h w k tag) (tail (w*h)) bits).count a=if i<w*h then k+16 else 0 := by
  11022. simp only [word,middle,tail,List.count_append,private_counts i a role,chunks_count size 5 i a role,
  11023. suffix_count tag i a role,mutable_counts i a role]
  11024. split <;> omega
  11025. theorem capped {h w k : Nat} (size : 1<w*h) (tag : Nat→List Bool) (bits : Nat→Bool) :
  11026. P455Quotient.Cap (k+16) (word (w*h) (middle h w k tag) (tail (w*h)) bits) := by
  11027. intro a
  11028. have role : a∈roles (a/2) := by simp only [roles,List.mem_cons,List.not_mem_nil,or_false,owner,mate]; omega
  11029. rw [word_count size tag bits _ a role]
  11030. split <;> omega
  11031. end P455PaddedWord
  11032. end
  11033. /- Begin Problem455SingletonEvaluation (from finite-semigroup-identity-bases). -/
  11034. section
  11035. namespace P455SingletonEvaluation
  11036. open P455Witness P455ContactLift P455CrossedSupport P455SourceFamilies P455SourceTheorem
  11037. open P455MarkedPath P455SlotSaturation P455SlotProduct P455RetainedVariant P455Compression
  11038. open P455Uncrossed P455PortReflection P455EdgeSource Problem455.Slots
  11039. abbrev W := List Nat
  11040. def Matches (n : Node) (x y : Nat) :=
  11041. (n.owner = x ∧ n.mate = y) ∨ (n.owner = y ∧ n.mate = x)
  11042. def MarksOnly (mark : Marking) (c : Certificate) :=
  11043. ∀ a b, mark a b → ∃ s : Bool, Matches (markedRecord c s) a b
  11044. theorem designated_marks (c : Certificate) : MarksOnly (sourceMarks id c) c := by
  11045. intro a b hit
  11046. cases c with
  11047. | slot s => exact ⟨false,.inl ⟨hit.1.symm,hit.2.symm⟩⟩
  11048. | functionality f => exact ⟨false,.inl ⟨hit.1.symm,hit.2.symm⟩⟩
  11049. | edge e =>
  11050. rcases hit with h|h
  11051. · exact ⟨false,.inl ⟨h.1.symm,h.2.symm⟩⟩
  11052. · exact ⟨true,.inl ⟨h.1.symm,h.2.symm⟩⟩
  11053. theorem pick_cross {c h mark x y} (only : MarksOnly mark c)
  11054. (hit : ∃ a ∈ h x, ∃ b ∈ h y, mark a b ∨ mark b a) :
  11055. ∃ s, Crosses (markedRecord c s) h x y := by
  11056. obtain ⟨a,ax,b,by',ab|ba⟩ := hit
  11057. · obtain ⟨s,⟨p,q⟩|⟨p,q⟩⟩ := only a b ab
  11058. · exact ⟨s,.inl ⟨p ▸ ax,q ▸ by'⟩⟩
  11059. · exact ⟨s,.inr ⟨p ▸ by',q ▸ ax⟩⟩
  11060. · obtain ⟨s,⟨p,q⟩|⟨p,q⟩⟩ := only b a ba
  11061. · exact ⟨s,.inr ⟨p ▸ by',q ▸ ax⟩⟩
  11062. · exact ⟨s,.inl ⟨p ▸ ax,q ▸ by'⟩⟩
  11063. def Violation (r : Nat) (allow : Tag → Prop) (ts : Tiles) (w : W) (x y : Nat) :=
  11064. ∃ (c : Certificate) (s : Bool), Matches (markedRecord c s) x y ∧
  11065. Holds r allow (sourceMarks id c) w (c.query r ts)
  11066. theorem changed_anchor (c : Certificate) (s : Bool) (d : Nat → Nat) :
  11067. markedRecord (transferred d c) s = sendNode d (markedRecord c s) := by
  11068. cases c <;> cases s <;> rfl
  11069. theorem reindexed_marks (c : Certificate) (d : Nat → Nat) :
  11070. sourceMarks id (transferred d c) = sourceMarks d c := by cases c <;> rfl
  11071. theorem compare_uniform {r allow mark T} (capT : P455Quotient.Cap r T)
  11072. (ts : Tiles) (c : Certificate) (only : MarksOnly mark c)
  11073. (tester : Holds r allow mark T (c.query r ts))
  11074. (f : P455Closure.Frame Nat) (l k : W) (x y : Nat) (hp : f.p = [x]) (hq : f.q = [y])
  11075. (fv : f.Valid r allow noMark) (capF : P455Closure.Cap r (side f l k false))
  11076. (u₀ : W) (uf : UniformSlots r allow mark u₀ x y)
  11077. (path : P455Quotient.Walk (P455Closure.Move r allow noMark) u₀ (side f l k false))
  11078. (cmp : Compressed r (side f l k false))
  11079. (val : Nat → P455Quotient.Q (rules r allow mark) T)
  11080. (diff : P455Quotient.eval (rules r allow mark) capT val (ruleWord r allow noMark (side f l k false) x y) ≠
  11081. P455Quotient.eval (rules r allow mark) capT val (ruleWord r allow noMark (side f l k true) x y)) :
  11082. ∃ b : Bool, Violation r allow ts (side f l k b) x y := by
  11083. let u := side f l k
  11084. let R := rules r allow mark
  11085. let names := retained r allow noMark (u false) x y
  11086. have mv : P455Closure.Move r allow noMark (u false) (u true) := ⟨f,false,l,k,fv,rfl,rfl,capF⟩
  11087. have cbit (b : Bool) : P455Closure.Cap r (u b) := by cases b; exact capF; exact mv.cap_right
  11088. have fc (b : Bool) : ClosedFlip r allow (u b) x y := ⟨f,b,l,k,hp,hq,fv,rfl⟩
  11089. obtain ⟨hr,cx,cy,_⟩ := flip_counts capF (fc false)
  11090. have hi : 0 < r := by omega
  11091. have hx : x ∈ names := mem_retained.mpr ⟨List.count_pos_iff.mp (cx.symm ▸ hi),.inl (.inl (P455Paths.near_self ..))⟩
  11092. have hy : y ∈ names := mem_retained.mpr ⟨List.count_pos_iff.mp (cy.symm ▸ hi),.inl (.inr (P455Paths.near_self ..))⟩
  11093. obtain ⟨g,L,K,gp,gq,gv,both,_⟩ := P455CompressedFrame.canonical_pair f l k names hx hy hp hq fv false capF
  11094. have perm (b : Bool) : names.Perm (retained r allow noMark (u b) x y) := by
  11095. cases b
  11096. · exact List.Perm.refl _
  11097. · exact same_retained mv x y
  11098. have eq0 (b : Bool) : ruleWord r allow noMark (u b) x y = side g L K b :=
  11099. (small_congr_names _ (perm b).symm).trans (both b)
  11100. have eqm (b : Bool) : ruleWord r allow mark (u b) x y = side g L K b := by
  11101. unfold ruleWord; rw [retained_remark (mark' := noMark)]; exact eq0 b
  11102. have neq : P455Quotient.eval R capT val (side g L K false) ≠ P455Quotient.eval R capT val (side g L K true) := by
  11103. rw [← eq0,← eq0]; exact diff
  11104. obtain ⟨b,live,⟨h,represent⟩,_⟩ := difference_live_representatives capT g L K val neq
  11105. have reps := fun a ha => (represent a ha).2
  11106. have nd : P455Quotient.eval R capT val (side g L K b) ≠ P455Quotient.eval R capT val (side g L K (!b)) := by
  11107. cases b
  11108. · exact neq
  11109. · exact Ne.symm neq
  11110. obtain ⟨s,cs⟩ := pick_cross only (difference_crosses capT g L K b x y gp gq gv val h reps nd)
  11111. let v := ruleWord r allow mark (u b) x y
  11112. have repv : ∀ a ∈ v, P455Quotient.ofWord R T (h a) = val a := by rw [show v = _ from eqm b]; exact reps
  11113. have livev : P455Quotient.eval R capT val v ≠ P455Quotient.zero R T := by rw [show v = _ from eqm b]; exact live
  11114. have pb : P455Quotient.Walk (P455Closure.Move r allow noMark) u₀ (u b) := by
  11115. cases b; exact path; exact .snoc path mv
  11116. have cb : Compressed r (u b) := by
  11117. cases b
  11118. · exact cmp
  11119. · intro a z link
  11120. exact cmp a z ((Problem455BlockBridge.move_link mv a z).mpr link)
  11121. obtain ⟨_,_,_,_,_,_,_,_,_,_,read,_⟩ := crossed_gadget capT (u b) (cbit b) x y (fc b)
  11122. (uniform_variant pb uf) h val repv livev ts c tester s false cs
  11123. let names' := retained r allow mark (u b) x y
  11124. obtain ⟨_,ax,ay,_⟩ := flip_counts (cbit b) (fc b)
  11125. have eqNames : names.Perm names' := by
  11126. change names.Perm (retained r allow mark (u b) x y)
  11127. rw [retained_remark (mark' := noMark)]; exact perm b
  11128. have xcnt : v.count x = r := (counts_retained _ _ _ (eqNames.mem_iff.mp hx)).trans ax
  11129. have ycnt : v.count y = r := (counts_retained _ _ _ (eqNames.mem_iff.mp hy)).trans ay
  11130. have ev := P455Quotient.eval_rep R capT val v h repv
  11131. have good := (P455Quotient.nonzero_iff R).mp (ev ▸ livev)
  11132. have cap := P455Quotient.good_cap R capT good
  11133. let d := donor v h r
  11134. refine ⟨b,transferred d c,s,?_,?_⟩
  11135. · rw [changed_anchor]
  11136. rcases cs with ⟨o,m⟩|⟨o,m⟩
  11137. · exact .inl ⟨donor_eq hi cap ⟨xcnt,o⟩,donor_eq hi cap ⟨ycnt,m⟩⟩
  11138. · exact .inr ⟨donor_eq hi cap ⟨ycnt,o⟩,donor_eq hi cap ⟨xcnt,m⟩⟩
  11139. · rw [reindexed_marks]; exact read cb
  11140. theorem compare {r allow mark T} (capT : P455Quotient.Cap r T)
  11141. (ts : Tiles) (c : Certificate) (only : MarksOnly mark c)
  11142. (tester : Holds r allow mark T (c.query r ts))
  11143. (f : P455Closure.Frame Nat) (l k : W) (x y : Nat) (hp : f.p = [x]) (hq : f.q = [y])
  11144. (fv : f.Valid r allow noMark) (capF : P455Closure.Cap r (side f l k false))
  11145. (u₀ w : W) (cap₀ : P455Closure.Cap r u₀) (identity : Identity r allow u₀ w)
  11146. (flip₀ : ClosedFlip r allow u₀ x y) (changed : select [x,y] u₀ ≠ select [x,y] w)
  11147. (path : P455Quotient.Walk (P455Closure.Move r allow noMark) u₀ (side f l k false))
  11148. (cmp : Compressed r (side f l k false))
  11149. (val : Nat → P455Quotient.Q (rules r allow mark) T)
  11150. (diff : P455Quotient.eval (rules r allow mark) capT val (ruleWord r allow noMark (side f l k false) x y) ≠
  11151. P455Quotient.eval (rules r allow mark) capT val (ruleWord r allow noMark (side f l k true) x y)) :
  11152. ∃ b : Bool, Violation r allow ts (side f l k b) x y :=
  11153. compare_uniform capT ts c only tester f l k x y hp hq fv capF u₀
  11154. (uniform_of_identity cap₀ identity flip₀ changed) path cmp val diff
  11155. end P455SingletonEvaluation
  11156. end
  11157. /- Begin Problem455GridAssembly (from finite-semigroup-identity-bases). -/
  11158. section
  11159. namespace P455GridAssembly
  11160. open P455GridRows P455Witness Problem455.Slots
  11161. abbrev W := List Nat
  11162. structure Rectangle (allow : Tag → Prop) (ts : Tiles) where
  11163. height : Nat
  11164. width : Nat
  11165. tile : Nat → Nat → Tag
  11166. allowed : ∀ i j, i ≤ height → j ≤ width → allow (tile i j)
  11167. horiz : ∀ i j, i ≤ height → j < width → ts.horizontal (tile i j) (tile i (j+1))
  11168. vert : ∀ i j, i < height → j ≤ width → ts.vertical (tile i j) (tile (i+1) j)
  11169. left : ∀ i j, i ≤ height → j ≤ width → (ts.left (tile i j) = true ↔ j=0)
  11170. right : ∀ i j, i ≤ height → j ≤ width → (ts.right (tile i j) = true ↔ j=width)
  11171. top : ∀ i j, i ≤ height → j ≤ width → (ts.top (tile i j) = true ↔ i=0)
  11172. bottom : ∀ i j, i ≤ height → j ≤ width → (ts.bottom (tile i j) = true ↔ i=height)
  11173. structure Row {r : Nat} {allow : Tag → Prop} {mark : Marking} {w : W} (ts : Tiles)
  11174. (c : Nat → EdgeCertificate) (s n : Nat) (odd : Bool) : Prop where
  11175. parity : ∀ j, j≤n → ts.oddRow (c (s+column n odd j)).a.tag=odd
  11176. left : ts.left (c (s+column n odd 0)).a.tag=true
  11177. right : ts.right (c (s+column n odd n)).a.tag=true
  11178. links : ∀ j, j<n → Holds r allow mark w
  11179. (rightward ts (c (s+column n odd j)).a (c (s+column n odd (j+1))).a)
  11180. private theorem min_bounded (p : Nat → Prop) (j : Nat) (yes : p j) :
  11181. ∃ a, p a ∧ ∀ b, b<a → ¬ p b := by
  11182. induction j using Nat.strongRecOn with
  11183. | ind j ih =>
  11184. by_cases e : ∃ k, k < j ∧ p k
  11185. · obtain ⟨k,lt,ok⟩ := e
  11186. exact ih k lt ok
  11187. · exact ⟨j,yes,fun b lt pb => e ⟨b,lt,pb⟩⟩
  11188. private theorem right_step {r allow mark w ts} (c : Nat → EdgeCertificate)
  11189. (arr : ∀ i, Arrow r allow mark w ts (c i)) (cont : ∀ i,(c i).b=(c (i+1)).a)
  11190. (i : Nat) (p : ts.oddRow (c i).a.tag=false) (q : ts.right (c i).a.tag=false) :
  11191. Holds r allow mark w (rightward ts (c i).a (c (i+1)).a) := by
  11192. have ending : endOfRow ts (c i).a=false := by simp [endOfRow,p,q]
  11193. have hs := (arr i).2.2.2
  11194. simp only [chosenSuccessor,ending,Bool.false_and,Bool.false_eq_true,if_false,p] at hs
  11195. have h := (arr i).2.2.1.1
  11196. simp only [q,Bool.not_false,flagQ,if_true] at h
  11197. rw [← cont, ← hs.1]
  11198. exact h
  11199. private theorem first_row {r allow mark w ts} (law : Laws ts) (c : Nat → EdgeCertificate)
  11200. (arr : ∀ i, Arrow r allow mark w ts (c i)) (cont : ∀ i,(c i).b=(c (i+1)).a)
  11201. (s : Nat) (left : ts.left (c s).a.tag=true) (par : ts.oddRow (c s).a.tag=false) :
  11202. ∃ n, @Row r allow mark w ts c s n false := by
  11203. obtain ⟨j,ret⟩ := later_return c arr cont s
  11204. have parity (a) (before : ∀ k, k<a → ts.right (c (s+k)).a.tag≠true) :
  11205. ts.oddRow (c (s+a)).a.tag=false := by
  11206. induction a with
  11207. | zero => simpa using par
  11208. | succ a ih =>
  11209. have p := ih (fun k lt => before k (by omega))
  11210. have q : ts.right (c (s+a)).a.tag=false := by
  11211. have n := before a (by omega)
  11212. cases b : ts.right (c (s+a)).a.tag <;> simp_all
  11213. have step := right_step c arr cont (s+a) p q
  11214. exact (law.horiz _ _ step.1).2.2.2.2.1.symm.trans p
  11215. have hasRight : ∃ a, ts.right (c (s+a)).a.tag=true := by
  11216. apply Classical.byContradiction; intro missing
  11217. have noR (a) : ts.right (c (s+a)).a.tag≠true := fun ok => missing ⟨a,ok⟩
  11218. have p := parity j (fun k _ => noR k)
  11219. have q : ts.right (c (s+j)).a.tag=false := by
  11220. cases b : ts.right (c (s+j)).a.tag <;> simp_all
  11221. simp [Return,endOfRow,p,q] at ret
  11222. obtain ⟨a,ha⟩ := hasRight
  11223. obtain ⟨n,last,prior⟩ := min_bounded (fun i => ts.right (c (s+i)).a.tag=true) a ha
  11224. refine ⟨n,?_,?_,?_,?_⟩
  11225. · intro k le; exact parity k (fun b lt => prior b (by omega))
  11226. · simpa [column] using left
  11227. · exact last
  11228. · intro k lt
  11229. have p := parity k (fun b lb => prior b (by omega))
  11230. have q : ts.right (c (s+k)).a.tag=false := by
  11231. have off := prior k lt
  11232. cases b : ts.right (c (s+k)).a.tag <;> simp_all
  11233. exact right_step c arr cont (s+k) p q
  11234. private theorem row_const (n : Nat) (f : Nat → Bool) (step : ∀ j, j<n → f j = f (j+1)) :
  11235. ∀ j, j≤n → f j = f 0 := by
  11236. intro j
  11237. induction j with
  11238. | zero => simp
  11239. | succ j ih => intro le; exact (step j (by omega)).symm.trans (ih (by omega))
  11240. private theorem next_row {r allow mark w ts} (law : Laws ts) (c : Nat → EdgeCertificate)
  11241. (arr : ∀ i, Arrow r allow mark w ts (c i)) (cont : ∀ i,(c i).b=(c (i+1)).a)
  11242. (funct : ∀ i, Functional r allow mark w ts (c i).a)
  11243. {s n odd} (row : @Row r allow mark w ts c s n odd)
  11244. (nonbottom : ∀ j, j≤n → ts.bottom (c (s+column n odd j)).a.tag=false) :
  11245. @Row r allow mark w ts c (s+n+1) n (!odd) ∧
  11246. ∀ j, j≤n → Holds r allow mark w
  11247. (downward ts (c (s+column n odd j)).a (c ((s+n+1)+column n (!odd) j)).a) := by
  11248. let ix (j : Nat) := s+column n odd j
  11249. have tr := advance_row law c arr cont funct ix n odd row.links nonbottom row.parity row.left row.right
  11250. have en : ix (column n (!odd) 0)=s+n := by cases odd <;> simp [ix,column]
  11251. simp only [en] at tr
  11252. obtain ⟨vs,hs⟩ := lower_row law c arr funct ix n row.links nonbottom
  11253. have down (j : Nat) (le : j≤n) : Holds r allow mark w
  11254. (downward ts (c (ix j)).a (c ((s+n+1)+column n (!odd) j)).a) := by
  11255. rw [tr j le]; exact vs j le
  11256. refine ⟨⟨?_,?_,?_,?_⟩,down⟩
  11257. · intro j le
  11258. exact (law.vert _ _ (down j le).1).2.2.2.2.2.trans (congrArg Bool.not (row.parity _ le))
  11259. · exact (law.vert _ _ (down 0 (by omega)).1).2.2.1.trans row.left
  11260. · exact (law.vert _ _ (down n (by omega)).1).2.2.2.1.trans row.right
  11261. · intro j lt; rw [tr j (by omega),tr (j+1) (by omega)]; exact hs _ lt
  11262. /-- A suffix of a rectangle indexed by its specified first row. Only this
  11263. first row may be top. Its actual top flag is supplied by the trace. -/
  11264. private structure Strip (allow : Tag → Prop) (ts : Tiles) (n : Nat) (first : Nat → Tag) where
  11265. h : Nat
  11266. t : Nat → Nat → Tag
  11267. head : ∀ j, j≤n → t 0 j=first j
  11268. ok : ∀ i j, i≤h → j≤n → allow (t i j)
  11269. horizontal : ∀ i j, i≤h → j<n → ts.horizontal (t i j) (t i (j+1))
  11270. vertical : ∀ i j, i<h → j≤n → ts.vertical (t i j) (t (i+1) j)
  11271. l : ∀ i j, i≤h → j≤n → (ts.left (t i j)=true ↔ j=0)
  11272. r : ∀ i j, i≤h → j≤n → (ts.right (t i j)=true ↔ j=n)
  11273. b : ∀ i j, i≤h → j≤n → (ts.bottom (t i j)=true ↔ i=h)
  11274. noTop : ∀ i j, 0<i → i≤h → j≤n → ts.top (t i j)=false
  11275. private theorem build {r allow mark w ts} (law : Laws ts) (c : Nat → EdgeCertificate)
  11276. (arr : ∀ i, Arrow r allow mark w ts (c i)) (cont : ∀ i,(c i).b=(c (i+1)).a)
  11277. (funct : ∀ i, Functional r allow mark w ts (c i).a)
  11278. (J : Nat) (ret : Return ts (c J)=true) (fuel : Nat) :
  11279. ∀ s n odd, s≤J → J-s≤fuel → @Row r allow mark w ts c s n odd →
  11280. Nonempty (Strip allow ts n (fun j => (c (s+column n odd j)).a.tag)) := by
  11281. induction fuel using Nat.strongRecOn with
  11282. | ind fuel ih =>
  11283. intro s n odd bound time row
  11284. let tag (j : Nat) := (c (s+column n odd j)).a.tag
  11285. have ok (j : Nat) : allow (tag j) := (arr _).1.2.2.1
  11286. have H (j) (lt : j<n) : ts.horizontal (tag j) (tag (j+1)) := (row.links j lt).1
  11287. have L (j) (le : j≤n) : ts.left (tag j)=true ↔ j=0 := by
  11288. cases j with
  11289. | zero => simp [tag,row.left]
  11290. | succ j => simp [(law.horiz _ _ (H j (by omega))).2.1]
  11291. have R (j) (le : j≤n) : ts.right (tag j)=true ↔ j=n := by
  11292. by_cases eq : j=n
  11293. · subst j; simp [tag,row.right]
  11294. · have lt : j<n := by omega
  11295. simp [(law.horiz _ _ (H j lt)).1,eq]
  11296. have B := row_const n (fun j => ts.bottom (tag j)) (fun j lt => (law.horiz _ _ (H j lt)).2.2.2.1)
  11297. cases bot : ts.bottom (tag 0) with
  11298. | true =>
  11299. refine ⟨⟨0,fun _ => tag,fun _ _ => rfl,fun _ j _ _ => ok j,
  11300. fun _ j _ lt => H j lt,fun _ _ lt _ => by omega,fun _ j _ => L j,
  11301. fun _ j _ => R j,?_,fun _ _ pos le _ => by omega⟩⟩
  11302. intro i j il jl
  11303. have bi := (B j jl).trans bot
  11304. simp [bi,Nat.le_zero.mp il]
  11305. | false =>
  11306. have nonbottom (j : Nat) (le : j≤n) : ts.bottom (tag j)=false := (B j le).trans bot
  11307. have nextLe : s+n+1≤J := by
  11308. apply Classical.byContradiction; intro short
  11309. have small : J-s≤n := by omega
  11310. let j := column n odd (J-s)
  11311. have inRow : j≤n := by cases odd <;> simp [j,column,small,Nat.sub_le]
  11312. have atJ : s+column n odd j=J := by cases odd <;> simp [j,column] <;> omega
  11313. have off := nonbottom j inRow
  11314. change ts.bottom (c (s+column n odd j)).a.tag=false at off
  11315. rw [atJ] at off
  11316. simp [Return,off] at ret
  11317. obtain ⟨low,V⟩ := next_row law c arr cont funct row nonbottom
  11318. obtain ⟨below⟩ := ih (J-(s+n+1)) (by omega) (s+n+1) n (!odd) nextLe (by omega) low
  11319. let t : Nat → Nat → Tag
  11320. | 0 => tag
  11321. | i+1 => below.t i
  11322. refine ⟨⟨below.h+1,t,fun _ _ => rfl,?_,?_,?_,?_,?_,?_,?_⟩⟩
  11323. · intro i j le jl; cases i with
  11324. | zero => exact ok j
  11325. | succ i => exact below.ok i j (by omega) jl
  11326. · intro i j le jl; cases i with
  11327. | zero => exact H j jl
  11328. | succ i => exact below.horizontal i j (by omega) jl
  11329. · intro i j lt jl; cases i with
  11330. | zero =>
  11331. change ts.vertical (tag j) (below.t 0 j)
  11332. rw [below.head _ jl]; exact (V j jl).1
  11333. | succ i => exact below.vertical i j (by omega) jl
  11334. · intro i j le jl; cases i with
  11335. | zero => exact L j jl
  11336. | succ i => exact below.l i j (by omega) jl
  11337. · intro i j le jl; cases i with
  11338. | zero => exact R j jl
  11339. | succ i => exact below.r i j (by omega) jl
  11340. · intro i j le jl; cases i with
  11341. | zero => change ts.bottom (tag j)=true ↔ _; simp [nonbottom j jl]
  11342. | succ i => exact (below.b i j (by omega) jl).trans (by omega)
  11343. · intro i j pos le jl
  11344. cases i with
  11345. | zero => omega
  11346. | succ i =>
  11347. cases i with
  11348. | zero =>
  11349. change ts.top (below.t 0 j)=false
  11350. rw [below.head _ jl]; exact (law.vert _ _ (V j jl).1).2.1
  11351. | succ i => exact below.noTop _ j (by omega) (by omega) jl
  11352. /-- Any indefinitely continued trace of actual arrows, with directional
  11353. functionality at each visited source, gives a positive legal rectangle.
  11354. The hypotheses only concern the trace in the original word. -/
  11355. theorem rectangle_of_trace {r allow mark w ts} (law : Laws ts) (c : Nat → EdgeCertificate)
  11356. (arr : ∀ i, Arrow r allow mark w ts (c i)) (cont : ∀ i,(c i).b=(c (i+1)).a)
  11357. (funct : ∀ i, Functional r allow mark w ts (c i).a) : Nonempty (Rectangle allow ts) := by
  11358. obtain ⟨k,ret⟩ := later_return c arr cont 0
  11359. simp only [Nat.zero_add] at ret
  11360. have start := return_target _ (arr k) ret
  11361. rw [cont] at start
  11362. let s := k+1
  11363. obtain ⟨n,row⟩ := first_row law c arr cont s start.2.1 start.2.2.1
  11364. obtain ⟨off,ending⟩ := later_return c arr cont s
  11365. have tops := row_const n (fun j => ts.top (c (s+j)).a.tag)
  11366. (fun j lt => (law.horiz _ _ (row.links j lt).1).2.2.1)
  11367. obtain ⟨box⟩ := build law c arr cont funct (s+off) ending off s n false (by omega) (by omega) row
  11368. refine ⟨⟨box.h,n,box.t,box.ok,box.horizontal,box.vertical,box.l,box.r,?_,box.b⟩⟩
  11369. intro i j le jl
  11370. cases i with
  11371. | zero =>
  11372. rw [box.head j jl]
  11373. have same := (tops j jl).trans (by simpa [s] using start.1)
  11374. simpa [column] using (show ts.top (c (s+j)).a.tag=true ↔ 0=0 from by simp [same])
  11375. | succ i => simp [box.noTop _ j (by omega) le jl]
  11376. end P455GridAssembly
  11377. end
  11378. /- Begin Problem455PaddedWordSlots (from finite-semigroup-identity-bases). -/
  11379. section
  11380. namespace P455PaddedWord
  11381. open P455PaddedMatchings P455PaddedPorts P455RectangleRank Problem455.Slots P455Witness
  11382. def text (h w k : Nat) (tag : Nat→Tag) (bit : Nat→Bool) := word (w*h) (middle h w k tag) (tail (w*h)) bit
  11383. theorem range_cut {i n : Nat} (lt : i<n) :
  11384. List.range n=List.range i ++ i :: List.range' (i+1) (n-(i+1)) := by
  11385. have app := List.range'_append_1 (s:=0) (m:=i+1) (n:=n-(i+1))
  11386. rw [show i+1+(n-(i+1))=n by omega] at app
  11387. simpa [←List.range_eq_range',List.range_succ,List.append_assoc] using app.symm
  11388. theorem phase_cut {h w k : Nat} (tag : Nat→Tag) (bits : Nat→Bool) (p : Fin 5) :
  11389. ∃ post, text h w k tag bits=
  11390. (((List.range (w*h)).flatMap privateCell) ++ portChunks h w p.val) ++ letters (matching h w p.val) ++ post := by
  11391. let rest := (List.range' (p.val+1) (5-(p.val+1))).flatMap fun a=>letters (matching h w a)
  11392. refine ⟨rest ++ suffix h w k tag ++ (List.range (w*h)).flatMap (mutableCell bits) ++ tail (w*h),?_⟩
  11393. have e : portChunks h w 5 = portChunks h w p.val ++ letters (matching h w p.val) ++ rest := by
  11394. unfold portChunks
  11395. conv => lhs; rw [range_cut p.isLt]
  11396. simp [rest,List.flatMap_append,List.flatMap_cons,List.append_assoc]
  11397. simp [text,word,middle,e,List.append_assoc]
  11398. theorem phase_index {h w : Nat} (size : 1<w*h) (p : Fin 5) (i a : Nat)
  11399. (lt : i<w*h) (role : a∈roles i) :
  11400. (((List.range (w*h)).flatMap privateCell) ++ portChunks h w p.val).count a=3+2*p.val := by
  11401. simp only [List.count_append,private_counts i a role,chunks_count size p.val i a role,if_pos lt]; omega
  11402. theorem private_cut {h w k : Nat} (tag : Nat→Tag) (bits : Nat→Bool) {i : Nat} (lt : i<w*h) :
  11403. ∃ post,text h w k tag bits=(List.range i).flatMap privateCell ++ privateCell i ++ post := by
  11404. let rest := (List.range' (i+1) (w*h-(i+1))).flatMap privateCell
  11405. refine ⟨rest++middle h w k tag++(List.range (w*h)).flatMap (mutableCell bits)++tail (w*h),?_⟩
  11406. have e : (List.range (w*h)).flatMap privateCell=(List.range i).flatMap privateCell ++ privateCell i ++ rest := by
  11407. conv => lhs; rw [range_cut lt]
  11408. simp [rest,List.flatMap_append,List.flatMap_cons,List.append_assoc]
  11409. simp [text,word,e,List.append_assoc]
  11410. theorem small_slots {h w k : Nat} (size : 1<w*h) (tag : Nat→Tag) (bits : Nat→Bool) :
  11411. ∀ a∈text h w k tag bits, ∀ d, slotStart d → Covered (text h w k tag bits) a d := by
  11412. intro a mem d sl
  11413. let i := a/2
  11414. have role : a∈roles i := by simp only [roles,List.mem_cons,List.not_mem_nil,or_false,owner,mate,i]; omega
  11415. have lt : i<w*h := by
  11416. have positive := List.count_pos_iff.mpr mem
  11417. rw [text,word_count size tag bits i a role] at positive
  11418. split at positive <;> omega
  11419. by_cases early : d=0 ∨ d=1
  11420. · obtain ⟨post,cut⟩ := private_cut tag bits lt
  11421. rw [cut]; exact private_slot_bound _ _ i a d role (by simp [private_counts i a role]) early
  11422. · have place : ∃ p : Fin 5, d=3+2*p.val := by
  11423. unfold slotStart at sl
  11424. rcases sl with e|e|e|e|e|e|e
  11425. · exact (early (.inl e)).elim
  11426. · exact (early (.inr e)).elim
  11427. · exact ⟨0,e⟩
  11428. · exact ⟨1,e⟩
  11429. · exact ⟨2,e⟩
  11430. · exact ⟨3,e⟩
  11431. · exact ⟨4,e⟩
  11432. obtain ⟨p,rfl⟩ := place
  11433. obtain ⟨post,cut⟩ := phase_cut tag bits p
  11434. rw [cut]; exact matching_slot_bound (matching_unique size _) i a _ role ((matching_cells size _ _).mpr lt)
  11435. (phase_index size p i a lt role)
  11436. def node (tag : Nat→Tag) (i : Nat) : Node := ⟨owner i,mate i,tag i⟩
  11437. theorem port_iff {h w k : Nat} (size : 1<w*h) (tag : Nat→Tag) (bits : Nat→Bool)
  11438. (allow : Tag→Prop) (mark : Marking) (p : Fin 5) {i j : Nat} (ne : i≠j) (li : i<w*h) (lj : j<w*h) :
  11439. let H := Holds (k+16) allow mark (text h w k tag bits)
  11440. H (orientedPort p.val (node tag i) (node tag j)) ↔ H (typedNode (node tag i)) ∧
  11441. H (typedNode (node tag j)) ∧ H (earlyDisjoint (roles i) (roles j)) ∧ Block.pair i j∈matching h w p.val := by
  11442. obtain ⟨post,cut⟩ := phase_cut tag bits p
  11443. dsimp only
  11444. rw [cut]
  11445. exact oriented_port_iff (by omega) allow mark p _ _ ne (matching_unique size _) ((matching_cells size _ _).mpr li)
  11446. ((matching_cells size _ _).mpr lj) (fun a m=> (List.mem_append.mp m).elim
  11447. (fun x=>phase_index size p i a li x) (fun x=>phase_index size p j a lj x))
  11448. end P455PaddedWord
  11449. end
  11450. /- Begin Problem455GuardProduct (from finite-semigroup-identity-bases). -/
  11451. section
  11452. namespace P455GuardProduct
  11453. open P455Witness P455SlotProduct P455SourceFamilies P455CrossedSupport
  11454. open P455PortReflection P455SlotSaturation P455DefectRename P455FirstRewrite
  11455. open Problem455.Slots
  11456. abbrev W := List Nat
  11457. inductive Guard where
  11458. | slot (s : SlotCertificate)
  11459. | func (f : FunctionalityCertificate)
  11460. def Guard.anchor : Guard → Node | .slot s => s.anchor | .func f => f.anchor
  11461. def Guard.bit : Guard → Bool | .slot s => s.bit | .func f => f.bit
  11462. def Guard.isFunc : Guard → Bool | .slot _ => false | .func _ => true
  11463. def Guard.query (g : Guard) (r : Nat) (ts : Tiles) : Query := match g with
  11464. | .slot s => s.query r | .func f => f.query ts
  11465. def Guard.withBit (g : Guard) (b : Bool) : Guard := match g with
  11466. | .slot s => .slot {s with bit := b} | .func f => .func {f with bit := b}
  11467. def width (isFunc : Bool) : Nat := if isFunc then 8 else 43
  11468. def words (r : Nat) (kind : Bool) := Problem455Finite.wordsUpTo (List.range (width kind)) (width kind*r)
  11469. structure Index (r : Nat) (allow : Tag → Prop) (ts : Tiles) where
  11470. kind : Bool
  11471. pos : Fin (words r kind).length
  11472. a : Fin (width kind)
  11473. b : Fin (width kind)
  11474. cap : P455Closure.Cap r ((words r kind).get pos)
  11475. accepted : ∃ g : Guard, g.isFunc = kind ∧ g.anchor.owner = a.val ∧ g.anchor.mate = b.val ∧
  11476. Holds r allow (pairMark a b) ((words r kind).get pos) (g.query r ts)
  11477. def Index.T (i : Index r allow ts) := (words r i.kind).get i.pos
  11478. def Index.R (i : Index r allow ts) := rules r allow (pairMark i.a i.b)
  11479. abbrev Carrier (r : Nat) (allow : Tag → Prop) (ts : Tiles) :=
  11480. (i : Index r allow ts) → P455Quotient.Q i.R i.T
  11481. def product (r : Nat) (allow : Tag → Prop) (ts : Tiles) : Model (Carrier r allow ts) where
  11482. op := fun u v i => P455Quotient.mul i.R i.cap (u i) (v i)
  11483. unit := fun i => P455Quotient.ofWord i.R i.T []
  11484. assoc := fun u v w => funext (fun i => P455Quotient.mul_assoc i.R i.cap (u i) (v i) (w i))
  11485. oneL := fun u => funext (fun i => (P455Quotient.unit_laws i.R i.cap (u i)).1)
  11486. oneR := fun u => funext (fun i => (P455Quotient.unit_laws i.R i.cap (u i)).2)
  11487. theorem observed {r allow ts u w} (valid : (product r allow ts).Valid u w)
  11488. (i : Index r allow ts) (h : Nat → W) :
  11489. P455Quotient.ofWord i.R i.T (u.flatMap h) = P455Quotient.ofWord i.R i.T (w.flatMap h) := by
  11490. let val : Nat → Carrier r allow ts := fun x j => P455Quotient.ofWord j.R j.T (h x)
  11491. have comp (z : W) : (product r allow ts).eval val z i = P455Quotient.ofWord i.R i.T (z.flatMap h) := by
  11492. induction z with
  11493. | nil => rfl
  11494. | cons a z ih =>
  11495. change P455Quotient.mul i.R i.cap (val a i) _ = _
  11496. rw [ih]; rfl
  11497. exact (comp u).symm.trans ((congrFun (valid val) i).trans (comp w))
  11498. theorem test_projects {r allow ts u w} (valid : (product r allow ts).Valid u w)
  11499. (keep : W) {x y : Nat} (ho : x ∈ keep) (hm : y ∈ keep)
  11500. (g : Guard) (n : Bool) (kind : g.isFunc = n) (len : keep.length ≤ width n)
  11501. (xa : g.anchor.owner = keep.idxOf x) (yb : g.anchor.mate = keep.idxOf y)
  11502. (capT : P455Closure.Cap r ((select keep u).map keep.idxOf))
  11503. (test : Holds r allow (markNode g.anchor) ((select keep u).map keep.idxOf) (g.query r ts)) :
  11504. select [x,y] u = select [x,y] w := by
  11505. let T := (select keep u).map keep.idxOf
  11506. have labels : ∀ a ∈ T, a < width n := by
  11507. intro a ha; obtain ⟨b,hb,rfl⟩ := List.mem_map.mp ha
  11508. exact Nat.lt_of_lt_of_le (List.idxOf_lt_length_of_mem (kept hb)) len
  11509. obtain ⟨j,eq⟩ := List.get_of_mem (Problem455Finite.covered (List.range (width n)) _ T
  11510. (capped_length _ T capT labels) (fun a ha => List.mem_range.mpr (labels a ha)))
  11511. let a : Fin (width n) := ⟨keep.idxOf x, Nat.lt_of_lt_of_le (List.idxOf_lt_length_of_mem ho) len⟩
  11512. let b : Fin (width n) := ⟨keep.idxOf y, Nat.lt_of_lt_of_le (List.idxOf_lt_length_of_mem hm) len⟩
  11513. have fm : markNode g.anchor = pairMark a b := by unfold markNode pairMark; rw [xa,yb]
  11514. let i : Index r allow ts := ⟨n,j,a,b,eq.symm ▸ capT,g,kind,xa,yb,eq.symm ▸ (fm ▸ test)⟩
  11515. have coord := observed valid i (image keep)
  11516. rw [image_word,image_word] at coord
  11517. have eqT : T = i.T := eq.symm
  11518. change P455Quotient.ofWord i.R i.T T = _ at coord
  11519. rw [eqT] at coord
  11520. have good : P455Quotient.Good i.R i.T i.T := ⟨_,.refl _,[],[],by simp⟩
  11521. have path := ((P455Quotient.same_nonzero_class i.R good).mp coord).2
  11522. have pr : select [a.val,b.val] i.T = select [a.val,b.val] ((select keep w).map keep.idxOf) :=
  11523. path.transport (P := fun z => select [a.val,b.val] i.T = select [a.val,b.val] z) rfl
  11524. (fun mv old => old.trans (mv.marked_proj _ _ ⟨rfl,rfl⟩))
  11525. rw [← eqT] at pr
  11526. change select [keep.idxOf x,keep.idxOf y] ((select keep u).map keep.idxOf) = _ at pr
  11527. rw [← binary_select_map keep u ho hm, ← binary_select_map keep w ho hm] at pr
  11528. have k (z : W) (c : Nat) (hc : c ∈ select [x,y] z) : c ∈ keep := by
  11529. rcases (by simpa using kept hc : c=x ∨ c=y) with e|e
  11530. · exact e ▸ ho
  11531. · exact e ▸ hm
  11532. have decoded := congrArg (List.map (decode keep)) pr
  11533. simpa only [decode_map (k u),decode_map (k w)] using decoded
  11534. private theorem free_all (qs : List Query) (all : ∀ q ∈ qs, markFree q = true) : markFree (allQ qs) = true := by
  11535. induction qs with
  11536. | nil => rfl
  11537. | cons q qs ih => simp [allQ,markFree,all q (by simp),ih (fun t ht => all t (by simp [ht]))]
  11538. private theorem free_sep (xs : W) : markFree (differentBlocks xs) = true := by
  11539. induction xs with
  11540. | nil => rfl
  11541. | cons a xs ih =>
  11542. have every : markFree (allQ (xs.map (Query.separate a))) = true := by
  11543. apply free_all; intro q h; obtain ⟨_,_,rfl⟩ := List.mem_map.mp h; rfl
  11544. simp [differentBlocks,markFree,ih,every]
  11545. theorem free_term (r o i : Nat) (d : SlotDefect) : markFree (terminalSlot r o i d) = true := by
  11546. cases d with
  11547. | deficient => rfl
  11548. | overflow xs =>
  11549. have terms : markFree (allQ (xs.map fun a => Query.both (.count a r) (.slot o i a))) = true := by
  11550. apply free_all; intro q h; obtain ⟨_,_,rfl⟩ := List.mem_map.mp h; rfl
  11551. simp [terminalSlot,allQ,markFree,terms,free_sep]
  11552. private theorem free_route (s : SlotCertificate) (r a : Nat) (p : List P455Paths.Step) :
  11553. markFree (route r a p (fun o => terminalSlot r o s.terminalIndex s.defect)) = true := by
  11554. induction p generalizing a with
  11555. | nil => exact free_term ..
  11556. | cons bc p ih =>
  11557. have ct : markFree (contact r a bc.1 bc.2) = true := by
  11558. cases c : bc.2 with
  11559. | record tag rev => cases rev <;> rfl
  11560. | port phase rev => rfl
  11561. simp [route,markFree,ct,ih]
  11562. def Guard.tail (g : Guard) (r : Nat) (ts : Tiles) : Query := match g with
  11563. | .slot s => allQ [.fixed (s.steps.length ≤ 6),route r (picked s) s.steps (fun o => terminalSlot r o s.terminalIndex s.defect)]
  11564. | .func f => allQ [neighbor ts f.anchor f.b f.dir,neighbor ts f.anchor f.c f.dir,
  11565. .separate (if f.distinguishMate then f.b.mate else f.b.owner) (if f.distinguishMate then f.c.mate else f.c.owner)]
  11566. theorem tail_free (g : Guard) (r : Nat) (ts : Tiles) : markFree (g.tail r ts) = true := by
  11567. cases g with
  11568. | slot s => simp [Guard.tail,allQ,markFree,free_route]
  11569. | func f => simp [Guard.tail,allQ,markFree,free_neighbor]
  11570. theorem split_query (g : Guard) (r : Nat) (ts : Tiles) (b : Bool) :
  11571. (g.withBit b).query r ts = .both (markedNode g.anchor b) (g.tail r ts) := by cases g <;> rfl
  11572. theorem replay {r allow ts u v} (path : P455Quotient.Walk (P455Closure.Move r allow noMark) u v)
  11573. (g : Guard) (ok : Holds r allow (markNode g.anchor) u (g.query r ts)) :
  11574. ∃ b, Holds r allow (markNode g.anchor) v ((g.withBit b).query r ts) := by
  11575. have same : g.withBit g.bit = g := by cases g <;> rfl
  11576. have parts := ok
  11577. rw [← same,split_query] at parts
  11578. obtain ⟨ne,length,tag,_,eq⟩ := parts.1
  11579. have recProof : Holds r allow noMark u (typedNode g.anchor) := ⟨ne,length,tag,g.bit,eq⟩
  11580. have obs := path.transport recProof (fun mv old => (query_invariant mv _).mp old)
  11581. obtain ⟨ne',length',tag',b,eq'⟩ := obs
  11582. have tail : Holds r allow noMark u (g.tail r ts) := remark (tail_free ..) parts.2
  11583. have last := path.transport tail (fun mv old => (query_invariant mv _).mp old)
  11584. refine ⟨b,?_⟩
  11585. rw [split_query]
  11586. exact ⟨⟨ne',length',tag',.inl ⟨rfl,rfl⟩,eq'⟩,remark (tail_free ..) last⟩
  11587. end P455GuardProduct
  11588. end
  11589. /- Begin Problem455UniformCross (from finite-semigroup-identity-bases). -/
  11590. section
  11591. namespace P455UniformCross
  11592. open P455Witness P455SourceFamilies P455SourceTheorem P455OriginalWalk
  11593. open P455ContactLift P455CrossedSupport P455SingletonEvaluation Problem455.Slots
  11594. theorem crossed {r allow mark T} (capT : P455Quotient.Cap r T)
  11595. (ts : Tiles) (c : Certificate) (tester : Holds r allow mark T (c.query r ts))
  11596. (U : List Nat) (uniform : ∀ a ∈ U, U.count a = r) (cmp : Compressed r U)
  11597. (x y : Nat) (flip : ClosedFlip r allow U x y)
  11598. (val : Nat → P455Quotient.Q (rules r allow mark) T) (h : Nat → List Nat)
  11599. (reps : ∀ a ∈ U, P455Quotient.ofWord (rules r allow mark) T (h a) = val a)
  11600. (live : P455Quotient.eval (rules r allow mark) capT val U ≠ P455Quotient.zero (rules r allow mark) T)
  11601. (s : Bool) (cross : Crosses (markedRecord c s) h x y) :
  11602. Violation r allow ts U x y := by
  11603. have capU : P455Closure.Cap r U := by
  11604. intro a
  11605. by_cases ha : a ∈ U
  11606. · exact Nat.le_of_eq (uniform a ha)
  11607. · simp [List.count_eq_zero.mpr ha]
  11608. obtain ⟨hr,cx,cy,_⟩ := flip_counts capU flip
  11609. have pos : 0 < r := by omega
  11610. obtain ⟨seed,side,img⟩ := choose_seed c s false cross
  11611. have source : Supplies U h r seed (startLabel c s false) :=
  11612. ⟨side.elim (fun eq => eq ▸ cx) (fun eq => eq ▸ cy),img⟩
  11613. let ident := fun a : Nat => [a]
  11614. have exp : P455Retained.Expansion U ident (fun _ => True) :=
  11615. ⟨fun _ _ _ => rfl, fun _ _ f => (f True.intro).elim⟩
  11616. have back : U.flatMap ident = U := by simp [ident]
  11617. have guard : OriginalGuard r allow mark (U.flatMap ident) (fun _ => True) seed 6 := by
  11618. rw [back]
  11619. intro t _
  11620. refine ⟨True.intro,?_⟩
  11621. intro i _ a occ
  11622. obtain ⟨j,seen⟩ := occ
  11623. exact ⟨True.intro,uniform a (stamped_mem_label _ _ (a,j) (seen.subset (by simp)))⟩
  11624. obtain ⟨_,_,_,_,_,_,_,read,_⟩ := arbitrary_reps_original_gadget capT val U h reps live ts c tester
  11625. s false seed hr source exp (back.symm ▸ capU) guard
  11626. rw [back] at read
  11627. let R := rules r allow mark
  11628. have ev := P455Quotient.eval_rep R capT val U h reps
  11629. have good := (P455Quotient.nonzero_iff R).mp (ev ▸ live)
  11630. have capH := P455Quotient.good_cap R capT good
  11631. let d := donor U h r
  11632. refine ⟨transferred d c,s,?_,?_⟩
  11633. · rw [changed_anchor]
  11634. rcases cross with ⟨xo,ym⟩|⟨yo,xm⟩
  11635. · exact .inl ⟨donor_eq pos capH ⟨cx,xo⟩,donor_eq pos capH ⟨cy,ym⟩⟩
  11636. · exact .inr ⟨donor_eq pos capH ⟨cy,yo⟩,donor_eq pos capH ⟨cx,xm⟩⟩
  11637. · rw [reindexed_marks]; exact read cmp
  11638. theorem crossed_word {r allow mark T} (capT : P455Quotient.Cap r T)
  11639. (ts : Tiles) (c : Certificate) (tester : Holds r allow mark T (c.query r ts))
  11640. (U : List Nat) (uniform : ∀ a ∈ U, U.count a = r) (cmp : Compressed r U)
  11641. (x y : Nat) (flip : ClosedFlip r allow U x y) (h : Nat → List Nat)
  11642. (good : P455Quotient.Good (rules r allow mark) T (U.flatMap h))
  11643. (s : Bool) (cross : Crosses (markedRecord c s) h x y) : Violation r allow ts U x y := by
  11644. let R := rules r allow mark
  11645. let val := fun a => P455Quotient.ofWord R T (h a)
  11646. apply crossed capT ts c tester U uniform cmp x y flip val h (fun _ _ => rfl) _ s cross
  11647. rw [P455Quotient.eval_rep R capT val U h (fun _ _ => rfl)]
  11648. exact (P455Quotient.nonzero_iff R).mpr good
  11649. end P455UniformCross
  11650. end
  11651. /- Begin Problem455PaddedAssembly (from finite-semigroup-identity-bases). -/
  11652. section
  11653. namespace P455PaddedTiles
  11654. open P455Witness
  11655. variable {n : Nat} {M : MachineTable n}
  11656. private theorem neg_of_ne {a b : Bool} (h : a≠b) : b= !a := by
  11657. cases a <;> cases b <;> simp_all
  11658. theorem system_laws (n : Nat) : P455GridRows.Laws (system n) where
  11659. horiz := by
  11660. rintro _ _ ⟨p,q,rfl,rfl,ok⟩
  11661. exact ⟨ok.1,ok.2.1,ok.2.2.1,ok.2.2.2.1,ok.2.2.2.2.1,neg_of_ne ok.2.2.2.2.2.1⟩
  11662. vert := by
  11663. rintro _ _ ⟨p,q,rfl,rfl,ok⟩
  11664. exact ⟨ok.1,ok.2.1,ok.2.2.1.symm,ok.2.2.2.1.symm,ok.2.2.2.2.1.symm,neg_of_ne ok.2.2.2.2.2.1⟩
  11665. private theorem odd_next (i : Nat) : odd (i+1)= !odd i := by
  11666. by_cases p : i%2=1
  11667. · simp [odd,p,show (i+1)%2≠1 by omega]
  11668. · simp [odd,p,show (i+1)%2=1 by omega]
  11669. private theorem flag_eq {b : Bool} {p : Prop} [Decidable p] (h : b=true ↔ p) : b=decide p := by
  11670. cases b <;> by_cases hp : p <;> simp_all
  11671. def from_assembly (A : P455GridAssembly.Rectangle (allowed M) (system n)) :
  11672. Rectangle M (A.width+1) (A.height+1) where
  11673. positiveW := by omega
  11674. positiveH := by omega
  11675. tag := A.tile
  11676. eligible := fun _ iy _ jx => A.allowed _ _ (by omega) (by omega)
  11677. right := fun _ iy _ jx => A.horiz _ _ (by omega) (by omega)
  11678. down := fun _ iy _ jx => A.vert _ _ (by omega) (by omega)
  11679. flags := by
  11680. intro y iy x jx
  11681. have hy : y≤A.height := by omega
  11682. have hx : x≤A.width := by omega
  11683. have tops := A.top y x hy hx
  11684. have lefts := A.left y x hy hx
  11685. refine ⟨flag_eq lefts,flag_eq ((A.right y x hy hx).trans (by omega)),flag_eq tops,
  11686. flag_eq ((A.bottom y x hy hx).trans (by omega)),?_,?_⟩
  11687. · clear tops lefts iy
  11688. induction y with
  11689. | zero =>
  11690. obtain ⟨p,eq,ok⟩ := A.allowed 0 x (by omega) hx
  11691. have top := (A.top 0 x (by omega) hx).mpr rfl
  11692. rw [←eq] at top ⊢
  11693. exact (ok.2.2.2.2.2.1 top).1
  11694. | succ y ih =>
  11695. have pr := (system_laws n).vert _ _ (A.vert y x (by omega) hx)
  11696. rw [pr.2.2.2.2.2,ih (by omega),odd_next]
  11697. · clear tops lefts jx
  11698. induction x with
  11699. | zero =>
  11700. obtain ⟨p,eq,ok⟩ := A.allowed y 0 hy (by omega)
  11701. have left := (A.left y 0 hy (by omega)).mpr rfl
  11702. rw [←eq] at left ⊢
  11703. exact ok.2.2.2.2.1 left
  11704. | succ x ih =>
  11705. have pr := (system_laws n).horiz _ _ (A.horiz y x hy (by omega))
  11706. rw [pr.2.2.2.2.2,ih (by omega),odd_next]
  11707. /-- Last row s is the accepting configuration. The trace uses width+1
  11708. cells, including when the last column is zero. -/
  11709. noncomputable def assembly_trace (A : P455GridAssembly.Rectangle (allowed M) (system n)) :
  11710. AcceptingTrace M (A.width+1) A.height := by
  11711. simpa using read_trace (from_assembly A)
  11712. /-- Infinite continuation of literal source-word arrows now yields
  11713. a finite accepting trace of the specified transition table. -/
  11714. theorem accepts_of_arrows {r : Nat} {mark : Marking} {w : List Nat} (c : Nat → EdgeCertificate)
  11715. (edges : ∀ i, P455GridRows.Arrow r (allowed M) mark w (system n) (c i))
  11716. (cont : ∀ i, (c i).b = (c (i+1)).a)
  11717. (functional : ∀ i, P455GridRows.Functional r (allowed M) mark w (system n) (c i).a) :
  11718. ∃ width s, Nonempty (AcceptingTrace M width s) := by
  11719. obtain ⟨R⟩ := P455GridAssembly.rectangle_of_trace (system_laws n) c edges cont functional
  11720. exact ⟨R.width+1,R.height,⟨assembly_trace R⟩⟩
  11721. end P455PaddedTiles
  11722. end
  11723. /- Begin Problem455PaddedOrders (from finite-semigroup-identity-bases). -/
  11724. section
  11725. namespace P455PaddedWord
  11726. open P455PaddedPorts P455PaddedMatchings P455RectangleRank P455Witness Problem455.Slots
  11727. private theorem in_stamp (n : Nat→Nat) (w : List Nat) {a j : Nat}
  11728. (lo : n a≤j) (hi : j<n a+w.count a) : (a,j)∈stamp n w := by
  11729. obtain ⟨p,t,e,ct⟩ := P455SlotOrigin.occurrence_cut w a (j-n a) (by omega)
  11730. rw [e,stamp_append,stamp]
  11731. apply List.mem_append_right
  11732. have idx : advance n p a=j := by simp [advance,ct]; omega
  11733. rw [idx]; exact List.mem_cons_self
  11734. theorem sees_across (l t : List Nat) (a i b j : Nat) (inL : i<l.count a)
  11735. (inR : l.count b≤j) (both : j<(l++t).count b) : sees (l++t) [(a,i),(b,j)] := by
  11736. unfold sees events
  11737. rw [stamp_append]
  11738. have left : (a,i)∈stamp (fun _=>0) l := in_stamp _ l (by omega) (by simpa using inL)
  11739. have right : (b,j)∈stamp (advance (fun _=>0) l) t := by
  11740. apply in_stamp <;> simp [advance,List.count_append] at * <;> omega
  11741. exact ((List.singleton_sublist.mpr left).append (List.singleton_sublist.mpr right) :
  11742. ([(a,i)]++[(b,j)]).Sublist _)
  11743. theorem early_order {h w k : Nat} (size : 1<w*h) (tag : Nat→Tag) (bits : Nat→Bool)
  11744. (allow : Tag→Prop) (mark : Marking) {i j a b e f : Nat} (lt : i<j) (last : j<w*h)
  11745. (ra : a∈roles i) (rb : b∈roles j) (ei : e<3) (fi : f<3) :
  11746. Holds (k+16) allow mark (text h w k tag bits) (earlier a e b f) := by
  11747. refine ⟨?_,?_⟩
  11748. · intro u m
  11749. rcases (show u=(a,e) ∨ u=(b,f) by simpa using m) with rfl|rfl <;> dsimp <;> omega
  11750. · obtain ⟨post,cut⟩ := private_cut tag bits last
  11751. have total := word_count (k:=k) size tag bits j b rb
  11752. rw [if_pos last] at total
  11753. change (text h w k tag bits).count b=_ at total
  11754. rw [cut,List.append_assoc] at total ⊢
  11755. apply sees_across
  11756. · simpa [private_counts i a ra,lt] using ei
  11757. · simp [private_counts j b rb]
  11758. · omega
  11759. theorem early_groups {h w k : Nat} (size : 1<w*h) (tag : Nat→Tag) (bits : Nat→Bool)
  11760. (allow : Tag→Prop) (mark : Marking) {i j : Nat} (ne : i≠j) (li : i<w*h) (lj : j<w*h) :
  11761. Holds (k+16) allow mark (text h w k tag bits) (earlyDisjoint (roles i) (roles j)) := by
  11762. by_cases e : i<j
  11763. · apply Or.inl
  11764. exact (P455PortReflection.earlyBefore_iff ..).mpr
  11765. (fun _ ra _ rb => early_order size tag bits allow mark e lj ra rb (by decide) (by decide))
  11766. · apply Or.inr
  11767. exact (P455PortReflection.earlyBefore_iff ..).mpr
  11768. (fun _ ra _ rb => early_order size tag bits allow mark (by omega : j<i) li ra rb (by decide) (by decide))
  11769. theorem first_owner {h w k : Nat} (size : 1<w*h) (tag : Nat→Tag) (bits : Nat→Bool)
  11770. (allow : Tag→Prop) (mark : Marking) {i j : Nat} (lt : i<j) (last : j<w*h) :
  11771. Holds (k+16) allow mark (text h w k tag bits) (earlier (owner i) 0 (owner j) 0) :=
  11772. early_order size tag bits allow mark lt last (by simp [roles]) (by simp [roles]) (by decide) (by decide)
  11773. private theorem adjacent_column_cut {h w y x : Nat} (ly : y<h) (lx : x+1<w) :
  11774. ∃ l t, columnCells h w=l++idAt w y x::idAt w y (x+1)::t := by
  11775. let restRow := List.range' (x+1+1) (w-(x+1+1))
  11776. have ec := range_cut lx
  11777. rw [List.range_succ] at ec
  11778. change List.range w=(List.range x ++ [x]) ++ (x+1) :: restRow at ec
  11779. have er := range_cut ly
  11780. let emit := fun z=>(List.range w).map (idAt w z)
  11781. refine ⟨(List.range y).flatMap emit ++ (List.range x).map (idAt w y),
  11782. restRow.map (idAt w y) ++ (List.range' (y+1) (h-(y+1))).flatMap emit,?_⟩
  11783. unfold columnCells
  11784. rw [er,List.flatMap_append,List.flatMap_cons]
  11785. change _ ++ (emit y ++ _) = _
  11786. have row : emit y=(List.range x).map (idAt w y) ++ idAt w y x :: idAt w y (x+1) :: restRow.map (idAt w y) := by
  11787. unfold emit; rw [ec]; simp [List.map_append,List.append_assoc]
  11788. rw [row]; simp [List.append_assoc,emit]
  11789. private theorem tags_counts {h w k : Nat} (tag : Nat→Tag) {i a : Nat} (role : a∈roles i) (lt : i<w*h) :
  11790. ((List.range k).flatMap (tagPhase (w*h) tag)).count a=k := by
  11791. have z := suffix_count (h:=h) (w:=w) (k:=k) tag i a role
  11792. rw [if_pos lt,suffix,List.count_append,count_role _ i a (by simpa [roles] using role),
  11793. count_one (columns_unique h w) ((columns_cells h w i).mpr lt)] at z
  11794. omega
  11795. /-- True for the left-to-right adjacent coordinates on both row parities.
  11796. Their numeric snake IDs may be increasing or decreasing. -/
  11797. theorem column_order {h w k : Nat} (size : 1<w*h) (tag : Nat→Tag) (bits : Nat→Bool)
  11798. (allow : Tag→Prop) (mark : Marking) {y x : Nat} (ly : y<h) (lx : x+1<w) :
  11799. Holds (k+16) allow mark (text h w k tag bits)
  11800. (earlier (owner (idAt w y x)) (13+k) (owner (idAt w y (x+1))) (13+k)) := by
  11801. let i := idAt w y x
  11802. let j := idAt w y (x+1)
  11803. have ix : i<w*h := id_bound ly (by omega)
  11804. have jx : j<w*h := id_bound ly lx
  11805. obtain ⟨l,t,cut⟩ := adjacent_column_cut ly lx
  11806. have nd := columns_unique h w
  11807. rw [cut] at nd
  11808. have dedup := List.pairwise_append.mp nd
  11809. have noJ : j∉l ++ [i] := by
  11810. intro m
  11811. rcases List.mem_append.mp m with m|m
  11812. · exact dedup.2.2 j m j (by simp [i,j]) rfl
  11813. · have ne := (List.nodup_cons.mp dedup.2.1).1
  11814. have eq : j=i := by simpa using m
  11815. exact ne (List.mem_cons.mpr (.inl eq.symm))
  11816. let core := (List.range (w*h)).flatMap privateCell ++ portChunks h w 5 ++
  11817. (List.range k).flatMap (tagPhase (w*h) tag)
  11818. let L := core ++ (l++[i]).flatMap roles
  11819. let Z := (j::t).flatMap roles ++ (List.range (w*h)).flatMap (mutableCell bits) ++ tail (w*h)
  11820. have whole : text h w k tag bits=L++Z := by
  11821. change columnCells h w=l++i::j::t at cut
  11822. simp [text,word,middle,suffix,cut,L,Z,core,List.flatMap_append,List.flatMap_cons,List.append_assoc]
  11823. have occur (u : Nat) (hu : u<w*h) : core.count (owner u)=13+k := by
  11824. have role : owner u∈roles u := by simp [roles]
  11825. simp [core,List.count_append,private_counts u _ role,chunks_count size 5 u _ role,tags_counts tag role hu,hu]; omega
  11826. have left : 13+k<L.count (owner i) := by
  11827. have one := List.count_pos_iff.mpr (show i∈l++[i] by simp)
  11828. dsimp only [L]
  11829. rw [List.count_append,count_role _ i _ (.inl rfl),occur i ix]; omega
  11830. have right : L.count (owner j)=13+k := by
  11831. dsimp only [L]
  11832. rw [List.count_append,count_role _ j _ (.inl rfl),occur j jx,List.count_eq_zero.mpr noJ,Nat.add_zero]
  11833. have total := word_count (k:=k) size tag bits j (owner j) (by simp [roles])
  11834. rw [if_pos jx] at total
  11835. change (text h w k tag bits).count (owner j)=_ at total
  11836. change Holds (k+16) allow mark (text h w k tag bits) (earlier (owner i) (13+k) (owner j) (13+k))
  11837. rw [whole] at total ⊢
  11838. refine ⟨?_,sees_across _ _ _ _ _ _ left (by omega) (by omega)⟩
  11839. intro e m
  11840. rcases (show e=(_,13+k) ∨ e=(_,13+k) by simpa using m) with rfl|rfl <;> dsimp <;> omega
  11841. end P455PaddedWord
  11842. end
  11843. /- Begin Problem455GuardRename (from fini