Lean / AbelCz/finite-semigroup-identity-bases / TarskiFiniteBasis.lean
Lean readerTarskiFiniteBasis.lean
Showing the first 600 kB.
import Mathlib.Computability.Partrecimport Mathlib.Computability.PostTuringMachineimport Mathlib.Computability.Primrecimport Mathlib.Computability.TMToPartrecimport Mathlib.Data.Fintype.EquivFinimport Mathlib.Data.Fintype.Optionimport Mathlib.Data.Fintype.Prodimport Mathlib.Data.List.FinRangeimport Stdset_option maxErrors 1000set_option backward.isDefEq.respectTransparency.types falseset_option maxHeartbeats 250000set_option linter.unusedSimpArgs falseprivate theorem p455MapFinRange (n : ℕ) :(List.finRange n).map Fin.val = List.range n := byapply List.ext_getElem <;> simp/- Begin Problem455MachineLocal (from finite-semigroup-identity-bases). -/sectionnamespace P455MachineLocalinductive Direction | left | stay | rightderiving DecidableEqstructure Ins (A Q : Type) wherestate : Qsymbol : Adir : Directionderiving DecidableEqstructure Cell (A Q : Type) wheresym : Ahead : Option Qderiving DecidableEqdef action (d : Q→A→Ins A Q) (c : Cell A Q) := c.head.map fun q=>d q c.symdef sends (i : Ins A Q) (toward : Direction) : Option Q := if i.dir=toward then some i.state else nonedef update (d : Q→A→Ins A Q) (l : Option (Cell A Q)) (c : Cell A Q) (r : Option (Cell A Q)) :Option (Cell A Q) :=match l.bind (action d), action d c, r.bind (action d) with| none,none,none => some ⟨c.sym,none⟩| some a,none,none => some ⟨c.sym,sends a .right⟩| none,none,some a => some ⟨c.sym,sends a .left⟩| none,some a,none =>if (a.dir=.left ∧ l.isNone=true) ∨ (a.dir=.right ∧ r.isNone=true) then noneelse some ⟨a.symbol,sends a .stay⟩| _,_,_ => nonedef atCell (tape : Nat→A) (p : Nat) (q : Q) (x : Nat) : Cell A Q :=⟨tape x,if x=p then some q else none⟩def leftOf (row : Nat→α) (x : Nat) := if x=0 then none else some (row (x-1))def rightOf (row : Nat→α) (w x : Nat) := if x+1=w then none else some (row (x+1))def exits (dir : Direction) (w p : Nat) : Prop :=(dir=.left ∧ p=0) ∨ (dir=.right ∧ p+1=w)instance (dir : Direction) (w p : Nat) : Decidable (exits dir w p) := by unfold exits; infer_instancedef dest (dir : Direction) (p : Nat) : Nat :=match dir with | .left => p-1 | .stay => p | .right => p+1def writeAt (tape : Nat→A) (p : Nat) (a : A) (x : Nat) := if x=p then a else tape xprivate theorem center_action (d : Q→A→Ins A Q) (tape : Nat→A) (p : Nat) (q : Q) (x : Nat) :action d (atCell tape p q x) = if x=p then some (d q (tape p)) else none := byby_cases e : x=p <;> simp [action,atCell,e]private theorem left_action (d : Q→A→Ins A Q) (tape : Nat→A) (p : Nat) (q : Q) (x : Nat) :(leftOf (atCell tape p q) x).bind (action d) =if x=p+1 then some (d q (tape p)) else none := byby_cases e : x=0· subst x; simp [leftOf]· have eq : (x-1=p) ↔ x=p+1 := by omegasimp [leftOf,e,center_action,eq]private theorem right_action (d : Q→A→Ins A Q) (tape : Nat→A) (p w : Nat) (hp : p<w) (q : Q) (x : Nat) :(rightOf (atCell tape p q) w x).bind (action d) =if x+1=p then some (d q (tape p)) else none := byby_cases e : x+1=w· simp [rightOf,e,show w≠p by omega]· simp [rightOf,e,center_action]private theorem left_boundary (row : Nat→α) (x : Nat) : (leftOf row x).isNone=true ↔ x=0 := byby_cases e : x=0 <;> simp [leftOf,e]private theorem right_boundary (row : Nat→α) (w x : Nat) : (rightOf row w x).isNone=true ↔ x+1=w := byby_cases e : x+1=w <;> simp [rightOf,e]/-- When an entire bounded row has one head, the local rule at that headis defined precisely when the physical move remains in the interval. -/theorem defined_at_head (d : Q→A→Ins A Q) (tape : Nat→A) (w p : Nat) (q : Q) (hp : p<w) :update d (leftOf (atCell tape p q) p) (atCell tape p q p) (rightOf (atCell tape p q) w p)=none↔ exits (d q (tape p)).dir w p := byunfold updaterw [left_action,right_action _ _ _ _ hp,center_action]simp only [if_neg (show p≠p+1 by omega),if_neg (show p+1≠p by omega),if_pos rfl]simp only [left_boundary,right_boundary]change (if exits (d q (tape p)).dir w p then _ else _) = none ↔ _by_cases e : exits (d q (tape p)).dir w p <;> simp [e]/-- Every cell of a nonescaping row has its exact next physical value. -/theorem local_step (d : Q→A→Ins A Q) (tape : Nat→A) (w p : Nat) (q : Q)(hp : p<w) (safe : ¬exits (d q (tape p)).dir w p) (x : Nat) (hx : x<w) :let i := d q (tape p)update d (leftOf (atCell tape p q) x) (atCell tape p q x) (rightOf (atCell tape p q) w x)=some (atCell (writeAt tape p i.symbol) (dest i.dir p) i.state x) := bydsimp onlyunfold updaterw [left_action,right_action _ _ _ _ hp,center_action]by_cases cp : x=p· subst xsimp only [if_neg (show p≠p+1 by omega),if_neg (show p+1≠p by omega),if_pos rfl]change (if ((d q (tape p)).dir=.left ∧ (leftOf (atCell tape p q) p).isNone=true) ∨((d q (tape p)).dir=.right ∧ (rightOf (atCell tape p q) w p).isNone=true)then none else some (Cell.mk (d q (tape p)).symbol (sends (d q (tape p)) .stay))) = _simp only [left_boundary,right_boundary]change (if exits (d q (tape p)).dir w p then _ else _) = _rw [if_neg safe]cases dir : (d q (tape p)).dir with| left =>have pos : p≠0 := by simpa [exits,dir] using safesimp [sends,dir,atCell,writeAt,dest,show p≠p-1 by omega]| stay => simp [sends,dir,atCell,writeAt,dest]| right => simp [sends,dir,atCell,writeAt,dest]· by_cases l : x=p+1· have r : x+1≠p := by omegasimp only [if_pos l,if_neg cp,if_neg r]cases dir : (d q (tape p)).dir <;>simp [sends,dir,atCell,writeAt,dest,cp,show x≠p-1 by omega,l,show p+1≠p-1 by omega]· by_cases r : x+1=p· simp only [if_neg l,if_neg cp,if_pos r]cases dir : (d q (tape p)).dir <;>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]· simp only [if_neg l,if_neg cp,if_neg r]cases dir : (d q (tape p)).dir <;>simp [sends,dir,atCell,writeAt,dest,cp,l,show x≠p-1 by omega]end P455MachineLocalend/- Begin Problem455Quotient (from finite-semigroup-identity-bases). -/sectionnamespace P455Quotientabbrev Word (α : Type) := List αinductive Walk {α : Type} (s : α → α → Prop) : α → α → Prop| refl (a) : Walk s a a| snoc {a b c} : Walk s a b → s b c → Walk s a cnamespace Walktheorem trans {s : α → α → Prop} (h : Walk s x y) (k : Walk s y z) : Walk s x z := byinduction k with| refl => exact h| snoc _ step ih => exact .snoc ih steptheorem symm {s : α → α → Prop} (rev : ∀ {x y}, s x y → s y x) (h : Walk s x y) :Walk s y x := byinduction h with| refl => exact .refl _| snoc _ step ih => exact (Walk.snoc (.refl _) (rev step)).trans ihtheorem transport {s : α → α → Prop} {P : α → Prop} (h : Walk s x y) (px : P x)(step : ∀ {u v}, s u v → P u → P v) : P y := byinduction h with| refl => exact px| snoc _ move ih => exact step move ihend Walksectionvariable {α : Type} [DecidableEq α]local notation "W" => Word αdef Cap (r : Nat) (u : W) : Prop := ∀ a : α, u.count a ≤ rstructure Rules (α : Type) [DecidableEq α] wherer : Natstep : Word α → Word α → Propreverse : ∀ {u v}, step u v → step v ucounts : ∀ {u v}, step u v → ∀ a, u.count a = v.count aextend : ∀ {u v}, step u v → ∀ l t, Cap r (l ++ u ++ t) →step (l ++ u ++ t) (l ++ v ++ t)variable (R : Rules α)abbrev Variant (T v : W) := Walk R.step T vdef Factor (u v : W) := ∃ l t : Word α, v = l ++ u ++ tdef Good (T u : W) := ∃ v, Variant R T v ∧ Factor u vtheorem count_walk {u v : W} (h : Walk R.step u v) (a : α) : u.count a = v.count a := byinduction h with| refl => rfl| snoc _ step ih => exact ih.trans (R.counts step a)theorem contextual_walk {u v : W} (h : Walk R.step u v) (l t : Word α)(hc : Cap R.r (l ++ u ++ t)) : Walk R.step (l ++ u ++ t) (l ++ v ++ t) := byinduction h with| refl => exact .refl _| snoc pre mv ih =>apply Walk.snoc ih (R.extend mv l t ?_)intro ahave eq := count_walk R pre ahave bound := hc asimp only [List.count_append] at *omegatheorem good_context {T u v : W} (hc : Cap R.r T) (h : Walk R.step u v)(l t : Word α) : Good R T (l ++ u ++ t) ↔ Good R T (l ++ v ++ t) := bysuffices f : ∀ {x y}, Walk R.step x y → Good R T (l ++ x ++ t) → Good R T (l ++ y ++ t) from⟨f h, f (h.symm R.reverse)⟩intro x y path ⟨variant, reach, left, right, eq⟩subst varianthave bound : Cap R.r ((left ++ l) ++ x ++ (t ++ right)) := byintro ahave e := count_walk R reach asimp only [List.count_append] at *have := hc aomegahave ext := contextual_walk R path (left ++ l) (t ++ right) boundsimp only [List.append_assoc] at reach ext ⊢exact ⟨_, reach.trans ext, left, right, by simp [List.append_assoc]⟩theorem good_cap {T u : W} (hc : Cap R.r T) (h : Good R T u) : Cap R.r u := byobtain ⟨_, reach, l, t, rfl⟩ := hintro ahave e := count_walk R reach ahave b := hc asimp only [List.count_append] at eomegatheorem factor_good {T u v : W} (g : Good R T v) (f : Factor u v) : Good R T u := byobtain ⟨w, path, l, t, hw⟩ := gobtain ⟨l', t', hv⟩ := fexact ⟨w, path, l ++ l', t' ++ t, by simp [hw, hv, List.append_assoc]⟩abbrev Raw (α : Type) := Option (Word α)def mulRaw : Raw α → Raw α → Raw α| some u, some v => some (u ++ v)| _, _ => nonedef Live (T : W) : Raw α → Prop| none => False| some u => Good R T udef Rel (T : W) (x y : Raw α) : Prop :=(¬ Live R T x ∧ ¬ Live R T y) ∨∃ u v : W, x = some u ∧ y = some v ∧ Good R T u ∧ Good R T v ∧ Walk R.step u vtheorem rel_refl (T : W) (x : Raw α) : Rel R T x x := byby_cases h : Live R T x· cases x with| none => exact h.elim| some u => exact Or.inr ⟨u,u,rfl,rfl,h,h,.refl _⟩· exact Or.inl ⟨h,h⟩theorem rel_symm {T : W} {x y : Raw α} : Rel R T x y → Rel R T y x := byrintro (⟨a,b⟩ | ⟨u,v,rfl,rfl,gu,gv,h⟩)· exact Or.inl ⟨b,a⟩· exact Or.inr ⟨v,u,rfl,rfl,gv,gu,h.symm R.reverse⟩theorem rel_trans {T : W} {x y z : Raw α} : Rel R T x y → Rel R T y z → Rel R T x z := byrintro (⟨a,b⟩ | ⟨u,v,rfl,rfl,gu,gv,h⟩) k· rcases k with ⟨_,c⟩ | ⟨v,w,rfl,rfl,gv,_,_⟩· exact Or.inl ⟨a,c⟩· exact (b gv).elim· rcases k with ⟨b,_⟩ | ⟨v',w,e,rfl,_,gw,h'⟩· exact (b gv).elim· cases eexact Or.inr ⟨u,w,rfl,rfl,gu,gw,h.trans h'⟩def setoid (T : W) : Setoid (Raw α) wherer := Rel R Tiseqv := ⟨rel_refl R T, rel_symm R, rel_trans R⟩abbrev Q (T : W) := Quotient (setoid R T)def context (l t : Word α) : Raw α → Raw α| none => none| some u => some (l ++ u ++ t)theorem dead_context {T : W} {x : Raw α} (d : ¬ Live R T x) (l t : Word α) :¬ Live R T (context l t x) := bycases x with| none => exact id| some u => exact fun g => d (factor_good R g ⟨l,t,rfl⟩)theorem rel_context {T : W} (hc : Cap R.r T) {x y : Raw α} (h : Rel R T x y)(l t : Word α) : Rel R T (context l t x) (context l t y) := byrcases h with ⟨a,b⟩ | ⟨u,v,rfl,rfl,_,_,path⟩· exact Or.inl ⟨dead_context R a l t,dead_context R b l t⟩· have equiv := good_context R hc path l tby_cases gu : Good R T (l ++ u ++ t)· exact Or.inr ⟨_,_,rfl,rfl,gu,equiv.mp gu,contextual_walk R path l t (good_cap R hc gu)⟩· exact Or.inl ⟨gu,fun gv => gu (equiv.mpr gv)⟩theorem mul_compat {T : W} (hc : Cap R.r T) {x y z t : Raw α}(h : Rel R T x y) (k : Rel R T z t) : Rel R T (mulRaw x z) (mulRaw y t) := byapply rel_trans R (y := mulRaw y z)· cases z with| none => cases x <;> cases y <;> exact rel_refl R _ _| some w =>have e := rel_context R hc h [] wcases x <;> cases y <;> exact e· cases y with| none => exact rel_refl R _ _| some w =>have e := rel_context R hc k w []cases z <;> cases t <;> simpa only [context, mulRaw, List.append_nil] using edef cls (T : W) (x : Raw α) : Q R T := Quotient.mk _ xset_option backward.isDefEq.respectTransparency false indef mul {T : W} (hc : Cap R.r T) (x y : Q R T) : Q R T :=Quotient.liftOn₂ x y (fun a b => cls R T (mulRaw a b))(fun _ _ _ _ h k => Quotient.sound (mul_compat R hc h k))def zero (T : W) : Q R T := cls R T nonedef ofWord (T u : W) : Q R T := cls R T (some u)theorem mul_assoc {T : W} (hc : Cap R.r T) (x y z : Q R T) :mul R hc (mul R hc x y) z = mul R hc x (mul R hc y z) := byinduction x using Quotient.inductionOn with | _ a =>induction y using Quotient.inductionOn with | _ b =>induction z using Quotient.inductionOn with | _ c =>change cls R T (mulRaw (mulRaw a b) c) = cls R T (mulRaw a (mulRaw b c))apply congrArg (cls R T)cases a <;> cases b <;> cases c <;> simp only [mulRaw, List.append_assoc]set_option backward.isDefEq.respectTransparency false intheorem unit_laws {T : W} (hc : Cap R.r T) (q : Q R T) :mul R hc (ofWord R T []) q = q ∧ mul R hc q (ofWord R T []) = q := byrefine Quotient.inductionOn(motive := fun a : Q R T => mul R hc (ofWord R T []) a = a ∧ mul R hc a (ofWord R T []) = a)q ?_intro achange cls R T (mulRaw (some []) a) = cls R T a ∧ cls R T (mulRaw a (some [])) = cls R T acases a <;> simp only [mulRaw, List.nil_append, List.append_nil, and_self]set_option backward.isDefEq.respectTransparency false intheorem absorbing {T : W} (hc : Cap R.r T) (q : Q R T) :mul R hc (zero R T) q = zero R T ∧ mul R hc q (zero R T) = zero R T := byinduction q using Quotient.inductionOn with | _ a =>cases a <;> exact ⟨rfl,rfl⟩theorem nonzero_iff {T u : W} : ofWord R T u ≠ zero R T ↔ Good R T u := byconstructor· intro hby_cases good : Good R T u· exact good· exact (h (Quotient.sound (Or.inl ⟨good,id⟩ : Rel R T (some u) none))).elim· intro good eqhave e : Rel R T (some u) none := Quotient.exact eqrcases e with ⟨bad,_⟩ | ⟨_,_,_,e,_,_,_⟩· exact bad good· contradictiontheorem good_empty (T : W) : Good R T [] :=⟨T,.refl T,T,[],by simp⟩theorem same_nonzero_class {T u v : W} (g : Good R T u) :ofWord R T u = ofWord R T v ↔ Good R T v ∧ Walk R.step u v := byconstructor· intro ehave h : Rel R T (some u) (some v) := Quotient.exact ercases h with ⟨bad,_⟩ | ⟨_,_,ea,eb,_,gv,path⟩· exact (bad g).elim· cases eacases ebexact ⟨gv,path⟩· rintro ⟨gv,path⟩exact Quotient.sound (Or.inr ⟨u,v,rfl,rfl,g,gv,path⟩ : Rel R T (some u) (some v))theorem unit_rep_unique (T u : W) : ofWord R T u = ofWord R T [] ↔ u = [] := byconstructor· intro eqhave path := ((same_nonzero_class R (good_empty R T)).mp eq.symm).2exact (List.Perm.nil_eq (List.perm_iff_count.mpr (count_walk R path))).symm· rintro rfl; rfltheorem nonzero_representative {T : W} (q : Q R T) (nz : q ≠ zero R T) :∃ u, Good R T u ∧ ofWord R T u = q := byinduction q using Quotient.inductionOn with | _ a =>cases a with| none => exact (nz rfl).elim| some u => exact ⟨u,(nonzero_iff R).mp nz,rfl⟩def eval {T : W} (hc : Cap R.r T) (a : β → Q R T) : List β → Q R T| [] => ofWord R T []| x :: xs => mul R hc (a x) (eval hc a xs)theorem eval_rep {T : W} (hc : Cap R.r T) (a : β → Q R T)(v : List β) (h : β → Word α) (reps : ∀ x ∈ v, ofWord R T (h x) = a x) :eval R hc a v = ofWord R T (v.flatMap h) := byinduction v with| nil => rfl| cons x xs ih =>rw [eval, ← reps x (by simp), ih (fun y hy => reps y (by simp [hy]))]rfltheorem arbitrary_representatives {T : W} (hc : Cap R.r T) (a : β → Q R T)(v : List β) (h : β → Word α) (reps : ∀ x ∈ v, ofWord R T (h x) = a x) :eval R hc a v ≠ zero R T ↔∃ variant l t, Variant R T variant ∧ variant = l ++ v.flatMap h ++ t := byrw [eval_rep R hc a v h reps, nonzero_iff]constructor· rintro ⟨z,path,l,t,e⟩; exact ⟨z,l,t,path,e⟩· rintro ⟨z,l,t,path,e⟩; exact ⟨z,path,l,t,e⟩theorem live_inputs {T : W} (hc : Cap R.r T) (a : β → Q R T)(v : List β) (nz : eval R hc a v ≠ zero R T) : ∀ x ∈ v, a x ≠ zero R T := byinduction v with| nil => simp| cons y ys ih =>have yn : a y ≠ zero R T := fun h => nz (by rw [eval,h,(absorbing R hc _).1])have ns : eval R hc a ys ≠ zero R T := fun h => nz (by rw [eval,h,(absorbing R hc _).2])intro x hxrcases List.mem_cons.mp hx with e | hx· exact e ▸ yn· exact ih ns x hx/-- For a fixed certificate, only preservation under ONE literal template movestill has to be discharged. The certificate is read in the enclosing variant. -/theorem designated {T : W} (hc : Cap R.r T) (a : β → Q R T) (v : List β)(h : β → Word α) (reps : ∀ x ∈ v, ofWord R T (h x) = a x)(nz : eval R hc a v ≠ zero R T) (P : Word α → Prop)(initial : P T) (one : ∀ {x y}, R.step x y → P x → P y) :∃ variant l t, Variant R T variant ∧ variant = l ++ v.flatMap h ++ t ∧ P variant := byobtain ⟨z,l,t,path,eq⟩ := (arbitrary_representatives R hc a v h reps).mp nzexact ⟨z,l,t,path,eq,path.transport initial one⟩endend P455Quotientend/- Begin Problem455Slots (from finite-semigroup-identity-bases). -/sectionnamespace Problem455.Slotsabbrev Word := List Natabbrev Event := Nat × Natdef advance (n : Nat → Nat) (w : Word) : Nat → Nat :=fun a => n a + w.count adef stamp (n : Nat → Nat) : Word → List Event| [] => []| a :: w => (a, n a) :: stamp (advance n [a]) wdef events (w : Word) := stamp (fun _ => 0) wtheorem advance_append (n : Nat → Nat) (u v : Word) :advance (advance n u) v = advance n (u ++ v) := byfunext asimp [advance, List.count_append, Nat.add_assoc]theorem stamp_append (n : Nat → Nat) (u v : Word) :stamp n (u ++ v) = stamp n u ++ stamp (advance n u) v := byinduction u generalizing n with| nil =>have hn : advance n [] = n := by funext a; simp [advance]simp [stamp, hn]| cons a u ih =>simp only [List.cons_append, stamp, ih]rw [advance_append]rfltheorem stamp_at (n : Nat → Nat) (m : Nat) (u : Word)(nd : u.Nodup) (hm : ∀ a ∈ u, n a = m) :stamp n u = u.map (fun a => (a, m)) := byinduction u generalizing n with| nil => rfl| cons a u ih =>obtain ⟨fresh, rest⟩ := List.nodup_cons.mp ndsimp only [stamp, List.map_cons]rw [hm a (by simp), ih _ rest]intro b hbhave hne : a ≠ b := by intro eq; exact fresh (eq ▸ hb)simp [advance, hne, Ne.symm hne, hm b (by simp [hb])]structure Move (m : Nat) wherepre : Wordp : Wordq : Wordpost : Worddp : p.Nodupdq : q.Nodupdisjoint : ∀ a ∈ p, a ∉ qindexP : ∀ a ∈ p, pre.count a = mindexQ : ∀ a ∈ q, pre.count a = mdef before {m : Nat} (s : Move m) := s.pre ++ (s.p ++ (s.q ++ s.post))def after {m : Nat} (s : Move m) := s.pre ++ (s.q ++ (s.p ++ s.post))def tagged (m : Nat) (w : Word) : List Event := w.map (fun a => (a, m))theorem move_events {m : Nat} (s : Move m) :∃ lo hi : List Event,events (before s) = lo ++ (tagged m s.p ++ (tagged m s.q ++ hi)) ∧events (after s) = lo ++ (tagged m s.q ++ (tagged m s.p ++ hi)) := bylet n := fun a => s.pre.count ahave hn : advance (fun _ => 0) s.pre = n := by funext a; simp [advance, n]have hp : stamp n s.p = tagged m s.p := stamp_at _ _ _ s.dp s.indexPhave hq : stamp n s.q = tagged m s.q := stamp_at _ _ _ s.dq s.indexQhave hp' : stamp (advance n s.q) s.p = tagged m s.p := byapply stamp_at _ _ _ s.dpintro a hasimp [advance, List.count_eq_zero.mpr (s.disjoint a ha), n, s.indexP a ha]have hq' : stamp (advance n s.p) s.q = tagged m s.q := byapply stamp_at _ _ _ s.dqintro a hahave fresh : a ∉ s.p := fun hp => s.disjoint a hp hasimp [advance, List.count_eq_zero.mpr fresh, n, s.indexQ a ha]have merge : advance (advance n s.p) s.q = advance (advance n s.q) s.p := byfunext asimp [advance, Nat.add_right_comm]refine ⟨events s.pre, stamp (advance (advance n s.q) s.p) s.post, ?_, ?_⟩· simp only [events, before, stamp_append, hn]change _ ++ (stamp n s.p ++ (stamp (advance n s.p) s.q ++ _)) = _rw [hp, hq', merge]· simp only [events, after, stamp_append, hn]change _ ++ (stamp n s.q ++ (stamp (advance n s.q) s.p ++ _)) = _rw [hq, hp']def select {α : Type} [DecidableEq α] (keep w : List α) : List α :=w.filter (fun e => decide (e ∈ keep))theorem select_append {α : Type} [DecidableEq α] (keep u v : List α) :select keep (u ++ v) = select keep u ++ select keep v := List.filter_append ..theorem select_nil {α : Type} [DecidableEq α] (keep w : List α)(h : ∀ a ∈ w, a ∉ keep) : select keep w = [] := byapply List.filter_eq_nil_iff.mprsimpa using htheorem selected_swap {α : Type} [DecidableEq α] (keep lo p q hi : List α)(nc : (∀ a ∈ p, a ∉ keep) ∨ (∀ a ∈ q, a ∉ keep)) :select keep (lo ++ (p ++ (q ++ hi))) = select keep (lo ++ (q ++ (p ++ hi))) := byrcases nc with h | h· simp [select_append, select_nil keep p h]· simp [select_append, select_nil keep q h]theorem protected_projection {m : Nat} (s : Move m) (keep : List Nat)(nc : (∀ a ∈ s.p, a ∉ keep) ∨ (∀ a ∈ s.q, a ∉ keep)) :select keep (before s) = select keep (after s) :=selected_swap keep _ _ _ _ nctheorem observed_events {m : Nat} (s : Move m) (keep : List Event)(nc : (∀ a ∈ s.p, (a,m) ∉ keep) ∨ (∀ a ∈ s.q, (a,m) ∉ keep)) :select keep (events (before s)) = select keep (events (after s)) := byobtain ⟨lo, hi, h, h'⟩ := move_events srw [h, h']apply selected_swapsimpa [tagged] using nc/- Observable order measured directly by the sublist relation on the wordof indexed occurrences. The pattern need not consist of consecutive events. -/def sees (w : Word) (pattern : List Event) := pattern.Sublist (events w)theorem sublist_select_self {α : Type} [DecidableEq α] (t w : List α) :t.Sublist (select t w) ↔ t.Sublist w := byconstructor· intro hexact h.trans (List.filter_sublist ..)· intro hhave hf := h.filter (fun x => decide (x ∈ t))have self : t.filter (fun x => decide (x ∈ t)) = t := byapply List.filter_eq_self.mprsimprwa [self] at hftheorem sees_invariant {m : Nat} (s : Move m) (t : List Event)(nc : (∀ a ∈ s.p, (a,m) ∉ t) ∨ (∀ a ∈ s.q, (a,m) ∉ t)) :sees (before s) t ↔ sees (after s) t := byunfold seesrw [← sublist_select_self t (events (before s)),← sublist_select_self t (events (after s)), observed_events s t nc]theorem immutable_pattern {m : Nat} (s : Move m) (t : List Event)(hm : ∀ e ∈ t, e.2 ≠ m) :sees (before s) t ↔ sees (after s) t := byapply sees_invariantleftexact fun a _ he => hm (a,m) he rfl/- An occupant can have mutable occurrence index. Only the two specifiedowner endpoints must be immutable. This covers unit-erasing as well asmultiletter representatives once their literal product has been located. -/theorem open_slot_event {m : Nat} (s : Move m) (owner i j : Nat) (e : Event)(hi : i ≠ m) (hj : j ≠ m) :sees (before s) [(owner,i),e,(owner,j)] ↔sees (after s) [(owner,i),e,(owner,j)] := byapply sees_invariantby_cases h : e.1 ∈ s.p· rightintro a hahave diff : (a,m) ≠ e := byintro eqhave : a = e.1 := congrArg Prod.fst eqexact s.disjoint e.1 h (this ▸ ha)simp [diff, Ne.symm hi, Ne.symm hj]· leftintro a hahave diff : (a,m) ≠ e := byintro eqhave : a = e.1 := congrArg Prod.fst eqexact h (this ▸ ha)simp [diff, Ne.symm hi, Ne.symm hj]def slotStart (i : Nat) : Prop :=i = 0 ∨ i = 1 ∨ i = 3 ∨ i = 5 ∨ i = 7 ∨ i = 9 ∨ i = 11def occupies (w : Word) (owner i a : Nat) : Prop :=∃ j, sees w [(owner,i),(a,j),(owner,i+1)]theorem seven_slots {k : Nat} (s : Move (14+k)) (owner i a : Nat)(hi : slotStart i) :occupies (before s) owner i a ↔ occupies (after s) owner i a := byhave h1 : i ≠ 14+k := by unfold slotStart at hi; omegahave h2 : i+1 ≠ 14+k := by unfold slotStart at hi; omegaexact exists_congr (fun j => open_slot_event s owner i (i+1) (a,j) h1 h2)def pair (a b : Nat) (bit : Bool) : Word := if bit then [b,a] else [a,b]def profilePrefix (a b : Nat) (tag : List Bool) : Word :=[a,a,b,a,b,b] ++ (List.replicate 5 [a,b,a,b]).flatten ++tag.flatMap (pair a b) ++ [a,b]def profile (a b : Nat) (tag : List Bool) (bit : Bool) : Word :=profilePrefix a b tag ++ (pair a b bit ++ [a,b])def typed (w : Word) (a b : Nat) (tag : List Bool) : Prop :=∃ bit, select [a,b] w = profile a b tag bittheorem tag_length (a b : Nat) (tag : List Bool) :(tag.flatMap (pair a b)).length = 2 * tag.length := byinduction tag with| nil => rfl| cons bit t ih => cases bit <;> simp [pair, ih] <;> omegatheorem profile_prefix_length (a b : Nat) (tag : List Bool) :(profilePrefix a b tag).length = 2 * (14+tag.length) := byunfold profilePrefixsimp only [List.length_append, tag_length]change 6 + 20 + (2*tag.length) + 2 = _omegatheorem length_select_pair (a b : Nat) (hab : a ≠ b) (w : Word) :(select [a,b] w).length = w.count a + w.count b := byinduction w with| nil => rfl| cons c w ih =>unfold select at *simp at ihby_cases hca : c = a· subst csimp [List.count_cons, hab, Ne.symm hab, ih]; omega· by_cases hcb : c = b· subst csimp [List.count_cons, hab, Ne.symm hab, ih]; omega· simp [List.count_cons, hca, hcb, Ne.symm hca, Ne.symm hcb, ih]theorem select_lone (a b : Nat) (w : Word) (hd : w.Nodup)(ha : a ∈ w) (hb : b ∉ w) :select [a,b] w = [a] := byinduction w with| nil => simp at ha| cons c w ih =>obtain ⟨hc,ht⟩ := List.nodup_cons.mp hdby_cases hca : c = a· subst chave hnil : select [a,b] w = [] := byapply select_nilintro x hxsimp only [List.mem_cons, List.not_mem_nil, or_false, not_or]exact ⟨fun e => hc (e ▸ hx),fun e => hb (by simp [e ▸ hx])⟩simpa [select, List.filter_cons] using congrArg (List.cons a) hnil· have hc' : c ≠ b := fun h => hb (by simp [h])have ha' : a ∈ w := by simpa [Ne.symm hca] using hahave hb' : b ∉ w := fun h => hb (by simp [h])simpa [select, hca, hc'] using ih ht ha' hb'theorem select_pair_symm (a b : Nat) (w : Word) : select [b,a] w = select [a,b] w := byunfold selectapply List.filter_congrintro x _simp [or_comm]private theorem exchange_at_split (a b : Nat) (lo hi fixed tail : Word)(len : lo.length = fixed.length) (bit : Bool) :(∃ b', lo ++ (pair a b bit ++ hi) = fixed ++ (pair a b b' ++ tail)) →(∃ b', lo ++ (pair a b (!bit) ++ hi) = fixed ++ (pair a b b' ++ tail)) := byrintro ⟨old,h⟩have eqPre : lo = fixed := byhave ht := congrArg (List.take lo.length) hsimpa [len] using htsubst fixedhave he := List.append_cancel_left hhave eqHi : hi = tail := byhave hd := congrArg (List.drop 2) hecases bit <;> cases old <;> simpa [pair] using hdexact ⟨!bit,by rw [eqHi]⟩theorem type_forward {m : Nat} (s : Move m) (a b : Nat) (tag : List Bool)(hab : a ≠ b) (hm : m = 14 + tag.length) :typed (before s) a b tag → typed (after s) a b tag := bylet keep := [a,b]by_cases hp : ∀ x ∈ s.p, x ∉ keep· intro eunfold typed at *rw [← protected_projection s [a,b] (.inl hp)]; exact eby_cases hq : ∀ x ∈ s.q, x ∉ keep· intro eunfold typed at *rw [← protected_projection s [a,b] (.inr hq)]; exact ehave shape : (a ∈ s.p ∧ b ∈ s.q) ∨ (b ∈ s.p ∧ a ∈ s.q) := byby_cases hap : a ∈ s.p· leftrefine ⟨hap,?_⟩apply Classical.byContradictionintro hbnapply hqintro x hxsimp only [keep, List.mem_cons, List.not_mem_nil, or_false, not_or]exact ⟨fun eq => s.disjoint a hap (eq ▸ hx), fun eq => hbn (eq ▸ hx)⟩· have hbp : b ∈ s.p := byapply Classical.byContradictionintro hbnapply hpintro x hxsimp only [keep, List.mem_cons, List.not_mem_nil, or_false, not_or]exact ⟨fun eq => hap (eq ▸ hx), fun eq => hbn (eq ▸ hx)⟩rightrefine ⟨hbp,?_⟩apply Classical.byContradictionintro hanapply hqintro x hxsimp only [keep, List.mem_cons, List.not_mem_nil, or_false, not_or]exact ⟨fun eq => han (eq ▸ hx),fun eq => s.disjoint b hbp (eq ▸ hx)⟩obtain ⟨bit,hp1,hq1,ca,cb⟩ :∃ bit : Bool, select [a,b] s.p ++ select [a,b] s.q = pair a b bit ∧select [a,b] s.q ++ select [a,b] s.p = pair a b (!bit) ∧s.pre.count a = m ∧ s.pre.count b = m := byrcases shape with ⟨pa,qb⟩ | ⟨pb,qa⟩· have p' := select_lone a b s.p s.dp pa (fun pb => s.disjoint b pb qb)have q' := select_lone b a s.q s.dq qb (s.disjoint a pa)rw [select_pair_symm] at q'exact ⟨false,by rw [p',q']; rfl,by rw [p',q']; rfl,s.indexP a pa,s.indexQ b qb⟩· have p' := select_lone b a s.p s.dp pb (fun pa => s.disjoint a pa qa)rw [select_pair_symm] at p'have q' := select_lone a b s.q s.dq qa (s.disjoint b pb)exact ⟨true,by rw [p',q']; rfl,by rw [p',q']; rfl,s.indexQ a qa,s.indexP b pb⟩have len : (select [a,b] s.pre).length = (profilePrefix a b tag).length := byrw [length_select_pair a b hab, ca, cb, hm, profile_prefix_length]; omegaunfold typed before after profilesimp only [select_append]rw [← List.append_assoc (select [a,b] s.p), hp1,← List.append_assoc (select [a,b] s.q), hq1]exact exchange_at_split a b _ _ _ _ len bitend Problem455.Slotsend/- Begin Problem455Closure (from finite-semigroup-identity-bases). -/sectionnamespace P455Closureuniverse uvariable {α : Type u} [DecidableEq α]def Cap (r : Nat) (w : List α) : Prop := ∀ a, w.count a ≤ r/-- false denotes block p and true denotes block q. -/def phasePair (b : Bool) : List Bool := [b, !b]def fixedPhases (tag : List Bool) : List Bool :=(List.replicate 5 [false,true,false,true]).flatten ++ tag.flatMap phasePair ++ phasePair false/-- The fillers before fixed phase tokens, before the mutable pair, andbefore the two final tokens may be arbitrary lists, including empty.A frame spans from the first p to the last q. -/structure Frame (α : Type u) wherepHead : αpTail : List αqInit : List αqLast : αtag : List Boolmiddle : List (List α × Bool)beforeMutable : List αbeforeFinalP : List αbeforeFinalQ : List αnamespace Framevariable (f : Frame α)def p := f.pHead :: f.pTaildef q := f.qInit ++ [f.qLast]def pair (b : Bool) := if b then f.q ++ f.p else f.p ++ f.qdef early := f.p ++ f.p ++ f.q ++ f.p ++ f.q ++ f.qdef mid := f.middle.flatMap fun e => e.1 ++ (if e.2 then f.q else f.p)def core (b : Bool) := f.early ++ f.mid ++ f.beforeMutable ++ f.pair b ++f.beforeFinalP ++ f.p ++ f.beforeFinalQ ++ f.q/-- The count condition explicitly encodes that the r designated copiesof each block exhaust its alphabet; all intervening fillers are inertfor the two blocks. Mark may be stored in either order. -/def Valid (r : Nat) (Allowed : List Bool → Prop) (Mark : α → α → Prop) : Prop :=r = 16 + f.tag.length ∧ Allowed f.tag ∧ f.middle.map Prod.snd = fixedPhases f.tag ∧f.p.Nodup ∧ f.q.Nodup ∧ (∀ a ∈ f.p, a ∉ f.q) ∧(∀ a ∈ f.p, ∀ b ∈ f.q, ¬ Mark a b ∧ ¬ Mark b a) ∧(∀ a, a ∈ f.p ∨ a ∈ f.q → (f.core false).count a = r)theorem count_core (a : α) (b : Bool) : (f.core b).count a = (f.core (!b)).count a := bycases b <;> simp [core, pair, List.count_append] <;> omegaomit [DecidableEq α] intheorem core_starts (b : Bool) : ∃ tail, f.core b = f.pHead :: tail := bysimp [core, early, p]omit [DecidableEq α] intheorem core_ends (b : Bool) : ∃ ini, f.core b = ini ++ [f.qLast] := byunfold core qrw [← List.append_assoc]exact ⟨_, rfl⟩private theorem count_tag_pairs (tag : List Bool) (side : Bool) :(tag.flatMap phasePair).count side = tag.length := byinduction tag with| nil => rfl| cons b bs ih =>cases b <;> cases side <;> simp_all [phasePair,List.count_cons,Nat.add_comm]private theorem fixed_count (tag : List Bool) (side : Bool) :(fixedPhases tag).count side = 11 + tag.length := bycases side <;> simp [fixedPhases,count_tag_pairs,phasePair,List.count_cons,Nat.add_comm,List.replicate_succ] <;> omegaprivate theorem token_count_le (p q : List α) (a : α) (side : Bool)(has : 1 ≤ (if side then q else p).count a) (es : List (List α × Bool)) :(es.map Prod.snd).count side ≤(es.flatMap fun e => e.1 ++ (if e.2 then q else p)).count a := byinduction es with| nil => simp| cons hd es ih =>obtain ⟨w,b⟩ := hdcases b <;> cases side <;>simp only [Bool.false_eq_true,if_false,if_true] at has <;>simp [List.count_cons] <;> omegaprivate theorem index_of_order {r : Nat} (hr : r = 16 + f.tag.length)(hmid : f.middle.map Prod.snd = fixedPhases f.tag) (bit : Bool) (l t : List α)(hc : Cap r (l ++ f.core bit ++ t)) (a : α) (ha : a ∈ f.p ∨ a ∈ f.q) :(l ++ f.early ++ f.mid ++ f.beforeMutable).count a = 14 + f.tag.length := byhave hcap := hc ahave hpq : 1 ≤ f.p.count a ∨ 1 ≤ f.q.count a := ha.imp List.count_pos_iff.mpr List.count_pos_iff.mprhave h1 : 11 + f.tag.length ≤ f.mid.count a := byrcases hpq with hp | hq· have h := token_count_le f.p f.q a false (by simpa using hp) f.middlesimpa [hmid,fixed_count,mid] using h· have h := token_count_le f.p f.q a true (by simpa using hq) f.middlesimpa [hmid,fixed_count,mid] using hhave h2 : 3 ≤ f.early.count a := by simp [early]; omegahave h3 : 1 ≤ (f.pair bit).count a := by cases bit <;> simp [pair] <;> omegasimp only [core,List.count_append] at hcap ⊢omega/-- Every block label has zero-based occurrence index 14+k at the mutablepair. Counts are derived from the actual profile and the cap; neitheran index hypothesis nor any restriction on outsiders in context is needed. -/theorem mutable_index {r : Nat} {Allowed : List Bool → Prop} {Mark : α → α → Prop}(hf : f.Valid r Allowed Mark) (bit : Bool) (l t : List α)(hc : Cap r (l ++ f.core bit ++ t)) (a : α) (ha : a ∈ f.p ∨ a ∈ f.q) :(l ++ f.early ++ f.mid ++ f.beforeMutable).count a = 14 + f.tag.length := byexact f.index_of_order hf.1 hf.2.2.1 bit l t hc a ha/-- Literal occurrence exhaustion follows from the phase order and cap.This shows the saturation field in Valid cannot exclude any cappedarrangement of the prescribed blocks, including arrangements withpreviously unrestricted fillers. -/theorem saturation_of_order {r : Nat} (hr : r = 16 + f.tag.length)(hmid : f.middle.map Prod.snd = fixedPhases f.tag) (bit : Bool) (l t : List α)(hc : Cap r (l ++ f.core bit ++ t)) (a : α) (ha : a ∈ f.p ∨ a ∈ f.q) :(f.core false).count a = r := byhave hc' : Cap r ([] ++ f.core false ++ []) := byintro zhave hh := hc zhave hd : (f.core bit).count z = (f.core false).count z := bycases bit with| false => rfl| true => exact f.count_core z truesimp only [List.count_append,hd, List.count_nil] at *omegahave idx := f.index_of_order hr hmid false [] [] hc' a hahave bound := hc' ahave sup : 1 ≤ f.p.count a ∨ 1 ≤ f.q.count a :=ha.imp List.count_pos_iff.mpr List.count_pos_iff.mprsimp only [List.nil_append,List.append_nil] at idx boundsimp only [core,pair,Bool.false_eq_true,if_false,List.count_append] at idx bound ⊢omegatheorem valid_of_capped_shape {r : Nat} {Allowed : List Bool → Prop} {Mark : α → α → Prop}(hr : r = 16 + f.tag.length) (ht : Allowed f.tag)(order : f.middle.map Prod.snd = fixedPhases f.tag)(dp : f.p.Nodup) (dq : f.q.Nodup) (apart : ∀ a ∈ f.p, a ∉ f.q)(unmarked : ∀ a ∈ f.p, ∀ b ∈ f.q, ¬ Mark a b ∧ ¬ Mark b a)(bit : Bool) (l t : List α) (hc : Cap r (l ++ f.core bit ++ t)) :f.Valid r Allowed Mark :=⟨hr,ht,order,dp,dq,apart,unmarked,f.saturation_of_order hr order bit l t hc⟩/-- A capped enclosing context contributes no extra occurrence of anymoved label, for either choice of the mutable order. -/theorem context_fresh {r : Nat} {Allowed : List Bool → Prop} {Mark : α → α → Prop}(hf : f.Valid r Allowed Mark) (bit : Bool) (l t : List α)(hc : Cap r (l ++ f.core bit ++ t)) (a : α) (ha : a ∈ f.p ∨ a ∈ f.q) :a ∉ l ∧ a ∉ t := byhave hs := hf.2.2.2.2.2.2.2 a hahave hs' : (f.core bit).count a = r := bycases bit with| false => exact hs| true => exact (f.count_core a true).trans hshave hh := hc asimp only [List.count_append,hs'] at hhexact ⟨List.count_eq_zero.mp (by omega),List.count_eq_zero.mp (by omega)⟩def profileBits (tag : List Bool) (bit : Bool) : List Bool :=[false,false,true,false,true,true] ++ fixedPhases tag ++ phasePair bit ++ phasePair falsedef profileWord (x y : α) (tag : List Bool) (bit : Bool) : List α :=(profileBits tag bit).map (fun b => if b then y else x)omit [DecidableEq α] inprivate theorem middle_trace (p q : List α) {x y : α} (hx : x ∈ p) (hy : y ∈ q)(es : List (List α × Bool)) :((es.map Prod.snd).map (fun b => if b then y else x)).Sublist(es.flatMap fun e => e.1 ++ if e.2 then q else p) := byinduction es with| nil => exact .slnil| cons e es ih =>obtain ⟨w,b⟩ := ehave one : [if b then y else x].Sublist (w ++ (if b then q else p)) := byapply List.sublist_append_of_sublist_rightcases b <;> simp [hx,hy]exact one.append ihomit [DecidableEq α] inprivate theorem profile_trace (bit : Bool) (x y : α) (hx : x ∈ f.p) (hy : y ∈ f.q)(order : f.middle.map Prod.snd = fixedPhases f.tag) :(profileWord x y f.tag bit).Sublist (f.core bit) := byhave px := List.singleton_sublist.mpr hxhave qy := List.singleton_sublist.mpr hyhave ea := ((((px.append px).append qy).append px).append qy).append qyhave mi := middle_trace f.p f.q hx hy f.middlerw [order] at mihave swapped : ((phasePair bit).map (fun b => if b then y else x)).Sublist (f.pair bit) := bycases bit with| false => exact px.append qy| true => exact qy.append pxhave pref := (ea.append mi).append (List.nil_sublist f.beforeMutable)have whole := (((((pref.append swapped).append (List.nil_sublist f.beforeFinalP)).append px).append(List.nil_sublist f.beforeFinalQ)).append qy)simpa only [profileWord,profileBits,core,early,List.map_append,List.append_nil,phasePair,List.map_cons,List.map_nil,Bool.false_eq_true,if_false,if_true,List.append_assoc,List.cons_append,List.nil_append, mid, Bool.not_false] using wholeomit [DecidableEq α] inprivate theorem pattern_length (x y : α) (tag : List Bool) (bit : Bool) :(profileWord x y tag bit).length = 2 * (16 + tag.length) := byhave tl : (tag.flatMap phasePair).length = 2 * tag.length := byinduction tag with| nil => rfl| cons b t ih => simp [phasePair,ih]; omegasimp [profileWord,profileBits,fixedPhases,phasePair,List.replicate_succ,tl]omegaprivate theorem select_length (x y : α) (w : List α) :(w.filter (fun a => decide (a = x ∨ a = y))).length ≤ w.count x + w.count y := byinduction w with| nil => simp| cons a as ih =>by_cases hx : a = x <;> by_cases hy : a = y <;>simp [hx,hy,List.count_cons,beq_iff_eq] at ih ⊢ <;> omegatheorem cross_projection {r : Nat} {Allowed : List Bool → Prop} {Mark : α → α → Prop}(hf : f.Valid r Allowed Mark) (bit : Bool) (l t : List α)(hc : Cap r (l ++ f.core bit ++ t)) (x y : α) (hx : x ∈ f.p) (hy : y ∈ f.q) :(l ++ f.core bit ++ t).filter (fun a => decide (a = x ∨ a = y)) =profileWord x y f.tag bit := byhave tr := f.profile_trace bit x y hx hy hf.2.2.1have tr' : (profileWord x y f.tag bit).Sublist (l ++ f.core bit ++ t) :=List.sublist_append_of_sublist_left (List.sublist_append_of_sublist_right tr)let keep := fun (a : α) => decide (a = x ∨ a = y)have intact : (profileWord x y f.tag bit).filter keep = profileWord x y f.tag bit := byapply List.filter_eq_self.mprintro a haobtain ⟨b,_,rfl⟩ := List.mem_map.mp hacases b <;> simp [keep]have tt := tr'.filter keeprw [intact] at ttapply Eq.symmapply tt.eq_of_length_lehave h := select_length x y (l ++ f.core bit ++ t)have h1 := hc xhave h2 := hc yhave hr := hf.1change ((l ++ f.core bit ++ t).filter (fun a => decide (a = x ∨ a = y))).length ≤ _rw [pattern_length]omegaend Frame/-- A single literal permitted swap, with both words written in the sameexternal context. All r copies of p and q are in the frame. -/def Move (r : Nat) (Allowed : List Bool → Prop) (Mark : α → α → Prop)(u v : List α) : Prop :=∃ (f : Frame α) (b : Bool) (l t : List α),f.Valid r Allowed Mark ∧ u = l ++ f.core b ++ t ∧v = l ++ f.core (!b) ++ t ∧ Cap r uvariable {r : Nat} {Allowed : List Bool → Prop} {Mark : α → α → Prop} {u v : List α}namespace Movetheorem count_eq (h : Move r Allowed Mark u v) (a : α) : u.count a = v.count a := byobtain ⟨f,b,l,t,_,hu,hv,_⟩ := hrw [hu,hv]simp only [List.count_append, f.count_core a b]theorem cap_left (h : Move r Allowed Mark u v) : Cap r u := byobtain ⟨_,_,_,_,_,_,_,hc⟩ := hexact hctheorem cap_right (h : Move r Allowed Mark u v) : Cap r v := byintro arw [← h.count_eq]exact h.cap_left atheorem symm (h : Move r Allowed Mark u v) : Move r Allowed Mark v u := byhave hc := h.cap_rightobtain ⟨f,b,l,t,hf,hu,hv,_⟩ := hexact ⟨f,!b,l,t,hf,hv,by simpa using hu,hc⟩/-- Extending a factor-local move to any capped context uses the sameliteral frame. Cap excludes a new occurrence of either block's labels. -/theorem extend_of_cap (h : Move r Allowed Mark u v) (l t : List α)(hc : Cap r (l ++ u ++ t)) : Move r Allowed Mark (l ++ u ++ t) (l ++ v ++ t) := byobtain ⟨f,b,i,j,hf,hu,hv,_⟩ := hrefine ⟨f,b,l ++ i,j ++ t,hf,?_,?_,hc⟩ <;> simp [hu,hv,List.append_assoc]end Moveomit [DecidableEq α] in/-- Two splittings of a word, when the prefix on the left avoids thedisplayed occurrence on the right. The shorter prefix is on the left. -/private theorem stripBefore {a : α} {l p z s : List α}(h : l ++ z = p ++ a :: s) (ha : a ∉ l) :∃ d, p = l ++ d ∧ z = d ++ a :: s := byinduction l generalizing p with| nil => exact ⟨p, by simp, by simpa using h⟩| cons x l ih =>cases p with| nil =>have hx : x = a := (List.cons.inj h).1exact False.elim (ha (by simp [hx]))| cons y p =>obtain ⟨hxy,hrest⟩ := List.cons.inj hobtain ⟨d,hp,hz⟩ := ih hrest (fun hm => ha (by simp [hm]))exact ⟨d,by simp [hp,hxy],hz⟩omit [DecidableEq α] in/-- In two splittings of a word, the factor x contains the whole corewhenever the left context avoids its first symbol and the rightcontext avoids its last symbol. Either context may be empty. -/theorem containCore {l x t i c j : List α} {a b : α}(h : l ++ x ++ t = i ++ c ++ j)(ha : a ∉ l) (hb : b ∉ t)(hfirst : ∃ s, c = a :: s) (hlast : ∃ k, c = k ++ [b]) :∃ d e, i = l ++ d ∧ j = e ++ t ∧ x = d ++ c ++ e := byobtain ⟨s,hs⟩ := hfirsthave h1 : l ++ (x ++ t) = i ++ a :: (s ++ j) := by simpa [hs,List.append_assoc] using hobtain ⟨d,hi,hxt⟩ := stripBefore h1 haobtain ⟨k,hk⟩ := hlasthave h2 : t.reverse ++ x.reverse = j.reverse ++ b :: (k.reverse ++ d.reverse) := byhave h' : x ++ t = d ++ c ++ j := by simpa [hs,List.append_assoc] using hxtsimpa [hk,List.reverse_append,List.append_assoc] using congrArg List.reverse h'obtain ⟨e,hj,_⟩ := stripBefore h2 (by simpa using hb)have hj' : j = e.reverse ++ t := bysimpa [List.reverse_append] using congrArg List.reverse hjhave hx : l ++ (x ++ t) = l ++ ((d ++ c ++ e.reverse) ++ t) := bysimpa [hi,hj',List.append_assoc] using hexact ⟨d,e.reverse,hi,hj',List.append_cancel_right (List.append_cancel_left hx)⟩/-- Restrict a witnessed global swap to a factor containing all copiesof the boundary anchors. Saturation of the other moving labels isautomatic once this entire frame has been recovered. -/theorem Frame.restrict_of_saturated (f : Frame α) (b : Bool)(hf : f.Valid r Allowed Mark) (l x t i j : List α)(whole : l ++ x ++ t = i ++ f.core b ++ j) (cap : Cap r (l ++ x ++ t))(hp : x.count f.pHead = r) (hq : x.count f.qLast = r) :∃ y, Move r Allowed Mark x y ∧ l ++ y ++ t = i ++ f.core (!b) ++ j := byhave hpl := cap f.pHeadhave hqt := cap f.qLastsimp only [List.count_append,hp,hq] at hpl hqthave hpl' : l.count f.pHead = 0 := by omegahave hqt' : t.count f.qLast = 0 := by omegaobtain ⟨d,e,hi,hj,hx⟩ := containCore whole (List.count_eq_zero.mp hpl')(List.count_eq_zero.mp hqt') (f.core_starts b) (f.core_ends b)have hxcap : Cap r x := byintro ahave hh := cap asimp only [List.count_append] at hhomegarefine ⟨d ++ f.core (!b) ++ e,⟨f,b,d,e,hf,hx,rfl,hxcap⟩,?_⟩simp [hi,hj,List.append_assoc]end P455Closureend/- Begin Problem455Swap (from finite-semigroup-identity-bases). -/sectionnamespace Problem455Swapabbrev Word := List Natdef occ (a : Nat) : Word → Nat| [] => 0| b :: w => (if a = b then 1 else 0) + occ a wdef cap (r : Nat) (w : Word) : Prop := ∀ a, occ a w ≤ rdef hit (x y : Nat) (left right : Option Nat) : Nat :=if left = some x ∧ right = some y then 1 else 0def bigram (x y : Nat) : Word → Nat| [] => 0| a :: w => hit x y (some a) w.head? + bigram x y wdef Link (r : Nat) (w : Word) (x y : Nat) : Prop := bigram x y w = rtheorem occ_append (a : Nat) (u v : Word) : occ a (u ++ v) = occ a u + occ a v := byinduction u with| nil => simp [occ]| cons b u ih => simp [occ, ih, Nat.add_assoc]theorem bigram_append (x y : Nat) (u v : Word) :bigram x y (u ++ v) = bigram x y u + bigram x y v + hit x y u.getLast? v.head? := byinduction u with| nil => simp [bigram, hit]| cons a u ih =>cases u with| nil => simp [bigram, hit, Nat.add_comm]| cons b w =>change hit x y (some a) (some b) + bigram x y ((b :: w) ++ v) = _rw [ih]simp [bigram, List.getLast?_cons_cons, Nat.add_assoc, Nat.add_left_comm, Nat.add_comm]theorem out_bound (x y z : Nat) (hyz : y ≠ z) (w : Word) :bigram x y w + bigram x z w ≤ occ x w := byinduction w with| nil => simp [bigram, occ]| cons a w ih =>simp only [bigram, occ]unfold hitsplit <;> split <;> split <;> simp_all <;> omegatheorem in_bound (x z y : Nat) (hxz : x ≠ z) (w : Word) :bigram x y w + bigram z y w ≤ occ y w.tail := byinduction w with| nil => simp [bigram, occ]| cons a w ih =>cases w with| nil => simp [bigram, hit, occ]| cons b w =>change hit x y (some a) (some b) + bigram x y (b :: w) +(hit z y (some a) (some b) + bigram z y (b :: w)) ≤ occ y (b :: w)simp only [List.tail_cons] at ihsimp only [occ]unfold hitsplit <;> split <;> split <;> simp_all <;> omegatheorem tail_occ_le (a : Nat) (w : Word) : occ a w.tail ≤ occ a w := bycases w <;> simp [occ]def Factor (u w : Word) : Prop := ∃ l t, w = l ++ u ++ ttheorem factor_pos (x y : Nat) {u w : Word} (hu : Factor u w)(h : 0 < bigram x y u) : 0 < bigram x y w := byobtain ⟨l,t,rfl⟩ := hurw [bigram_append, bigram_append]omegadef privatePhase (p q : Word) := p ++ p ++ q ++ p ++ q ++ qprivate theorem private_boundaries {p q w : Word} {i j s t : Nat}(hf : Factor (privatePhase p q) w)(hp : p.head? = some i) (hq : q.head? = some j)(ep : p.getLast? = some s) (eq : q.getLast? = some t) :0 < bigram s i w ∧ 0 < bigram s j w ∧ 0 < bigram t i w ∧ 0 < bigram t j w := byhave pn : p ≠ [] := by intro e; simp [e] at hphave qn : q ≠ [] := by intro e; simp [e] at hqrefine ⟨factor_pos _ _ hf ?_, factor_pos _ _ hf ?_, factor_pos _ _ hf ?_, factor_pos _ _ hf ?_⟩ <;>simp only [privatePhase, bigram_append, List.getLast?_append, ep, eq, hp, hq] <;>simp [hit] <;> omegaprivate theorem safe_ends {p q w : Word} {i j s t x y r : Nat}(hc : cap r w) (hf : Factor (privatePhase p q) w)(hp : p.head? = some i) (hq : q.head? = some j)(ep : p.getLast? = some s) (eq : q.getLast? = some t)(hij : i ≠ j) (hst : s ≠ t) (hxy : Link r w x y) :x ≠ s ∧ x ≠ t ∧ y ≠ i ∧ y ≠ j := byobtain ⟨hsi,hsj,hti,htj⟩ := private_boundaries hf hp hq ep eqhave outs (a : Nat) (hai : 0 < bigram a i w) (haj : 0 < bigram a j w) : x ≠ a := byintro h; subst aby_cases hy : y = i· subst yhave b := out_bound x i j hij whave c := hc xunfold Link at hxyomega· have b := out_bound x y i hy whave c := hc xunfold Link at hxyomegahave ins (a : Nat) (hsa : 0 < bigram s a w) (hta : 0 < bigram t a w) : y ≠ a := byintro h; subst aby_cases hx : x = s· subst xhave b := in_bound s t y hst whave c := hc yhave d := tail_occ_le y wunfold Link at hxyomega· have b := in_bound x s y hx whave c := hc yhave d := tail_occ_le y wunfold Link at hxyomegaexact ⟨outs s hsi hsj, outs t hti htj, ins i hsi hti, ins j hsj htj⟩private theorem safe_count_swap {p q : Word} {i j s t x y : Nat} (l u : Word)(hp : p.head? = some i) (hq : q.head? = some j)(ep : p.getLast? = some s) (eq : q.getLast? = some t)(h : x ≠ s ∧ x ≠ t ∧ y ≠ i ∧ y ≠ j) :bigram x y (l ++ p ++ q ++ u) = bigram x y (l ++ q ++ p ++ u) := byobtain ⟨xs,xt,yi,yj⟩ := hsimp only [bigram_append, List.getLast?_append, ep, eq, hp, hq]simp [hit, Ne.symm xs, Ne.symm xt, Ne.symm yi, Ne.symm yj]omegatheorem repeatedLink_swap {p q : Word} {i j s t r : Nat} (l u : Word)(hp : p.head? = some i) (hq : q.head? = some j)(ep : p.getLast? = some s) (eq : q.getLast? = some t)(hij : i ≠ j) (hst : s ≠ t)(hc : cap r (l ++ p ++ q ++ u))(hf : Factor (privatePhase p q) (l ++ p ++ q ++ u))(hg : Factor (privatePhase p q) (l ++ q ++ p ++ u)) (x y : Nat) :Link r (l ++ p ++ q ++ u) x y ↔ Link r (l ++ q ++ p ++ u) x y := byhave hd : cap r (l ++ q ++ p ++ u) := byintro ahave b := hc asimp only [occ_append] at b ⊢omegaconstructor· intro hhave good := safe_ends hc hf hp hq ep eq hij hst hexact (safe_count_swap l u hp hq ep eq good).symm.trans h· intro hhave good := safe_ends hd hg hp hq ep eq hij hst hexact (safe_count_swap l u hp hq ep eq good).trans h/-- Nonoriented finite paths generate the repeated-block partition onsaturated letters. Singletons occur as paths of length zero. -/inductive Joined (edges : Nat → Nat → Prop) : Nat → Nat → Prop where| refl (x) : Joined edges x x| extend {x y z} : Joined edges x y → (edges y z ∨ edges z y) → Joined edges x zdef SameBlock (r : Nat) (w : Word) (x y : Nat) : Prop :=occ x w = r ∧ occ y w = r ∧ Joined (Link r w) x ytheorem sameBlock_swap {p q : Word} {i j s t r : Nat} (l u : Word)(hp : p.head? = some i) (hq : q.head? = some j)(ep : p.getLast? = some s) (eq : q.getLast? = some t)(hij : i ≠ j) (hst : s ≠ t)(hc : cap r (l ++ p ++ q ++ u))(hf : Factor (privatePhase p q) (l ++ p ++ q ++ u))(hg : Factor (privatePhase p q) (l ++ q ++ p ++ u)) (x y : Nat) :SameBlock r (l ++ p ++ q ++ u) x y ↔ SameBlock r (l ++ q ++ p ++ u) x y := byhave e : Link r (l ++ p ++ q ++ u) = Link r (l ++ q ++ p ++ u) :=funext fun a => funext fun b => propext (repeatedLink_swap l u hp hq ep eq hij hst hc hf hg a b)simp only [SameBlock, e, occ_append]constructor <;> rintro ⟨h1,h2,h3⟩ <;> exact ⟨by omega, by omega, h3⟩/-- Every repeated link inside a proper or improper literal factor remainsa link of a capped enclosing word. To pull a block distinction backfrom the enclosing tester, only this direction is needed. -/theorem link_factor {r x y : Nat} {w u : Word} (f : Factor u w)(hc : cap r w) (h : Link r u x y) : Link r w x y := byhave bound := out_bound x y (y+1) (by omega) whave ceil := hc xobtain ⟨l,t,rfl⟩ := funfold Link at *rw [bigram_append, bigram_append] at bound ⊢omegaprivate theorem joined_of_imp {e d : Nat → Nat → Prop} {a b : Nat}(h : ∀ x y, e x y → d x y) (j : Joined e a b) : Joined d a b := byinduction j with| refl => exact .refl _| extend walk last ih =>exact .extend ih (last.imp (h _ _) (h _ _))theorem sameBlock_factor {r x y : Nat} {w u : Word} (f : Factor u w)(hc : cap r w) (h : SameBlock r u x y) : SameBlock r w x y := byobtain ⟨hx,hy,hj⟩ := hrefine ⟨?_,?_,joined_of_imp (fun _ _ hh => link_factor f hc hh) hj⟩all_goalsobtain ⟨l,t,rfl⟩ := fhave bx := hc xhave by' := hc ysimp only [occ_append] at bx by' ⊢omegaend Problem455Swapend/- Begin Problem455DonorInterval (from finite-semigroup-identity-bases). -/sectionnamespace P455DonorIntervaluniverse u vvariable {α : Type u} {β : Type v} [DecidableEq α] [DecidableEq β]/-- Count the contributions of one chosen donor and all other variablesseparately, with equality for every source word. -/theorem split_contributions (h : α → List β) (w : List α) (x : α) (s : β) :(w.flatMap h).count s = w.count x * (h x).count s +((w.filter (fun a => decide (a ≠ x))).flatMap h).count s := byinduction w with| nil => simp| cons a w ih =>by_cases e : a = x· subst asimp [List.count_cons, Nat.add_mul, ih, Nat.add_comm, Nat.add_left_comm, Nat.add_assoc]· simp [List.count_cons, e, Ne.symm e, ih, Nat.add_comm, Nat.add_left_comm, Nat.add_assoc]/-- A label contributed by a positively saturated source variable iscontributed exactly once per occurrence, and by no other variablepresent in the evaluated side. A global cap only on this label suffices. -/theorem exclusive (h : α → List β) (w : List α) (x : α) (s : β) (r : Nat)(hr : 0 < r) (hx : w.count x = r) (mem : s ∈ h x)(bound : (w.flatMap h).count s ≤ r) :(h x).count s = 1 ∧(∀ y ∈ w, y ≠ x → s ∉ h y) ∧ (w.flatMap h).count s = r := byhave spl := split_contributions h w x srw [hx] at splhave pos := List.count_pos_iff.mpr memhave one : (h x).count s = 1 := byapply Classical.byContradictionintro diffhave two : 2 ≤ (h x).count s := by omegahave ge := Nat.mul_le_mul_left r tworw [Nat.mul_two] at geomegarw [one,Nat.mul_one] at splhave none : s ∉ (w.filter (fun a => decide (a ≠ x))).flatMap h :=List.count_eq_zero.mp (by omega)refine ⟨one,?_,by omega⟩intro y hy hne in_yapply noneexact List.mem_flatMap.mpr ⟨y,List.mem_filter.mpr ⟨hy,by simpa using hne⟩,in_y⟩/-- Within any chosen sublist of the evaluated source, occurrence numbersfor an exclusively supplied label agree with those of its source variable. -/theorem count_on_subword (h : α → List β) (w u : List α) (x : α) (s : β)(inside : ∀ y ∈ u, y ∈ w) (single : (h x).count s = 1)(exclusive : ∀ y ∈ w, y ≠ x → s ∉ h y) :(u.flatMap h).count s = u.count x := byinduction u with| nil => simp| cons a u ih =>have rest := ih (fun y hy => inside y (by simp [hy]))by_cases eq : a = x· subst a; simp [List.count_cons,single,rest,Nat.add_comm]· have na := exclusive a (inside a (by simp)) eqsimp [List.count_cons,eq,Ne.symm eq,List.count_eq_zero.mpr na,rest]/-- The literal open interval between corresponding consecutive copies of s.The final equality identifies the zero-based index of its left endpoint;the absence clause certifies consecutiveness in the output word. -/theorem consecutive_interval (h : α → List β) (U L I R : List α)(x : α) (s : β) (p q : List β) (r : Nat)(cut : U = L ++ [x] ++ I ++ [x] ++ R) (consecutive : x ∉ I)(image : h x = p ++ [s] ++ q)(saturated : U.count x = r) (bounded : (U.flatMap h).count s ≤ r) :(∀ y ∈ U, y ≠ x → s ∉ h y) ∧ s ∉ p ∧ s ∉ q ∧s ∉ q ++ I.flatMap h ++ p ∧U.flatMap h = (L.flatMap h ++ p) ++ [s] ++ (q ++ I.flatMap h ++ p) ++[s] ++ (q ++ R.flatMap h) ∧(L.flatMap h ++ p).count s = L.count x ∧ (U.flatMap h).count s = r := byhave hr : 0 < r := byrw [← saturated]exact List.count_pos_iff.mpr (by simp [cut])have hx : s ∈ h x := by simp [image]obtain ⟨single,noOther,full⟩ := exclusive h U x s r hr saturated hx boundedhave single' := singlesimp only [image,List.count_append,List.count_singleton_self] at single'have hp : s ∉ p := List.count_eq_zero.mp (by omega)have hq : s ∉ q := List.count_eq_zero.mp (by omega)have inner : (I.flatMap h).count s = I.count x := count_on_subword h U I x s(fun y hy => by simp [cut,hy]) single noOtherhave hi : s ∉ I.flatMap h := List.count_eq_zero.mp (inner.trans (List.count_eq_zero.mpr consecutive))have left := count_on_subword h U L x s (fun y hy => by simp [cut,hy]) single noOtherexact ⟨noOther,hp,hq,by simp [hp,hq,hi],by simp [cut,image,List.flatMap_append,List.append_assoc],by simp [left,List.count_eq_zero.mpr hp],full⟩omit [DecidableEq α] [DecidableEq β] in/-- Once an occupant is excluded from the boundary donor's image, someliteral name of the open source slot supplies it. No global conditionon the other images or gap alphabets enters this inference. -/theorem interior_supplier (h : α → List β) (I : List α) (x : α) (s t : β)(p q : List β) (image : h x = p ++ [s] ++ q)(occupies : t ∈ q ++ I.flatMap h ++ p) (other : t ∉ h x) :∃ y ∈ I, t ∈ h y := byhave nowhere := othersimp only [image,List.mem_append,List.mem_singleton,not_or] at nowheresimp only [List.mem_append] at occupiesrcases occupies with (hq | hi) | hp· exact False.elim (nowhere.2 hq)· exact List.mem_flatMap.mp hi· exact False.elim (nowhere.1.1 hp)/-- If the literal output is a factor of a capped enclosing variant, everycopy of s occurs in that factor. In particular external context cannotchange the absolute occurrence indices of its two slot endpoints. -/theorem enclosing_context (F left right : List β) (s : β) (r : Nat)(saturated : F.count s = r) (capped : (left ++ F ++ right).count s ≤ r) :s ∉ left ∧ s ∉ right := bysimp only [List.count_append,saturated] at cappedexact ⟨List.count_eq_zero.mp (by omega),List.count_eq_zero.mp (by omega)⟩end P455DonorIntervalend/- Begin Problem455MathlibCode (from finite-semigroup-identity-bases). -/sectionnamespace P455MathlibCodeopen Turing Turing.PartrecToTM2def pos : List Bool → PosNum| [] => .one| true :: xs => .bit1 (pos xs)| false :: xs => .bit0 (pos xs)def wire (xs : List Bool) : Nat := pos xs.reversedef letter : Bool → Γ' | false => .bit0 | true => .bit1theorem trPos (xs : List Bool) : trPosNum (pos xs) = xs.map letter ++ [.bit1] := byinduction xs with| nil => rfl| cons b xs ih => cases b <;> simp [pos,trPosNum,letter,ih]theorem raw_main (xs : List Bool) :(trList [wire xs]).reverse = .cons :: .bit1 :: xs.map letter := bysimp [wire,trNat,PosNum.of_to_nat,trNum,trPos,← List.map_reverse]theorem pos_injective : Function.Injective pos := byintro xsinduction xs with| nil => rintro (_|⟨_ | _,_⟩) h <;> simp [pos] at *| cons b xs ih =>rintro (_ | ⟨c,cs⟩) h· cases b <;> simp [pos] at h· cases b <;> cases c <;> simp [pos] at h ⊢ <;> exact ih htheorem wire_injective : Function.Injective wire := byintro x y hhave hn := congrArg (fun n : Nat => (n : Num)) hsimp only [wire,PosNum.of_to_nat,Num.pos.injEq] at hnsimpa using congrArg List.reverse (pos_injective hn)def op (b : Bool) (n : Nat) := if b = true then (n+n)+1 else n+ntheorem pos_fold (xs : List Bool) : (pos xs : Nat) = xs.foldr op 1 := byinduction xs with| nil => rfl| cons b xs ih => cases b <;> simp [pos,op,List.foldr,PosNum.cast_bit0,PosNum.cast_bit1,ih]theorem wire_prim : Primrec wire := byhave h : Primrec (fun z : Bool × Nat => op z.1 z.2) := byexact Primrec.ite (Primrec.eq.comp Primrec.fst (.const true))(Primrec.nat_add.comp (Primrec.nat_add.comp Primrec.snd Primrec.snd) (.const 1))(Primrec.nat_add.comp Primrec.snd Primrec.snd)exact (Primrec.list_foldr Primrec.list_reverse (.const 1) (h.comp Primrec.snd).to₂).of_eqfun xs => (pos_fold xs.reverse).symmdef candidate (n : Nat) := (Encodable.decode (α := List Bool) n).getD []def check (z n : Nat) : Option (List Bool) :=if wire (candidate n) = z then some (candidate n) else nonetheorem check_prim : Primrec₂ check := byhave h : Primrec candidate := Primrec.option_getD.comp Primrec.decode (.const [])exact (Primrec.ite (Primrec.eq.comp (wire_prim.comp (h.comp Primrec.snd)) Primrec.fst)(Primrec.option_some.comp (h.comp Primrec.snd)) (.const none)).to₂theorem find_wire (x : List Bool) : x ∈ Nat.rfindOpt (check (wire x)) := byhave ok : check (wire x) (Encodable.encode x) = some x := by simp [check,candidate]have d := Nat.rfindOpt_dom.mpr ⟨_,x,ok⟩have h := Part.get_mem dobtain ⟨n, hn⟩ := Nat.rfindOpt_spec hunfold check at hnsplit at hnnext ht => exact Eq.mp (congrArg (fun b => b ∈ Nat.rfindOpt (check (wire x)))((Option.some.inj hn).symm.trans (wire_injective ht))) hnext => contradiction/-- One finite partial-recursive instruction tree, fixed before all inputs,operates on the sentinel-terminated positive integer wire codes. -/theorem compile {f : List Bool → List Bool} (hf : Computable f) :∃ c : ToPartrec.Code, ∀ x, [wire (f x)] ∈ c.eval [wire x] := bylet F : Nat →. Nat := fun n => (Nat.rfindOpt (check n)).map (fun x => wire (f x))have hF : Partrec F := (Partrec.rfindOpt check_prim.to_comp).map (((wire_prim.to_comp.comp hf).comp Computable.snd).to₂)obtain ⟨c,hc⟩ := ToPartrec.Code.exists_code (Nat.Partrec'.part_iff₁.mpr hF)refine ⟨c,fun x => ?_⟩let v : List.Vector Nat 1 := ⟨[wire x],rfl⟩rw [show c.eval [wire x] = _ from hc v]exact (Part.mem_map_iff _).mpr ⟨_,(Part.mem_map_iff _).mpr ⟨_,find_wire x,rfl⟩,rfl⟩end P455MathlibCodeend/- Begin Problem455MathlibMarker (from finite-semigroup-identity-bases). -/sectionnamespace P455MathlibMarkeropen Turingvariable {K : Type} {G : K → Type} {L V : Type} [DecidableEq K]abbrev Track := TM2to1.Γ' K Gdef safe : TM1.Stmt (Track (G := G)) L V → Prop| .move _ s | .load _ s => safe s| .write w s => (∀ a v, (w a v).1 = a.1) ∧ safe s| .branch _ p q => safe p ∧ safe q| .goto _ | .halt => Trueomit [DecidableEq K] intheorem trNormal_safe (s : TM2.Stmt G L V) : safe (TM2to1.trNormal s) := byinduction s <;> simp_all [TM2to1.trNormal,safe]theorem tr_safe (M : L → TM2.Stmt G L V) (q) : safe (TM2to1.tr M q) := bycases q with| normal => exact trNormal_safe _| ret => exact ⟨trNormal_safe _,True.intro⟩| go k s q => cases s <;> simp [TM2to1.tr,TM2to1.trStAct,safe]variable [Inhabited L] [Inhabited V]variable (M : L → TM1.Stmt (Track (G := G)) L V)def safeState (q : TM1to0.Λ' M) := ∀ p ∈ q.1, safe pdef preserves (a : Track (G := G)) : TM0.Stmt (Track (G := G)) → Prop| .move _ => True| .write b => b.1=a.1variable (hm : ∀ l, safe (M l))include hmomit [DecidableEq K] [Inhabited L] [Inhabited V] intheorem trAux_safe (a : Track (G := G)) (p : TM1.Stmt (Track (G := G)) L V)(hp : safe p) (v) :safeState M (TM1to0.trAux M a p v).1 ∧ preserves a (TM1to0.trAux M a p v).2 := byinduction p generalizing v with| move _ q => simpa [TM1to0.trAux,safeState,preserves,safe] using hp| write w q => exact ⟨fun _ h => Option.some.inj h ▸ hp.2, hp.1 _ _⟩| load _ _ ih => exact ih hp _| branch b p q ih₁ ih₂ =>cases e : b a v <;> simp only [TM1to0.trAux,e,cond] <;> first | exact ih₁ hp.1 v | exact ih₂ hp.2 v| goto l => simpa [TM1to0.trAux,safeState,preserves] using hm (l a v)| halt => simp [TM1to0.trAux,safeState,preserves]omit [DecidableEq K] intheorem guarded {S : Finset (TM1to0.Λ' M)} (hs : TM0.Supports (TM1to0.tr M) ↑S) :∃ U : Finset (TM1to0.Λ' M), TM0.Supports (TM1to0.tr M) ↑U ∧∀ q ∈ U, ∀ a q' b, (TM1to0.tr M) q a = some (q',.write b) → b.1=a.1 := byclassicalrefine ⟨S.filter (safeState M), ⟨?_,?_⟩,?_⟩· apply Finset.mem_filter.mprrefine ⟨hs.1, ?_⟩intro p hpchange some (M default) = some p at hpexact (Option.some.inj hp) ▸ hm default· rintro ⟨_ | p,v⟩ a q' s step good· contradictionobtain ⟨mem,safeP⟩ := Finset.mem_filter.mp goodhave hp := safeP p rflhave h := (trAux_safe M hm a p hp v).1exact Finset.mem_filter.mpr ⟨hs.2 step mem,(congrArg (safeState M) (congrArg Prod.fst (Option.some.inj step))).mp h⟩· rintro ⟨_ | p,v⟩ good a q' b step· contradictionhave hp := (Finset.mem_filter.mp good).2 p rflhave h := (trAux_safe M hm a p hp v).2exact (congrArg (preserves a) (congrArg Prod.snd (Option.some.inj step))).mp hend P455MathlibMarkerend/- Begin Problem455ObservationBridge (from finite-semigroup-identity-bases). -/section/- Literal profile-frame move and the observations of marked testers.Names are natural numbers. All occurrence indices in this file are zero-based. -/namespace P455Closure.Moveopen Problem455variable {r : Nat} {Allowed : List Bool → Prop} {Mark : Nat → Nat → Prop}{u v : List Nat}/-- Extract adjacent, commonly indexed block occurrences from a literal frame.No position, marked projection, or protected-slot preservation is a premise. -/theorem asSlotMove (h : P455Closure.Move r Allowed Mark u v) :∃ s : Slots.Move (r-2), u = Slots.before s ∧ v = Slots.after s ∧(∀ a ∈ s.p, ∀ b ∈ s.q, ¬ Mark a b ∧ ¬ Mark b a) ∧ 16 ≤ r := byobtain ⟨f,bit,l,t,hf,hu,hv,hc⟩ := hhave hr := hf.1have hx : ∀ x, x ∈ f.p ∨ x ∈ f.q →(l ++ f.early ++ f.mid ++ f.beforeMutable).count x = r-2 := byintro x hxhave hh := f.mutable_index hf bit l t (hu ▸ hc) x hxomegaobtain ⟨_,_,_,np,nq,dis,marks,_⟩ := hflet s : Slots.Move (r-2) :={ pre := l ++ f.early ++ f.mid ++ f.beforeMutablep := f.pq := f.qpost := f.beforeFinalP ++ f.p ++ f.beforeFinalQ ++ f.q ++ tdp := npdq := nqdisjoint := disindexP := fun x m => hx x (.inl m)indexQ := fun x m => hx x (.inr m) }cases bit with| false =>refine ⟨s,?_,?_,marks,by omega⟩ <;>simp [s, hu, hv, Slots.before, Slots.after, Frame.core, Frame.pair, List.append_assoc]| true =>let t' : Slots.Move (r-2) :={ pre := s.prep := s.qq := s.ppost := s.postdp := s.dqdq := s.dpdisjoint := fun x hx hx' => s.disjoint x hx' hxindexP := s.indexQindexQ := s.indexP }refine ⟨t',?_,?_,(fun x hx y hy => (marks y hy x hx).symm),by omega⟩ <;>simp [s, t', hu, hv, Slots.before, Slots.after, Frame.core, Frame.pair, List.append_assoc]theorem order_iff (h : P455Closure.Move r Allowed Mark u v) (pat : List Slots.Event)(idx : ∀ e ∈ pat, e.2 ≠ r-2) : Slots.sees u pat ↔ Slots.sees v pat := byobtain ⟨s,rfl,rfl,_⟩ := asSlotMove hexact Slots.immutable_pattern s pat idxtheorem slot_iff (h : P455Closure.Move r Allowed Mark u v) (owner i a : Nat)(hi : Slots.slotStart i) : Slots.occupies u owner i a ↔ Slots.occupies v owner i a := byobtain ⟨s,rfl,rfl,_,hr⟩ := asSlotMove hhave h1 : i ≠ r-2 := by unfold Slots.slotStart at hi; omegahave h2 : i+1 ≠ r-2 := by unfold Slots.slotStart at hi; omegaexact exists_congr (fun j => Slots.open_slot_event s owner i (i+1) (a,j) h1 h2)theorem marked_proj (h : P455Closure.Move r Allowed Mark u v) (a b : Nat)(hm : Mark a b) : Slots.select [a,b] u = Slots.select [a,b] v := byobtain ⟨s,rfl,rfl,marks,_⟩ := asSlotMove happly Slots.protected_projectionby_cases hap : a ∈ s.p· rightintro x hxsimp only [List.mem_cons, List.not_mem_nil, or_false, not_or]exact ⟨fun eq => s.disjoint a hap (eq ▸ hx),fun eq => (marks a hap b (eq ▸ hx)).1 hm⟩· by_cases hbp : b ∈ s.p· rightintro x hxsimp only [List.mem_cons, List.not_mem_nil, or_false, not_or]exact ⟨fun eq => (marks b hbp a (eq ▸ hx)).2 hm,fun eq => s.disjoint b hbp (eq ▸ hx)⟩· leftintro x hxsimp only [List.mem_cons, List.not_mem_nil, or_false, not_or]exact ⟨fun eq => hap (eq ▸ hx),fun eq => hbp (eq ▸ hx)⟩theorem typed_iff (h : P455Closure.Move r Allowed Mark u v) (a b : Nat)(tag : List Bool) (hne : a ≠ b) (hlen : tag.length+16 = r) :Slots.typed u a b tag ↔ Slots.typed v a b tag := byconstructor· obtain ⟨s,rfl,rfl,_⟩ := asSlotMove hexact Slots.type_forward s a b tag hne (by omega)· obtain ⟨s,hu,hv,_⟩ := asSlotMove h.symmrw [hu,hv]exact Slots.type_forward s a b tag hne (by omega)end P455Closure.Moveend/- Begin Problem455Finite (from finite-semigroup-identity-bases). -/sectionnamespace Problem455Finitedef rules (r : Nat) (allow : List Bool → Prop) (mark : Nat → Nat → Prop) :P455Quotient.Rules Nat wherer := rstep := P455Closure.Move r allow markreverse := P455Closure.Move.symmcounts := P455Closure.Move.count_eqextend h l t := P455Closure.Move.extend_of_cap h l topen P455Quotient/-- Enumerate all words of length at most n on the input list alphabet.Duplicates in the alphabet are harmless. -/def wordsUpTo (alphabet : List α) : Nat → List (List α)| 0 => [[]]| n+1 => [] :: alphabet.flatMap (fun a => (wordsUpTo alphabet n).map (List.cons a))theorem covered (a : List α) (n : Nat) (w : List α) (len : w.length ≤ n)(names : ∀ x ∈ w, x ∈ a) : w ∈ wordsUpTo a n := byinduction n generalizing w with| zero =>cases w <;> simp_all [wordsUpTo]| succ n ih =>cases w with| nil => simp [wordsUpTo]| cons x w =>have hx := names x (by simp)have hl : w.length ≤ n := by simpa using lenhave hw := ih w hl (fun z hz => names z (by simp [hz]))apply List.mem_cons_of_memapply List.mem_flatMap.mprexact ⟨x,hx,List.mem_map.mpr ⟨w,hw,rfl⟩⟩theorem good_bound [DecidableEq α] (R : Rules α) (T w : Word α)(good : Good R T w) : w.length ≤ T.length ∧ ∀ x ∈ w, x ∈ T := byobtain ⟨v,path,l,t,hv⟩ := goodhave perm := List.perm_iff_count.mpr (count_walk R path)have len := perm.length_eqrefine ⟨?_,?_⟩· simp only [hv,List.length_append] at lenomega· intro x hxapply perm.mem_iff.mprsimp [hv,hx]/-- A list of every quotient element, possibly with repeated entries.This enumerates the explicit zero even for an empty template. -/def carrier [DecidableEq α] (R : Rules α) (T : Word α) : List (Q R T) :=zero R T :: (wordsUpTo T T.length).map (ofWord R T)theorem carrier_complete [DecidableEq α] (R : Rules α) (T : Word α) (q : Q R T) :q ∈ carrier R T := byby_cases dead : q = zero R T· simp [carrier,dead]· obtain ⟨w,good,e⟩ := nonzero_representative R q deadobtain ⟨len,names⟩ := good_bound R T w goodexact List.mem_cons_of_mem _ (List.mem_map.mpr ⟨w, covered T T.length w len names, e⟩)end Problem455Finiteend/- Begin Problem455BlockBridge (from finite-semigroup-identity-bases). -/sectionnamespace Problem455BlockBridgeopen P455Closureopen Problem455Swaptheorem occ_count (a : Nat) (w : List Nat) : occ a w = w.count a := byinduction w with| nil => rfl| cons b w ih =>by_cases h : a = b· subst b; simp [occ, ih, List.count_cons, Nat.add_comm]· simp [occ, ih, List.count_cons, h, Ne.symm h]private def leftPart (f : Frame Nat) (l : List Nat) :=l ++ f.early ++ f.mid ++ f.beforeMutableprivate def rightPart (f : Frame Nat) (t : List Nat) :=f.beforeFinalP ++ f.p ++ f.beforeFinalQ ++ f.q ++ tprivate theorem frame_false (f : Frame Nat) (l t : List Nat) :l ++ f.core false ++ t = leftPart f l ++ f.p ++ f.q ++ rightPart f t := bysimp [leftPart, rightPart, Frame.core, Frame.pair, List.append_assoc]private theorem frame_true (f : Frame Nat) (l t : List Nat) :l ++ f.core true ++ t = leftPart f l ++ f.q ++ f.p ++ rightPart f t := bysimp [leftPart, rightPart, Frame.core, Frame.pair, List.append_assoc]private theorem early_factor (f : Frame Nat) (l t : List Nat) (b : Bool) :Factor (privatePhase f.p f.q) (l ++ f.core b ++ t) := byrefine ⟨l, f.mid ++ f.beforeMutable ++ f.pair b ++ f.beforeFinalP ++ f.p ++f.beforeFinalQ ++ f.q ++ t, ?_⟩simp [Frame.core, Frame.early, privatePhase, List.append_assoc]private theorem frameLink {r : Nat} {allow : List Bool → Prop} {mark : Nat → Nat → Prop}(f : Frame Nat) (l t : List Nat) (wf : f.Valid r allow mark)(hc : Cap r (l ++ f.core false ++ t)) (x y : Nat) :Link r (l ++ f.core false ++ t) x y ↔ Link r (l ++ f.core true ++ t) x y := byhave pn : f.p ≠ [] := by simp [Frame.p]have qn : f.q ≠ [] := by simp [Frame.q]let i := f.pHeadlet j := f.q.head qnlet s := f.p.getLast pnlet z := f.qLasthave hp : f.p.head? = some i := rflhave hq : f.q.head? = some j := List.head?_eq_head qnhave ep : f.p.getLast? = some s := List.getLast?_eq_getLast pnhave eq : f.q.getLast? = some z := by simp [Frame.q,z]have disj := wf.2.2.2.2.2.1have hpMem : i ∈ f.p := by simp [i, Frame.p]have hqMem : j ∈ f.q := List.head_mem _have epMem : s ∈ f.p := List.getLast_mem _have eqMem : z ∈ f.q := by simp [z,Frame.q]have hij : i ≠ j := fun h => disj i hpMem (h ▸ hqMem)have hsz : s ≠ z := fun h => disj s epMem (h ▸ eqMem)have cf : cap r (l ++ f.core false ++ t) := byintro arw [occ_count]exact hc ahave ef := early_factor f l t falsehave et := early_factor f l t truerw [frame_false] at cf ef ⊢rw [frame_true] at et ⊢exact repeatedLink_swap _ _ hp hq ep eq hij hsz cf ef et x y/-- Invariance of each repeated adjacent pair under the actual frame move. -/theorem move_link {r : Nat} {allow : List Bool → Prop} {mark : Nat → Nat → Prop}{u v : List Nat} (h : Move r allow mark u v) (x y : Nat) :Link r u x y ↔ Link r v x y := byhave hd := h.cap_rightobtain ⟨f,b,l,t,hf,rfl,rfl,hc⟩ := hcases b· exact frameLink f l t hf hc x y· exact (frameLink f l t hf hd x y).symm/-- The repeated-block relation consists of saturated endpoints and pathsin the fixed graph of repeated links. -/theorem move_sameBlock {r : Nat} {allow : List Bool → Prop} {mark : Nat → Nat → Prop}{u v : List Nat} (h : Move r allow mark u v) (x y : Nat) :SameBlock r u x y ↔ SameBlock r v x y := byhave rel : Link r u = Link r v := funext fun a => funext fun b => propext (move_link h a b)simp only [SameBlock,rel,occ_count,h.count_eq]end Problem455BlockBridgeend/- Begin Problem455MathlibTM (from finite-semigroup-identity-bases). -/section/- The compilation fixes a finite machine before the input. Its exactterminal tape equals the same physical encoding of the output list. -/namespace P455MathlibTMopen Turing PartrecToTM2 P455MathlibCodeabbrev Track := TM2to1.Γ' K' (fun _ => Γ')instance stackFinite : Fintype K' :=⟨{.main,.rev,.aux,.stack},fun k => by cases k <;> simp⟩def cell (bottom : Bool) (s : Γ') : Track :=(bottom, Function.update (fun _ => none) K'.main (some s))def image (x : List Bool) : List Track :=cell true .cons :: cell false .bit1 :: x.map (fun b => cell false (letter b))theorem tr_input (x : List Bool) :TM2to1.trInit (Γ := fun _ => Γ') K'.main (trList [wire x]) = image x := byunfold TM2to1.trInitrw [raw_main]simp [image,cell,List.map_map,Function.comp_def,List.headI]theorem unique_sim {K : Type} {G : K → Type} {L V : Type}{u : TM2.Cfg G L V} {a b}(ha : TM2to1.TrCfg u a) (hb : TM2to1.TrCfg u b) : a=b := bycases ha with| mk t ht =>cases hb with| mk s hs =>have eq : t=s := byapply ListBlank.extintro nfunext khave h := congrArg (fun z => ListBlank.nth z n) ((ht k).trans (hs k).symm)simpa only [proj_map_nth] using hsubst srflprivate theorem final_config {K : Type} {G : K → Type} {L V : Type}{u : TM2.Cfg G L V} {a} (h : TM2to1.TrCfg u a) (val : V) :TM2to1.TrCfg ⟨(none : Option L),val,u.stk⟩ ⟨none,val,a.Tape⟩ := bycases h with| mk t ht => exact .mk t htprivate theorem stack_update (x : List Γ') :Function.update (fun _ : K' => ([] : List Γ')) .main x = K'.elim x [] [] [] := byfunext kcases k <;> simp [K'.elim,Function.update]/-- Finiteness of the actual alphabet, a finite support of reachablecontrol labels and full bilateral tape equality at a genuine halt. -/theorem supported {f : List Bool → List Bool} (hf : Computable f) :∃ (L : Type) (_ : Inhabited L) (M : TM0.Machine Track L) (S : Finset L),TM0.Supports M (S : Set L) ∧(∀ q ∈ S, ∀ a q' b, M q a = some (q',.write b) → b.1=a.1) ∧∀ x, ∃ q, (⟨q,Tape.mk₁ (image (f x))⟩ : TM0.Cfg Track L) ∈StateTransition.eval (TM0.step M) (TM0.init (image x)) := byclassicalobtain ⟨c, hc⟩ := compile hfletI : Inhabited PartrecToTM2.Λ' := ⟨trNormal c .halt⟩let M₁ := TM2to1.tr PartrecToTM2.trlet M₀ := TM1to0.tr M₁obtain ⟨S,hs,mark⟩ := P455MathlibMarker.guarded M₁ (P455MathlibMarker.tr_safe _)(TM1to0.tr_supports M₁ (TM2to1.tr_supports _ (PartrecToTM2.tr_supports c .halt)))refine ⟨_,inferInstance,M₀,S,hs,mark,?_⟩intro xlet v := [wire x]let w := [wire (f x)]have run : PartrecToTM2.halt w ∈ StateTransition.eval (TM2.step PartrecToTM2.tr) (PartrecToTM2.init c v) := byrw [PartrecToTM2.tr_eval]exact (Part.mem_map_iff _).mpr ⟨_,hc x,rfl⟩have e (u : List Nat) : PartrecToTM2.init c u = TM2.init (Λ := PartrecToTM2.Λ') (σ := Option Γ') K'.main (trList u) := bysimp [PartrecToTM2.init,TM2.init,stack_update]rflrw [e] at runobtain ⟨b, hb, rb⟩ := StateTransition.tr_eval (TM2to1.tr_respects PartrecToTM2.tr)(TM2to1.trCfg_init (Γ := fun _ : K' => Γ') (Λ := PartrecToTM2.Λ') (σ := Option Γ') K'.main (trList v)) runhave standard := TM2to1.trCfg_init (Γ := fun _ : K' => Γ') (Λ := PartrecToTM2.Λ') (σ := Option Γ') K'.main (trList w)have target := final_config standard (none : Option Γ')simp only [TM2.init,stack_update,TM1.init] at targethave eq := unique_sim hb targetsubst bobtain ⟨d, hd, rd⟩ := StateTransition.tr_eval (TM1to0.tr_respects M₁) rfl rbsubst drefine ⟨(none,none),?_⟩dsimp only [v,w] at rdrw [tr_input, tr_input] at rdchange (⟨(none, none), Tape.mk₁ (image (f x))⟩ : TM0.Cfg Track (TM1to0.Λ' M₁)) ∈StateTransition.eval (TM0.step (TM1to0.tr M₁))⟨(some (M₁ default), none), Tape.mk₁ (image x)⟩exact rdend P455MathlibTMend/- Begin Problem455FactorSlots (from finite-semigroup-identity-bases). -/sectionnamespace Problem455.Slotsdef shift (n : Nat → Nat) (e : Event) : Event := (e.1, n e.1 + e.2)def unshift (n : Nat → Nat) (e : Event) : Event := (e.1, e.2 - n e.1)@[simp] theorem unshift_shift (n : Nat → Nat) (e : Event) :unshift n (shift n e) = e := by cases e; simp [unshift, shift, Nat.add_sub_cancel_left]theorem stamp_shift (extra n : Nat → Nat) (w : Word) :stamp (fun x => extra x + n x) w = (stamp n w).map (shift extra) := byinduction w generalizing n with| nil => rfl| cons a w ih =>have he : advance (fun x => extra x + n x) [a] =(fun x => extra x + advance n [a] x) := by funext x; simp [advance, Nat.add_assoc]simp only [stamp, List.map_cons, he, ih, shift]theorem labels_of_stamp (n : Nat → Nat) (w : Word) :(stamp n w).map Prod.fst = w := byinduction w generalizing n with| nil => rfl| cons a w ih => simp [stamp, ih]theorem stamped_mem_label (n : Nat → Nat) (w : Word) (e : Event)(h : e ∈ stamp n w) : e.1 ∈ w := byrw [← labels_of_stamp n w]exact List.mem_map_of_mem htheorem events_of_factor (l f t : Word) :events (l ++ f ++ t) =events l ++ ((events f).map (shift (fun a => l.count a)) ++stamp (fun a => l.count a + f.count a) t) := byhave hn : advance (fun _ => 0) l = (fun a => l.count a) := by funext a; simp [advance]have hh := stamp_shift (fun a => l.count a) (fun _ => 0) fsimp only [Nat.add_zero] at hhsimp only [List.append_assoc, events, stamp_append, hn, hh]rflprivate theorem trim_left {α : Type} {a : α} {pat u v : List α}(ha : a ∉ u) (h : (a :: pat).Sublist (u ++ v)) : (a :: pat).Sublist v := byinduction u with| nil => exact h| cons c u ih =>cases h with| cons _ h => exact ih (fun hh => ha (by simp [hh])) h| cons_cons _ _ => exact False.elim (ha (by simp))private theorem trim_three {α : Type} {a e b : α} {l f t : List α}(ha : a ∉ l) (hb : b ∉ t) :[a,e,b].Sublist (l ++ (f ++ t)) ↔ [a,e,b].Sublist f := byconstructor· intro hhave h' := (trim_left ha h).reversesimp only [List.reverse_append, List.reverse_cons, List.reverse_nil, List.nil_append,List.cons_append, List.singleton_append] at h'have hh := (trim_left (by simpa using hb : b ∉ t.reverse) h').reversesimpa using hh· intro hexact List.sublist_append_of_sublist_right (List.sublist_append_of_sublist_left h)/-- No assumption on the number of outside copies of the occupant. Itsoccurrence number is shifted on entering the surrounding word. -/theorem factor_occupies (l f t : Word) (owner i a : Nat) (hl : owner ∉ l) (ht : owner ∉ t) :occupies (l ++ f ++ t) owner i a ↔ occupies f owner i a := byhave hz := List.count_eq_zero.mpr hlhave left : (owner, i) ∉ events l := fun hm => hl (stamped_mem_label _ _ _ hm)have right : (owner, i + 1) ∉ stamp (fun x => l.count x + f.count x) t :=fun hm => ht (stamped_mem_label _ _ _ hm)let n := fun x => l.count xhave shiftS : ∀ j, unshift n (owner,j) = (owner,j) := by simp [unshift, n, hz]have shiftF : ∀ j, shift n (owner,j) = (owner,j) := by simp [shift,n,hz]constructor· rintro ⟨k,h⟩unfold sees at hrw [events_of_factor] at hhave hh := ((trim_three left right).mp h).map (unshift n)refine ⟨k-n a,?_⟩simpa [sees, List.map_map, Function.comp_def, Nat.add_sub_cancel_left, shiftS, unshift, shift, n, hz] using hh· rintro ⟨k,h⟩refine ⟨n a+k,?_⟩unfold seesrw [events_of_factor]apply (trim_three left right).mprhave hh := h.map (shift n)simpa [shiftF, shift, n, hz] using hh/-- In a capped variant, saturation in a factor supplies the owner hypothesis.This also applies to non-consecutive arbitrary slot endpoints through theunderlying three-event trimming lemma. -/theorem saturated_factor_occupies (l f t : Word) (owner i a r : Nat)(cap : P455Closure.Cap r (l ++ f ++ t)) (sat : f.count owner = r) :occupies (l ++ f ++ t) owner i a ↔ occupies f owner i a := byhave h := cap ownersimp only [List.count_append, sat] at hexact factor_occupies l f t owner i a(List.count_eq_zero.mp (by omega)) (List.count_eq_zero.mp (by omega))theorem saturated_factor_sees (l f t : Word) (pat : List Event) (r : Nat)(cap : P455Closure.Cap r (l ++ f ++ t))(sat : ∀ e ∈ pat, f.count e.1 = r) :sees (l ++ f ++ t) pat ↔ sees f pat := byhave fresh : ∀ e ∈ pat, l.count e.1 = 0 ∧ e.1 ∉ t := byintro e hehave hh := cap e.1simp only [List.count_append, sat e he] at hhexact ⟨by omega,List.count_eq_zero.mp (by omega)⟩let n := fun x => l.count xhave left : ∀ e ∈ pat, e ∉ events l := fun e he hc =>(List.count_eq_zero.mp (fresh e he).1) (stamped_mem_label _ _ _ hc)have right : ∀ e ∈ pat, e ∉ stamp (fun x => l.count x + f.count x) t := fun e he hc =>(fresh e he).2 (stamped_mem_label _ _ _ hc)have hs : pat.map (shift n) = pat := byconv => rhs; rw [← List.map_id (l := pat)]apply List.map_congr_leftintro e hesimp [shift,n,(fresh e he).1]have hr : pat.map (unshift n) = pat := byconv => rhs; rw [← List.map_id (l := pat)]apply List.map_congr_leftintro e hesimp [unshift,n,(fresh e he).1]unfold seesrw [events_of_factor]constructor· intro hhave mid := (h.of_sublist_append_right left).of_sublist_append_left righthave hh := mid.map (unshift n)simpa [hr, List.map_map, Function.comp_def, Nat.add_sub_cancel_left, unshift, shift, n] using hh· intro hhave hh := h.map (shift n)rw [hs] at hhexact List.sublist_append_of_sublist_right (List.sublist_append_of_sublist_left hh)/- If an occupant is not saturated, its occurrence number can change evenwhen the owner is saturated. Here 3 is the owner and the leading 7 isoutside the factor. These closed examples are separate from the lemmas. -/example : sees [3,7,3] [(3,0),(7,0),(3,1)] := by unfold sees; decideexample : ¬ sees [7,3,7,3] [(3,0),(7,0),(3,1)] := by unfold sees; decideexample : sees [7,3,7,3] [(3,0),(7,1),(3,1)] := by unfold sees; decideend Problem455.Slotsend/- Begin Problem455Uncrossed (from finite-semigroup-identity-bases). -/sectionnamespace P455Uncrossedopen P455Closure Problem455Finiteabbrev W := List Natabbrev Tags := List Bool → Propabbrev Marks := Nat → Nat → Propdef side (f : Frame Nat) (l k : W) (bit : Bool) := l ++ f.core bit ++ kdef Unmarked (mark : Marks) (h : Nat → W) (x y : Nat) : Prop :=∀ a ∈ h x, ∀ b ∈ h y, ¬ mark a b ∧ ¬ mark b aprivate theorem nodup_of_counts (w : W) (h : ∀ a ∈ w, w.count a ≤ 1) : w.Nodup := byinduction w with| nil => simp| cons a w ih =>apply List.nodup_cons.mprhave one := h a (by simp)simp only [List.count_cons_self] at oneexact ⟨List.count_eq_zero.mp (by omega),ih fun b hb => by have hh := h b (by simp [hb]); simp [List.count_cons] at hh; omega⟩private theorem core_mem {r A M} (f : Frame Nat) (valid : f.Valid r A M)(bit : Bool) (a : Nat) (mem : a ∈ f.p ∨ a ∈ f.q) : (f.core bit).count a = r := byhave base := valid.2.2.2.2.2.2.2 a memcases bit· exact base· exact (f.count_core a true).trans baseprivate def mappedFrame (f : Frame Nat) (h : Nat → W) (pHead : Nat) (pTail qInit : W)(qLast : Nat) : Frame Nat wherepHead := pHeadpTail := pTailqInit := qInitqLast := qLasttag := f.tagmiddle := f.middle.map (fun e => (e.1.flatMap h, e.2))beforeMutable := f.beforeMutable.flatMap hbeforeFinalP := f.beforeFinalP.flatMap hbeforeFinalQ := f.beforeFinalQ.flatMap hprivate theorem mid_image (f : Frame Nat) (h : Nat → W) (phead : Nat) (pt qi : W) (qlast : Nat)(hp : f.p.flatMap h = phead :: pt) (hq : f.q.flatMap h = qi ++ [qlast]) :f.mid.flatMap h = (mappedFrame f h phead pt qi qlast).mid := bysimp only [Frame.mid,mappedFrame,List.flatMap_assoc,List.flatMap_map]congr 1funext zobtain ⟨w,b⟩ := zcases b <;> simp only [Function.comp_apply, Bool.false_eq_true, if_false, if_true,List.flatMap_append, hp, hq] <;> rflprivate theorem core_image (f : Frame Nat) (h : Nat → W) (phead : Nat) (pt qi : W) (qlast : Nat)(hp : f.p.flatMap h = phead :: pt) (hq : f.q.flatMap h = qi ++ [qlast]) (bit : Bool) :(f.core bit).flatMap h = (mappedFrame f h phead pt qi qlast).core bit := byhave mid := mid_image f h phead pt qi qlast hp hqcases bit <;> simp only [Frame.core,Frame.early,Frame.pair,Bool.false_eq_true,if_false,if_true,List.flatMap_append, mid, hp, hq] <;> rfltheorem equal_or_move {r allow mark} (f : Frame Nat) (l k : W) (bit : Bool) (x y : Nat)(hp : f.p = [x]) (hq : f.q = [y]) (valid : f.Valid r allow (fun _ _ => False))(h : Nat → W) (clear : Unmarked mark h x y)(cap : Cap r ((side f l k bit).flatMap h)) :(side f l k bit).flatMap h = (side f l k (!bit)).flatMap h ∨Move r allow mark ((side f l k bit).flatMap h) ((side f l k (!bit)).flatMap h) := byhave xmap : f.p.flatMap h = h x := by simp [hp]have ymap : f.q.flatMap h = h y := by simp [hq]by_cases empty : h x = [] ∨ h y = []· leftrcases empty with hx | hy <;> cases bit <;>simp [side,Frame.core,Frame.pair,List.flatMap_append,xmap,ymap, *]righthave nonX : h x ≠ [] := fun e => empty (Or.inl e)have nonY : h y ≠ [] := fun e => empty (Or.inr e)obtain ⟨phead,pt,p⟩ : ∃ a t, h x = a :: t := by cases hv : h x <;> simp_allobtain ⟨qi,qlast,q⟩ : ∃ t a, h y = t ++ [a] := bycases hv : (h y).reverse with| nil => have e := congrArg List.reverse hv; simp_all| cons a t => exact ⟨t.reverse,a,by simpa using congrArg List.reverse hv⟩let g := mappedFrame f h phead pt qi qlasthave gp : g.p = h x := p.symmhave gq : g.q = h y := q.symmhave eq (b : Bool) :(side f l k b).flatMap h = l.flatMap h ++ g.core b ++ k.flatMap h := bysimp only [side,List.flatMap_append,core_image f h _ _ _ _ (xmap.trans p) (ymap.trans q),g]have capCore : Cap r ((f.core bit).flatMap h) := byintro a; have hh := cap a; simp only [side,List.flatMap_append,List.count_append] at hh; omegahave xm : x ∈ f.p := by simp [hp]have ym : y ∈ f.q := by simp [hq]have ne : x ≠ y := fun e => valid.2.2.2.2.2.1 x xm (e ▸ ym)have hr : 0 < r := by have := valid.1; omegahave cx := core_mem f valid bit x (.inl xm)have cy := core_mem f valid bit y (.inr ym)have usedY : y ∈ f.core bit := List.count_pos_iff.mp (cy.symm ▸ hr)have excl (a : Nat) (ha : a ∈ h x) :=P455DonorInterval.exclusive h (f.core bit) x a r hr cx ha (capCore a)have capImage := eq bit ▸ caphave gv : g.Valid r allow mark := byapply g.valid_of_capped_shape valid.1 valid.2.1 _ _ _ _ _ bit (l.flatMap h) (k.flatMap h) capImage· simpa [g,mappedFrame,List.map_map,Function.comp_def] using valid.2.2.1· rw [gp]; apply nodup_of_countsexact fun a ha => Nat.le_of_eq (excl a ha).1· rw [gq]; apply nodup_of_countsexact fun a ha => Nat.le_of_eq (P455DonorInterval.exclusive h (f.core bit) y a r hr cy ha (capCore a)).1· rw [gp,gq]; exact fun a ha => (excl a ha).2.1 y usedY ne.symm· simpa only [gp,gq,Unmarked] using clearexact ⟨g,bit,l.flatMap h,k.flatMap h,gv,eq bit,eq (!bit),cap⟩private theorem words_from_good {r allow mark T} (capT : P455Quotient.Cap r T)(f : Frame Nat) (l k : W) (bit : Bool) (x y : Nat)(hp : f.p = [x]) (hq : f.q = [y]) (valid : f.Valid r allow (fun _ _ => False))(h : Nat → W) (clear : Unmarked mark h x y)(good : P455Quotient.Good (rules r allow mark) T ((side f l k bit).flatMap h)) :P455Quotient.ofWord (rules r allow mark) T ((side f l k bit).flatMap h) =P455Quotient.ofWord (rules r allow mark) T ((side f l k (!bit)).flatMap h) := bylet R := rules r allow markhave cap := P455Quotient.good_cap R capT goodrcases equal_or_move f l k bit x y hp hq valid h clear cap with e | move· rw [e]· have path := P455Quotient.Walk.snoc (s := R.step) (.refl _) movehave equiv := P455Quotient.good_context R capT path [] []simp only [List.nil_append,List.append_nil] at equivexact (P455Quotient.same_nonzero_class R good).mpr ⟨equiv.mp good,path⟩/-- Uncrossed literal representatives agree even if their product is zero.Any nonzero side supplies the cap on its evaluated factor. -/theorem uncrossed_words {r allow mark T} (capT : P455Quotient.Cap r T)(f : Frame Nat) (l k : W) (bit : Bool) (x y : Nat)(hp : f.p = [x]) (hq : f.q = [y]) (valid : f.Valid r allow (fun _ _ => False))(h : Nat → W) (clear : Unmarked mark h x y) :P455Quotient.ofWord (rules r allow mark) T ((side f l k bit).flatMap h) =P455Quotient.ofWord (rules r allow mark) T ((side f l k (!bit)).flatMap h) := bylet R := rules r allow markby_cases g : P455Quotient.Good R T ((side f l k bit).flatMap h)· exact words_from_good capT f l k bit x y hp hq valid h clear gby_cases g' : P455Quotient.Good R T ((side f l k (!bit)).flatMap h)· simpa using (words_from_good capT f l k (!bit) x y hp hq valid h clear g').symmhave dead (w : W) (h : ¬ P455Quotient.Good R T w) :P455Quotient.ofWord R T w = P455Quotient.zero R T := byapply Classical.byContradictionintro nz; exact h ((P455Quotient.nonzero_iff R).mp nz)exact (dead _ g).trans (dead _ g').symmtheorem same_letters (f : Frame Nat) (l k : W) (bit : Bool) (a : Nat) :a ∈ side f l k bit ↔ a ∈ side f l k (!bit) := byhave c := f.count_core a bithave perm : (side f l k bit).count a = (side f l k (!bit)).count a := bysimp only [side,List.count_append,c]rw [←List.count_pos_iff,←List.count_pos_iff,perm]/-- Arbitrarily chosen quotient representatives for all occurring variablesare enough for a decision for a fixed evaluation. -/theorem uncrossed_eval {r allow mark T} (capT : P455Quotient.Cap r T)(f : Frame Nat) (l k : W) (bit : Bool) (x y : Nat)(hp : f.p = [x]) (hq : f.q = [y]) (valid : f.Valid r allow (fun _ _ => False))(val : Nat → P455Quotient.Q (rules r allow mark) T) (h : Nat → W)(reps : ∀ a ∈ side f l k bit, P455Quotient.ofWord (rules r allow mark) T (h a) = val a)(clear : Unmarked mark h x y) :P455Quotient.eval (rules r allow mark) capT val (side f l k bit) =P455Quotient.eval (rules r allow mark) capT val (side f l k (!bit)) := byrw [P455Quotient.eval_rep _ _ _ _ h reps,P455Quotient.eval_rep _ _ _ _ h (fun a ha => reps a ((same_letters f l k bit a).mpr ha))]exact uncrossed_words capT f l k bit x y hp hq valid h clear/-- A distinguishing evaluation forces a cross-block mark in EVERY choice ofrepresentatives of its occurring variables. Both stored orientations count. -/theorem difference_crosses {r allow mark T} (capT : P455Quotient.Cap r T)(f : Frame Nat) (l k : W) (bit : Bool) (x y : Nat)(hp : f.p = [x]) (hq : f.q = [y]) (valid : f.Valid r allow (fun _ _ => False))(val : Nat → P455Quotient.Q (rules r allow mark) T) (h : Nat → W)(reps : ∀ a ∈ side f l k bit, P455Quotient.ofWord (rules r allow mark) T (h a) = val a)(diff : P455Quotient.eval (rules r allow mark) capT val (side f l k bit) ≠P455Quotient.eval (rules r allow mark) capT val (side f l k (!bit))) :∃ a ∈ h x, ∃ b ∈ h y, mark a b ∨ mark b a := byapply Classical.byContradictionintro noneapply diffapply uncrossed_eval capT f l k bit x y hp hq valid val h repsintro a ha b hbexact ⟨fun e => none ⟨a,ha,b,hb,Or.inl e⟩,fun e => none ⟨a,ha,b,hb,Or.inr e⟩⟩/-- A distinguishing valuation has a live orientation and simultaneous arbitrarygood-word representatives for its letters. Each such simultaneous choiceoccurs as a literal factor of a variant, including arbitrary proper factors. -/theorem difference_live_representatives {r allow mark T} (capT : P455Quotient.Cap r T)(f : Frame Nat) (l k : W)(val : Nat → P455Quotient.Q (rules r allow mark) T)(diff : P455Quotient.eval (rules r allow mark) capT val (side f l k false) ≠P455Quotient.eval (rules r allow mark) capT val (side f l k true)) :∃ bit : Bool,P455Quotient.eval (rules r allow mark) capT val (side f l k bit) ≠P455Quotient.zero (rules r allow mark) T ∧(∃ h : Nat → W, ∀ a ∈ side f l k bit,P455Quotient.Good (rules r allow mark) T (h a) ∧P455Quotient.ofWord (rules r allow mark) T (h a) = val a) ∧(∀ h : Nat → W, (∀ a ∈ side f l k bit,P455Quotient.ofWord (rules r allow mark) T (h a) = val a) →∃ V left right, P455Quotient.Variant (rules r allow mark) T V ∧V = left ++ (side f l k bit).flatMap h ++ right) := byclassicallet R := rules r allow markhave live : ∃ bit, P455Quotient.eval R capT val (side f l k bit) ≠ P455Quotient.zero R T := byby_cases nz : P455Quotient.eval R capT val (side f l k false) ≠ P455Quotient.zero R T· exact ⟨false,nz⟩· exact ⟨true,fun z => diff ((Classical.not_not.mp nz).trans z.symm)⟩obtain ⟨bit,nz⟩ := liverefine ⟨bit,nz,?_,?_⟩· have word (a) (ha : a ∈ side f l k bit) :=P455Quotient.nonzero_representative R (val a) (P455Quotient.live_inputs R capT val _ nz a ha)let h (a : Nat) := if ha : a ∈ side f l k bit then (word a ha).choose else []refine ⟨h,fun a ha => ?_⟩simpa only [h,dif_pos ha] using (word a ha).choose_spec· intro h repsexact (P455Quotient.arbitrary_representatives R capT val _ h reps).mp nzend P455Uncrossedend/- Begin Problem455EffectiveQReach (from finite-semigroup-identity-bases). -/sectionnamespace P455EffectiveQReachopen P455Quotientvariable {α : Type} [DecidableEq α]def via (edge : α → α → Bool) : List α → α → α → Bool| [], x, y => decide (x=y) || edge x y| z::zs, x, y => via edge zs x y || (via edge zs x z && via edge zs z y)private theorem initial (e : α → α → Bool) (s : List α) {a b : α} (h : a=b ∨ e a b=true) :via e s a b = true := byinduction s with| nil => simpa [via] using h| cons z zs ih => simp [via,ih]private theorem splice (e : α → α → Bool) (s : List α) {a b c : α} (mem : b∈s)(p : via e s a b=true) (q : via e s b c=true) : via e s a c=true := byinduction s generalizing a b c with| nil => simp at mem| cons z zs ih =>simp only [via,Bool.or_eq_true,Bool.and_eq_true] at p q ⊢rcases List.mem_cons.mp mem with rfl|tail· exact Or.inr ⟨p.elim id (·.1),q.elim id (·.2)⟩· rcases p with p|⟨px,py⟩ <;> rcases q with q|⟨qx,qy⟩· exact .inl (ih tail p q)· exact .inr ⟨ih tail p qx,qy⟩· exact .inr ⟨px,ih tail py q⟩· exact .inr ⟨px,qy⟩theorem sound {rel : α → α → Prop} (e : α → α → Bool) (ok : ∀ x y,e x y=true → rel x y)(s : List α) {a b : α} (h : via e s a b = true) : Walk rel a b := byinduction s generalizing a b with| nil =>simp only [via,Bool.or_eq_true,decide_eq_true_eq] at hrcases h with rfl|h· exact .refl _· exact .snoc (.refl _) (ok _ _ h)| cons z zs ih =>simp only [via,Bool.or_eq_true,Bool.and_eq_true] at hexact h.elim ih (fun ⟨p,q⟩ => (ih p).trans (ih q))theorem complete {rel : α → α → Prop} (e : α → α → Bool) (ok : ∀ x y,rel x y → e x y=true)(s : List α) {a b : α} (cover : ∀ x, Walk rel a x → x∈s) (p : Walk rel a b) :via e s a b = true := byinduction p with| refl => exact initial _ _ (.inl rfl)| snoc p step ih => exact splice _ _ (cover _ p) ih (initial _ _ (.inr (ok _ _ step)))end P455EffectiveQReachend/- Begin Problem455Witness (from finite-semigroup-identity-bases). -/sectionnamespace P455Witnessopen Problem455.Slotsabbrev W := List Natabbrev Tag := List Boolabbrev Marking := Nat → Nat → Prop/- A finite conjunction/disjunction of observations on a single word.A static test depends only on the chosen certificate and tile alphabet. -/inductive Query where| fixed (p : Prop)| count (a n : Nat)| deficient (a : Nat)| record (a b : Nat) (tag : Tag)| markedBit (a b : Nat) (tag : Tag) (bit : Bool)| order (pattern : List Event)| slot (owner i a : Nat)| separate (a b : Nat)| both (x y : Query)| either (x y : Query)def Holds (r : Nat) (allow : Tag → Prop) (mark : Marking) (w : W) : Query → Prop| .fixed p => p| .count a n => w.count a = n| .deficient a => w.count a < r| .record a b tag => a ≠ b ∧ tag.length + 16 = r ∧ allow tag ∧ typed w a b tag| .markedBit a b tag bit => a ≠ b ∧ tag.length + 16 = r ∧ allow tag ∧ (mark a b ∨ mark b a) ∧select [a,b] w = profile a b tag bit| .order pat => (∀ e ∈ pat, e.2 ≠ r - 2) ∧ sees w pat| .slot o i a => slotStart i ∧ occupies w o i a| .separate a b => ¬ Problem455Swap.SameBlock r w a b| .both x y => Holds r allow mark w x ∧ Holds r allow mark w y| .either x y => Holds r allow mark w x ∨ Holds r allow mark w ytheorem unordered_projection {r allow mark u v} (h : P455Closure.Move r allow mark u v)(a b : Nat) (hm : mark a b ∨ mark b a) : select [a,b] u = select [a,b] v := byrcases hm with forward | reverse· exact h.marked_proj a b forward· simpa only [select_pair_symm b a] using h.marked_proj b a reversetheorem query_invariant {r allow mark u v} (h : P455Closure.Move r allow mark u v) (q : Query) :Holds r allow mark u q ↔ Holds r allow mark v q := byinduction q with| fixed => rfl| count a n => simp only [Holds, h.count_eq a]| deficient a => simp only [Holds, h.count_eq a]| record a b tag =>simp only [Holds]constructor <;> rintro ⟨ne,len,ok,t⟩· exact ⟨ne,len,ok,(h.typed_iff a b tag ne len).mp t⟩· exact ⟨ne,len,ok,(h.typed_iff a b tag ne len).mpr t⟩| markedBit a b tag bit =>simp only [Holds]constructor <;> rintro ⟨ne,len,ok,mk,t⟩· exact ⟨ne,len,ok,mk,(unordered_projection h a b mk) ▸ t⟩· exact ⟨ne,len,ok,mk,(unordered_projection h a b mk).symm ▸ t⟩| order pat =>constructor <;> rintro ⟨imm,t⟩· exact ⟨imm,(h.order_iff pat imm).mp t⟩· exact ⟨imm,(h.order_iff pat imm).mpr t⟩| slot o i a =>constructor <;> rintro ⟨hi,t⟩· exact ⟨hi,(h.slot_iff o i a hi).mp t⟩· exact ⟨hi,(h.slot_iff o i a hi).mpr t⟩| separate a b => exact not_congr (Problem455BlockBridge.move_sameBlock h a b)| both _ _ ih jh => exact and_congr ih jh| either _ _ ih jh => exact or_congr ih jhdef allQ : List Query → Query| [] => .fixed True| q :: qs => .both q (allQ qs)def flagQ (b : Bool) (q : Query) : Query := if b then q else .fixed Truestructure Node whereowner : Natmate : Nattag : Tagderiving DecidableEqdef typedNode (n : Node) := Query.record n.owner n.mate n.tagdef markedNode (n : Node) (b : Bool) := Query.markedBit n.owner n.mate n.tag bdef earlier (a i b j : Nat) := Query.order [(a,i),(b,j)]/-- Last early copy of every role on the left precedes the first of every roleon the right. Indices throughout are zero-based. -/def earlyBefore (xs ys : W) := allQ (xs.flatMap fun x => ys.map fun y => earlier x 2 y 0)def earlyDisjoint (xs ys : W) := Query.either (earlyBefore xs ys) (earlyBefore ys xs)inductive ContactChoice where| record (tag : Tag) (reverseRoles : Bool)| port (phase : Fin 5) (reverseOrder : Bool)def contact (r a b : Nat) : ContactChoice → Query| .record tag rev => if rev then .record b a tag else .record a b tag| .port port rev =>let i := 3 + 2 * port.vallet x := if rev then b else alet y := if rev then a else ballQ [.fixed (a ≠ b), .count a r, .count b r, earlyDisjoint [a] [b],.order [(x,i),(y,i),(x,i+1),(y,i+1)]]def route (r start : Nat) (steps : List (Nat × ContactChoice)) (terminal : Nat → Query) : Query :=match steps with| [] => terminal start| (b,c) :: rest => .both (contact r start b c) (route r b rest terminal)inductive SlotDefect where| deficient (a : Nat)| overflow (occupants : List Nat)def differentBlocks : W → Query| [] => .fixed True| a :: xs => .both (allQ (xs.map (Query.separate a))) (differentBlocks xs)def terminalSlot (r owner i : Nat) : SlotDefect → Query| .deficient a => .both (.slot owner i a) (.deficient a)| .overflow xs =>allQ [.fixed (xs.length = 5), differentBlocks (owner :: xs),allQ (xs.map fun a => .both (.count a r) (.slot owner i a))]structure SlotCertificate whereanchor : Nodebit : BoolstartAtMate : Boolsteps : List (Nat × ContactChoice)terminalIndex : Natdefect : SlotDefectdef SlotCertificate.query (s : SlotCertificate) (r : Nat) : Query :=let start := if s.startAtMate then s.anchor.mate else s.anchor.ownerallQ [markedNode s.anchor s.bit, .fixed (s.steps.length ≤ 6),route r start s.steps (fun o => terminalSlot r o s.terminalIndex s.defect)]/-- All data from machine tiles are fixed independently of the word. -/structure Tiles wherehorizontal : Tag → Tag → Propvertical : Tag → Tag → Propleft : Tag → Boolright : Tag → Booltop : Tag → Boolbottom : Tag → BooloddColumn : Tag → BooloddRow : Tag → Booldef orientedPort (phase : Nat) (a b : Node) : Query :=let i := 3 + 2 * phaselet x := a.owner; let y := a.mate; let z := b.owner; let t := b.mateallQ [typedNode a, typedNode b, earlyDisjoint [x,y] [z,t],.order [(x,i),(y,i),(z,i),(t,i),(x,i+1),(y,i+1),(z,i+1),(t,i+1)]]inductive Dir | right | left | down | updef rightward (ts : Tiles) (a b : Node) :=allQ [.fixed (ts.horizontal a.tag b.tag), orientedPort (if ts.oddColumn a.tag then 1 else 0) a b,earlier a.owner (13+a.tag.length) b.owner (13+a.tag.length)]def downward (ts : Tiles) (a b : Node) : Query :=.both (.fixed (ts.vertical a.tag b.tag))(orientedPort (if ts.oddRow a.tag then 3 else 2) a b)def neighbor (ts : Tiles) (a b : Node) : Dir → Query| .right => rightward ts a b| .left => rightward ts b a| .down => downward ts a b| .up => downward ts b astructure FunctionalityCertificate whereanchor : Nodebit : Boolb : Nodec : Nodedir : DirdistinguishMate : Booldef FunctionalityCertificate.query (f : FunctionalityCertificate) (ts : Tiles) :=let role := fun n : Node => if f.distinguishMate then n.mate else n.ownerallQ [markedNode f.anchor f.bit, neighbor ts f.anchor f.b f.dir,neighbor ts f.anchor f.c f.dir, .separate (role f.b) (role f.c)]structure EdgeCertificate wherea : Nodeb : Noderight : Nodeleft : Nodedown : Nodeup : Nodediagonal : Nodedef endOfRow (ts : Tiles) (a : Node) :=if ts.oddRow a.tag then ts.left a.tag else ts.right a.tagdef localCert (ts : Tiles) (e : EdgeCertificate) :=let a := e.aallQ [flagQ (!ts.right a.tag) (rightward ts a e.right),flagQ (!ts.left a.tag) (rightward ts e.left a),flagQ (!ts.bottom a.tag) (downward ts a e.down),flagQ (!ts.top a.tag) (downward ts e.up a),flagQ (!ts.right a.tag && !ts.bottom a.tag)(.both (downward ts e.right e.diagonal) (rightward ts e.down e.diagonal))]def chosenSuccessor (ts : Tiles) (e : EdgeCertificate) : Query :=let a := e.a; let b := e.bif endOfRow ts a && ts.bottom a.tag thenallQ [.fixed ((ts.top b.tag && ts.left b.tag && !ts.oddRow b.tag && !ts.oddColumn b.tag) = true),.either (orientedPort 4 a b) (orientedPort 4 b a), earlier b.owner 0 a.owner 0]elselet next := if endOfRow ts a then e.down else if ts.oddRow a.tag then e.left else e.right.both (.fixed (next = b)) (earlier a.owner 0 b.owner 0)def EdgeCertificate.query (e : EdgeCertificate) (ts : Tiles) :=allQ [markedNode e.a true, markedNode e.b false, localCert ts e, chosenSuccessor ts e]inductive Certificate where| slot (s : SlotCertificate)| functionality (f : FunctionalityCertificate)| edge (e : EdgeCertificate)def Certificate.query (c : Certificate) (r : Nat) (ts : Tiles) :=match c with| .slot s => s.query r| .functionality f => f.query ts| .edge e => e.query tsabbrev rules := Problem455Finite.rules/-- Every enclosing variant keeps the same designated certificate, even whena chosen literal representative (or the whole product) is a proper factor. -/theorem every_variant {r allow mark T w} (path : P455Quotient.Variant (rules r allow mark) T w)(c : Certificate) (ts : Tiles) :Holds r allow mark T (c.query r ts) → Holds r allow mark w (c.query r ts) := byintro hexact path.transport h (fun mv old => (query_invariant mv _).mp old)theorem arbitrary_reps_designated {r allow mark T} (cap : P455Quotient.Cap r T){β : Type} (val : β → P455Quotient.Q (rules r allow mark) T) (v : List β)(h : β → W) (reps : ∀ x ∈ v, P455Quotient.ofWord (rules r allow mark) T (h x) = val x)(live : P455Quotient.eval (rules r allow mark) cap val v ≠ P455Quotient.zero (rules r allow mark) T)(c : Certificate) (ts : Tiles) (initial : Holds r allow mark T (c.query r ts)) :∃ w l t, P455Quotient.Variant (rules r allow mark) T w ∧w = l ++ v.flatMap h ++ t ∧ Holds r allow mark w (c.query r ts) := byapply P455Quotient.designated (rules r allow mark) cap val v h reps live _ initialexact fun mv old => (query_invariant mv _).mp oldend P455Witnessend/- Begin Problem455SameDonor (from finite-semigroup-identity-bases). -/sectionnamespace Problem455SameDonoropen Problem455Swapprivate theorem count_le_output {β : Type} [DecidableEq β] (h : β → Word)(x : β) (a : Nat) (ha : a ∈ h x) (v : List β) :v.count x ≤ occ a (v.flatMap h) := byhave pos : 0 < occ a (h x) := byrw [Problem455BlockBridge.occ_count]exact List.count_pos_iff.mpr hainduction v with| nil => simp [occ]| cons b v ih =>simp only [List.flatMap_cons, occ_append]by_cases e : b = x· subst b; simp [List.count_cons]; omega· simp [List.count_cons, e]; omegaprivate theorem count_le_edge {β : Type} [DecidableEq β] (h : β → Word)(x : β) (a b : Nat) (hab : 0 < bigram a b (h x)) (v : List β) :v.count x ≤ bigram a b (v.flatMap h) := byinduction v with| nil => simp [bigram]| cons z v ih =>simp only [List.flatMap_cons, bigram_append]by_cases e : z = x· subst z; simp [List.count_cons]; omega· simp [List.count_cons, e]; omegaprivate theorem transJoined {e : Nat → Nat → Prop} {a b c : Nat}(h1 : Joined e a b) (h2 : Joined e b c) : Joined e a c := byinduction h2 with| refl => exact h1| extend _ z ih => exact .extend ih zprivate theorem symmJoined {e : Nat → Nat → Prop} {a b : Nat}(h : Joined e a b) : Joined e b a := byinduction h with| refl => exact .refl _| extend _ z ih => exact transJoined (.extend (.refl _) z.symm) ihprivate theorem headConnected (r : Nat) (F : Word) (a : Nat) (t : Word)(links : ∀ i j, 0 < bigram i j (a :: t) → Link r F i j) :∀ b ∈ a :: t, Joined (Link r F) a b := byinduction t generalizing a with| nil =>intro b hbhave := List.mem_singleton.mp hbsubst b; exact .refl _| cons c t ih =>intro b hbrcases List.mem_cons.mp hb with h | hb· subst b; exact .refl _· have ac : Link r F a c := links a c (by simp [bigram, hit] <;> omega)have tailLinks : ∀ i j, 0 < bigram i j (c :: t) → Link r F i j := byintro i j posapply linkschange 0 < hit i j (some a) (some c) + bigram i j (c :: t)omegaexact transJoined (.extend (.refl _) (.inl ac)) (ih c tailLinks b hb)/-- Under the cap, every label in the image of an r-occurring source variableis saturated and all such labels belong to one maximal repeated block.There is no condition on substitutions of any other source variable. -/theorem sameDonor {β : Type} [DecidableEq β] {r : Nat} (v : List β)(h : β → Word) (x : β) (hx : v.count x = r)(hc : ∀ a, (v.flatMap h).count a ≤ r) (a b : Nat) (ha : a ∈ h x) (hb : b ∈ h x) :SameBlock r (v.flatMap h) a b := byhave cap' : cap r (v.flatMap h) := byintro j; rw [Problem455BlockBridge.occ_count]; exact hc jhave sat (i : Nat) (hi : i ∈ h x) : occ i (v.flatMap h) = r := byhave lower := count_le_output h x i hi vhave upper := cap' iomegahave links (i j : Nat) (ij : 0 < bigram i j (h x)) : Link r (v.flatMap h) i j := byhave lower := count_le_edge h x i j ij vhave upper := out_bound i j (j+1) (by omega) (v.flatMap h)have ceiling := cap' iunfold Linkomegarefine ⟨sat a ha,sat b hb,?_⟩cases eq : h x with| nil => simp [eq] at ha| cons c t =>rw [eq] at ha hb linksexact transJoined (symmJoined (headConnected r _ c t links a ha))(headConnected r _ c t links b hb)private theorem multiplicity_lower {β : Type} [DecidableEq β] (v : List β) (h : β → Word)(x : β) (a : Nat) : v.count x * (h x).count a ≤ (v.flatMap h).count a := byinduction v with| nil => simp| cons b v ih =>simp only [List.flatMap_cons, List.count_append]by_cases e : b = x· subst bsimp [List.count_cons, Nat.add_mul]omega· simp [List.count_cons, e]; omega/-- A named letter donated by x appears exactly once in h(x), and no othervariable USED by v donates that letter. Variables absent from v arelegitimately unconstrained. -/theorem uniqueDonor {β : Type} [DecidableEq β] {r : Nat} (v : List β)(h : β → Word) (x : β) (rpos : 0 < r) (hx : v.count x = r)(hc : ∀ a, (v.flatMap h).count a ≤ r) (a : Nat) (ha : a ∈ h x) :(h x).count a = 1 ∧ ∀ y ∈ v, y ≠ x → a ∉ h y := byconstructor· have m := multiplicity_lower v h x arw [hx] at mhave p := List.count_pos_iff.mpr hahave c := hc aby_cases hn : (h x).count a = 1· exact hn· exfalsohave two : 2 ≤ (h x).count a := by omegahave bad := Nat.mul_le_mul_left r twoomega· intro y hy yx ayobtain ⟨l,t,e⟩ := List.append_of_mem hyhave h1 := count_le_output h x a ha lhave h2 := count_le_output h x a ha trw [Problem455BlockBridge.occ_count] at h1 h2have yPos := List.count_pos_iff.mpr ayhave c := hc asimp only [e,List.flatMap_append,List.flatMap_cons,List.count_append] at csimp [e,List.count_append,List.count_cons,yx] at hxomegaend Problem455SameDonorend/- Begin Problem455MathlibFinite (from finite-semigroup-identity-bases). -/sectionnamespace P455MathlibFiniteopen Turing P455MathlibTM/-- The states really form a finite type. Every instruction writing onthe tape preserves its Boolean marker track, on all symbols. -/theorem finite_machine {f : List Bool → List Bool} (hf : Computable f) :∃ (Q : Type) (_ : Fintype Q) (_ : Inhabited Q) (M : TM0.Machine Track Q),(∀ q a q' b, M q a = some (q',.write b) → b.1=a.1) ∧∀ x, ∃ q, (⟨q,Tape.mk₁ (image (f x))⟩ : TM0.Cfg Track Q) ∈StateTransition.eval (TM0.step M) (TM0.init (image x)) := byclassicalobtain ⟨L,I,M,S,hs,guard,run⟩ := supported hflet Q := {q : L // q ∈ S}letI : Inhabited Q := ⟨⟨default,hs.1⟩⟩let pick (q : L) : Q := if h : q ∈ S then ⟨q,h⟩ else defaulthave proj (q : L) (h : q ∈ S) : (pick q).val = q := by simp [pick,h]let sym : PointedMap Track Track := ⟨id,rfl⟩let N := M.map sym sym pick Subtype.valrefine ⟨Q,inferInstance,inferInstance,N,?_,?_⟩· intro q a q' b stepchange (M q.val a).map (Prod.map pick (TM0.Stmt.map sym)) = _ at stepobtain ⟨⟨r,s⟩,hr,he⟩ := Option.map_eq_some_iff.mp stepcases s with| move d =>change (pick r, TM0.Stmt.move d) = (q',TM0.Stmt.write b) at hecases he| write z =>change (pick r,TM0.Stmt.write z) = (q',TM0.Stmt.write b) at hehave eq : z=b := TM0.Stmt.write.inj (congrArg Prod.snd he)exact eq ▸ guard q.val q.property a r z hr· intro xobtain ⟨r,stop⟩ := run xhave sim := TM0.Machine.map_respects M sym sym (⟨pick,Subtype.ext (proj _ hs.1)⟩ : PointedMap L Q)Subtype.val hs (fun _ => rfl) projhave lift (q : L) (xs : List Track) :TM0.Cfg.map sym pick (⟨q,Tape.mk₁ xs⟩ : TM0.Cfg Track L) = ⟨pick q,Tape.mk₁ xs⟩ := bysimp [TM0.Cfg.map,Tape.map_mk₁,sym]have eq : TM0.Cfg.map sym pick (TM0.init (Λ := L) (image x)) = TM0.init (Λ := Q) (image x) := byunfold TM0.initrw [lift]exact congrArg (fun q => TM0.Cfg.mk q (Tape.mk₁ (image x))) (Subtype.ext (proj _ hs.1))obtain ⟨b,⟨_,equ⟩,ok⟩ := StateTransition.tr_eval sim ⟨hs.1,eq⟩ stopsubst brw [lift] at okexact ⟨_,ok⟩end P455MathlibFiniteend/- Begin Problem455SlotOrigin (from finite-semigroup-identity-bases). -/sectionnamespace P455SlotOriginopen Problem455.Slotstheorem event_bounds (n : Nat → Nat) (w : Word) (a j : Nat)(hj : (a,j) ∈ stamp n w) : n a ≤ j ∧ j < n a + w.count a := byinduction w generalizing n with| nil => simp [stamp] at hj| cons b w ih =>rcases List.mem_cons.mp hj with he | he· obtain ⟨rfl,rfl⟩ := Prod.mk.inj hesimp [List.count_cons]· have h := ih (advance n [b]) hesimp only [advance, List.count_cons, List.count_nil] at *omega/-- The i-th (zero-based) occurrence exists exactly when the count exceeds i.This direction supplies a literal cut with its prefix count. -/theorem occurrence_cut (w : Word) (x i : Nat) (hi : i < w.count x) :∃ l t, w = l ++ x :: t ∧ l.count x = i := byinduction w generalizing i with| nil => simp at hi| cons a w ih =>by_cases h : a = x· subst acases i with| zero => exact ⟨[],w,rfl,rfl⟩| succ i =>have c : i < w.count x := by simpa [List.count_cons] using hiobtain ⟨l,t,e,ei⟩ := ih i cexact ⟨x::l,t,by simp [e],by simp [List.count_cons,ei]⟩· have c : i < w.count x := by simpa [List.count_cons,h,Ne.symm h] using hiobtain ⟨l,t,e,ei⟩ := ih i cexact ⟨a::l,t,by simp [e],by simp [List.count_cons,h,Ne.symm h,ei]⟩theorem slot_cut (w : Word) (x i : Nat) (hi : i+1 < w.count x) :∃ l mid t, w = l ++ [x] ++ mid ++ [x] ++ t ∧ l.count x = i ∧ x ∉ mid := byobtain ⟨l,suffix,e,ei⟩ := occurrence_cut w x i (by omega)have hs : x ∈ suffix := byapply List.count_pos_iff.mprw [e,List.count_append,ei] at hisimp only [List.count_cons_self] at hiomegaobtain ⟨mid,t,et,hn⟩ := List.eq_append_cons_of_mem hsexact ⟨l,mid,t,by simp [e,et,List.append_assoc],ei,hn⟩private theorem trim_start {α : Type} (a : α) (xs l v : List α)(h : a ∉ l) (sub : (a :: xs).Sublist (l ++ v)) : (a::xs).Sublist v := byinduction l with| nil => simpa using sub| cons b l ih =>cases sub with| cons _ sub => exact ih (fun m => h (by simp [m])) sub| cons_cons _ _ => exact (h (by simp)).elimprivate theorem framed_iff {α : Type} (l m t : List α) (a b y : α)(ha : a ∉ l) (hb : b ∉ t) :[a,y,b].Sublist (l ++ (a :: m ++ [b]) ++ t) ↔ y ∈ m := byconstructor· intro subrw [List.append_assoc] at subhave inner := (trim_start a _ l _ ha sub).reversesimp only [List.reverse_append,List.reverse_cons,List.reverse_nil,List.append_nil,List.nil_append,List.singleton_append,List.cons_append] at innerrw [List.append_assoc] at innerhave back := (trim_start b _ t.reverse _ (by simpa using hb) inner).reversehave mid : [a,y,b].Sublist (a :: (m ++ [b])) := by simpa using backhave last : ([y] ++ [b]).Sublist (m ++ [b]) := List.cons_sublist_cons.mp midsimpa using (List.append_sublist_append_right [b]).mp last· intro hyhave sub : ([y] : List α).Sublist m := by simpa using hyhave sub₂ := (List.append_sublist_append_right [b]).mpr subexact List.sublist_append_of_sublist_left (List.sublist_append_of_sublist_right (sub₂.cons₂ a))/-- Slot membership in a fixed literal split, including a possibly deficientoccupant. The occupant's own occurrence number is existential. -/theorem occupies_at_cut (l mid t : Word) (x y : Nat) (hn : x ∉ mid) :occupies (l ++ [x] ++ mid ++ [x] ++ t) x (l.count x) y ↔ y ∈ mid := bylet n := advance (fun _ => 0) (l ++ [x])let n' := advance (fun _ => 0) (l ++ [x] ++ mid ++ [x])have nm : (advance n mid) x = l.count x+1 := bysimp [n,advance,List.count_append,List.count_eq_zero.mpr hn]have ne : n' x = l.count x+2 := bysimp [n',advance,List.count_append,List.count_eq_zero.mpr hn]have eq : events (l ++ [x] ++ mid ++ [x] ++ t) =events l ++ ((x,l.count x) :: stamp n mid ++ [(x,l.count x+1)]) ++ stamp n' t := byunfold eventssimp only [stamp_append,stamp,List.append_nil,advance_append,n,n']simp [advance,List.count_append,List.count_eq_zero.mpr hn,List.append_assoc, Nat.add_assoc]have ha : (x,l.count x) ∉ events l := byintro hhave hh := (event_bounds (fun _ => 0) l x _ h).2omegahave hb : (x,l.count x+1) ∉ stamp n' t := byintro hhave hh := (event_bounds n' t x _ h).1omegaunfold occupies seesrw [eq]constructor· rintro ⟨j,hj⟩exact stamped_mem_label n mid (y,j) ((framed_iff _ _ _ _ _ _ ha hb).mp hj)· intro hyrw [← labels_of_stamp n mid] at hyobtain ⟨⟨a,j⟩,he,rfl⟩ := List.mem_map.mp hyexact ⟨j,(framed_iff _ _ _ _ _ _ ha hb).mpr he⟩theorem supplier (v : Word) (h : Nat → Word) (l k : Word) (x s t i r : Nat)(hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k))(hx : v.count x = r) (hs : s ∈ h x) (hout : t ∉ h x)(ho : occupies (l ++ v.flatMap h ++ k) s i t)(guard : ∀ y, occupies v x i y → v.count y = r) :∃ y, occupies v x i y ∧ t ∈ h y ∧ v.count y = r ∧ x ≠ y := byhave cb : (v.flatMap h).count s ≤ r := byhave c := cap ssimp only [List.count_append] at comegahave sat := (P455DonorInterval.exclusive h v x s r hr hx hs cb).2.2have hf := (saturated_factor_occupies l (v.flatMap h) k s i t r cap sat).mp hohave bound : i+1 < v.count x := byobtain ⟨j,hj⟩ := hfhave he : (s,i+1) ∈ events (v.flatMap h) := hj.mem (by simp)have hh := (event_bounds (fun _ => 0) _ s _ he).2omegaobtain ⟨L,I,R,cut,idx,cons⟩ := slot_cut v x i boundobtain ⟨p,q,split,_⟩ := List.eq_append_cons_of_mem hshave image : h x = p ++ [s] ++ q := by simpa [List.append_assoc] using splitobtain ⟨_,_,_,hni,hw,hi,_⟩ :=P455DonorInterval.consecutive_interval h v L I R x s p q r cut cons image hx cbhave hit : t ∈ q ++ I.flatMap h ++ p := byrw [← idx, ← hi, hw] at hfexact (occupies_at_cut _ _ _ _ _ hni).mp hfobtain ⟨y,hy,don⟩ := P455DonorInterval.interior_supplier h I x s t p q image hit houthave occ : occupies v x i y := byrw [cut,← idx]exact (occupies_at_cut _ _ _ _ _ cons).mpr hyexact ⟨y,occ,don,guard y occ,fun eq => hout (eq ▸ don)⟩/-- A terminal slot may include the boundary donor. No contact orseparate-block assumption is needed for this disjunction. -/theorem supplier_or_boundary (v : Word) (h : Nat → Word) (l k : Word) (x s t i r : Nat)(hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k))(hx : v.count x = r) (hs : s ∈ h x)(ho : occupies (l ++ v.flatMap h ++ k) s i t)(guard : ∀ y, occupies v x i y → v.count y = r) :t ∈ h x ∨ ∃ y, occupies v x i y ∧ t ∈ h y ∧ v.count y = r ∧ x ≠ y := byby_cases bound : t ∈ h x· exact .inl bound· exact .inr (supplier v h l k x s t i r hr cap hx hs bound ho guard)end P455SlotOriginend/- Begin Problem455EffectiveQ (from finite-semigroup-identity-bases). -/sectionnamespace P455EffectiveQopen P455Quotient Problem455Finiteabbrev W := List Natdef words (u : W) := wordsUpTo u u.lengththeorem subword {u v : W} (s : u.Sublist v) : u ∈ words v := covered v v.length u s.length_le s.subsetdef factorB (u v : W) := (words v).any (fun l => (words v).any (fun t => decide (v=l++u++t)))theorem factor_iff (u v : W) : factorB u v=true ↔ Factor u v := bysimp only [factorB,List.any_eq_true,decide_eq_true_eq]constructor· rintro ⟨l,_,t,_,h⟩; exact ⟨l,t,h⟩· rintro ⟨l,t,rfl⟩exact ⟨l,subword ((List.sublist_append_left l u).trans (List.sublist_append_left _ t)),t,subword (List.sublist_append_right _ _),rfl⟩def walkB (e : W → W → Bool) (u v : W) := P455EffectiveQReach.via e (words u) u vtheorem walk_iff (R : Rules Nat) (e : W → W → Bool) (ok : ∀ u v,e u v=true ↔ R.step u v)(u v : W) : walkB e u v=true ↔ Walk R.step u v := byconstructor· exact P455EffectiveQReach.sound _ (fun x y => (ok x y).mp) _· intro pathapply P455EffectiveQReach.complete _ (fun x y => (ok x y).mpr) _ _ pathintro x reachhave perm := List.perm_iff_count.mpr (count_walk R reach)exact covered _ _ _ (Nat.le_of_eq perm.length_eq.symm) (fun _ m => perm.mem_iff.mpr m)def goodB (e : W → W → Bool) (T u : W) :=(words T).any fun v => walkB e T v && factorB u vtheorem good_iff (R : Rules Nat) (e : W → W → Bool) (ok : ∀ u v,e u v=true ↔ R.step u v)(T u : W) : goodB e T u=true ↔ Good R T u := bysimp only [goodB,List.any_eq_true,Bool.and_eq_true,walk_iff R e ok,factor_iff]constructor· rintro ⟨v,_,p,f⟩; exact ⟨v,p,f⟩· rintro ⟨v,p,f⟩have pe := List.perm_iff_count.mpr (count_walk R p)exact ⟨v,covered _ _ _ (Nat.le_of_eq pe.length_eq.symm) (fun _ m => pe.mem_iff.mpr m),p,f⟩def liveB (e : W → W → Bool) (T : W) : Raw Nat → Bool| none => false| some u => goodB e T udef paired (e : W → W → Bool) (T : W) : Raw Nat → Raw Nat → Bool| some u,some v => goodB e T u && goodB e T v && walkB e u v| _,_ => falsedef relB (e : W → W → Bool) (T : W) (a b : Raw Nat) :=((!liveB e T a) && (!liveB e T b)) || paired e T a btheorem rel_iff (R : Rules Nat) (e : W → W → Bool) (ok : ∀ u v,e u v=true ↔ R.step u v)(T : W) (a b : Raw Nat) : relB e T a b=true ↔ Rel R T a b := byhave live (x : Raw Nat) : liveB e T x=true ↔ Live R T x := bycases x with| none => simp [liveB,Live]| some u => exact good_iff R e ok T uhave no (x : Raw Nat) : (!liveB e T x)=true ↔ ¬Live R T x := byrw [←live]; cases liveB e T x <;> decidesimp only [relB,Bool.or_eq_true,Bool.and_eq_true,no,P455Quotient.Rel]apply or_congr_rightcases a <;> cases b <;> simp [paired,good_iff R e ok,walk_iff R e ok,and_assoc,Option.some.injEq]def eqB (R : Rules Nat) (e : W → W → Bool) (ok : ∀ u v,e u v=true ↔ R.step u v)(T : W) (x y : Q R T) : Bool :=Quotient.liftOn₂ x y (relB e T) (byintro a b c d ac bdapply Bool.eq_iff_iff.mprrw [rel_iff R e ok,rel_iff R e ok]exact ⟨fun ab => rel_trans R (rel_symm R ac) (rel_trans R ab bd),fun cd => rel_trans R ac (rel_trans R cd (rel_symm R bd))⟩)theorem eq_iff (R : Rules Nat) (e : W → W → Bool) (ok : ∀ u v,e u v=true ↔ R.step u v)(T : W) (x y : Q R T) : eqB R e ok T x y=true ↔ x=y := byinduction x,y using Quotient.inductionOn₂ with | _ a b =>exact (rel_iff R e ok T a b).trans ⟨fun h => Quotient.sound (s := setoid R T) h,fun h => Quotient.exact h⟩def decEq (R : Rules Nat) (e : W → W → Bool) (ok : ∀ u v,e u v=true ↔ R.step u v)(T : W) : DecidableEq (Q R T) :=fun x y => decidable_of_bool _ (eq_iff R e ok T x y)end P455EffectiveQend/- Begin Problem455PaddedTiles (from finite-semigroup-identity-bases). -/sectionnamespace P455PaddedTilesopen P455Witnessstructure Tile (n : Nat) whereleft : Boolright : Booltop : Boolbottom : BooloddRow : BooloddColumn : Booll : Option (Fin n)c : Fin nr : Option (Fin n)b : Fin nderiving DecidableEqdef digit (n k : Nat) : Tag := List.replicate k true ++ List.replicate (n-k) falsedef letter : Option (Fin n) → Nat| none => 0| some a => a.val+1def token {n : Nat} (s : Option (Fin n)) := digit (n+1) (letter s)def code (p : Tile n) : Tag :=p.left :: p.right :: p.top :: p.bottom :: p.oddRow :: p.oddColumn ::(token p.l ++ (token (some p.c) ++ (token p.r ++ token (some p.b))))def widthCode (n : Nat) := 6+4*(n+1)private theorem token_length (s : Option (Fin n)) : (token s).length=n+1 := byhave lim : letter s ≤ n+1 := by cases s with| none => simp [letter]| some a => simp only [letter]; have := a.isLt; omegasimp [token,digit]; omegatheorem code_length (p : Tile n) : (code p).length = widthCode n := bysimp [code,widthCode,token_length]; omegaprivate theorem token_inj {a b : Option (Fin n)} (eq : token a = token b) : a=b := byhave ct := congrArg (List.count true) eqhave zero (k : Nat) : (List.replicate k false).count true=0 := byapply List.count_eq_zero.mprintro mhave := List.eq_of_mem_replicate mcontradictionsimp [token,digit,zero] at ctcases a <;> cases b <;> simp_all [letter,Fin.ext_iff]theorem code_inj {p q : Tile n} (eq : code p = code q) : p=q := bycases p with| mk l r t b row col ll cc rr bb =>cases q with| mk l' r' t' b' row' col' ll' cc' rr' bb' =>simp only [code,List.cons.injEq] at eqobtain ⟨rfl,rfl,rfl,rfl,rfl,rfl,eq⟩ := eqobtain ⟨e1,e⟩ := List.append_inj eq ((token_length _).trans (token_length _).symm)obtain ⟨e2,e⟩ := List.append_inj e ((token_length _).trans (token_length _).symm)obtain ⟨e3,e4⟩ := List.append_inj e ((token_length _).trans (token_length _).symm)have z1 := token_inj e1; have z2 := Option.some.inj (token_inj e2)have z3 := token_inj e3; have z4 := Option.some.inj (token_inj e4)subst_vars; rfl/-- Local alphabet of center symbols, including all possible head marks.Undefined entries reject forbidden triples, including a head leaving the tape. -/structure MachineTable (n : Nat) wheremarker : Fin n → Boolinitial : Bool → Fin naccept : Fin ndistinct : initial true ≠ acceptnext : Option (Fin n) → Fin n → Option (Fin n) → Option (Fin n)def Admitted (M : MachineTable n) (p : Tile n) :=M.next p.l p.c p.r = some p.b ∧p.left = p.l.isNone ∧ p.right = p.r.isNone ∧ M.marker p.c = p.left ∧(p.left=true → p.oddColumn=false) ∧(p.top=true → p.oddRow=false ∧ p.c=M.initial p.left) ∧(p.bottom=true → p.left=true → p.c=M.accept)def allowed (M : MachineTable n) (tag : Tag) := ∃ p, code p=tag ∧ Admitted M pdef Horizontal (p q : Tile n) :=p.right=false ∧ q.left=false ∧ p.top=q.top ∧ p.bottom=q.bottom ∧p.oddRow=q.oddRow ∧ p.oddColumn≠q.oddColumn ∧ q.l=some p.c ∧ p.r=some q.cdef Vertical (p q : Tile n) :=p.bottom=false ∧ q.top=false ∧ p.left=q.left ∧ p.right=q.right ∧p.oddColumn=q.oddColumn ∧ p.oddRow≠q.oddRow ∧ p.b=q.cdef system (n : Nat) : Tiles wherehorizontal := fun x y => ∃ p q : Tile n, code p=x ∧ code q=y ∧ Horizontal p qvertical := fun x y => ∃ p q : Tile n, code p=x ∧ code q=y ∧ Vertical p qleft := fun t => t[0]?.getD falseright := fun t => t[1]?.getD falsetop := fun t => t[2]?.getD falsebottom := fun t => t[3]?.getD falseoddRow := fun t => t[4]?.getD falseoddColumn := fun t => t[5]?.getD falsedef leftAt (row : Nat → Fin n) (x : Nat) := if x=0 then none else some (row (x-1))def rightAt (row : Nat → Fin n) (w x : Nat) := if x+1=w then none else some (row (x+1))def odd (i : Nat) : Bool := decide (i%2=1)/-- Finite accepting trace through row s on w cells. The final local updateis checked once, including at both flagged boundaries. -/structure Run (M : MachineTable n) (w s : Nat) wherepositive : 0<wrows : Nat → Nat → Fin nstart : ∀ x, x<w → rows 0 x=M.initial (decide (x=0))marks : ∀ y, y≤s → ∀ x, x<w → M.marker (rows y x)=decide (x=0)steps : ∀ y, y<s → ∀ x, x<w →M.next (leftAt (rows y) x) (rows y x) (rightAt (rows y) w x)=some (rows (y+1) x)accept : rows s 0=M.acceptstutter : ∀ x, x<w →M.next (leftAt (rows s) x) (rows s x) (rightAt (rows s) w x)=some (rows s x)variable {n w s : Nat} {M : MachineTable n}theorem positive_time (R : Run M w s) : 0<s := bycases s with| zero =>have z := (R.start 0 R.positive).symm.trans R.acceptexact False.elim (M.distinct (by simpa using z))| succ => omegadef tileAt (R : Run M w s) (extra y x : Nat) : Tile n whereleft := decide (x=0)right := decide (x+1=w)top := decide (y=0)bottom := decide (y=s+extra)oddRow := odd yoddColumn := odd xl := leftAt (R.rows (min y s)) xc := R.rows (min y s) xr := rightAt (R.rows (min y s)) w xb := R.rows (min (y+1) s) xtheorem admits_tile (R : Run M w s) (extra y x : Nat) (hx : x<w) :Admitted M (tileAt R extra y x) := byrefine ⟨?_,?_,?_,R.marks _ (Nat.min_le_right ..) _ hx,?_,?_,?_⟩· by_cases h : y<s· 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· simpa [tileAt,Nat.min_eq_right (by omega : s≤y),Nat.min_eq_right (by omega : s≤y+1)] using R.stutter x hx· by_cases e : x=0 <;> simp [tileAt,leftAt,e]· by_cases e : x+1=w <;> simp [tileAt,rightAt,e]· intro h; have e : x=0 := of_decide_eq_true h; simp [tileAt,odd,e]· intro h; have e : y=0 := of_decide_eq_true h; simpa [tileAt,odd,e] using R.start x hx· intro a bhave ey : y=s+extra := of_decide_eq_true ahave ex : x=0 := of_decide_eq_true bsimpa [tileAt,ex,ey,Nat.min_eq_right (by omega : s≤s+extra)] using R.acceptprivate theorem opposite (x : Nat) : odd x ≠ odd (x+1) := byunfold oddby_cases e : x%2=1· have f : (x+1)%2 ≠ 1 := by omegasimp [e,f]· have f : (x+1)%2 = 1 := by omegasimp [e,f]theorem horizontal (R : Run M w s) (extra y x : Nat) (hx : x+1<w) :Horizontal (tileAt R extra y x) (tileAt R extra y (x+1)) := byrefine ⟨?_,?_,rfl,rfl,rfl,opposite _,?_,?_⟩· simp [tileAt,show x+1≠w by omega]· simp [tileAt]· simp [tileAt,leftAt]· simp [tileAt,rightAt,show x+1≠w by omega]theorem vertical (R : Run M w s) (extra y x : Nat) (hy : y<s+extra) :Vertical (tileAt R extra y x) (tileAt R extra (y+1) x) := byrefine ⟨?_,?_,rfl,rfl,rfl,opposite _,rfl⟩· simp [tileAt,show y≠s+extra by omega]· simp [tileAt]structure Rectangle (M : MachineTable n) (width height : Nat) wherepositiveW : 0<widthpositiveH : 0<heighttag : Nat → Nat → Tageligible : ∀ y, y<height → ∀ x, x<width → allowed M (tag y x)flags : ∀ y, y<height → ∀ x, x<width →(system n).left (tag y x)=decide (x=0) ∧ (system n).right (tag y x)=decide (x+1=width) ∧(system n).top (tag y x)=decide (y=0) ∧ (system n).bottom (tag y x)=decide (y+1=height) ∧(system n).oddRow (tag y x)=odd y ∧ (system n).oddColumn (tag y x)=odd xright : ∀ y, y<height → ∀ x, x+1<width → (system n).horizontal (tag y x) (tag y (x+1))down : ∀ y, y+1<height → ∀ x, x<width → (system n).vertical (tag y x) (tag (y+1) x)def rectangle (R : Run M w s) (extra : Nat) : Rectangle M w (s+extra+1) wherepositiveW := R.positivepositiveH := by omegatag := fun y x => code (tileAt R extra y x)eligible := fun y _ x hx => ⟨_,rfl,admits_tile R extra y x hx⟩flags := byintro y _ x _simp [system,code,tileAt]right := fun y _ x hx => ⟨_,_,rfl,rfl,horizontal R extra y x hx⟩down := fun y hy x _ => ⟨_,_,rfl,rfl,vertical R extra y x (by omega)⟩/-- The same tag alphabet, tag length and tile relations work at everybound. Width one is allowed. The construction pads time alone. -/theorem unbounded (R : Run M w s) (k : Nat) :∃ h, 1<h ∧ k<2*(w*h) ∧ Nonempty (Rectangle M w h) := byhave time := positive_time Rlet h := s+k+1have hw : 1≤w := R.positivehave size : h ≤ w*h := by simpa using Nat.mul_le_mul_right h hwexact ⟨h,by dsimp [h]; omega,by dsimp [h] at *; omega,⟨rectangle R k⟩⟩end P455PaddedTilesend/- Begin Problem455GadgetPaths (from finite-semigroup-identity-bases). -/section/- Routes are expressed in the same concrete contact predicates as thecertificate. Each step records its record or port orientation. -/namespace P455Pathsopen P455Witness Problem455.Slotsabbrev Step := Nat × ContactChoicedef Walk (r : Nat) (allow : Tag → Prop) (mark : Marking) (w : W) (s : Nat) :List Step → Prop| [] => True| (b,c) :: rest => Holds r allow mark w (contact r s b c) ∧ Walk r allow mark w b restdef endpoint (s : Nat) : List Step → Nat| [] => s| (b,_) :: rest => endpoint b resttheorem route_iff {r allow mark w} (s : Nat) (p : List Step) (f : Nat → Query) :Holds r allow mark w (route r s p f) ↔Walk r allow mark w s p ∧ Holds r allow mark w (f (endpoint s p)) := byinduction p generalizing s with| nil => simp [route, Walk, endpoint]| cons p ps ih => rcases p with ⟨b,c⟩; simp only [route,Holds,Walk,endpoint,ih,and_assoc]def Near (r : Nat) (allow : Tag → Prop) (mark : Marking) (w : W) (s b J : Nat) : Prop :=∃ p, Walk r allow mark w s p ∧ endpoint s p = b ∧ p.length ≤ Jtheorem near_self {r allow mark w} (s J : Nat) : Near r allow mark w s s J :=⟨[],True.intro,rfl,Nat.zero_le _⟩theorem near_one {r allow mark w s t} (c : ContactChoice)(hc : Holds r allow mark w (contact r s t c)) : Near r allow mark w s t 1 :=⟨[(t,c)],⟨hc,True.intro⟩,rfl,Nat.le_refl _⟩theorem near_mono {r allow mark w s b n m} (h : Near r allow mark w s b n) (le : n ≤ m) :Near r allow mark w s b m := byobtain ⟨p,v,e,len⟩ := h; exact ⟨p,v,e,Nat.le_trans len le⟩theorem walk_append {r allow mark w} (a : Nat) (p q : List Step) :Walk r allow mark w a (p++q) ↔ Walk r allow mark w a p ∧ Walk r allow mark w (endpoint a p) q := byinduction p generalizing a with| nil => simp [Walk,endpoint]| cons ab p ih => obtain ⟨b,c⟩ := ab; simp [Walk,endpoint,ih,and_assoc]theorem endpoint_append (a : Nat) (p q : List Step) :endpoint a (p++q) = endpoint (endpoint a p) q := byinduction p generalizing a with| nil => rfl| cons ab p ih => exact ih ab.1theorem near_trans {r allow mark w a b c i j} (h : Near r allow mark w a b i)(g : Near r allow mark w b c j) : Near r allow mark w a c (i+j) := byobtain ⟨p,hp,ep,lp⟩ := hobtain ⟨q,hq,eq,lq⟩ := gexact ⟨p++q,(walk_append ..).mpr ⟨hp,ep.symm ▸ hq⟩,by rw [endpoint_append,ep,eq], by simp; omega⟩abbrev V (r : Nat) (allow : Tag → Prop) (mark : Marking) (w : W) := Holds r allow mark wtheorem allQ_iff {r allow mark w} (qs : List Query) :V r allow mark w (allQ qs) ↔ ∀ q ∈ qs, V r allow mark w q := byinduction qs with| nil => simp [allQ,V,Holds]| cons x xs ih => change (_ ∧ V r allow mark w (allQ xs)) ↔ _; simp [ih]theorem slot_route {r allow mark w} (s : SlotCertificate)(ok : V r allow mark w (s.query r)) :let a := if s.startAtMate then s.anchor.mate else s.anchor.owners.steps.length ≤ 6 ∧ Walk r allow mark w a s.steps ∧V r allow mark w (terminalSlot r (endpoint a s.steps) s.terminalIndex s.defect) := bysimp only [SlotCertificate.query,allQ,Holds,V] at okexact ⟨ok.2.1,(route_iff ..).mp ok.2.2.1⟩theorem record_counts {r allow mark w a b tag}(bound : P455Closure.Cap r w) (recProof : V r allow mark w (.record a b tag)) :w.count a = r ∧ w.count b = r := byobtain ⟨ne,hl,_,bit,eq⟩ := recProofhave n := congrArg List.length eqsimp only [length_select_pair a b ne,profile,List.length_append,profile_prefix_length] at nhave ca := bound a; have cb := bound bcases bit <;> simp [pair] at n <;> omegatheorem record_pair {r allow mark w} {n : Node} (recProof : V r allow mark w (typedNode n)) :Near r allow mark w n.owner n.mate 1 ∧ Near r allow mark w n.mate n.owner 1 :=⟨near_one (.record n.tag false) recProof, near_one (.record n.tag true) recProof⟩private theorem stamp_lower (n : Nat → Nat) (w : W) (a i : Nat)(h : (a,i) ∈ stamp n w) : n a ≤ i := byinduction w generalizing n with| nil => simp [stamp] at h| cons b w ih =>rcases List.mem_cons.mp h with he|hh· cases he; exact Nat.le_refl _· have z := ih (advance n [b]) hh; simp only [advance] at z; omegatheorem stamp_unique (n : Nat → Nat) (w : W) : (stamp n w).Nodup := byinduction w generalizing n with| nil => simp [stamp]| cons a w ih =>apply List.nodup_cons.mprrefine ⟨fun bad => ?_, ih _⟩have low := stamp_lower (advance n [a]) w a (n a) badsimp [advance] at low <;> omegatheorem owner_early {r allow mark w} (a b : Node)(early : V r allow mark w (earlyDisjoint [a.owner,a.mate] [b.owner,b.mate])) :V r allow mark w (earlyDisjoint [a.owner] [b.owner]) := byrcases early with h|h· left; exact ⟨h.1,True.intro⟩· right; exact ⟨h.1,True.intro⟩theorem owner_port {r allow mark w} (cap : P455Closure.Cap r w) (p : Fin 5) (a b : Node)(ok : V r allow mark w (orientedPort p a b)) :V r allow mark w (contact r a.owner b.owner (.port p false)) ∧V r allow mark w (contact r b.owner a.owner (.port p true)) := byobtain ⟨na,nb,early,order,_⟩ := oklet i := 3 + 2*p.vallet pat := [(a.owner,i),(b.owner,i),(a.owner,i+1),(b.owner,i+1)]have sub : pat.Sublist [(a.owner,i),(a.mate,i),(b.owner,i),(b.mate,i),(a.owner,i+1),(a.mate,i+1),(b.owner,i+1),(b.mate,i+1)] := byexact .cons₂ _ (.cons _ (.cons₂ _ (.cons _ (.cons₂ _ (.cons _ (.cons₂ _ (List.nil_sublist _)))))))have obs : V r allow mark w (.order pat) :=⟨fun e he => order.1 e (sub.subset he),sub.trans order.2⟩have nd := (stamp_unique (fun _ => 0) w).sublist obs.2have ne : a.owner ≠ b.owner := byintro eqhave := (List.nodup_cons.mp nd).1exact this (by simp [eq])have xa := (record_counts cap na).1have xb := (record_counts cap nb).1have ed := owner_early a b earlyexact ⟨⟨ne,xa,xb,ed,obs,True.intro⟩,⟨Ne.symm ne,xb,xa,ed.symm,obs,True.intro⟩⟩/-- One actual port yields an owner contact in both directions. -/def Joined (r : Nat) (allow : Tag → Prop) (mark : Marking) (w : W) (a b : Node) :=Near r allow mark w a.owner b.owner 1 ∧ Near r allow mark w b.owner a.owner 1theorem port_joined {r allow mark w} (cap : P455Closure.Cap r w) (n : Nat) (hn : n < 5){a b : Node} (ok : V r allow mark w (orientedPort n a b)) : Joined r allow mark w a b := byobtain ⟨f,g⟩ := owner_port cap ⟨n,hn⟩ a b okexact ⟨near_one _ f,near_one _ g⟩theorem right_paths {r allow mark w ts a b} (cap : P455Closure.Cap r w)(ok : V r allow mark w (rightward ts a b)) : Joined r allow mark w a b :=port_joined cap _ (by split <;> decide) ok.2.1theorem down_paths {r allow mark w ts a b} (cap : P455Closure.Cap r w)(ok : V r allow mark w (downward ts a b)) : Joined r allow mark w a b :=port_joined cap _ (by split <;> decide) ok.2theorem neighbor_paths {r allow mark w ts a b} (cap : P455Closure.Cap r w) (d : Dir)(ok : V r allow mark w (neighbor ts a b d)) : Joined r allow mark w a b := bycases d with| right => exact right_paths cap ok| left => exact (right_paths cap ok).symm| down => exact down_paths cap ok| up => exact (down_paths cap ok).symmtheorem neighbor_target_record {r allow mark w ts a b d}(ok : V r allow mark w (neighbor ts a b d)) : V r allow mark w (typedNode b) := bycases d with| right => exact ok.2.1.2.1| left => exact ok.2.1.1| down => exact ok.2.2.1| up => exact ok.2.1theorem marked_typed {r allow mark w a bit} (m : V r allow mark w (markedNode a bit)) :V r allow mark w (typedNode a) := ⟨m.1,m.2.1,m.2.2.1,bit,m.2.2.2.2⟩end P455Pathsend/- Begin Problem455ContactGeometry (from finite-semigroup-identity-bases). -/sectionnamespace P455ContactGeometryopen Problem455.Slots P455Witness/-- Erasing unselected labels preserves the indices of selected labels. -/theorem project_stamp (keep w : Word) (n n' : Nat → Nat)(agree : ∀ a ∈ keep, n a = n' a) :stamp n (select keep w) = (stamp n' w).filter (fun e => decide (e.1 ∈ keep)) := byinduction w generalizing n n' with| nil => rfl| cons a w ih =>by_cases ha : a ∈ keep· simp only [select, List.filter_cons, decide_eq_true ha, if_true, stamp]rw [agree a ha]congr 1apply ihintro b hbsimp [advance, agree b hb]· simp only [select, List.filter_cons, decide_eq_false ha, Bool.false_eq_true, if_false, stamp]apply ihintro b hbhave ne : a ≠ b := fun e => ha (e ▸ hb)simp [advance, ne, Ne.symm ne, agree b hb]theorem projected_events_sublist (keep w : Word) : (events (select keep w)).Sublist (events w) := byrw [events, project_stamp keep w (fun _ => 0) (fun _ => 0) (fun _ _ => rfl)]exact List.filter_sublist ..private theorem profile_initial {a b : Nat} (ab : a ≠ b) (tag : Tag) (bit : Bool) :[(a,0),(a,1),(b,0),(a,2),(b,1),(b,2)].Sublist (events (profile a b tag bit)) := byhave shape : ∃ t : Word, profile a b tag bit = [a,a,b,a,b,b] ++ t := byunfold profile profilePrefixsimp only [List.append_assoc]exact ⟨_,rfl⟩obtain ⟨t,e⟩ := shaperw [e,events,stamp_append]have pre : stamp (fun _ => 0) [a,a,b,a,b,b] = [(a,0),(a,1),(b,0),(a,2),(b,1),(b,2)] := bysimp [stamp,advance,ab,Ne.symm ab]rw [pre]exact List.sublist_append_left ../-- A record supplies the two open slot witnesses and an early order thatcannot occur between two labels donated by one uniform variable. -/private theorem record_geometry {z : Word} {a b : Nat} {tag : Tag}(ab : a ≠ b) (typ : typed z a b tag) :occupies z a 1 b ∧ occupies z b 0 a ∧ sees z [(a,1),(b,0)] := byobtain ⟨bit,eq⟩ := typhave initial := profile_initial ab tag bitrw [← eq] at initialhave sub := initial.trans (projected_events_sublist [a,b] z)refine ⟨⟨0,?_⟩,⟨2,?_⟩,?_⟩· exact (List.Sublist.cons _ (.cons₂ _ (.cons₂ _ (.cons₂ _ (List.nil_sublist _))))).trans sub· exact (List.Sublist.cons _ (.cons _ (.cons₂ _ (.cons₂ _ (.cons₂ _ (List.nil_sublist _)))))).trans sub· exact (List.Sublist.cons _ (.cons₂ _ (.cons₂ _ (List.nil_sublist _)))).trans sub/-- The seven slots and the obstruction to a shared donor follow fromthe actual record or port contact. The port can be read in either direction. -/theorem geometry {r allow mark z a b c} (hc : Holds r allow mark z (contact r a b c)) :(∃ i, slotStart i ∧ occupies z a i b) ∧(∃ i, 0 < i ∧ (sees z [(a,i),(b,0)] ∨ sees z [(b,i),(a,0)])) := bycases c with| record tag rev =>cases rev· obtain ⟨ab,_,_,typ⟩ := hcobtain ⟨slot,_,ord⟩ := record_geometry ab typexact ⟨⟨1,by simp [slotStart],slot⟩,⟨1,by decide,.inl ord⟩⟩· obtain ⟨ba,_,_,typ⟩ := hcobtain ⟨_,slot,ord⟩ := record_geometry ba typexact ⟨⟨0,by simp [slotStart],slot⟩,⟨1,by decide,.inr ord⟩⟩| port phase rev =>let i := 3+2*phase.valhave hi : slotStart i := by have := phase.isLt; unfold i slotStart; omegahave early : Holds r allow mark z (earlyDisjoint [a] [b]) := hc.2.2.2.1have ord : sees z [(a,2),(b,0)] ∨ sees z [(b,2),(a,0)] := byrcases early with e | e· exact .inl e.1.2· exact .inr e.1.2refine ⟨⟨i,hi,?_⟩,⟨2,by decide,ord⟩⟩cases rev· have seq : sees z [(a,i),(b,i),(a,i+1),(b,i+1)] := hc.2.2.2.2.1.2exact ⟨i,(List.Sublist.cons₂ _ (.cons₂ _ (.cons₂ _ (List.nil_sublist _)))).trans seq⟩· have seq : sees z [(b,i),(a,i),(b,i+1),(a,i+1)] := hc.2.2.2.2.1.2exact ⟨i+1,(List.Sublist.cons _ (.refl _)).trans seq⟩theorem contact_slot {r allow mark z a b c} (hc : Holds r allow mark z (contact r a b c)) :∃ i, slotStart i ∧ occupies z a i b := (geometry hc).1/-- Membership of a stamped occurrence gives inclusive lower and exclusiveupper bounds from the prefix counter and the number of copies in the segment. -/theorem stamp_range (n : Nat → Nat) (w : Word) {a i : Nat} (h : (a,i) ∈ stamp n w) :n a ≤ i ∧ i < n a + w.count a := byinduction w generalizing n with| nil => simp [stamp] at h| cons b w ih =>rcases List.mem_cons.mp h with head | tail· obtain ⟨rfl,rfl⟩ := Prod.mk.inj headsimp [List.count_cons]· have z := ih _ tailby_cases e : b = a· subst b; simp [advance,List.count_cons] at z ⊢; omega· simp [advance,List.count_cons,e,Ne.symm e] at z ⊢; omegaprivate theorem impossible_order {z f t : Word} {a b i : Nat} (eq : z = f ++ t)(low : f.count a ≤ i) (positive : 0 < f.count b) : ¬ sees z [(a,i),(b,0)] := byintro ehave h : [(a,i),(b,0)].Sublist (events f ++ stamp (advance (fun _ => 0) f) t) := bysimpa only [sees, eq, events, stamp_append] using ehave first : (a,i) ∉ events f := byintro memhave bad := (stamp_range (fun _ => 0) f mem).2simp only [Nat.zero_add] at badomegahave last : (b,0) ∉ stamp (advance (fun _ => 0) f) t := byintro memhave := stamp_range (advance (fun _ => 0) f) t memsimp [advance] at thisomegahave strip {α : Type} {x y : α} {l k : List α} (n : x ∉ l)(s : [x,y].Sublist (l ++ k)) : [x,y].Sublist k := byinduction l with| nil => exact s| cons j l ih =>cases s with| cons _ rest => exact ih (fun e => n (by simp [e])) rest| cons_cons _ _ => exact (n (by simp)).elimexact last ((strip first h).subset (by simp))/-- Initial source/prefix split at the first occurrence of one used name. -/private theorem first_split (x : Nat) (v : Word) (occ : x ∈ v) :∃ l t, v = l ++ x :: t ∧ x ∉ l := byinduction v with| nil => simp at occ| cons a v ih =>by_cases e : a = x· subst a; exact ⟨[],v,rfl,by simp⟩· obtain ⟨l,t,eq,nh⟩ := ih (by simpa [Ne.symm e] using occ)exact ⟨a::l,t,by simp [eq],by simp [e,Ne.symm e,nh]⟩/-- Two labels from the same donor each have exactly one occurrence inthe prefix ending at its first image, even if the labels coincide. -/theorem same_image_no_early {r : Nat} {v : Word} {h : Nat → Word}{l t : Word} {x a b i : Nat} (hr : 0 < r)(bound : P455Closure.Cap r (l ++ v.flatMap h ++ t))(hx : v.count x = r) (ha : a ∈ h x) (hb : b ∈ h x) (hi : 0 < i) :¬ sees (l ++ v.flatMap h ++ t) [(a,i),(b,0)] := byhave px : x ∈ v := List.count_pos_iff.mp (hx ▸ hr)obtain ⟨pre,post,cut,avoid⟩ := first_split x v pxhave bounds (j : Nat) (mem : j ∈ h x) : (l ++ pre.flatMap h ++ h x).count j = 1 := byhave bb := bound jsimp only [List.count_append] at bbobtain ⟨one,exclusive,sat⟩ := P455DonorInterval.exclusive h v x j r hr hx mem (by omega)have fresh : j ∉ pre.flatMap h := byintro zobtain ⟨y,hy,yj⟩ := List.mem_flatMap.mp zexact exclusive y (by simp [cut,hy]) (fun e => avoid (e ▸ hy)) yjhave left : l.count j = 0 := by omegasimp [List.count_append,left,List.count_eq_zero.mpr fresh,one]have eq : l ++ v.flatMap h ++ t = (l ++ pre.flatMap h ++ h x) ++ (post.flatMap h ++ t) := bysimp [cut,List.flatMap_append,List.append_assoc]exact impossible_order eq (by rw [bounds a ha]; omega) (by rw [bounds b hb]; decide)/-- An actual contact to a label donated by x cannot be another letter ofh(x). Saturation is required only of the owner donor. -/theorem contact_excludes_image {r allow mark} {v : Word} {h : Nat → Word}{l t : Word} {x a b c} (hr : 0 < r)(bound : P455Closure.Cap r (l ++ v.flatMap h ++ t))(hx : v.count x = r) (ha : a ∈ h x)(hc : Holds r allow mark (l ++ v.flatMap h ++ t) (contact r a b c)) : b ∉ h x := byintro hbobtain ⟨i,hi,ord⟩ := (geometry hc).2rcases ord with ord | ord· exact same_image_no_early hr bound hx ha hb hi ord· exact same_image_no_early hr bound hx hb ha hi ordend P455ContactGeometryend/- Begin Problem455ContactReflection (from finite-semigroup-identity-bases). -/sectionnamespace P455ContactReflectionopen Problem455.Slots P455Witnessdef eventMap (d : Nat → Nat) (e : Event) : Event := (d e.1, e.2)theorem select_stamped (keep w : W) (n n' : Nat → Nat)(eqn : ∀ a ∈ keep, n a = n' a) :(stamp n w).filter (fun e => decide (e.1 ∈ keep)) = stamp n' (select keep w) := byinduction w generalizing n n' with| nil => rfl| cons a w ih =>by_cases ha : a ∈ keep· simp only [stamp, select, List.filter_cons, ha, decide_true, Bool.true_eq, if_true]rw [eqn a ha]congr 1apply ihintro b hbsimp only [advance, eqn b hb]· simp only [stamp, select, List.filter_cons, ha, decide_false, Bool.false_eq_true, if_false]apply ihintro b hbhave ab : a ≠ b := fun e => ha (e ▸ hb)simp [advance, eqn b hb, ab]theorem sees_select (keep w : W) (pat : List Event) (support : ∀ e ∈ pat, e.1 ∈ keep)(seen : sees w pat) : sees (select keep w) pat := byhave filtered := seen.filter (fun e => decide (e.1 ∈ keep))have self : pat.filter (fun e => decide (e.1 ∈ keep)) = pat := byapply List.filter_eq_self.mpr; simpa using supportrw [self] at filteredunfold sees events at *rw [select_stamped keep w _ (fun _ => 0) (fun _ _ => rfl)] at filteredexact filteredtheorem select_sees (keep w : W) (pat : List Event) (seen : sees (select keep w) pat) :sees w pat := byunfold sees events at *rw [← select_stamped keep w (fun _ => 0) _ (fun _ _ => rfl)] at seenexact seen.trans (List.filter_sublist ..)theorem stamp_map (d : Nat → Nat) (w keep : W) (n n' : Nat → Nat)(inside : ∀ a ∈ w, a ∈ keep) (dinj : ∀ a ∈ keep, ∀ b ∈ keep, d a = d b → a = b)(eqn : ∀ a ∈ keep, n a = n' (d a)) :(stamp n w).map (eventMap d) = stamp n' (w.map d) := byinduction w generalizing n n' with| nil => rfl| cons a w ih =>have ha := inside a (by simp)simp only [stamp, List.map_cons, eventMap, eqn a ha, List.cons.injEq, true_and]apply ih _ _ (fun b hb => inside b (by simp [hb]))intro b hbby_cases eq : a = b· subst b; simp [advance,eqn a ha]· have ne : d a ≠ d b := fun e => eq (dinj a ha b hb e)simp [advance, eq, ne, eqn b hb]theorem selected_donor_word {r : Nat} {v l k : W} {h : Nat → W}(hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k))(keep : W) (d : Nat → Nat)(uniform : ∀ a ∈ keep, v.count (d a) = r ∧ a ∈ h (d a))(dinj : ∀ a ∈ keep, ∀ b ∈ keep, d a = d b → a = b) :(select keep (l ++ v.flatMap h ++ k)).map d = select (keep.map d) v := byhave exclusive (a) (ha : a ∈ keep) :=P455DonorInterval.exclusive h v (d a) a r hr (uniform a ha).1 (uniform a ha).2(by have := cap a; simp only [List.count_append] at this; omega)have disjoint (a) (ha : a ∈ keep) := P455DonorInterval.enclosing_context(v.flatMap h) l k a r (exclusive a ha).2.2 (cap a)have sl := select_nil keep l (fun a hm ha => (disjoint a ha).1 hm)have sk := select_nil keep k (fun a hm ha => (disjoint a ha).2 hm)rw [select_append, select_append, sl, sk, List.nil_append, List.append_nil]have owner (x) (hx : x ∈ v) (a) (ha : a ∈ keep) (in_h : a ∈ h x) : d a = x := byby_cases eq : x = d a· exact eq.symm· exact ((exclusive a ha).2.1 x hx eq in_h).elimhave per (x) (hx : x ∈ v) :(select keep (h x)).map d = select (keep.map d) [x] := byby_cases mem : x ∈ keep.map d· obtain ⟨a,ha,eq⟩ := List.mem_map.mp memhave all_a (b) (hb : b ∈ select keep (h x)) : b = a := byobtain ⟨in_h,keep_b⟩ := List.mem_filter.mp hbhave kb : b ∈ keep := by simpa using keep_bexact dinj b kb a ha ((owner x hx b kb in_h).trans eq.symm)have ct : (select keep (h x)).count a = 1 := byrw [select, List.count_filter (by simpa using ha), ← eq, (exclusive a ha).1]have len := List.count_eq_length.mpr (fun b hb => (all_a b hb).symm)have one : select keep (h x) = List.replicate 1 a :=List.eq_replicate_iff.mpr ⟨len.symm.trans ct, all_a⟩rw [one]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]· have none := select_nil keep (h x) (fun a in_h ha =>mem (List.mem_map.mpr ⟨a,ha,owner x hx a ha in_h⟩))rw [none]simp only [select, List.filter_cons, mem, decide_false, Bool.false_eq_true, if_false, List.filter_nil, List.map_nil]have fit (w : W) (sub : ∀ x ∈ w, x ∈ v) :(select keep (w.flatMap h)).map d = select (keep.map d) w := byinduction w with| nil => rfl| cons a ws ih =>change (select keep (h a ++ ws.flatMap h)).map d = select (keep.map d) ([a] ++ ws)rw [select_append, List.map_append, select_append, per a (sub a (by simp)),ih (fun b hb => sub b (by simp [hb]))]exact fit v (fun _ hmem => hmem)theorem reflect_order {r : Nat} {v l k : W} {h : Nat → W}(hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k))(keep : W) (d : Nat → Nat)(uniform : ∀ a ∈ keep, v.count (d a) = r ∧ a ∈ h (d a))(dinj : ∀ a ∈ keep, ∀ b ∈ keep, d a = d b → a = b)(pat : List Event) (inside : ∀ e ∈ pat, e.1 ∈ keep)(seen : sees (l ++ v.flatMap h ++ k) pat) : sees v (pat.map (eventMap d)) := byhave selected := sees_select keep _ pat inside seenapply select_sees (keep.map d)have named := selected.map (eventMap d)unfold sees events at *rw [stamp_map d _ keep _ (fun _ => 0)(fun a ha => by have := (List.mem_filter.mp ha).2; simpa using this) dinj (fun _ _ => rfl),selected_donor_word hr cap keep d uniform dinj] at namedexact namedtheorem map_profile (d : Nat → Nat) (a b : Nat) (tag : Tag) (bit : Bool) :(profile a b tag bit).map d = profile (d a) (d b) tag bit := byhave bp (c : Bool) : (pair a b c).map d = pair (d a) (d b) c := by cases c <;> rflhave tp : (tag.flatMap (pair a b)).map d = tag.flatMap (pair (d a) (d b)) := byinduction tag with| nil => rfl| cons c tag ih => simp [bp, ih]simp only [profile,profilePrefix,List.map_append,bp,tp]rflprivate theorem two_labels {r : Nat} {v l k : W} {h : Nat → W} {x y s t : Nat}(hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k))(hx : v.count x = r) (hy : v.count y = r) (hxy : x ≠ y) (hs : s ∈ h x) (ht : t ∈ h y) :∃ d : Nat → Nat, d s = x ∧ d t = y ∧(∀ a ∈ [s,t], v.count (d a) = r ∧ a ∈ h (d a)) ∧(∀ a ∈ [s,t], ∀ b ∈ [s,t], d a = d b → a = b) := byhave hy' : y ∈ v := List.count_pos_iff.mp (by omega)have diff : s ≠ t := byintro eqhave excl := P455DonorInterval.exclusive h v x s r hr hx hs(by have := cap s; simp only [List.count_append] at this; omega)exact excl.2.1 y hy' (Ne.symm hxy) (eq ▸ ht)let d := fun a => if a = s then x else yhave p : d s = x := by simp [d]have q : d t = y := by simp [d, Ne.symm diff]refine ⟨d,p,q,?_,?_⟩· intro a memsimp only [List.mem_cons, List.not_mem_nil, or_false] at memrcases mem with rfl | rfl· exact p.symm ▸ And.intro hx hs· exact q.symm ▸ And.intro hy ht· intro a ha b hb esimp only [List.mem_cons, List.not_mem_nil, or_false] at ha hbrcases ha with rfl | rfl <;> rcases hb with rfl | rfl <;> simp_alltheorem reflect_profile {r : Nat} {v l k : W} {h : Nat → W} {x y s t : Nat}(hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k))(hx : v.count x = r) (hy : v.count y = r) (hxy : x ≠ y) (hs : s ∈ h x) (ht : t ∈ h y)(tag : Tag) (bit : Bool) (eq : select [s,t] (l ++ v.flatMap h ++ k) = profile s t tag bit) :select [x,y] v = profile x y tag bit := byobtain ⟨d,p,q,uniform,inj⟩ := two_labels hr cap hx hy hxy hs hthave e := selected_donor_word hr cap [s,t] d uniform injrw [eq,map_profile] at esimpa only [List.map_cons,List.map_nil,p,q] using e.symmtheorem reflect_order_query {r : Nat} {v l k : W} {h : Nat → W}{allow : Tag → Prop} {mark : Marking}(hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k))(keep : W) (d : Nat → Nat)(uniform : ∀ a ∈ keep, v.count (d a) = r ∧ a ∈ h (d a))(dinj : ∀ a ∈ keep, ∀ b ∈ keep, d a = d b → a = b)(pat : List Event) (inside : ∀ e ∈ pat, e.1 ∈ keep)(seen : Holds r allow mark (l ++ v.flatMap h ++ k) (.order pat)) :Holds r allow mark v (.order (pat.map (eventMap d))) := byobtain ⟨imm, order⟩ := seenrefine ⟨?_, reflect_order hr cap keep d uniform dinj pat inside order⟩rintro e heobtain ⟨a,ha,rfl⟩ := List.mem_map.mp heexact imm a hatheorem reflect_contact {r : Nat} {allow : Tag → Prop} {mark : Marking}{v l k : W} {h : Nat → W} {x y s t : Nat}(hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k))(hx : v.count x = r) (hy : v.count y = r) (hxy : x ≠ y) (hs : s ∈ h x) (ht : t ∈ h y)(c : ContactChoice) :Holds r allow mark (l ++ v.flatMap h ++ k) (contact r s t c) →Holds r allow mark v (contact r x y c) := bycases c with| record tag rev =>cases rev· rintro ⟨_,len,code,bit,eq⟩exact ⟨hxy,len,code,bit,reflect_profile hr cap hx hy hxy hs ht tag bit eq⟩· rintro ⟨_,len,code,bit,eq⟩exact ⟨Ne.symm hxy,len,code,bit,reflect_profile hr cap hy hx (Ne.symm hxy) ht hs tag bit eq⟩| port phase rev =>obtain ⟨d,p,q,uniform,inj⟩ := two_labels hr cap hx hy hxy hs hthave orders := @reflect_order_query r v l k h allow mark hr cap [s,t] d uniform injhave left (i j : Nat) (sig : Holds r allow mark (l ++ v.flatMap h ++ k) (earlier s i t j)) :Holds r allow mark v (earlier x i y j) := byhave o := orders [(s,i),(t,j)] (by simp) sigsimpa [eventMap,p,q,earlier] using ohave right (i j : Nat) (sig : Holds r allow mark (l ++ v.flatMap h ++ k) (earlier t i s j)) :Holds r allow mark v (earlier y i x j) := byhave o := orders [(t,i),(s,j)] (by simp) sigsimpa [eventMap,p,q,earlier] using ointro coreobtain ⟨_,_,_,early,ordered,_⟩ := corerefine ⟨hxy,hx,hy,?_,?_,True.intro⟩· rcases early with ⟨o,_⟩ | ⟨o,_⟩· exact Or.inl ⟨left 2 0 o,True.intro⟩· exact Or.inr ⟨right 2 0 o,True.intro⟩· let i := 3 + 2 * phase.valcases rev with| false =>have o := orders [(s,i),(t,i),(s,i+1),(t,i+1)] (by simp) orderedsimpa [eventMap,p,q,i] using o| true =>have o := orders [(t,i),(s,i),(t,i+1),(s,i+1)] (by simp) orderedsimpa [eventMap,p,q,i] using oend P455ContactReflectionend/- Begin Problem455TerminalTransfer (from finite-semigroup-identity-bases). -/sectionnamespace P455TerminalTransferopen Problem455.Slots P455Witness/-- In the overflow branch the assignment is specified only on the fiveselected labels. Different source names are enough for the slot bound. -/def Lift (v : Word) (h : Nat → Word) (x i r : Nat) : SlotDefect → Prop| .deficient _ => False| .overflow xs => ∃ assign : Nat → Nat, xs.length = 5 ∧ (x :: xs.map assign).Nodup ∧∀ a ∈ xs, occupies v x i (assign a) ∧ a ∈ h (assign a) ∧ v.count (assign a) = rtheorem holds_all {r allow mark z} (qs : List Query) :Holds r allow mark z (allQ qs) ↔ ∀ q ∈ qs, Holds r allow mark z q := byinduction qs with| nil => simp [allQ,Holds]| cons q qs ih => simp [allQ,Holds,ih]theorem block_separation {r allow mark z} (xs : List Nat) :Holds r allow mark z (differentBlocks xs) ↔xs.Pairwise (fun a b => ¬ Problem455Swap.SameBlock r z a b) := byinduction xs with| nil => simp [differentBlocks,Holds]| cons a xs ih =>simp [differentBlocks,Holds,holds_all,ih,List.pairwise_cons]theorem terminal (v : Word) (h : Nat → Word) (l k : Word) (x s i r : Nat)(hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k)) (hx : v.count x = r)(hs : s ∈ h x) (guard : ∀ y, occupies v x i y → v.count y = r) {allow mark}(d : SlotDefect)(obs : Holds r allow mark (l ++ v.flatMap h ++ k) (terminalSlot r s i d)) :Lift v h x i r d := bylet z := l ++ v.flatMap h ++ khave capF : ∀ j, (v.flatMap h).count j ≤ r := byintro ahave c := cap asimp only [List.count_append] at comegahave satZ (a y : Nat) (hy : v.count y = r) (ha : a ∈ h y) : z.count a = r := byhave full := (P455DonorInterval.exclusive h v y a r hr hy ha (capF a)).2.2have c := cap asimp only [z,List.count_append] at *omegahave common (y a b : Nat) (hy : v.count y = r) (ha : a ∈ h y) (hb : b ∈ h y) :Problem455Swap.SameBlock r z a b := byhave capZ : Problem455Swap.cap r z := byintro crw [Problem455BlockBridge.occ_count]exact cap cexact Problem455Swap.sameBlock_factor ⟨l,k,rfl⟩ capZ(Problem455SameDonor.sameDonor v h y hy capF a b ha hb)cases d with| deficient a =>obtain ⟨⟨_,occ⟩,bad⟩ := obschange z.count a < r at badrcases P455SlotOrigin.supplier_or_boundary v h l k x s a i r hr cap hx hs occ guard withbnd | ⟨y,_,ay,hy,_⟩· have := satZ a x hx bndomega· have := satZ a y hy ayomega| overflow xs =>change Holds r allow mark z (allQ _) at obshave ob := (holds_all _).mp obshave len : xs.length = 5 := ob (.fixed _) (by simp)have sep := (block_separation (s::xs)).mp (ob _ (by simp))obtain ⟨ownerSep,tailSep⟩ := List.pairwise_cons.mp sephave rest : ∀ a ∈ xs, occupies z s i a := byintro a hahave htest : Holds r allow mark z(allQ (xs.map fun a => .both (.count a r) (.slot s i a))) := ob _ (by simp)have hin := (holds_all _).mp htest (.both (.count a r) (.slot s i a)) (List.mem_map.mpr ⟨a,ha,rfl⟩)exact hin.2.2classicalhave supply (a : Nat) (ha : a ∈ xs) :∃ y, occupies v x i y ∧ a ∈ h y ∧ v.count y = r ∧ x ≠ y :=P455SlotOrigin.supplier v h l k x s a i r hr cap hx hs(fun shared => ownerSep a ha (common x s a hx hs shared)) (rest a ha) guardlet assign := fun a => if ha : a ∈ xs then (supply a ha).choose else xhave spec (a : Nat) (ha : a ∈ xs) :occupies v x i (assign a) ∧ a ∈ h (assign a) ∧ v.count (assign a) = r ∧ x ≠ assign a := bysimpa [assign,ha] using (supply a ha).choose_spechave nodup : (xs.map assign).Nodup := byapply List.pairwise_map.mprapply tailSep.imp_of_memintro a b ha hb distinct ehave A := spec a hahave B := spec b hbexact distinct (common (assign a) a b A.2.2.1 A.2.1 (e ▸ B.2.1))refine ⟨assign,len,List.nodup_cons.mpr ⟨?_,nodup⟩,?_⟩· rintro memberobtain ⟨a,ha,e⟩ := List.mem_map.mp memberexact (spec a ha).2.2.2 e.symm· intro a hahave e := spec a haexact ⟨e.1,e.2.1,e.2.2.1⟩end P455TerminalTransferend/- Begin Problem455EffectiveQMove (from finite-semigroup-identity-bases). -/sectionnamespace P455EffectiveQMoveopen P455Closure P455EffectiveQabbrev W := List Natdef capB (r : Nat) (u : W) := u.all fun a => decide (u.count a ≤ r)theorem cap_iff (r : Nat) (u : W) : capB r u=true ↔ Cap r u := bysimp only [capB,List.all_eq_true,decide_eq_true_eq,Cap]constructor· intro h a; by_cases m : a∈u· exact h a m· simp [List.count_eq_zero_of_not_mem m]· exact fun h a _ => h adef validB (r : Nat) (tags : List (List Bool)) (marks : Nat → Nat → Bool) (f : Frame Nat) :=decide (r = 16 + f.tag.length ∧ f.tag∈tags ∧ f.middle.map Prod.snd=fixedPhases f.tag ∧f.p.Nodup ∧ f.q.Nodup ∧ (∀ a∈f.p, a∉f.q) ∧(∀ a∈f.p, ∀ b∈f.q, marks a b=false ∧ marks b a=false) ∧(∀ a∈f.p++f.q,(f.core false).count a=r))theorem valid_iff {tags marks allow mark} (tag_ok : ∀ t, t∈tags ↔ allow t)(mark_ok : ∀ a b,marks a b=true ↔ mark a b)(r : Nat) (f : Frame Nat) : validB r tags marks f=true ↔ f.Valid r allow mark := byhave unmarked (a b) : marks a b=false ↔ ¬mark a b := byrw [←mark_ok]; cases marks a b <;> decidesimp only [validB,decide_eq_true_eq,Frame.Valid,tag_ok,unmarked,List.mem_append]def entries (u : W) := (words u).flatMap (fun g => [(g,false),(g,true)])def frames (tags : List (List Bool)) (u : W) : List (Frame Nat) :=tags.flatMap fun t => u.flatMap fun a => (words u).flatMap fun p =>(words u).flatMap fun q => u.flatMap fun z =>(Problem455Finite.wordsUpTo (entries u) (fixedPhases t).length).flatMap fun es =>(words u).flatMap fun m => (words u).flatMap fun l =>(words u).map fun n => ⟨a,p,q,z,t,es,m,l,n⟩private theorem left {u a b : W} (h : u.Sublist a) : u.Sublist (a++b) :=h.trans (List.sublist_append_left _ _)private theorem right {u a b : W} (h : u.Sublist b) : u.Sublist (a++b) :=h.trans (List.sublist_append_right _ _)theorem frame_mem {tags allow r mark} (tag_ok : ∀ t,t∈tags ↔ allow t)(f : Frame Nat) (b : Bool) (l t : W) (fv : f.Valid r allow mark) :f ∈ frames tags (l++f.core b++t) := bylet u := l++f.core b++thave core : (f.core b).Sublist u := left (right (List.Sublist.refl _))have within (s : W) (hs : s.Sublist (f.core b)) : s.Sublist u := hs.trans corehave early : f.early.Sublist u := within _ (left (left (left (left (left (left (left (.refl _))))))))have pp : f.p.Sublist u :=(show f.p.Sublist f.early from left (left (left (left (left (.refl _)))))).trans earlyhave qq : f.q.Sublist u := (right (.refl _) : f.q.Sublist f.early).trans earlyhave a : f.pHead∈u := pp.subset (by simp [Frame.p])have z : f.qLast∈u := qq.subset (by simp [Frame.q])have pt : f.pTail∈words u := subword ((List.sublist_cons_self ..).trans pp)have qi : f.qInit∈words u := subword ((List.sublist_append_left ..).trans qq)have mid : f.mid.Sublist u := within _ (left (left (left (left (left (left (right (.refl _))))))))have m : f.beforeMutable∈words u := subword (within _ (left (left (left (left (left (right (.refl _))))))))have p : f.beforeFinalP∈words u := subword (within _ (left (left (left (right (.refl _))))))have n : f.beforeFinalQ∈words u := subword (within _ (left (right (.refl _))))have es : f.middle ∈ Problem455Finite.wordsUpTo (entries u) (fixedPhases f.tag).length := byhave sz := congrArg List.length fv.2.2.1apply Problem455Finite.covered _ _ _ (by simpa using Nat.le_of_eq sz)rintro ⟨g,v⟩ memhave item : g.Sublist f.mid := bylet B := fun e : W×Bool => e.1 ++ (if e.2 then f.q else f.p)have item : (B (g,v)).Sublist ((f.middle.map B).flatten) :=List.sublist_flatten_of_mem (List.mem_map_of_mem mem)exact (List.sublist_append_left g _).trans (by simpa [Frame.mid,List.flatMap_def,B] using item)have gg := subword (item.trans mid)apply List.mem_flatMap.mprexact ⟨g,gg,by cases v <;> simp⟩change f ∈ frames tags usimp only [frames,List.mem_flatMap,List.mem_map]exact ⟨f.tag,(tag_ok _).mpr fv.2.1,f.pHead,a,f.pTail,pt,f.qInit,qi,f.qLast,z,f.middle,es,f.beforeMutable,m,f.beforeFinalP,p,f.beforeFinalQ,n,rfl⟩theorem min_length {r allow} {mark : Nat → Nat → Prop} {u v : W} (h : Move r allow mark u v) : r ≤ u.length := byobtain ⟨f,b,l,t,valid,rfl,_,_⟩ := hhave sat := valid.2.2.2.2.2.2.2 f.pHead (.inl (by simp [Frame.p]))have count : (f.core b).count f.pHead=r := bycases b with| false => exact sat| true => exact (f.count_core f.pHead true).trans sathave len := List.count_le_length (a := f.pHead) (l := f.core b)simp only [List.length_append]omegadef moveB (r : Nat) (tags : List (List Bool)) (marks : Nat → Nat → Bool) (u v : W) :=decide (r ≤ u.length) && capB r u && (frames tags u).any fun f => validB r tags marks f && [false,true].any fun b =>(words u).any fun l => (words u).any fun t =>decide (u=l++f.core b++t ∧ v=l++f.core (!b)++t)theorem move_iff {tags marks allow mark} (tag_ok : ∀ t,t∈tags ↔ allow t)(mark_ok : ∀ a b,marks a b=true ↔ mark a b)(r : Nat) (u v : W) : moveB r tags marks u v=true ↔ Move r allow mark u v := bysimp only [moveB,Bool.and_eq_true,List.any_eq_true,decide_eq_true_eq,cap_iff,valid_iff tag_ok mark_ok]constructor· rintro ⟨⟨_,cap⟩,f,_,fv,b,_,l,_,t,_,src,dst⟩; exact ⟨f,b,l,t,fv,src,dst,cap⟩· intro hhave len := min_length hobtain ⟨f,b,l,t,fv,rfl,rfl,cp⟩ := hexact ⟨⟨len,cp⟩,f,frame_mem tag_ok f b l t fv,fv,b,by cases b <;> simp,l,subword (left (left (.refl _))),t,subword (right (.refl _)),rfl,rfl⟩def markedEq {tags : List (List Bool)} {marks : Nat → Nat → Bool}{allow : List Bool → Prop} {mark : Nat → Nat → Prop} (tag_ok : ∀ t,t∈tags ↔ allow t)(mark_ok : ∀ a b,marks a b=true ↔ mark a b) (r : Nat) (T : W) :DecidableEq (P455Quotient.Q (Problem455Finite.rules r allow mark) T) :=P455EffectiveQ.decEq _ (moveB r tags marks) (move_iff tag_ok mark_ok r) Tend P455EffectiveQMoveend/- Begin Problem455RealizerGraph (from finite-semigroup-identity-bases). -/sectionnamespace P455RealizerGraphopen P455EffectiveQvariable {α : Type} [DecidableEq α]def joinAt (k : α) (m : List (α × α)) := m ++ m.flatMap fun p =>if p.2=k then m.filterMap (fun q => if q.1=k then some (p.1,q.2) else none) else []theorem mem_joinAt (k a b : α) (m : List (α × α)) :(a,b)∈joinAt k m ↔ (a,b)∈m ∨ ((a,k)∈m ∧ (k,b)∈m) := bysimp only [joinAt,List.mem_append,List.mem_flatMap]apply or_congr_rightconstructor· rintro ⟨⟨x,y⟩,px,h⟩by_cases eq : y=k· subst yrw [if_pos rfl] at hobtain ⟨⟨z,w⟩,qz,h⟩ := List.mem_filterMap.mp hdsimp only at hsplit at h· rename_i hzkobtain ⟨hxa,hwb⟩ := Prod.mk.inj (Option.some.inj h)subst z; subst x; subst wexact ⟨px,qz⟩· contradiction· simp [eq] at h· rintro ⟨p,q⟩refine ⟨(a,k),p,?_⟩simp [List.mem_filterMap]exact qdef initial (domain : List α) (edge : α → α → Bool) := domain.flatMap fun a =>(domain.filter fun b => decide (a=b) || edge a b).map fun b => (a,b)theorem mem_initial {domain : List α} (edge : α → α → Bool) {a b : α} (ha : a∈domain) (hb : b∈domain) :(a,b)∈initial domain edge ↔ a=b ∨ edge a b=true := bysimp only [initial,List.mem_flatMap,List.mem_map,List.mem_filter,Bool.or_eq_true,decide_eq_true_eq,Prod.mk.injEq]constructor· rintro ⟨x,_,y,⟨_,e⟩,rfl,rfl⟩; exact e· intro h; exact ⟨a,ha,b,⟨hb,h⟩,rfl,rfl⟩theorem mem_fold {domain : List α} (e : α → α → Bool) (pivots : List α)(hp : ∀ x∈pivots,x∈domain) {a b : α} (ha : a∈domain) (hb : b∈domain) :(a,b)∈pivots.foldr joinAt (initial domain e) ↔ P455EffectiveQReach.via e pivots a b=true := byinduction pivots generalizing a b with| nil => simpa [P455EffectiveQReach.via] using mem_initial e ha hb| cons k ks ih =>have mem := hp k List.mem_cons_selfhave rest : ∀ x∈ks,x∈domain := fun x h => hp x (List.mem_cons_of_mem _ h)simp only [List.foldr_cons,mem_joinAt,P455EffectiveQReach.via,Bool.or_eq_true,Bool.and_eq_true,ih rest ha hb,ih rest ha mem,ih rest mem hb]def walk (e : W → W → Bool) (u v : W) :=let pivots := words udecide ((u,v)∈pivots.foldr joinAt (initial (u::v::pivots) e))theorem walk_eq (e : W → W → Bool) (u v : W) : walk e u v=walkB e u v := byapply Bool.eq_iff_iff.mprsimp only [walk,decide_eq_true_eq,walkB]exact mem_fold e _ (fun x h => by simp [h]) (by simp) (by simp)end P455RealizerGraphend/- Begin Problem455PaddedReadback (from finite-semigroup-identity-bases). -/sectionnamespace P455PaddedTilesopen P455Witnessvariable {n w h : Nat} {M : MachineTable n}private theorem clip {v : Nat} (hv : 0<v) (k : Nat) : min k (v-1)<v := byhave := Nat.min_le_right k (v-1)omeganoncomputable def readTile (R : Rectangle M w h) (y x : Nat) : Tile n :=(R.eligible (min y (h-1)) (clip R.positiveH _) (min x (w-1)) (clip R.positiveW _)).choosetheorem read_tile_data (R : Rectangle M w h) (y x : Nat) (hy : y<h) (hx : x<w) :code (readTile R y x)=R.tag y x ∧ Admitted M (readTile R y x) := byhave d := (R.eligible (min y (h-1)) (clip R.positiveH _) (min x (w-1)) (clip R.positiveW _)).choose_specrefine ⟨?_,d.2⟩change code (readTile R y x) = R.tag (min y (h-1)) (min x (w-1)) ∧ _ at dsimpa only [Nat.min_eq_left (by omega : y≤h-1),Nat.min_eq_left (by omega : x≤w-1)] using d.1private theorem read_flags (R : Rectangle M w h) (y x : Nat) (hy : y<h) (hx : x<w) :(readTile R y x).left=decide (x=0) ∧ (readTile R y x).right=decide (x+1=w) ∧(readTile R y x).top=decide (y=0) ∧ (readTile R y x).bottom=decide (y+1=h) := byhave f := R.flags y hy x hxrw [← (read_tile_data R y x hy hx).1] at fexact ⟨f.1,f.2.1,f.2.2.1,f.2.2.2.1⟩theorem read_horizontal (R : Rectangle M w h) (y x : Nat) (hy : y<h) (hx : x+1<w) :Horizontal (readTile R y x) (readTile R y (x+1)) := byobtain ⟨a,b,pa,pb,H⟩ := R.right y hy x hxhave ea := code_inj (pa.trans (read_tile_data R y x hy (by omega)).1.symm)have eb := code_inj (pb.trans (read_tile_data R y (x+1) hy hx).1.symm)simpa only [ea,eb] using Htheorem read_vertical (R : Rectangle M w h) (y x : Nat) (hy : y+1<h) (hx : x<w) :Vertical (readTile R y x) (readTile R (y+1) x) := byobtain ⟨a,b,pa,pb,V⟩ := R.down y hy x hxhave ea := code_inj (pa.trans (read_tile_data R y x (by omega) hx).1.symm)have eb := code_inj (pb.trans (read_tile_data R (y+1) x hy hx).1.symm)simpa only [ea,eb] using Vnoncomputable def centers (R : Rectangle M w h) (y x : Nat) := (readTile R y x).ctheorem read_triple (R : Rectangle M w h) (y x : Nat) (hy : y<h) (hx : x<w) :(readTile R y x).l=leftAt (centers R y) x ∧(readTile R y x).r=rightAt (centers R y) w x := byhave d := (read_tile_data R y x hy hx).2have f := read_flags R y x hy hxconstructor· by_cases e : x=0· have b := d.2.1.symm.trans f.1simp [e] at bsimpa [leftAt,e] using b· have p := (read_horizontal R y (x-1) hy (by omega)).2.2.2.2.2.2.1simpa [leftAt,e,centers,show x-1+1=x by omega] using p· by_cases e : x+1=w· have b := d.2.2.1.symm.trans f.2.1simp [e] at bsimpa [rightAt,e] using b· have p := (read_horizontal R y x hy (by omega)).2.2.2.2.2.2.2simpa [rightAt,e,centers] using p/-- A trace on w cells, ending with the accepting center at its leftmostcell. Stuttering beyond the last row uses the specific machine table. -/structure AcceptingTrace (M : MachineTable n) (w s : Nat) wherepositive : 0<wrows : Nat → Nat → Fin nstart : ∀ x, x<w → rows 0 x = M.initial (decide (x=0))marks : ∀ y, y≤s → ∀ x, x<w → M.marker (rows y x)=decide (x=0)steps : ∀ y, y<s → ∀ x, x<w →M.next (leftAt (rows y) x) (rows y x) (rightAt (rows y) w x)=some (rows (y+1) x)accept : rows s 0=M.acceptnoncomputable def read_trace (R : Rectangle M w h) : AcceptingTrace M w (h-1) wherepositive := R.positiveWrows := centers Rstart := byintro x hxhave d := (read_tile_data R 0 x R.positiveH hx).2have f := read_flags R 0 x R.positiveH hxexact ((d.2.2.2.2.2.1 (by simpa using f.2.2.1)).2).trans (congrArg M.initial f.1)marks := byintro y hy x hxhave lt : y<h := by have := R.positiveH; omegaexact (read_tile_data R y x lt hx).2.2.2.2.1.trans (read_flags R y x lt hx).1steps := byintro y hy x hxhave lt : y<h := by omegahave upd := (read_tile_data R y x lt hx).2.1have triple := read_triple R y x lt hxrw [triple.1,triple.2] at updexact upd.trans (congrArg some (read_vertical R y x (by omega) hx).2.2.2.2.2.2)accept := byhave hy : h-1<h := by have := R.positiveH; omegahave e : h-1+1=h := by have := R.positiveH; omegahave f := read_flags R (h-1) 0 hy R.positiveWexact (read_tile_data R (h-1) 0 hy R.positiveW).2.2.2.2.2.2.2(by simpa [e] using f.2.2.2) (by simpa using f.1)theorem trace_iff_rectangles(stationary : ∀ {w s}, (T : AcceptingTrace M w s) → ∀ x, x<w →M.next (leftAt (T.rows s) x) (T.rows s x) (rightAt (T.rows s) w x)=some (T.rows s x)) :(∃ w s, Nonempty (AcceptingTrace M w s)) ↔(∃ w, ∀ k, ∃ h, 1<h ∧ k<2*(w*h) ∧ Nonempty (Rectangle M w h)) := byconstructor· rintro ⟨w,s,⟨t⟩⟩let r : Run M w s := ⟨t.positive,t.rows,t.start,t.marks,t.steps,t.accept,stationary t⟩exact ⟨w,unbounded r⟩· rintro ⟨w,rects⟩obtain ⟨h,_,_,⟨r⟩⟩ := rects 0exact ⟨w,h-1,⟨read_trace r⟩⟩end P455PaddedTilesend/- Begin Problem455CertificateReach (from finite-semigroup-identity-bases). -/sectionnamespace P455CertificateReachopen P455Witness P455Pathsinductive Active (ts : Tiles) (e : EdgeCertificate) : Node → Prop| anchor : Active ts e e.a| successor : Active ts e e.b| right : ts.right e.a.tag = false → Active ts e e.right| left : ts.left e.a.tag = false → Active ts e e.left| down : ts.bottom e.a.tag = false → Active ts e e.down| up : ts.top e.a.tag = false → Active ts e e.up| diagonal : ts.right e.a.tag = false → ts.bottom e.a.tag = false → Active ts e e.diagonalprivate theorem role_near {r allow mark w n label} (recProof : V r allow mark w (typedNode n))(role : label = n.owner ∨ label = n.mate) : Near r allow mark w n.owner label 1 := byrcases role with h|h· simpa [h] using (near_self (r := r) (allow := allow) (mark := mark) (w := w) n.owner 1)· exact h ▸ (record_pair recProof).1theorem functionality_reach {r allow mark w} (cap : P455Closure.Cap r w)(ts : Tiles) (f : FunctionalityCertificate) (ok : V r allow mark w (f.query ts)){n : Node} {label : Nat} (node : n = f.anchor ∨ n = f.b ∨ n = f.c)(role : label = n.owner ∨ label = n.mate) : Near r allow mark w f.anchor.owner label 2 := byrcases node with h|h|h <;> subst n· exact near_mono (role_near (marked_typed ok.1) role) (by decide)· have port := ok.2.1exact near_trans (neighbor_paths cap f.dir port).1 (role_near (neighbor_target_record port) role)· have port := ok.2.2.1exact near_trans (neighbor_paths cap f.dir port).1 (role_near (neighbor_target_record port) role)private theorem on_guard {r allow mark w b q} (hb : b = false)(h : V r allow mark w (flagQ (!b) q)) : V r allow mark w q := bysimpa [flagQ,hb] using hprivate theorem local_right {r allow mark w ts e} (h : V r allow mark w (localCert ts e))(b : ts.right e.a.tag = false) : V r allow mark w (rightward ts e.a e.right) :=on_guard b h.1private theorem local_left {r allow mark w ts e} (h : V r allow mark w (localCert ts e))(b : ts.left e.a.tag = false) : V r allow mark w (rightward ts e.left e.a) :=on_guard b h.2.1private theorem local_down {r allow mark w ts e} (h : V r allow mark w (localCert ts e))(b : ts.bottom e.a.tag = false) : V r allow mark w (downward ts e.a e.down) :=on_guard b h.2.2.1private theorem local_up {r allow mark w ts e} (h : V r allow mark w (localCert ts e))(b : ts.top e.a.tag = false) : V r allow mark w (downward ts e.up e.a) :=on_guard b h.2.2.2.1private theorem local_square {r allow mark w ts e} (h : V r allow mark w (localCert ts e))(b : ts.right e.a.tag = false) (d : ts.bottom e.a.tag = false) :V r allow mark w (downward ts e.right e.diagonal) ∧V r allow mark w (rightward ts e.down e.diagonal) := byhave sq := h.2.2.2.2.1simpa [flagQ,b,d,V,Holds] using sq/-- Either the selected local neighbor is the second endpoint, or thecertificate contains an actual return port in one of its two orientations. -/theorem successor_joined {r allow mark w} {ts : Tiles} {e : EdgeCertificate} (cap : P455Closure.Cap r w)(ok : V r allow mark w (e.query ts)) : Joined r allow mark w e.a e.b := byhave lc := ok.2.2.1have succ := ok.2.2.2.1unfold chosenSuccessor at succdsimp only at succsplit at succnext ret =>rcases succ.2.1 with f|b· exact port_joined cap 4 (by decide) f· exact (port_joined cap 4 (by decide) b).symmnext noReturn =>have eq := succ.1cases row : endOfRow ts e.a with| true =>have bottom : ts.bottom e.a.tag = false := by simpa [row] using noReturnhave target : e.down = e.b := by simpa [row,P455Witness.Holds] using eqexact target ▸ down_paths cap (local_down lc bottom)| false =>cases odd : ts.oddRow e.a.tag with| true =>have left : ts.left e.a.tag = false := by simpa [endOfRow,odd] using rowhave target : e.left = e.b := by simpa [row,odd,P455Witness.Holds] using eqexact target ▸ (right_paths cap (local_left lc left)).symm| false =>have right : ts.right e.a.tag = false := by simpa [endOfRow,odd] using rowhave target : e.right = e.b := by simpa [row,odd,P455Witness.Holds] using eqexact target ▸ right_paths cap (local_right lc right)theorem active_owner {r allow mark w} (cap : P455Closure.Cap r w)(ts : Tiles) (e : EdgeCertificate) (ok : V r allow mark w (e.query ts)){n : Node} (active : Active ts e n) :Near r allow mark w e.a.owner n.owner 2 ∧ V r allow mark w (typedNode n) := byhave lc := ok.2.2.1cases active with| anchor => exact ⟨near_self _ _,marked_typed ok.1⟩| successor => exact ⟨near_mono (successor_joined cap ok).1 (by decide),marked_typed ok.2.1⟩| right b =>have p := local_right lc bexact ⟨near_mono (right_paths cap p).1 (by decide),neighbor_target_record (d := .right) p⟩| left b =>have p := local_left lc bexact ⟨near_mono (right_paths cap p).2 (by decide),neighbor_target_record (d := .left) p⟩| down b =>have p := local_down lc bexact ⟨near_mono (down_paths cap p).1 (by decide),neighbor_target_record (d := .down) p⟩| up b =>have p := local_up lc bexact ⟨near_mono (down_paths cap p).2 (by decide),neighbor_target_record (d := .up) p⟩| diagonal rr dd =>have p := local_right lc rrhave q := (local_square lc rr dd).1exact ⟨near_trans (right_paths cap p).1 (down_paths cap q).1,neighbor_target_record (d := .down) q⟩/-- For either endpoint owner, every role genuinely used in the specifiededge certificate is within four actual record/port contacts. -/theorem edge_reach {r allow mark w} (cap : P455Closure.Cap r w)(ts : Tiles) (e : EdgeCertificate) (ok : V r allow mark w (e.query ts)){n : Node} {label : Nat} (active : Active ts e n) (role : label = n.owner ∨ label = n.mate) :Near r allow mark w e.a.owner label 4 ∧ Near r allow mark w e.b.owner label 4 := byobtain ⟨reach,recProof⟩ := active_owner cap ts e ok activehave first := near_trans reach (role_near recProof role)exact ⟨near_mono first (by decide),near_trans (successor_joined cap ok).2 first⟩end P455CertificateReachend/- Begin Problem455ContactLift (from finite-semigroup-identity-bases). -/sectionnamespace P455ContactLiftopen Problem455.Slots P455Witness P455Pathsdef Supplies (v : W) (h : Nat → W) (r x s : Nat) := v.count x = r ∧ s ∈ h xnoncomputable def donor (v : W) (h : Nat → W) (r s : Nat) : Nat := byclassicalexact if hs : ∃ x, Supplies v h r x s then hs.choose else 0theorem factor_cap {v l k : W} {h : Nat → W} {r : Nat}(cap : P455Closure.Cap r (l ++ v.flatMap h ++ k)) : P455Closure.Cap r (v.flatMap h) := byintro s; have hs := cap s; simp only [List.count_append] at hs; omegatheorem donor_eq {v h r x s} (hr : 0 < r) (cap : P455Closure.Cap r (v.flatMap h))(supply : Supplies v h r x s) : donor v h r s = x := byclassicalhave existsDonor : ∃ y, Supplies v h r y s := ⟨x,supply⟩have other := existsDonor.choose_spechave used : existsDonor.choose ∈ v := List.count_pos_iff.mp (other.1.symm ▸ hr)have exc := (P455DonorInterval.exclusive h v x s r hr supply.1 supply.2 (cap s)).2.1unfold donor; rw [dif_pos existsDonor]exact Classical.byContradiction (fun ne => exc _ used ne other.2)def Guard (r : Nat) (allow : Tag → Prop) (mark : Marking) (v : W) (seed J : Nat) : Prop :=∀ x, Near r allow mark v seed x J → ∀ i, slotStart i →∀ y, occupies v x i y → v.count y = rtheorem guard_uniform {r allow mark v seed J} (uniform : ∀ x ∈ v, v.count x = r) :Guard r allow mark v seed J := byintro _ _ _ _ y hyobtain ⟨j,sub⟩ := hyhave hm : (y,j) ∈ events v := sub.subset (by simp)exact uniform y (stamped_mem_label _ _ _ hm)theorem contact_step {r allow mark v h l k x s t} (hr : 0 < r)(cap : P455Closure.Cap r (l ++ v.flatMap h ++ k)) (sup : Supplies v h r x s)(guard : ∀ i, slotStart i → ∀ y, occupies v x i y → v.count y = r)(c : ContactChoice) (hc : Holds r allow mark (l ++ v.flatMap h ++ k) (contact r s t c)) :let y := donor v h r tSupplies v h r y t ∧ x ≠ y ∧ Holds r allow mark v (contact r x y c) := byobtain ⟨i,slot,occ⟩ := P455ContactGeometry.contact_slot hchave ext := P455ContactGeometry.contact_excludes_image hr cap sup.1 sup.2 hcobtain ⟨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)have g : Supplies v h r y t := ⟨hy,ht⟩have refl := P455ContactReflection.reflect_contact hr cap sup.1 hy ne sup.2 ht c hcsimpa only [donor_eq hr (factor_cap cap) g] using And.intro g (And.intro ne refl)def relabel (d : Nat → Nat) (p : List Step) := p.map fun bc => (d bc.1,bc.2)theorem endpoint_relabel (d : Nat → Nat) (s : Nat) (p : List Step) :endpoint (d s) (relabel d p) = d (endpoint s p) := byinduction p generalizing s with| nil => rfl| cons head p ih => exact ih head.1/-- Each step comes from the concrete record/port test in the enclosing word.Induction keeps the length of the source prefix to which the guard applies. -/theorem transfer_from {r allow mark v h l k seed J} (hr : 0 < r)(cap : P455Closure.Cap r (l ++ v.flatMap h ++ k)) (guard : Guard r allow mark v seed J)(s : Nat) (p : List Step) (n : Nat) (sup : Supplies v h r (donor v h r s) s)(near : Near r allow mark v seed (donor v h r s) n) (bound : n+p.length ≤ J)(walk : Walk r allow mark (l ++ v.flatMap h ++ k) s p) :Walk r allow mark v (donor v h r s) (relabel (donor v h r) p) ∧Supplies v h r (donor v h r (endpoint s p)) (endpoint s p) := byinduction p generalizing n s with| nil => exact ⟨True.intro,sup⟩| cons bc rest ih =>obtain ⟨b,c⟩ := bchave len : n+1+rest.length ≤ J := by simpa [Nat.add_assoc,Nat.add_comm 1 rest.length] using boundhave g := guard _ (near_mono near (by omega))obtain ⟨next,_,edge⟩ := contact_step hr cap sup g c walk.1have more := near_trans near (near_one c edge)obtain ⟨tail,last⟩ := ih b (n+1) next more len walk.2exact ⟨⟨edge,tail⟩,last⟩theorem lift_walk {r allow mark v h l k s seed J} (hr : 0 < r)(cap : P455Closure.Cap r (l ++ v.flatMap h ++ k)) (start : Supplies v h r seed s)(guard : Guard r allow mark v seed J) (p : List Step) (bound : p.length ≤ J)(walk : Walk r allow mark (l ++ v.flatMap h ++ k) s p) :Walk r allow mark v seed (relabel (donor v h r) p) ∧Supplies v h r (donor v h r (endpoint s p)) (endpoint s p) := byhave eq := donor_eq hr (factor_cap cap) startsimpa only [eq] using transfer_from hr cap guard s p 0 (eq.symm ▸ start)(eq.symm ▸ near_self seed 0) (by simpa using bound) walktheorem lift_near {r allow mark v h l k s seed J a n} (hr : 0 < r)(cap : P455Closure.Cap r (l ++ v.flatMap h ++ k)) (start : Supplies v h r seed s)(guard : Guard r allow mark v seed J) (bound : n ≤ J)(near : Near r allow mark (l ++ v.flatMap h ++ k) s a n) :Supplies v h r (donor v h r a) a ∧ Near r allow mark v seed (donor v h r a) n := byobtain ⟨p,w,ep,len⟩ := nearobtain ⟨sw,sup⟩ := lift_walk hr cap start guard p (Nat.le_trans len bound) wrw [ep] at suprefine ⟨sup,relabel (donor v h r) p,sw,?_,by simpa [relabel] using len⟩have eq := donor_eq hr (factor_cap cap) startrw [← eq,endpoint_relabel,ep]end P455ContactLiftend/- Begin Problem455PortReflection (from finite-semigroup-identity-bases). -/sectionnamespace P455PortReflectionopen Problem455.Slots P455Witness P455ContactReflection P455ContactGeometrydef roles (a : Node) : W := [a.owner,a.mate]def sendNode (d : Nat → Nat) (a : Node) : Node := ⟨d a.owner,d a.mate,a.tag⟩def UniformOn (r : Nat) (v : W) (h : Nat → W) (d : Nat → Nat) (xs : W) :=∀ a ∈ xs, v.count (d a) = r ∧ a ∈ h (d a)theorem holds_all {r allow mark w} (xs : List Query) :Holds r allow mark w (allQ xs) ↔ ∀ q ∈ xs, Holds r allow mark w q := byinduction xs with| nil => simp [allQ,Holds]| cons q qs ih => simp only [allQ,Holds,ih,List.forall_mem_cons]theorem earlyBefore_iff {r allow mark w} (xs ys : W) :Holds r allow mark w (earlyBefore xs ys) ↔∀ a ∈ xs, ∀ b ∈ ys, Holds r allow mark w (earlier a 2 b 0) := bysimp only [earlyBefore,holds_all,List.mem_flatMap,List.mem_map]constructor· intro h a ha b hbexact h _ ⟨a,ha,b,hb,rfl⟩· rintro h _ ⟨a,ha,b,hb,rfl⟩exact h a ha b hbsection Uniformvariable {r : Nat} {v l k : W} {h : Nat → W} {d : Nat → Nat}{allow : Tag → Prop} {mark : Marking}theorem record_roles_distinct (hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k))(a : Node) (uniform : UniformOn r v h d (roles a))(recProof : Holds r allow mark (l ++ v.flatMap h ++ k) (typedNode a)) :d a.owner ≠ d a.mate := byintro eqobtain ⟨hx,hs⟩ := uniform a.owner (by simp [roles])obtain ⟨_,ht⟩ := uniform a.mate (by simp [roles])have nc := contact_excludes_image hr cap hx hs(c := .record a.tag false) (b := a.mate) recProofexact nc (eq ▸ ht)theorem reflect_typedNode (hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k))(a : Node) (uniform : UniformOn r v h d (roles a))(recProof : Holds r allow mark (l ++ v.flatMap h ++ k) (typedNode a)) :Holds r allow mark v (typedNode (sendNode d a)) := byobtain ⟨hx,hs⟩ := uniform a.owner (by simp [roles])obtain ⟨hy,ht⟩ := uniform a.mate (by simp [roles])exact reflect_contact hr cap hx hy (record_roles_distinct hr cap a uniform recProof)hs ht (.record a.tag false) recProoftheorem reflect_markedNode (hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k))(a : Node) (bit : Bool) (uniform : UniformOn r v h d (roles a)) (sourceMark : Marking)(marked : sourceMark (d a.owner) (d a.mate) ∨ sourceMark (d a.mate) (d a.owner))(recProof : Holds r allow mark (l ++ v.flatMap h ++ k) (markedNode a bit)) :Holds r allow sourceMark v (markedNode (sendNode d a) bit) := byobtain ⟨ne,len,code,_,eq⟩ := recProofhave rec' : Holds r allow mark (l ++ v.flatMap h ++ k) (typedNode a) :=⟨ne,len,code,bit,eq⟩obtain ⟨hx,hs⟩ := uniform a.owner (by simp [roles])obtain ⟨hy,ht⟩ := uniform a.mate (by simp [roles])have diff := record_roles_distinct hr cap a uniform rec'exact ⟨diff,len,code,marked,reflect_profile hr cap hx hy diff hs ht a.tag bit eq⟩theorem port_injective (hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k))(a b : Node) (phase : Nat) (uniform : UniformOn r v h d (roles a ++ roles b))(port : Holds r allow mark (l ++ v.flatMap h ++ k) (orientedPort phase a b)) :∀ s ∈ roles a ++ roles b, ∀ t ∈ roles a ++ roles b, d s = d t → s = t := byhave each (n : Node) (uni : UniformOn r v h d (roles n))(recProof : Holds r allow mark (l ++ v.flatMap h ++ k) (typedNode n)) :∀ z ∈ roles n, ∀ t ∈ roles n, d z = d t → z = t := byhave distinct := record_roles_distinct hr cap n uni recProofintro z hz t ht eqsimp [roles] at hz htrcases hz with rfl | rfl <;> rcases ht with rfl | rfl <;> simp_allhave ua : UniformOn r v h d (roles a) := fun x hx => uniform x (by simp [hx])have ub : UniformOn r v h d (roles b) := fun x hx => uniform x (by simp [hx])have cross (s) (hs : s ∈ roles a) (t) (ht : t ∈ roles b) : d s ≠ d t := byintro eqobtain ⟨hx,sa⟩ := ua s hsobtain ⟨_,tb⟩ := ub t htrw [← eq] at tbhave early : Holds r allow mark (l ++ v.flatMap h ++ k) (earlyDisjoint (roles a) (roles b)) :=port.2.2.1rcases early with e | e· exact same_image_no_early hr cap hx sa tb (by decide : 0 < 2)(((earlyBefore_iff _ _).mp e s hs t ht).2)· exact same_image_no_early hr cap hx tb sa (by decide : 0 < 2)(((earlyBefore_iff _ _).mp e t ht s hs).2)intro s hs t ht eqrcases List.mem_append.mp hs with hs | hs <;> rcases List.mem_append.mp ht with ht | ht· exact each a ua port.1 s hs t ht eq· exact (cross s hs t ht eq).elim· exact (cross t ht s hs eq.symm).elim· exact each b ub port.2.1 s hs t ht eqtheorem port_owner_order (hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k))(a b : Node) (phase : Nat) (uniform : UniformOn r v h d (roles a ++ roles b))(port : Holds r allow mark (l ++ v.flatMap h ++ k) (orientedPort phase a b))(pat : List Event) (inside : ∀ e ∈ pat, e.1 ∈ roles a ++ roles b)(order : Holds r allow mark (l ++ v.flatMap h ++ k) (.order pat)) :Holds r allow mark v (.order (pat.map (eventMap d))) :=reflect_order_query hr cap _ d uniform (port_injective hr cap a b phase uniform port)pat inside ordertheorem reflect_port (hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k))(a b : Node) (phase : Nat) (uniform : UniformOn r v h d (roles a ++ roles b))(port : Holds r allow mark (l ++ v.flatMap h ++ k) (orientedPort phase a b)) :Holds r allow mark v (orientedPort phase (sendNode d a) (sendNode d b)) := byhave ua : UniformOn r v h d (roles a) := fun x hx => uniform x (by simp [hx])have ub : UniformOn r v h d (roles b) := fun x hx => uniform x (by simp [hx])have transfer := port_owner_order hr cap a b phase uniform porthave early (xs ys : W) (within : ∀ z ∈ xs ++ ys, z ∈ roles a ++ roles b)(order : Holds r allow mark (l ++ v.flatMap h ++ k) (earlyBefore xs ys)) :Holds r allow mark v (earlyBefore (xs.map d) (ys.map d)) := byapply (earlyBefore_iff _ _).mprintro u hu v' hvobtain ⟨i,hi,rfl⟩ := List.mem_map.mp huobtain ⟨j,hj,rfl⟩ := List.mem_map.mp hvhave pat := transfer [(i,2),(j,0)] (byintro e hesimp only [List.mem_cons,List.not_mem_nil,or_false] at hercases he with rfl | rfl· exact within i (by simp [hi])· exact within j (by simp [hj]))((earlyBefore_iff _ _).mp order i hi j hj)simpa [eventMap,earlier] using patrefine ⟨reflect_typedNode hr cap a ua port.1,reflect_typedNode hr cap b ub port.2.1,?_,?_,True.intro⟩· rcases port.2.2.1 with e | e· exact Or.inl (early (roles a) (roles b) (fun _ hz => hz) e)· exact Or.inr (early (roles b) (roles a) (fun z hz => by simpa [or_comm] using hz) e)· let i := 3+2*phasehave pat := transfer [(a.owner,i),(a.mate,i),(b.owner,i),(b.mate,i),(a.owner,i+1),(a.mate,i+1),(b.owner,i+1),(b.mate,i+1)] (by simp [roles]) port.2.2.2.1simpa [eventMap, sendNode, i] using pattheorem reflect_rightward (hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k))(ts : Tiles) (a b : Node) (uniform : UniformOn r v h d (roles a ++ roles b))(dir : Holds r allow mark (l ++ v.flatMap h ++ k) (rightward ts a b)) :Holds r allow mark v (rightward ts (sendNode d a) (sendNode d b)) := byhave order := port_owner_order hr cap a b _ uniform dir.2.1[(a.owner,13+a.tag.length),(b.owner,13+a.tag.length)] (by simp [roles]) dir.2.2.1exact ⟨dir.1,reflect_port hr cap a b _ uniform dir.2.1,by simpa [sendNode,eventMap,earlier] using order,True.intro⟩theorem reflect_downward (hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k))(ts : Tiles) (a b : Node) (uniform : UniformOn r v h d (roles a ++ roles b))(dir : Holds r allow mark (l ++ v.flatMap h ++ k) (downward ts a b)) :Holds r allow mark v (downward ts (sendNode d a) (sendNode d b)) :=⟨dir.1,reflect_port hr cap a b _ uniform dir.2⟩theorem reflect_neighbor (hr : 0 < r) (cap : P455Closure.Cap r (l ++ v.flatMap h ++ k))(ts : Tiles) (a b : Node) (dir : Dir) (uniform : UniformOn r v h d (roles a ++ roles b))(port : Holds r allow mark (l ++ v.flatMap h ++ k) (neighbor ts a b dir)) :Holds r allow mark v (neighbor ts (sendNode d a) (sendNode d b) dir) := byhave rev : UniformOn r v h d (roles b ++ roles a) := fun x hx =>uniform x (by simpa [or_comm] using hx)cases dir· exact reflect_rightward hr cap ts a b uniform port· exact reflect_rightward hr cap ts b a rev port· exact reflect_downward hr cap ts a b uniform port· exact reflect_downward hr cap ts b a rev portend Uniform/-- Structural independence of the ambient marking. Only a designatedmarked-bit query reads it. The record and ordering parts of a portcan therefore be used with any source marking. -/def markFree : Query → Bool| .markedBit .. => false| .both x y | .either x y => markFree x && markFree y| _ => truetheorem remark {r w allow} {src dst : Marking} {q : Query} (free : markFree q = true)(holds : Holds r allow src w q) : Holds r allow dst w q := byinduction q with| fixed | count | deficient | record | order | slot | separate => exact holds| markedBit => cases free| both x y hx hy =>have both := Bool.and_eq_true_iff.mp freeexact ⟨hx both.1 holds.1, hy both.2 holds.2⟩| either x y hx hy =>have both := Bool.and_eq_true_iff.mp freeexact holds.elim (fun a => Or.inl (hx both.1 a)) (fun b => Or.inr (hy both.2 b))theorem free_port (i : Nat) (a b : Node) : markFree (orientedPort i a b) = true := rfltheorem free_neighbor (ts : Tiles) (a b : Node) (dir : Dir) :markFree (neighbor ts a b dir) = true := by cases dir <;> rfltheorem port_remark {r w allow} {src dst : Marking} {i a b}(holds : Holds r allow src w (orientedPort i a b)) : Holds r allow dst w (orientedPort i a b) :=remark (free_port i a b) holdstheorem neighbor_remark {r w allow} {src dst : Marking} {ts a b dir}(holds : Holds r allow src w (neighbor ts a b dir)) : Holds r allow dst w (neighbor ts a b dir) :=remark (free_neighbor ts a b dir) holdsend P455PortReflectionend/- Begin Problem455RealizerPrim (from finite-semigroup-identity-bases). -/section/- Encoded first-order subroutines for the #455 computation. -/namespace P455GraphPrimopen P455EffectiveQ P455RealizerGraphvariable {A B C : Type} [Primcodable A] [Primcodable B] [Primcodable C]theorem filter {l : A → List B} {p : A → B → Bool}(hl : Primrec l) (hp : Primrec₂ p) : Primrec fun a => (l a).filter (p a) := byhave k : Primrec₂ (fun a (x : B) => if p a x then some x else none) :=(Primrec.ite (show PrimrecPred (fun z : A×B => p z.1 z.2=true) bysimpa [PrimrecPred, Primrec₂] using hp) (Primrec.option_some.comp Primrec.snd) (.const none)).to₂apply (Primrec.listFilterMap hl k).of_eqintro ainduction l a with| nil => rfl| cons b bs ih => cases h : p a b <;> simp [h,ih]theorem join [DecidableEq B] : Primrec₂ (@joinAt B _) := byapply Primrec₂.mkapply Primrec.list_append.comp Primrec.sndapply Primrec.list_flatMap Primrec.sndapply Primrec₂.mkapply Primrec.ite (Primrec.eq.comp (Primrec.snd.comp Primrec.snd) (Primrec.fst.comp Primrec.fst))· apply Primrec.listFilterMap (Primrec.snd.comp Primrec.fst)apply Primrec₂.mkapply Primrec.ite (Primrec.eq.comp (Primrec.fst.comp Primrec.snd) (Primrec.fst.comp (Primrec.fst.comp Primrec.fst)))· exact Primrec.option_some.comp (Primrec.pair (Primrec.fst.comp (Primrec.snd.comp Primrec.fst))(Primrec.snd.comp Primrec.snd))· exact .const none· exact .const []theorem graphFold [DecidableEq B] {p : A → List B} {s : A → List (B×B)}(hp : Primrec p) (hs : Primrec s) : Primrec fun a => (p a).foldr joinAt (s a) := byexact Primrec.list_foldr (h := fun _ (ks : B × List (B×B)) => joinAt ks.1 ks.2) hp hs(((join.comp Primrec.fst Primrec.snd).comp Primrec.snd).to₂)theorem wordsUpTo : Primrec₂ (@Problem455Finite.wordsUpTo B) := bylet step (l : List B) (x : Nat × List (List B)) :=[] :: l.flatMap (fun a => x.2.map (List.cons a))have steprec : Primrec₂ step := byapply Primrec₂.mkapply Primrec.list_cons.comp (.const [])apply Primrec.list_flatMap Primrec.fstapply Primrec₂.mkapply Primrec.list_map (Primrec.snd.comp (Primrec.snd.comp Primrec.fst))exact (Primrec.list_cons.comp (Primrec.snd.comp Primrec.fst) Primrec.snd).to₂apply (Primrec.nat_rec (Primrec.const [[]]) steprec).of_eqintro l ninduction n with| zero => rfl| succ n ih => simp [Problem455Finite.wordsUpTo,step,ih]theorem wordPool : Primrec words := (wordsUpTo.comp Primrec.id Primrec.list_length)theorem initialized [DecidableEq B] {e : A → B → B → Bool}(he : Primrec (fun x : A×(B×B) => e x.1 x.2.1 x.2.2)){d : A → List B} (hd : Primrec d) :Primrec fun a => initial (d a) (e a) := byapply Primrec.list_flatMap hdapply Primrec₂.mkapply Primrec.list_map· apply filter (hd.comp Primrec.fst)apply Primrec₂.mkapply Primrec.or.comp· have same : PrimrecPred (fun z : (A × B) × B => z.1.2 = z.2) :=(Primrec.eq (α := B)).comp (Primrec.snd.comp Primrec.fst) Primrec.sndclassicalexact same.decide· exact he.comp (Primrec.pair (Primrec.fst.comp Primrec.fst)(Primrec.pair (Primrec.snd.comp Primrec.fst) Primrec.snd))· exact (Primrec.pair (Primrec.snd.comp Primrec.fst) Primrec.snd).to₂theorem contains [DecidableEq B] {v : A → B} {xs : A → List B}(hv : Primrec v) (hx : Primrec xs) : Primrec fun a => decide (v a∈xs a) := byapply ((Primrec.nat_lt.comp (Primrec.list_idxOf.comp hv hx) (Primrec.list_length.comp hx)).decide).of_eqintro a; simp [List.idxOf_lt_length_iff]theorem reachable {e : A → W → W → Bool} (he : Primrec (fun x : A×(W×W) => e x.1 x.2.1 x.2.2)){u v : A → W} (hu : Primrec u) (hv : Primrec v) :Primrec fun a => walkB (e a) (u a) (v a) := byhave piv := wordPool.comp huhave dom := Primrec.list_cons.comp hu (Primrec.list_cons.comp hv piv)exact (contains (hu.pair hv) (graphFold piv (initialized he dom))).of_eq (fun a => byrw [←walk_eq (e a) (u a) (v a)]apply Bool.eq_iff_iff.mprsimp only [walk,decide_eq_true_eq])theorem anyB {l : A → List B} {p : A → B → Bool} (hl : Primrec l) (hp : Primrec₂ p) :Primrec fun a => (l a).any (p a) := byapply (Primrec.list_foldr hl (Primrec.const false)(Primrec.or.comp (hp.comp Primrec.fst (Primrec.fst.comp Primrec.snd))(Primrec.snd.comp Primrec.snd)).to₂).of_eqintro ainduction l a with| nil => rfl| cons b bs ih => simp [ih]theorem factor {u v : A → W} (hu : Primrec u) (hv : Primrec v) : Primrec fun a => factorB (u a) (v a) := byapply anyB (wordPool.comp hv)apply Primrec₂.mkapply anyB (wordPool.comp (hv.comp Primrec.fst))apply Primrec₂.mkexact (Primrec.eq.comp (hv.comp (Primrec.fst.comp Primrec.fst))(Primrec.list_append.comp (Primrec.list_append.comp (Primrec.snd.comp Primrec.fst)(hu.comp (Primrec.fst.comp Primrec.fst))) Primrec.snd)).decidetheorem good {e : A → W → W → Bool} (he : Primrec (fun x : A×(W×W) => e x.1 x.2.1 x.2.2)){t u : A → W} (ht : Primrec t) (hu : Primrec u) :Primrec fun a => goodB (e a) (t a) (u a) := byapply anyB (wordPool.comp ht)apply Primrec₂.mkexact Primrec.and.comp(reachable (A := A × W) (e := fun p => e p.1) (he.comp (Primrec.pair (Primrec.fst.comp Primrec.fst) Primrec.snd))(ht.comp Primrec.fst) Primrec.snd)(factor (hu.comp Primrec.fst) Primrec.snd)end P455GraphPrimend/- Begin Problem455MachineTable (from finite-semigroup-identity-bases). -/sectionnamespace P455MachineTableopen P455MachineLocal P455PaddedTilesstructure TM (g q : Nat) wheremarker : Fin gblank : Fin gblank_ne : blank≠markerstart : Fin qaccept : Fin qdistinct : start≠acceptdelta : Fin q→Fin g→Ins (Fin g) (Fin q)keeps : ∀ z a,(delta z a).symbol=marker ↔ a=markerleftSafe : ∀ z,(delta z marker).dir≠.leftstationary : delta accept marker=⟨accept,marker,.stay⟩abbrev C (g q : Nat) := Cell (Fin g) (Fin q)def headIndex (p : Option (Fin q)) : Nat := match p with | none => 0 | some x => x.val+1def enc (c : C g q) : Fin (g*(q+1)) :=⟨g*headIndex c.head+c.sym.val,byhave v := c.sym.isLthave z : headIndex c.head ≤ q := by cases hh : c.head with| none => simp [headIndex]| some s => simp [headIndex]; have := s.isLt; omegahave m := Nat.mul_le_mul_left g zrw [Nat.mul_add,Nat.mul_one]; omega⟩def dec (M : TM g q) (x : Fin (g*(q+1))) : C g q :=let h := x.val/glet symbol := x.val%glet head := if e : 0<h then some (⟨h-1,byhave gr := M.marker.isLthave pos : 0<g := by omegahave div := (Nat.div_lt_iff_lt_mul pos).mpr (calc x.val < g*(q+1) := x.isLt_ = _ := Nat.mul_comm ..)dsimp [h] at *; omega⟩ : Fin q) else none⟨⟨symbol,Nat.mod_lt _ (by have := M.marker.isLt; omega)⟩,head⟩theorem dec_enc (M : TM g q) (c : C g q) : dec M (enc c)=c := byobtain ⟨s,h⟩ := chave gpos : 0<g := by have := s.isLt; omegacases h with| none => simp [dec,enc,headIndex,Nat.div_eq_of_lt s.isLt,Nat.mod_eq_of_lt s.isLt]| some p =>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]theorem enc_inj (M : TM g q) {a b : C g q} (e : enc a=enc b) : a=b := bysimpa [dec_enc] using congrArg (dec M) edef compile (M : TM g q) : MachineTable (g*(q+1)) wheremarker := fun v=>decide ((dec M v).sym=M.marker)initial := fun left=>if left then enc ⟨M.marker,some M.start⟩ else enc ⟨M.blank,none⟩accept := enc ⟨M.marker,some M.accept⟩distinct := byintro eqhave h := congrArg Cell.head (enc_inj M eq)exact M.distinct (Option.some.inj h)next := fun l c r => (update M.delta (l.map (dec M)) (dec M c) (r.map (dec M))).map encstructure Config (g q : Nat) wheretape : Nat→Fin gpos : Natstate : Fin qdef init (M : TM g q) : Config g q := ⟨(fun i=>if i=0 then M.marker else M.blank),0,M.start⟩def step (M : TM g q) (c : Config g q) : Config g q :=let ins := M.delta c.state (c.tape c.pos)⟨writeAt c.tape c.pos ins.symbol,dest ins.dir c.pos,ins.state⟩def run (M : TM g q) : Nat→Config g q| 0 => init M| t+1 => step M (run M t)def row (M : TM g q) (t x : Nat) := enc (atCell (run M t).tape (run M t).pos (run M t).state x)theorem marker_iff (M : TM g q) (t x : Nat) : (run M t).tape x=M.marker ↔ x=0 := byinduction t with| zero => by_cases e : x=0 <;> simp [run,init,e,M.blank_ne]| succ t ih =>change writeAt _ _ _ x=M.marker ↔ x=0by_cases e : x=(run M t).pos· rw [writeAt,if_pos e,M.keeps,←e]; exact ih· simpa [writeAt,e] using ihtheorem head_bound (M : TM g q) (t : Nat) : (run M t).pos ≤ t := byinduction t with| zero => exact Nat.le_refl _| succ t ih =>change dest (_ : Ins (Fin g) (Fin q)).dir (run M t).pos≤t+1cases d : (M.delta (run M t).state ((run M t).tape (run M t).pos)).dir <;>simp [dest] <;> omegatheorem physical_safe {t w : Nat} (M : TM g q) (wide : t+1<w) :¬ exits (M.delta (run M t).state ((run M t).tape (run M t).pos)).dir w (run M t).pos := byintro badrcases bad with ⟨left,at0⟩|⟨_,edge⟩· rw [at0,(marker_iff M t 0).mpr rfl] at leftexact M.leftSafe _ left· have := head_bound M t; omegatheorem left_dec (M : TM g q) (t x : Nat) :(leftAt (row M t) x).map (dec M)=leftOf (atCell (run M t).tape (run M t).pos (run M t).state) x := byby_cases e : x=0 <;> simp [leftAt,leftOf,e,row,dec_enc]theorem right_dec (M : TM g q) (t x w : Nat) :(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 := byby_cases e : x+1=w <;> simp [rightAt,rightOf,e,row,dec_enc]theorem local_value (M : TM g q) (t w x : Nat) (head : (run M t).pos<w)(safe : ¬exits (M.delta (run M t).state ((run M t).tape (run M t).pos)).dir w (run M t).pos)(hx : x<w) :(compile M).next (leftAt (row M t) x) (row M t x) (rightAt (row M t) w x)=some (row M (t+1) x) := bychange (update M.delta _ (dec M (enc _)) _).map enc=_rw [left_dec,right_dec,dec_enc,local_step _ _ _ _ _ head safe _ hx]rflend P455MachineTableend/- Begin Problem455Retained (from finite-semigroup-identity-bases). -/sectionnamespace P455Retainedopen Problem455.Slots P455Witness P455Paths P455ContactLiftstructure Expansion (v : W) (e : Nat → W) (kept : Nat → Prop) : Prop whereliteral : ∀ x ∈ v, kept x → e x = [x]gaps : ∀ g ∈ v, ¬ kept g → v.count g = 1 ∧ e g ≠ [] ∧ ∀ a ∈ e g, ¬ kept a/-- Projecting onto any chosen retained labels commutes with expansion. -/theorem Expansion.select_eq {v e kept} (exp : Expansion v e kept)(s keep : W) (sub : ∀ a ∈ s, a ∈ v) (hk : ∀ a ∈ keep, kept a) :select keep (s.flatMap e) = select keep s := byinduction s with| nil => rfl| cons x xs ih =>have hx := sub x (by simp)have rs := ih (fun a ha => sub a (by simp [ha]))change select keep (e x ++ xs.flatMap e) = select keep ([x] ++ xs)rw [select_append,select_append,rs]by_cases keep_x : kept x· rw [exp.literal x hx keep_x]· have gap := exp.gaps x hx keep_xrw [select_nil keep (e x) (fun a ha ab => gap.2.2 a ha (hk a ab))]have no : x ∉ keep := fun h => keep_x (hk x h)simp [select,no]theorem Expansion.count_eq {v e kept} (exp : Expansion v e kept)(s : W) (sub : ∀ a ∈ s, a ∈ v) (x : Nat) (hx : kept x) :(s.flatMap e).count x = s.count x := byhave h := congrArg (List.count x) (exp.select_eq s [x] sub (by simpa using hx))simpa [select] using htheorem Expansion.small_cap {v e kept r} (exp : Expansion v e kept) (hr : 1 < r)(cap : P455Closure.Cap r (v.flatMap e)) : P455Closure.Cap r v := byintro xby_cases use : x ∈ v· by_cases k : kept x· rw [← exp.count_eq v (fun _ h => h) x k]; exact cap x· rw [(exp.gaps x use k).1]; omega· rw [List.count_eq_zero.mpr use]; omegatheorem contact_counts {r allow mark v x y c} (cap : P455Closure.Cap r v)(h : Holds r allow mark v (contact r x y c)) : v.count x = r ∧ v.count y = r := bycases c with| record tag rev =>cases rev· exact record_counts cap h· exact (record_counts cap h).symm| port phase rev => exact ⟨h.2.1,h.2.2.1⟩theorem Expansion.contact {v e kept r allow mark x y} (exp : Expansion v e kept) (hr : 1 < r)(cap : P455Closure.Cap r (v.flatMap e)) (c : ContactChoice)(edge : Holds r allow mark v (P455Witness.contact r x y c)) :Holds r allow mark (v.flatMap e) (P455Witness.contact r x y c) := byobtain ⟨xc,yc⟩ := contact_counts (exp.small_cap hr cap) edgehave used (a) (count : v.count a = r) : kept a := byapply Classical.byContradictionintro khave hm : a ∈ v := List.count_pos_iff.mp (by omega)have := (exp.gaps a hm k).1; omegahave xx := used x xchave yy := used y ychave eq (a b) (ha : kept a) (hb : kept b) : select [a,b] (v.flatMap e) = select [a,b] v :=exp.select_eq v [a,b] (fun _ h => h) (by simpa using And.intro ha hb)have ord (pat : List Event) (inside : ∀ a ∈ pat, a.1 ∈ [x,y])(old : Holds r allow mark v (.order pat)) : Holds r allow mark (v.flatMap e) (.order pat) := byrefine ⟨old.1, P455ContactReflection.select_sees [x,y] _ pat ?_⟩rw [eq x y xx yy]exact P455ContactReflection.sees_select _ _ _ inside old.2cases c with| record tag rev =>cases rev with| false =>obtain ⟨ne,len,tag,bit,hp⟩ := edgeexact ⟨ne,len,tag,bit,(eq x y xx yy).trans hp⟩| true =>obtain ⟨ne,len,tag,bit,hp⟩ := edgeexact ⟨ne,len,tag,bit,(eq y x yy xx).trans hp⟩| port port rev =>obtain ⟨ne,_,_,early,order,_⟩ := edgerefine ⟨ne,(exp.count_eq _ (fun _ h => h) x xx).trans xc,(exp.count_eq _ (fun _ h => h) y yy).trans yc,?_,?_,True.intro⟩· rcases early with l|rr· exact .inl ⟨ord _ (by simp) l.1,True.intro⟩· exact .inr ⟨ord _ (by simp) rr.1,True.intro⟩· cases rev <;> exact ord _ (by simp) ordertheorem Expansion.walk {v e kept r allow mark} (exp : Expansion v e kept) (hr : 1 < r)(cap : P455Closure.Cap r (v.flatMap e)) (s : Nat) (p : List Step)(walk : Walk r allow mark v s p) : Walk r allow mark (v.flatMap e) s p := byinduction p generalizing s with| nil => exact True.intro| cons step ps ih => exact ⟨exp.contact hr cap step.2 walk.1, ih _ walk.2⟩theorem Expansion.near {v e kept r allow mark} (exp : Expansion v e kept) (hr : 1 < r)(cap : P455Closure.Cap r (v.flatMap e)) {s t J : Nat} (near : Near r allow mark v s t J) :Near r allow mark (v.flatMap e) s t J := byobtain ⟨p,h,ep,le⟩ := nearexact ⟨p,exp.walk hr cap s p h,ep,le⟩/-- An occurrence in a small open slot contributes every letter of itsexpansion inside the corresponding literal open slot of the original.For an unretained variable the nonempty gap gives a genuine occupant. -/theorem Expansion.in_original_slot {v e kept} (exp : Expansion v e kept) (x i y : Nat) (kx : kept x)(ho : occupies v x i y) (a : Nat) (ha : a ∈ e y) : occupies (v.flatMap e) x i a := byobtain ⟨j,hj⟩ := hohave hm : (x,i+1) ∈ events v := hj.mem (by simp)have bound : i+1 < v.count x := by simpa using (P455SlotOrigin.event_bounds (fun _ => 0) _ x _ hm).2obtain ⟨L,I,R,cut,idx,cons⟩ := P455SlotOrigin.slot_cut v x i boundhave hy : y ∈ I := byapply (P455SlotOrigin.occupies_at_cut L I R x y cons).mprw [←cut,idx]; exact ⟨j,hj⟩have hI : (I.flatMap e).count x = I.count x := exp.count_eq I (fun a h => by simp [cut,h]) x kxhave fresh : x ∉ I.flatMap e := List.count_eq_zero.mp (hI.trans (List.count_eq_zero.mpr cons))have pref := exp.count_eq L (fun a h => by simp [cut,h]) x kxhave ex := exp.literal x (by simp [cut]) kxhave expanded : v.flatMap e =(L.flatMap e) ++ [x] ++ I.flatMap e ++ [x] ++ R.flatMap e := bysimp [cut,ex,List.flatMap_append]rw [expanded,←idx,←pref]exact (P455SlotOrigin.occupies_at_cut _ _ _ _ _ fresh).mpr (List.mem_flatMap.mpr ⟨y,hy,ha⟩)theorem Expansion.slot_guard {v e kept r} (exp : Expansion v e kept)(x i : Nat) (kx : kept x)(original : ∀ a, occupies (v.flatMap e) x i a → kept a ∧ (v.flatMap e).count a = r) :∀ y, occupies v x i y → v.count y = r := byintro y hoobtain ⟨j,obs⟩ := hohave used : y ∈ v := stamped_mem_label _ _ (y,j) (obs.mem (by simp))by_cases ky : kept y· have mem : y ∈ e y := by rw [exp.literal y used ky]; simphave claim := (original y (exp.in_original_slot x i y kx ⟨j,obs⟩ y mem)).2exact (exp.count_eq v (fun _ h => h) y ky).symm.trans claim· have gap := exp.gaps y used kyobtain ⟨a,ha⟩ : ∃ a, a ∈ e y := bycases he : e y with| nil => exact (gap.2.1 he).elim| cons a rest => exact ⟨a,by simp⟩exact (gap.2.2 a ha (original a (exp.in_original_slot x i y kx ⟨j,obs⟩ a ha)).1).elim/-- Derive the guard on the actual smaller rule from the retention of theoriginal radius-J contact ball and the uniformity of its slot occupants. -/theorem Expansion.guard {v e kept r allow mark seed J} (exp : Expansion v e kept)(hr : 1 < r) (cap : P455Closure.Cap r (v.flatMap e))(original : ∀ x, Near r allow mark (v.flatMap e) seed x J →kept x ∧ ∀ i, slotStart i → ∀ y, occupies (v.flatMap e) x i y →kept y ∧ (v.flatMap e).count y = r) :Guard r allow mark v seed J := byintro x near i hiobtain ⟨kx,slots⟩ := original x (exp.near hr cap near)exact exp.slot_guard x i kx (slots i hi)end P455Retainedend/- Begin Problem455SourceFamilies (from finite-semigroup-identity-bases). -/section/- Source interpretations of the designated slot and duplicate-neighborcertificates. Block distinctions require no repeated links to be readliterally back in the source. The weaker name/count conclusions do not. -/namespace P455SourceFamiliesopen P455Witness P455Paths P455ContactLift P455PortReflection Problem455.Slotsdef markNode (a : Node) : Marking := fun x y => x = a.owner ∧ y = a.matedef picked (s : SlotCertificate) := if s.startAtMate then s.anchor.mate else s.anchor.ownerdef sendDefect (d : Nat → Nat) : SlotDefect → SlotDefect| .deficient a => .deficient (d a)| .overflow xs => .overflow (xs.map d)def sendSlot (d : Nat → Nat) (s : SlotCertificate) : SlotCertificate :={ s with anchor := sendNode d s.anchor, steps := relabel d s.steps, defect := sendDefect d s.defect }def sendFunc (d : Nat → Nat) (f : FunctionalityCertificate) : FunctionalityCertificate :={ f with anchor := sendNode d f.anchor, b := sendNode d f.b, c := sendNode d f.c }def Compressed (r : Nat) (v : W) := ∀ a b, ¬ Problem455Swap.Link r v a btheorem compressed_separates {r v} (cmp : Compressed r v) {a b : Nat} (ne : a ≠ b) :¬ Problem455Swap.SameBlock r v a b := byintro samehave joined := same.2.2cases joined with| refl => exact ne rfl| extend _ adj => rcases adj with f|b <;> exact cmp _ _ (by assumption)private theorem remark_contact {r allow mark src w a b} (c : ContactChoice)(obs : V r allow mark w (contact r a b c)) : V r allow src w (contact r a b c) := byapply remark _ obscases c with| record tag rev => cases rev <;> rfl| port phase rev => rfltheorem remark_walk {r allow mark src w} (a : Nat) (p : List Step)(h : Walk r allow mark w a p) : Walk r allow src w a p := byinduction p generalizing a with| nil => exact True.intro| cons pair p ih => exact ⟨remark_contact pair.2 h.1,ih pair.1 h.2⟩theorem valid_slot {r allow mark w o i} (d : SlotDefect)(q : V r allow mark w (terminalSlot r o i d)) : slotStart i := bycases d with| deficient a => exact q.1.1| overflow xs =>cases xs with| nil => have h : ([] : List Nat).length = 5 := q.1; contradiction| cons a _ => exact q.2.2.1.1.2.1theorem rebuild_terminal_in {r v u h x i} (d : Nat → Nat) (a : SlotDefect)(slot : slotStart i) (cmp : Compressed r u)(unique : ∀ {a y}, Supplies v h r y a → d a = y)(inside : ∀ y, occupies v x i y → v.count y = r → occupies u x i y ∧ u.count y = r){allow mark} (lifted : P455TerminalTransfer.Lift v h x i r a) :Holds r allow mark u (terminalSlot r x i (sendDefect d a)) := bycases a with| deficient s => exact lifted.elim| overflow xs =>obtain ⟨f,len,nd,spec⟩ := liftedhave eq (a : Nat) (inxs : a∈xs) : d a = f a :=unique ⟨(spec a inxs).2.2,(spec a inxs).2.1⟩have maps : xs.map d = xs.map f := List.map_congr_left eqhave bs : (x :: xs.map d).Pairwise (fun a b => ¬ Problem455Swap.SameBlock r u a b) := byrw [maps]; exact nd.imp (fun ne => compressed_separates cmp ne)refine ⟨by simpa [P455Witness.Holds] using len,(P455TerminalTransfer.block_separation _).mpr bs,?_,True.intro⟩apply (allQ_iff _).mprintro q hqobtain ⟨z,hz,rfl⟩ := List.mem_map.mp hqobtain ⟨a,ha,rfl⟩ := List.mem_map.mp hzhave sp := spec a hahave out := inside (f a) sp.1 sp.2.2exact eq a ha ▸ And.intro out.2 (And.intro slot out.1)theorem rebuild_terminal {r v h x i} (d : Nat → Nat) (a : SlotDefect)(slot : slotStart i) (cmp : Compressed r v)(unique : ∀ {a y}, Supplies v h r y a → d a = y){allow mark} (lifted : P455TerminalTransfer.Lift v h x i r a) :Holds r allow mark v (terminalSlot r x i (sendDefect d a)) :=rebuild_terminal_in d a slot cmp unique (fun _ o cnt => ⟨o,cnt⟩) lifteddef SlotResult (r : Nat) (allow : Tag → Prop) (v : W) (h : Nat → W) (seed : Nat)(s : SlotCertificate) : Prop :=let d := donor v h rlet s' := sendSlot d slet m := markNode s'.anchorHolds r allow m v (markedNode s'.anchor s.bit) ∧Walk r allow m v seed s'.steps ∧P455TerminalTransfer.Lift v h (d (endpoint (picked s) s.steps)) s.terminalIndex r s.defect ∧(Compressed r v → Holds r allow m v (s'.query r))theorem slot_source {r allow mark v h l k seed} (hr : 0 < r)(cap : P455Closure.Cap r (l ++ v.flatMap h ++ k)) (s : SlotCertificate)(ok : V r allow mark (l ++ v.flatMap h ++ k) (s.query r))(start : Supplies v h r seed (picked s)) (guard : Guard r allow mark v seed 6) :SlotResult r allow v h seed s := bylet d := donor v h rlet m := markNode (sendNode d s.anchor)have seedEq : d (picked s) = seed := donor_eq hr (factor_cap cap) starthave anch : V r allow mark (l ++ v.flatMap h ++ k) (markedNode s.anchor s.bit) := ok.1have ports := record_pair (marked_typed anch)have rolesU : UniformOn r v h d (roles s.anchor) := byintro u memhave links : Near r allow mark (l ++ v.flatMap h ++ k) (picked s) u 1 := byrcases (show u=s.anchor.owner ∨ u=s.anchor.mate by simpa [roles] using mem) with rfl|rfl· cases z : s.startAtMate <;> simp only [picked,z,Bool.false_eq_true,if_false,if_true]· exact near_self _ _· exact ports.2· cases z : s.startAtMate <;> simp only [picked,z,Bool.false_eq_true,if_false,if_true]· exact ports.1· exact near_self _ _exact (lift_near hr cap start guard (by decide : 1 ≤ 6) links).1have bit := reflect_markedNode hr cap s.anchor s.bit rolesU m (.inl ⟨rfl,rfl⟩) anchobtain ⟨len,outputWalk,terminal⟩ := slot_route s okhave walks := lift_walk hr cap start guard s.steps len outputWalklet endLabel := endpoint (picked s) s.stepshave ext : Near r allow mark (l ++ v.flatMap h ++ k) (picked s) endLabel 6 :=⟨s.steps,outputWalk,rfl,len⟩obtain ⟨en,towards⟩ := lift_near hr cap start guard (Nat.le_refl _) exthave slot := valid_slot s.defect terminalhave g := guard (d endLabel) towards s.terminalIndex slothave lf := P455TerminalTransfer.terminal v h l k (d endLabel) endLabel s.terminalIndex rhr cap en.1 en.2 g s.defect terminalhave sw : Walk r allow m v seed (relabel d s.steps) := remark_walk _ _ walks.1refine ⟨bit,sw,lf,?_⟩intro cmphave term : V r allow m v (terminalSlot r (d endLabel) s.terminalIndex (sendDefect d s.defect)) :=rebuild_terminal d s.defect slot cmp (fun hh => donor_eq hr (factor_cap cap) hh) lfhave pickEq : picked (sendSlot d s) = d (picked s) := bycases z : s.startAtMate <;> simp [picked,sendSlot,sendNode,z]refine ⟨bit,by simpa [sendSlot,relabel,P455Witness.Holds] using len,?_,True.intro⟩apply (route_iff ..).mprchange Walk r allow m v (picked (sendSlot d s)) (relabel d s.steps) ∧V r allow m v (terminalSlot r (endpoint (picked (sendSlot d s)) (relabel d s.steps))s.terminalIndex (sendDefect d s.defect))rw [pickEq,endpoint_relabel]exact ⟨seedEq.symm ▸ sw,term⟩def roleOf (b : Bool) (n : Node) := if b then n.mate else n.ownerdef FuncResult (r : Nat) (allow : Tag → Prop) (ts : Tiles) (v : W) (h : Nat → W)(f : FunctionalityCertificate) : Prop :=let f' := sendFunc (donor v h r) flet m := markNode f'.anchorHolds r allow m v (markedNode f'.anchor f'.bit) ∧Holds r allow m v (neighbor ts f'.anchor f'.b f'.dir) ∧Holds r allow m v (neighbor ts f'.anchor f'.c f'.dir) ∧roleOf f'.distinguishMate f'.b ≠ roleOf f'.distinguishMate f'.c ∧(Compressed r v → Holds r allow m v (f'.query ts))theorem functionality_source {r allow mark v h l k seed} (hr : 0 < r)(cap : P455Closure.Cap r (l ++ v.flatMap h ++ k)) (ts : Tiles) (f : FunctionalityCertificate)(ok : V r allow mark (l ++ v.flatMap h ++ k) (f.query ts))(start : Supplies v h r seed f.anchor.owner) (guard : Guard r allow mark v seed 6) :FuncResult r allow ts v h f := bylet d := donor v h rlet m := markNode (sendNode d f.anchor)have supplies (n : Node) (use : n=f.anchor ∨ n=f.b ∨ n=f.c) : UniformOn r v h d (roles n) := byintro a hahave reach := P455CertificateReach.functionality_reach cap ts f ok use(show a=n.owner ∨ a=n.mate by simpa [roles] using ha)exact (lift_near hr cap start guard (by decide : 2 ≤ 6) reach).1have union (n : Node) (use : n=f.anchor ∨ n=f.b ∨ n=f.c) :UniformOn r v h d (roles f.anchor ++ roles n) := byintro a harcases List.mem_append.mp ha with h1|h2· exact supplies _ (.inl rfl) _ h1· exact supplies n use _ h2have bit := reflect_markedNode hr cap f.anchor f.bit (supplies _ (.inl rfl)) m (.inl ⟨rfl,rfl⟩) ok.1have b := neighbor_remark (dst := m) (reflect_neighbor hr cap ts f.anchor f.b f.dir (union _ (.inr (.inl rfl))) ok.2.1)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)have rb (n : Node) : roleOf f.distinguishMate n ∈ roles n := bycases e : f.distinguishMate <;> simp [roleOf,roles,e]have sb := supplies f.b (.inr (.inl rfl)) _ (rb f.b)have sc := supplies f.c (.inr (.inr rfl)) _ (rb f.c)have neat : d (roleOf f.distinguishMate f.b) ≠ d (roleOf f.distinguishMate f.c) := byintro eqhave same := Problem455SameDonor.sameDonor v h _ sb.1 (factor_cap cap) _ _ sb.2 (eq.symm ▸ sc.2)apply ok.2.2.2.1exact Problem455Swap.sameBlock_factor ⟨l,k,rfl⟩(fun a => by rw [Problem455BlockBridge.occ_count]; exact cap a) samehave mapped (n : Node) : roleOf f.distinguishMate (sendNode d n) = d (roleOf f.distinguishMate n) := bycases f.distinguishMate <;> rflhave neq : roleOf f.distinguishMate (sendNode d f.b) ≠ roleOf f.distinguishMate (sendNode d f.c) := bysimpa only [mapped] using neatexact ⟨bit,b,c,neq,fun cmp => ⟨bit,b,c,compressed_separates cmp neq,True.intro⟩⟩end P455SourceFamiliesend/- Begin Problem455EdgeSource (from finite-semigroup-identity-bases). -/sectionnamespace P455EdgeSourceopen P455Witness P455Paths P455CertificateReach P455PortReflection P455ContactReflectionopen P455ContactLiftdef sendEdge (d : Nat → Nat) (e : EdgeCertificate) : EdgeCertificate :=⟨sendNode d e.a, sendNode d e.b, sendNode d e.right, sendNode d e.left,sendNode d e.down, sendNode d e.up, sendNode d e.diagonal⟩def endpointMarks (d : Nat → Nat) (e : EdgeCertificate) (s t : Nat) : Prop :=(s = d e.a.owner ∧ t = d e.a.mate) ∨ (s = d e.b.owner ∧ t = d e.b.mate)private theorem when_true {r allow mark w b q} (f : b = true → Holds r allow mark w q) :Holds r allow mark w (flagQ b q) := bycases b· exact True.intro· exact f rflprivate theorem read_guard {r allow mark w b q} (hb : b = true)(f : Holds r allow mark w (flagQ b q)) : Holds r allow mark w q := by simpa [flagQ,hb] using f/-- Retain one real four-role port between the endpoints. This also suppliesthe injectivity needed for the final first-owner comparison. -/theorem endpoint_port {r allow mark w} (ts : Tiles) (e : EdgeCertificate)(ok : Holds r allow mark w (e.query ts)) :∃ p, Holds r allow mark w (orientedPort p e.a e.b) ∨Holds r allow mark w (orientedPort p e.b e.a) := byhave lc := ok.2.2.1have succ := ok.2.2.2.1unfold chosenSuccessor at succdsimp only at succsplit at succnext ret => exact ⟨4,succ.2.1⟩next noReturn =>have eq := succ.1cases row : endOfRow ts e.a with| true =>have down : ts.bottom e.a.tag = false := by simpa [row] using noReturnhave target : e.down = e.b := by simpa [row,P455Witness.Holds] using eqhave ok := read_guard (by simp [down]) lc.2.2.1exact ⟨_,.inl (target ▸ ok.2)⟩| false =>cases odd : ts.oddRow e.a.tag with| true =>have left : ts.left e.a.tag = false := by simpa [endOfRow,odd] using rowhave target : e.left = e.b := by simpa [row,odd,P455Witness.Holds] using eqhave ok := read_guard (by simp [left]) lc.2.1exact ⟨_,.inr (target ▸ ok.2.1)⟩| false =>have right : ts.right e.a.tag = false := by simpa [endOfRow,odd] using rowhave target : e.right = e.b := by simpa [row,odd,P455Witness.Holds] using eqhave ok := read_guard (by simp [right]) lc.1exact ⟨_,.inl (target ▸ ok.2.1)⟩theorem edge_source {r allow mark v h l k d} (hr : 0 < r)(cap : P455Closure.Cap r (l ++ v.flatMap h ++ k)) (ts : Tiles) (e : EdgeCertificate)(supply : ∀ n, Active ts e n → UniformOn r v h d (roles n))(ok : Holds r allow mark (l ++ v.flatMap h ++ k) (e.query ts)) :Holds r allow (endpointMarks d e) v ((sendEdge d e).query ts) := byhave both {n m} (an : Active ts e n) (am : Active ts e m) :UniformOn r v h d (roles n ++ roles m) := byintro y hyrcases List.mem_append.mp hy with h|h· exact supply n an y h· exact supply m am y hhave localRight (rr : ts.right e.a.tag = false) :=read_guard (by simp [rr]) ok.2.2.1.1have localLeft (ll : ts.left e.a.tag = false) :=read_guard (by simp [ll]) ok.2.2.1.2.1have localDown (dd : ts.bottom e.a.tag = false) :=read_guard (by simp [dd]) ok.2.2.1.2.2.1have localUp (uu : ts.top e.a.tag = false) :=read_guard (by simp [uu]) ok.2.2.1.2.2.2.1have localSq (rr : ts.right e.a.tag = false) (dd : ts.bottom e.a.tag = false) :=read_guard (by simp [rr,dd]) ok.2.2.1.2.2.2.2.1have hs : Holds r allow (endpointMarks d e) v (localCert ts (sendEdge d e)) := byrefine ⟨when_true (fun b => ?_),when_true (fun b => ?_),when_true (fun b => ?_),when_true (fun b => ?_),when_true (fun b => ?_),True.intro⟩· have rr : ts.right e.a.tag = false := by simpa [sendEdge,sendNode] using bexact reflect_rightward hr cap ts _ _ (both .anchor (.right rr)) (localRight rr)· have ll : ts.left e.a.tag = false := by simpa [sendEdge,sendNode] using bexact reflect_rightward hr cap ts _ _ (both (.left ll) .anchor) (localLeft ll)· have dd : ts.bottom e.a.tag = false := by simpa [sendEdge,sendNode] using bexact reflect_downward hr cap ts _ _ (both .anchor (.down dd)) (localDown dd)· have uu : ts.top e.a.tag = false := by simpa [sendEdge,sendNode] using bexact reflect_downward hr cap ts _ _ (both (.up uu) .anchor) (localUp uu)· obtain ⟨rr,dd⟩ : ts.right e.a.tag = false ∧ ts.bottom e.a.tag = false := bysimpa [sendEdge,sendNode] using bexact ⟨reflect_downward hr cap ts _ _ (both (.right rr) (.diagonal rr dd)) (localSq rr dd).1,reflect_rightward hr cap ts _ _ (both (.down dd) (.diagonal rr dd)) (localSq rr dd).2⟩have aBit := reflect_markedNode hr cap e.a true (supply _ .anchor) (endpointMarks d e)(Or.inl (Or.inl ⟨rfl,rfl⟩)) ok.1have bBit := reflect_markedNode hr cap e.b false (supply _ .successor) (endpointMarks d e)(Or.inl (Or.inr ⟨rfl,rfl⟩)) ok.2.1refine ⟨aBit,bBit,hs,?_,True.intro⟩have rel (pat) (mem : ∀ u ∈ pat, u.1 ∈ roles e.a ++ roles e.b) (ord :Holds r allow mark (l ++ v.flatMap h ++ k) (.order pat)) :Holds r allow mark v (.order (pat.map (eventMap d))) := byobtain ⟨p,forward|back⟩ := endpoint_port ts e ok· exact port_owner_order hr cap _ _ p (both .anchor .successor) forward pat mem ord· exact port_owner_order hr cap _ _ p (both .successor .anchor) back pat(fun u hu => by have := mem u hu; simpa [or_comm] using this) ordhave suc := ok.2.2.2.1unfold chosenSuccessor at suc ⊢dsimp only [sendEdge,sendNode] at suc ⊢change Holds r allow _ v (if endOfRow ts e.a && ts.bottom e.a.tag then _ else _)split at sucnext ret =>rw [if_pos ret]have ord := rel [(e.b.owner,0),(e.a.owner,0)] (by simp [roles]) suc.2.2.1refine ⟨suc.1,?_,ord,True.intro⟩rcases suc.2.1 with f|b· exact .inl (reflect_port hr cap _ _ _ (both .anchor .successor) f)· exact .inr (reflect_port hr cap _ _ _ (both .successor .anchor) b)next noReturn =>rw [if_neg noReturn]have ord := rel [(e.a.owner,0),(e.b.owner,0)] (by simp [roles]) suc.2refine ⟨?_,ord⟩change (if endOfRow ts e.a then sendNode d e.down elseif ts.oddRow e.a.tag then sendNode d e.left else sendNode d e.right) = sendNode d e.bhave eq := suc.1cases row : endOfRow ts e.a <;> cases parity : ts.oddRow e.a.tag <;>simp only [row,parity,Bool.false_eq_true,if_false,if_true] at eq ⊢ <;>exact congrArg (sendNode d) eq/-- A guarded source seed on the owner of either marked endpoint suppliesevery active record used above. No map of the tester alphabet is assumed. -/theorem edge_source_of_seed {r allow mark v h l k seed J} (hr : 0 < r)(cap : P455Closure.Cap r (l ++ v.flatMap h ++ k)) (ts : Tiles) (e : EdgeCertificate)(ok : Holds r allow mark (l ++ v.flatMap h ++ k) (e.query ts))(startAtSecond : Bool)(start : Supplies v h r seed (if startAtSecond then e.b.owner else e.a.owner))(guard : Guard r allow mark v seed J) (budget : 4 ≤ J) :Holds r allow (endpointMarks (donor v h r) e) v ((sendEdge (donor v h r) e).query ts) := byapply edge_source hr cap ts e _ okintro n active y hyhave role : y = n.owner ∨ y = n.mate := by simpa [roles] using hyobtain ⟨a,b⟩ := edge_reach cap ts e ok active rolehave near : Near r allow mark (l ++ v.flatMap h ++ k)(if startAtSecond then e.b.owner else e.a.owner) y 4 := by cases startAtSecond <;> assumptionexact (lift_near hr cap start guard budget near).1/-- Starting at a mate rather than an owner costs one record contact.Only a donor for this one chosen occurrence label is needed. -/theorem edge_source_from_role {r allow mark v h l k seed J} (hr : 0 < r)(cap : P455Closure.Cap r (l ++ v.flatMap h ++ k)) (ts : Tiles) (e : EdgeCertificate)(ok : Holds r allow mark (l ++ v.flatMap h ++ k) (e.query ts))(atSecond atMate : Bool)(start : let a := if atSecond then e.b else e.aSupplies v h r seed (if atMate then a.mate else a.owner))(guard : Guard r allow mark v seed J) (budget : (if atMate then 5 else 4) ≤ J) :Holds r allow (endpointMarks (donor v h r) e) v ((sendEdge (donor v h r) e).query ts) := bycases atMate with| false =>cases atSecond· exact edge_source_of_seed hr cap ts e ok false start guard budget· exact edge_source_of_seed hr cap ts e ok true start guard budget| true =>apply edge_source hr cap ts e _ okintro n active y hyhave role : y = n.owner ∨ y = n.mate := by simpa [roles] using hyobtain ⟨a,b⟩ := edge_reach cap ts e ok active rolecases atSecond· have step := (record_pair (marked_typed ok.1)).2exact (lift_near hr cap start guard budget (near_trans step a)).1· have step := (record_pair (marked_typed ok.2.1)).2exact (lift_near hr cap start guard budget (near_trans step b)).1end P455EdgeSourceend/- Begin Problem455RealizerClass (from finite-semigroup-identity-bases). -/sectionnamespace P455ClassPrimopen P455EffectiveQ P455GraphPrimvariable {A : Type} [Primcodable A]abbrev Raw := Option Wtheorem live {e : A → W → W → Bool} (he : Primrec (fun x : A×(W×W) => e x.1 x.2.1 x.2.2)){T : A → W} {z : A → Raw} (ht : Primrec T) (hz : Primrec z) :Primrec fun a => liveB (e a) (T a) (z a) := bylet h (a : A) (w : W) := goodB (e a) (T a) whave recProof : Primrec₂ h :=Primrec₂.mk (good (A := A × W) (e := fun q => e q.1)(he.comp (Primrec.pair (Primrec.fst.comp Primrec.fst) Primrec.snd))(ht.comp Primrec.fst) Primrec.snd)exact (Primrec.option_casesOn hz (Primrec.const false) recProof).of_eq(fun a => by cases z a <;> rfl)theorem pairedRec {e : A → W → W → Bool} (he : Primrec (fun x : A×(W×W) => e x.1 x.2.1 x.2.2)){T : A → W} {x y : A → Raw} (ht : Primrec T) (hx : Primrec x) (hy : Primrec y) :Primrec fun a => paired (e a) (T a) (x a) (y a) := bylet inside (a : A) (u v : W) := goodB (e a) (T a) u && goodB (e a) (T a) v && walkB (e a) u vhave ep : Primrec (fun p : ((A×W)×W)×(W×W) => e p.1.1.1 p.2.1 p.2.2) :=he.comp (Primrec.pair (Primrec.fst.comp (Primrec.fst.comp Primrec.fst)) Primrec.snd)have rr : Primrec (fun p : (A×W)×W => inside p.1.1 p.1.2 p.2) :=Primrec.and.comp (Primrec.and.comp(good (A := (A×W)×W) (e := fun p => e p.1.1) ep (ht.comp (Primrec.fst.comp Primrec.fst))(Primrec.snd.comp Primrec.fst))(good (A := (A×W)×W) (e := fun p => e p.1.1) ep (ht.comp (Primrec.fst.comp Primrec.fst)) Primrec.snd))(reachable (A := (A×W)×W) (e := fun p => e p.1.1) ep (Primrec.snd.comp Primrec.fst) Primrec.snd)let tail (a : A) (u : W) : Bool := Option.casesOn (y a) false (inside a u)have tr : Primrec₂ tail := Primrec₂.mk(Primrec.option_casesOn (hy.comp Primrec.fst) (Primrec.const false) rr.to₂)exact (Primrec.option_casesOn hx (Primrec.const false) tr).of_eq(fun a => by cases x a <;> cases h : y a <;> simp [tail,inside,h,paired])theorem relation {e : A → W → W → Bool} (he : Primrec (fun x : A×(W×W) => e x.1 x.2.1 x.2.2)){T : A → W} {x y : A → Raw} (ht : Primrec T) (hx : Primrec x) (hy : Primrec y) :Primrec fun a => relB (e a) (T a) (x a) (y a) :=Primrec.or.comp (Primrec.and.comp (Primrec.not.comp (live he ht hx)) (Primrec.not.comp (live he ht hy)))(pairedRec he ht hx hy)end P455ClassPrimend/- Begin Problem455RealizerFrameOps (from finite-semigroup-identity-bases). -/sectionnamespace P455FramePrimopen P455Closure P455EffectiveQ P455GraphPrimabbrev Tag := List Boolabbrev Marks := List (Nat×Nat)abbrev PairList := List (List Nat×Bool)abbrev FrameData := Nat × W × W × Nat × Tag × PairList × W × W × Wdef packing : Frame Nat ≃ FrameData wheretoFun f := (f.pHead,f.pTail,f.qInit,f.qLast,f.tag,f.middle,f.beforeMutable,f.beforeFinalP,f.beforeFinalQ)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,d.2.2.2.2.2.2.2.1,d.2.2.2.2.2.2.2.2⟩left_inv _ := rflright_inv _ := rflinstance framePrimcodable : Primcodable (Frame Nat) := Primcodable.ofEquiv _ packingtheorem pack : Primrec packing := Primrec.of_equivtheorem unpack : Primrec packing.symm := Primrec.of_equiv_symmvariable {A B C : Type} [Primcodable A] [Primcodable B] [Primcodable C]theorem allB {l : A → List B} {p : A → B → Bool} (hl : Primrec l) (hp : Primrec₂ p) :Primrec fun a => (l a).all (p a) := byapply (Primrec.not.comp (anyB hl (Primrec.not.comp₂ hp))).of_eqintro a; simp only [List.not_any_eq_all_not,Bool.not_not]theorem countN {z : A → Nat} {l : A → W} (hz : Primrec z) (hl : Primrec l) :Primrec fun a => (l a).count (z a) := byapply (Primrec.list_length.comp (P455GraphPrim.filter hl((Primrec.beq.comp Primrec.snd (hz.comp Primrec.fst)).to₂))).of_eqintro asimp [List.count_eq_countP,List.countP_eq_length_filter,BEq.comm]theorem nodup {l : A → W} (hl : Primrec l) : Primrec fun a => decide (l a).Nodup := byapply (allB hl ((Primrec.eq.comp (countN Primrec.snd (hl.comp Primrec.fst)) (.const 1)).decide.to₂)).of_eqintro aapply Bool.eq_iff_iff.mprsimp only [List.all_eq_true,decide_eq_true_eq,List.nodup_iff_count_eq_one]theorem singleton {v : A → B} (hv : Primrec v) : Primrec fun a => [v a] := Primrec.list_cons.comp hv (.const [])theorem pairs : Primrec phasePair :=Primrec.list_cons.comp Primrec.id (singleton Primrec.not)theorem phases : Primrec fixedPhases :=Primrec.list_append.comp (Primrec.list_append.comp (.const _) (Primrec.list_flatMap Primrec.id (pairs.comp₂ .right))) (.const _)theorem pHead : Primrec (@Frame.pHead Nat) := (Primrec.fst.comp pack)theorem pTail : Primrec (@Frame.pTail Nat) := (Primrec.fst.comp (Primrec.snd.comp pack))theorem qInit : Primrec (@Frame.qInit Nat) := (Primrec.fst.comp (Primrec.snd.comp (Primrec.snd.comp pack)))theorem qLast : Primrec (@Frame.qLast Nat) := (Primrec.fst.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp pack))))theorem tag : Primrec (@Frame.tag Nat) := (Primrec.fst.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp pack)))))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))))))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)))))))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))))))))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))))))))theorem p : Primrec (@Frame.p Nat) := Primrec.list_cons.comp pHead pTailtheorem q : Primrec (@Frame.q Nat) := Primrec.list_append.comp qInit (singleton qLast)theorem early : Primrec (@Frame.early Nat) :=Primrec.list_append.comp (Primrec.list_append.comp (Primrec.list_append.comp (Primrec.list_append.comp(Primrec.list_append.comp p p) q) p) q) qtheorem mid : Primrec (@Frame.mid Nat) := Primrec.list_flatMap middle <| Primrec₂.mk <|Primrec.list_append.comp (Primrec.fst.comp Primrec.snd)(Primrec.ite (Primrec.eq.comp (Primrec.snd.comp Primrec.snd) (.const true))(q.comp Primrec.fst) (p.comp Primrec.fst))theorem pairCore : Primrec₂ (@Frame.pair Nat) := Primrec₂.mk <|Primrec.ite (Primrec.eq.comp Primrec.snd (.const true))(Primrec.list_append.comp (q.comp Primrec.fst) (p.comp Primrec.fst))(Primrec.list_append.comp (p.comp Primrec.fst) (q.comp Primrec.fst))theorem core : Primrec₂ (@Frame.core Nat) := Primrec₂.mk <|(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))end P455FramePrimend/- Begin Problem455MachineTrace (from finite-semigroup-identity-bases). -/sectionnamespace P455MachineTableopen P455MachineLocal P455PaddedTilesprivate theorem left_agree {u v : Nat→Fin n} {w x : Nat} (hx : x<w) (eq : ∀ j,j<w→u j=v j) :leftAt u x=leftAt v x := byby_cases e : x=0 <;> simp [leftAt,e,eq (x-1) (by omega)]private theorem right_agree {u v : Nat→Fin n} {w x : Nat} (hx : x<w) (eq : ∀ j,j<w→u j=v j) :rightAt u w x=rightAt v w x := byby_cases e : x+1=w· simp [rightAt,e]· simp [rightAt,e,eq _ (by omega : x+1<w)]private theorem next_inside {d : Direction} {p w : Nat} (hp : p<w) (safe : ¬exits d w p) : dest d p<w := bycases d <;> simp [exits,dest] at * <;> omegatheorem agrees (M : TM g q) {w s : Nat} (T : AcceptingTrace (compile M) w s) :∀ t,t≤s → (run M t).pos<w ∧ ∀ x,x<w → T.rows t x=row M t x := byintro t; induction t with| zero =>intro _refine ⟨T.positive,?_⟩intro x hxrw [T.start x hx]by_cases e : x=0 <;> simp [compile,row,run,init,atCell,e]| succ t ih =>intro stobtain ⟨hp,eq⟩ := ih (by omega)have moves (x : Nat) (hx : x<w) :=T.steps t (by omega) x hxhave atStep (x : Nat) (hx : x<w) :(compile M).next (leftAt (row M t) x) (row M t x) (rightAt (row M t) w x)=some (T.rows (t+1) x) := bysimpa only [left_agree hx eq,right_agree hx eq,eq x hx] using moves x hxlet p := (run M t).poslet z := (run M t).statelet tape := (run M t).tapehave safe : ¬exits (M.delta z (tape p)).dir w p := byintro badhave e := (defined_at_head M.delta tape w p z hp).mpr badhave observed := atStep p hpchange (update M.delta _ (dec M (enc _)) _).map enc=_ at observedrw [left_dec,right_dec,dec_enc] at observedchange (update M.delta (leftOf (atCell tape p z) p) (atCell tape p z p) (rightOf (atCell tape p z) w p)).map enc=_ at observedrw [e] at observedcontradictionrefine ⟨next_inside hp safe,?_⟩intro x hxexact Option.some.inj ((atStep x hx).symm.trans (local_value M t w x hp safe hx))def Genuine (M : TM g q) (t : Nat) := (run M t).pos=0 ∧ (run M t).state=M.accepttheorem genuine_of_trace (M : TM g q) {w s : Nat} (T : AcceptingTrace (compile M) w s) : Genuine M s := byhave eq := ((agrees M T s (by omega)).2 0 T.positive).symm.trans T.accepthave old := enc_inj M eqchange atCell (run M s).tape (run M s).pos (run M s).state 0=⟨M.marker,some M.accept⟩ at oldhave head := congrArg Cell.head oldby_cases e : (run M s).pos=0· exact ⟨e,by simpa [atCell,e] using head⟩· simp [atCell,Ne.symm e] at headtheorem fixed_accept (M : TM g q) {s : Nat} (accepts : Genuine M s) : run M (s+1)=run M s := byhave fixedCfg (c : Config g q) (at0 : c.pos=0) (state : c.state=M.accept) (eq0 : c.tape 0=M.marker) :step M c=c := bycases c with| mk tape pos st =>change pos=0 at at0; change st=M.accept at statesubst pos; subst stchange tape 0=M.marker at eq0have fixed : writeAt tape 0 M.marker=tape := by funext x; by_cases e : x=0 <;> simp [writeAt,e,eq0]simp [step,eq0,M.stationary,dest,fixed]exact fixedCfg (run M s) accepts.1 accepts.2 ((marker_iff M s 0).mpr rfl)private theorem same_value (M : TM g q) {s : Nat} (genuine : Genuine M s) (x : Nat) :row M (s+1) x=row M s x := by unfold row; rw [fixed_accept M genuine]/-- Every accepting trace of a compiled machine supplies its own full-rowstutter, including the unwritten cells and both strip boundaries. -/theorem trace_stutters (M : TM g q) {w s : Nat} (T : AcceptingTrace (compile M) w s) :∀ 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) := byhave ⟨hp,eq⟩ := agrees M T s (by omega)have g := genuine_of_trace M Thave safe : ¬exits (M.delta (run M s).state ((run M s).tape (run M s).pos)).dir w (run M s).pos := bysimp [g.1,g.2,(marker_iff M s 0).mpr rfl,M.stationary,exits]intro x hxrw [left_agree hx eq,right_agree hx eq,eq x hx,local_value M s w x hp safe hx,same_value M g]theorem trace_of_genuine (M : TM g q) {s : Nat} (g : Genuine M s) : Nonempty (AcceptingTrace (compile M) (s+2) s) := byrefine ⟨⟨by omega,row M,?_,?_,?_,?_⟩⟩· intro x _; by_cases e : x=0 <;> simp [row,run,init,atCell,compile,e]· intro y _ x _; simp only [compile,row,dec_enc,atCell]by_cases e : x=0· simp [e,(marker_iff M y 0).mpr rfl]· have f : (run M y).tape x ≠ M.marker := fun h=>e ((marker_iff M y x).mp h)simp [e,f]· intro y hy x hx; exact local_value M _ _ _ (by have := head_bound M y; omega) (physical_safe M (by omega)) hx· simp [row,compile,atCell,g.1,g.2,(marker_iff M s 0).mpr rfl]theorem trace_iff (M : TM g q) : (∃ t,Genuine M t) ↔ ∃ w s, Nonempty (AcceptingTrace (compile M) w s) := byconstructor· rintro ⟨s,g⟩; exact ⟨_,s,trace_of_genuine M g⟩· rintro ⟨w,s,⟨T⟩⟩; exact ⟨s,genuine_of_trace M T⟩theorem rectangles_iff (M : TM g q) : (∃ t,Genuine M t) ↔∃ w, ∀ k, ∃ h, 1<h ∧ k<2*(w*h) ∧ Nonempty (Rectangle (compile M) w h) :=(trace_iff M).trans (trace_iff_rectangles (fun T => trace_stutters M T))end P455MachineTableend/- Begin Problem455OriginalWalk (from finite-semigroup-identity-bases). -/section/- End-to-end transport of a designated marked-word path to its originalword after expanding the small rule's gaps. Both valuations may use thesame Nat name for unrelated alphabet entries. Only e expands the rule;h supplies the actual tester representatives. -/namespace P455OriginalWalkopen Problem455.Slots P455Witness P455Paths P455ContactLift P455Retaineddef OriginalGuard (r : Nat) (allow : Tag → Prop) (mark : Marking) (u : W)(kept : Nat → Prop) (seed J : Nat) : Prop :=∀ x, Near r allow mark u seed x J →kept x ∧ ∀ i, slotStart i → ∀ y, occupies u x i y → kept y ∧ u.count y = r/-- Every output step of the recorded list is read in the original once itsreached labels are replaced by their unique donors. No injectivity of theentire reached-label map is asserted. -/theorem lift_walk {v e kept r allow mark seed J h l k s}(exp : Expansion v e kept) (hr : 1 < r) (capU : P455Closure.Cap r (v.flatMap e))(original : OriginalGuard r allow mark (v.flatMap e) kept seed J)(capZ : P455Closure.Cap r (l ++ v.flatMap h ++ k)) (start : Supplies v h r seed s)(p : List Step) (len : p.length ≤ J)(walk : Walk r allow mark (l ++ v.flatMap h ++ k) s p) :let d := donor v h rlet y := d (endpoint s p)Walk r allow mark (v.flatMap e) seed (relabel d p) ∧endpoint seed (relabel d p) = y ∧ (relabel d p).length = p.length ∧ kept y ∧Supplies v h r y (endpoint s p) ∧ Supplies (v.flatMap e) h r y (endpoint s p) := bylet d := donor v h rhave pos : 0 < r := by omegahave eq : d s = seed := donor_eq pos (factor_cap capZ) startobtain ⟨small,supply⟩ := P455ContactLift.lift_walk pos capZ start (exp.guard hr capU original) p len walkhave large := exp.walk hr capU seed _ smallhave ep : endpoint seed (relabel d p) = d (endpoint s p) := by rw [← eq,endpoint_relabel]have lp : (relabel d p).length = p.length := by simp [relabel]have reach : Near r allow mark (v.flatMap e) seed (d (endpoint s p)) J :=⟨relabel d p,large,ep,lp ▸ len⟩have ky := (original _ reach).1exact ⟨large,ep,lp,ky,supply,(exp.count_eq v (fun _ h => h) _ ky).trans supply.1,supply.2⟩theorem lift_near {v e kept r allow mark seed J h l k s a n}(exp : Expansion v e kept) (hr : 1 < r) (capU : P455Closure.Cap r (v.flatMap e))(original : OriginalGuard r allow mark (v.flatMap e) kept seed J)(capZ : P455Closure.Cap r (l ++ v.flatMap h ++ k)) (start : Supplies v h r seed s)(bound : n ≤ J) (near : Near r allow mark (l ++ v.flatMap h ++ k) s a n) :let y := donor v h r aNear r allow mark (v.flatMap e) seed y n ∧ kept y ∧Supplies v h r y a ∧ Supplies (v.flatMap e) h r y a := byobtain ⟨p,walk,ea,len⟩ := nearobtain ⟨w,ep,lp,kp,small,full⟩ := lift_walk exp hr capU original capZ start p (Nat.le_trans len bound) walkrw [ea] at ep kp small fullexact ⟨⟨_,w,ep,lp ▸ len⟩,kp,small,full⟩end P455OriginalWalkend/- Begin Problem455OriginalEdges (from finite-semigroup-identity-bases). -/sectionnamespace P455OriginalEdgesopen Problem455.Slots P455Witness P455Paths P455Retained P455PortReflectionsectionvariable {r : Nat} {v : W} {e : Nat → W} {kept : Nat → Prop}{allow : Tag → Prop} {mark : Marking}theorem kept_roles (exp : Expansion v e kept) (hr : 1 < r) (cap : P455Closure.Cap r (v.flatMap e)){a : Node} (recProof : Holds r allow mark v (typedNode a)) : ∀ x ∈ roles a, kept x := byobtain ⟨cnt,cn'⟩ := record_counts (exp.small_cap hr cap) recProofintro x hxhave ct : v.count x = r := byrcases (show x = a.owner ∨ x = a.mate by simpa [roles] using hx) with eq|eq· exact eq ▸ cnt· exact eq ▸ cn'apply Classical.byContradictionintro gaphave := (exp.gaps x (List.count_pos_iff.mp (by omega)) gap).1omegatheorem expand_markedNode (exp : Expansion v e kept) (hr : 1 < r) (cap : P455Closure.Cap r (v.flatMap e)){a : Node} {bit : Bool} (recProof : Holds r allow mark v (markedNode a bit)) :Holds r allow mark (v.flatMap e) (markedNode a bit) := byhave eq := exp.select_eq v (roles a) (fun _ h => h) (kept_roles exp hr cap (marked_typed recProof))exact ⟨recProof.1,recProof.2.1,recProof.2.2.1,recProof.2.2.2.1,eq.trans recProof.2.2.2.2⟩theorem expand_typedNode (exp : Expansion v e kept) (hr : 1 < r) (cap : P455Closure.Cap r (v.flatMap e)){a : Node} (recProof : Holds r allow mark v (typedNode a)) : Holds r allow mark (v.flatMap e) (typedNode a) :=exp.contact hr cap (.record a.tag false) recProoftheorem expand_order (exp : Expansion v e kept) {p : List Event}(labels : ∀ ev ∈ p, kept ev.1) (ord : Holds r allow mark v (.order p)) :Holds r allow mark (v.flatMap e) (.order p) := bylet ks := p.map Prod.fsthave all : ∀ a ∈ ks, kept a := byintro a hobtain ⟨ev,he,rfl⟩ := List.mem_map.mp hexact labels ev herefine ⟨ord.1,P455ContactReflection.select_sees ks _ p ?_⟩rw [exp.select_eq v ks (fun _ h => h) all]exact P455ContactReflection.sees_select ks _ p (fun ev he => List.mem_map_of_mem he) ord.2theorem expand_earlier (exp : Expansion v e kept) {a i b j}(ha : kept a) (hb : kept b) (ord : Holds r allow mark v (earlier a i b j)) :Holds r allow mark (v.flatMap e) (earlier a i b j) :=expand_order exp (by simp [ha,hb]) ordtheorem expand_port (exp : Expansion v e kept) (hr : 1 < r) (cap : P455Closure.Cap r (v.flatMap e)){p : Nat} {a b : Node} (port : Holds r allow mark v (orientedPort p a b)) :Holds r allow mark (v.flatMap e) (orientedPort p a b) := byobtain ⟨ra,rb,early,order,_⟩ := porthave ka := kept_roles exp hr cap rahave kb := kept_roles exp hr cap rbhave earl {xs ys : W} (kx : ∀ a ∈ xs, kept a) (ky : ∀ a ∈ ys, kept a)(obs : Holds r allow mark v (earlyBefore xs ys)) :Holds r allow mark (v.flatMap e) (earlyBefore xs ys) := byapply (earlyBefore_iff _ _).mprexact fun a ha b hb => expand_earlier exp (kx a ha) (ky b hb) ((earlyBefore_iff _ _).mp obs a ha b hb)refine ⟨expand_typedNode exp hr cap ra,expand_typedNode exp hr cap rb,?_,?_,True.intro⟩· exact early.elim (fun h => Or.inl (earl ka kb h)) (fun h => Or.inr (earl kb ka h))· have ka' : kept a.owner ∧ kept a.mate := by simpa [roles] using kahave kb' : kept b.owner ∧ kept b.mate := by simpa [roles] using kbexact expand_order exp (by simp [ka'.1,ka'.2,kb'.1,kb'.2]) ordertheorem expand_right (exp : Expansion v e kept) (hr : 1 < r) (cap : P455Closure.Cap r (v.flatMap e)){ts : Tiles} {a b : Node} (q : Holds r allow mark v (rightward ts a b)) :Holds r allow mark (v.flatMap e) (rightward ts a b) := byhave p := q.2.1exact ⟨q.1,expand_port exp hr cap p,expand_earlier exp (kept_roles exp hr cap p.1 _ (by simp [roles]))(kept_roles exp hr cap p.2.1 _ (by simp [roles])) q.2.2.1,True.intro⟩theorem expand_down (exp : Expansion v e kept) (hr : 1 < r) (cap : P455Closure.Cap r (v.flatMap e)){ts : Tiles} {a b : Node} (q : Holds r allow mark v (downward ts a b)) :Holds r allow mark (v.flatMap e) (downward ts a b) := ⟨q.1,expand_port exp hr cap q.2⟩theorem expand_neighbor (exp : Expansion v e kept) (hr : 1 < r) (cap : P455Closure.Cap r (v.flatMap e)){ts : Tiles} {a b : Node} (d : Dir) (q : Holds r allow mark v (neighbor ts a b d)) :Holds r allow mark (v.flatMap e) (neighbor ts a b d) := bycases d with| right => exact expand_right exp hr cap q| left => exact expand_right exp hr cap q| down => exact expand_down exp hr cap q| up => exact expand_down exp hr cap qprivate theorem flag {b : Bool} {q : Query}(f : Holds r allow mark v q → Holds r allow mark (v.flatMap e) q)(h : Holds r allow mark v (flagQ b q)) : Holds r allow mark (v.flatMap e) (flagQ b q) := bycases b· exact True.intro· exact f htheorem expand_edge (exp : Expansion v e kept) (hr : 1 < r) (cap : P455Closure.Cap r (v.flatMap e)){ts : Tiles} {edge : EdgeCertificate} (query : Holds r allow mark v (edge.query ts)) :Holds r allow mark (v.flatMap e) (edge.query ts) := byobtain ⟨a,b,localQ,succ,_⟩ := queryrefine ⟨expand_markedNode exp hr cap a,expand_markedNode exp hr cap b,?_,?_,True.intro⟩· exact ⟨flag (expand_right exp hr cap) localQ.1,flag (expand_right exp hr cap) localQ.2.1,flag (expand_down exp hr cap) localQ.2.2.1,flag (expand_down exp hr cap) localQ.2.2.2.1,flag (fun ⟨d,r⟩ => ⟨expand_down exp hr cap d,expand_right exp hr cap r⟩) localQ.2.2.2.2.1,True.intro⟩· have ka : kept edge.a.owner := kept_roles exp hr cap (marked_typed a) _ (by simp [roles])have kb : kept edge.b.owner := kept_roles exp hr cap (marked_typed b) _ (by simp [roles])unfold chosenSuccessor at succ ⊢dsimp only at succ ⊢split at succnext ret =>rw [if_pos ret]exact ⟨succ.1,succ.2.1.elim (fun f => Or.inl (expand_port exp hr cap f))(fun b => Or.inr (expand_port exp hr cap b)),expand_earlier exp kb ka succ.2.2.1,True.intro⟩next notRet =>rw [if_neg notRet]exact ⟨succ.1,expand_earlier exp ka kb succ.2⟩endend P455OriginalEdgesend/- Begin Problem455Compression (from finite-semigroup-identity-bases). -/sectionnamespace P455Compressionopen P455Witness P455Retainedinductive Piece where| literal (a : Nat)| gap (w : W)deriving DecidableEqdef body : Piece → W | .literal a => [a] | .gap w => wdef prependOutside (a : Nat) : List Piece → List Piece| .gap w :: tail => .gap (a::w) :: tail| cs => .gap [a] :: csdef pieces (names : W) : W → List Piece| [] => []| a :: u =>let rest := pieces names uif a ∈ names then .literal a :: rest else prependOutside a restdef good (names : W) : Piece → Prop| .literal a => a ∈ names| .gap w => w ≠ [] ∧ ∀ a ∈ w, a ∉ names/-- Adjacency of gap pieces is prohibited; with good and exact decoding thisexpresses maximality of every omitted run, also at the two ends. -/def noTouch : List Piece → Prop| .gap _ :: .gap _ :: _ => False| _ :: tail => noTouch tail| [] => Trueprivate theorem prepend_body (a : Nat) (cs : List Piece) :(prependOutside a cs).flatMap body = a :: cs.flatMap body := bycases cs with| nil => rfl| cons p tail => cases p <;> rfltheorem decoded (names u : W) : (pieces names u).flatMap body = u := byinduction u with| nil => rfl| cons a u ih =>by_cases c : a ∈ names· simp [pieces,c,body,ih]· simp [pieces,c,prepend_body,ih]private theorem prepend_good {a : Nat} {cs : List Piece} {names : W} (ha : a ∉ names)(all : ∀ c ∈ cs, good names c) : ∀ c ∈ prependOutside a cs, good names c := bycases cs with| nil => simp [prependOutside,good,ha]| cons p tail =>cases p with| literal b => simp [prependOutside,good,ha] at *; exact all| gap w =>have h := all (.gap w) (by simp)simp only [good] at hsimp only [prependOutside,List.forall_mem_cons,good,List.cons_ne_nil,not_false_eq_true,true_and]exact ⟨⟨by simp,ha,h.2⟩,fun c hc => all c (by simp [hc])⟩theorem pieces_good (names u : W) : ∀ c ∈ pieces names u, good names c := byinduction u with| nil => simp [pieces]| cons a u ih =>by_cases k : a ∈ names· simp only [pieces,if_pos k,List.forall_mem_cons]exact ⟨k,ih⟩· simpa only [pieces,if_neg k] using prepend_good k ihprivate theorem prepend_sep {cs : List Piece} (a : Nat) (ok : noTouch cs) :noTouch (prependOutside a cs) := bycases cs with| nil => exact True.intro| cons p tail =>cases p with| literal b => exact ok| gap w => cases tail with| nil => exact True.intro| cons p' rest => cases p' <;> exact oktheorem maximal (names u : W) : noTouch (pieces names u) := byinduction u with| nil => exact True.intro| cons a u ih =>by_cases k : a ∈ names· simpa only [pieces,if_pos k,noTouch] using ih· simpa only [pieces,if_neg k] using prepend_sep a ih/-- The numerical bound counts even retained names not occurring in u. -/def base (u names : W) := u.sum + names.sum + 1private theorem le_sum {a : Nat} {w : W} (ha : a ∈ w) : a ≤ w.sum := byinduction w with| nil => simp at ha| cons b w ih =>simp only [List.sum_cons]rcases List.mem_cons.mp ha with h|h· omega· have := ih h; omegadef code : Nat → List Piece → W| _,[] => []| n,.literal a :: cs => a :: code (n+1) cs| n,.gap _ :: cs => n :: code (n+1) csdef lookup : Nat → List Piece → Nat → W| _,[],a => [a]| n,.literal _ :: cs,a => lookup (n+1) cs a| n,.gap w :: cs,a => if a=n then w else lookup (n+1) cs adef small (u names : W) := code (base u names) (pieces names u)def expand (u names : W) := lookup (base u names) (pieces names u)private theorem low_fixed (cs : List Piece) (a n : Nat) (low : a < n) :lookup n cs a = [a] := byinduction cs generalizing n with| nil => rfl| cons p cs ih =>cases p <;> simp [lookup,show a ≠ n by omega,ih (n+1) (by omega)]private theorem low_kept (cs : List Piece) (names : W)(all : ∀ c ∈ cs, good names c) (a n : Nat) (low : a < n) (use : a ∈ code n cs) :a ∈ names := byinduction cs generalizing n with| nil => cases use| cons c cs ih =>have rest := ih (fun c hc => all c (by simp [hc])) (n+1) (by omega)cases c with| literal b =>rcases List.mem_cons.mp use with eq|mem· obtain rfl := eq; exact all (.literal a) (by simp)· exact rest mem| gap w =>rcases List.mem_cons.mp use with eq|mem· omega· exact rest memprivate theorem decode_code (cs : List Piece) (names : W) (n : Nat)(all : ∀ c ∈ cs, good names c) (large : ∀ a ∈ names, a < n) :(code n cs).flatMap (lookup n cs) = cs.flatMap body := byinduction cs generalizing n with| nil => rfl| cons c cs ih =>have goodTail (p) (hp : p ∈ cs) : good names p := all _ (by simp [hp])have tail := ih (n+1) goodTail (fun a ha => by have := large a ha; omega)cases c with| literal a =>have low := large a (all (.literal a) (by simp))simp [code,lookup,low_fixed cs a (n+1) (by omega),body,tail]| gap w =>have miss : n ∉ code (n+1) cs := byintro hhave := large n (low_kept cs names goodTail n (n+1) (by omega) h)omegahave eq : (code (n+1) cs).flatMap (lookup n (.gap w :: cs)) =(code (n+1) cs).flatMap (lookup (n+1) cs) := bysimp only [List.flatMap_def]apply congrArg List.flattenexact List.map_congr_left (fun a ha => byhave dif : a ≠ n := fun d => miss (d ▸ ha)simp [lookup,dif])change lookup n (.gap w::cs) n ++ (code (n+1) cs).flatMap _ = w ++ cs.flatMap bodyrw [eq,tail]simp [lookup]private theorem gap_code (cs : List Piece) (names : W) (n : Nat)(all : ∀ c ∈ cs, good names c) (large : ∀ a ∈ names, a < n) :∀ g ∈ code n cs, g ∉ names →(code n cs).count g = 1 ∧ lookup n cs g ≠ [] ∧ ∀ a ∈ lookup n cs g, a ∉ names := byinduction cs generalizing n with| nil => simp [code]| cons c cs ih =>intro g use outsidehave goodTail (p) (hp : p ∈ cs) : good names p := all _ (by simp [hp])have tail := ih (n+1) goodTail (fun a ha => by have := large a ha; omega) gcases c with| literal a =>have dif : g ≠ a := fun d => outside (d ▸ all (.literal a) (by simp))have occurs : g ∈ code (n+1) cs := by simpa [code,dif] using usesimpa [code,lookup,List.count_cons,dif,Ne.symm dif] using tail occurs outside| gap w =>by_cases same : g=n· subst ghave miss : n ∉ code (n+1) cs := fun u =>outside (low_kept cs names goodTail n (n+1) (by omega) u)have gw := all (.gap w) (by simp)simpa [code,lookup,List.count_cons,List.count_eq_zero.mpr miss,good] using gw· have occurs : g ∈ code (n+1) cs := by simpa [code,same] using usesimpa [code,lookup,List.count_cons,same,Ne.symm same] using tail occurs outsidetheorem recover (u names : W) : (small u names).flatMap (expand u names) = u :=(decode_code (pieces names u) names (base u names) (pieces_good names u)(fun a h => by have := le_sum h; unfold base; omega)).trans (decoded names u)theorem canonical (u names : W) : Expansion (small u names) (expand u names) (fun a => a ∈ names) whereliteral x _ kept := low_fixed _ _ _ (by have := le_sum kept; unfold base; omega)gaps := gap_code (pieces names u) names (base u names) (pieces_good names u)(fun a h => by have := le_sum h; unfold base; omega)/-- Every generated gap name lies outside the original alphabet. -/theorem gap_fresh (u names : W) (g : Nat) (use : g ∈ small u names) (unkept : g ∉ names) : g ∉ u := byintro origapply unkeptapply low_kept (pieces names u) names (pieces_good names u) g (base u names) _ usehave := le_sum origunfold base; omegatheorem counts_retained (u names : W) (x : Nat) (hx : x ∈ names) :(small u names).count x = u.count x := byhave c := (canonical u names).count_eq (small u names) (fun _ h => h) x hxrw [recover] at cexact c.symmend P455Compressionend/- Begin Problem455DefectProjection (from finite-semigroup-identity-bases). -/sectionnamespace P455DefectProjectionopen P455Witness P455Paths P455SourceFamilies Problem455.Slotstheorem select_sub (keep smaller u : W) (hs : ∀ a ∈ smaller, a ∈ keep) :select smaller (select keep u) = select smaller u := byinduction u with| nil => rfl| cons x u ih =>by_cases hx : x ∈ keep· by_cases hm : x ∈ smaller <;> simp_all [select]· have hm : x ∉ smaller := fun h => hx (hs _ h)simp_all [select]theorem select_count (keep u : W) (a : Nat) (mem : a ∈ keep) :(select keep u).count a = u.count a :=List.count_filter (by simpa using mem)theorem select_cap {r u} (keep : W) (cap : P455Closure.Cap r u) :P455Closure.Cap r (select keep u) := byintro aby_cases mem : a ∈ keep· simpa only [select_count keep u _ mem] using cap a· have missing : a ∉ select keep u := by simp [select,mem]simp [List.count_eq_zero.mpr missing]theorem select_order {r allow mark u} (keep : W) (pat : List Event)(hs : ∀ e ∈ pat, e.1 ∈ keep) (obs : Holds r allow mark u (.order pat)) :Holds r allow mark (select keep u) (.order pat) :=⟨obs.1, P455ContactReflection.sees_select keep u pat hs obs.2⟩theorem select_marked {r allow mark u} (keep : W) (n : Node) (b : Bool)(ho : n.owner ∈ keep) (hm : n.mate ∈ keep) (obs : Holds r allow mark u (markedNode n b)) :Holds r allow mark (select keep u) (markedNode n b) := byobtain ⟨ne,len,tag,mk,eq⟩ := obsrefine ⟨ne,len,tag,mk,(select_sub keep [n.owner,n.mate] u ?_).trans eq⟩simpa using And.intro ho hmtheorem select_record {r allow mark u} (keep : W) (a b : Nat) (tag : Tag) (ha : a ∈ keep)(hb : b ∈ keep) (obs : Holds r allow mark u (.record a b tag)) :Holds r allow mark (select keep u) (.record a b tag) := byobtain ⟨ne,len,ok,bit,eq⟩ := obsexact ⟨ne,len,ok,bit,(select_sub keep [a,b] u (by simpa using And.intro ha hb)).trans eq⟩theorem select_contact {r allow mark u} (keep : W) (a b : Nat) (c : ContactChoice)(ha : a ∈ keep) (hb : b ∈ keep) (obs : Holds r allow mark u (contact r a b c)) :Holds r allow mark (select keep u) (contact r a b c) := bycases c with| record tag rev =>cases rev with| false => exact select_record keep a b tag ha hb obs| true => exact select_record keep b a tag hb ha obs| port phase rev =>obtain ⟨ab,ac,bc,early,order,endQ⟩ := obsrefine ⟨ab,(select_count keep u a ha).trans ac,(select_count keep u b hb).trans bc,?_,?_,endQ⟩· rcases early with ⟨f,_⟩|⟨f,_⟩· exact .inl ⟨select_order keep _ (by simpa using And.intro ha hb) f,True.intro⟩· exact .inr ⟨select_order keep _ (by simpa using And.intro hb ha) f,True.intro⟩· cases rev <;> apply select_order keep _ _ order <;> simp [ha,hb]theorem select_walk {r allow mark u} (keep : W) (a : Nat) (p : List Step)(ha : a ∈ keep) (hs : ∀ m ∈ p, m.1 ∈ keep) (w : Walk r allow mark u a p) :Walk r allow mark (select keep u) a p := byinduction p generalizing a with| nil => trivial| cons bc rest ih =>obtain ⟨b,c⟩ := bchave hb := hs (b,c) (by simp)exact ⟨select_contact keep a b c ha hb w.1,ih b hb (fun s h => hs s (by simp [h])) w.2⟩theorem endpoint_kept (keep : W) (a : Nat) (p : List Step) (ha : a ∈ keep)(hs : ∀ m ∈ p, m.1 ∈ keep) : endpoint a p ∈ keep := byinduction p generalizing a with| nil => exact ha| cons bc p ih => exact ih bc.1 (hs bc (by simp)) (fun s h => hs s (by simp [h]))theorem select_slot {u : W} (keep : W) (t i b : Nat)(ht : t ∈ keep) (hb : b ∈ keep) (obs : occupies u t i b) :occupies (select keep u) t i b := byobtain ⟨j,h⟩ := obsexact ⟨j,P455ContactReflection.sees_select keep u _ (by simp [hb,ht]) h⟩/-- A genuine slot component of alphabet size at most nine suffices for adeficient occupant. The cap and all unchanged occurrence indices arederived in the projection. Both orientations and length-zero routesare allowed; the keep list can repeat names. -/theorem bounded_defect_kind {r allow mark u} (cap : P455Closure.Cap r u) (n : Node) (bit side : Bool)(t i bad : Nat) (anchor : Holds r allow (markNode n) u (markedNode n bit))(near : Near r allow mark u (if side then n.mate else n.owner) t 6)(slot : slotStart i) (occ : occupies u t i bad) (deficient : u.count bad < r) :∃ (keep : W) (s : SlotCertificate), keep.length ≤ 9 ∧ n.owner ∈ keep ∧ n.mate ∈ keep ∧bad ∈ keep ∧ s.defect = .deficient bad ∧ s.anchor = n ∧ s.bit = bit ∧ P455Closure.Cap r (select keep u) ∧Holds r allow (markNode n) (select keep u) (s.query r) := bylet a := if side then n.mate else n.ownerobtain ⟨p,w,ep,len⟩ := nearlet keep := n.owner :: n.mate :: bad :: p.map Prod.fsthave h1 : n.owner ∈ keep := by simp [keep]have h2 : n.mate ∈ keep := by simp [keep]have h3 : bad ∈ keep := by simp [keep]have start : a ∈ keep := by cases side <;> simp [a,h1,h2]have ins : ∀ m ∈ p, m.1 ∈ keep := fun m hm => by simp [keep,List.mem_map_of_mem hm]have last : t ∈ keep := ep ▸ endpoint_kept keep a p start inslet s : SlotCertificate := ⟨n,bit,side,p,i,.deficient bad⟩refine ⟨keep,s,by simpa [keep] using (show p.length + 3 ≤ 9 by omega),h1,h2,h3,rfl,rfl,rfl,select_cap keep cap,select_marked keep n bit h1 h2 anchor,len,?_,True.intro⟩apply (route_iff ..).mprrefine ⟨remark_walk _ _ (select_walk keep a p start ins w),?_⟩change (slotStart i ∧ occupies (select keep u) (endpoint a p) i bad) ∧ (select keep u).count bad < rrw [show endpoint a p = t from ep, select_count keep u bad h3]exact ⟨⟨slot,select_slot keep t i bad last h3 occ⟩,deficient⟩theorem bounded_defect {r allow mark u} (cap : P455Closure.Cap r u) (n : Node) (bit side : Bool)(t i bad : Nat) (anchor : Holds r allow (markNode n) u (markedNode n bit))(near : Near r allow mark u (if side then n.mate else n.owner) t 6)(slot : slotStart i) (occ : occupies u t i bad) (deficient : u.count bad < r) :∃ (keep : W) (s : SlotCertificate), keep.length ≤ 9 ∧ n.owner ∈ keep ∧ n.mate ∈ keep ∧s.anchor = n ∧ s.bit = bit ∧ P455Closure.Cap r (select keep u) ∧Holds r allow (markNode n) (select keep u) (s.query r) := byobtain ⟨keep,s,len,ho,hm,_,_,anc,bs,cp,h⟩ :=bounded_defect_kind cap n bit side t i bad anchor near slot occ deficientexact ⟨keep,s,len,ho,hm,anc,bs,cp,h⟩end P455DefectProjectionend/- Begin Problem455FirstRewrite (from finite-semigroup-identity-bases). -/sectionnamespace P455FirstRewriteabbrev W := List Natabbrev Sub := Nat → Wdef Step (G : W → W → Prop) (A B : W) : Prop :=∃ (u v p q : W) (h : Sub), (G u v ∨ G v u) ∧ u ≠ [] ∧ v ≠ [] ∧(∀ x, h x ≠ []) ∧ A = p ++ u.flatMap h ++ q ∧ B = p ++ v.flatMap h ++ qabbrev Derives (G : W → W → Prop) := P455Quotient.Walk (Step G)/-- A deduction entirely in a two-word class contains an actual one-stepinstance from the initial to the other word. Self steps may occur anywhere. -/theorem first_change {G : W → W → Prop} {A B : W} (ne : A ≠ B)(two : ∀ w, Derives G A w → w = A ∨ w = B) (path : Derives G A B) : Step G A B := bysuffices go : ∀ w, Derives G A w → w = A ∨ Step G A B byexact (go B path).resolve_left ne.symmintro w walkinduction walk with| refl => exact Or.inl rfl| @snoc v w prev step ih =>rcases ih with h | done· rcases two w (.snoc prev step) with f | f· exact Or.inl f· exact Or.inr (h ▸ f ▸ step)· exact Or.inr donedef proj (a b : Nat) (w : W) : W := w.filter (fun x => decide (x = a ∨ x = b))private theorem proj_append (a b : Nat) (p q : W) :proj a b (p ++ q) = proj a b p ++ proj a b q := List.filter_append p qprivate theorem filter_erase (f : Nat → Bool) (a : Nat) (w : W) :(w.erase a).filter f = (w.filter f).erase a := byinduction w with| nil => rfl| cons x xs ih =>by_cases e : x = a· subst xby_cases h : f a = true· simp [h]· have n : a ∉ xs.filter f := by simp [h]simp [h, List.erase_of_not_mem n]· by_cases h : f x = true <;> simp [List.erase_cons, e, h, ih]private theorem first_split {a : Nat} {v : W} (mem : a ∈ v) :∃ L R : W, v = L ++ a :: R ∧ a ∉ L := byinduction v with| nil => simp at mem| cons z zs ih =>by_cases e : z = a· subst z; exact ⟨[],zs,rfl,by simp⟩· obtain ⟨l,r,f,n⟩ := ih ((List.mem_cons.mp mem).resolve_left (Ne.symm e))exact ⟨z::l,r,by simp [f],by simp [Ne.symm e,n]⟩private theorem prefix_head {a z : Nat} {L : W} (n : a ∉ L) (m : z ∈ L) :∃ t, proj a z L = z :: t := byinduction L with| nil => simp at m| cons c L ih =>have ca : c ≠ a := fun e => n (e ▸ List.mem_cons_self)by_cases cz : c = z· subst c; exact ⟨proj a z L,by simp [proj]⟩· have mz := (List.mem_cons.mp m).resolve_left (Ne.symm cz)obtain ⟨t,e⟩ := ih (fun h => n (List.mem_cons_of_mem c h)) mzexact ⟨t, by simpa [proj,ca,cz] using e⟩private theorem flatten_commute (g : Sub) (a : Nat) (L : W)(ok : ∀ z ∈ L, g a ++ g z = g z ++ g a) :g a ++ L.flatMap g = L.flatMap g ++ g a := byinduction L with| nil => simp| cons z L ih =>have tail := ih (fun x h => ok x (List.mem_cons_of_mem z h))have head := ok z (List.mem_cons_self)simp only [List.flatMap_cons]calc_ = (g a ++ g z) ++ L.flatMap g := (List.append_assoc ..).symm_ = (g z ++ g a) ++ L.flatMap g := by rw [head]_ = _ := by simp only [List.append_assoc,tail]/-- Multiplicities and two-letter projections of all pairs with noncommutingimages determine the whole substituted word, even for erasing substitutions. -/theorem trace {u v : W} (g : Sub) (counts : ∀ x, u.count x = v.count x)(pairs : ∀ i j, g i ++ g j ≠ g j ++ g i → proj i j u = proj i j v) :u.flatMap g = v.flatMap g := byinduction u generalizing v with| nil =>cases v with| nil => rfl| cons b t => simpa using counts b| cons a u ih =>have m : a ∈ v := List.count_pos_iff.mp (by rw [← counts]; simp)obtain ⟨L,R,rfl,n⟩ := first_split mhave cross (z) (mz : z ∈ L) : g a ++ g z = g z ++ g a := byapply Classical.byContradictionintro badhave pair := pairs a z badobtain ⟨t,eq⟩ := prefix_head n mzrw [proj_append,eq] at pairhave az : a = z := by simpa [proj] using congrArg List.head? pairexact n (az ▸ mz)have er : (L ++ a :: R).erase a = L ++ R := byrw [List.erase_append_right _ n, List.erase_cons_head]have cnt (x) : u.count x = (L ++ R).count x := byhave orig := counts xsimp only [List.count_append,List.count_cons] at orig ⊢omegahave rest (i j) (bad : g i ++ g j ≠ g j ++ g i) : proj i j u = proj i j (L ++ R) := byhave eq := congrArg (fun w : W => w.erase a) (pairs i j bad)unfold proj at eqrw [← filter_erase, ← filter_erase, List.erase_cons_head, er] at eqexact eqhave sub := ih cnt restsimp only [List.flatMap_cons,List.flatMap_append] at sub ⊢calc_ = g a ++ (L.flatMap g ++ R.flatMap g) := by rw [sub]_ = _ := by rw [← List.append_assoc, flatten_commute g a L cross, List.append_assoc]/-- The two tester consequences required of a rule in the chosen orientation.Clipping at r+1 records the overflow class. -/structure TesterRule (r : Nat) (u v : W) : Prop whereunary : ∀ x, min (u.count x) (r+1) = min (v.count x) (r+1)binary : P455Quotient.Cap r u → P455Quotient.Cap r v →∀ i j, proj i j u ≠ proj i j v → u.count i = r ∧ u.count j = rprivate theorem cap_rule {r : Nat} {p q u : W} {h : Sub} (ne : ∀ x, h x ≠ [])(cap : P455Quotient.Cap r (p ++ u.flatMap h ++ q)) : P455Quotient.Cap r u := byintro xobtain ⟨a,hm⟩ : ∃ a, a ∈ h x := bycases e : h x with| nil => exact False.elim (ne x e)| cons a t => exact ⟨a,List.mem_cons_self⟩have pos := List.count_pos_iff.mpr hmhave mul := Nat.mul_le_mul_left (u.count x) poshave ct := P455DonorInterval.split_contributions h u x ahave bound := cap asimp only [List.count_append] at boundsimp only [Nat.mul_one] at mulomegaprivate theorem counted_edge (h : Sub) (x a b : Nat)(pos : 0 < Problem455Swap.bigram a b (h x)) (u : W) :u.count x ≤ Problem455Swap.bigram a b (u.flatMap h) := byinduction u with| nil => simp [Problem455Swap.bigram]| cons z u ih =>simp only [List.flatMap_cons,Problem455Swap.bigram_append]by_cases e : z = x· subst z; simp [List.count_cons]; omega· simp [List.count_cons,e]; omegaprivate theorem singleton {r : Nat} {p q u : W} {h : Sub}(ne : ∀ x, h x ≠ []) (cap : P455Quotient.Cap r (p ++ u.flatMap h ++ q))(compressed : P455SourceFamilies.Compressed r (p ++ u.flatMap h ++ q)){x : Nat} (sat : u.count x = r) : ∃ a, h x = [a] := bycases e : h x with| nil => exact False.elim (ne x e)| cons a t =>cases t with| nil => exact ⟨a,rfl⟩| cons b tail =>have edge : 0 < Problem455Swap.bigram a b (h x) := byrw [e]; simp [Problem455Swap.bigram,Problem455Swap.hit] <;> omegahave lo := counted_edge h x a b edge ulet U := p ++ u.flatMap h ++ qhave lower : r ≤ Problem455Swap.bigram a b U := bydsimp [U]; rw [Problem455Swap.bigram_append,Problem455Swap.bigram_append]; omegahave upper := Problem455Swap.out_bound a b (b+1) (by omega) Urw [Problem455BlockBridge.occ_count] at upperhave hc : U.count a ≤ r := cap aexact False.elim (compressed a b (by change Problem455Swap.bigram a b U = r; omega))private theorem project_images (a b : Nat) (u : W) (h : Sub) :proj a b (u.flatMap h) = u.flatMap (fun x => proj a b (h x)) := byinduction u with| nil => rfl| cons x u ih => simp only [List.flatMap_cons,proj_append,ih]private theorem projected_commutes_without (a b c d : Nat) (ca : c ≠ a) (da : d ≠ a) :proj a b [c] ++ proj a b [d] = proj a b [d] ++ proj a b [c] := byby_cases cb : c = b <;> by_cases db : d = b <;> simp_all [proj]/-- Every literal name in a changed binary projection is the singleton imageof an actual matched-side rule variable. This uses no occurrence indexing. -/theorem changed_name {r : Nat} (hr : 0 < r) {p q u v : W} {h : Sub}(ne : ∀ x, h x ≠ []) (cap : P455Quotient.Cap r (p ++ u.flatMap h ++ q))(compressed : P455SourceFamilies.Compressed r (p ++ u.flatMap h ++ q))(rule : TesterRule r u v) (a b : Nat)(changed : proj a b (p ++ u.flatMap h ++ q) ≠ proj a b (p ++ v.flatMap h ++ q)) :∃ x ∈ u, h x = [a] := byhave cu := cap_rule ne caphave counts (x) : u.count x = v.count x := byhave eq := rule.unary xhave bound := cu xomegahave cv : P455Quotient.Cap r v := fun x => counts x ▸ cu xlet g : Sub := fun x => proj a b (h x)apply Classical.byContradictionintro absentapply changedsimp only [proj_append,project_images]have pair (i j) (bad : g i ++ g j ≠ g j ++ g i) : proj i j u = proj i j v := byapply Classical.byContradictionintro diffobtain ⟨ci,cj⟩ := rule.binary cu cv i j diffobtain ⟨c,ec⟩ := singleton ne cap compressed ciobtain ⟨d,ed⟩ := singleton ne cap compressed cjhave mi : i ∈ u := List.count_pos_iff.mp (ci ▸ hr)have mj : j ∈ u := List.count_pos_iff.mp (cj ▸ hr)have ca : c ≠ a := fun e => absent ⟨i,mi,ec.trans (e ▸ rfl)⟩have da : d ≠ a := fun e => absent ⟨j,mj,ed.trans (e ▸ rfl)⟩apply badsimpa [g,ec,ed] using projected_commutes_without a b c d ca darw [show u.flatMap (fun x => proj a b (h x)) = v.flatMap (fun x => proj a b (h x))from trace g counts pair]/-- A list of distinct names included in an arbitrary covering list gives anumeric lower bound on its length, even if that covering list contains repeats. -/theorem size_le {D C : W} (uniq : D.Nodup) (sub : ∀ a ∈ D, a ∈ C) : D.length ≤ C.length := byinduction D generalizing C with| nil => simp| cons a t ih =>obtain ⟨fresh,tail⟩ := List.nodup_cons.mp uniqhave mem := sub a List.mem_cons_selfhave le := ih tail (C := C.erase a) (fun x hx =>(List.mem_erase_of_ne (a := x) (b := a) (fun e => fresh (e ▸ hx))).mpr (sub x (List.mem_cons_of_mem _ hx)))have len := List.length_erase_of_mem memhave pos : 0 < C.length := by cases C <;> simp_allsimp only [List.length_cons]omega/-- Any explicit list of rule variables covering the matched side must haveat least as many entries as there are distinct literal participants. -/theorem instance_rank {r : Nat} (hr : 0 < r) {p q u v D C : W} {h : Sub}(ne : ∀ x, h x ≠ []) (cap : P455Quotient.Cap r (p ++ u.flatMap h ++ q))(compressed : P455SourceFamilies.Compressed r (p ++ u.flatMap h ++ q))(rule : TesterRule r u v) (uniq : D.Nodup) (cover : ∀ x ∈ u, x ∈ C)(changes : ∀ a ∈ D, ∃ b, proj a b (p ++ u.flatMap h ++ q) ≠proj a b (p ++ v.flatMap h ++ q)) : D.length ≤ C.length := byhave sub (a) (ma : a ∈ D) : a ∈ C.map (fun x => (h x).headD 0) := byobtain ⟨b,diff⟩ := changes a maobtain ⟨x,mx,e⟩ := changed_name hr ne cap compressed rule a b diffexact List.mem_map.mpr ⟨x,cover x mx,by simp [e]⟩simpa using size_le uniq sub/-- The list of distinct variables of an oriented rule pair. -/def names : W → W| [] => []| x :: w => if x ∈ w then names w else x :: names w@[simp] theorem mem_names (a : Nat) (w : W) : a ∈ names w ↔ a ∈ w := byinduction w with| nil => simp [names]| cons x w ih =>by_cases e : x ∈ w· simp only [names,if_pos e,ih,List.mem_cons]exact ⟨Or.inr, fun h => h.elim (fun eq => eq ▸ e) id⟩· simp [names,e,ih]theorem names_distinct (w : W) : (names w).Nodup := byinduction w with| nil => simp [names]| cons x w ih => by_cases e : x ∈ w <;> simp [names,e,ih]def rank (u v : W) := (names (u ++ v)).lengththeorem rank_swap (u v : W) : rank u v = rank v u := byapply Nat.le_antisymm· apply size_le (names_distinct _)simp [List.mem_append,Or.comm]· apply size_le (names_distinct _)simp [List.mem_append,Or.comm]/-- This is the usual semigroup-word semantics in a monoid. The operationalone occurs in rule terms. Empty contexts use the unit when evaluated. -/structure Model (A : Type) whereop : A → A → Aunit : Aassoc : ∀ x y z, op (op x y) z = op x (op y z)oneL : ∀ x, op unit x = xoneR : ∀ x, op x unit = xnamespace Modelvariable {A : Type} (M : Model A)def eval (f : Nat → A) : W → A| [] => M.unit| x :: xs => M.op (f x) (eval f xs)def Valid (u v : W) := ∀ f, M.eval f u = M.eval f vtheorem eval_append (f : Nat → A) (u v : W) :M.eval f (u ++ v) = M.op (M.eval f u) (M.eval f v) := byinduction u with| nil => simp [eval,M.oneL]| cons x t ih => simp [eval,ih,M.assoc]theorem eval_instance (f : Nat → A) (h : Sub) (w : W) :M.eval f (w.flatMap h) = M.eval (fun x => M.eval f (h x)) w := byinduction w with| nil => rfl| cons x t ih => simp [eval,eval_append,ih]theorem step_sound {G : W → W → Prop} (valid : ∀ u v, G u v → M.Valid u v){U V : W} (s : Step G U V) : M.Valid U V := byobtain ⟨u,v,p,q,h,orient,_,_,_,rfl,rfl⟩ := sintro fsimp only [M.eval_append,M.eval_instance]rcases orient with g | g· rw [valid u v g]· rw [valid v u g]theorem derives_sound {G : W → W → Prop} (valid : ∀ u v, G u v → M.Valid u v){U V : W} (walk : Derives G U V) : M.Valid U V := byinduction walk with| refl => intro _; rfl| snoc _ st ih => exact fun f => (ih f).trans (M.step_sound valid st f)end Model/-- Hypotheses on one actual pair of witness words; validity of thedistinguished identity and exhaustion of its semantic class are separate. -/structure RankWitness {A : Type} (M : Model A) (r : Nat) (U V D : W) : Prop wherenonempty : U ≠ [] ∧ V ≠ []different : U ≠ Videntity : M.Valid U Vtwo : ∀ w, M.Valid U w → w = U ∨ w = Vcap : P455Quotient.Cap r Ucompressed : P455SourceFamilies.Compressed r Udistinct : D.Nodupparticipants : ∀ a ∈ D, ∃ b, proj a b U ≠ proj a b V/-- Every actual step which first leaves U has rule rank at least |D|. -/theorem step_rank {A : Type} {M : Model A} {r : Nat} (hr : 0 < r){U V D : W} (wit : RankWitness M r U V D)(testers : ∀ u v, M.Valid u v → TesterRule r u v){G : W → W → Prop} (valid : ∀ u v, G u v → M.Valid u v) {T : W}(s : Step G U T) (diff : U ≠ T) :∃ u v, G u v ∧ D.length ≤ rank u v := byhave iden := M.step_sound valid shave direct := (wit.two T iden).resolve_left diff.symmsubst Tobtain ⟨u,v,p,q,h,oriented,_,_,ne,eq1,eq2⟩ := shave vr : M.Valid u v := oriented.elim (valid u v) (fun rev f => (valid v u rev f).symm)have cover (x) (m : x ∈ u) : x ∈ names (u ++ v) := by simp [m]have bound : D.length ≤ rank u v := byapply instance_rank hr ne (eq1 ▸ wit.cap) (eq1 ▸ wit.compressed) (testers _ _ vr)wit.distinct coversimpa only [← eq1, ← eq2] using wit.participantsrcases oriented with forward | backward· exact ⟨u,v,forward,bound⟩· exact ⟨v,u,backward,rank_swap u v ▸ bound⟩theorem derivation_rank {A : Type} {M : Model A} {r : Nat} (hr : 0 < r){U V D : W} (wit : RankWitness M r U V D)(testers : ∀ u v, M.Valid u v → TesterRule r u v){G : W → W → Prop} (valid : ∀ u v, G u v → M.Valid u v) (path : Derives G U V) :∃ u v, G u v ∧ D.length ≤ rank u v :=step_rank hr wit testers valid (first_change wit.different(fun w walk => wit.two w (M.derives_sound valid walk)) path) wit.different/-- The monoid M is fixed before the padding bound is chosen. No assumptionabout the existence of an accepting computation or rectangle is encoded. -/theorem no_finite_basis_of_witnesses {A : Type} (M : Model A) (r : Nat) (hr : 0 < r)(testers : ∀ u v, M.Valid u v → TesterRule r u v)(witnesses : ∀ k : Nat, ∃ U V D, RankWitness M r U V D ∧ k < D.length)(G : List (W × W)) (valid : ∀ u v, (u,v) ∈ G → M.Valid u v) :∃ U V, U ≠ [] ∧ V ≠ [] ∧ M.Valid U V ∧ ¬ Derives (fun u v => (u,v) ∈ G) U V := bylet sizes := G.map (fun t => rank t.1 t.2)obtain ⟨U,V,D,w,large⟩ := witnesses sizes.sumrefine ⟨U,V,w.nonempty.1,w.nonempty.2,w.identity,?_⟩intro derivationobtain ⟨u,v,mem,bound⟩ := derivation_rank hr w testers valid derivationhave inSizes : rank u v ∈ sizes := List.mem_map.mpr ⟨(u,v),mem,rfl⟩have less (s : List Nat) (n) (m : n ∈ s) : n ≤ s.sum := byinduction s with| nil => simp at m| cons z t ih =>simp only [List.sum_cons]rcases List.mem_cons.mp m with e | m· omega· have := ih m; omegahave := less sizes (rank u v) inSizesomegaend P455FirstRewriteend/- Begin Problem455LiteralMovePrim (from finite-semigroup-identity-bases). -/section/- Primitive recursive literal-move search on standard natural-numberencodings, uniformly in the cap, tags and finitely stored mark relation. -/namespace P455FrameProofset_option maxHeartbeats 450000open P455Closure P455EffectiveQ P455GraphPrim P455FramePrimopen P455EffectiveQMove (capB frames entries validB moveB)variable {A B : Type} [Primcodable A] [Primcodable B]private theorem same_decision {p : Prop} (a b : Decidable p) : @decide p a = @decide p b := byrw [Subsingleton.elim a b]theorem forNames {l : A → List B} {pr : A → B → Prop} [d : ∀ a, DecidablePred (pr a)](hl : Primrec l) (hp : Primrec₂ fun a b => decide (pr a b)) : PrimrecPred fun a => ∀ b∈l a,pr a b := byapply Primrec.primrecPredapply (allB hl hp).of_eqintro aapply Bool.eq_iff_iff.mprsimp only [List.all_eq_true,decide_eq_true_eq]theorem capCheck {r : A → Nat} {w : A → W} (hr : Primrec r) (hw : Primrec w) :Primrec fun a => capB (r a) (w a) := byapply allB hwexact (Primrec.nat_le.comp (countN Primrec.snd (hw.comp Primrec.fst)) (hr.comp Primrec.fst)).decide.to₂theorem validity {r : A → Nat} {tags : A → List Tag} {marks : A → Marks} {f : A → Frame Nat}(hr : Primrec r) (ht : Primrec tags) (hm : Primrec marks) (hf : Primrec f) :Primrec fun a => validB (r a) (tags a) (fun x y => decide ((x,y)∈marks a)) (f a) := byunfold validBapply PrimrecPred.decidelet Fp := P455FramePrim.p.comp hflet Fq := P455FramePrim.q.comp hflet Ft := P455FramePrim.tag.comp hflet Fm := P455FramePrim.middle.comp hfhave apart : PrimrecPred (fun a => ∀ x∈(f a).p, x∉(f a).q) := byapply forNames Fpexact (PrimrecPred.not (contains Primrec.snd (Fq.comp Primrec.fst)).primrecPred).decide.to₂have marksOK : PrimrecPred (fun a => ∀ x∈(f a).p, ∀ y∈(f a).q,decide ((x,y)∈marks a)=false ∧ decide ((y,x)∈marks a)=false) := byapply forNames Fpapply Primrec₂.mkapply PrimrecPred.decideapply forNames (Fq.comp Primrec.fst)apply Primrec₂.mkhave old : Primrec (fun s : (A×Nat)×Nat => marks s.1.1) := (hm.comp Primrec.fst).comp Primrec.fsthave xy : Primrec (fun s : (A×Nat)×Nat => decide ((s.1.2,s.2)∈marks s.1.1)) :=(contains (Primrec.pair (Primrec.snd.comp Primrec.fst) Primrec.snd) old).of_eq (fun _ => same_decision _ _)have yx : Primrec (fun s : (A×Nat)×Nat => decide ((s.2,s.1.2)∈marks s.1.1)) :=(contains (Primrec.pair Primrec.snd (Primrec.snd.comp Primrec.fst)) old).of_eq (fun _ => same_decision _ _)exact (PrimrecPred.and (Primrec.eq.comp xy (.const false)) (Primrec.eq.comp yx (.const false))).decidehave saturated : PrimrecPred (fun a => ∀ x∈(f a).p++(f a).q, ((f a).core false).count x = r a) := byapply forNames (Primrec.list_append.comp Fp Fq)exact (Primrec.eq.comp (countN Primrec.snd ((P455FramePrim.core.comp hf (.const false)).comp Primrec.fst))(hr.comp Primrec.fst)).decide.to₂apply PrimrecPred.and (Primrec.eq.comp hr (Primrec.nat_add.comp (.const 16) (Primrec.list_length.comp Ft)))have member : Primrec (fun a => decide ((f a).tag ∈ tags a)) := (contains Ft ht).of_eq (fun _ => same_decision _ _)apply PrimrecPred.and member.primrecPredapply PrimrecPred.and (Primrec.eq.comp (Primrec.list_map Fm (Primrec.snd.comp₂ Primrec₂.right)) (phases.comp Ft))apply PrimrecPred.and (nodup Fp).primrecPredapply PrimrecPred.and (nodup Fq).primrecPredapply PrimrecPred.and apartapply PrimrecPred.and marksOKexact saturatedtheorem entriesRec {w : A → W} (hw : Primrec w) : Primrec fun a => entries (w a) := byapply Primrec.list_flatMap (wordPool.comp hw)apply Primrec₂.mkexact Primrec.list_cons.comp (Primrec.pair Primrec.snd (.const false))(singleton (Primrec.pair Primrec.snd (.const true)))private def choices {X Y : Type} (xs : List X) (ys : List Y) : List (X × Y) :=xs.flatMap fun x => ys.map fun y => (x,y)private theorem map_choices {X Y Z : Type} (xs : List X) (ys : List Y) (f : X × Y → Z) :(choices xs ys).map f = xs.flatMap fun x => ys.map fun y => f (x,y) := bysimp only [choices, List.map_flatMap, List.map_map, Function.comp_def]private theorem choices_rec {X Y : Type} [Primcodable X] [Primcodable Y]{xs : A → List X} {ys : A → List Y} (hx : Primrec xs) (hy : Primrec ys) :Primrec fun a => choices (xs a) (ys a) := byapply Primrec.list_flatMap hxapply Primrec₂.mkapply Primrec.list_map (hy.comp Primrec.fst)exact (Primrec.pair (Primrec.snd.comp Primrec.fst) Primrec.snd).to₂private abbrev Body := Nat × W × W × Nat × PairList × W × W × Wprivate def insertTag (t : Tag) (b : Body) : FrameData :=(b.1,b.2.1,b.2.2.1,b.2.2.2.1,t,b.2.2.2.2)private theorem insert_rec : Primrec₂ insertTag := byapply Primrec₂.mkhave tail1 : Primrec (fun s : Tag × Body => s.2.2) := Primrec.snd.comp Primrec.sndhave tail2 := Primrec.snd.comp tail1have tail3 := Primrec.snd.comp tail2have tail4 := Primrec.snd.comp tail3exact Primrec.pair (Primrec.fst.comp Primrec.snd) (Primrec.pair (Primrec.fst.comp tail1)(Primrec.pair (Primrec.fst.comp tail2) (Primrec.pair (Primrec.fst.comp tail3)(Primrec.pair Primrec.fst tail4))))theorem frameList {tags : A → List Tag} {w : A → W} (ht : Primrec tags) (hw : Primrec w) :Primrec fun a => frames (tags a) (w a) := byapply Primrec.list_flatMap htapply Primrec₂.mklet U : (A × Tag) → W := fun s => w s.1let S : (A × Tag) → List W := fun s => P455EffectiveQ.words (U s)let E : (A × Tag) → List PairList := fun s =>Problem455Finite.wordsUpTo (entries (U s)) (fixedPhases s.2).lengthhave hU : Primrec U := hw.comp Primrec.fsthave hS : Primrec S := wordPool.comp hUhave hE : Primrec E := wordsUpTo.comp (entriesRec hU) (Primrec.list_length.comp (phases.comp Primrec.snd))have bodies := choices_rec hU (choices_rec hS (choices_rec hS (choices_rec hU(choices_rec hE (choices_rec hS (choices_rec hS hS))))))have attach : Primrec₂ (fun (s : A × Tag) (b : Body) => packing.symm (insertTag s.2 b)) :=unpack.comp₂ (insert_rec.comp₂ (Primrec.snd.comp₂ Primrec₂.left) Primrec₂.right)apply (Primrec.list_map bodies attach).of_eqintro ssimp only [map_choices, insertTag, packing]rfltheorem literalMove {r : A → Nat} {tags : A → List Tag} {marks : A → Marks} {u v : A → W}(hr : Primrec r) (ht : Primrec tags) (hm : Primrec marks) (hu : Primrec u) (hv : Primrec v) :Primrec fun a => moveB (r a) (tags a) (fun x y => decide ((x,y)∈marks a)) (u a) (v a) := byapply Primrec.and.comp (Primrec.and.comp (Primrec.nat_le.comp hr (Primrec.list_length.comp hu)).decide (capCheck hr hu))apply anyB (frameList ht hu)apply Primrec₂.mkapply Primrec.and.comp (validity (hr.comp Primrec.fst) (ht.comp Primrec.fst) (hm.comp Primrec.fst) Primrec.snd)apply anyB (Primrec.const [false,true])apply Primrec₂.mkapply anyB (wordPool.comp ((hu.comp Primrec.fst).comp Primrec.fst))apply Primrec₂.mkapply anyB (wordPool.comp (((hu.comp Primrec.fst).comp Primrec.fst).comp Primrec.fst))apply Primrec₂.mklet C := ((((A × Frame Nat) × Bool) × W) × W)have f : Primrec (fun x : C => x.1.1.1.2) := (((Primrec.snd.comp Primrec.fst).comp Primrec.fst).comp Primrec.fst)have b : Primrec (fun x : C => x.1.1.2) := ((Primrec.snd.comp Primrec.fst).comp Primrec.fst)have l : Primrec (fun x : C => x.1.2) := (Primrec.snd.comp Primrec.fst)have t : Primrec (fun x : C => x.2) := Primrec.sndapply PrimrecPred.decideexact PrimrecPred.and(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))(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))end P455FrameProofend/- Begin Problem455MachineCleanup (from finite-semigroup-identity-bases). -/sectionnamespace P455MachineCleanupopen P455MachineLocal P455MachineTable P455PaddedTilesstructure Ordinary (g q : Nat) wheremarker : Fin gblank : Fin gblank_ne : blank≠markerstart : Fin qdelta : Fin q→Fin g→Option (Ins (Fin g) (Fin q))keeps : ∀ z a ins, delta z a=some ins → (ins.symbol=marker ↔ a=marker)leftSafe : ∀ z ins, delta z marker=some ins → ins.dir≠.leftdef old (z : Fin q) : Fin (q+2) := ⟨z.val,by have := z.isLt; omega⟩def cleanState (q : Nat) : Fin (q+2) := ⟨q,by omega⟩def acceptState (q : Nat) : Fin (q+2) := ⟨q+1,by omega⟩def extend (ins : Ins (Fin g) (Fin q)) : Ins (Fin g) (Fin (q+2)) :=⟨old ins.state,ins.symbol,ins.dir⟩def trans (M : Ordinary g q) (z : Fin (q+2)) (a : Fin g) : Ins (Fin g) (Fin (q+2)) :=if h : z.val<q thenmatch M.delta ⟨z.val,h⟩ a with| none => ⟨cleanState q,a,.stay⟩| some i => extend ielse if z.val=q thenif a=M.marker then ⟨acceptState q,a,.stay⟩ else ⟨cleanState q,a,.left⟩else ⟨acceptState q,a,.stay⟩theorem old_step (M : Ordinary g q) (z : Fin q) (a : Fin g) : trans M (old z) a =match M.delta z a with| none => ⟨cleanState q,a,.stay⟩| some i => extend i := by simp [trans,old,z.isLt]theorem clean_step (M : Ordinary g q) (a : Fin g) : trans M (cleanState q) a =if a=M.marker then ⟨acceptState q,a,.stay⟩ else ⟨cleanState q,a,.left⟩ := bysimp [trans,cleanState]def normalized (M : Ordinary g q) : TM g (q+2) wheremarker := M.markerblank := M.blankblank_ne := M.blank_nestart := old M.startaccept := acceptState qdistinct := by intro e; have v := congrArg Fin.val e; change M.start.val=q+1 at v; have := M.start.isLt; omegadelta := trans Mkeeps := byintro z aunfold transsplitnext bound =>cases e : M.delta ⟨z.val,bound⟩ a with| none => rfl| some i => exact M.keeps _ _ _ enext =>split· split <;> rfl· rflleftSafe := byintro zunfold transsplitnext bound =>cases e : M.delta ⟨z.val,bound⟩ M.marker with| none => simp| some i => exact M.leftSafe _ _ enext =>split <;> simpstationary := by simp [trans,acceptState,show ¬q+1<q by omega]def config₀ (M : Ordinary g q) : Config g q :=⟨fun x=>if x=0 then M.marker else M.blank,0,M.start⟩def instruction (M : Ordinary g q) (c : Config g q) := M.delta c.state (c.tape c.pos)def once (M : Ordinary g q) (c : Config g q) : Config g q :=match instruction M c with| none => c| some ins => ⟨writeAt c.tape c.pos ins.symbol,dest ins.dir c.pos,ins.state⟩def original (M : Ordinary g q) : Nat→Config g q| 0 => config₀ M| t+1 => once M (original M t)def stopped (M : Ordinary g q) (t : Nat) := instruction M (original M t)=nonedef lift (c : Config g q) : Config g (q+2) := ⟨c.tape,c.pos,old c.state⟩theorem simulates (M : Ordinary g q) (t : Nat) (prior : ∀ j,j<t→¬stopped M j) :run (normalized M) t=lift (original M t) := byinduction t with| zero => rfl| succ t ih =>have now := prior t (by omega)change step (normalized M) (run (normalized M) t) = lift (once M (original M t))rw [ih (fun j lt=>prior j (by omega))]cases eq : instruction M (original M t) with| none => exact (now eq).elim| some ins =>have instr : trans M (old (original M t).state) ((original M t).tape (original M t).pos)=extend ins := byrw [old_step]; change (match instruction M (original M t) with | none => _ | some i => extend i) = _rw [eq]simp [step,normalized,lift,instr,once,eq,extend]private theorem eventually_clean (M : Ordinary g q) (p : Nat) :∀ t, (run (normalized M) t).pos=p → (run (normalized M) t).state=cleanState q →∃ s,Genuine (normalized M) s := byinduction p with| zero =>intro t pos statehave marker := (marker_iff (normalized M) t 0).mpr rflchange (run (normalized M) t).tape 0=M.marker at markerrefine ⟨t+1,?_⟩change dest (trans M _ _).dir _=0 ∧ (trans M _ _).state=acceptState qrw [state,pos,marker,clean_step]simp [dest]| succ p ih =>intro t pos statehave neq : (run (normalized M) t).tape (p+1)≠M.marker := byintro e; have z := (marker_iff (normalized M) t (p+1)).mp e; omegaapply ih (t+1)· change dest (trans M _ _).dir _=prw [state,pos,clean_step,if_neg neq]; simp [dest]· change (trans M _ _).state=cleanState qrw [state,pos,clean_step,if_neg neq]private theorem first_stop (M : Ordinary g q) (t : Nat) (h : stopped M t) :∃ j, stopped M j ∧ (∀ i,i<j→¬stopped M i) := byinduction t using Nat.strongRecOn with| ind t ih =>by_cases early : ∃ i,i<t ∧ stopped M i· obtain ⟨i,lt,yes⟩ := early; exact ih i lt yes· exact ⟨t,h,fun i lt st=>early ⟨i,lt,st⟩⟩theorem halts_iff_genuine (M : Ordinary g q) :(∃ t,stopped M t) ↔ ∃ s,Genuine (normalized M) s := byconstructor· rintro ⟨t,yes⟩obtain ⟨j,st,prior⟩ := first_stop M t yeshave exactAt := simulates M j priorhave instr : trans M (old (original M j).state) ((original M j).tape (original M j).pos) =⟨cleanState q,(original M j).tape (original M j).pos,.stay⟩ := byrw [old_step]; unfold stopped instruction at st; rw [st]apply eventually_clean M (original M j).pos (j+1)· change (step (normalized M) (run (normalized M) j)).pos=_rw [exactAt]; simp [normalized,step,lift,instr,dest]· change (step (normalized M) (run (normalized M) j)).state=_rw [exactAt]; simp [normalized,step,lift,instr]· rintro ⟨s,_,accept⟩apply Classical.byContradictionintro nonehave eq := simulates M s (fun j _ h=>none ⟨j,h⟩)rw [eq] at accepthave indices := congrArg Fin.val acceptchange (original M s).state.val=q+1 at indiceshave := (original M s).state.isLt; omega/-- Compilation targets the very same numerical tile system as the wordtesters. The halt may occur at *any* tape position, including at time zero. -/theorem halts_iff_trace (M : Ordinary g q) : (∃ t,stopped M t) ↔∃ w s, Nonempty (AcceptingTrace (compile (normalized M)) w s) :=(halts_iff_genuine M).trans (trace_iff (normalized M))theorem halts_iff_rectangles (M : Ordinary g q) : (∃ t,stopped M t) ↔∃ w, ∀ k, ∃ h, 1<h ∧ k<2*(w*h) ∧ Nonempty (Rectangle (compile (normalized M)) w h) :=(halts_iff_genuine M).trans (rectangles_iff (normalized M))end P455MachineCleanupend/- Begin Problem455OriginalTerminal (from finite-semigroup-identity-bases). -/section/- Endpoint obstruction in the actual original source word after all gapvariables of the smaller rule have been expanded. -/namespace P455OriginalTerminalopen Problem455.Slots P455Witness P455Retained P455TerminalTransfer/-- Keep the identical five selected output names and the identical fivedonor variables when an overflow obstruction is taken back to theoriginal word. Deficiency already gives a contradiction. -/theorem expand {r : Nat} {v : Word} {e h : Nat → Word} {kept : Nat → Prop} {x i : Nat}(exp : Expansion v e kept) (hr : 1 < r) (kx : kept x)(d : SlotDefect) (small : Lift v h x i r d) :Lift (v.flatMap e) h x i r d := bycases d with| deficient a => exact small| overflow xs =>obtain ⟨assign,len,nd,valid⟩ := smallrefine ⟨assign,len,nd,?_⟩intro a haobtain ⟨obs,ha',cnt⟩ := valid a hahave used : assign a ∈ v := List.count_pos_iff.mp (by omega)have keep : kept (assign a) := byapply Classical.byContradictionintro gaphave := (exp.gaps (assign a) used gap).1omegahave hx : assign a ∈ e (assign a) := by rw [exp.literal _ used keep]; simpexact ⟨exp.in_original_slot x i _ kx obs _ hx,ha',(exp.count_eq _ (fun _ h => h) _ keep).trans cnt⟩end P455OriginalTerminalend/- Begin Problem455CompressedFrame (from finite-semigroup-identity-bases). -/sectionnamespace P455CompressedFrameopen P455Closure P455Compression P455Uncrossedprivate theorem prepend_cut (a x : Nat) (cs tail : List Piece) :prependOutside a (cs ++ .literal x :: tail) =prependOutside a cs ++ .literal x :: tail := bycases cs with| nil => rfl| cons p cs => cases p <;> rflprivate theorem pieces_cut (names u v : W) (x : Nat) (hx : x ∈ names) :pieces names (u ++ x :: v) = pieces names u ++ .literal x :: pieces names v := byinduction u with| nil => simp [pieces,hx]| cons a u ih =>by_cases k : a ∈ names· simp [pieces,k,ih]· simp [pieces,k,ih,prepend_cut]private theorem code_append (n : Nat) (p q : List Piece) :code n (p ++ q) = code n p ++ code (n+p.length) q := byinduction p generalizing n with| nil => simp [code]| cons e p ih => cases e <;> simp [code,ih,Nat.add_assoc,Nat.add_comm,Nat.add_left_comm]private def enc (names : W) (n : Nat) (w : W) := code n (pieces names w)private def span (names w : W) := (pieces names w).lengthprivate theorem enc_cut {names : W} {x : Nat} (hx : x ∈ names) (n : Nat) (u v : W) :enc names n (u ++ x :: v) = enc names n u ++ x :: enc names (n+span names u+1) v := bysimp only [enc,span,pieces_cut _ _ _ _ hx,code_append,code]private theorem enc_cons {names : W} {x : Nat} (hx : x ∈ names) (n : Nat) (v : W) :enc names n (x :: v) = x :: enc names (n+1) v := by simp [enc,pieces,hx,code]private def pick (x y : Nat) (b : Bool) := if b then y else xprivate def middleWord (x y : Nat) (es : List (W × Bool)) : W :=es.flatMap fun e => e.1 ++ [pick x y e.2]private def encodeMiddle (names : W) (n : Nat) : List (W × Bool) → List (W × Bool)| [] => []| (u,b)::es => (enc names n u,b) :: encodeMiddle names (n+span names u+1) esprivate def finish (names : W) (n : Nat) : List (W × Bool) → Nat| [] => n| (u,_)::es => finish names (n+span names u+1) esprivate theorem enc_middle {names : W} {x y : Nat} (hx : x ∈ names) (hy : y ∈ names)(n : Nat) (es : List (W × Bool)) (tail : W) :enc names n (middleWord x y es ++ tail) =middleWord x y (encodeMiddle names n es) ++ enc names (finish names n es) tail := byinduction es generalizing n with| nil => simp [middleWord,encodeMiddle,finish]| cons e es ih =>obtain ⟨gap,b⟩ := ehave hk : pick x y b ∈ names := by cases b <;> simp [pick,hx,hy]change enc names n (((gap ++ [pick x y b]) ++ middleWord x y es) ++ tail) =(((enc names n gap ++ [pick x y b]) ++ middleWord x y (encodeMiddle names _ es)) ++enc names (finish names _ es) tail)simp only [List.append_assoc,List.singleton_append,enc_cut hk,ih,List.cons_append,List.nil_append]private theorem mid_tags (names : W) (n : Nat) (es : List (W × Bool)) :(encodeMiddle names n es).map Prod.snd = es.map Prod.snd := byinduction es generalizing n with| nil => rfl| cons e es ih => cases e; simp [encodeMiddle,ih]private theorem singleton_mid (f : Frame Nat) {x y : Nat} (hp : f.p = [x]) (hq : f.q = [y]) :f.mid = middleWord x y f.middle := byunfold Frame.mid middleWordcongr 1funext ecases e.2 <;> simp [hp,hq,pick]private def firstSuffix (f : Frame Nat) (l : W) (x y : Nat) :=l ++ [x,x,y,x,y,y] ++ middleWord x y f.middle ++ f.beforeMutableprivate def lastSuffix (f : Frame Nat) (k : W) (x y : Nat) :=f.beforeFinalP ++ x :: (f.beforeFinalQ ++ y :: k)private theorem literal_pair (f : Frame Nat) (l k : W) {x y : Nat} (hp : f.p = [x])(hq : f.q = [y]) (b : Bool) :side f l k b = firstSuffix f l x y ++ pick x y b :: pick x y (!b) :: lastSuffix f k x y := bycases b <;> simp [side,Frame.core,Frame.early,Frame.pair,firstSuffix,lastSuffix,hp,hq,singleton_mid f hp hq,pick,List.append_assoc]private theorem sum_append (a b : W) : (a++b).sum = a.sum+b.sum := byinduction a with| nil => simp| cons x a ih => simp [ih,Nat.add_assoc]private theorem same_base (f : Frame Nat) (l k names : W) {x y : Nat} (hp : f.p = [x])(hq : f.q = [y]) (b : Bool) :base (side f l k b) names = base (side f l k false) names := bycases b <;> simp [literal_pair f l k hp hq,base,sum_append,pick,Nat.add_comm,Nat.add_left_comm,Nat.add_assoc]private def make (f : Frame Nat) (names : W) (x y head : Nat) : Frame Nat :=let n := finish names head f.middlelet p := n+span names f.beforeMutable+2{ pHead := x, pTail := [], qInit := [], qLast := y, tag := f.tag,middle := encodeMiddle names head f.middle, beforeMutable := enc names n f.beforeMutable,beforeFinalP := enc names p f.beforeFinalP,beforeFinalQ := enc names (p+span names f.beforeFinalP+1) f.beforeFinalQ }private theorem enc_frame (f : Frame Nat) (l k names : W) {x y : Nat} (hx : x ∈ names)(hy : y ∈ names) (hp : f.p = [x]) (hq : f.q = [y]) (start : Nat) :let head := start+span names l+6let n := finish names head f.middlelet p := n+span names f.beforeMutable+2let q := p+span names f.beforeFinalP+1let g := make f names x y head∀ b, enc names start (side f l k b) =side g (enc names start l) (enc names (q+span names f.beforeFinalQ+1) k) b := bydsimp onlyintro blet head := start+span names l+6let g := make f names x y headhave gp : g.p = [x] := rflhave gq : g.q = [y] := rflchange _ = side g _ _ bcases b <;>simp only [literal_pair f l k hp hq,literal_pair g _ _ gp gq,firstSuffix,lastSuffix,pick,Bool.not_false,Bool.not_true,Bool.false_eq_true,if_false,if_true,List.append_assoc,List.cons_append,List.nil_append] <;>rw [enc_cut hx,enc_cons hx,enc_cons hy,enc_cons hx,enc_cons hy,enc_cons hy,enc_middle hx hy] <;>first| rw [enc_cut hx,enc_cons hy,enc_cut hx,enc_cut hy]| rw [enc_cut hy,enc_cons hx,enc_cut hx,enc_cut hy]all_goals rflprivate theorem lookup_congr (pre p q : List Piece)(same : ∀ n, lookup n p = lookup n q) (n : Nat) :lookup n (pre ++ p) = lookup n (pre ++ q) := byinduction pre generalizing n with| nil => exact same n| cons c cs ih =>cases c with| literal a => exact ih (n+1)| gap w => funext a; simp [lookup,congrFun (ih (n+1)) a]/-- Both smaller words use the same expansion, including corresponding gapvariables on either side of the mutable pair. -/theorem same_expansion (f : Frame Nat) (l k names : W) {x y : Nat} (hx : x ∈ names)(hy : y ∈ names) (hp : f.p = [x]) (hq : f.q = [y]) (b : Bool) :expand (side f l k b) names = expand (side f l k false) names := byunfold expandrw [same_base f l k names hp hq b]cases b with| false => rfl| true =>rw [literal_pair f l k hp hq true,literal_pair f l k hp hq false]simp only [pick,Bool.not_true,Bool.not_false,Bool.false_eq_true,if_false,if_true,pieces_cut _ _ _ _ hx,pieces_cut _ _ _ _ hy,pieces,hx,hy,if_true]apply lookup_congrintro nrfl/-- For any common retained list containing x and y, both canonical shorterwords form one common valid literal singleton frame with equal contexts.Its one expansion simultaneously recovers the two original words. -/theorem canonical_pair {r allow} (f : Frame Nat) (l k names : W) {x y : Nat}(hx : x ∈ names) (hy : y ∈ names) (hp : f.p = [x]) (hq : f.q = [y])(valid : f.Valid r allow (fun _ _ => False)) (origBit : Bool)(cap : Cap r (side f l k origBit)) :∃ (g : Frame Nat) (left right : W),g.p = [x] ∧ g.q = [y] ∧ g.Valid r allow (fun _ _ => False) ∧(∀ b, small (side f l k b) names = side g left right b) ∧(∀ b, (side g left right b).flatMap (expand (side f l k origBit) names) = side f l k b) := bylet start := base (side f l k false) nameslet head := start+span names l+6let n := finish names head f.middlelet p := n+span names f.beforeMutable+2let q := p+span names f.beforeFinalP+1let g := make f names x y headlet left := enc names start llet right := enc names (q+span names f.beforeFinalQ+1) khave gp : g.p = [x] := rflhave gq : g.q = [y] := rflhave eq (b : Bool) : small (side f l k b) names = side g left right b := byunfold smallrw [same_base f l k names hp hq b]exact enc_frame f l k names hx hy hp hq start bhave bound : Cap r (side g left right origBit) := byrw [← eq]apply (canonical (side f l k origBit) names).small_cap (by have := valid.1; omega)rw [recover]exact caphave v : g.Valid r allow (fun _ _ => False) := byapply g.valid_of_capped_shape valid.1 valid.2.1 _ _ _ _ _ origBit left right bound· exact (mid_tags names head f.middle).trans valid.2.2.1· simpa only [gp,← hp] using valid.2.2.2.1· simpa only [gq,← hq] using valid.2.2.2.2.1· simpa only [gp,gq,← hp,← hq] using valid.2.2.2.2.2.1· simprefine ⟨g,left,right,gp,gq,v,eq,?_⟩intro brw [← eq,(same_expansion f l k names hx hy hp hq origBit).trans(same_expansion f l k names hx hy hp hq b).symm]exact recover _ _end P455CompressedFrameend/- Begin Problem455DefectRename (from finite-semigroup-identity-bases). -/sectionnamespace P455DefectRenameopen P455Witness P455Paths P455ContactLift P455SourceFamiliesopen P455ContactReflection P455PortReflection P455DefectProjection Problem455.Slotsdef decode (keep : W) (i : Nat) : Nat := (keep[i]?).getD 0theorem decode_idx (keep : W) {a : Nat} (h : a ∈ keep) : decode keep (keep.idxOf a) = a := byinduction keep with| nil => contradiction| cons b keep ih =>by_cases eq : b = a· subst b; simp [decode]· have ha : a ∈ keep := (List.mem_cons.mp h).resolve_left (Ne.symm eq)simpa [decode,List.idxOf_cons,cond_eq_if,beq_iff_eq,eq] using ih hatheorem decode_map {keep w : W} (hs : ∀ a ∈ w, a ∈ keep) :(w.map keep.idxOf).map (decode keep) = w := byrw [List.map_map]calc_ = w.map id := List.map_congr_left (fun a ha => decode_idx keep (hs a ha))_ = w := List.map_id wdef extend (keep : W) (a : Nat) := if a ∈ keep then keep.idxOf a else keep.length + atheorem extend_inj (keep : W) {a b : Nat} (h : extend keep a = extend keep b) : a = b := byby_cases ha : a ∈ keep <;> by_cases hb : b ∈ keep <;> simp only [extend,ha,hb,if_true,if_false] at h· simpa only [decode_idx keep ha, decode_idx keep hb] using congrArg (decode keep) h· have := List.idxOf_lt_length_of_mem ha; omega· have := List.idxOf_lt_length_of_mem hb; omega· omegaabbrev Injects (d : Nat → Nat) := ∀ {a b}, d a = d b → a = btheorem select_map_inj (d : Nat → Nat) (inj : Injects d) (keep w : W) :select (keep.map d) (w.map d) = (select keep w).map d := byinduction w with| nil => rfl| cons a w ih =>have iff : d a ∈ keep.map d ↔ a ∈ keep := byconstructor· intro h; obtain ⟨b,hb,eq⟩ := List.mem_map.mp h; exact inj eq ▸ hb· exact List.mem_map_of_memby_cases ha : a ∈ keep <;> simp_all [select]theorem kept {keep w : W} {a : Nat} (h : a ∈ select keep w) : a ∈ keep := bysimpa using (List.mem_filter.mp h).2theorem extend_map {keep w : W} (hs : ∀ a ∈ w, a ∈ keep) :w.map (extend keep) = w.map keep.idxOf :=List.map_congr_left (fun a ha => by simp [extend, hs a ha])theorem binary_select_map (keep w : W) {x y : Nat} (hx : x ∈ keep) (hy : y ∈ keep) :(select [x,y] w).map keep.idxOf =select [keep.idxOf x,keep.idxOf y] ((select keep w).map keep.idxOf) := byhave h := select_map_inj (extend keep) (extend_inj keep) [x,y] (select keep w)rw [select_sub keep [x,y] w (by simpa using And.intro hx hy),extend_map (fun _ ha => kept ha),extend_map (keep := keep) (w := select [x,y] w) (byintro a ha; have hxy : a = x ∨ a = y := by simpa using kept harcases hxy with rfl|rfl <;> assumption)] at hsimpa [extend,hx,hy] using h.symmtheorem count_rename (d : Nat → Nat) (inj : Injects d) (w : W) (a : Nat) :(w.map d).count (d a) = w.count a := byinduction w with| nil => rfl| cons b w ih =>by_cases eq : b = a· subst b; simp [ih]· have ne : d b ≠ d a := fun e => eq (inj e)simp [eq,ne,ih, List.count_cons, beq_iff_eq]theorem cap_rename {r w} (d : Nat → Nat) (inj : Injects d) (cp : P455Closure.Cap r w) :P455Closure.Cap r (w.map d) := byintro aby_cases mem : a ∈ w.map d· obtain ⟨b,_,rfl⟩ := List.mem_map.mp memsimpa only [count_rename d inj] using cp b· simp [List.count_eq_zero.mpr mem]theorem rename_sees (d : Nat → Nat) (inj : Injects d) {w pat} (obs : sees w pat) :sees (w.map d) (pat.map (eventMap d)) := byunfold sees events at *rw [← stamp_map d w w (fun _ => 0) (fun _ => 0) (fun _ h => h) (fun _ _ _ _ h => inj h) (fun _ _ => rfl)]exact obs.map _theorem rename_order {r allow src dst w} (d : Nat → Nat) (inj : Injects d) (pat : List Event)(h : Holds r allow src w (.order pat)) :Holds r allow dst (w.map d) (.order (pat.map (eventMap d))) := byrefine ⟨?_,rename_sees d inj h.2⟩intro e he; obtain ⟨f,hf,rfl⟩ := List.mem_map.mp he; exact h.1 f hftheorem rename_pattern (d : Nat → Nat) (inj : Injects d) {w a b tag bit}(h : select [a,b] w = profile a b tag bit) :select [d a,d b] (w.map d) = profile (d a) (d b) tag bit := byrw [← map_profile d a b tag bit, ← h, ← select_map_inj d inj [a,b] w]rfltheorem rename_marked {r allow src w} (d : Nat → Nat) (inj : Injects d) (n : Node) (bit : Bool)(h : Holds r allow src w (markedNode n bit)) :Holds r allow (markNode (sendNode d n)) (w.map d) (markedNode (sendNode d n) bit) :=⟨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⟩theorem rename_record {r allow src dst w a b tag} (d : Nat → Nat) (inj : Injects d)(h : Holds r allow src w (.record a b tag)) :Holds r allow dst (w.map d) (.record (d a) (d b) tag) := byobtain ⟨ne,len,ok,bit,pr⟩ := hexact ⟨fun e => ne (inj e),len,ok,bit,rename_pattern d inj pr⟩theorem rename_contact {r allow src dst w} (d : Nat → Nat) (inj : Injects d) (a b : Nat) (c : ContactChoice)(h : Holds r allow src w (contact r a b c)) :Holds r allow dst (w.map d) (contact r (d a) (d b) c) := bycases c with| record tag rev => cases rev <;> exact rename_record d inj h| port phase rev =>obtain ⟨ab,ac,bc,early,obs,last⟩ := hrefine ⟨fun e => ab (inj e),(count_rename d inj w a).trans ac,(count_rename d inj w b).trans bc,?_,?_,last⟩· rcases early with ⟨h,_⟩|⟨h,_⟩· exact .inl ⟨rename_order d inj [(a,2),(b,0)] h,True.intro⟩· exact .inr ⟨rename_order d inj [(b,2),(a,0)] h,True.intro⟩· cases rev <;> exact rename_order d inj _ obstheorem rename_walk {r allow src dst w} (d : Nat → Nat) (inj : Injects d) (a : Nat) (p : List Step)(h : Walk r allow src w a p) :Walk r allow dst (w.map d) (d a) (relabel d p) := byinduction p generalizing a with| nil => trivial| cons bc p ih => exact ⟨rename_contact d inj a bc.1 bc.2 h.1,ih _ h.2⟩theorem rename_deficient {r allow w} (d : Nat → Nat) (inj : Injects d) (s : SlotCertificate)(b : Nat) (kind : s.defect = .deficient b) (h : Holds r allow (markNode s.anchor) w (s.query r)) :Holds r allow (markNode (sendSlot d s).anchor) (w.map d) ((sendSlot d s).query r) := byobtain ⟨len,walk,term⟩ := slot_route s hlet start := picked shave start' : picked (sendSlot d s) = d start := bycases side : s.startAtMate <;> simp [sendSlot,picked,sendNode,start,side]rw [kind] at termobtain ⟨⟨slot,j,seen⟩,cnt⟩ := termrefine ⟨rename_marked d inj s.anchor s.bit h.1,by simpa [sendSlot,relabel,P455Witness.Holds] using len,?_,True.intro⟩apply (route_iff ..).mprchange Walk _ _ _ _ (picked (sendSlot d s)) (relabel d s.steps) ∧ Holds _ _ _ _(terminalSlot r (endpoint (picked (sendSlot d s)) (relabel d s.steps)) s.terminalIndex (sendDefect d s.defect))rw [start',endpoint_relabel,kind]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⟩theorem canonical_defect {r allow mark u} (cap : P455Closure.Cap r u) (n : Node) (bit side : Bool)(t i bad : Nat) (anchor : Holds r allow (markNode n) u (markedNode n bit))(near : Near r allow mark u (if side then n.mate else n.owner) t 6)(slot : slotStart i) (occ : occupies u t i bad) (deficient : u.count bad < r) :∃ (keep : W) (s : SlotCertificate), keep.length ≤ 9 ∧ n.owner ∈ keep ∧ n.mate ∈ keep ∧s.anchor.owner = keep.idxOf n.owner ∧ s.anchor.mate = keep.idxOf n.mate ∧ s.bit = bit ∧s.defect = .deficient (keep.idxOf bad) ∧ (∀ a ∈ (select keep u).map keep.idxOf, a < 9) ∧P455Closure.Cap r ((select keep u).map keep.idxOf) ∧Holds r allow (markNode s.anchor) ((select keep u).map keep.idxOf) (s.query r) := byobtain ⟨keep,s,len,ho,hm,hb,kind,anc,bs,cp,h⟩ :=bounded_defect_kind cap n bit side t i bad anchor near slot occ deficientlet d := extend keephave mapEq := extend_map (keep := keep) (w := select keep u) (fun _ ha => kept ha)have valid := rename_deficient d (extend_inj keep) s bad kind (by simpa only [anc] using h)refine ⟨keep,sendSlot d s,len,ho,hm,by simp [sendSlot,sendNode,d,extend,anc,ho],by simp [sendSlot,sendNode,d,extend,anc,hm],bs,by simp [sendSlot,sendDefect,kind,d,extend,hb],?_,?_,?_⟩· intro a ha; obtain ⟨b,bm,rfl⟩ := List.mem_map.mp haexact Nat.lt_of_lt_of_le (List.idxOf_lt_length_of_mem (kept bm)) len· rw [← mapEq]; exact cap_rename d (extend_inj keep) cp· rw [← mapEq]; exact validend P455DefectRenameend/- Begin Problem455BlockSeparators (from finite-semigroup-identity-bases). -/sectionnamespace P455BlockSeparatorsopen P455Witness Problem455.Slots Problem455Swap/-- A directed path of the literal repeated bigrams. -/inductive Directed (e : Nat → Nat → Prop) : Nat → Nat → Prop| refl (a) : Directed e a a| snoc {a b c} : Directed e a b → e b c → Directed e a ctheorem prepend {e a b c} (h : e a b) (p : Directed e b c) : Directed e a c := byinduction p with| refl => exact .snoc (.refl _) h| snoc _ last ih => exact .snoc ih lasttheorem split_first {e a b} (p : Directed e a b) :a = b ∨ ∃ c, e a c ∧ Directed e c b := byinduction p with| refl => exact .inl rfl| @snoc y z _ last ih =>rcases ih with eq|⟨c,first,rest⟩· exact .inr ⟨z, eq ▸ last,.refl z⟩· exact .inr ⟨c,first,.snoc rest last⟩theorem orient {e a b} (outgoing : ∀ {x y z}, e x y → e x z → y = z)(incoming : ∀ {x y z}, e y x → e z x → y = z) (p : Joined e a b) :Directed e a b ∨ Directed e b a := byinduction p with| refl => exact .inl (.refl _)| @extend y z prev h ih =>rcases ih with f|b· rcases h with f'|b'· exact .inl (.snoc f f')· cases f with| refl => exact .inr (.snoc (.refl _) b')| snoc rest last => exact .inl (incoming last b' ▸ rest)· rcases h with f'|b'· rcases split_first b with eq|⟨c,first,rest⟩· exact .inl (eq ▸ Directed.snoc (.refl _) f')· exact .inr (outgoing first f' ▸ rest)· exact .inr (prepend b' b)theorem directed_of_same {r w a b} (hr : 0 < r) (cap : P455Closure.Cap r w)(same : SameBlock r w a b) : Directed (Link r w) a b ∨ Directed (Link r w) b a := byapply orient _ _ same.2.2· intro x y z xy xzapply Classical.byContradiction; intro nehave h := out_bound x y z ne wrw [show bigram x y w = r from xy,show bigram x z w = r from xz,Problem455BlockBridge.occ_count] at hhave hx := cap x; omega· intro x y z yx zxapply Classical.byContradiction; intro nehave h := Nat.le_trans (in_bound y z x ne w) (tail_occ_le x w)rw [show bigram y x w = r from yx,show bigram z x w = r from zx,Problem455BlockBridge.occ_count] at hhave hx := cap x; omega/-- Suffixes starting at each occurrence, listed in word order. -/def rows (a : Nat) : W → List W| [] => []| b :: w => if a = b then (b :: w) :: rows a w else rows a wtheorem rows_length (a : Nat) (w : W) : (rows a w).length = w.count a := byinduction w with| nil => rfl| cons b w ih => by_cases eq : a = b <;> simp_all [rows,List.count_cons,beq_iff_eq,Ne.symm]/-- Each row can be shifted exactly one position across a repeatedlink. This includes equality of the entire remaining suffix, ratherthan a numerical comparison of positions. -/private def edgeRows (a b : Nat) : W → List W| [] => []| c :: w => if c = a ∧ w.head? = some b then w :: edgeRows a b w else edgeRows a b wprivate theorem edgeRows_length (a b : Nat) (w : W) : (edgeRows a b w).length = bigram a b w := byinduction w with| nil => rfl| cons c w ih =>by_cases test : c = a ∧ w.head? = some b <;> simp [edgeRows,bigram,hit,test,ih,Nat.add_comm]private theorem edge_sub_left (a b : Nat) (w : W) :((edgeRows a b w).map (List.cons a)).Sublist (rows a w) := byinduction w with| nil => exact .slnil| cons c w ih =>by_cases k : c = a· subst cby_cases h : w.head? = some b· simpa [edgeRows,rows,h] using ih.cons₂ (a::w)· simpa [edgeRows,rows,h] using ih.cons (a::w)· simpa [rows,edgeRows,k,Ne.symm k] using ihprivate theorem edge_sub_right (a b : Nat) (w : W) :(edgeRows a b w).Sublist (rows b w.tail) := byinduction w with| nil => exact .slnil| cons c w ih =>cases w with| nil => simp [rows,edgeRows]| cons x t =>by_cases mem : x = b· subst xby_cases yes : c = a· simpa [rows,edgeRows,yes] using ih.cons₂ (b::t)· simpa [rows,edgeRows,yes] using ih.cons (b::t)· simpa [rows,edgeRows,mem,Ne.symm mem] using ihtheorem link_rows {r a b w} (cap : P455Closure.Cap r w) (link : Link r w a b) :rows a w = (rows b w).map (List.cons a) := byhave l := edge_sub_left a b whave f := edge_sub_right a b whave s : (rows b w.tail).Sublist (rows b w) := bycases w with| nil => exact .slnil| cons x t =>by_cases eq : b=x· simp [rows,eq]· simp [rows,eq]have t := f.trans shave len : (edgeRows a b w).length = r := (edgeRows_length ..).trans linkhave e := t.eq_of_length_le (by rw [rows_length,len]; exact cap b)have g := l.eq_of_length_le (by rw [List.length_map,rows_length,len]; exact cap a)rw [← g,e]theorem directed_prefix {r w a b} (cap : P455Closure.Cap r w) (p : Directed (Link r w) a b) :∃ pre : W, rows a w = (rows b w).map (pre ++ ·) := byinduction p with| refl => exact ⟨[],by simp⟩| @snoc y z prev edge ih =>obtain ⟨pre,h⟩ := ihrefine ⟨pre ++ [y],?_⟩rw [h,link_rows cap edge,List.map_map]apply List.map_congr_leftintro row _; simptheorem row_head {a : Nat} {w row : W} (h : row ∈ rows a w) : row.head? = some a := byinduction w with| nil => contradiction| cons x w ih =>by_cases eq : a=x· subst x; rcases (show row = a::w ∨ row ∈ rows a w by simpa [rows] using h) with rfl|old· rfl· exact ih old· exact ih (by simpa [rows,eq] using h)theorem all_next {w : W} (a b : Nat)(h : ∀ z ∈ rows a w, z.tail.head? = some b) : bigram a b w = w.count a := byinduction w with| nil => rfl| cons x w ih =>by_cases eq : x=a· subst xhave next := h (a::w) (by simp [rows])have recProof := ih (fun z hz => h z (by simp [rows,hz]))simp [bigram,hit,show w.head? = some b from next,recProof,Nat.add_comm]· have recProof := ih (fun z hz => h z (by simp [rows,Ne.symm eq,hz]))simp [bigram,hit,eq,recProof,List.count_cons,beq_iff_eq]theorem directed_of_prefix {r w b} (hr : 0 < r) (cap : P455Closure.Cap r w)(cb : w.count b = r) (pre : W) (a : Nat)(eq : rows a w = (rows b w).map (pre ++ ·)) : Directed (Link r w) a b := byhave non : rows b w ≠ [] := byintro z; have h := rows_length b w; rw [z,cb] at h; simp at h; omegaobtain ⟨z,hz⟩ := List.exists_mem_of_ne_nil _ noninduction pre generalizing a with| nil =>have e : rows a w = rows b w := by simpa using eqhave ma := row_head (e ▸ hz : z ∈ rows a w)exact (show a=b by simpa [row_head hz] using ma.symm) ▸ Directed.refl _| cons c p ih =>have ma := row_head (w := w) (a := a) (row := (c::p)++z)(eq ▸ List.mem_map_of_mem hz)have ac : c=a := by simpa using masubst clet next := p.head?.getD bhave all (v) (hv : v ∈ rows b w) : (p ++ v).head? = some next := bycases p with| nil => simpa [next] using row_head hv| cons x xs => rflhave ct : w.count a = r := by simpa [rows_length,cb] using congrArg List.length eqhave li : Link r w a next := byapply Eq.trans _ ct; apply all_nextintro t htrw [eq] at htobtain ⟨v,hv,rfl⟩ := List.mem_map.mp htexact all v hvapply prepend liapply ihhave strip := congrArg (List.map List.tail) ((link_rows cap li).symm.trans eq)simpa [List.map_map,Function.comp_def] using striptheorem directed_joined {e a b} (p : Directed e a b) : Joined e a b := byinduction p with| refl => exact .refl _| snoc _ last ih => exact .extend ih (.inl last)theorem reversed_joined {e a b} (p : Directed e a b) : Joined e b a := byinduction p with| refl => exact .refl _| snoc _ last ih =>have cat {x y z} (p : Joined e x y) (q : Joined e y z) : Joined e x z := byinduction q with| refl => exact p| extend _ t j => exact .extend j texact cat (.extend (.refl _) (.inr last)) ihtheorem project_rows (keep : W) {a : Nat} (ha : a ∈ keep) (w : W) :rows a (select keep w) = (rows a w).map (select keep) := byinduction w with| nil => rfl| cons b w ih =>by_cases eq : a=b· subst b; simp [rows,select,ha,ih] at *· by_cases hb : b ∈ keep <;> simp [rows,select,ha,hb,eq,ih] at *theorem pair_ext {w v : W} (pairs : ∀ c d : Nat, select [c,d] w = select [c,d] v) : w = v := byinduction w generalizing v with| nil =>cases v with| nil => rfl| cons b v => simpa [select] using pairs b b| cons a w ih =>cases v with| nil => simpa [select] using pairs a a| cons b v =>have eq : a = b := by simpa [select] using congrArg List.head? (pairs a b)subst bapply congrArg (List.cons a)apply ihintro c dby_cases ac : a = c <;> by_cases ad : a = d <;> simpa [select,ac,ad] using pairs c dtheorem rowmaps_ext {as bs : List W} (pairs : ∀ c d : Nat,as.map (select [c,d]) = bs.map (select [c,d])) : as = bs := byinduction as generalizing bs with| nil => cases bs with| nil => rfl| cons b bs => simpa using pairs 0 0| cons a as ih =>cases bs with| nil => simpa using pairs 0 0| cons b bs =>have h (c d) := List.cons.inj (show select [c,d] a :: as.map (select [c,d]) =select [c,d] b :: bs.map (select [c,d]) from pairs c d)exact List.cons.injEq _ _ _ _ |>.mpr ⟨pair_ext fun c d => (h c d).1,ih fun c d => (h c d).2⟩theorem row_suffix {a : Nat} {w row : W} (m : row ∈ rows a w) : row <:+ w := byinduction w with| nil => contradiction| cons x w ih =>by_cases eq : a=x· subst x; rcases (show row = a::w ∨ row ∈ rows a w by simpa [rows] using m) with rfl|old· exact List.suffix_refl _· exact (ih old).trans (List.suffix_cons _ _)· exact (ih (by simpa [rows,eq] using m)).trans (List.suffix_cons _ _)theorem project_prefix (keep : W) (pre : W) (bs : List W) :(bs.map (pre ++ ·)).map (select keep) =(bs.map (select keep)).map (select keep pre ++ ·) := bysimp [List.map_map, Function.comp_def, select, List.filter_append]/-- A putative merger in every extension of some two extra namesrecovers an actual directed repeated block in the original word.The orientation is fixed by the first rows in the original word. -/private theorem reconstruct {r w a b} (hr : 0 < r) (cp : P455Closure.Cap r w)(cb : w.count b = r) (ne : a ≠ b) (A B : W) (As Bs : List W)(aa : rows a w = A::As) (bb : rows b w = B::Bs) (pre : W) (first : A = pre ++ B)(merges : ∀ c d : Nat, ∃ keep : W, a ∈ keep ∧ b ∈ keep ∧ c ∈ keep ∧ d ∈ keep ∧SameBlock r (select keep w) a b) : Directed (Link r w) a b := byhave ma : A ∈ rows a w := by simp [aa]have mb : B ∈ rows b w := by simp [bb]have headA := row_head mahave headB := row_head mbhave pre_head : pre.head? = some a := bycases pre with| nil => simp_all| cons x p => simpa [first] using headAapply directed_of_prefix hr cp cb preapply rowmaps_extintro c dobtain ⟨keep,ha,hb,hc,hd,sm⟩ := merges c dhave not_empty : select keep pre ≠ [] := bycases pre with| nil => contradiction| cons x p =>have eq : x=a := by simpa using pre_headsimp [select,eq,ha]have rx := project_rows keep ha whave ry := project_rows keep hb whave capK := P455DefectProjection.select_cap keep cphave hdir := directed_of_same hr capK smhave orient' : ∃ k : W, rows a (select keep w) = (rows b (select keep w)).map (k ++ ·) := byrcases hdir with f|g· exact directed_prefix capK f· obtain ⟨k,h⟩ := directed_prefix capK grw [rx,ry,aa,bb] at hhave eq := (List.cons.inj h).1have len := congrArg List.length eqsimp only [first,select_append,List.length_append] at lenhave pos := List.length_pos_iff.mpr not_emptyomegaobtain ⟨k,h⟩ := orient'rw [rx,ry] at hhave fst := hrw [aa,bb] at fsthave eq := (List.cons.inj fst).1change select keep A = k ++ select keep B at eqrw [first,select_append] at eqhave := List.append_cancel_right eqsubst krw [← project_prefix] at hlet f := select [c,d]have nested : ∀ z : W, f (select keep z) = f z := fun z =>P455DefectProjection.select_sub keep [c,d] z (by simpa using And.intro hc hd)have proj := congrArg (List.map f) hsimpa only [List.map_map, Function.comp_def,nested] using projtheorem robust_separators {r w a b} (hr : 0 < r) (cp : P455Closure.Cap r w)(ca : w.count a = r) (cb : w.count b = r) (apart : ¬ SameBlock r w a b) :∃ c d : Nat, ∀ keep : W, a ∈ keep → b ∈ keep → c ∈ keep → d ∈ keep →¬ SameBlock r (select keep w) a b := byclassicalapply Classical.byContradictionintro contrahave merges : ∀ c d : Nat, ∃ keep : W, a ∈ keep ∧ b ∈ keep ∧ c ∈ keep ∧ d ∈ keep ∧SameBlock r (select keep w) a b := byintro c dapply Classical.byContradiction; intro missapply contra; refine ⟨c,d,?_⟩intro keep ha hb hc hd hmexact miss ⟨keep,ha,hb,hc,hd,hm⟩have oba : occ a w = r := (Problem455BlockBridge.occ_count ..).trans cahave obb : occ b w = r := (Problem455BlockBridge.occ_count ..).trans cbhave ne : a ≠ b := by rintro rfl; exact apart ⟨oba,obb,.refl _⟩apply apartrefine ⟨oba,obb,?_⟩have split (z : Nat) (cz : w.count z = r) : ∃ h t, rows z w = h::t := bycases eq : rows z w with| nil => have := rows_length z w; rw [eq,cz] at this; simp at this; omega| cons h t => exact ⟨h,t,rfl⟩obtain ⟨A,As,aa⟩ := split a caobtain ⟨B,Bs,bb⟩ := split b cbrcases List.suffix_or_suffix_of_suffix (row_suffix (a := b) (by simp [bb] : B ∈ rows b w))(row_suffix (a := a) (by simp [aa] : A ∈ rows a w)) with ⟨pre,h⟩|⟨pre,h⟩· exact directed_joined (reconstruct hr cp cb ne A B As Bs aa bb pre h.symm merges)· apply reversed_joined (reconstruct hr cp ca ne.symm B A Bs As bb aa pre h.symm ?_)intro c dobtain ⟨keep,ha,hb,hc,hd,m⟩ := merges c drefine ⟨keep,hb,ha,hc,hd,m.2.1,m.1,?_⟩rcases directed_of_same hr (P455DefectProjection.select_cap keep cp) m with f|g· exact reversed_joined f· exact directed_joined gend P455BlockSeparatorsend/- Begin Problem455FirstTesters (from finite-semigroup-identity-bases). -/sectionnamespace P455FirstTestersopen P455FirstRewrite P455Quotientdef plain (r : Nat) : Rules Nat wherer := rstep := fun _ _ => Falsereverse := False.elimcounts := False.elimextend := False.elimdef power (r : Nat) : W := List.replicate r 0def Binary (r : Nat) (T : W) := (∀ x ∈ T, x = 0 ∨ x = 1) ∧Cap r T ∧ 0 < T.count 0 ∧ 0 < T.count 1 ∧ (T.count 0 < r ∨ T.count 1 < r)abbrev Index (r : Nat) := { T : W // T = power r ∨ Binary r T }def Index.cap {r : Nat} (i : Index r) : Cap (plain r).r i.val := byrcases i.property with e | b· intro x; rw [e,power,List.count_replicate]; split <;> simp [plain]· exact b.2.1private theorem binary_length {T : W} (letters : ∀ x ∈ T, x = 0 ∨ x = 1) :T.length = T.count 0 + T.count 1 := byinduction T with| nil => rfl| cons x t ih =>have tail := ih (fun y m => letters y (List.mem_cons_of_mem _ m))rcases letters x List.mem_cons_self with rfl | rfl <;> simp [List.count_cons] <;> omegatheorem index_covered {r : Nat} (i : Index r) : i.val ∈ Problem455Finite.wordsUpTo [0, 1] (2*r) := byapply Problem455Finite.covered· rcases i.property with e | b· rw [e,power,List.length_replicate]; omega· have cnt := binary_length b.1have l := b.2.1 0have h := b.2.1 1omega· intro x mrcases i.property with e | b· rw [e] at m; have := List.eq_of_mem_replicate m; simp_all [power]· simpa using b.1 x mabbrev Carrier (r : Nat) := (i : Index r) → Q (plain r) i.valdef product (r : Nat) : Model (Carrier r) whereop := fun x y i => mul (plain r) i.cap (x i) (y i)unit := fun i => ofWord (plain r) i.val []assoc := fun x y z => funext (fun i => mul_assoc (plain r) i.cap (x i) (y i) (z i))oneL := fun x => funext (fun i => (unit_laws (plain r) i.cap (x i)).1)oneR := fun x => funext (fun i => (unit_laws (plain r) i.cap (x i)).2)theorem observed {r u v} (h : (product r).Valid u v) (i : Index r) (f : Sub) :ofWord (plain r) i.val (u.flatMap f) = ofWord (plain r) i.val (v.flatMap f) := bylet val : Nat → Carrier r := fun x j => ofWord (plain r) j.val (f x)have comp (w : W) : (product r).eval val w i = ofWord (plain r) i.val (w.flatMap f) := byinduction w with| nil => rfl| cons x xs ih =>change mul (plain r) i.cap (ofWord (plain r) i.val (f x)) ((product r).eval val xs i) = _rw [ih]; rflexact (comp u).symm.trans ((congrFun (h val) i).trans (comp v))private theorem reflect {r : Nat} {T A B : W} (factor : Factor A T)(eq : ofWord (plain r) T A = ofWord (plain r) T B) : A = B := byhave good : Good (plain r) T A := ⟨T,.refl T,factor⟩have path := ((same_nonzero_class (plain r) good).mp eq).2induction path with| refl => rfl| snoc _ f _ => exact False.elim fdef unaryImage (x z : Nat) : W := if z = x then [0] else []private theorem unary_word (x : Nat) (w : W) :w.flatMap (unaryImage x) = power (w.count x) := byinduction w with| nil => rfl| cons z t ih =>by_cases e : z = x <;> simp [List.flatMap_cons,unaryImage,e,List.count_cons,ih,power,List.replicate_succ]private theorem small_count {r u v} (h : (product r).Valid u v) {x : Nat} (bd : u.count x ≤ r) :u.count x = v.count x := bylet i : Index r := ⟨power r,Or.inl rfl⟩have eq := observed h i (unaryImage x)simp only [unary_word] at eqhave fac : Factor (power (u.count x)) (power r) := byrefine ⟨[], power (r-u.count x), ?_⟩simp only [List.nil_append,power,List.replicate_append_replicate]congr 1; omegasimpa [power] using congrArg List.length (reflect fac eq)def code (i j x : Nat) : W := if x = i then [0] else if x = j then [1] else []private theorem code_letters (i j : Nat) (w : W) (x : Nat) (m : x ∈ w.flatMap (code i j)) :x = 0 ∨ x = 1 := byobtain ⟨y,_,m⟩ := List.mem_flatMap.mp munfold code at msplit at m· exact Or.inl (List.mem_singleton.mp m)· split at m· exact Or.inr (List.mem_singleton.mp m)· simp at mprivate theorem code_counts (i j : Nat) (ne : i ≠ j) (w : W) :(w.flatMap (code i j)).count 0 = w.count i ∧ (w.flatMap (code i j)).count 1 = w.count j := byinduction w with| nil => simp| cons x xs ih =>by_cases xi : x=i <;> by_cases xj : x=j <;>simp_all [List.flatMap_cons,code,List.count_cons]private theorem decode (i j : Nat) (w : W) :(w.flatMap (code i j)).map (fun z => if z = 0 then i else j) = proj i j w := byinduction w with| nil => rfl| cons x t ih =>by_cases e : x=i <;> by_cases f : x=j <;> simp_all [List.flatMap_cons,code,proj]private theorem only_one {i j : Nat} (u : W) (miss : j ∉ u) :proj i j u = List.replicate (u.count i) i := byinduction u with| nil => rfl| cons x t ih =>have nx : x ≠ j := fun e => miss (e ▸ List.mem_cons_self)have tail := ih (fun m => miss (List.mem_cons_of_mem x m))by_cases xi : x=i <;> simp_all [proj,List.count_cons,List.replicate_succ]private theorem proj_swap (i j : Nat) (w : W) : proj i j w = proj j i w := bysimp only [proj,Or.comm]private theorem identical_letter (i : Nat) (w : W) :proj i i w = List.replicate (w.count i) i := byinduction w with| nil => rfl| cons z t ih => by_cases eq : z = i <;> simp_all [proj,List.count_cons,List.replicate_succ]/-- Every identity in this fixed finite tester product satisfies the actualclipped unary and binary restrictions used by the first-change proof. -/theorem tester_rule {r u v} (h : (product r).Valid u v) : TesterRule r u v := byhave clipped (x) : min (u.count x) (r+1) = min (v.count x) (r+1) := byby_cases a : u.count x ≤ r· rw [small_count h a]· by_cases b : v.count x ≤ r· rw [small_count (fun f => (h f).symm) b]· omegarefine ⟨clipped,?_⟩intro cu cv i j diffhave counts (x) : u.count x = v.count x := by have := clipped x; have := cu x; omegahave ne : i ≠ j := byintro e; subst j; apply diff; rw [identical_letter, identical_letter, counts]have positive (a b) (d : proj a b u ≠ proj a b v) : 0 < u.count b := byapply Nat.pos_of_ne_zero; intro zero; apply dhave zv : v.count b = 0 := (counts b).symm.trans zerorw [only_one u (List.count_eq_zero.mp zero),only_one v (List.count_eq_zero.mp zv),counts]have pj := positive i j diffhave pi := positive j i (by simpa only [proj_swap j i] using diff)apply Classical.byContradictionintro failhave low : u.count i < r ∨ u.count j < r := byhave := cu i; have := cu j; omegalet T := u.flatMap (code i j)obtain ⟨c0,c1⟩ := code_counts i j ne uhave letters := code_letters i j uhave cap : Cap r T := byintro xby_cases mem : x ∈ T· rcases letters x mem with rfl | rfl· exact c0 ▸ cu i· exact c1 ▸ cu j· rw [List.count_eq_zero_of_not_mem mem]; omegalet ix : Index r := ⟨T,Or.inr ⟨letters,cap,c0 ▸ pi,c1 ▸ pj,by simpa only [T,c0,c1] using low⟩⟩have eq := observed h ix (code i j)have fac : Factor T T := ⟨[],[],by simp⟩have ee := reflect fac eqdsimp [T] at eeapply diffrw [← decode i j u,← decode i j v,ee]/-- Extra components of the final direct product are arbitrary. Including theunmarked testers forces their consequences for every valid multiplication identity. -/def combine {A B : Type} (M : Model A) (N : Model B) : Model (A × B) whereop := fun x y => (M.op x.1 y.1,N.op x.2 y.2)unit := (M.unit,N.unit)assoc := fun _ _ _ => Prod.ext (M.assoc ..) (N.assoc ..)oneL := fun _ => Prod.ext (M.oneL _) (N.oneL _)oneR := fun _ => Prod.ext (M.oneR _) (N.oneR _)theorem valid_left {A B : Type} (M : Model A) (N : Model B) {u v}(h : (combine M N).Valid u v) : M.Valid u v := byintro flet g := fun x => (f x,N.unit)have fst (w : W) : ((combine M N).eval g w).1 = M.eval f w := byinduction w with| nil => rfl| cons x t ih => exact congrArg (M.op (f x)) ihexact (fst u).symm.trans ((congrArg Prod.fst (h g)).trans (fst v))theorem first_change_no_finite_basis {A : Type} (N : Model A) (r : Nat) (hr : 0 < r)(witnesses : ∀ k, ∃ U V D, RankWitness (combine (product r) N) r U V D ∧ k < D.length)(G : List (W × W)) (valid : ∀ u v, (u,v) ∈ G → (combine (product r) N).Valid u v) :∃ U V, U ≠ [] ∧ V ≠ [] ∧ (combine (product r) N).Valid U V ∧¬ Derives (fun u v => (u,v) ∈ G) U V :=no_finite_basis_of_witnesses _ r hr (fun _ _ h => tester_rule (valid_left _ _ h))witnesses G validend P455FirstTestersend/- Begin Problem455Schedule (from finite-semigroup-identity-bases). -/sectionnamespace P455Scheduleabbrev Edges := Nat → Nat → Propabbrev Bits := Nat → Boolinductive Path (R : Edges) : Nat → Nat → Prop| edge {x y} (e : R x y) : Path R x y| join {x y z} (l : Path R x y) (r : Path R y z) : Path R x zdef induced (C : List Nat) (E : Edges) : Edges := fun a b => a ∈ C ∧ b ∈ C ∧ E a bdef Acyclic (C : List Nat) (E : Edges) := ∀ a, ¬Path (induced C E) a adef Good (C : List Nat) (E : Edges) (s : Bits) :=∀ a b, E a b → (a ∈ C ∨ b ∈ C) → s a = true → s b = truedef Flip (C : List Nat) (E : Edges) (available : Nat → Prop) (s t : Bits) :=Good C E s ∧ Good C E t ∧ ∃ a ∈ C, available a ∧ s a ≠ t a ∧ ∀ b, b ≠ a → s b = t bdef Down (C : List Nat) (E : Edges) (available : Nat → Prop) (s t : Bits) :=Flip C E available s t ∧ ∀ a, t a = true → s a = truedef meet (A B : Bits) : Bits := fun a => A a && B aprivate theorem minimal {R : Edges} (no : ∀ a, ¬ R a a)(tr : ∀ {a b c}, R a b → R b c → R a c) (xs : List Nat) (ne : xs ≠ []) :∃ a ∈ xs, ∀ b ∈ xs, ¬ R b a := byinduction xs with| nil => exact (ne rfl).elim| cons x xs ih =>by_cases emp : xs = []· subst xsrefine ⟨x,List.mem_cons_self,?_⟩intro b hbobtain rfl := List.mem_singleton.mp hbexact no bobtain ⟨a,mem,first⟩ := ih empby_cases e : R x a· refine ⟨x,List.mem_cons_self,?_⟩intro b hbrcases List.mem_cons.mp hb with eq|hit· exact eq ▸ no x· exact fun k => first b hit (tr k e)· refine ⟨a,List.mem_cons_of_mem _ mem,?_⟩intro b hbrcases List.mem_cons.mp hb with eq|hit· exact eq ▸ e· exact first b hitprivate theorem switch {C E} (acy : Acyclic C E) (available : Nat → Prop) (s t : Bits)(sOK : Good C E s) (tOK : Good C E t) (todo : List Nat)(uniq : todo.Nodup)(all : ∀ a ∈ todo, a ∈ C ∧ available a ∧ s a = true ∧ t a = false)(cover : ∀ a, s a ≠ t a → a ∈ todo) :P455Quotient.Walk (Down C E available) s t := byclassicalby_cases empty : todo = []· have eq : s = t := byfunext a; apply Classical.byContradiction; intro diffexact List.not_mem_nil (empty ▸ cover a diff)rw [eq]; exact .refl _obtain ⟨a,am,first⟩ :=minimal (R := Path (induced C E)) acy (fun m n => .join m n) todo emptyobtain ⟨ac,ch,sa,ta⟩ := all a amlet v : Bits := fun j => if j=a then false else s jhave change : v a = false := by simp [v]have fixed (j) (h : j ≠ a) : v j = s j := by simp [v,h]have vOK : Good C E v := byintro i j edge touch onhave si : s i = true := byby_cases eq : i = a· subst i; simp [change] at on· exact (fixed i eq).symm.trans onby_cases eq : j = a· subst jhave off : t i = false := bycases e : t i with| false => rfl| true => have impossible := tOK i a edge (.inr ac) e; simp [ta] at impossiblehave active := cover i (by simp [si,off])exact False.elim (first i active (.edge ⟨(all i active).1,ac,edge⟩))· exact (fixed j eq).trans (sOK i j edge touch si)have single : Down C E available s v := byrefine ⟨⟨sOK,vOK,a,ac,ch,by simp [sa,change],fun j ne => (fixed j ne).symm⟩,?_⟩intro j hby_cases eq : j=a· subst j; simp [change] at h· exact (fixed j eq).symm.trans hhave next (j) (hj : j ∈ todo.erase a) :j ∈ C ∧ available j ∧ v j = true ∧ t j = false := byobtain ⟨ne,hit⟩ := uniq.mem_erase_iff.mp hjobtain ⟨h1,h2,h3,h4⟩ := all j hitexact ⟨h1,h2,(fixed j ne).trans h3,h4⟩have rem (j) (diff : v j ≠ t j) : j ∈ todo.erase a := byby_cases eq : j=a· subst j; exact False.elim (diff (change.trans ta.symm))· exact uniq.mem_erase_iff.mpr ⟨eq,cover j (fun h => diff ((fixed j eq).trans h))⟩have tail := switch acy available v t vOK tOK (todo.erase a) (uniq.erase a) next remexact (P455Quotient.Walk.snoc (.refl _) single).trans tailtermination_by todo.lengthdecreasing_byhave n := List.length_erase_of_mem amhave pos : 0 < todo.length := List.length_pos_iff.mpr emptyomegaprivate theorem down_to_meet {C E} (acy : Acyclic C E) (A B : Bits) (gA : Good C E A) (gB : Good C E B)(fixed : ∀ a, A a ≠ B a → a ∈ C) :P455Quotient.Walk (Down C E (fun a => A a=true ∧ B a=false)) A (meet A B) := bylet todo := (P455FirstRewrite.names C).filter (fun a => A a && !B a)have inTodo (a) : a ∈ todo ↔ a ∈ C ∧ A a = true ∧ B a = false := bysimp [todo,P455FirstRewrite.mem_names]have ok : Good C E (meet A B) := byintro i j edge hit hobtain ⟨a,b⟩ := Bool.and_eq_true_iff.mp hexact Bool.and_eq_true_iff.mpr ⟨gA i j edge hit a,gB i j edge hit b⟩apply switch acy _ _ _ gA ok todo ((P455FirstRewrite.names_distinct C).sublist List.filter_sublist)· intro a haobtain ⟨hc,h1,h2⟩ := (inTodo a).mp haexact ⟨hc,⟨h1,h2⟩,h1,by simp [meet,h2]⟩· intro a diffcases ha : A a <;> cases hb : B a <;> simp [meet,ha,hb] at diffexact (inTodo a).mpr ⟨fixed a (by simp [ha,hb]),ha,hb⟩/-- Explicit two phases. Within each phase every changed vertex moves in asingle direction. The starting-only and target-only vertex sets are disjoint. -/theorem phases {C E} (acy : Acyclic C E) (A B : Bits) (gA : Good C E A) (gB : Good C E B)(fixed : ∀ a, A a ≠ B a → a ∈ C) :P455Quotient.Walk (Down C E (fun a => A a=true ∧ B a=false)) A (meet A B) ∧P455Quotient.Walk (Down C E (fun a => B a=true ∧ A a=false)) B (meet A B) := byhave eq : meet B A = meet A B := by funext a; exact Bool.and_comm ..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))⟩def Toward (C : List Nat) (E : Edges) (goal : Bits) (s t : Bits) :=Flip C E (fun a => t a = goal a) s tprivate theorem map_walk {R S : Bits → Bits → Prop} {a b : Bits}(path : P455Quotient.Walk R a b) (one : ∀ {u v}, R u v → S u v) : P455Quotient.Walk S a b := byinduction path with| refl => exact .refl _| snoc _ m ih => exact .snoc ih (one m)private theorem reverse_path {R : Bits → Bits → Prop} {a b : Bits}(h : P455Quotient.Walk (fun s t => R t s) a b) : P455Quotient.Walk R b a := byinduction h with| refl => exact .refl _| snoc _ m ih => exact (P455Quotient.Walk.snoc (.refl _) m).trans ihtheorem schedule {C E} (acy : Acyclic C E) (A B : Bits) (gA : Good C E A) (gB : Good C E B)(fixed : ∀ a, A a ≠ B a → a ∈ C) :P455Quotient.Walk (Toward C E B) A B := byobtain ⟨lhs,rhs⟩ := phases acy A B gA gB fixedapply (map_walk lhs (S := Toward C E B) ?_).trans· exact reverse_path (map_walk rhs (S := fun s t => Toward C E B t s) (byintro s t stobtain ⟨⟨ok1,ok2,a,hc,ab,ne,unch⟩,down⟩ := sthave ons : s a = true := by cases h : s a <;> cases k : t a <;> simp_allexact ⟨ok2,ok1,a,hc,ons.trans ab.1.symm,Ne.symm ne,fun j h => (unch j h).symm⟩))· intro s t stobtain ⟨⟨ok1,ok2,a,hc,ab,ne,unch⟩,down⟩ := sthave off : t a = false := by cases h : s a <;> cases k : t a <;> simp_allexact ⟨ok1,ok2,a,hc,off.trans ab.2.symm,ne,unch⟩/-- Realizing the safe Boolean singletons by bounded-rank word steps producesan ordinary multiplication-only equational deduction for the two words. -/theorem derivation {C E} (acy : Acyclic C E) (A B : Bits) (gA : Good C E A) (gB : Good C E B)(fixed : ∀ a, A a ≠ B a → a ∈ C) (word : Bits → P455FirstRewrite.W){M : P455FirstRewrite.Model α} (k : Nat)(one : ∀ s t, Toward C E B s t →P455FirstRewrite.Step (fun u v => M.Valid u v ∧ P455FirstRewrite.rank u v ≤ k) (word s) (word t)) :P455FirstRewrite.Derives (fun u v => M.Valid u v ∧ P455FirstRewrite.rank u v ≤ k) (word A) (word B) := byhave lift {a b : Bits} (path : P455Quotient.Walk (Toward C E B) a b) :P455FirstRewrite.Derives (fun u v => M.Valid u v ∧ P455FirstRewrite.rank u v ≤ k)(word a) (word b) := byinduction path with| refl => exact .refl _| snoc _ move ih => exact .snoc ih (one _ _ move)exact lift (schedule acy A B gA gB fixed)end P455Scheduleend/- Begin Problem455EffectiveMachineCode (from finite-semigroup-identity-bases). -/section/- Explicit finite instruction arrays for the machines of the reduction. -/namespace P455EffectiveMachineopen P455MachineLocal P455MachineCleanupstructure Code (g q : Nat) wheremarker : Fin gblank : Fin gstart : Fin qrows : Vector (Vector (Option (Ins (Fin g) (Fin q))) g) qdef Code.read (C : Code g q) (s : Fin q) (a : Fin g) := (C.rows.get s).get adef Code.Safe (C : Code g q) : Prop := C.blank ≠ C.marker ∧ ∀ s a,match C.read s a with| none => True| some i => (i.symbol=C.marker ↔ a=C.marker) ∧ (a=C.marker → i.dir≠.left)def finiteAll (p : Fin n → Prop) (d : ∀ i,Decidable (p i)) : Decidable (∀ i,p i) := bylet f (i : Fin n) := @decide (p i) (d i)apply decidable_of_iff ((List.finRange n).all f=true)rw [List.all_eq_true]constructor· intro h ihave mem : i∈List.finRange n := byhave bound : i.val < (List.finRange n).length := by simpsimpa using (List.getElem_mem (l:=List.finRange n) bound)exact of_decide_eq_true (h i mem)· intro h i _exact @decide_eq_true (p i) (d i) (h i)instance (C : Code g q) : Decidable C.Safe := bylet p (s : Fin q) (a : Fin g) : Prop := match C.read s a with| none => True| some i => (i.symbol=C.marker ↔ a=C.marker) ∧ (a=C.marker → i.dir≠.left)let check (s : Fin q) (a : Fin g) : Decidable (p s a) := byunfold p; split <;> infer_instanceletI alld : Decidable (∀ s a,p s a) := finiteAll _ (fun s => finiteAll _ (check s))change Decidable (C.blank≠C.marker ∧ ∀ s a,p s a)infer_instancedef Code.machine (C : Code g q) (v : C.Safe) : Ordinary g q wheremarker := C.markerblank := C.blankblank_ne := v.1start := C.startdelta := C.readkeeps := byintro s a i ehave h := v.2 s arw [e] at hexact h.1leftSafe := byintro s i ehave h := v.2 s C.markerrw [e] at hexact h.2 rfldef Code.decode (C : Code g q) : Option (Ordinary g q) :=if h : C.Safe then some (C.machine h) else nonedef quote (M : Ordinary g q) : Code g q :=⟨M.marker,M.blank,M.start,Vector.ofFn (fun s => Vector.ofFn (M.delta s))⟩@[simp] theorem read_quote (M : Ordinary g q) (s a) : (quote M).read s a=M.delta s a := bysimp [Code.read,quote,Vector.get]theorem safe_quote (M : Ordinary g q) : (quote M).Safe := byrefine ⟨M.blank_ne,fun s a => ?_⟩rw [read_quote]cases e : M.delta s a with| none => trivial| some i =>exact ⟨M.keeps s a i e, fun h => M.leftSafe s i (by change a=M.marker at h; simpa [h] using e)⟩@[simp] theorem quote_decode (M : Ordinary g q) : (quote M).decode=some M := byrw [Code.decode,dif_pos (safe_quote M)]congr 1have ext (X Y : Ordinary g q) (mr : X.marker=Y.marker) (bl : X.blank=Y.blank)(st : X.start=Y.start) (dt : X.delta=Y.delta) : X=Y := bycases X; cases Y; simp_allexact ext _ _ rfl rfl rfl (funext fun s => funext fun a => read_quote M s a)/-- Names and a rectangular array of ordinary natural numbers give the publicmachine-code payload. 0 is an undefined instruction. 1+3*(g*s+a)+d codesa next state s, write symbol a and direction d (left/stay/right). -/def dirCode : Direction → Nat | .left => 0 | .stay => 1 | .right => 2def entryCode (g : Nat) (i : Option (Ins (Fin g) (Fin q))) : Nat :=match i with| none => 0| some x => 1+3*(g*x.state.val+x.symbol.val)+dirCode x.dirdef Code.numerals (C : Code g q) : List Nat :=[g,q,C.marker.val,C.blank.val,C.start.val] ++C.rows.toList.flatMap (fun row => row.toList.map (entryCode g))def unary (n : Nat) := List.replicate n true ++ [false]def Code.bits (C : Code g q) : List Bool := C.numerals.flatMap unaryend P455EffectiveMachineend/- Begin Problem455SourceTheorem (from finite-semigroup-identity-bases). -/sectionnamespace P455SourceTheoremopen P455Witness P455Paths P455ContactLift P455SourceFamilies P455PortReflectionopen P455EdgeSource P455Retained P455OriginalWalk Problem455.Slotsdef startLabel (c : Certificate) (second mate : Bool) : Nat :=match c with| .slot s => picked s| .functionality f => f.anchor.owner| .edge e =>let n := if second then e.b else e.aif mate then n.mate else n.ownerdef transferred (d : Nat → Nat) : Certificate → Certificate| .slot s => .slot (sendSlot d s)| .functionality f => .functionality (sendFunc d f)| .edge e => .edge (sendEdge d e)def sourceMarks (d : Nat → Nat) : Certificate → Marking| .slot s => markNode (sendNode d s.anchor)| .functionality f => markNode (sendNode d f.anchor)| .edge e => endpointMarks d edef SourceEvidence (r : Nat) (allow : Tag → Prop) (ts : Tiles) (v : W) (h : Nat → W)(seed : Nat) : Certificate → Prop| .slot s => SlotResult r allow v h seed s| .functionality f => FuncResult r allow ts v h f| .edge e => Holds r allow (endpointMarks (donor v h r) e) v ((sendEdge (donor v h r) e).query ts)theorem in_source {r allow mark v h l k seed} (hr : 0 < r)(cap : P455Closure.Cap r (l ++ v.flatMap h ++ k)) (ts : Tiles) (c : Certificate)(second mate : Bool) (ok : Holds r allow mark (l ++ v.flatMap h ++ k) (c.query r ts))(start : Supplies v h r seed (startLabel c second mate)) (guard : Guard r allow mark v seed 6) :SourceEvidence r allow ts v h seed c := bycases c with| slot s => exact slot_source hr cap s ok start guard| functionality f => exact functionality_source hr cap ts f ok start guard| edge e => exact edge_source_from_role hr cap ts e ok second mate start guard (by split <;> decide)theorem compressed_query {r allow ts v h seed c} (ev : SourceEvidence r allow ts v h seed c)(cmp : Compressed r v) :Holds r allow (sourceMarks (donor v h r) c) v ((transferred (donor v h r) c).query r ts) := bycases c with| slot s => exact ev.2.2.2 cmp| functionality f => exact ev.2.2.2.2 cmp| edge e => exact ev/-- Form in the evaluated rule word. Each bounded literal contact walk istransported with the identical sequence of choices. -/theorem arbitrary_reps_source_gadget {r allow mark T} (capT : P455Quotient.Cap r T)(val : Nat → P455Quotient.Q (rules r allow mark) T) (v : W) (h : Nat → W)(reps : ∀ x ∈ v, P455Quotient.ofWord (rules r allow mark) T (h x) = val x)(live : P455Quotient.eval (rules r allow mark) capT val v ≠ P455Quotient.zero (rules r allow mark) T)(ts : Tiles) (c : Certificate) (initial : Holds r allow mark T (c.query r ts))(second mate : Bool) (seed : Nat) (hr : 0 < r)(start : Supplies v h r seed (startLabel c second mate)) (guard : Guard r allow mark v seed 6) :∃ z l k, P455Quotient.Variant (rules r allow mark) T z ∧ z = l ++ v.flatMap h ++ k ∧Holds r allow mark z (c.query r ts) ∧ SourceEvidence r allow ts v h seed c ∧∀ p : List Step, p.length ≤ 6 → Walk r allow mark z (startLabel c second mate) p →Walk r allow mark v seed (relabel (donor v h r) p) ∧Supplies v h r (donor v h r (endpoint (startLabel c second mate) p))(endpoint (startLabel c second mate) p) := byobtain ⟨z,l,k,path,eq,ok⟩ := arbitrary_reps_designated capT val v h reps live c ts initialsubst zhave cap : P455Closure.Cap r (l ++ v.flatMap h ++ k) :=fun s => (P455Quotient.count_walk _ path s) ▸ capT sexact ⟨_,l,k,path,rfl,ok,in_source hr cap ts c second mate ok start guard,fun p bp wp => P455ContactLift.lift_walk hr cap start guard p bp wp⟩theorem expanded_query {r allow mark ts v h e kept seed c second mate T}(exp : Expansion v e kept) (hr : 1 < r) (capU : P455Closure.Cap r (v.flatMap e))(capF : P455Closure.Cap r (v.flatMap h))(original : OriginalGuard r allow mark (v.flatMap e) kept seed 6)(start : Supplies v h r seed (startLabel c second mate))(ev : SourceEvidence r allow ts v h seed c)(initial : Holds r allow mark T (c.query r ts)) (cmp : Compressed r (v.flatMap e)) :let d := donor v h rHolds r allow (sourceMarks d c) (v.flatMap e) ((transferred d c).query r ts) := bylet d := donor v h rhave pos : 0 < r := by omegacases c with| edge ed =>exact P455OriginalEdges.expand_edge exp hr capU ev| functionality f =>obtain ⟨bit,b,c,dist,_⟩ := evexact ⟨P455OriginalEdges.expand_markedNode exp hr capU bit,P455OriginalEdges.expand_neighbor exp hr capU f.dir b,P455OriginalEdges.expand_neighbor exp hr capU f.dir c,compressed_separates cmp dist,True.intro⟩| slot s =>obtain ⟨bit,walk,terminal,_⟩ := evhave eq : d (picked s) = seed := donor_eq pos capF starthave big := exp.walk hr capU _ _ walklet m := markNode (sendNode d s.anchor)let finalLabel := endpoint (picked s) s.stepshave ep : endpoint seed (relabel d s.steps) = d finalLabel := by rw [← eq,endpoint_relabel]have pickEq : picked (sendSlot d s) = d (picked s) := bycases z : s.startAtMate <;> simp [picked,sendSlot,sendNode,z]obtain ⟨len,_,termT⟩ := slot_route s initialhave valid := valid_slot s.defect termThave bigWalk : Walk r allow mark (v.flatMap e) seed (relabel d s.steps) :=remark_walk _ _ bighave reach : Near r allow mark (v.flatMap e) seed (d finalLabel) 6 :=⟨relabel d s.steps,bigWalk,ep,by simpa [relabel] using len⟩have ownerKept := (original _ reach).1have transfer (y : Nat) (inside : occupies v (d finalLabel) s.terminalIndex y) (cnt : v.count y = r) :occupies (v.flatMap e) (d finalLabel) s.terminalIndex y ∧ (v.flatMap e).count y = r := byhave present : y ∈ v := List.count_pos_iff.mp (by omega)have ky : kept y := byapply Classical.byContradictionintro absenthave := (exp.gaps y present absent).1omegahave mem : y ∈ e y := by rw [exp.literal y present ky]; simpexact ⟨exp.in_original_slot _ _ _ ownerKept inside y mem,(exp.count_eq _ (fun _ h => h) y ky).trans cnt⟩have term : Holds r allow m (v.flatMap e)(terminalSlot r (d finalLabel) s.terminalIndex (sendDefect d s.defect)) :=rebuild_terminal_in d s.defect valid cmp (fun hh => donor_eq pos capF hh) transfer terminalrefine ⟨P455OriginalEdges.expand_markedNode exp hr capU bit,by simpa [sendSlot,relabel,P455Witness.Holds] using len,?_,True.intro⟩apply (route_iff ..).mprchange Walk r allow m (v.flatMap e) (picked (sendSlot d s)) (relabel d s.steps) ∧Holds r allow m (v.flatMap e) (terminalSlot r (endpoint (picked (sendSlot d s)) (relabel d s.steps))s.terminalIndex (sendDefect d s.defect))rw [pickEq,endpoint_relabel]exact ⟨eq.symm ▸ big,term⟩/-- The complete quotient-to-original-word result. The evaluation substitutes hin the smaller word v. Independently e expands the fresh gaps of v to theoriginal source word U. No equality between these two substitutions is used. -/theorem arbitrary_reps_original_gadget {r allow mark T} (capT : P455Quotient.Cap r T)(val : Nat → P455Quotient.Q (rules r allow mark) T) (v : W) (h : Nat → W)(reps : ∀ x ∈ v, P455Quotient.ofWord (rules r allow mark) T (h x) = val x)(live : P455Quotient.eval (rules r allow mark) capT val v ≠ P455Quotient.zero (rules r allow mark) T)(ts : Tiles) (c : Certificate) (initial : Holds r allow mark T (c.query r ts))(second mate : Bool) (seed : Nat) (hr : 1 < r)(start : Supplies v h r seed (startLabel c second mate)){e kept} (exp : Expansion v e kept) (capU : P455Closure.Cap r (v.flatMap e))(original : OriginalGuard r allow mark (v.flatMap e) kept seed 6) :let d := donor v h rlet u := v.flatMap elet a := startLabel c second mate∃ z l k, P455Quotient.Variant (rules r allow mark) T z ∧ z = l ++ v.flatMap h ++ k ∧Holds r allow mark z (c.query r ts) ∧ SourceEvidence r allow ts v h seed c ∧(Compressed r u → Holds r allow (sourceMarks d c) u ((transferred d c).query r ts)) ∧∀ p : List Step, p.length ≤ 6 → Walk r allow mark z a p →Walk r allow mark u seed (relabel d p) ∧ endpoint seed (relabel d p) = d (endpoint a p) ∧(relabel d p).length = p.length ∧ kept (d (endpoint a p)) ∧Supplies v h r (d (endpoint a p)) (endpoint a p) ∧ Supplies u h r (d (endpoint a p)) (endpoint a p) := byobtain ⟨z,l,k,path,eq,ok,source,_⟩ := arbitrary_reps_source_gadget capT val v h reps live ts c initialsecond mate seed (by omega) start (exp.guard hr capU original)subst zhave cap : P455Closure.Cap r (l ++ v.flatMap h ++ k) :=fun s => (P455Quotient.count_walk _ path s) ▸ capT sexact ⟨_,l,k,path,rfl,ok,source,expanded_query exp hr capU (factor_cap cap) original start source initial,fun p len walk => P455OriginalWalk.lift_walk exp hr capU original cap start p len walk⟩end P455SourceTheoremend/- Begin Problem455SmallRank (from finite-semigroup-identity-bases). -/sectionnamespace P455SmallRankopen P455Closure P455Compression P455Uncrossedopen P455FirstRewrite (names rank size_le mem_names names_distinct Step Model)private def lits : List Piece → W| [] => []| .literal a :: t => a :: lits t| .gap _ :: t => lits tprivate def gaps (n : Nat) : List Piece → W| [] => []| .literal _ :: t => gaps (n+1) t| .gap _ :: t => n :: gaps (n+1) tprivate theorem gap_bound (n : Nat) : ∀ (cs : List Piece), noTouch cs →(gaps n cs).length ≤ (lits cs).length + 1| [],_ => by simp [gaps,lits]| .literal _ :: cs,ok => byhave := gap_bound (n+1) cs oksimpa [gaps,lits] using Nat.le_step this| [.gap _],_ => by simp [gaps,lits]| .gap _ :: .literal _ :: cs,ok => byhave h := gap_bound (n+1+1) cs oksimp only [gaps,lits,List.length_cons]omega| .gap _ :: .gap _ :: _,ok => False.elim okprivate theorem lit_subset (cs : List Piece) : (lits cs).Sublist (cs.flatMap body) := byinduction cs with| nil => exact .slnil| cons p cs ih =>cases p with| literal a => exact ih.cons₂ a| gap w => exact ih.trans (List.sublist_append_right _ _)private theorem cover (keep : W) (n : Nat) (cs : List Piece)(all : ∀ c ∈ cs,good keep c) (a : Nat) (ha : a ∈ code n cs) :a ∈ keep ∨ a ∈ gaps n cs := byinduction cs generalizing n with| nil => cases ha| cons c cs ih =>have tail (p) (hp : p ∈ cs) := all p (List.mem_cons_of_mem _ hp)cases c with| literal x =>rcases List.mem_cons.mp ha with e|m· exact .inl (e ▸ all (.literal x) List.mem_cons_self)· exact ih (n+1) tail m| gap w =>rcases List.mem_cons.mp ha with e|m· exact .inr (List.mem_cons.mpr (.inl e))· exact (ih (n+1) tail m).imp_right (List.mem_cons_of_mem _)private theorem lit_mem {keep : W} (cs : List Piece) (all : ∀ c ∈ cs,good keep c) :∀ a ∈ lits cs, a ∈ keep := byinduction cs with| nil => simp [lits]| cons c cs ih =>have tail (p) (hp : p ∈ cs) := all p (List.mem_cons_of_mem _ hp)cases c with| literal x =>intro a m; rcases List.mem_cons.mp m with e|h· exact e ▸ all (.literal x) List.mem_cons_self· exact ih tail a h| gap _ => exact ih tailprivate theorem count_away (a : Nat) (w : W) :w.length = w.count a + (w.filter (· != a)).length := byinduction w with| nil => rfl| cons b w ih =>by_cases e : b = a <;> simp [e,List.count_cons] <;> omegaprivate theorem length_bound (r : Nat) (C w : W) (cap : Cap r w)(covered : ∀ a ∈ w, a ∈ C) : w.length ≤ r*C.length := byinduction C generalizing w with| nil =>cases w with| nil => simp| cons a t => exact (List.not_mem_nil (covered a List.mem_cons_self)).elim| cons a C ih =>let t := w.filter (· != a)have subset : t.Sublist w := List.filter_sublisthave ht : Cap r t := fun b => Nat.le_trans (subset.count_le b) (cap b)have tc (b) (hb : b ∈ t) : b ∈ C := byobtain ⟨bw,ba⟩ := List.mem_filter.mp hbexact (List.mem_cons.mp (covered b bw)).resolve_left (by simpa using ba)have h := ih t ht tchave split := count_away a whave c := cap asimp only [List.length_cons,Nat.mul_succ]dsimp [t] at h; omegaprivate theorem literal_bound {r : Nat} (u keep : W) (cap : Cap r u) :(lits (pieces keep u)).length ≤ r*(names keep).length := byhave sub := lit_subset (pieces keep u)rw [decoded] at subapply length_bound· exact fun a => Nat.le_trans (sub.count_le a) (cap a)· exact fun a h => (mem_names a keep).mpr (lit_mem _ (pieces_good keep u) a h)private theorem code_length (n : Nat) (cs : List Piece) :(code n cs).length = (lits cs).length + (gaps n cs).length := byinduction cs generalizing n with| nil => rfl| cons c cs ih => cases c <;> simp [code,lits,gaps,ih,Nat.add_assoc,Nat.add_comm,Nat.add_left_comm]theorem small_length {r : Nat} (u keep : W) (cap : Cap r u) :(small u keep).length ≤ 2*(r*(names keep).length)+1 := byhave l := literal_bound u keep caphave g := gap_bound (base u keep) (pieces keep u) (maximal keep u)unfold small; rw [code_length]; omega/-- Covers the joint rank of both sides when they have identical support,counting each kept name only once even when the given list contains repeats. -/theorem joint_rank {r : Nat} (u keep v : W) (cap : Cap r u)(same : ∀ a ∈ v, a ∈ small u keep) :rank (small u keep) v ≤ (names keep).length + r*(names keep).length + 1 := bylet cs := pieces keep ulet n := base u keephave l := literal_bound u keep caphave g := gap_bound n cs (maximal keep u)have le : rank (small u keep) v ≤ ((names keep) ++ gaps n cs).length := byapply size_le (names_distinct _)intro a hahave ma := (List.mem_append.mp ((mem_names _ _).mp ha)).elim id (same a)have mem := cover keep n cs (pieces_good keep u) a maexact List.mem_append.mpr (mem.imp_left (mem_names a keep).mpr)simp only [List.length_append] at ledsimp only [cs] at g; dsimp only [cs] at le; omegaprivate theorem lookup_nonempty (keep : W) (cs : List Piece) (all : ∀ c ∈ cs,good keep c)(n a : Nat) : lookup n cs a ≠ [] := byinduction cs generalizing n with| nil => simp [lookup]| cons c cs ih =>have tail (p) (hp : p ∈ cs) := all p (List.mem_cons_of_mem _ hp)cases c with| literal x => exact ih tail (n+1)| gap w =>by_cases e : a=n· simpa only [lookup,if_pos e] using (all (.gap w) List.mem_cons_self).1· simpa only [lookup,if_neg e] using ih tail (n+1)theorem expansion_nonempty (u keep : W) (a : Nat) : expand u keep a ≠ [] :=lookup_nonempty keep _ (pieces_good keep u) _ a/-- The literal source flip is one step using a semantically valid identity onat most N + r*N + 1 variables. All substitution images, even for unusedvariables, are nonempty semigroup words. -/theorem bounded_step {A : Type} (M : Model A) {r allowed} (f : Frame Nat)(l k keep : W) {x y : Nat} (hx : x ∈ keep) (hy : y ∈ keep)(hp : f.p = [x]) (hq : f.q = [y]) (valid : f.Valid r allowed (fun _ _ => False))(b : Bool) (cap : Cap r (side f l k b))(semantic : M.Valid (small (side f l k b) keep) (small (side f l k (!b)) keep)) :let N := (names keep).lengthStep (fun u v => M.Valid u v ∧ rank u v ≤ N+r*N+1)(side f l k b) (side f l k (!b)) := bydsimp onlyobtain ⟨g,left,right,gp,_,_,eq,expanded⟩ :=P455CompressedFrame.canonical_pair f l k keep hx hy hp hq valid b caphave letters (a) (ha : a ∈ small (side f l k (!b)) keep) : a ∈ small (side f l k b) keep := byrw [eq] at ha ⊢exact (P455Uncrossed.same_letters g left right b a).mpr hahave nonempty (c : Bool) : small (side f l k c) keep ≠ [] := byrw [eq]; obtain ⟨t,e⟩ := g.core_starts csimp [side,e]refine ⟨_,_,[],[],expand (side f l k b) keep,.inl ⟨semantic,joint_rank _ _ _ cap letters⟩,nonempty b,nonempty (!b),expansion_nonempty _ _,?_,?_⟩all_goals simp only [List.nil_append,List.append_nil,eq,expanded]end P455SmallRankend/- Begin Problem455OtherProjection (from finite-semigroup-identity-bases). -/sectionnamespace P455OtherProjectionopen P455Witness P455Paths P455SourceFamilies P455PortReflection P455DefectProjection Problem455.Slotsopen Problem455Swap (SameBlock)def Covers (keep xs : W) := ∀ a ∈ xs, a ∈ keepprivate theorem fan {r w} (hr : 0 < r) (cp : P455Closure.Cap r w) (a : Nat) (xs : W)(ca : w.count a = r) (sat : ∀ b ∈ xs, w.count b = r)(diff : ∀ b ∈ xs, ¬ SameBlock r w a b) :∃ aux : W, aux.length ≤ 2*xs.length ∧ ∀ keep : W, a ∈ keep → Covers keep xs → Covers keep aux →∀ b ∈ xs, ¬ SameBlock r (select keep w) a b := byinduction xs with| nil => exact ⟨[],by simp,by simp⟩| cons x xs ih =>obtain ⟨c,d,wit⟩ := P455BlockSeparators.robust_separators hr cp ca (sat x (by simp)) (diff x (by simp))obtain ⟨more,len,win⟩ := ih (fun b h => sat b (by simp [h])) (fun b h => diff b (by simp [h]))refine ⟨c::d::more,by simp; omega,?_⟩intro keep ha members extra b hbrcases List.mem_cons.mp hb with rfl|hx· exact wit keep ha (members _ (by simp)) (extra _ (by simp)) (extra _ (by simp))· exact win keep ha (fun j hj => members j (by simp [hj])) (fun j hj => extra j (by simp [hj])) b hxtheorem simultaneous {r w} (hr : 0 < r) (cp : P455Closure.Cap r w) (xs : W)(sat : ∀ a ∈ xs, w.count a = r) (diff : xs.Pairwise (fun a b => ¬ SameBlock r w a b)) :∃ aux : W, aux.length ≤ xs.length * (xs.length-1) ∧ ∀ keep : W, Covers keep xs → Covers keep aux →xs.Pairwise (fun a b => ¬ SameBlock r (select keep w) a b) := byinduction xs with| nil => exact ⟨[],by simp,by simp⟩| cons a xs ih =>obtain ⟨ds,pw⟩ := List.pairwise_cons.mp diffhave st (b) (h : b ∈ xs) := sat b (by simp [h])obtain ⟨xs₁,n₁,k₁⟩ := fan hr cp a xs (sat a (by simp)) st dsobtain ⟨xs₂,n₂,k₂⟩ := ih st pwrefine ⟨xs₁ ++ xs₂,?_,?_⟩· simp only [List.length_append,List.length_cons,Nat.add_sub_cancel]have le := Nat.add_le_add n₁ n₂cases n : xs.length with| zero => simpa only [n,Nat.mul_zero,Nat.zero_mul] using le| succ m =>simp [n,Nat.add_mul,Nat.mul_add,Nat.succ_mul,Nat.mul_succ] at *omega· intro keep mem morehave keepX (b) (h : b ∈ xs) := mem b (by simp [h])exact List.pairwise_cons.mpr ⟨k₁ keep (mem a (by simp)) keepX (fun z h => more z (by simp [h])),k₂ keep keepX (fun z h => more z (by simp [h]))⟩theorem walk_count {r allow mark w} (cap : P455Closure.Cap r w) (a : Nat) (p : List Step)(ct : w.count a = r) (walk : Walk r allow mark w a p) : w.count (endpoint a p) = r := byinduction p generalizing a with| nil => exact ct| cons bc p ih =>obtain ⟨b,c⟩ := bcapply ih b _ walk.2cases c with| record tag rev =>cases rev with| false => exact (record_counts cap walk.1).2| true => exact (record_counts cap walk.1).1| port phase rev => exact walk.1.2.2.1theorem bounded_overflow {r allow u} (hr : 0 < r) (cap : P455Closure.Cap r u) (s : SlotCertificate)(xs : W) (kind : s.defect = .overflow xs) (ok : Holds r allow (markNode s.anchor) u (s.query r)) :∃ keep : W, keep.length ≤ 43 ∧ s.anchor.owner ∈ keep ∧ s.anchor.mate ∈ keep ∧Covers keep (s.steps.map Prod.fst ++ xs) ∧ P455Closure.Cap r (select keep u) ∧Holds r allow (markNode s.anchor) (select keep u) (s.query r) := bylet a := picked slet t := endpoint a s.stepsobtain ⟨bound,walk,term⟩ := slot_route s okrw [kind] at termobtain ⟨len,diff,all,_⟩ := termhave members (b : Nat) (h : b ∈ xs) :u.count b = r ∧ slotStart s.terminalIndex ∧ occupies u t s.terminalIndex b :=(allQ_iff _).mp all _ (List.mem_map_of_mem h)have ct := record_counts cap (marked_typed (a := s.anchor) (bit := s.bit) ok.1)have start : u.count a = r := bycases side : s.startAtMate <;> simp [a,picked,side,ct]have termCount := walk_count cap a s.steps start walkhave st : ∀ b ∈ t::xs, u.count b = r := byintro b h; rcases List.mem_cons.mp h with rfl|h· exact termCount· exact (members b h).1obtain ⟨more,n,apart⟩ := simultaneous hr cap (t::xs) st ((P455TerminalTransfer.block_separation _).mp diff)let keep := s.anchor.owner :: s.anchor.mate :: (s.steps.map Prod.fst ++ xs ++ more)have owner : s.anchor.owner ∈ keep := by simp [keep]have mate : s.anchor.mate ∈ keep := by simp [keep]have used (z) (hz : z ∈ s.steps.map Prod.fst ++ xs) : z ∈ keep :=List.mem_cons_of_mem _ (List.mem_cons_of_mem _ (List.mem_append_left _ hz))have keptOcc (b) (hb : b ∈ xs) := used b (List.mem_append_right _ hb)have path (m : Step) (hm : m ∈ s.steps) : m.1 ∈ keep :=used _ (List.mem_append_left _ (List.mem_map_of_mem hm))have pickedKept : a ∈ keep := by cases side : s.startAtMate <;> simp [a,picked,side,owner,mate]have last := endpoint_kept keep a s.steps pickedKept pathhave allSep := apart keep (by simpa [Covers] using And.intro last keptOcc)(fun z h => by simp [keep,h])refine ⟨keep,?_,owner,mate,used,select_cap keep cap,select_marked keep _ _ owner mate ok.1,bound,?_,True.intro⟩· change xs.length = 5 at lensimp only [List.length_cons,len] at nsimp [keep,len]omega· apply (route_iff ..).mprrefine ⟨select_walk keep a s.steps pickedKept path walk,?_⟩rw [kind]refine ⟨len,(P455TerminalTransfer.block_separation _).mpr allSep,?_,True.intro⟩apply (allQ_iff _).mprintro q hq; obtain ⟨b,h,rfl⟩ := List.mem_map.mp hqhave m := members b hexact ⟨(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⟩theorem select_early {r allow mark u} (keep xs ys : W) (hx : Covers keep xs) (hy : Covers keep ys)(obs : Holds r allow mark u (earlyBefore xs ys)) : Holds r allow mark (select keep u) (earlyBefore xs ys) := byapply (earlyBefore_iff _ _).mprintro a ha b hbapply select_order keep _ _ ((earlyBefore_iff _ _).mp obs a ha b hb)simp [hx a ha,hy b hb]theorem select_port {r allow mark u} (keep : W) (a b : Node) (i : Nat)(keepA : Covers keep (roles a)) (keepB : Covers keep (roles b))(obs : Holds r allow mark u (orientedPort i a b)) : Holds r allow mark (select keep u) (orientedPort i a b) := byhave ao := keepA a.owner (by simp [roles]); have am := keepA a.mate (by simp [roles])have bo := keepB b.owner (by simp [roles]); have bm := keepB b.mate (by simp [roles])obtain ⟨ra,rb,early,order,_⟩ := obsrefine ⟨select_record keep _ _ _ ao am ra,select_record keep _ _ _ bo bm rb,?_,?_,True.intro⟩· rcases early with e|e· exact .inl (select_early keep _ _ keepA keepB e)· exact .inr (select_early keep _ _ keepB keepA e)· apply select_order keep _ _ order; simp [ao,am,bo,bm]theorem select_neighbor {r allow mark u} (keep : W) (ts : Tiles) (a b : Node) (dir : Dir)(keepA : Covers keep (roles a)) (keepB : Covers keep (roles b))(obs : Holds r allow mark u (neighbor ts a b dir)) :Holds r allow mark (select keep u) (neighbor ts a b dir) := byhave ao := keepA a.owner (by simp [roles]); have bo := keepB b.owner (by simp [roles])cases dir with| down => exact ⟨obs.1,select_port keep _ _ _ keepA keepB obs.2⟩| up => exact ⟨obs.1,select_port keep _ _ _ keepB keepA obs.2⟩| right => exact ⟨obs.1,select_port keep _ _ _ keepA keepB obs.2.1,select_order keep _ (by simp [ao,bo]) obs.2.2.1,True.intro⟩| left => exact ⟨obs.1,select_port keep _ _ _ keepB keepA obs.2.1,select_order keep _ (by simp [ao,bo]) obs.2.2.1,True.intro⟩theorem bounded_functionality {r allow u} (hr : 0 < r) (cap : P455Closure.Cap r u)(ts : Tiles) (f : FunctionalityCertificate)(ok : Holds r allow (markNode f.anchor) u (f.query ts)) :∃ keep : W, keep.length ≤ 8 ∧ Covers keep (roles f.anchor ++ roles f.b ++ roles f.c) ∧P455Closure.Cap r (select keep u) ∧ Holds r allow (markNode f.anchor) (select keep u) (f.query ts) := byobtain ⟨anchor,nb,nc,apart,_⟩ := oklet role := roleOf f.distinguishMatehave sat (n : Node) (obs : Holds r allow (markNode f.anchor) u (neighbor ts f.anchor n f.dir)) :u.count (role n) = r := byhave ct := record_counts cap (neighbor_target_record obs)cases side : f.distinguishMate <;> simp [role,roleOf,side,ct]obtain ⟨x,y,diff⟩ := P455BlockSeparators.robust_separators hr cap (sat _ nb) (sat _ nc) apartlet names := roles f.anchor ++ roles f.b ++ roles f.clet keep := x::y::nameshave k : Covers keep names := fun z hz => by simp [keep,hz]have ka : Covers keep (roles f.anchor) := fun z h => k z (by simp [names,h])have kb : Covers keep (roles f.b) := fun z h => k z (by simp [names,h])have kc : Covers keep (roles f.c) := fun z h => k z (by simp [names,h])have kr (n : Node) (h : Covers keep (roles n)) : role n ∈ keep := byapply hcases side : f.distinguishMate <;> simp [roles,role,roleOf,side]refine ⟨keep,by simp [keep,names,roles],k,select_cap keep cap,select_marked keep _ _ (ka _ (by simp [roles])) (ka _ (by simp [roles])) anchor,select_neighbor keep ts _ _ _ ka kb nb,select_neighbor keep ts _ _ _ ka kc nc,diff keep (kr _ kb) (kr _ kc) (by simp [keep]) (by simp [keep]),True.intro⟩end P455OtherProjectionend/- Begin Problem455StructuralWords (from finite-semigroup-identity-bases). -/sectionnamespace P455Structuralopen P455Witness P455Quotient P455Closure P455Uncrossed Problem455.Slotsopen P455SourceFamilies P455FirstTestersabbrev W := List Natdef Rec (T : W) (r : Nat) (allow : Tag → Prop) (a b : Nat) :=∃ tag, Holds r allow (fun _ _ => False) T (.record a b tag)def Edge (T : W) (r : Nat) (allow : Tag → Prop) (a b : Nat) :=Rec T r allow a b ∨ Rec T r allow b adef Width (k : Nat) (T : W) := ∃ C : W, C.length ≤ k ∧ ∀ x ∈ T, x ∈ Cdef Overlap (T : W) (r : Nat) (allow : Tag → Prop) :=∃ o p q, o ≠ p ∧ o ≠ q ∧ p ≠ q ∧ Edge T r allow o p ∧ Edge T r allow o qdef Intrusion (T : W) (r : Nat) (allow : Tag → Prop) :=∃ o p z j, o ≠ p ∧ z ≠ o ∧ z ≠ p ∧ Rec T r allow o p ∧ sees T [(o,0),(z,j),(p,2)]def Structural (T : W) (r : Nat) (allow : Tag → Prop) :=(Width 4 T ∧ Overlap T r allow) ∨ (Width 3 T ∧ Intrusion T r allow)def early (a b : Nat) : W := [a,a,b,a,b,b]def Closed (T : W) (a b : Nat) :=a ≠ b ∧ ∃ L R : W, T = L ++ early a b ++ R ∧ a ∉ L ∧ b ∉ Lprivate theorem only_z (x z : Nat) (L : W) (nx : x ∉ L) :select [x,z] L = List.replicate (L.count z) z := byinduction L with| nil => rfl| cons c t ih =>have nt : x ∉ t := fun h => nx (List.mem_cons_of_mem _ h)have cx : c ≠ x := fun e => nx (e ▸ List.mem_cons_self)by_cases cz : c = z <;> simp_all [select,List.count_cons,List.replicate_succ]private theorem early_projection {a b x z : Nat} {T : W} (closed : Closed T a b)(inPair : x = a ∨ x = b) (outside : z ≠ a ∧ z ≠ b) :∃ n R, select [x,z] T = List.replicate n z ++ [x,x,x] ++ R := byobtain ⟨ab,L,R,rfl,na,nb⟩ := closedrefine ⟨L.count z,select [x,z] R,?_⟩rcases inPair with rfl|rfl <;> rw [select_append,select_append,only_z _ _ _ (by assumption)] <;>simp [select,early,ab,Ne.symm ab,Ne.symm outside.1,Ne.symm outside.2]private theorem not_record_tail {x z : Nat} (xz : x ≠ z) (n : Nat) (tail : W) (tag : Tag) (bit : Bool) :List.replicate n z ++ [x,x,x] ++ tail ≠ profile x z tag bit ∧List.replicate n z ++ [x,x,x] ++ tail ≠ profile z x tag bit := bycases n with| zero => simp [profile,profilePrefix,xz]| succ n =>cases n with| zero => simp [profile,profilePrefix,xz,Ne.symm xz,List.replicate_succ]| succ n =>cases n with| zero => simp [profile,profilePrefix,xz,Ne.symm xz,List.replicate_succ]| succ n => simp [profile,profilePrefix,xz,Ne.symm xz,List.replicate_succ]theorem no_external_record {r allow a b T} (closed : Closed T a b) {x z : Nat}(inside : x = a ∨ x = b) (out : z ≠ a ∧ z ≠ b) : ¬ Edge T r allow x z := byobtain ⟨n,tail,eq⟩ := early_projection closed inside outhave nz : x ≠ z := by omegarintro (⟨t,_,_,_,bit,profileEq⟩|⟨t,_,_,_,bit,profileEq⟩)· exact (not_record_tail nz n tail t bit).1 (eq.symm.trans profileEq)· exact (not_record_tail nz n tail t bit).2 (eq.symm.trans ((select_pair_symm x z T).symm.trans profileEq))private theorem early_bound {T : W} {a b o p z j : Nat} (closed : Closed T a b)(oi : o=a ∨ o=b) (pi' : p=a ∨ p=b) (out : z ≠ a ∧ z ≠ b) :¬ sees T [(o,0),(z,j),(p,2)] := byobtain ⟨ab,L,R,rfl,na,nb⟩ := closedintro obshave no : o ∉ L := oi.elim (fun e => e ▸ na) (fun e => e ▸ nb)have cp : (early a b).count p = 3 := byrcases pi' with rfl|rfl <;> simp [early,List.count_cons,ab,Ne.symm ab]let inner := (events (early a b)).map (shift (fun x => L.count x))let right := stamp (fun x => L.count x + (early a b).count x) Rhave h : [(o,0),(z,j),(p,2)].Sublist (events L ++ (inner ++ right)) := bysimpa only [sees,events_of_factor,inner,right] using obshave nl : (o,0) ∉ events L := fun m => no (stamped_mem_label _ _ _ m)have nr : (p,2) ∉ right := byintro mhave low := (P455ContactGeometry.stamp_range (fun x => L.count x + (early a b).count x) R m).1omegahave strip {α : Type} (x : α) (pat u v : List α) (nx : x ∉ u)(sub : (x::pat).Sublist (u++v)) : (x::pat).Sublist v := byinduction u with| nil => exact sub| cons c u ih =>cases sub with| cons _ s => exact ih (fun m => nx (List.mem_cons_of_mem _ m)) s| cons_cons => exact False.elim (nx List.mem_cons_self)have h1 := (strip _ _ _ _ nl h).reversesimp only [List.reverse_append,List.reverse_cons,List.reverse_nil,List.nil_append,List.cons_append] at h1have h2 := (strip _ _ right.reverse inner.reverse (by simpa using nr) h1).reversehave mid : (z,j) ∈ inner := by simpa using h2.subset (show (z,j) ∈ ([(p,2),(z,j),(o,0)] : List Event).reverse by simp)obtain ⟨e,me,eq⟩ := List.mem_map.mp midhave ze : e.1 = z := congrArg Prod.fst eqhave is := stamped_mem_label _ _ _ mesimp [early,ze,out.1,out.2] at isprivate theorem rec_mem {T r allow a b} (h : Rec T r allow a b) : a ∈ T ∧ b ∈ T := byobtain ⟨t,_,_,_,bit,eq⟩ := hhave f (x : Nat) (hx : x=a ∨ x=b) : x ∈ T := byhave mm : x ∈ profile a b t bit := by rcases hx with rfl|rfl <;> simp [profile,profilePrefix]rw [← eq] at mmexact (List.mem_filter.mp mm).1exact ⟨f a (.inl rfl),f b (.inr rfl)⟩private theorem edge_mem {T r allow a b} (h : Edge T r allow a b) : a ∈ T ∧ b ∈ T :=h.elim rec_mem (fun q => (rec_mem q).symm)private theorem closed_mem {T a b} (h : Closed T a b) : a ∈ T ∧ b ∈ T := byobtain ⟨_,l,t,rfl,_,_⟩ := hsimp [early]private theorem separated_core {T r allow a b o p} (c : Closed T a b) (edge : Edge T r allow o p) :(o=a ∨ o=b) ↔ (p=a ∨ p=b) := byconstructor· intro happly Classical.byContradiction; intro nexact no_external_record c h ⟨fun e => n (.inl e),fun e => n (.inr e)⟩ edge· intro happly Classical.byContradiction; intro nexact no_external_record c h ⟨fun e => n (.inl e),fun e => n (.inr e)⟩ edge.symmtheorem structural_excludes_closed {r allow T a b} (stest : Structural T r allow) (c : Closed T a b) : False := byobtain ⟨ma,mb⟩ := closed_mem chave ab := c.1rcases 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⟩· have linkP := separated_core c e1have linkQ := separated_core c e2by_cases h : o=a ∨ o=b· have hp := linkP.mp h; have hq := linkQ.mp h; omega· have A := edge_mem e1; have B := edge_mem e2have uniq : [a,b,o,p,q].Nodup := by simp [List.nodup_cons]; omegahave sub (x) (m : x ∈ [a,b,o,p,q]) : x ∈ C := bysimp only [List.mem_cons,List.not_mem_nil,or_false] at mrcases m with rfl|rfl|rfl|rfl|rfl <;> apply Cmem <;> simp_allhave := P455FirstRewrite.size_le uniq subsimp at this; omega· have link := separated_core c (Or.inl rec' : Edge T r allow o p)by_cases h : o=a ∨ o=b· have hp := link.mp happly early_bound c h hp _ seenomega· have A := rec_mem rec'have uniq : [a,b,o,p].Nodup := by simp [List.nodup_cons]; omegahave sub (x) (m : x ∈ [a,b,o,p]) : x ∈ C := bysimp only [List.mem_cons,List.not_mem_nil,or_false] at mrcases m with rfl|rfl|rfl|rfl <;> apply Cmem <;> simp_allhave := P455FirstRewrite.size_le uniq subsimp at this; omegaend P455Structuralend/- Begin Problem455RectangleRank (from finite-semigroup-identity-bases). -/sectionnamespace P455RectangleRankopen P455FirstRewritedef owner (i : Nat) := 2*idef mate (i : Nat) := 2*i+1def privateCell (i : Nat) : W := [owner i,owner i,mate i,owner i,mate i,mate i]def mutableCell (bit : Nat → Bool) (i : Nat) : W :=if bit i then [mate i,owner i] else [owner i,mate i]def word (t : Nat) (middle tail : W) (bit : Nat → Bool) :=(List.range t).flatMap privateCell ++ middle ++ (List.range t).flatMap (mutableCell bit) ++ taildef constant (b : Bool) : Nat → Bool := fun _ => bprivate theorem within {t i : Nat} (m : i ∈ List.range t) {x : Nat}(member : x = owner i ∨ x = mate i) : x < 2*t := byhave := List.mem_range.mp munfold owner mate at memberomegatheorem word_names {t : Nat} {middle tail : W} (bit : Nat → Bool)(small : ∀ x ∈ middle ++ tail, x < 2*t) (x) (hx : x ∈ word t middle tail bit) : x < 2*t := bysimp only [word,List.mem_append,List.mem_flatMap] at hxrcases hx with ((⟨i,mi,m⟩|m)|⟨i,mi,m⟩)|m· apply within misimp only [privateCell,List.mem_cons,List.mem_nil_iff,or_false] at mrcases m with h|h|h|h|h|h <;> simp [h]· exact small x (List.mem_append_left _ m)· apply within miunfold mutableCell at msplit at m <;> simp_all [Or.comm]· exact small x (List.mem_append_right _ m)private theorem private_factor {t i : Nat} (ix : i < t) (middle tail : W) (bit : Nat → Bool) :P455Quotient.Factor (privateCell i) (word t middle tail bit) := byobtain ⟨l,r,e⟩ := List.append_of_mem (List.mem_range.mpr ix)refine ⟨l.flatMap privateCell,r.flatMap privateCell ++ middle ++(List.range t).flatMap (mutableCell bit) ++ tail,?_⟩unfold wordconv => lhs; arg 1; arg 1; arg 1; rw [e]simp [List.flatMap_cons,List.append_assoc]private theorem positive_factor {a b : Nat} {f u : W} (factor : P455Quotient.Factor f u)(pos : 0 < Problem455Swap.bigram a b f) : 0 < Problem455Swap.bigram a b u := byobtain ⟨p,q,rfl⟩ := factorrw [Problem455Swap.bigram_append,Problem455Swap.bigram_append]omegatheorem no_links {r t : Nat} (hr : 0 < r) {middle tail : W} (bit : Nat → Bool)(small : ∀ x ∈ middle ++ tail, x < 2*t)(cap : P455Quotient.Cap r (word t middle tail bit)) :P455SourceFamilies.Compressed r (word t middle tail bit) := bylet U := word t middle tail bitintro x y linkchange Problem455Swap.bigram x y U = r at linkhave bound := Problem455Swap.out_bound x y (y+1) (by omega) Urw [Problem455BlockBridge.occ_count] at boundhave mem : x ∈ U := List.count_pos_iff.mp (by omega)have smallX := word_names bit small x memlet i := x/2have ix : i < t := by dsimp [i]; omegahave either : x = owner i ∨ x = mate i := by simp only [owner,mate,i]; omegahave ne : owner i ≠ mate i := by simp [owner,mate]have fac := private_factor ix middle tail bithave aPos : 0 < Problem455Swap.bigram x (owner i) U := byapply positive_factor facrcases either with e|e <;> conv => rhs; arg 1; rw [e]all_goals simp [privateCell,Problem455Swap.bigram,Problem455Swap.hit,ne,Ne.symm ne] <;> omegahave bPos : 0 < Problem455Swap.bigram x (mate i) U := byapply positive_factor facrcases either with e|e <;> conv => rhs; arg 1; rw [e]all_goals simp [privateCell,Problem455Swap.bigram,Problem455Swap.hit,ne,Ne.symm ne] <;> omegaobtain ⟨z,ny,pz⟩ : ∃ z, y ≠ z ∧ 0 < Problem455Swap.bigram x z U := byby_cases e : y = owner i· exact ⟨mate i,e ▸ ne,bPos⟩· exact ⟨owner i,e,aPos⟩have upper := Problem455Swap.out_bound x y z ny Urw [Problem455BlockBridge.occ_count] at upperhave cx : U.count x ≤ r := cap xomegaprivate theorem project_mutable (cells : W) (nd : cells.Nodup) (bit : Nat → Bool) (i : Nat) :proj (owner i) (mate i) (cells.flatMap (mutableCell bit)) =(if i ∈ cells then mutableCell bit i else []) := byinduction cells with| nil => rfl| cons j t ih =>have tail := ih (List.nodup_cons.mp nd).2by_cases e : i=j· subst jhave out := (List.nodup_cons.mp nd).1have one : proj (owner i) (mate i) (mutableCell bit i) = mutableCell bit i := bycases hb : bit i <;> simp [proj,mutableCell,hb]simp only [List.flatMap_cons,proj,List.filter_append] at tail one ⊢rw [one,tail]simp [out]· have eqs : owner j ≠ owner i ∧ owner j ≠ mate i ∧ mate j ≠ owner i ∧ mate j ≠ mate i := byunfold owner mate; omegahave no : proj (owner i) (mate i) (mutableCell bit j) = [] := bycases b : bit j <;> simp [proj,mutableCell,b,eqs.1,eqs.2.1,eqs.2.2.1,eqs.2.2.2]simp only [List.flatMap_cons,proj,List.filter_append] at tail no ⊢rw [no,tail]simp [e]theorem participants {t : Nat} (middle tail : W) :∀ x ∈ List.range (2*t), ∃ y,proj x y (word t middle tail (constant false)) ≠ proj x y (word t middle tail (constant true)) := byintro x mhave lt := List.mem_range.mp mlet i := x/2have mi : i ∈ List.range t := List.mem_range.mpr (by dsimp [i]; omega)have pairDiff : proj (owner i) (mate i) (word t middle tail (constant false)) ≠proj (owner i) (mate i) (word t middle tail (constant true)) := byintro eqsimp only [word,proj,List.filter_append,List.append_cancel_right_eq,List.append_cancel_left_eq] at eqchange proj (owner i) (mate i) ((List.range t).flatMap (mutableCell (constant false))) =proj (owner i) (mate i) ((List.range t).flatMap (mutableCell (constant true))) at eqrw [project_mutable _ List.nodup_range,project_mutable _ List.nodup_range] at eqsimp [mi,mutableCell,constant,owner,mate] at eqhave either : x = owner i ∨ x = mate i := by simp only [owner,mate,i]; omegarcases either with e|e· exact ⟨mate i,e ▸ pairDiff⟩· refine ⟨owner i,?_⟩rw [e]simpa only [proj,Or.comm] using pairDiff/-- Local inequalities along the numbered snake and its wrap force aconstant bit on all cells. There is no assumption on bits outside the array. -/theorem cycle_constant {t : Nat} (bit : Nat → Bool) (next : ∀ i, i+1 < t →bit i = true → bit (i+1) = true) (wrap : 0 < t → bit (t-1) = true → bit 0 = true) :∃ b, ∀ i < t, bit i = b := byhave onward (i j : Nat) (le : i ≤ j) (lt : j < t) (yes : bit i = true) : bit j = true := byinduction j with| zero => have := Nat.eq_zero_of_le_zero le; simpa [this] using yes| succ j ih =>by_cases e : i=j+1· exact e ▸ yes· exact next j lt (ih (by omega) (by omega))by_cases existsTrue : ∃ i < t, bit i = true· obtain ⟨i,lt,active⟩ := existsTruehave first := wrap (by omega) (onward i (t-1) (by omega) (by omega) active)exact ⟨true,fun j lj => onward 0 j (by omega) lj first⟩· exact ⟨false,fun i li => by cases eq : bit i <;> simp_all⟩theorem word_constant {t : Nat} (middle tail : W) (bit : Nat → Bool) (b : Bool)(all : ∀ i < t, bit i = b) : word t middle tail bit = word t middle tail (constant b) := byhave m : (List.range t).flatMap (mutableCell bit) = (List.range t).flatMap (mutableCell (constant b)) := byhave go (xs : W) (small : ∀ i ∈ xs, i < t) : xs.flatMap (mutableCell bit) = xs.flatMap (mutableCell (constant b)) := byinduction xs with| nil => rfl| cons x xs ih =>have tailEq := ih (fun i hi => small i (List.mem_cons_of_mem _ hi))simp [List.flatMap_cons,tailEq,mutableCell,constant,all x (small x List.mem_cons_self)]exact go _ (fun _ => List.mem_range.mp)simp only [word,m]/-- The remaining semantic inputs are the constant identity, representationof every identical word by cell bits, and detection of each descendingsnake (including wrap) edge. The two-word class is proved from these. -/theorem witness {A : Type} {M : Model A} {r t : Nat} (hr : 0 < r) (ht : 0 < t) (middle tail : W)(small : ∀ x ∈ middle ++ tail, x < 2*t)(cap : P455Quotient.Cap r (word t middle tail (constant false)))(identity : M.Valid (word t middle tail (constant false)) (word t middle tail (constant true)))(represent : ∀ w, M.Valid (word t middle tail (constant false)) w →∃ bit, w = word t middle tail bit)(edge : ∀ bit, M.Valid (word t middle tail (constant false)) (word t middle tail bit) →(∀ i, i+1 < t → bit i = true → bit (i+1) = true) ∧(0 < t → bit (t-1) = true → bit 0 = true)) :RankWitness M r (word t middle tail (constant false)) (word t middle tail (constant true))(List.range (2*t)) := byhave m0 : 0 ∈ List.range (2*t) := List.mem_range.mpr (by omega)obtain ⟨y,change0⟩ := participants middle tail 0 m0have ne : word t middle tail (constant false) ≠ word t middle tail (constant true) :=fun e => change0 (congrArg (proj 0 y) e)have nonempty (bit : Nat → Bool) : word t middle tail bit ≠ [] := byobtain ⟨p,q,eq⟩ := private_factor (i:=0) ht middle tail bitrw [eq]; simp [privateCell]refine ⟨⟨nonempty _,nonempty _⟩,ne,identity,?_,cap,no_links hr _ small cap,List.nodup_range,participants middle tail⟩intro w validobtain ⟨bit,rfl⟩ := represent w validobtain ⟨nx,wrap⟩ := edge bit validobtain ⟨b,all⟩ := cycle_constant bit nx wrapcases b with| false => exact Or.inl (word_constant middle tail bit false all)| true => exact Or.inr (word_constant middle tail bit true all)end P455RectangleRankend/- Begin Problem455EffectiveMachineDiagonal (from finite-semigroup-identity-bases). -/section/- A diagonal argument for actual deterministic finite-control one-headmachines. Input is a finite Boolean word over two tape symbols. -/namespace P455EffectiveMachineopen P455MachineLocal P455MachineCleanup P455MachineTablestructure Alphabet (M : Ordinary g q) wherebit : Bool → Fin gaway : ∀ b, bit b ≠ M.markerink : ∀ b, bit b ≠ M.blankdistinct : bit false ≠ bit true/-- Position zero holds the permanent marker. Input occupies positions1 through length. All further cells are initially blank. -/def inputTape (M : Ordinary g q) (A : Alphabet M) (w : List Bool) : Nat → Fin g| 0 => M.marker| x+1 => (w[x]?).elim M.blank A.bitdef inputConfig (M : Ordinary g q) (A : Alphabet M) (w : List Bool) : Config g q :=⟨inputTape M A w,0,M.start⟩def follow (M : Ordinary g q) (c : Config g q) : Nat → Config g q| 0 => c| t+1 => once M (follow M c t)def HALT (M : Ordinary g q) (c : Config g q) := ∃ t, instruction M (follow M c t)=nonedef selfBits (M : Ordinary g q) (A : Alphabet M) : List Bool :=unary (A.bit false).val ++ unary (A.bit true).val ++ (quote M).bitsdef SelfHalt (M : Ordinary g q) (A : Alphabet M) :=HALT M (inputConfig M A (selfBits M A))theorem inputTape_blank (M : Ordinary g q) (A : Alphabet M) :inputConfig M A [] = config₀ M := byhave tape : inputTape M A [] = fun x => if x=0 then M.marker else M.blank := byfunext x; cases x <;> simp [inputTape]simp [inputConfig,config₀,tape]theorem blank_run (M : Ordinary g q) (t : Nat) : follow M (config₀ M) t = original M t := byinduction t with| zero => rfl| succ t ih => simp only [follow,original,ih]theorem blank_halts (M : Ordinary g q) : HALT M (config₀ M) ↔ ∃ t, stopped M t := bysimp only [HALT,stopped,blank_run]theorem rest (M : Ordinary g q) (c : Config g q) {t} (h : instruction M (follow M c t)=none) (k) :follow M c (t+k)=follow M c t := byinduction k with| zero => rfl| succ k ih => simp [Nat.add_succ,follow,ih,once,h]theorem unique_halt (M : Ordinary g q) (c : Config g q) {a b}(ha : instruction M (follow M c a)=none) (hb : instruction M (follow M c b)=none) :follow M c a=follow M c b := byby_cases le : a≤b· have e := rest M c ha (b-a)rw [show a+(b-a)=b by omega] at eexact e.symm· have e := rest M c hb (a-b)rw [show b+(a-b)=a by omega] at eexact edef trap (M : Ordinary g q) (answer : Fin q → Bool) : Ordinary g q wheremarker := M.markerblank := M.blankblank_ne := M.blank_nestart := M.startdelta := fun s a =>match M.delta s a with| some i => some i| none => if answer s then some ⟨s,a,.stay⟩ else nonekeeps := byintro s a i eqcases h : M.delta s a with| some j => simp only [h,Option.some.injEq] at eq; exact M.keeps s a i (eq ▸ h)| none =>simp only [h] at eqsplit at eq <;> simp_all <;> subst i <;> simpleftSafe := byintro s i eqcases h : M.delta s M.marker with| some j => simp only [h,Option.some.injEq] at eq; exact M.leftSafe s i (eq ▸ h)| none =>simp only [h] at eqsplit at eq <;> simp_all <;> subst i <;> simpdef liftAlphabet (M : Ordinary g q) (A : Alphabet M) (answer : Fin q → Bool) : Alphabet (trap M answer) :=⟨A.bit,A.away,A.ink,A.distinct⟩theorem write_same (f : Nat → Fin g) (p) : writeAt f p (f p) = f := byfunext i; by_cases h : i=p <;> simp [writeAt,h]theorem once_trap (M : Ordinary g q) (ans) (c : Config g q) : once (trap M ans) c = once M c := bycases c with| mk tape pos state =>cases e : M.delta state (tape pos) with| some i => simp [once,instruction,trap,e]| none => cases h : ans state <;> simp [once,instruction,trap,e,h,dest,write_same]theorem follow_trap (M : Ordinary g q) (ans) (c : Config g q) (t) :follow (trap M ans) c t = follow M c t := byinduction t with| zero => rfl| succ t ih => simp only [follow,ih,once_trap]theorem stop_trap (M : Ordinary g q) (ans) (c : Config g q) :instruction (trap M ans) c=none ↔ instruction M c=none ∧ ans c.state=false := bycases e : M.delta c.state (c.tape c.pos) <;> cases h : ans c.state <;> simp [instruction,trap,e,h]theorem halt_trap_iff (M : Ordinary g q) (ans) (c : Config g q) {t}(ended : instruction M (follow M c t)=none) :HALT (trap M ans) c ↔ ans (follow M c t).state=false := byconstructor· rintro ⟨i,hi⟩rw [follow_trap,stop_trap] at hiexact unique_halt M c hi.1 ended ▸ hi.2· intro hexact ⟨t,by rw [follow_trap,stop_trap]; exact ⟨ended,h⟩⟩/-- A decider may have any finite work alphabet and arbitrary finitecontrol. On the code of a binary-input machine it must halt and itsBoolean output is read from the final control state. No behavior onill-formed encodings is required. -/def DecidesSelf (D : Ordinary g q) (A : Alphabet D) (answer : Fin q→Bool) : Prop :=∀ {g' q'} (P : Ordinary g' q') (B : Alphabet P),let c := inputConfig D A (selfBits P B)∃ t, instruction D (follow D c t)=none ∧(answer (follow D c t).state=true ↔ SelfHalt P B)theorem no_self_decider (D : Ordinary g q) (A : Alphabet D) (answer : Fin q → Bool) :¬DecidesSelf D A answer := byintro correctlet P := trap D answerlet B := liftAlphabet D A answerlet c := inputConfig D A (selfBits P B)have same : inputConfig P B (selfBits P B)=c := rflobtain ⟨t,halt,ok⟩ := correct P Bchange instruction D (follow D c t)=none at haltchange (answer (follow D c t).state=true ↔ HALT P (inputConfig P B (selfBits P B))) at okrw [same] at okhave contradiction := ok.trans (halt_trap_iff D answer c halt)cases e : answer (follow D c t).state <;> simp [e] at contradictionend P455EffectiveMachineend/- Begin Problem455CrossedSupport (from finite-semigroup-identity-bases). -/section/- The guard used for a crossed flip is constructed from the two actualsource names. The remaining geometric premise concerns only the countsof literal original-slot occupants in the indicated radius. -/namespace P455CrossedSupportopen P455Witness P455Paths P455ContactLift P455SourceFamiliesopen P455OriginalWalk P455SourceTheorem Problem455.Slotsdef ClosedFlip (r : Nat) (allow : Tag → Prop) (u : W) (x y : Nat) : Prop :=∃ (f : P455Closure.Frame Nat) (b : Bool) (l k : W),f.p = [x] ∧ f.q = [y] ∧ f.Valid r allow (fun _ _ => False) ∧ u = l ++ f.core b ++ ktheorem flip_counts {r allow u x y} (cap : P455Closure.Cap r u) (flip : ClosedFlip r allow u x y) :1 < r ∧ u.count x = r ∧ u.count y = r ∧ x ≠ y := byobtain ⟨f,b,l,k,hp,hq,v,rfl⟩ := fliphave one (a : Nat) (mem : a ∈ f.p ∨ a ∈ f.q) : (l ++ f.core b ++ k).count a = r := byhave sat := v.2.2.2.2.2.2.2 a memhave bit : (f.core b).count a = r := by cases b <;> first | exact sat | exact (f.count_core a true).trans sathave bound := cap a; simp only [List.count_append,bit] at bound ⊢; omegahave xp : x ∈ f.p := by simp [hp]have yq : y ∈ f.q := by simp [hq]exact ⟨by have := v.1; omega,one _ (.inl xp),one _ (.inr yq),fun e => v.2.2.2.2.2.1 _ xp (e ▸ yq)⟩def markedRecord (c : Certificate) (second : Bool) : Node :=match c with| .slot s => s.anchor| .functionality f => f.anchor| .edge e => if second then e.b else e.a/-- Either orientation of the chosen unordered pair across the two images. -/def Crosses (n : Node) (h : Nat → W) (x y : Nat) : Prop :=(n.owner ∈ h x ∧ n.mate ∈ h y) ∨ (n.owner ∈ h y ∧ n.mate ∈ h x)theorem start_role (c : Certificate) (second mate : Bool) :startLabel c second mate = (markedRecord c second).owner ∨startLabel c second mate = (markedRecord c second).mate := bycases c with| slot s => cases e : s.startAtMate <;> simp [picked,startLabel,markedRecord,e]| functionality f => exact .inl rfl| edge e => cases mate <;> simp [startLabel,markedRecord]theorem choose_seed {h x y} (c : Certificate) (second mate : Bool)(cross : Crosses (markedRecord c second) h x y) :∃ seed, (seed = x ∨ seed = y) ∧ startLabel c second mate ∈ h seed := byrcases start_role c second mate with owner|other· rcases cross with c1|c2· exact ⟨x,.inl rfl,owner.symm ▸ c1.1⟩· exact ⟨y,.inr rfl,owner.symm ▸ c2.1⟩· rcases cross with c1|c2· exact ⟨y,.inr rfl,other.symm ▸ c1.2⟩· exact ⟨x,.inl rfl,other.symm ▸ c2.2⟩def InBall (r : Nat) (allow : Tag → Prop) (mark : Marking) (u : W) (x y t : Nat) :=Near r allow mark u x t 6 ∨ Near r allow mark u y t 6def UniformSlots (r : Nat) (allow : Tag → Prop) (mark : Marking) (u : W) (x y : Nat) :=∀ t, InBall r allow mark u x y t → ∀ i, slotStart i → ∀ b, occupies u t i b → u.count b = rdef Needed (r : Nat) (allow : Tag → Prop) (mark : Marking) (u : W) (x y b : Nat) : Prop :=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/-- Finite retained support. Repetitions in the carrier list u do not affectmembership. Tile compatibility and allowed tags can be arbitrary predicates. -/noncomputable def retained (r : Nat) (allow : Tag → Prop) (mark : Marking) (u : W) (x y : Nat) : W := byclassicalexact u.filter (fun b => decide (Needed r allow mark u x y b))theorem mem_retained {r allow mark u x y b} :b ∈ retained r allow mark u x y ↔ b ∈ u ∧ Needed r allow mark u x y b := byclassicalsimp [retained]theorem walked_name {r allow mark u} (hr : 0 < r) (cap : P455Closure.Cap r u) (a : Nat)(p : List Step) (ha : a ∈ u) (w : Walk r allow mark u a p) : endpoint a p ∈ u := byinduction p generalizing a with| nil => exact ha| cons step ps ih =>obtain ⟨b,c⟩ := stephave count := (P455Retained.contact_counts cap w.1).2exact ih b (List.count_pos_iff.mp (count.symm ▸ hr)) w.2theorem actual_guard {r allow mark u x y seed} (hr : 0 < r) (cap : P455Closure.Cap r u)(hx : x ∈ u) (hy : y ∈ u) (side : seed = x ∨ seed = y) (unif : UniformSlots r allow mark u x y) :OriginalGuard r allow mark u (fun a => a ∈ retained r allow mark u x y) seed 6 := byintro t nearhave ball : InBall r allow mark u x y t := side.elim (fun a => .inl (a ▸ near)) (fun a => .inr (a ▸ near))have hs : seed ∈ u := side.elim (fun a => a.symm ▸ hx) (fun a => a.symm ▸ hy)obtain ⟨p,w,eq,_⟩ := nearhave ht := eq ▸ walked_name hr cap seed p hs wrefine ⟨mem_retained.mpr ⟨ht,.inl ball⟩,?_⟩intro i hi b betweenhave inside : b ∈ u := byobtain ⟨j,events⟩ := betweenexact stamped_mem_label _ _ (b,j) (events.subset (by simp))exact ⟨mem_retained.mpr ⟨inside,.inr ⟨t,i,ball,hi,between⟩⟩,unif t ball i hi b between⟩end P455CrossedSupportend/- Begin Problem455EdgeProjection (from finite-semigroup-identity-bases). -/sectionnamespace P455EdgeProjectionopen P455Witness P455Paths P455SourceFamilies P455CertificateReach P455PortReflection P455EdgeSourceopen P455DefectProjection P455OtherProjection P455DefectRename Problem455.Slotsdef candidates (ts : Tiles) (e : EdgeCertificate) : List (Node × Bool) :=[(e.a,true),(e.b,true),(e.right,!ts.right e.a.tag),(e.left,!ts.left e.a.tag),(e.down,!ts.bottom e.a.tag),(e.up,!ts.top e.a.tag),(e.diagonal,!ts.right e.a.tag && !ts.bottom e.a.tag)]def nodes (ts : Tiles) (e : EdgeCertificate) :=((candidates ts e).filter Prod.snd).map Prod.fstdef names (ts : Tiles) (e : EdgeCertificate) := (nodes ts e).flatMap rolestheorem nodes_exact {ts e n} : n ∈ nodes ts e ↔ Active ts e n := byconstructor· intro h; obtain ⟨⟨j,b⟩,m,rfl⟩ := List.mem_map.mp hobtain ⟨cand,bok⟩ := List.mem_filter.mp mchange b = true at bok; subst bsimp only [candidates,List.mem_cons,List.not_mem_nil,or_false,Prod.mk.injEq,true_and,and_true] at candrcases cand with h|h|⟨h,p⟩|⟨h,p⟩|⟨h,p⟩|⟨h,p⟩|⟨h,p⟩ <;> subst j· exact .anchor· exact .successor· exact .right (by simpa using p.symm)· exact .left (by simpa using p.symm)· exact .down (by simpa using p.symm)· exact .up (by simpa using p.symm)· have two : ts.right e.a.tag = false ∧ ts.bottom e.a.tag = false := by simpa using p.symmexact .diagonal two.1 two.2· intro activeapply List.mem_map.mprrefine ⟨(_,true),List.mem_filter.mpr ⟨?_,rfl⟩,rfl⟩cases active <;> simp_all [candidates]theorem names_exact {ts e x} : x ∈ names ts e ↔ ∃ n, Active ts e n ∧ x ∈ roles n := bysimp [names,List.mem_flatMap,nodes_exact]theorem names_bound (ts : Tiles) (e : EdgeCertificate) : (names ts e).length ≤ 14 := byhave rep (ls : List Node) : (ls.flatMap roles).length = ls.length * 2 := byinduction ls with| nil => rfl| cons x ls ih => simp [roles,List.flatMap_cons,ih,Nat.add_mul, Nat.add_comm] at *; omegahave bound : (nodes ts e).length ≤ 7 := bysimpa [nodes,candidates] using (List.length_filter_le Prod.snd (candidates ts e))rw [names,rep]; omegatheorem covered {ts e n} (ac : Active ts e n) : Covers (names ts e) (roles n) :=fun _ h => names_exact.mpr ⟨n,ac,h⟩theorem saturated {r allow mark u} (cap : P455Closure.Cap r u) (ts : Tiles) (e : EdgeCertificate)(ok : Holds r allow mark u (e.query ts)) {x : Nat} (mem : x ∈ names ts e) : u.count x = r := byobtain ⟨n,ac,role⟩ := names_exact.mp memhave ct := record_counts cap (active_owner cap ts e ok ac).2rcases (show x = n.owner ∨ x = n.mate by simpa [roles] using role) with rfl|rfl· exact ct.1· exact ct.2private theorem flag {r allow mark u} (keep : W) (b : Bool) (q : Query)(transfer : b = true → Holds r allow mark u q → Holds r allow mark (select keep u) q)(h : Holds r allow mark u (flagQ b q)) : Holds r allow mark (select keep u) (flagQ b q) := bycases b· exact True.intro· exact transfer rfl htheorem project_edge {r allow mark u} (ts : Tiles) (e : EdgeCertificate)(ok : Holds r allow mark u (e.query ts)) : Holds r allow mark (select (names ts e) u) (e.query ts) := bylet keep := names ts ehave ka : Covers keep (roles e.a) := covered .anchorhave kb : Covers keep (roles e.b) := covered .successorhave ao := ka e.a.owner (by simp [roles]); have am := ka e.a.mate (by simp [roles])have bo := kb e.b.owner (by simp [roles]); have bm := kb e.b.mate (by simp [roles])obtain ⟨ma,mb,lc,succ,_⟩ := okrefine ⟨select_marked keep _ _ ao am ma,select_marked keep _ _ bo bm mb,?_,?_,True.intro⟩· refine ⟨flag keep _ _ (fun b q => ?_) lc.1,flag keep _ _ (fun b q => ?_) lc.2.1,flag keep _ _ (fun b q => ?_) lc.2.2.1,flag keep _ _ (fun b q => ?_) lc.2.2.2.1,flag keep _ _ (fun b q => ?_) lc.2.2.2.2.1,True.intro⟩· exact select_neighbor keep ts e.a e.right .right ka (covered (.right (by simpa using b))) q· exact select_neighbor keep ts e.a e.left .left ka (covered (.left (by simpa using b))) q· exact select_neighbor keep ts e.a e.down .down ka (covered (.down (by simpa using b))) q· exact select_neighbor keep ts e.a e.up .up ka (covered (.up (by simpa using b))) q· have pair : ts.right e.a.tag = false ∧ ts.bottom e.a.tag = false := by simpa using bhave dg := covered (e := e) (.diagonal pair.1 pair.2)exact ⟨select_neighbor keep ts e.right e.diagonal .down (covered (.right pair.1)) dg q.1,select_neighbor keep ts e.down e.diagonal .right (covered (.down pair.2)) dg q.2⟩· unfold chosenSuccessor at succ ⊢dsimp only at succ ⊢split at succnext ret =>rw [if_pos ret]refine ⟨succ.1,succ.2.1.elim (fun q => .inl (select_port keep _ _ _ ka kb q))(fun q => .inr (select_port keep _ _ _ kb ka q)),select_order keep _ (by simp [bo,ao]) succ.2.2.1,True.intro⟩next other =>rw [if_neg other]exact ⟨succ.1,select_order keep _ (by simp [bo,ao]) succ.2⟩def template (ts : Tiles) (e : EdgeCertificate) (u : W) :=(select (names ts e) u).map (names ts e).idxOf/-- The only source assumptions are the cap and an actual 1,0 edgecertificate in the observed side. The other side is unrestricted.Marking the two endpoint records retains the bit of either one. -/theorem canonical_edge {r allow mark u} (cap : P455Closure.Cap r u) (ts : Tiles) (e : EdgeCertificate)(ok : Holds r allow mark u (e.query ts)) :let keep := names ts elet T := template ts e uP455Closure.Cap r T ∧ (∀ x ∈ T, x < 14 ∧ T.count x = r) ∧Holds r allow (endpointMarks keep.idxOf e) T ((sendEdge keep.idxOf e).query ts) := bylet keep := names ts elet w := select keep ulet T := template ts e ulet d := keep.idxOfhave hr : 0 < r := by have h : e.a.tag.length + 16 = r := ok.1.2.1; omegahave sat {x : Nat} (hx : x ∈ keep) : w.count x = r :=(select_count keep u x hx).trans (saturated cap ts e ok hx)have small (x) (m : x ∈ w) : x ∈ keep := kept mhave ext : w.map (extend keep) = T := extend_map smallhave cp : P455Closure.Cap r T := ext ▸ cap_rename (extend keep) (extend_inj keep) (select_cap keep cap)have ct {x : Nat} (hx : x ∈ keep) : T.count (d x) = r := byrw [← ext,show d x = extend keep x by simp [d,extend,hx],count_rename _ (extend_inj keep),sat hx]refine ⟨cp,?_,?_⟩· intro y hy; obtain ⟨x,xm,rfl⟩ := List.mem_map.mp hyexact ⟨Nat.lt_of_lt_of_le (List.idxOf_lt_length_of_mem (small x xm)) (names_bound ts e),ct (small x xm)⟩· let h := fun j => [decode keep j]have back : ([] : W) ++ T.flatMap h ++ [] = w := byhave single (v : W) : v.flatMap h = v.map (decode keep) := byinduction v with| nil => rfl| cons a v ih => simp [h,List.flatMap_cons,ih] at *simpa only [List.nil_append,List.append_nil,single,T,template,keep,w] using decode_map smallhave uniform (n : Node) (ac : Active ts e n) : UniformOn r T h d (roles n) := byintro x hx; have k := covered ac x hxexact ⟨ct k,by simp [h,d,decode_idx keep k]⟩exact edge_source (mark := mark) (l := []) (k := []) hr (by rw [back]; exact select_cap keep cap)ts e uniform (by rw [back]; exact project_edge ts e ok)end P455EdgeProjectionend/- Begin Problem455Structural (from finite-semigroup-identity-bases). -/sectionnamespace P455Structuralopen P455Witness P455Quotient P455Closure P455Uncrossed Problem455.Slotsopen P455SourceFamilies P455FirstTestersprivate theorem image_edge (h : Nat → W) (x a b : Nat)(pos : 0 < Problem455Swap.bigram a b (h x)) (u : W) :u.count x ≤ Problem455Swap.bigram a b (u.flatMap h) := byinduction u with| nil => simp [Problem455Swap.bigram]| cons z u ih =>simp only [List.flatMap_cons,Problem455Swap.bigram_append]by_cases e : z=x· subst z; simp [List.count_cons]; omega· simp [List.count_cons,e]; omegaprivate theorem singleton_in_template {r : Nat} {T p q u : W} {h : Nat → W} {x : Nat}(eq : T = p ++ u.flatMap h ++ q) (cap : P455Closure.Cap r T) (cmp : Compressed r T)(cx : u.count x = r) (nonempty : h x ≠ []) : ∃ a, h x = [a] := bycases z : h x with| nil => exact False.elim (nonempty z)| cons a t =>cases t with| nil => exact ⟨a,rfl⟩| cons b t =>have pair : 0 < Problem455Swap.bigram a b (h x) := byrw [z]; simp [Problem455Swap.bigram,Problem455Swap.hit] <;> omegahave base := image_edge h x a b pair uhave low : r ≤ Problem455Swap.bigram a b T := byrw [eq,Problem455Swap.bigram_append,Problem455Swap.bigram_append]; omegahave top := Problem455Swap.out_bound a b (b+1) (by omega) Trw [Problem455BlockBridge.occ_count] at tophave high := cap aexact False.elim (cmp a b (by unfold Problem455Swap.Link; omega))private theorem image_count {r : Nat} (h : Nat → W) (u : W) (x a : Nat)(c : u.count x = r) (img : h x = [a]) : r ≤ (u.flatMap h).count a := byhave h := P455DonorInterval.split_contributions h u x asimp [img,c] at homega/-- Under any substitution, a live factor in a structural tester givesliteral equality of the two substituted words. All other images may beempty or arbitrarily long and may use shared names. -/theorem structural_factor {r T allow} (cap : P455Closure.Cap r T) (cmp : Compressed r T)(stest : Structural T r allow) (f : Frame Nat) (l k : W) (bit : Bool) (x y : Nat)(hp : f.p = [x]) (hq : f.q = [y]) (valid : f.Valid r allow (fun _ _ => False))(h : Nat → W) (fac : Factor ((side f l k bit).flatMap h) T) :(side f l k bit).flatMap h = (side f l k (!bit)).flatMap h := byobtain ⟨pre,post,eq⟩ := fachave eqCore : T = (pre ++ l.flatMap h) ++ (f.core bit).flatMap h ++ (k.flatMap h ++ post) := bysimpa [side,List.flatMap_append,List.append_assoc] using eqhave count (z : Nat) (role : z = x ∨ z = y) : (f.core bit).count z = r := byhave has : z ∈ f.p ∨ z ∈ f.q := by simpa [hp,hq] using rolehave orig := valid.2.2.2.2.2.2.2 z hascases bit with| false => exact orig| true => exact (f.count_core z true).trans orighave commute : h x ++ h y = h y ++ h x := byby_cases nx : h x = []· simp [nx]by_cases ny : h y = []· simp [ny]obtain ⟨a,ax⟩ := singleton_in_template eqCore cap cmp (count x (.inl rfl)) nxobtain ⟨b,by'⟩ := singleton_in_template eqCore cap cmp (count y (.inr rfl)) nyby_cases ab : a=b· simp [ax,by',ab]exfalsoapply structural_excludes_closed stestlet L := pre ++ l.flatMap hhave fresh (z s : Nat) (kind : z=x ∨ z=y) (im : h z = [s]) : s ∉ L := byhave bound := cap srw [eqCore] at boundhave ct := image_count h (f.core bit) z s (count z kind) imapply List.count_eq_zero.mpdsimp [L]simp only [List.count_append] at bound ⊢omegalet tail := f.mid ++ f.beforeMutable ++ f.pair bit ++ f.beforeFinalP ++ f.p ++ f.beforeFinalQ ++ f.qhave shape : f.core bit = f.early ++ tail := by simp [Frame.core,tail,List.append_assoc]refine ⟨ab,L,tail.flatMap h ++ (k.flatMap h ++ post),?_,fresh x a (.inl rfl) ax,fresh y b (.inr rfl) by'⟩rw [eqCore,shape]simp [L,Frame.early,hp,hq,List.flatMap_append,List.flatMap_cons,ax,by',List.append_assoc,early]cases bit <;>simp only [side,Frame.core,Frame.pair,List.flatMap_append,List.flatMap_cons,List.flatMap_nil,Bool.false_eq_true,if_false,if_true,Bool.not_false,Bool.not_true,hp,hq,List.append_nil] <;>rw [commute]private theorem plain_factor {r : Nat} {T u : W} (g : Good (plain r) T u) : Factor u T := byobtain ⟨v,walk,fac⟩ := ghave e : T=v := by induction walk with| refl => rfl| snoc _ impossible _ => exact False.elim impossibleexact e ▸ fac/-- Universal equality in the actual Rees factor monoid of each structuraltemplate. Zero evaluations, either live orientation and arbitrary goodrepresentatives are handled through the quotient evaluation. -/theorem structural_eval {r T allow} (cap : P455Closure.Cap r T) (cmp : Compressed r T)(stest : Structural T r allow) (f : Frame Nat) (l k : W) (x y : Nat)(hp : f.p=[x]) (hq : f.q=[y]) (valid : f.Valid r allow (fun _ _ => False))(val : Nat → Q (plain r) T) :eval (plain r) cap val (side f l k false) = eval (plain r) cap val (side f l k true) := byclassicalapply Classical.byContradictionintro dlet R := plain rhave live : ∃ b : Bool, eval R cap val (side f l k b) ≠ zero R T := byby_cases nz : eval R cap val (side f l k false) ≠ zero R T· exact ⟨false,nz⟩· exact ⟨true,fun eq => d ((Classical.not_not.mp nz).trans eq.symm)⟩obtain ⟨b,nz⟩ := livelet u := side f l k bhave existsRep (a : Nat) (ha : a ∈ u) :=nonzero_representative R (val a) (live_inputs R cap val _ nz a ha)let h (a : Nat) := if yes : a ∈ u then (existsRep a yes).choose else []have rep (a) (mem : a ∈ u) : ofWord R T (h a) = val a := bysimpa only [h,dif_pos mem] using (existsRep a mem).choose_spec.2have original := eval_rep R cap val u h rephave separated := structural_factor cap cmp stest f l k b x y hp hq valid h(plain_factor ((nonzero_iff R).mp (original ▸ nz)))have other := eval_rep R cap val (side f l k (!b)) h(fun a ha => rep a ((same_letters f l k b a).mpr ha))have done := original.trans ((congrArg (ofWord R T) separated).trans other.symm)cases b· exact d done· exact d done.symmend P455Structuralend/- Begin Problem455PaddedPorts (from finite-semigroup-identity-bases). -/sectionnamespace P455PaddedPortsopen P455RectangleRank Problem455.Slotsabbrev W := List Natinductive Block where| single (i : Nat)| pair (i j : Nat)deriving DecidableEqdef cells : Block → W| .single i => [i]| .pair i j => [i,j]def phase (bs : List Block) := bs.flatMap fun b => cells b ++ cells bdef roles (i : Nat) := [owner i,mate i]def letters (bs : List Block) := (phase bs).flatMap rolesprivate theorem singleton_head {i j u : Nat} {p : W} (ne : i≠j)(eq : u :: u :: p = [i,j,i,j]) : False := byobtain ⟨rfl,e⟩ := List.cons.inj eqexact ne (List.cons.inj e).1private theorem only_pair (bs : List Block) (i j : Nat) (ne : i≠j)(obs : select [i,j] (phase bs)=[i,j,i,j]) : Block.pair i j ∈ bs := byinduction bs with| nil => simp [phase,select] at obs| cons b bs ih =>change select [i,j] ((cells b ++ cells b) ++ phase bs) = _ at obsrw [select_append,select_append] at obscases b with| single u =>by_cases hu : u=i ∨ u=j· have su : select [i,j] [u]=[u] := by simp [select,hu]simp only [cells,su,List.cons_append,List.nil_append] at obsexact (singleton_head ne obs).elim· have su : select [i,j] [u]=[] := by simp [select,hu]simp only [cells,su,List.nil_append] at obsexact List.mem_cons_of_mem _ (ih obs)| pair u v =>by_cases hu : u=i ∨ u=j <;> by_cases hv : v=i ∨ v=j· have sv : select [i,j] [u,v]=[u,v] := by simp [select,hu,hv]simp only [cells,sv,List.cons_append,List.nil_append,List.cons.injEq] at obsobtain ⟨rfl,rfl,_⟩ := obsexact List.mem_cons_self· have sv : select [i,j] [u,v]=[u] := by simp [select,hu,hv]simp only [cells,sv,List.cons_append,List.nil_append] at obsexact (singleton_head ne obs).elim· have sv : select [i,j] [u,v]=[v] := by simp [select,hu,hv]simp only [cells,sv,List.cons_append,List.nil_append] at obsexact (singleton_head ne obs).elim· have sv : select [i,j] [u,v]=[] := by simp [select,hu,hv]simp only [cells,sv,List.nil_append] at obsexact List.mem_cons_of_mem _ (ih obs)private theorem phase_mem (bs : List Block) (x : Nat) : x∈phase bs ↔ x∈bs.flatMap cells := bysimp [phase,List.mem_flatMap]private theorem pair_present {bs : List Block} (nd : (bs.flatMap cells).Nodup)(i j : Nat) (present : Block.pair i j ∈ bs) : select [i,j] (phase bs)=[i,j,i,j] := byobtain ⟨pre,post,eq⟩ := List.append_of_mem presentsubst bschange ((_ ++ (.pair i j :: post)).flatMap cells).Nodup at ndsimp only [List.flatMap_append,List.flatMap_cons,cells,List.cons_append,List.nil_append] at ndhave parts := List.pairwise_append.mp ndhave hits (x : Nat) (m : x∈pre.flatMap cells) : x∉[i,j] := byintro ehave no := parts.2.2 x m x (by simpa using List.mem_append_left (post.flatMap cells) e : x∈i::j::post.flatMap cells)exact no rflhave ends (x : Nat) (m : x∈post.flatMap cells) : x∉[i,j] := byhave hi := (List.nodup_cons.mp parts.2.1).1have hj := (List.nodup_cons.mp (List.nodup_cons.mp parts.2.1).2).1intro ercases (show x=i ∨ x=j by simpa using e) with rfl|rfl· exact hi (List.mem_cons_of_mem _ m)· exact hj mhave s1 := select_nil [i,j] (phase pre) (fun x m => hits x ((phase_mem ..).mp m))have s2 := select_nil [i,j] (phase post) (fun x m => ends x ((phase_mem ..).mp m))change select [i,j] ((pre ++ .pair i j :: post).flatMap _) = _rw [List.flatMap_append,List.flatMap_cons,select_append]change select [i,j] (phase pre) ++ select [i,j] (([i,j] ++ [i,j]) ++ phase post)=_rw [s1,select_append,s2]simp [select]theorem phase_exact {bs : List Block} (nd : (bs.flatMap cells).Nodup)(i j : Nat) (ne : i≠j) :select [i,j] (phase bs)=[i,j,i,j] ↔ Block.pair i j∈bs :=⟨only_pair bs i j ne,pair_present nd i j⟩private theorem roles_inj {s t : W} (eq : s.flatMap roles=t.flatMap roles) : s=t := byinduction s generalizing t with| nil => cases t <;> simp_all [roles]| cons i s ih =>cases t with| nil => simp [roles] at eq| cons j t =>simp only [List.flatMap_cons,roles,List.cons_append,List.nil_append,List.cons.injEq] at eqhave e : i=j := by have := eq.1; unfold owner at this; omegarw [e,ih eq.2.2]private theorem role_selection (s : W) (i j : Nat) :select (roles i ++ roles j) (s.flatMap roles) = (select [i,j] s).flatMap roles := byinduction s with| nil => rfl| cons a s ih =>by_cases h : a=i ∨ a=j· have kept : select (roles i ++ roles j) (roles a)=roles a := byrcases h with rfl|rfl <;> simp [roles,select]have er : select [i,j] (a::s)=a::select [i,j] s := by simp [select,h]simp only [List.flatMap_cons,select_append,kept,ih,er]· have hf : a≠i ∧ a≠j := by simpa using hhave non : ∀ b∈roles a, b∉roles i ++ roles j := byintro b m nsimp only [roles,List.cons_append,List.nil_append,List.mem_cons,List.not_mem_nil,or_false] at m nunfold owner mate at m nomegahave erased := select_nil _ _ nonhave er : select [i,j] (a::s)=select [i,j] s := by simp [select,h]simp only [List.flatMap_cons,select_append,erased,ih,er,List.nil_append]/-- In the literal eight-occurrence projection on the four actual roles,the oriented interleaving exists exactly for an intended matching edge.This is independent of block order and permits unmatched boundary cells. -/theorem literal_phase_exact {bs : List Block} (nd : (bs.flatMap cells).Nodup)(i j : Nat) (ne : i≠j) :select (roles i ++ roles j) (letters bs) =[owner i,mate i,owner j,mate j,owner i,mate i,owner j,mate j] ↔Block.pair i j∈bs := byunfold lettersrw [role_selection,← phase_exact nd i j ne]change _ = [i,j,i,j].flatMap roles ↔ _exact ⟨roles_inj,congrArg (List.flatMap roles)⟩end P455PaddedPortsend/- Begin Problem455EffectiveMachinePrefix (from finite-semigroup-identity-bases). -/section/- Compile a finite straight-line initialization script into ordinary finitecontrol, preserving halting from arbitrary tapes and positions. -/namespace P455EffectivePrefixopen P455EffectiveMachine P455MachineLocal P455MachineTable P455MachineCleanupinductive Cmd (g : Nat) | right | left | putRight (v : Fin g)structure Env (g : Nat) wheretape : Nat → Fin gpos : Natdef Env.start (env : Env g) (M : Ordinary g q) : Config g q := ⟨env.tape,env.pos,M.start⟩def write (mark : Fin g) (cmd : Cmd g) (a : Fin g) :=match cmd with| .putRight v => if a=mark ∨ v=mark then a else v| _ => adef motion (mark : Fin g) (cmd : Cmd g) (a : Fin g) : Direction :=match cmd with| .left => if a=mark then .stay else .left| _ => .rightdef effect (mark : Fin g) (cmd : Cmd g) (env : Env g) : Env g :=let a := env.tape env.pos⟨writeAt env.tape env.pos (write mark cmd a),dest (motion mark cmd a) env.pos⟩theorem write_marker (mark : Fin g) (cmd : Cmd g) (a) :write mark cmd a=mark ↔ a=mark := bycases cmd <;> simp [write]split <;> simp_alltheorem safe_motion (mark : Fin g) (cmd : Cmd g) : motion mark cmd mark ≠ .left := bycases cmd <;> simp [motion]def old (s : Fin q) : Fin (q+1) := ⟨s.val,by have := s.isLt; omega⟩def head (q) : Fin (q+1) := ⟨q,by omega⟩def liftIns (i : Ins (Fin g) (Fin q)) : Ins (Fin g) (Fin (q+1)) := ⟨old i.state,i.symbol,i.dir⟩def push (M : Ordinary g q) (cmd : Cmd g) : Ordinary g (q+1) wheremarker := M.markerblank := M.blankblank_ne := M.blank_nestart := head qdelta s a := if h : s.val<q then (M.delta ⟨s.val,h⟩ a).map liftInselse some ⟨old M.start,write M.marker cmd a,motion M.marker cmd a⟩keeps := byintro s a i eqsplit at eqnext h =>cases e : M.delta ⟨s.val,h⟩ a with| none => simp [e] at eq| some j => rw [e] at eq; change some (liftIns j) = some i at eq; obtain rfl := Option.some.inj eq; exact M.keeps _ _ _ enext =>simp only [Option.some.injEq] at eqsubst i; exact write_marker ..leftSafe := byintro s i eqsplit at eqnext h =>cases e : M.delta ⟨s.val,h⟩ M.marker with| none => simp [e] at eq| some j => rw [e] at eq; change some (liftIns j) = some i at eq; obtain rfl := Option.some.inj eq; exact M.leftSafe _ _ enext =>simp only [Option.some.injEq] at eqsubst i; exact safe_motion M.marker cmddef liftConfig (c : Config g q) : Config g (q+1) := ⟨c.tape,c.pos,old c.state⟩theorem old_ins (M : Ordinary g q) (cmd) (s a) :(push M cmd).delta (old s) a=(M.delta s a).map liftIns := bysimp [push,old,s.isLt]theorem head_ins (M : Ordinary g q) (cmd) (a) :(push M cmd).delta (head q) a=some ⟨old M.start,write M.marker cmd a,motion M.marker cmd a⟩ := bysimp [push,head]theorem once_old (M : Ordinary g q) (cmd) (c : Config g q) :once (push M cmd) (liftConfig c)=liftConfig (once M c) := bycases c with| mk tape pos s =>cases h : M.delta s (tape pos) <;> simp [once,instruction,liftConfig,old_ins,h,liftIns]theorem after_one (M : Ordinary g q) (cmd) (e : Env g) (t) :follow (push M cmd) (e.start (push M cmd)) (t+1)=liftConfig (follow M ((effect M.marker cmd e).start M) t) := byinduction t with| zero =>change once (push M cmd) ⟨e.tape,e.pos,head q⟩=_simp [once,instruction,head_ins,follow,liftConfig,effect,Env.start]| succ t ih => rw [follow,ih,once_old,follow]theorem push_iff (M : Ordinary g q) (cmd) (e : Env g) :HALT (push M cmd) (e.start (push M cmd)) ↔ HALT M ((effect M.marker cmd e).start M) := byconstructor· rintro ⟨t,fin⟩cases t with| zero =>change (push M cmd).delta (head q) (e.tape e.pos)=none at finsimp [head_ins] at fin| succ t =>refine ⟨t,?_⟩rw [after_one] at finsimp only [instruction,liftConfig,old_ins,Option.map_eq_none_iff] at finexact fin· rintro ⟨t,fin⟩refine ⟨t+1,?_⟩rw [after_one]simpa only [instruction,liftConfig,old_ins,Option.map_eq_none_iff] using findef install (M : Ordinary g q) : List (Cmd g) → (s : Nat) × Ordinary g s| [] => ⟨q,M⟩| c::cs => let N := install M cs; ⟨N.1+1,push N.2 c⟩theorem installed_marker (M : Ordinary g q) (cs) : (install M cs).2.marker=M.marker := byinduction cs with| nil => rfl| cons c cs ih => exact ihtheorem installed_blank (M : Ordinary g q) (cs) : (install M cs).2.blank=M.blank := byinduction cs with| nil => rfl| cons c cs ih => exact ihdef perform (mark : Fin g) (cs : List (Cmd g)) (e : Env g) := cs.foldl (fun z c => effect mark c z) etheorem install_iff (M : Ordinary g q) (cs) (e : Env g) :HALT (install M cs).2 (e.start (install M cs).2) ↔ HALT M ((perform M.marker cs e).start M) := byinduction cs generalizing e with| nil => rfl| cons c cs ih =>exact (push_iff (install M cs).2 c e).trans (by rw [installed_marker]; exact ih _)end P455EffectivePrefixend/- Begin Problem455EffectiveMachineChain (from finite-semigroup-identity-bases). -/section/- An executable finite-control composition of a tape transducer and adecision machine. The transition at the writer's terminal configurationchanges control to the reader and leaves the entire tape unchanged. -/namespace P455EffectiveChainopen P455EffectiveMachine P455MachineLocal P455MachineCleanup P455MachineTabledef left (r) (s : Fin q) : Fin (q+r) := ⟨s.val,by have := s.isLt; omega⟩def right (q) (s : Fin r) : Fin (q+r) := ⟨q+s.val,by have := s.isLt; omega⟩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⟩def rename (f : Fin q → Fin r) (c : Config g q) : Config g r := ⟨c.tape,c.pos,f c.state⟩def seqDelta (W : Ordinary g q) (D : Ordinary g r) (s : Fin (q+r)) (a : Fin g) :Option (Ins (Fin g) (Fin (q+r))) :=if h : s.val<q thenmatch W.delta ⟨s.val,h⟩ a with| some i => some (insMap (left r) i)| none => some ⟨right q D.start,a,.stay⟩else (D.delta ⟨s.val-q,by have := s.isLt; omega⟩ a).map (insMap (right q))theorem left_delta (W : Ordinary g q) (D : Ordinary g r) (s a) :seqDelta W D (left r s) a = match W.delta s a with| some i => some (insMap (left r) i)| none => some ⟨right q D.start,a,.stay⟩ := by simp [seqDelta,left,s.isLt]theorem right_delta (W : Ordinary g q) (D : Ordinary g r) (s a) :seqDelta W D (right q s) a=(D.delta s a).map (insMap (right q)) := byhave h : ¬ q+s.val<q := by omegasimp [seqDelta,right,h,Nat.add_sub_cancel_left]def chain (W : Ordinary g q) (D : Ordinary g r) (mark : W.marker=D.marker) : Ordinary g (q+r) wheremarker := W.markerblank := W.blankblank_ne := W.blank_nestart := left r W.startdelta := seqDelta W Dkeeps := byintro s a i eqby_cases h : s.val<q· let j : Fin q := ⟨s.val,h⟩have e : s=left r j := rflrw [e,left_delta] at eqcases d : W.delta j a with| none => rw [d] at eq; obtain rfl := Option.some.inj eq; rfl| some z => rw [d] at eq; obtain rfl := Option.some.inj eq; exact W.keeps _ _ _ d· let j : Fin r := ⟨s.val-q,by have := s.isLt; omega⟩have e : s=right q j := Fin.ext (by dsimp [j,right]; omega)rw [e,right_delta] at eqcases d : D.delta j a with| none => simp [d] at eq| some z =>rw [d] at eq; obtain rfl := Option.some.inj eqexact mark ▸ D.keeps _ _ _ dleftSafe := byintro s i eqby_cases h : s.val<q· let j : Fin q := ⟨s.val,h⟩have e : s=left r j := rflrw [e,left_delta] at eqcases d : W.delta j W.marker with| none => rw [d] at eq; obtain rfl := Option.some.inj eq; exact Direction.noConfusion| some z => rw [d] at eq; obtain rfl := Option.some.inj eq; exact W.leftSafe _ _ d· let j : Fin r := ⟨s.val-q,by have := s.isLt; omega⟩have e : s=right q j := Fin.ext (by dsimp [j,right]; omega)rw [e,right_delta,mark] at eqcases d : D.delta j D.marker with| none => simp [d] at eq| some z => rw [d] at eq; obtain rfl := Option.some.inj eq; exact D.leftSafe _ _ ddef liftAlphabet (W : Ordinary g q) (D : Ordinary g r) (mark) (A : Alphabet W) : Alphabet (chain W D mark) :=⟨A.bit,A.away,A.ink,A.distinct⟩def out (q) (ans : Fin r→Bool) (s : Fin (q+r)) : Bool :=if h : s.val<q then false else ans ⟨s.val-q,by have := s.isLt; omega⟩theorem out_right (q) (ans : Fin r→Bool) (s) : out q ans (right q s)=ans s := byhave h : ¬ q+s.val<q := by omegasimp [out,right,h,Nat.add_sub_cancel_left]theorem left_step (W : Ordinary g q) (D : Ordinary g r) (mark) (c : Config g q)(live : instruction W c≠none) :once (chain W D mark) (rename (left r) c)=rename (left r) (once W c) := bycases c with| mk tape pos s =>cases e : W.delta s (tape pos) with| none => exact False.elim (live e)| some i => simp [once,instruction,chain,rename,left_delta,e,insMap]theorem shift_control (W : Ordinary g q) (D : Ordinary g r) (mark) (c : Config g q)(halt : instruction W c=none) :once (chain W D mark) (rename (left r) c)=rename (right q) ⟨c.tape,c.pos,D.start⟩ := bychange W.delta c.state (c.tape c.pos)=none at haltsimp [once,instruction,chain,rename,left_delta,halt,write_same,dest]theorem right_step (W : Ordinary g q) (D : Ordinary g r) (mark) (c : Config g r) :once (chain W D mark) (rename (right q) c)=rename (right q) (once D c) := bycases c with| mk tape pos s => cases e : D.delta s (tape pos) <;> simp [once,instruction,chain,rename,right_delta,e,insMap]theorem follows_left (W : Ordinary g q) (D : Ordinary g r) (mark) (c : Config g q) (t)(before : ∀ j, j<t → instruction W (follow W c j)≠none) :follow (chain W D mark) (rename (left r) c) t=rename (left r) (follow W c t) := byinduction t with| zero => rfl| succ t ih =>rw [follow,ih (fun j h => before j (by omega)),left_step _ _ _ _ (before t (by omega)),follow]theorem follows_right (W : Ordinary g q) (D : Ordinary g r) (mark) (c : Config g r) (t) :follow (chain W D mark) (rename (right q) c) t=rename (right q) (follow D c t) := byinduction t with| zero => rfl| succ t ih => simp only [follow,ih,right_step]theorem follow_add (M : Ordinary g q) (c : Config g q) (t k) :follow M c (t+k)=follow M (follow M c t) k := byinduction k with| zero => rfl| succ k ih => exact congrArg (once M) ihtheorem earliest (P : Nat→Prop) (t : Nat) (hit : P t) : ∃ j, P j ∧ ∀ i, i<j → ¬P i := byinduction t using Nat.strongRecOn with| ind t ih =>by_cases h : ∃ j, j<t ∧ P j· obtain ⟨j,lt,yes⟩ := h; exact ih j lt yes· exact ⟨t,hit,fun i lt yes => h ⟨i,lt,yes⟩⟩def Delivers (W : Ordinary g q) (A : Alphabet W) (x : List Bool) (D : Ordinary g r)(B : Alphabet D) (y : List Bool) : Prop :=∃ t, let c := follow W (inputConfig W A x) tinstruction W c=none ∧ c.pos=0 ∧ c.tape=inputTape D B ydef Answers (D : Ordinary g q) (B : Alphabet D) (ans : Fin q → Bool) (y : List Bool) (v : Bool) : Prop :=∃ t, let c := follow D (inputConfig D B y) tinstruction D c=none ∧ ans c.state=vtheorem answers_chain (W : Ordinary g q) (D : Ordinary g r) (mark : W.marker=D.marker)(A : Alphabet W) (B : Alphabet D) (ans : Fin r→Bool) {x y v}(produces : Delivers W A x D B y) (reads : Answers D B ans y v) :Answers (chain W D mark) (liftAlphabet W D mark A) (out q ans) x v := byobtain ⟨t,atT,pos,tape⟩ := producesobtain ⟨k,stopped,verdict⟩ := readslet c := inputConfig W A xlet C := chain W D markobtain ⟨j,atJ,before⟩ := earliest (fun i => instruction W (follow W c i)=none) t atThave eq : follow W c j=follow W c t := unique_halt W c atJ atThave env : (⟨(follow W c j).tape,(follow W c j).pos,D.start⟩ : Config g r)=inputConfig D B y := byrw [eq]; change (⟨(follow W (inputConfig W A x) t).tape,(follow W (inputConfig W A x) t).pos,D.start⟩ : Config g r)=_rw [pos,tape]; rfllet ini := inputConfig C (liftAlphabet W D mark A) xhave ini_eq : ini=rename (left r) c := rflhave start : follow C ini (j+1)=rename (right q) (inputConfig D B y) := byrw [ini_eq,follow,follows_left _ _ _ _ _ before,shift_control _ _ _ _ atJ,env]have final : follow C ini (j+1+k)=rename (right q) (follow D (inputConfig D B y) k) := byrw [follow_add,start,follows_right]refine ⟨j+1+k,?_⟩change instruction C (follow C ini (j+1+k))=none ∧ out q ans (follow C ini (j+1+k)).state=vrw [final]constructor· simpa only [instruction,C,chain,rename,right_delta,Option.map_eq_none_iff] using stopped· exact (out_right ..).trans verdictend P455EffectiveChainend/- Begin Problem455MarkedPath (from finite-semigroup-identity-bases). -/sectionnamespace P455MarkedPathopen P455Witness P455Paths P455ContactLift P455SourceFamilies P455SourceTheoremopen P455CrossedSupport P455OriginalWalk P455Compressionnoncomputable def ruleWord (r : Nat) (allow : Tag → Prop) (mark : Marking) (u : W) (x y : Nat) :=small u (retained r allow mark u x y)/-- A source statement independent of any arbitrary donor map or proposedwalk in the source. All ordered comparisons and all witness labels in itsquery are the result of the three concrete tester proofs. -/theorem crossed_gadget {r allow mark T} (capT : P455Quotient.Cap r T)(u : W) (capU : P455Closure.Cap r u) (x y : Nat) (flip : ClosedFlip r allow u x y)(uniform : UniformSlots r allow mark u x y)(h : Nat → W) (val : Nat → P455Quotient.Q (rules r allow mark) T)(reps : ∀ a ∈ ruleWord r allow mark u x y, P455Quotient.ofWord (rules r allow mark) T (h a) = val a)(live : P455Quotient.eval (rules r allow mark) capT val (ruleWord r allow mark u x y) ≠P455Quotient.zero (rules r allow mark) T)(ts : Tiles) (c : Certificate) (valid : Holds r allow mark T (c.query r ts))(second mate : Bool) (cross : Crosses (markedRecord c second) h x y) :let names := retained r allow mark u x ylet v := ruleWord r allow mark u x ylet d := donor v h rlet a := startLabel c second mate∃ seed z l k, (seed = x ∨ seed = y) ∧ Supplies v h r seed a ∧P455Quotient.Variant (rules r allow mark) T z ∧ z = l ++ v.flatMap h ++ k ∧Holds r allow mark z (c.query r ts) ∧ SourceEvidence r allow ts v h seed c ∧(Compressed r u → Holds r allow (sourceMarks d c) u ((transferred d c).query r ts)) ∧∀ p : List Step, p.length ≤ 6 → Walk r allow mark z a p →Walk r allow mark u seed (relabel d p) ∧ endpoint seed (relabel d p) = d (endpoint a p) ∧(relabel d p).length = p.length ∧ d (endpoint a p) ∈ names ∧Supplies v h r (d (endpoint a p)) (endpoint a p) ∧ Supplies u h r (d (endpoint a p)) (endpoint a p) := bylet names := retained r allow mark u x ylet v := ruleWord r allow mark u x ylet e := expand u nameshave exp : P455Retained.Expansion v e (fun a => a ∈ names) := canonical u nameshave orig : v.flatMap e = u := recover u namesobtain ⟨hr,cx,cy,_⟩ := flip_counts capU fliphave pos : 0 < r := by omegahave hx : x ∈ u := List.count_pos_iff.mp (cx.symm ▸ pos)have hy : y ∈ u := List.count_pos_iff.mp (cy.symm ▸ pos)obtain ⟨seed,side,img⟩ := choose_seed c second mate crosshave guard := actual_guard pos capU hx hy side uniformhave ks := (guard seed (near_self _ _)).1have count : u.count seed = r := side.elim (fun eq => eq.symm ▸ cx) (fun eq => eq.symm ▸ cy)have start : Supplies v h r seed (startLabel c second mate) := ⟨(counts_retained u names seed ks).trans count,img⟩have cap : P455Closure.Cap r (v.flatMap e) := orig.symm ▸ capUhave guard' : OriginalGuard r allow mark (v.flatMap e) (fun a => a ∈ names) seed 6 := orig.symm ▸ guardobtain ⟨z,l,k,path,eq,vw,ev,cmp,walks⟩ :=arbitrary_reps_original_gadget capT val v h reps live ts c valid second mate seed hr start exp cap guard'rw [orig] at cmp walksexact ⟨seed,z,l,k,side,start,path,eq,vw,ev,cmp,walks⟩end P455MarkedPathend/- Begin Problem455SupportBound (from finite-semigroup-identity-bases). -/sectionnamespace P455SupportBoundopen P455Witness P455Paths P455ContactGeometry P455CrossedSupport Problem455.Slotsopen P455FirstRewrite (names mem_names names_distinct size_le)noncomputable def occupants (u : W) (t i : Nat) : W := byclassicalexact (names u).filter (fun a => decide (occupies u t i a))theorem mem_occupants {u : W} {t i a : Nat} : a ∈ occupants u t i ↔ occupies u t i a := byclassicalsimp only [occupants,List.mem_filter,mem_names,decide_eq_true_eq,and_iff_right_iff_imp]rintro ⟨j,seen⟩exact stamped_mem_label _ _ (a,j) (seen.subset (by simp))def Capacity (r : Nat) (allow : Tag → Prop) (mark : Marking) (u : W) (x y K : Nat) :=∀ t, InBall r allow mark u x y t → ∀ i, slotStart i → (occupants u t i).length ≤ Kprivate def starts : W := [0,1,3,5,7,9,11]private theorem in_starts (i : Nat) : i ∈ starts ↔ slotStart i := by simp [starts,slotStart]private theorem flat_bound (u : W) (F : Nat → W) (K : Nat) (b : ∀ t ∈ u, (F t).length ≤ K) :(u.flatMap F).length ≤ u.length*K := byinduction u with| nil => simp| cons a u ih =>have v := ih (fun t ht => b t (List.mem_cons_of_mem _ ht))have h := b a List.mem_cons_selfsimp only [List.flatMap_cons,List.length_append,List.length_cons,Nat.succ_mul]omega/-- Includes all seven literal slots of a reached vertex. It may overcountnon-neighbors. Outside the radius-six ball there is no outgoing list. -/noncomputable def next (r : Nat) (allow : Tag → Prop) (mark : Marking) (u : W) (x y t : Nat) : W := byclassicalexact if InBall r allow mark u x y t then starts.flatMap (occupants u t) else []private theorem next_bound {r allow mark u x y K} (cap : Capacity r allow mark u x y K)(t : Nat) : (next r allow mark u x y t).length ≤ 7*K := byclassicalby_cases ball : InBall r allow mark u x y t· rw [next,if_pos ball]exact flat_bound starts (occupants u t) K (fun i hi => cap t ball i ((in_starts i).mp hi))· simp [next,ball]private theorem next_slot {r allow mark u x y t i a} (ball : InBall r allow mark u x y t)(slot : slotStart i) (o : occupies u t i a) : a ∈ next r allow mark u x y t := byclassicalrw [next,if_pos ball]exact List.mem_flatMap.mpr ⟨i,(in_starts i).mpr slot,mem_occupants.mpr o⟩/-- 1 + D + ... + D^j. -/def geometric (D : Nat) : Nat → Nat | 0 => 1 | j+1 => 1+D*geometric D jprivate def explore (F : Nat → W) : Nat → Nat → W| 0, t => [t]| j+1, t => t :: (F t).flatMap (explore F j)private theorem seed_mem (F : Nat → W) (j t : Nat) : t ∈ explore F j t := bycases j <;> exact List.mem_cons_selfprivate theorem explore_bound (F : Nat → W) (D : Nat) (bound : ∀ t, (F t).length ≤ D) (j t : Nat) :(explore F j t).length ≤ geometric D j := byinduction j generalizing t with| zero => simp [geometric,explore]| succ j ih =>have s := flat_bound (F t) (explore F j) (geometric D j) (fun a _ => ih a)have b := Nat.mul_le_mul_right (geometric D j) (bound t)simp only [geometric,explore,List.length_cons]; omegaprivate theorem walked {r allow mark u x y} (source t : Nat) (seed : source=x ∨ source=y)(n j : Nat) (budget : n+j ≤ 6) (pre : Near r allow mark u source t n)(p : List Step) (walk : Walk r allow mark u t p) (len : p.length ≤ j) :endpoint t p ∈ explore (next r allow mark u x y) j t := byinduction p generalizing t n j with| nil => exact seed_mem _ _ _| cons e p ih =>obtain ⟨a,c⟩ := ecases j with| zero => simp at len| succ j =>have ball : InBall r allow mark u x y t :=seed.elim (fun eq => .inl (eq ▸ near_mono pre (by omega))) (fun eq => .inr (eq ▸ near_mono pre (by omega)))obtain ⟨i,slot,occ⟩ := contact_slot walk.1have into := next_slot ball slot occhave more := near_trans pre (near_one c walk.1)have cont := ih a (n+1) j (by omega) more walk.2 (by simp_all)exact List.mem_cons_of_mem _ (List.mem_flatMap.mpr ⟨a,into,cont⟩)theorem retained_bound {r allow mark u x y K} (cap : Capacity r allow mark u x y K) :(names (retained r allow mark u x y)).length ≤2*(1+7*K)*geometric (7*K) 6 := bylet F := next r allow mark u x ylet D := 7*Klet ball := explore F 6 x ++ explore F 6 ylet covered := ball ++ ball.flatMap Fhave all (b) (hb : InBall r allow mark u x y b) : b ∈ ball := byhave mem (s) (origin : s=x ∨ s=y) (near : Near r allow mark u s b 6) : b ∈ explore F 6 s := byobtain ⟨p,wp,eq,len⟩ := nearexact eq ▸ walked s s origin 0 6 (by decide) (near_self s 0) p wp lenexact List.mem_append.mpr (hb.imp (mem x (.inl rfl)) (mem y (.inr rfl)))have included (a) (ha : a ∈ names (retained r allow mark u x y)) : a ∈ covered := byobtain ⟨_,needs⟩ := mem_retained.mp ((mem_names _ _).mp ha)unfold coveredapply List.mem_append.mprrcases needs with b | ⟨t,i,reach,slot,occ⟩· exact .inl (all a b)· exact .inr (List.mem_flatMap.mpr ⟨t,all t reach,next_slot reach slot occ⟩)have fb (a) : (F a).length ≤ D := next_bound cap ahave count := size_le (names_distinct _) includedhave size : ball.length ≤ 2*geometric D 6 := byhave bx := explore_bound F D fb 6 xhave by' := explore_bound F D fb 6 ydsimp only [ball]; rw [List.length_append]; omegahave more := flat_bound ball F D (fun t _ => fb t)have gross : covered.length ≤ ball.length*(1+D) := bydsimp only [covered]; rw [List.length_append,Nat.mul_add,Nat.mul_one]; omegahave lim := Nat.mul_le_mul_right (1+D) sizehave fin := Nat.le_trans count (Nat.le_trans gross lim)simpa only [D,Nat.mul_assoc,Nat.mul_left_comm,Nat.mul_comm] using fintheorem retained_bound_four {r allow mark u x y} (cap : Capacity r allow mark u x y 4) :(names (retained r allow mark u x y)).length ≤ 2*(1+28)*geometric 28 6 := retained_bound cap/-- The owner cannot itself be a literal occupant between two consecutiveindexed copies, whether or not the containing word is capped. -/theorem owner_absent (u : W) (t i : Nat) : ¬ occupies u t i t := byintro occobtain ⟨j,hj⟩ := occhave mem : (t,i+1) ∈ events u := hj.mem (by simp)have b := (P455SlotOrigin.event_bounds (fun _ => 0) u t (i+1) mem).2obtain ⟨l,mid,k,cut,index,fresh⟩ := P455SlotOrigin.slot_cut u t i (by omega)have occ' : occupies u t i t := ⟨j,hj⟩rw [cut,←index] at occ'exact fresh ((P455SlotOrigin.occupies_at_cut l mid k t t fresh).mp occ')/-- An overfull genuine protected slot supplies five distinct saturatedoccupants and their literal terminal witness in a compressed source. -/theorem overflow_of_more {r allow mark u x y t i}(uniform : UniformSlots r allow mark u x y) (cmp : P455SourceFamilies.Compressed r u)(ball : InBall r allow mark u x y t) (slot : slotStart i)(over : 4 < (occupants u t i).length) :∃ xs, Holds r allow mark u (terminalSlot r t i (.overflow xs)) := byclassicallet xs := (occupants u t i).take 5have inside (a) (ha : a ∈ xs) : occupies u t i a :=mem_occupants.mp ((List.take_sublist _ _).subset ha)have nodup : xs.Nodup :=(names_distinct u).sublist (List.Sublist.trans (List.take_sublist _ _) List.filter_sublist)have uniq : (t::xs).Nodup := List.nodup_cons.mpr ⟨fun h => owner_absent u t i (inside t h),nodup⟩refine ⟨xs,List.length_take_of_le (by omega),(P455TerminalTransfer.block_separation _).mpr(uniq.imp (fun ne => P455SourceFamilies.compressed_separates cmp ne)),?_,True.intro⟩apply (allQ_iff _).mprintro q memobtain ⟨a,ha,rfl⟩ := List.mem_map.mp memhave occ := inside a haexact ⟨uniform t ball i slot a occ,slot,occ⟩theorem capacity_of_no_overflow {r allow mark u x y}(uniform : UniformSlots r allow mark u x y) (cmp : P455SourceFamilies.Compressed r u)(none : ∀ t, InBall r allow mark u x y t → ∀ i, slotStart i →∀ xs, ¬ Holds r allow mark u (terminalSlot r t i (.overflow xs))) :Capacity r allow mark u x y 4 := byintro t ball i slotexact Nat.le_of_not_lt (fun h => byobtain ⟨xs,w⟩ := overflow_of_more uniform cmp ball slot hexact none t ball i slot xs w)/-- Uniform one-step rank under the actual source geometric guard and validityof the canonical smaller identity. Bound depends only on the fixed r. -/theorem bounded_step_of_capacity {A : Type} (M : P455FirstRewrite.Model A){r allow mark} (f : P455Closure.Frame Nat) (l k : W) {x y : Nat}(hp : f.p = [x]) (hq : f.q = [y]) (valid : f.Valid r allow (fun _ _ => False))(b : Bool) (cap : P455Closure.Cap r (P455Uncrossed.side f l k b))(capacity : Capacity r allow mark (P455Uncrossed.side f l k b) x y 4)(semantic :let keep := retained r allow mark (P455Uncrossed.side f l k b) x yM.Valid (P455Compression.small (P455Uncrossed.side f l k b) keep)(P455Compression.small (P455Uncrossed.side f l k (!b)) keep)) :let N := 2*(1+28)*geometric 28 6P455FirstRewrite.Step (fun u v => M.Valid u v ∧ P455FirstRewrite.rank u v ≤ N+r*N+1)(P455Uncrossed.side f l k b) (P455Uncrossed.side f l k (!b)) := bylet u := P455Uncrossed.side f l k blet keep := retained r allow mark u x yhave flip : ClosedFlip r allow u x y := ⟨f,b,l,k,hp,hq,valid,rfl⟩obtain ⟨hr,cx,cy,_⟩ := flip_counts cap fliphave hx : x ∈ keep := mem_retained.mpr⟨List.count_pos_iff.mp (cx.symm ▸ (by omega : 0 < r)),.inl (.inl (near_self x 6))⟩have hy : y ∈ keep := mem_retained.mpr⟨List.count_pos_iff.mp (cy.symm ▸ (by omega : 0 < r)),.inl (.inr (near_self y 6))⟩have step := P455SmallRank.bounded_step M f l k keep hx hy hp hq valid b cap semantichave small : (names keep).length ≤ 2*(1+28)*geometric 28 6 := retained_bound_four capacityhave scaled := Nat.mul_le_mul_left r smallobtain ⟨U,V,L,R,h,hyp,nu,nv,ne,src,dst⟩ := steprefine ⟨U,V,L,R,h,?_,nu,nv,ne,src,dst⟩rcases hyp with ⟨val,rnk⟩|⟨val,rnk⟩· exact .inl ⟨val,by omega⟩· exact .inr ⟨val,by omega⟩end P455SupportBoundend/- Begin Problem455StructuralProduct (from finite-semigroup-identity-bases). -/sectionnamespace P455StructuralProductopen P455Structural P455Witness P455Quotient P455Closure P455Uncrossedopen P455SourceFamilies P455FirstTesters P455FirstRewritedef templates (r : Nat) := Problem455Finite.wordsUpTo (List.range 4) (4*r)structure Index (r : Nat) (allow : Tag → Prop) wherepos : Fin (templates r).lengthcap : P455Closure.Cap r ((templates r).get pos)cmp : Compressed r ((templates r).get pos)test : Structural ((templates r).get pos) r allowdef Index.T (i : Index r allow) := (templates r).get i.posabbrev Carrier (r : Nat) (allow : Tag → Prop) := (i : Index r allow) → Q (plain r) i.Tdef product (r : Nat) (allow : Tag → Prop) : Model (Carrier r allow) whereop := fun x y i => mul (plain r) i.cap (x i) (y i)unit := fun i => ofWord (plain r) i.T []assoc := fun x y z => funext (fun i => mul_assoc (plain r) i.cap (x i) (y i) (z i))oneL := fun x => funext (fun i => (unit_laws (plain r) i.cap (x i)).1)oneR := fun x => funext (fun i => (unit_laws (plain r) i.cap (x i)).2)theorem coordinate (f : Nat → Carrier r allow) (w : List Nat) (i : Index r allow) :(product r allow).eval f w i = eval (plain r) i.cap (fun x => f x i) w := byinduction w with| nil => rfl| cons x xs ih => exact congrArg (mul (plain r) i.cap (f x i)) ihtheorem identity {r allow} (f : Frame Nat) (l k : List Nat) (x y : Nat)(hp : f.p=[x]) (hq : f.q=[y]) (valid : f.Valid r allow (fun _ _ => False)) :(product r allow).Valid (side f l k false) (side f l k true) := byintro valfunext irw [coordinate,coordinate]exact structural_eval i.cap i.cmp i.test f l k x y hp hq valid _/-- The actual shared canonical words of the positional gap constructionsatisfy the structural subproduct identity for every retained-name listcontaining the marked roles. -/theorem small_identity {r allow} (f : Frame Nat) (l k names : List Nat) (x y : Nat)(hx : x ∈ names) (hy : y ∈ names) (hp : f.p=[x]) (hq : f.q=[y])(valid : f.Valid r allow (fun _ _ => False)) (bit : Bool)(cap : P455Closure.Cap r (side f l k bit)) :(product r allow).Valid (P455Compression.small (side f l k false) names)(P455Compression.small (side f l k true) names) := byobtain ⟨g,L,K,gp,gq,gv,eq,_⟩ :=P455CompressedFrame.canonical_pair f l k names hx hy hp hq valid bit caprw [eq,eq]exact identity g L K x y gp gq gvend P455StructuralProductend/- Begin Problem455PaddedMatchings (from finite-semigroup-identity-bases). -/sectionnamespace P455PaddedMatchingsopen P455PaddedPorts P455PaddedTilesdef idAt (w y x : Nat) := w*y + (if odd y then w-1-x else x)private theorem offset_lt {w x : Nat} (y : Nat) (hx : x<w) :(if odd y then w-1-x else x)<w := by split <;> omegatheorem id_inj {w y x z q : Nat} (hx : x<w) (hq : q<w) (eq : idAt w y x=idAt w z q) :y=z ∧ x=q := byhave wt : 0<w := by omegahave div := congrArg (· / w) eqsimp only [idAt,Nat.mul_add_div wt,Nat.div_eq_of_lt (offset_lt y hx),Nat.div_eq_of_lt (offset_lt z hq),Nat.add_zero] at divsubst zsimp only [idAt,Nat.add_left_cancel_iff] at eqsplit at eq <;> omegatheorem id_bound {w h y x : Nat} (hy : y<h) (hx : x<w) : idAt w y x < w*h := byhave le := Nat.mul_le_mul_left w (show y+1≤h by omega)rw [Nat.mul_add,Nat.mul_one] at lehave off := offset_lt y hxunfold idAt; omegatheorem id_covers {w h i : Nat} (lt : i<w*h) :∃ y<h, ∃ x<w, idAt w y x=i := byhave wpos : 0<w := bycases w with| zero => simp at lt| succ => omegalet y := i/wlet j := i%whave jo : j<w := Nat.mod_lt _ wposhave ex := Nat.mod_add_div i whave yl : y<h := byby_cases e : y<h· exact e· have mul := Nat.mul_le_mul_left w (show h≤y by omega)change w*h≤w*(i/w) at mulomegarefine ⟨y,yl,if odd y then w-1-j else j,offset_lt y jo,?_⟩unfold idAtby_cases e : odd y=true· simp [e]have z : w-1-(w-1-j)=j := by omegarw [z]dsimp [y,j]; omega· simp [e]dsimp [y,j]; omegadef pairs (f : Nat → Nat) (start : Nat) : Nat → List Block| 0 => []| 1 => [.single (f start)]| n+2 => .pair (f start) (f (start+1)) :: pairs f (start+2) ndef line (skip : Bool) (f : Nat → Nat) (size : Nat) :=if skip then match size with| 0 => []| k+1 => .single (f 0) :: pairs f 1 kelse pairs f 0 sizeprivate theorem pair_cells (f : Nat→Nat) (s n : Nat) :(pairs f s n).flatMap cells = (List.range' s n).map f := byinduction n using Nat.strongRecOn generalizing s with| ind n ih =>cases n with| zero => rfl| succ n => cases n with| zero => rfl| succ n =>simp [pairs,cells,ih n (by omega) (s+2),List.range'_succ]theorem line_cells (skip : Bool) (f : Nat→Nat) (n : Nat) :(line skip f n).flatMap cells=(List.range n).map f := bycases skip· simp [line,pair_cells,List.range_eq_range']· cases n with| zero => rfl| succ n => simp [line,cells,pair_cells,List.range_eq_range',List.range'_succ]private theorem pair_edge (f : Nat → Nat) (s n a b : Nat) :Block.pair a b ∈ pairs f s n ↔∃ k, k+1<n ∧ k%2=0 ∧ a=f (s+k) ∧ b=f (s+k+1) := byinduction n using Nat.strongRecOn generalizing s with| ind n ih =>cases n with| zero => simp [pairs]| succ n => cases n with| zero => simp [pairs]| succ n =>simp only [pairs,List.mem_cons,Block.pair.injEq]rw [ih n (by omega)]constructor· rintro (⟨ea,eb⟩|⟨k,lt,par,ea,eb⟩)· exact ⟨0,by omega,rfl,by simpa using ea,by simpa using eb⟩· exact ⟨k+2,by omega,by omega,by simpa [Nat.add_assoc,Nat.add_comm,Nat.add_left_comm] using ea,by simpa [Nat.add_assoc,Nat.add_comm,Nat.add_left_comm] using eb⟩· rintro ⟨k,lt,par,ea,eb⟩by_cases e : k=0· subst k; exact .inl ⟨by simpa using ea,by simpa using eb⟩· have kk : s+2+(k-2)=s+k := by omegaexact .inr ⟨k-2,by omega,by omega,by simpa only [kk] using ea,by simpa only [kk] using eb⟩theorem line_edge (skip : Bool) (f : Nat→Nat) (size a b : Nat) :Block.pair a b ∈ line skip f size ↔∃ k, k+1<size ∧ odd k=skip ∧ a=f k ∧ b=f (k+1) := bycases skip· simp only [line,Bool.false_eq_true,if_false,pair_edge,Nat.zero_add]constructor· rintro ⟨k,lt,p,u,v⟩; exact ⟨k,lt,by simp [odd,p],u,v⟩· rintro ⟨k,lt,p,u,v⟩; exact ⟨k,lt,by simp [odd] at p; omega,u,v⟩· cases size with| zero => simp [line]| succ n =>simp only [line,if_true,List.mem_cons,Block.noConfusion,reduceCtorEq,false_or,pair_edge]constructor· rintro ⟨k,lt,p,u,v⟩refine ⟨k+1,by omega,?_,?_,?_⟩· simp [odd,show (k+1)%2=1 by omega]· simpa [Nat.add_comm] using u· simpa [Nat.add_assoc,Nat.add_comm,Nat.add_left_comm] using v· rintro ⟨k,lt,p,u,v⟩; simp [odd] at pexact ⟨k-1,by omega,by omega,by simpa [show 1+(k-1)=k by omega] using u,by simpa [show 1+(k-1)=k by omega] using v⟩def lines (m n : Nat) (skip : Bool) (f : Nat→Nat→Nat) :=(List.range m).flatMap fun z=>line skip (f z) nprivate theorem flatten_lines (m n : Nat) (skip : Bool) (f : Nat→Nat→Nat) :(lines m n skip f).flatMap cells=(List.range m).flatMap (fun z=>(List.range n).map (f z)) := bysimp [lines,List.flatMap_assoc,line_cells]theorem lines_unique (m n : Nat) (skip : Bool) (f : Nat→Nat→Nat)(inj : ∀ z<m, ∀ x<n, ∀ t<m, ∀ j<n, f z x=f t j → z=t ∧ x=j) :((lines m n skip f).flatMap cells).Nodup := byrw [flatten_lines]apply List.pairwise_flatMap.mprconstructor· intro z hzapply List.pairwise_map.mprexact List.nodup_range.imp_of_mem (fun hx hj ne eq => ne(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)· apply List.nodup_range.imp_of_memintro z t hz ht ne a ha b hb eqobtain ⟨x,hx,rfl⟩ := List.mem_map.mp haobtain ⟨j,hj,rfl⟩ := List.mem_map.mp hbexact 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).1def horizontal (h w : Nat) (skip : Bool) := lines h w skip (idAt w)def vertical (h w : Nat) (skip : Bool) := lines w h skip (fun x y=>idAt w y x)theorem horizontal_unique (h w : Nat) (skip : Bool) :((horizontal h w skip).flatMap cells).Nodup :=lines_unique _ _ _ _ (fun _ _ _ hx _ _ _ hj eq=>id_inj hx hj eq)theorem vertical_unique (h w : Nat) (skip : Bool) :((vertical h w skip).flatMap cells).Nodup :=lines_unique _ _ _ _ (fun _ hx _ _ _ hj _ _ eq=>And.symm (id_inj hx hj eq))theorem horizontal_cells (h w i : Nat) (skip : Bool) :i∈(horizontal h w skip).flatMap cells ↔ i<w*h := byrw [horizontal,flatten_lines]constructor· intro m; obtain ⟨y,hy,mx⟩ := List.mem_flatMap.mp mobtain ⟨x,hx,rfl⟩ := List.mem_map.mp mxexact id_bound (List.mem_range.mp hy) (List.mem_range.mp hx)· intro lt; obtain ⟨y,hy,x,hx,eq⟩ := id_covers ltexact List.mem_flatMap.mpr ⟨y,List.mem_range.mpr hy,List.mem_map.mpr ⟨x,List.mem_range.mpr hx,eq⟩⟩theorem vertical_cells (h w i : Nat) (skip : Bool) :i∈(vertical h w skip).flatMap cells ↔ i<w*h := byrw [vertical,flatten_lines]constructor· intro m; obtain ⟨x,hx,my⟩ := List.mem_flatMap.mp mobtain ⟨y,hy,rfl⟩ := List.mem_map.mp myexact id_bound (List.mem_range.mp hy) (List.mem_range.mp hx)· intro lt; obtain ⟨y,hy,x,hx,eq⟩ := id_covers ltexact List.mem_flatMap.mpr ⟨x,List.mem_range.mpr hx,List.mem_map.mpr ⟨y,List.mem_range.mpr hy,eq⟩⟩theorem horizontal_edge (h w a b : Nat) (skip : Bool) :Block.pair a b∈horizontal h w skip ↔∃ y<h, ∃ x, x+1<w ∧ odd x=skip ∧ a=idAt w y x ∧ b=idAt w y (x+1) := bysimp [horizontal,lines,List.mem_flatMap,line_edge]theorem vertical_edge (h w a b : Nat) (skip : Bool) :Block.pair a b∈vertical h w skip ↔∃ x<w, ∃ y, y+1<h ∧ odd y=skip ∧ a=idAt w y x ∧ b=idAt w (y+1) x := bysimp [vertical,lines,List.mem_flatMap,line_edge]def wrap (t : Nat) : List Block :=.pair (t-1) 0 :: ((List.range t).filter fun i=>0<i && i<t-1).map Block.singletheorem wrap_edge (t a b : Nat) : Block.pair a b ∈ wrap t ↔ a=t-1 ∧ b=0 := bysimp [wrap,List.mem_map]private theorem flatten_singles (xs : List Nat) : (xs.map Block.single).flatMap cells=xs := byinduction xs with| nil => rfl| cons a xs ih => simp [cells,ih]theorem wrap_unique {t : Nat} (ht : 1<t) : ((wrap t).flatMap cells).Nodup := bysimp only [wrap,List.flatMap_cons,cells,flatten_singles,List.cons_append,List.nil_append]simp [List.nodup_cons,show t-1≠0 by omega]exact List.Pairwise.filter _ List.nodup_rangetheorem wrap_cells {t : Nat} (ht : 1<t) (i : Nat) : i∈(wrap t).flatMap cells ↔ i<t := bysimp only [wrap,List.flatMap_cons,cells,flatten_singles,List.cons_append,List.nil_append,List.mem_cons,List.mem_filter,List.mem_range,Bool.and_eq_true,decide_eq_true_eq]omegaend P455PaddedMatchingsend/- Begin Problem455PaddedIndexed (from finite-semigroup-identity-bases). -/sectionnamespace P455PaddedPortsopen P455RectangleRank Problem455.Slotstheorem count_one {ks : W} (nd : ks.Nodup) {a : Nat} (m : a∈ks) : ks.count a=1 := byinduction ks with| nil => simp at m| cons x ks ih =>obtain ⟨out,tail⟩ := List.nodup_cons.mp ndby_cases e : a=x· subst x; simp [List.count_cons,List.count_eq_zero.mpr out]· have z : a∈ks := by simpa [e] using msimp [List.count_cons,e,Ne.symm e,ih tail z]theorem count_phase (bs : List Block) (c : Nat) :(phase bs).count c = 2*(bs.flatMap cells).count c := byinduction bs with| nil => rfl| cons b bs ih =>change ((cells b ++ cells b) ++ phase bs).count c=2*((cells b) ++ bs.flatMap cells).count csimp only [List.count_append,ih]; omegatheorem count_role (s : W) (c a : Nat) (target : a=owner c ∨ a=mate c) :(s.flatMap roles).count a=s.count c := byinduction s with| nil => rfl| cons k s ih =>simp only [List.flatMap_cons,List.count_append,ih]by_cases eq : k=c· subst krcases target with rfl|rfl <;> simp [roles,List.count_cons,owner,mate] <;> omega· have non : a∉roles k := byunfold rolessimp only [List.mem_cons,List.not_mem_nil,or_false]unfold owner mate at target ⊢; omegasimp [List.count_eq_zero.mpr non,List.count_cons,eq,Ne.symm eq]/-- Context can contribute arbitrarily many other events, including earlieror later copies of the four observed roles. Only the counts at the actualphase boundary are relevant. -/theorem indexed_window {ks pre mid post : W} {k : Nat} (nd : ks.Nodup)(before : ∀ a∈ks, pre.count a=k) (inside : ∀ a∈ks, mid.count a=2) :sees (pre++mid++post) (stamp (fun _=>k) (ks++ks)) ↔ select ks mid=ks++ks := bylet active (e : Event) := decide (e.1∈ks ∧ k≤e.2 ∧ e.2<k+2)let zero : Nat → Nat := fun _=>0let p : Nat → Nat := fun a=>pre.count alet q : Nat → Nat := fun a=>pre.count a+mid.count ahave whole : events (pre++mid++post)=stamp zero pre ++ (stamp p mid ++ stamp q post) := bysimp only [List.append_assoc,events,stamp_append]have e : advance (fun _=>0) pre=p := by funext a; simp [advance,p]have f : advance p mid=q := by rflrw [e,f]have none₁ : (stamp zero pre).filter active=[] := byapply List.filter_eq_nil_iff.mprrintro ⟨a,i⟩ mem yesobtain ⟨m,lo,_⟩ := of_decide_eq_true yeshave lim := (P455ContactGeometry.stamp_range zero pre mem).2change i<0+pre.count a at limhave := before a m; omegahave none₂ : (stamp q post).filter active=[] := byapply List.filter_eq_nil_iff.mprrintro ⟨a,i⟩ mem yesobtain ⟨m,_,hi⟩ := of_decide_eq_true yeshave lim := (P455ContactGeometry.stamp_range q post mem).1change pre.count a+mid.count a≤i at limhave := before a m; have := inside a m; omegahave middle : (stamp p mid).filter active=stamp (fun _=>k) (select ks mid) := byrw [P455ContactGeometry.project_stamp ks mid (fun _=>k) p (fun a m => (before a m).symm)]apply List.filter_congrrintro ⟨a,i⟩ memby_cases m : a∈ks· have lim := P455ContactGeometry.stamp_range p mid memchange pre.count a≤i ∧ i<pre.count a+mid.count a at limhave := before a m; have := inside a msimp [active,m,show k≤i by omega,show i<k+2 by omega]· simp [active,m]have observed : (events (pre++mid++post)).filter active=stamp (fun _=>k) (select ks mid) := bysimp only [whole,List.filter_append,none₁,none₂,middle,List.append_nil,List.nil_append]have full : (stamp (fun _=>k) (ks++ks)).filter active = stamp (fun _=>k) (ks++ks) := byapply List.filter_eq_self.mprrintro ⟨x,i⟩ mhave mem := stamped_mem_label (fun _=>k) (ks++ks) _ mhave mx : x∈ks := by simpa using memhave lim := P455ContactGeometry.stamp_range (fun _=>k) (ks++ks) msimp only [List.count_append,count_one nd mx] at limexact decide_eq_true ⟨mx,lim.1,by omega⟩constructor· intro seqhave sub := seq.filter activechange ((stamp (fun _=>k) (ks++ks)).filter active).Sublist ((events (pre++mid++post)).filter active) at subrw [full,observed] at subhave words := sub.map Prod.fstsimp only [labels_of_stamp] at wordshave perm : (select ks mid).Perm (ks++ks) := byapply List.perm_iff_count.mprintro aby_cases m : a∈ks· unfold selectrw [List.count_filter (p:=fun e => decide (e ∈ ks)) (decide_eq_true m),List.count_append,inside a m,count_one nd m]· have no : a∉select ks mid := by simp [select,m]simp [List.count_eq_zero.mpr no,List.count_eq_zero.mpr m]exact (words.eq_of_length perm.length_eq.symm).symm· intro eqrw [←eq,←observed]exact List.filter_sublist ..def portPattern (i j k : Nat) : List Event :=[(owner i,k),(mate i,k),(owner j,k),(mate j,k),(owner i,k+1),(mate i,k+1),(owner j,k+1),(mate j,k+1)]theorem indexed_port_exact {bs : List Block} {pre post : W} {i j k : Nat} (ne : i≠j)(nd : (bs.flatMap cells).Nodup) (mi : i∈bs.flatMap cells) (mj : j∈bs.flatMap cells)(prefixCount : ∀ a∈roles i ++ roles j, pre.count a=k) :sees (pre++letters bs++post) (portPattern i j k) ↔ Block.pair i j∈bs := bylet ks := roles i ++ roles jhave dis : owner i≠mate i ∧ owner j≠mate j ∧ owner i≠owner j ∧ owner i≠mate j ∧mate i≠owner j ∧ mate i≠mate j := by unfold owner mate; omegahave 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]have window (a) (used : a∈ks) : (letters bs).count a=2 := byhave ea : (a=owner i ∨ a=mate i) ∨ (a=owner j ∨ a=mate j) := bysimpa only [ks,roles,List.mem_append,List.mem_cons,List.not_mem_nil,or_false] using usedrcases ea with ai|aj· rw [letters,count_role _ i a ai,count_phase,count_one nd mi]· rw [letters,count_role _ j a aj,count_phase,count_one nd mj]have ev : stamp (fun _=>k) (ks++ks)=portPattern i j k := byrw [stamp_append,stamp_at (fun _=>k) k ks nod (fun _ _ => rfl),stamp_at (advance (fun _=>k) ks) (k+1) ks nod (fun a m=>by simp [advance,count_one nod m])]rflrw [← ev,indexed_window nod prefixCount window]exact literal_phase_exact nd i j ne/-- The original tester query, without any hypothesis that it holds. Thestatic typed-record and early-disjoint requirements are displayed separatelyfrom the geometric matching criterion. -/theorem oriented_port_iff {r : Nat} (hr : 16≤r) (allow : P455Witness.Tag → Prop)(mark : P455Witness.Marking) (port : Fin 5) (tagI tagJ : P455Witness.Tag){bs : List Block} {pre post : W} {i j : Nat} (ne : i≠j)(nd : (bs.flatMap cells).Nodup) (mi : i∈bs.flatMap cells) (mj : j∈bs.flatMap cells)(prefixCount : ∀ a∈roles i ++ roles j, pre.count a=3+2*port.val) :let a : P455Witness.Node := ⟨owner i,mate i,tagI⟩let b : P455Witness.Node := ⟨owner j,mate j,tagJ⟩let H := P455Witness.Holds r allow mark (pre++letters bs++post)H (P455Witness.orientedPort port.val a b) ↔ H (P455Witness.typedNode a) ∧H (P455Witness.typedNode b) ∧ H (P455Witness.earlyDisjoint (roles i) (roles j)) ∧Block.pair i j∈bs := bydsimp onlyhave obs := indexed_port_exact (post:=post) ne nd mi mj prefixCountconstructor· rintro ⟨ta,tb,ear,ord,_⟩exact ⟨ta,tb,ear,obs.mp ord.2⟩· rintro ⟨ta,tb,ear,matchEdge⟩refine ⟨ta,tb,ear,⟨?_,obs.mpr matchEdge⟩,True.intro⟩intro e mhave lt := port.isLtsimp only [List.mem_cons,List.not_mem_nil,or_false] at mrcases m with h|h|h|h|h|h|h|h <;> rw [h] <;> dsimp <;> omegaend P455PaddedPortsend/- Begin Problem455WriterFrontier (from finite-semigroup-identity-bases). -/section/- A simulated blank and a never-scanned blank have different physical codes.Thus the used interval can be erased even if it contains arbitrary blank gaps. -/namespace P455WriterFrontieropen P455MachineLocal P455MachineTable P455MachineCleanup P455EffectiveMachinedef ink (a : Fin g) : Fin (g+1) := ⟨a.val, by have := a.isLt; omega⟩def fresh (g : Nat) : Fin (g+1) := ⟨g, by omega⟩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⟩theorem ink_ne_fresh (a : Fin g) : ink a ≠ fresh g := byintro h; have v := congrArg Fin.val h; change a.val=g at v; exact (Nat.ne_of_lt a.isLt) vdef eraseTag (blank : Fin g) (a : Fin (g+1)) : Fin g :=if h : a.val<g then ⟨a.val,h⟩ else blank@[simp] theorem erase_ink (blank a : Fin g) : eraseTag blank (ink a)=a := by simp [eraseTag,ink,a.isLt]@[simp] theorem erase_fresh (blank : Fin g) : eraseTag blank (fresh g)=blank := by simp [eraseTag,fresh]theorem erase_marker (M : Ordinary g q) (a : Fin (g+1)) :eraseTag M.blank a=M.marker ↔ a=ink M.marker := byby_cases h : a.val<g· simp only [eraseTag,h,↓reduceDIte]constructor· intro e; exact Fin.ext (congrArg (fun z : Fin g => z.val) e)· intro e; exact Fin.ext (congrArg (fun z : Fin (g+1) => z.val) e)· have ne : a≠ink M.marker := byintro eq; subst a; exact h M.marker.isLtsimp [eraseTag,h,M.blank_ne,ne]def tagIns (i : Ins (Fin g) (Fin q)) : Ins (Fin (g+1)) (Fin q) :=⟨i.state,ink i.symbol,i.dir⟩def monitor (M : Ordinary g q) : Ordinary (g+1) q wheremarker := ink M.markerblank := fresh gblank_ne := Ne.symm (ink_ne_fresh _)start := M.startdelta z a := (M.delta z (eraseTag M.blank a)).map tagInskeeps := byintro z a i ecases h : M.delta z (eraseTag M.blank a) with| none => simp [h] at e| some j =>rw [h] at echange some (tagIns j)=some i at ehave e := Option.some.inj esubst i; exact ink_inj.trans ((M.keeps _ _ _ h).trans (erase_marker M a))leftSafe := byintro z i esimp only [erase_ink] at ecases h : M.delta z M.marker with| none => simp [h] at e| some j =>rw [h] at echange some (tagIns j)=some i at ehave e := Option.some.inj esubst i; exact M.leftSafe _ _ hdef alphabet (M : Ordinary g q) (A : Alphabet M) : Alphabet (monitor M) wherebit b := ink (A.bit b)away b h := A.away b (ink_inj.mp h)ink b := ink_ne_fresh (A.bit b)distinct h := A.distinct (ink_inj.mp h)def tape (n : Nat) (f : Nat → Fin g) (j : Nat) := if j≤n then ink (f j) else fresh gdef liftCfg (n : Nat) (c : Config g q) : Config (g+1) q := ⟨tape n c.tape,c.pos,c.state⟩def Good (M : Ordinary g q) (c : Config g q) (n : Nat) : Prop :=c.pos≤n+1 ∧ (∀ j, n<j → c.tape j=M.blank) ∧ (∀ j, c.tape j=M.marker ↔ j=0)theorem input_good (M : Ordinary g q) (A : Alphabet M) (x : List Bool) :Good M (inputConfig M A x) x.length := byrefine ⟨Nat.zero_le _,?_,?_⟩· intro j h; cases j with| zero => omega| succ i => simp [inputConfig,inputTape,List.getElem?_eq_none (show x.length≤i by omega)]· intro j; cases j with| zero => simp [inputConfig,inputTape]| succ i =>change (x[i]?).elim M.blank A.bit=M.marker ↔ i+1=0cases x[i]? with| none => simp [M.blank_ne]| some b => simp [A.away]theorem input_eq (M : Ordinary g q) (A : Alphabet M) (x : List Bool) :inputConfig (monitor M) (alphabet M A) x=liftCfg x.length (inputConfig M A x) := bysuffices h : inputTape (monitor M) (alphabet M A) x=tape x.length (inputTape M A x) bychange (⟨_,0,M.start⟩ : Config (g+1) q)=⟨_,0,M.start⟩rw [h]rflfunext jcases j with| zero => simp [inputTape,tape,monitor]| succ i =>by_cases h : i<x.length· simp [inputTape,tape,show i+1≤x.length by omega,List.getElem?_eq_getElem h,alphabet]· simp [inputTape,tape,show ¬ i+1≤x.length by omega,List.getElem?_eq_none (show x.length≤i by omega),monitor]theorem ins_eq (M : Ordinary g q) {c : Config g q} {n} (h : Good M c n) :instruction (monitor M) (liftCfg n c)=(instruction M c).map tagIns := bychange (M.delta c.state (eraseTag M.blank (tape n c.tape c.pos))).map _=_by_cases p : c.pos≤n· simp [tape,p,instruction]· simp [tape,p,instruction,h.2.1 c.pos (by omega)]theorem good_step (M : Ordinary g q) {c : Config g q} {n} (h : Good M c n) {i}(e : instruction M c=some i) :Good M (once M c) (max n c.pos) := byhave pos := h.1have p : c.pos ≤ max n c.pos := Nat.le_max_right _ _simp only [once,e,Good]refine ⟨?_,?_,?_⟩· cases i.dir <;> simp [dest] <;> omega· intro j lthave ne : j≠c.pos := by omegasimp [writeAt,ne,h.2.1 j (by omega)]· intro jby_cases eq : j=c.pos· subst j; simpa [writeAt] using (M.keeps _ _ _ e).trans (h.2.2 c.pos)· simp [writeAt,eq,h.2.2]theorem step_eq (M : Ordinary g q) {c : Config g q} {n} (h : Good M c n) {i}(e : instruction M c=some i) :once (monitor M) (liftCfg n c)=liftCfg (max n c.pos) (once M c) := byhave k : writeAt (tape n c.tape) c.pos (ink i.symbol)=tape (max n c.pos) (writeAt c.tape c.pos i.symbol) := byfunext jby_cases eq : j=c.pos· subst j; simp [tape,writeAt,Nat.le_max_right]· have pos := h.1have iff : j≤max n c.pos ↔ j≤n := by omegasimp [writeAt,tape,eq,iff]have s := ins_eq M hrw [e] at schange instruction (monitor M) (liftCfg n c)=some (tagIns i) at srw [once,s]simp only [once,e,liftCfg,tagIns,k]theorem simulates (M : Ordinary g q) (A : Alphabet M) (x : List Bool) (t : Nat) :∃ n, Good M (follow M (inputConfig M A x) t) n ∧follow (monitor M) (inputConfig (monitor M) (alphabet M A) x) t=liftCfg n (follow M (inputConfig M A x) t) := byinduction t with| zero => exact ⟨_,input_good M A x,input_eq M A x⟩| succ t ih =>obtain ⟨n,ok,sim⟩ := ihlet c := follow M (inputConfig M A x) tchange ∃ k, Good M (once M c) k ∧ once (monitor M) _=liftCfg k (once M c)rw [sim]cases e : instruction M c with| none =>have stop := ins_eq M okchange instruction (monitor M) (liftCfg n c)=(instruction M c).map tagIns at stoprw [e] at stopexact ⟨n,by simpa [once,e] using ok,by simp [once,e,stop,c] at *⟩| some i => exact ⟨_,good_step M ok e,step_eq M ok e⟩end P455WriterFrontierend/- Begin Problem455EffectiveMachineRelabel (from finite-semigroup-identity-bases). -/sectionnamespace P455EffectiveRelabelopen P455MachineLocal P455MachineCleanup P455MachineTable P455EffectiveMachineopen P455EffectiveChainstructure Emb (g h : Nat) whereenc : Fin g → Fin hback : Fin h → Fin gundo : ∀ a, back (enc a)=atheorem Emb.inj (e : Emb g h) (a b) : e.enc a=e.enc b ↔ a=b := byconstructor· intro eq; simpa only [e.undo] using congrArg e.back eq· intro eq; rw [eq]def mapped (e : Emb g h) (i : Ins (Fin g) (Fin q)) : Ins (Fin h) (Fin q) :=⟨i.state,e.enc i.symbol,i.dir⟩def expand (M : Ordinary g q) (e : Emb g h) : Ordinary h q wheremarker := e.enc M.markerblank := e.enc M.blankblank_ne := fun equ => M.blank_ne ((e.inj ..).mp equ)start := M.startdelta s x := if x=e.enc (e.back x) then (M.delta s (e.back x)).map (mapped e) else nonekeeps := byintro s x i yessplit at yesnext right =>cases st : M.delta s (e.back x) with| none => simp [st] at yes| some z =>rw [st] at yes; obtain rfl := Option.some.inj yeschange e.enc z.symbol=e.enc M.marker ↔ x=e.enc M.markerexact (e.inj ..).trans ((M.keeps _ _ _ st).trans⟨fun eq => right.trans (congrArg e.enc eq), fun eq =>(e.inj ..).mp (right.symm.trans eq)⟩)next => contradictionleftSafe := byintro s i yessimp only [e.undo,if_true] at yescases st : M.delta s M.marker with| none => simp [st] at yes| some z =>rw [st] at yes; obtain rfl := Option.some.inj yesexact M.leftSafe _ _ stdef alpha (M : Ordinary g q) (A : Alphabet M) (e : Emb g h) : Alphabet (expand M e) wherebit b := e.enc (A.bit b)away b eq := A.away b ((e.inj ..).mp eq)ink b eq := A.ink b ((e.inj ..).mp eq)distinct eq := A.distinct ((e.inj ..).mp eq)def conf (e : Emb g h) (c : Config g q) : Config h q := ⟨fun j => e.enc (c.tape j),c.pos,c.state⟩theorem input_tape (M : Ordinary g q) (A : Alphabet M) (e : Emb g h) (w : List Bool) (j) :inputTape (expand M e) (alpha M A e) w j = e.enc (inputTape M A w j) := bycases j with| zero => rfl| succ j => cases eq : w[j]? <;> simp [inputTape,eq,expand,alpha]theorem exp_instruction (M : Ordinary g q) (e : Emb g h) (c : Config g q) :instruction (expand M e) (conf e c)=(instruction M c).map (mapped e) := bysimp [instruction,expand,conf,e.undo]theorem exp_once (M : Ordinary g q) (e : Emb g h) (c : Config g q) :once (expand M e) (conf e c)=conf e (once M c) := byunfold once; rw [exp_instruction]cases st : instruction M c with| none => rfl| some z =>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) := byfunext j; by_cases eq : j=c.pos <;> simp [conf,writeAt,eq]exact congrArg (fun f => Config.mk f (dest z.dir c.pos) z.state) tapetheorem exp_run (M : Ordinary g q) (A : Alphabet M) (e : Emb g h) (w t) :follow (expand M e) (inputConfig (expand M e) (alpha M A e) w) t=conf e (follow M (inputConfig M A w) t) := byinduction t with| zero =>exact congrArg (fun f => Config.mk f 0 M.start) (funext (input_tape M A e w))| succ t ih => simp only [follow,ih,exp_once]theorem exp_answers (M : Ordinary g q) (A : Alphabet M) (e : Emb g h) {ans w b}(out : Answers M A ans w b) : Answers (expand M e) (alpha M A e) ans w b := byobtain ⟨t,stop,ok⟩ := outrefine ⟨t,?_⟩simp only [exp_run]constructor· rw [exp_instruction,stop]; rfl· exact ok/-- The distinguished four symbols occupy exactly 0 (marker), 1 (blank),2 (false) and 3 (true). Other symbols retain their index at the chosenoffset. This allows two unrelated scratch alphabets to coexist. -/def number (M : Ordinary g q) (A : Alphabet M) (base : Nat) (a : Fin g) :=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.valdef denumber (M : Ordinary g q) (A : Alphabet M) (base y : Nat) :=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 trueelse if h : y-base<g then (⟨y-base,h⟩ : Fin g) else M.blanktheorem number_lt (M : Ordinary g q) (A : Alphabet M) (lo : 4≤base) (hi : base+g ≤ h) (a : Fin g) :number M A base a < h := byhave small := a.isLtunfold numbersplit <;> (first | omega | split <;> (first | omega | split <;> (first | omega | split <;> omega)))theorem denumber_number (M : Ordinary g q) (A : Alphabet M) (lo : 4≤base) (a : Fin g) :denumber M A base (number M A base a)=a := byunfold numbersplitnext eq => simp [denumber,eq]next =>splitnext eq => simp [denumber,eq]next =>splitnext eq => simp [denumber,eq]next =>splitnext eq => simp [denumber,eq]next =>have zero : base+a.val≠0 := by omegahave one : base+a.val≠1 := by omegahave two : base+a.val≠2 := by omegahave three : base+a.val≠3 := by omegasimp [denumber,zero,one,two,three,Nat.add_sub_cancel_left,a.isLt] <;> omegadef common (M : Ordinary g q) (A : Alphabet M) (lo : 4≤base) (hi : base+g≤h) : Emb g h :=⟨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⟩@[simp] theorem mark_number (M : Ordinary g q) (A : Alphabet M) (base) : number M A base M.marker=0 := bysimp [number]@[simp] theorem blank_number (M : Ordinary g q) (A : Alphabet M) (base) : number M A base M.blank=1 := bysimp [number,M.blank_ne]@[simp] theorem bit_number (M : Ordinary g q) (A : Alphabet M) (base) (b : Bool) :number M A base (A.bit b)=if b then 3 else 2 := bycases b <;> simp [number,A.away,A.ink,Ne.symm A.distinct]end P455EffectiveRelabelend/- Begin Problem455SlotProduct (from finite-semigroup-identity-bases). -/sectionnamespace P455SlotProductopen P455Witness P455Paths P455SourceFamilies P455CrossedSupport Problem455.Slotsdef alphabet := List.range 9def templates (r : Nat) := Problem455Finite.wordsUpTo alphabet (9*r)def pairMark (a b : Nat) : Marking := fun x y => x = a ∧ y = bstructure Index (r : Nat) (allow : Tag → Prop) wherenum : Fin (templates r).lengtha : Fin 9b : Fin 9cap : P455Closure.Cap r ((templates r).get num)test : ∃ (s : SlotCertificate) (d : Nat), s.defect = .deficient d ∧s.anchor.owner = a.val ∧ s.anchor.mate = b.val ∧Holds r allow (pairMark a.val b.val) ((templates r).get num) (s.query r)def Index.T (i : Index r allow) := (templates r).get i.numdef Index.R (i : Index r allow) := rules r allow (pairMark i.a i.b)abbrev Carrier (r : Nat) (allow : Tag → Prop) := (i : Index r allow) → P455Quotient.Q i.R i.Tdef evalP (v : Nat → Carrier r allow) (w : W) : Carrier r allow :=fun i => P455Quotient.eval i.R i.cap (fun x => v x i) wdef Identity (r : Nat) (allow : Tag → Prop) (u w : W) :=∀ v : Nat → Carrier r allow, evalP v u = evalP v wtheorem index_injective {i j : Index r allow} (n : i.num = j.num) (a : i.a = j.a)(b : i.b = j.b) : i = j := by cases i; cases j; cases n; cases a; cases b; rfltheorem coordinate_finite (i : Index r allow) (q : P455Quotient.Q i.R i.T) :q ∈ Problem455Finite.carrier i.R i.T := Problem455Finite.carrier_complete ..private theorem remove_count (w : W) (a : Nat) :(w.filter (· != a)).length + w.count a = w.length := byinduction w with| nil => rfl| cons b t ih =>by_cases eq : a = b· subst b; simp [List.count_cons] at ih ⊢; omega· simp [List.count_cons,eq,Ne.symm eq,beq_iff_eq] at ih ⊢; omegatheorem capped_length {r : Nat} (k : Nat) (w : W) (cap : P455Closure.Cap r w)(names : ∀ x ∈ w, x < k) : w.length ≤ k*r := byinduction k generalizing w with| zero => cases w with| nil => simp| cons x xs => exact False.elim (Nat.not_lt_zero _ (names x (by simp)))| succ k ih =>have cp : P455Closure.Cap r (w.filter (· != k)) :=fun x => Nat.le_trans (List.Sublist.count_le x List.filter_sublist) (cap x)have low := ih _ cp (fun x hx => byobtain ⟨mem,p⟩ := List.mem_filter.mp hxhave h := names x memhave e : x ≠ k := by simpa [bne_iff_ne] using pomega)have ct := cap khave tot := remove_count w krw [Nat.succ_mul]; omegadef image (keep : W) (a : Nat) : W := if a ∈ keep then [keep.idxOf a] else []theorem image_word (keep w : W) :w.flatMap (image keep) = (select keep w).map keep.idxOf := byinduction w with| nil => rfl| cons a t ih => by_cases h : a ∈ keep <;> simp [image,select,h,ih, List.flatMap_cons] at */-- A true identity at the finite product specializes simultaneously atthe coordinatewise erasing-and-renaming valuation, even if othercoordinates send some of its one-letter words to zero. -/theorem marked_test {r allow u w} (valid : Identity r allow u w) (keep : W)(i : Index r allow) (eq : (select keep u).map keep.idxOf = i.T) :select [i.a.val,i.b.val] ((select keep u).map keep.idxOf) =select [i.a.val,i.b.val] ((select keep w).map keep.idxOf) := bylet v : Nat → Carrier r allow := fun x j => P455Quotient.ofWord j.R j.T (image keep x)have comp := congrFun (valid v) ichange P455Quotient.eval i.R i.cap _ u = P455Quotient.eval i.R i.cap _ w at comprw [P455Quotient.eval_rep i.R i.cap (fun x => v x i) u (image keep) (fun _ _ => rfl),P455Quotient.eval_rep i.R i.cap (fun x => v x i) w (image keep) (fun _ _ => rfl),image_word,image_word,eq] at comphave good : P455Quotient.Good i.R i.T i.T := ⟨i.T,.refl _,[],[],by simp⟩have path := ((P455Quotient.same_nonzero_class i.R good).mp comp).2rw [eq]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 rflintro z z' mv oldexact old.trans (mv.marked_proj _ _ ⟨rfl,rfl⟩)private theorem tag_map (x y : Nat) (t : Tag) :(t.flatMap P455Closure.phasePair).map (fun b => if b then y else x) = t.flatMap (pair x y) := byinduction t with| nil => rfl| cons b t ih => cases b <;> simp [List.flatMap_cons,P455Closure.phasePair,pair,ih]theorem profile_eq (x y : Nat) (t : Tag) (b : Bool) :P455Closure.Frame.profileWord x y t b = profile x y t b := bycases b <;> simp [P455Closure.Frame.profileWord,P455Closure.Frame.profileBits,P455Closure.fixedPhases,P455Closure.phasePair,profile,profilePrefix,pair,List.replicate_succ,tag_map,List.append_assoc]theorem flip_anchor {r allow u x y} (cap : P455Closure.Cap r u)(flip : ClosedFlip r allow u x y) : ∃ tag bit,Holds r allow (markNode ⟨x,y,tag⟩) u (markedNode ⟨x,y,tag⟩ bit) := byobtain ⟨_,_,_,ne⟩ := flip_counts cap flipobtain ⟨f,b,l,k,hp,hq,ok,rfl⟩ := fliprefine ⟨f.tag,b,ne,by change f.tag.length + 16 = r; have h := ok.1; omega,ok.2.1,.inl ⟨rfl,rfl⟩,?_⟩have h := f.cross_projection ok b l k cap x y (by simp [hp]) (by simp [hq])simpa [select,profile_eq] using hend P455SlotProductend/- Begin Problem455PaddedSnake (from finite-semigroup-identity-bases). -/sectionnamespace P455PaddedMatchingsopen P455PaddedTilesdef rowEnd (w y x : Nat) : Prop := if odd y then x=0 else x+1=wdef Next (w y x v z : Nat) : Prop :=(odd y=false ∧ v=y ∧ z=x+1) ∨(odd y=true ∧ v=y ∧ z+1=x) ∨(v=y+1 ∧ z=x ∧ rowEnd w y x)theorem odd_succ (y : Nat) : odd (y+1)= !odd y := byby_cases e : y%2=1· simp [odd,e,show (y+1)%2≠1 by omega]· simp [odd,e,show (y+1)%2=1 by omega]theorem first_id (w : Nat) : idAt w 0 0=0 := by simp [idAt,odd]theorem end_id {w y x : Nat} (hx : x<w) (endRow : rowEnd w y x) :idAt w y x+1=w*(y+1) := bycases par : odd y <;> simp [rowEnd,par] at endRow <;> simp [idAt,par,Nat.mul_add] <;> omegatheorem down_id {w y x : Nat} (hx : x<w) (endRow : rowEnd w y x) :idAt w (y+1) x=idAt w y x+1 := byrw [end_id hx endRow]cases par : odd y <;> simp [rowEnd,par] at endRow <;> simp [idAt,odd_succ,par] <;> omegatheorem stepping {w h i : Nat} (bound : i+1<w*h) :∃ 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 := byobtain ⟨y,hy,x,hx,eq⟩ := id_covers (show i<w*h by omega)refine ⟨y,hy,x,hx,?_⟩by_cases b : rowEnd w y x· have jy : y+1<h := byby_cases strict : y+1<h· exact strict· have e : y+1=h := by omegahave endPos := end_id hx brw [e,eq] at endPos; omegaexact ⟨y+1,jy,x,hx,eq,(down_id hx b).trans (congrArg (·+1) eq),.inr (.inr ⟨rfl,rfl,b⟩)⟩· cases par : odd y with| false =>simp [rowEnd,par] at brefine ⟨y,hy,x+1,by omega,eq,?_,.inl ⟨par,rfl,rfl⟩⟩simp [idAt,par] at eq ⊢; omega| true =>simp [rowEnd,par] at brefine ⟨y,hy,x-1,by omega,eq,?_,.inr (.inl ⟨par,rfl,by omega⟩)⟩simp [idAt,par] at eq ⊢; omegatheorem last_cell {w h : Nat} (pos : 0<w*h) :∃ y<h, ∃ x<w, y+1=h ∧ rowEnd w y x ∧ idAt w y x=w*h-1 := byhave wy : 0<w := by cases w with | zero => simp at pos | succ => omegahave hy : 0<h := by cases h with | zero => simp at pos | succ => omegalet y := h-1let x := if odd y then 0 else w-1have hx : x<w := by dsimp [x]; split <;> omegahave b : rowEnd w y x := by cases p : odd y <;> simp [rowEnd,x,p] <;> omegahave e : y+1=h := by dsimp [y]; omegahave z := end_id hx brw [e] at zexact ⟨y,by dsimp [y]; omega,x,hx,e,b,by omega⟩def decodeRow (w i : Nat) := i/wdef decodeCol (w i : Nat) := if odd (decodeRow w i) then w-1-(i%w) else i%wtheorem decode_id {w y x : Nat} (hx : x<w) :decodeRow w (idAt w y x)=y ∧ decodeCol w (idAt w y x)=x := byhave wt : 0<w := by omegahave off : (if odd y then w-1-x else x)<w := by split <;> omegahave yr : decodeRow w (idAt w y x)=y := bysimp [decodeRow,idAt,Nat.mul_add_div wt,Nat.div_eq_of_lt off]refine ⟨yr,?_⟩unfold decodeColrw [yr]simp only [idAt,Nat.mul_add_mod,Nat.mod_eq_of_lt off]cases p : odd y <;> simp <;> omegadef tagAt (w : Nat) (tile : Nat→Nat→List Bool) (i : Nat) :=tile (decodeRow w i) (decodeCol w i)theorem tag_id (tile : Nat→Nat→List Bool) {w y x : Nat} (hx : x<w) :tagAt w tile (idAt w y x)=tile y x := by simp [tagAt,(decode_id hx).1,(decode_id hx).2]end P455PaddedMatchingsend/- Begin Problem455PaddedSlots (from finite-semigroup-identity-bases). -/sectionnamespace P455PaddedPortsopen P455RectangleRank Problem455.Slotsdef Covered (w : W) (a k : Nat) := ∃ small : W, small.length≤4 ∧∀ z, occupies w a k z → z∈smallprivate theorem trim {α : Type} (a : α) (t l m : List α) (h : a∉l)(sub : (a::t).Sublist (l++m)) : (a::t).Sublist m := byinduction l with| nil => exact sub| cons z l ih =>cases sub with| cons _ s => exact ih (fun mem=>h (List.mem_cons_of_mem _ mem)) s| cons_cons _ _ => exact (h List.mem_cons_self).elim/-- If the two bounding indexed occurrences are in one literal factor,the occupant occurs in that factor, even if other copies occur elsewhere. -/theorem occupant_in_factor (l m t : W) (a k z : Nat) (start : l.count a≤k)(finish : k+1<l.count a+m.count a) (occ : occupies (l++m++t) a k z) : z∈m := byobtain ⟨j,sub⟩ := occunfold sees at subrw [events_of_factor] at subhave nl : (a,k)∉events l := byintro e; have := (P455ContactGeometry.stamp_range (fun _=>0) l e).2omegahave nt : (a,k+1) ∉ stamp (fun x=>l.count x+m.count x) t := byintro e; have := (P455ContactGeometry.stamp_range (fun x=>l.count x+m.count x) t e).1omegahave rest := trim _ _ _ _ nl subhave back := rest.reversesimp only [List.reverse_append,List.reverse_cons,List.reverse_nil,List.nil_append,List.cons_append,List.singleton_append] at backhave small := (trim _ _ _ _ (by simpa using nt : (a,k+1) ∉ (stamp (fun x=>l.count x+m.count x) t).reverse) back).reversehave mid : [(a,k),(z,j),(a,k+1)].Sublist ((events m).map (shift (fun x=>l.count x))) := by simpa using smallobtain ⟨e,em,ev⟩ := List.mem_map.mp (mid.subset (by simp : (z,j)∈[(a,k),(z,j),(a,k+1)]))have lab := congrArg Prod.fst evchange e.1=z at labrw [←lab]; exact stamped_mem_label (fun _=>0) m e emtheorem private_slot_bound (l t : W) (c a k : Nat) (role : a∈roles c) (lo : l.count a=0)(early : k=0 ∨ k=1) : Covered (l++privateCell c++t) a k := byrefine ⟨roles c,by simp [roles],?_⟩intro z occhave ne : owner c≠mate c := by simp [owner,mate]have count : (privateCell c).count a=3 := byrcases (show a=owner c ∨ a=mate c by simpa [roles] using role) with rfl|rfl <;>simp [privateCell,List.count_cons,ne,Ne.symm ne]have mem := occupant_in_factor l (privateCell c) t a k z (by omega) (by omega) occsimpa [privateCell,roles,or_assoc,or_left_comm,or_comm] using memprivate theorem letters_split (l t : List Block) :letters (l++t)=letters l++letters t := by simp [letters,phase,List.flatMap_append]private theorem block_letters (b : Block) (t : List Block) :letters (b::t)=(cells b).flatMap roles ++ (cells b).flatMap roles ++ letters t := bysimp [letters,phase,List.flatMap_cons,List.flatMap_append,List.append_assoc]private theorem role_from (x a c : Nat) (m : a∈roles c) (same : a∈roles x) : c=x := bysimp only [roles,List.mem_cons,List.not_mem_nil,or_false] at m sameunfold owner mate at m same; omegaprivate theorem index_mem (bs : List Block) (a c : Nat) (role : a∈roles c)(m : a∈letters bs) : c∈bs.flatMap cells := byobtain ⟨x,hx,mx⟩ := List.mem_flatMap.mp mhave eq := role_from _ _ _ role mxrw [eq]obtain ⟨b,hb,inBlock⟩ := List.mem_flatMap.mp hxexact List.mem_flatMap.mpr ⟨b,hb,by simpa using inBlock⟩theorem matching_slot_bound {bs : List Block} (nd : (bs.flatMap cells).Nodup){l t : W} (c a k : Nat) (role : a∈roles c) (present : c∈bs.flatMap cells)(index : l.count a=k) : Covered (l++letters bs++t) a k := byobtain ⟨b,inBs,inBlock⟩ := List.mem_flatMap.mp presentobtain ⟨pre,post,e⟩ := List.append_of_mem inBssubst bssimp only [List.flatMap_append,List.flatMap_cons] at ndhave ds := (List.pairwise_append.mp nd).2.2have noPre : a∉letters pre := byintro hmexact ds c (index_mem pre a c role hm) c (List.mem_append_left _ inBlock) rfllet names := (cells b).flatMap roleshave has : a∈names := List.mem_flatMap.mpr ⟨c,inBlock,role⟩have size : names.length≤4 := by cases b <;> simp [names,cells,roles]have positive := List.count_pos_iff.mpr hashave cut : l++letters (pre++b::post)++t=(l++letters pre)++(names++names)++(letters post++t) := byrw [letters_split,block_letters]; simp [names,List.append_assoc]have left : (l++letters pre).count a=k := by simp [List.count_eq_zero.mpr noPre,index]refine ⟨names,size,?_⟩intro z occrw [cut] at occhave hit := occupant_in_factor (l++letters pre) (names++names) (letters post++t) a k z(by omega) (by simp only [List.count_append] at left ⊢; omega) occsimpa using hitend P455PaddedPortsend/- Begin Problem455WriterSweep (from finite-semigroup-identity-bases). -/sectionnamespace P455WriterSweepopen P455MachineLocal P455MachineTable P455MachineCleanup P455EffectiveMachineopen P455EffectiveChain P455WriterFrontierdef reach (M : Ordinary g q) (c d : Config g q) := ∃ t, follow M c t=dtheorem trans {M : Ordinary g q} {a b c} (h : reach M a b) (k : reach M b c) : reach M a c := byobtain ⟨u,rfl⟩ := h; obtain ⟨v,hv⟩ := kexact ⟨u+v,by rw [follow_add,hv]⟩theorem single {M : Ordinary g q} {c d} (h : once M c=d) : reach M c d := ⟨1,h⟩def cleanSym (M : Ordinary g q) (O : Alphabet M) (read : Fin g → Option Bool)(a : Fin (g+1)) : Fin (g+1) :=if a=ink M.marker then ink M.marker elseif a=fresh g then fresh g else(read (eraseTag M.blank a)).elim (fresh g) (fun b => ink (O.bit b))theorem clean_mark (M : Ordinary g q) (O : Alphabet M) (read) (a) :cleanSym M O read a=ink M.marker ↔ a=ink M.marker := byhave freshNe := Ne.symm (ink_ne_fresh M.marker)by_cases h : a=ink M.marker· simp [cleanSym,h]· simp only [cleanSym,h,↓reduceIte,iff_false]split· exact freshNe· cases read (eraseTag M.blank a) with| none => exact freshNe| some b => exact fun e => O.away b (ink_inj.mp e)def control (M : Ordinary g q) (O : Alphabet M) (read : Fin g→Option Bool)(s : Fin 3) (a : Fin (g+1)) : Option (Ins (Fin (g+1)) (Fin 3)) :=if s=0 thenif a=ink M.marker then some ⟨1,a,.right⟩ else some ⟨0,a,.left⟩else if s=1 thenif a=fresh g then some ⟨2,a,.left⟩ else some ⟨1,cleanSym M O read a,.right⟩else if a=ink M.marker then none else some ⟨2,a,.left⟩def sweep (M : Ordinary g q) (O : Alphabet M) (read : Fin g→Option Bool) : Ordinary (g+1) 3 wheremarker := ink M.markerblank := fresh gblank_ne := Ne.symm (ink_ne_fresh _)start := 0delta := control M O readkeeps := byintro s a i eunfold control at esplit at e <;> split at e· cases e; rfl· cases e; rfl· split at e· cases e; rfl· cases e; exact clean_mark ..· split at e· contradiction· cases e; rflleftSafe := byintro s i esimp only [control,if_pos rfl,ink_ne_fresh,↓reduceIte] at esplit at e· cases e; exact Direction.noConfusion· split at e· cases e; exact Direction.noConfusion· contradictiondef mix (src dst : Nat→Fin k) (p i : Nat) := if i<p then dst i else src itheorem mix_next (src dst : Nat→Fin k) (p) :writeAt (mix src dst p) p (dst p)=mix src dst (p+1) := byfunext i; by_cases e : i=p· subst i; simp [writeAt,mix]· have same : i<p+1 ↔ i<p := by omegasimp [writeAt,mix,e,same]theorem rewind (M : Ordinary g q) (O : Alphabet M) (read) (src : Nat → Fin (g+1))(proper : ∀ j, src j=ink M.marker ↔ j=0) (s : Fin 3) (mode : s=0 ∨ s=2) (p) :reach (sweep M O read) ⟨src,p,s⟩ ⟨src,0,s⟩ := byinduction p with| zero => exact ⟨0,rfl⟩| succ p ih =>apply trans _ ihapply singlehave ne : src (p+1)≠ink M.marker := fun e => Nat.succ_ne_zero p ((proper _).mp e)rcases mode with rfl|rfl <;> simp [once,instruction,sweep,control,ne,write_same,dest]theorem sweep_run (M : Ordinary g q) (O : Alphabet M) (read) (src dst : Nat → Fin (g+1))(n : Nat) (used : ∀ i, i≤n → src i≠fresh g)(tailBlank : ∀ i, n<i → src i=fresh g)(clean : ∀ i, dst i=cleanSym M O read (src i))(p k : Nat) (bound : p+k=n+1) :reach (sweep M O read) ⟨mix src dst p,p,1⟩ ⟨dst,n,2⟩ := byinduction k generalizing p with| zero =>have e : p=n+1 := by omegasubst phave ne := Ne.symm (ink_ne_fresh M.marker)have whole : mix src dst (n+1)=dst := byfunext i; by_cases le : i<n+1· simp [mix,le]· have blank := tailBlank i (by omega)simp [mix,le,clean i,blank,cleanSym,ne]have blank : dst (n+1)=fresh g := byrw [clean,tailBlank _ (by omega)]simp [cleanSym,ne]rw [whole]; apply singlehave stop : instruction (sweep M O read) ⟨dst,n+1,1⟩=some ⟨2,dst (n+1),.left⟩ := bysimp [instruction,sweep,control,blank]rw [once,stop]; simp [write_same,dest]| succ k ih =>have le : p≤n := by omegaapply trans _ (ih (p+1) (by omega))apply singlehave atp : mix src dst p p=src p := by simp [mix]have ins : instruction (sweep M O read) ⟨mix src dst p,p,1⟩=some ⟨1,dst p,.right⟩ := bysimp [instruction,sweep,control,atp,used _ le,clean p]rw [once,ins]simp [mix_next,dest]theorem finish (M : Ordinary g q) (O : Alphabet M) (read) (src : Nat→Fin (g+1)) (p n)(proper : ∀ j, src j=ink M.marker ↔ j=0)(used : ∀ i, i≤n → src i≠fresh g) (tailBlank : ∀ i, n<i → src i=fresh g) :let dst := fun j => cleanSym M O read (src j)reach (sweep M O read) ⟨src,p,0⟩ ⟨dst,0,2⟩ ∧instruction (sweep M O read) ⟨dst,0,2⟩=none := bylet dst := fun j => cleanSym M O read (src j)have mp : ∀ j, dst j=ink M.marker ↔ j=0 := fun j => (clean_mark ..).trans (proper j)have origin := (proper 0).mpr rflhave start : mix src dst 1=src := byfunext i; cases i with| zero => simp [mix,dst,origin,cleanSym]| succ i => simp [mix]constructor· apply trans (rewind M O read src proper 0 (Or.inl rfl) p)have first : reach (sweep M O read) ⟨src,0,0⟩ ⟨mix src dst 1,1,1⟩ := byrw [start]; apply singlehave i : instruction (sweep M O read) ⟨src,0,0⟩=some ⟨1,src 0,.right⟩ := bysimp [instruction,sweep,control,origin]rw [once,i]; simp [dest,write_same]exact trans first (trans (sweep_run M O read src dst n used tailBlank (fun _ => rfl) 1 n (by omega))(rewind M O read dst mp 2 (Or.inr rfl) n))· change control M O read 2 (dst 0)=nonesimp [control,(mp 0).mpr rfl]end P455WriterSweepend/- Begin Problem455EffectiveMachineRelabelChain (from finite-semigroup-identity-bases). -/section/- A single concrete writer suffices for every numerical-table decider,without any requirement tying their work alphabets or bit conventions. -/namespace P455RelabeledChainopen P455MachineLocal P455MachineCleanup P455MachineTable P455EffectiveMachineopen P455EffectiveChain P455EffectiveRelabeldef writerEmb (W : Ordinary g q) (O : Alphabet W) (h : Nat) : Emb g (4+g+h) :=common W O (base:=4) (by decide) (by omega)def readerEmb (g : Nat) (D : Ordinary h r) (B : Alphabet D) : Emb h (4+g+h) :=common D B (base:=4+g) (by omega) (by omega)theorem marker_agrees (W : Ordinary g q) (O : Alphabet W) (D : Ordinary h r) (B : Alphabet D) :(expand W (writerEmb W O h)).marker=(expand D (readerEmb g D B)).marker := byapply Fin.extexact (mark_number W O 4).trans (mark_number D B (4+g)).symmtheorem tapes_agree (W : Ordinary g q) (O : Alphabet W) (D : Ordinary h r) (B : Alphabet D) (w : List Bool) :(fun j => (writerEmb W O h).enc (inputTape W O w j))=inputTape (expand D (readerEmb g D B)) (alpha D B (readerEmb g D B)) w := byfunext j; rw [input_tape]; apply Fin.extcases j with| zero => exact (mark_number W O 4).trans (mark_number D B (4+g)).symm| succ j =>cases eq : w[j]? with| none => simpa only [inputTape,eq,Option.elim_none,writerEmb,readerEmb,common] using(blank_number W O 4).trans (blank_number D B (4+g)).symm| some b => simpa only [inputTape,eq,Option.elim_some,writerEmb,readerEmb,common] using(bit_number W O 4 b).trans (bit_number D B (4+g) b).symmdef combined (W : Ordinary g q) (O : Alphabet W) (D : Ordinary h r) (B : Alphabet D) :Ordinary (4+g+h) (q+r) :=chain (expand W (writerEmb W O h)) (expand D (readerEmb g D B)) (marker_agrees W O D B)def inputs (W : Ordinary g q) (A O : Alphabet W) (D : Ordinary h r) (B : Alphabet D) :Alphabet (combined W O D B) :=P455EffectiveChain.liftAlphabet _ _ _ (alpha W A (writerEmb W O h))theorem expands_delivery (W : Ordinary g q) (A O : Alphabet W) (D : Ordinary h r) (B : Alphabet D) {x y}(writing : Delivers W A x W O y) :Delivers (expand W (writerEmb W O h)) (alpha W A (writerEmb W O h)) x(expand D (readerEmb g D B)) (alpha D B (readerEmb g D B)) y := byobtain ⟨t,stopped,pos,tape⟩ := writingrefine ⟨t,?_⟩simp only [exp_run]constructor· rw [exp_instruction,stopped]; rfl· refine ⟨pos,?_⟩change (fun j => (writerEmb W O h).enc ((follow W (inputConfig W A x) t).tape j))=_rw [tape]; exact tapes_agree W O D B y/-- Physical composition on one one-sided tape. The writer may use twodifferent bit alphabets for input and output. The reader's originalalphabet and final-state convention are unrestricted. The fresh commonalphabet and all transition tables are computed from the two programs. -/theorem answers_combined (W : Ordinary g q) (A O : Alphabet W) (D : Ordinary h r)(B : Alphabet D) (ans : Fin r→Bool) {x y b}(writing : Delivers W A x W O y) (reading : Answers D B ans y b) :Answers (combined W O D B) (inputs W A O D B) (out q ans) x b :=answers_chain _ _ (marker_agrees W O D B) _ _ ans(expands_delivery W A O D B writing) (exp_answers D B (readerEmb g D B) reading)end P455RelabeledChainend/- Begin Problem455SlotSaturation (from finite-semigroup-identity-bases). -/sectionnamespace P455SlotSaturationopen P455Witness P455Paths P455ContactLift P455OriginalWalk P455CrossedSupportopen P455SlotProduct P455SourceFamilies P455SourceTheorem P455MarkedPathopen P455DefectRename Problem455.Slotstheorem uniform_of_identity {r allow mark u w x y} (cap : P455Closure.Cap r u)(valid : Identity r allow u w) (flip : ClosedFlip r allow u x y)(changed : select [x,y] u ≠ select [x,y] w) : UniformSlots r allow mark u x y := byobtain ⟨tag,bit,marked⟩ := flip_anchor cap fliplet n : Node := ⟨x,y,tag⟩intro t near i slot bad occapply Classical.byContradictionintro nehave defic : u.count bad < r := by have := cap bad; omegahave route : ∃ side : Bool, Near r allow mark u (if side then n.mate else n.owner) t 6 := byrcases near with hx | hy· exact ⟨false,hx⟩· exact ⟨true,hy⟩obtain ⟨side,rt⟩ := routeobtain ⟨keep,s,len,ho,hm,sx,sy,_,kind,labels,capT,test⟩ :=canonical_defect cap n bit side t i bad marked rt slot occ deficlet T := (select keep u).map keep.idxOfhave mem : T ∈ templates r := Problem455Finite.covered _ _ _(capped_length 9 T capT labels) (fun a ha => List.mem_range.mpr (labels a ha))obtain ⟨j,eq⟩ := List.get_of_mem memlet a : Fin 9 := ⟨keep.idxOf x, Nat.lt_of_lt_of_le (List.idxOf_lt_length_of_mem ho) len⟩let b : Fin 9 := ⟨keep.idxOf y, Nat.lt_of_lt_of_le (List.idxOf_lt_length_of_mem hm) len⟩have xa : s.anchor.owner = a.val := sxhave yb : s.anchor.mate = b.val := syhave fm : markNode s.anchor = pairMark a b := byunfold markNode pairMarkrw [xa,yb]have tc : Holds r allow (pairMark a b) T (s.query r) := fm ▸ testlet idx : Index r allow := ⟨j,a,b,eq.symm ▸ capT,s, keep.idxOf bad,kind,xa,yb,eq.symm ▸ tc⟩have proj := marked_test valid keep idx eq.symmchange select [keep.idxOf x, keep.idxOf y] _ = select [keep.idxOf x, keep.idxOf y] _ at projrw [← binary_select_map keep u ho hm, ← binary_select_map keep w ho hm] at projhave kept' (word : W) (c : Nat) (hc : c ∈ select [x,y] word) : c ∈ keep := byrcases (by simpa using kept hc : c = x ∨ c = y) with h|h· exact h ▸ ho· exact h ▸ hmhave decoded := congrArg (List.map (decode keep)) projdsimp only [n] at decodedexact changed (by simpa only [decode_map (kept' u),decode_map (kept' w)] using decoded)abbrev noMark : Marking := fun _ _ => Falsetheorem pull_walk {r allow mark u v} (mv : P455Closure.Move r allow noMark u v)(t : Nat) (p : List Step) (w : Walk r allow mark v t p) : Walk r allow mark u t p := byhave w0 : Walk r allow noMark v t p := remark_walk t p wapply remark_walk (mark := noMark) t pclear winduction p generalizing t with| nil => trivial| cons bc tail ih => exact ⟨(query_invariant mv _).mpr w0.1, ih _ w0.2⟩theorem uniform_variant {r allow mark u v x y}(path : P455Quotient.Walk (P455Closure.Move r allow noMark) u v)(uf : UniformSlots r allow mark u x y) : UniformSlots r allow mark v x y := byapply path.transport ufintro w z mv old t near i slot b occhave pull {s} (h : Near r allow mark z s t 6) : Near r allow mark w s t 6 := byobtain ⟨p,wa,ep,len⟩ := hexact ⟨p,pull_walk mv s p wa,ep,len⟩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))theorem crossed_at_variant {r allow mark T} (capT : P455Quotient.Cap r T)(u : W) (capU : P455Closure.Cap r u) (x y : Nat) (flip : ClosedFlip r allow u x y)(u₀ w : W) (cap₀ : P455Closure.Cap r u₀) (identity : Identity r allow u₀ w)(flip₀ : ClosedFlip r allow u₀ x y) (changed : select [x,y] u₀ ≠ select [x,y] w)(path : P455Quotient.Walk (P455Closure.Move r allow noMark) u₀ u)(h : Nat → W) (val : Nat → P455Quotient.Q (rules r allow mark) T)(reps : ∀ a ∈ ruleWord r allow mark u x y, P455Quotient.ofWord (rules r allow mark) T (h a) = val a)(live : P455Quotient.eval (rules r allow mark) capT val (ruleWord r allow mark u x y) ≠P455Quotient.zero (rules r allow mark) T)(ts : Tiles) (c : Certificate) (valid : Holds r allow mark T (c.query r ts))(second mate : Bool) (cross : Crosses (markedRecord c second) h x y) :let names := retained r allow mark u x ylet v := ruleWord r allow mark u x ylet d := donor v h rlet a := startLabel c second mate∃ seed z l k, (seed = x ∨ seed = y) ∧ Supplies v h r seed a ∧P455Quotient.Variant (rules r allow mark) T z ∧ z = l ++ v.flatMap h ++ k ∧Holds r allow mark z (c.query r ts) ∧ SourceEvidence r allow ts v h seed c ∧(Compressed r u → Holds r allow (sourceMarks d c) u ((transferred d c).query r ts)) ∧∀ p : List Step, p.length ≤ 6 → Walk r allow mark z a p →Walk r allow mark u seed (relabel d p) ∧ endpoint seed (relabel d p) = d (endpoint a p) ∧(relabel d p).length = p.length ∧ d (endpoint a p) ∈ names ∧Supplies v h r (d (endpoint a p)) (endpoint a p) ∧ Supplies u h r (d (endpoint a p)) (endpoint a p) :=crossed_gadget capT u capU x y flip(uniform_variant path (uniform_of_identity cap₀ identity flip₀ changed))h val reps live ts c valid second mate crossend P455SlotSaturationend/- Begin Problem455EdgeProduct (from finite-semigroup-identity-bases). -/sectionnamespace P455EdgeProductopen P455Witness P455Paths P455EdgeSource P455EdgeProjection P455PortReflection P455CertificateReachopen P455DefectRename P455SlotProduct Problem455.Slotsopen P455FirstRewrite (Model)abbrev W := List Natdef words (r : Nat) := Problem455Finite.wordsUpTo (List.range 14) (14*r)def marks (a b c d : Nat) (x y : Nat) := (x = a ∧ y = b) ∨ (x = c ∧ y = d)structure Index (r : Nat) (allow : Tag → Prop) (ts : Tiles) wherenum : Fin (words r).lengtha : Fin 14b : Fin 14c : Fin 14d : Fin 14cap : P455Closure.Cap r ((words r).get num)test : ∃ e : EdgeCertificate, e.a.owner = a.val ∧ e.a.mate = b.val ∧e.b.owner = c.val ∧ e.b.mate = d.val ∧(∀ x : Nat, x ∈ (words r).get num ↔ x ∈ names ts e) ∧Holds r allow (marks a b c d) ((words r).get num) (e.query ts)def Index.T (i : Index r allow ts) := (words r).get i.numdef Index.R (i : Index r allow ts) := rules r allow (marks i.a i.b i.c i.d)abbrev Carrier (r : Nat) (allow : Tag → Prop) (ts : Tiles) :=(i : Index r allow ts) → P455Quotient.Q i.R i.Tdef product (r : Nat) (allow : Tag → Prop) (ts : Tiles) : Model (Carrier r allow ts) whereop := fun u v i => P455Quotient.mul i.R i.cap (u i) (v i)unit := fun i => P455Quotient.ofWord i.R i.T []assoc := fun u v w => funext (fun i => P455Quotient.mul_assoc i.R i.cap (u i) (v i) (w i))oneL := fun u => funext (fun i => (P455Quotient.unit_laws i.R i.cap (u i)).1)oneR := fun u => funext (fun i => (P455Quotient.unit_laws i.R i.cap (u i)).2)theorem observed {r allow ts u w} (valid : (product r allow ts).Valid u w)(i : Index r allow ts) (h : Nat → W) :P455Quotient.ofWord i.R i.T (u.flatMap h) = P455Quotient.ofWord i.R i.T (w.flatMap h) := bylet val : Nat → Carrier r allow ts := fun x j => P455Quotient.ofWord j.R j.T (h x)have comp (z : W) : (product r allow ts).eval val z i = P455Quotient.ofWord i.R i.T (z.flatMap h) := byinduction z with| nil => rfl| cons a z ih =>change P455Quotient.mul i.R i.cap (val a i) _ = _rw [ih]; rflexact (comp u).symm.trans ((congrFun (valid val) i).trans (comp w))theorem names_send (f : Nat → Nat) (ts : Tiles) (e : EdgeCertificate) :names ts (sendEdge f e) = (names ts e).map f := bycases rr : ts.right e.a.tag <;> cases dd : ts.bottom e.a.tag <;>cases ll : ts.left e.a.tag <;> cases uu : ts.top e.a.tag <;>simp [names,nodes,candidates,sendEdge,sendNode,roles,rr,dd,ll,uu,List.filter_cons]/-- At either endpoint of a true identity the complete 1,0 edge testforces both marked binary projections to agree with the oppositeword. The opposite word is arbitrary. -/theorem endpoint_observed {r allow mark ts u w} (cap : P455Closure.Cap r u)(valid : (product r allow ts).Valid u w) (e : EdgeCertificate)(ok : Holds r allow mark u (e.query ts)) :select [e.a.owner,e.a.mate] u = select [e.a.owner,e.a.mate] w ∧select [e.b.owner,e.b.mate] u = select [e.b.owner,e.b.mate] w := bylet keep := names ts elet T := template ts e ulet f := keep.idxOfobtain ⟨ct,namesT,cert⟩ := canonical_edge cap ts e okhave hr : 0 < r := by have h : e.a.tag.length + 16 = r := ok.1.2.1; omegahave exactT (x : Nat) : x ∈ T ↔ x ∈ names ts (sendEdge f e) := byrw [names_send]constructor· intro h; obtain ⟨z,hz,rfl⟩ := List.mem_map.mp hexact List.mem_map_of_mem (kept hz)· intro h; obtain ⟨z,hz,rfl⟩ := List.mem_map.mp happly List.mem_map_of_memapply List.count_pos_iff.mpchange 0 < (select keep u).count zrw [P455DefectProjection.select_count keep u z hz,saturated cap ts e ok hz]exact hrhave low (a : Nat) (h : a ∈ keep) : f a < 14 :=Nat.lt_of_lt_of_le (List.idxOf_lt_length_of_mem h) (names_bound ts e)have ao := covered (ts := ts) (e := e) .anchor e.a.owner (by simp [roles])have am := covered (ts := ts) (e := e) .anchor e.a.mate (by simp [roles])have bo := covered (ts := ts) (e := e) .successor e.b.owner (by simp [roles])have bm := covered (ts := ts) (e := e) .successor e.b.mate (by simp [roles])let a : Fin 14 := ⟨_,low _ ao⟩let b : Fin 14 := ⟨_,low _ am⟩let c : Fin 14 := ⟨_,low _ bo⟩let d : Fin 14 := ⟨_,low _ bm⟩have lowT (x : Nat) (h : x ∈ T) := (namesT x h).1obtain ⟨j,eq⟩ := List.get_of_mem (Problem455Finite.covered (List.range 14) _ T(capped_length _ T ct lowT) (fun x h => List.mem_range.mpr (lowT x h)))let i : Index r allow ts := ⟨j,a,b,c,d,eq.symm ▸ ct,sendEdge f e,rfl,rfl,rfl,rfl,eq.symm ▸ exactT,eq.symm ▸ cert⟩have comp := observed valid i (image keep)rw [image_word,image_word] at comphave sameT : T = i.T := eq.symmchange P455Quotient.ofWord i.R i.T T = _ at comprw [sameT] at comphave good : P455Quotient.Good i.R i.T i.T := ⟨_,.refl _,[],[],by simp⟩have path := ((P455Quotient.same_nonzero_class i.R good).mp comp).2have recover (x y : Nat) (hx : x ∈ keep) (hy : y ∈ keep) (markPair : marks a b c d (f x) (f y)) :select [x,y] u = select [x,y] w := byhave pr := path.transport (P := fun z => select [f x,f y] i.T = select [f x,f y] z) rfl(fun mv old => old.trans (mv.marked_proj _ _ markPair))rw [← sameT] at prchange select [keep.idxOf x,keep.idxOf y] ((select keep u).map keep.idxOf) = _ at prrw [← binary_select_map keep u hx hy,← binary_select_map keep w hx hy] at prhave k (z : W) (j : Nat) (mem : j ∈ select [x,y] z) : j ∈ keep := byrcases (by simpa using kept mem : j=x ∨ j=y) with rfl|rfl <;> assumptionsimpa only [decode_map (k u),decode_map (k w)] using congrArg (List.map (decode keep)) prexact ⟨recover _ _ ao am (.inl ⟨rfl,rfl⟩),recover _ _ bo bm (.inr ⟨rfl,rfl⟩)⟩end P455EdgeProductend/- Begin Problem455PaddedWord (from finite-semigroup-identity-bases). -/sectionnamespace P455PaddedWordopen P455PaddedPorts P455PaddedMatchings P455RectangleRankabbrev W := List Natdef matching (h w : Nat) : Nat → List Block| 0 => horizontal h w false| 1 => horizontal h w true| 2 => vertical h w false| 3 => vertical h w true| _+4 => wrap (w*h)def portChunks (h w n : Nat) :=(List.range n).flatMap fun k => letters (matching h w k)def tagPhase (t : Nat) (tag : Nat → List Bool) (k : Nat) :=(List.range t).flatMap (mutableCell fun i => (tag i)[k]?.getD false)def columnCells (h w : Nat) := (List.range h).flatMap fun y => (List.range w).map (idAt w y)def suffix (h w k : Nat) (tag : Nat → List Bool) : W :=(List.range k).flatMap (tagPhase (w*h) tag) ++ (columnCells h w).flatMap rolesdef middle (h w k : Nat) (tag : Nat → List Bool) : W := portChunks h w 5 ++ suffix h w k tagdef tail (t : Nat) : W := (List.range t).flatMap (mutableCell (constant false))theorem matching_unique {h w : Nat} (size : 1<w*h) (k : Nat) :((matching h w k).flatMap cells).Nodup := bycases k with| zero => exact horizontal_unique ..| succ k => cases k with| zero => exact horizontal_unique ..| succ k => cases k with| zero => exact vertical_unique ..| succ k => cases k with| zero => exact vertical_unique ..| succ k => exact wrap_unique sizetheorem matching_cells {h w : Nat} (size : 1<w*h) (k i : Nat) :i∈(matching h w k).flatMap cells ↔ i<w*h := bycases k with| zero => exact horizontal_cells ..| succ k => cases k with| zero => exact horizontal_cells ..| succ k => cases k with| zero => exact vertical_cells ..| succ k => cases k with| zero => exact vertical_cells ..| succ k => exact wrap_cells size itheorem columns_eq (h w : Nat) :columnCells h w=(horizontal h w false).flatMap cells := bychange _ = (lines h w false (idAt w)).flatMap cellssimp [columnCells,lines,List.flatMap_assoc,line_cells]theorem columns_unique (h w : Nat) : (columnCells h w).Nodup := byrw [columns_eq]; exact horizontal_unique ..theorem columns_cells (h w i : Nat) : i∈columnCells h w ↔ i<w*h := byrw [columns_eq]; exact horizontal_cells ..end P455PaddedWordend/- Begin Problem455RetainedVariant (from finite-semigroup-identity-bases). -/section/- Retention is relative to the chosen marked component only throughmark-independent contact observations. Both live orientations useexactly the same literal names and the same numerical gap naming. -/namespace P455RetainedVariantopen P455Witness P455Paths P455CrossedSupport P455SlotSaturation P455Compressionopen Problem455.Slotstheorem near_move {r allow mark u v} (mv : P455Closure.Move r allow noMark u v) (a t J : Nat) :Near r allow mark u a t J ↔ Near r allow mark v a t J := byconstructor· rintro ⟨p,w,e,len⟩; exact ⟨p,pull_walk mv.symm _ _ w,e,len⟩· rintro ⟨p,w,e,len⟩; exact ⟨p,pull_walk mv _ _ w,e,len⟩theorem needed_move {r allow mark u v} (mv : P455Closure.Move r allow noMark u v) (x y b : Nat) :Needed r allow mark u x y b ↔ Needed r allow mark v x y b := byhave ball (t) : InBall r allow mark u x y t ↔ InBall r allow mark v x y t :=or_congr (near_move mv x t 6) (near_move mv y t 6)apply or_congr (ball b)constructor· rintro ⟨t,i,nb,sl,oc⟩; exact ⟨t,i,(ball t).mp nb,sl,(mv.slot_iff t i b sl).mp oc⟩· rintro ⟨t,i,nb,sl,oc⟩; exact ⟨t,i,(ball t).mpr nb,sl,(mv.slot_iff t i b sl).mpr oc⟩theorem same_retained {r allow mark u v} (mv : P455Closure.Move r allow noMark u v) (x y : Nat) :(retained r allow mark u x y).Perm (retained r allow mark v x y) := byclassicalhave perm : u.Perm v := List.perm_iff_count.mpr mv.count_equnfold retainedhave pred : (fun b => decide (Needed r allow mark u x y b)) =(fun b => decide (Needed r allow mark v x y b)) := byfunext b; simp [(needed_move mv x y b : Needed r allow mark u x y b ↔ _)]rw [pred]exact perm.filter _theorem sum_perm {s t : W} (h : s.Perm t) : s.sum = t.sum := byinduction h with| nil => rfl| cons _ _ ih => simp [ih]| swap => simp [List.sum_cons]; omega| trans _ _ ih jh => exact ih.trans jhtheorem pieces_perm (w : W) {s t : W} (perm : s.Perm t) : pieces s w = pieces t w := byinduction w with| nil => rfl| cons a w ih =>by_cases h : a ∈ s· simp [pieces,h,perm.mem_iff.mp h,ih]· have ht : a ∉ t := fun m => h (perm.mem_iff.mpr m)simp [pieces,h,ht,ih]theorem small_congr_names (w : W) {s t : W} (perm : s.Perm t) : small w s = small w t := bysimp only [small,base,sum_perm perm,pieces_perm w perm]theorem retained_remark {r allow mark mark' u x y} :retained r allow mark u x y = retained r allow mark' u x y := byclassicalhave near (a b : Nat) (m m' : Marking) (h : Near r allow m u a b 6) : Near r allow m' u a b 6 := byobtain ⟨p,w,ep,len⟩ := hexact ⟨p,P455SourceFamilies.remark_walk a p w,ep,len⟩have ball (b : Nat) (m m' : Marking) (h : InBall r allow m u x y b) : InBall r allow m' u x y b :=h.imp (near _ _ _ _) (near _ _ _ _)have need (a : Nat) (m m' : Marking) (h : Needed r allow m u x y a) : Needed r allow m' u x y a := byrcases h with h|⟨t,i,h,hi,occ⟩· exact .inl (ball _ _ _ h)· exact .inr ⟨t,i,ball _ _ _ h,hi,occ⟩unfold retainedapply List.filter_congrintro b _simp [show Needed r allow mark u x y b ↔ Needed r allow mark' u x y b from ⟨need _ _ _,need _ _ _⟩]end P455RetainedVariantend/- Begin Problem455ProfileComponent (from finite-semigroup-identity-bases). -/sectionnamespace P455ProfileComponentopen P455Witness P455Closure P455SlotProduct P455SlotSaturation Problem455.Slotsabbrev W := List Nattheorem profile_support (a b : Nat) (tag : Tag) (bit : Bool) {z : Nat}(m : z ∈ profile a b tag bit) : z = a ∨ z = b := byrw [← profile_eq] at mobtain ⟨c,_,rfl⟩ := List.mem_map.mp mcases c <;> simptheorem profile_length (a b : Nat) (tag : Tag) (bit : Bool) :(profile a b tag bit).length = 2 * (tag.length + 16) := bycases bit <;> simp [profile,pair,profile_prefix_length] <;> omegatheorem profile_cap {a b : Nat} (ne : a ≠ b) (tag : Tag) (bit : Bool) :Cap (tag.length + 16) (profile a b tag bit) := byintro xhave tagct (x : Nat) : (tag.flatMap (pair a b)).count x ≤ tag.length := byinduction tag with| nil => simp| cons f tag ih =>cases f <;> by_cases xa : a=x <;> by_cases xb : b=x <;>simp [List.flatMap_cons,pair,List.count_cons,beq_iff_eq,xa,xb,ne,Ne.symm ne] at * <;> omegahave cp := tagct xcases bit <;> by_cases xa : a=x <;> by_cases xb : b=x <;>simp [profile,profilePrefix,pair,List.replicate_succ,List.count_cons,beq_iff_eq,xa,xb,ne,Ne.symm ne] at * <;> omegadef frame (a b : Nat) (tag : Tag) : Frame Nat :=⟨a,[],[],b,tag,(fixedPhases tag).map (fun token => ([],token)),[],[],[]⟩theorem frame_core (a b : Nat) (tag : Tag) (bit : Bool) :(frame a b tag).core bit = profile a b tag bit := byhave md (ls : List Bool) : (ls.map (fun token => (([] : W),token))).flatMap(fun e => e.1 ++ (if e.2 then [b] else [a])) = ls.map (fun k => if k then b else a) := byinduction ls with| nil => rfl| cons c ls ih => cases c <;> simp [List.flatMap_cons, ih] at *rw [← profile_eq]cases bit <;> simp [Frame.core,Frame.early,Frame.mid,Frame.pair,Frame.p,Frame.q,frame,Frame.profileWord,Frame.profileBits,md,phasePair,List.append_assoc]theorem forward {r allow a b tag} (ne : a ≠ b) (length : tag.length+16 = r)(allowed : allow tag) (bit : Bool) :Move r allow noMark (profile a b tag bit) (profile a b tag (!bit)) := bylet f := frame a b taghave cp : Cap r (profile a b tag bit) := length ▸ profile_cap ne tag bithave cf : Cap r ([] ++ f.core bit ++ []) := by simpa [f,frame_core] using cprefine ⟨f,bit,[],[],f.valid_of_capped_shape (by change r = 16+tag.length; omega) allowed(by simp [f,frame,List.map_map,Function.comp_def]) (by simp [f,frame,Frame.p])(by simp [f,frame,Frame.q]) (by simpa [f,frame,Frame.p,Frame.q] using ne)(by simp [noMark]) bit [] [] cf,by simp [f,frame_core],by simp [f,frame_core],cp⟩theorem variants {r allow a b tag} (ne : a ≠ b) (length : tag.length+16 = r)(allowed : allow tag) (bit : Bool) (u : W) :P455Quotient.Variant (rules r allow noMark) (profile a b tag bit) u ↔∃ v : Bool, u = profile a b tag v := byconstructor· intro pathhave supp (x : Nat) (inU : x ∈ u) : x=a ∨ x=b := byhave ct := P455Quotient.count_walk (rules r allow noMark) path xexact profile_support a b tag bit (List.count_pos_iff.mp (ct ▸ List.count_pos_iff.mpr inU))have selfU : select [a,b] u = u := by apply List.filter_eq_self.mpr; simpa using supphave selfT : select [a,b] (profile a b tag bit) = profile a b tag bit := byapply List.filter_eq_self.mprintro x h; simpa using profile_support a b tag bit hhave typed' := path.transport (P := fun z => typed z a b tag) ⟨bit,selfT⟩(fun mv yes => (mv.typed_iff a b tag ne length).mp yes)simpa [typed,selfU] using typed'· rintro ⟨v,rfl⟩cases bit <;> cases v· exact .refl _· exact .snoc (.refl _) (forward ne length allowed false)· exact .snoc (.refl _) (forward ne length allowed true)· exact .refl _theorem factors {r allow a b tag} (ne : a ≠ b) (length : tag.length+16 = r)(allowed : allow tag) (bit : Bool) (u : W) :P455Quotient.Good (rules r allow noMark) (profile a b tag bit) u ↔∃ v : Bool, P455Quotient.Factor u (profile a b tag v) := byconstructor· rintro ⟨w,p,f⟩; obtain ⟨v,rfl⟩ := (variants ne length allowed bit w).mp p; exact ⟨v,f⟩· rintro ⟨v,f⟩; exact ⟨_,(variants ne length allowed bit _).mpr ⟨v,rfl⟩,f⟩theorem move_size {r allow mark} {u v : W} (h : Move r allow mark u v) : 2*r ≤ u.length := byobtain ⟨f,t,l,k,ok,rfl,_,cp⟩ := hhave pr := f.cross_projection ok t l k cp f.pHead f.qLast (by simp [Frame.p]) (by simp [Frame.q])have small := List.length_filter_le (fun a => decide (a=f.pHead ∨ a=f.qLast)) (l ++ f.core t ++ k)rw [pr,profile_eq,profile_length] at smallhave eq := ok.1omegatheorem proper_singleton {r allow a b tag bit u v} (live : P455Quotient.Good (rules r allow noMark)(profile a b tag bit) u) (short : u.length < 2*r) :P455Quotient.ofWord (rules r allow noMark) (profile a b tag bit) u =P455Quotient.ofWord (rules r allow noMark) (profile a b tag bit) v ↔ u=v := byconstructor· intro eqhave path := ((P455Quotient.same_nonzero_class _ live).mp eq).2exact path.transport (P := fun z => u=z) rfl (fun mv e => bysubst_vars; have := move_size mv; omega)· rintro rfl; rfltheorem classes {r allow a b tag} (ne : a ≠ b) (length : tag.length+16 = r)(allowed : allow tag) (bit : Bool) (u v : W) :let R := rules r allow noMarklet T := profile a b tag bitP455Quotient.ofWord R T u = P455Quotient.ofWord R T v ↔ u=v ∨((∃ i : Bool, u = profile a b tag i) ∧ (∃ j : Bool, v = profile a b tag j)) ∨(¬ (∃ i : Bool, P455Quotient.Factor u (profile a b tag i)) ∧¬ (∃ j : Bool, P455Quotient.Factor v (profile a b tag j))) := bylet R := rules r allow noMarklet T := profile a b tag bitchange P455Quotient.ofWord R T u = P455Quotient.ofWord R T v ↔ _constructor· intro eqby_cases valid : P455Quotient.Good R T u· by_cases short : u.length < 2*r· exact .inl ((proper_singleton valid short).mp eq)· obtain ⟨i,L,K,e⟩ := (factors ne length allowed bit u).mp validhave lens := congrArg List.length esimp only [profile_length,length,List.length_append] at lenshave lk : L=[] ∧ K=[] := ⟨List.length_eq_zero_iff.mp (by omega),List.length_eq_zero_iff.mp (by omega)⟩have full : u = profile a b tag i := by simpa [lk.1,lk.2] using e.symmhave path := ((P455Quotient.same_nonzero_class _ valid).mp eq).2rw [full] at pathexact .inr (.inl ⟨⟨i,full⟩,(variants ne length allowed i v).mp path⟩)· have dead : ¬ P455Quotient.Good R T v := byintro g; exact valid (((P455Quotient.same_nonzero_class _ g).mp eq.symm).1)exact .inr (.inr ⟨fun h => valid ((factors ne length allowed bit u).mpr h),fun h => dead ((factors ne length allowed bit v).mpr h)⟩)· rintro (rfl|⟨⟨i,rfl⟩,⟨j,rfl⟩⟩|⟨du,dv⟩)· rfl· have live (b' : Bool) : P455Quotient.Good R T (profile a b tag b') :=(factors ne length allowed bit _).mpr ⟨b',[],[],by simp⟩exact (P455Quotient.same_nonzero_class _ (live i)).mpr⟨live j,(variants ne length allowed i _).mpr ⟨j,rfl⟩⟩· apply Quotient.sound; exact .inl ⟨fun gu => du ((factors ne length allowed bit u).mp gu),fun gv => dv ((factors ne length allowed bit v).mp gv)⟩end P455ProfileComponentend/- Begin Problem455GridRows (from finite-semigroup-identity-bases). -/sectionnamespace P455GridRowsopen P455Witness P455Paths Problem455.Slots/-- Horizontal and vertical compatible tile pairs obey the flags in themachine construction. The bare `Tiles` structure does not impose them. -/structure Laws (ts : Tiles) : Prop wherehoriz : ∀ a b, ts.horizontal a b →ts.right a=false ∧ ts.left b=false ∧ ts.top a=ts.top b ∧ts.bottom a=ts.bottom b ∧ ts.oddRow a=ts.oddRow b ∧ ts.oddColumn b= !ts.oddColumn avert : ∀ a b, ts.vertical a b →ts.bottom a=false ∧ ts.top b=false ∧ ts.left b=ts.left a ∧ts.right b=ts.right a ∧ ts.oddColumn b=ts.oddColumn a ∧ ts.oddRow b= !ts.oddRow adef Arrow (r : Nat) (allow : Tag → Prop) (mark : Marking) (w : W) (ts : Tiles) (e : EdgeCertificate) :=Holds r allow mark w (typedNode e.a) ∧ Holds r allow mark w (typedNode e.b) ∧Holds r allow mark w (localCert ts e) ∧ Holds r allow mark w (chosenSuccessor ts e)def Functional (r : Nat) (allow : Tag → Prop) (mark : Marking) (w : W) (ts : Tiles) (a : Node) :=∀ (d : Dir) (b c : Node), Holds r allow mark w (neighbor ts a b d) →Holds r allow mark w (neighbor ts a c d) → b=cprivate theorem active {r allow mark w q b} (h : Holds r allow mark w (flagQ (!b) q))(off : b=false) : Holds r allow mark w q := by simpa only [off,Bool.not_false,flagQ,if_true] using h/-- The diagonal must be the down-neighbor of the already visited right-handupper cell. No functionality on either of the two proposed lower cells. -/theorem descend_pair {r allow mark w ts} (law : Laws ts) (x y : EdgeCertificate)(hX : Holds r allow mark w (localCert ts x)) (hY : Holds r allow mark w (localCert ts y))(fx : Functional r allow mark w ts x.a) (fy : Functional r allow mark w ts y.a)(edge : Holds r allow mark w (rightward ts x.a y.a)) (nb : ts.bottom x.a.tag=false) :Holds r allow mark w (downward ts x.a x.down) ∧Holds r allow mark w (downward ts y.a y.down) ∧Holds r allow mark w (rightward ts x.down y.down) := byhave lawH := law.horiz _ _ edge.1have nr := lawH.1have ny : ts.bottom y.a.tag=false := lawH.2.2.2.1.symm.trans nbhave square : Holds r allow mark w (downward ts x.right x.diagonal) ∧Holds r allow mark w (rightward ts x.down x.diagonal) := bysimpa [flagQ,nr,nb,Holds] using hX.2.2.2.2.1have toY := fx .right x.right y.a (active hX.1 nr) edgehave downY := active hY.2.2.1 nyhave d : x.diagonal = y.down := fy .down _ _ (toY ▸ square.1) downYexact ⟨active hX.2.2.1 nb,downY,d ▸ square.2⟩theorem enters_down {r allow mark w ts} (e : EdgeCertificate) (arr : Arrow r allow mark w ts e)(endRow : endOfRow ts e.a = true) (notBottom : ts.bottom e.a.tag = false) : e.b = e.down := byhave suc := arr.2.2.2simp only [chosenSuccessor,endRow,notBottom,Bool.and_false,Bool.false_eq_true,if_false,if_true] at sucexact suc.1.symmprivate theorem goes_right {r allow mark w ts} (e : EdgeCertificate) (arr : Arrow r allow mark w ts e)(odd : ts.oddRow e.a.tag=false) (right : ts.right e.a.tag=false) :Holds r allow mark w (rightward ts e.a e.b) := byhave endRow : endOfRow ts e.a = false := by simp [endOfRow,odd,right]have suc := arr.2.2.2simp only [chosenSuccessor,endRow,Bool.false_and,Bool.false_eq_true,if_false,odd] at sucexact suc.1 ▸ active arr.2.2.1.1 rightprivate theorem goes_left {r allow mark w ts} (e : EdgeCertificate) (arr : Arrow r allow mark w ts e)(odd : ts.oddRow e.a.tag=true) (left : ts.left e.a.tag=false) :Holds r allow mark w (rightward ts e.b e.a) := byhave endRow : endOfRow ts e.a = false := by simp [endOfRow,odd,left]have suc := arr.2.2.2simp only [chosenSuccessor,endRow,Bool.false_and,Bool.false_eq_true,if_false,odd,if_true] at sucexact suc.1 ▸ active arr.2.2.1.2.1 left/-- An arbitrary candidate row is forced onto the cycle once its first cellis known to lie there. Induction obtains functionality from the tracebefore identifying its next cell. Width one is n=0. -/theorem trace_row {r allow mark w ts} (law : Laws ts) (atCell : Nat → EdgeCertificate)(arrow : ∀ i, Arrow r allow mark w ts (atCell i))(continuous : ∀ i, (atCell i).b=(atCell (i+1)).a)(functional : ∀ i, Functional r allow mark w ts (atCell i).a)(row : Nat → Node) (n start : Nat) (odd : Bool)(init : (atCell start).a=row 0)(rowOdd : ∀ j, j≤n → ts.oddRow (row j).tag=odd)(links : ∀ j, j<n → Holds r allow mark w(if odd then rightward ts (row (j+1)) (row j) else rightward ts (row j) (row (j+1)))) :∀ j, j≤n → (atCell (start+j)).a=row j := byintro jinduction j with| zero => intro _; exact init| succ j ih =>intro lehave here := ih (by omega)have p : ts.oddRow (atCell (start+j)).a.tag=odd := here ▸ rowOdd j (by omega)have one := links j (by omega)have eq : (atCell (start+j)).b=row (j+1) := bycases odd with| false =>have R : Holds r allow mark w (rightward ts (atCell (start+j)).a (row (j+1))) := here ▸ onehave next := goes_right _ (arrow (start+j)) p (law.horiz _ _ R.1).1exact functional _ .right _ _ next R| true =>have L : Holds r allow mark w (rightward ts (row (j+1)) (atCell (start+j)).a) := here ▸ onehave next := goes_left _ (arrow (start+j)) p (law.horiz _ _ L.1).2.1exact functional _ .left _ _ next Lexact (continuous _).symm.trans eq/-- Positive left-to-right ordering of a nonbottom upper row; its cells aregiven by positions in the trace. This yields the entire lower right chainand its vertical links, even before the new row is known to be on the trace. -/theorem lower_row {r allow mark w ts} (law : Laws ts) (atCell : Nat → EdgeCertificate)(arrow : ∀ i, Arrow r allow mark w ts (atCell i))(functional : ∀ i, Functional r allow mark w ts (atCell i).a)(index : Nat → Nat) (n : Nat)(edges : ∀ j, j<n → Holds r allow mark w (rightward ts (atCell (index j)).a (atCell (index (j+1))).a))(nonbottom : ∀ j, j≤n → ts.bottom (atCell (index j)).a.tag=false) :(∀ j, j≤n → Holds r allow mark w (downward ts (atCell (index j)).a (atCell (index j)).down)) ∧(∀ j, j<n → Holds r allow mark w (rightward ts (atCell (index j)).down (atCell (index (j+1))).down)) := byrefine ⟨fun j hj => active (arrow (index j)).2.2.1.2.2.1 (nonbottom _ hj),?_⟩intro j hjexact (descend_pair law _ _ (arrow _).2.2.1 (arrow _).2.2.1(functional _) (functional _) (edges j hj) (nonbottom j (by omega))).2.2/-- Turn a directed indexed comparison in the actual word into a strictnumerical rank. Every stamped occurrence appears in just one position. -/private theorem idx_lt (a b : Event) (ls : List Event) (nd : ls.Nodup)(sub : [a,b].Sublist ls) : ls.idxOf a < ls.idxOf b := byinduction ls with| nil => cases sub| cons x ls ih =>obtain ⟨fresh,distinct⟩ := List.nodup_cons.mp ndcases sub with| cons _ sub =>have hitA : a ∈ ls := sub.subset (by simp)have hitB : b ∈ ls := sub.subset (by simp)have xa : x ≠ a := fun eq => fresh (eq ▸ hitA)have xb : x ≠ b := fun eq => fresh (eq ▸ hitB)simpa only [List.idxOf_cons,cond_eq_if,beq_iff_eq,if_neg xa,if_neg xb,if_neg (Ne.symm xa),if_neg (Ne.symm xb),Nat.add_lt_add_iff_right] using ih distinct sub| cons_cons _ sub =>have hit : b ∈ ls := sub.subset List.mem_cons_selfhave ab : a ≠ b := fun eq => fresh (eq ▸ hit)simp [List.idxOf_cons,cond_eq_if,beq_iff_eq,ab,Ne.symm ab]def position (w : W) (a : Node) := (events w).idxOf (a.owner,0)def Return (ts : Tiles) (e : EdgeCertificate) :=endOfRow ts e.a && ts.bottom e.a.tagtheorem forward_increases {r allow mark w ts} (e : EdgeCertificate)(arr : Arrow r allow mark w ts e) (forward : Return ts e=false) :position w e.a < position w e.b := byhave h := arr.2.2.2change (endOfRow ts e.a && ts.bottom e.a.tag)=false at forwardsimp only [chosenSuccessor,forward,Bool.false_eq_true,if_false] at hexact idx_lt _ _ _ (stamp_unique _ _) h.2.2/-- On an indefinitely continued trace of genuine arrows (in particular arepeated directed cycle), a return occurs beyond every starting index. -/theorem later_return {r allow mark w ts} (atCell : Nat → EdgeCertificate)(arrow : ∀ i, Arrow r allow mark w ts (atCell i))(continuous : ∀ i, (atCell i).b=(atCell (i+1)).a) (start : Nat) :∃ offset, Return ts (atCell (start+offset))=true := byapply Classical.byContradictionintro nonehave forward (j) : Return ts (atCell (start+j))=false := bycases e : Return ts (atCell (start+j)) with| false => rfl| true => exact (none ⟨j,e⟩).elimhave grows (j) : j ≤ position w (atCell (start+j)).a := byinduction j with| zero => exact Nat.zero_le _| succ j ih =>have inc := forward_increases _ (arrow _) (forward j)rw [continuous] at incexact Nat.lt_of_le_of_lt ih inchave impossible := grows ((events w).length+1)have bound (z : Event) : (events w).idxOf z ≤ (events w).length := byby_cases h : z ∈ events w· exact Nat.le_of_lt (List.idxOf_lt_length_of_mem h)· exact Nat.le_of_eq (List.idxOf_eq_length h)have c := bound ((atCell (start+((events w).length+1))).a.owner,0)unfold position at impossibleomegatheorem return_target {r allow mark w ts} (e : EdgeCertificate) (arr : Arrow r allow mark w ts e)(back : Return ts e=true) :ts.top e.b.tag=true ∧ ts.left e.b.tag=true ∧ ts.oddRow e.b.tag=false ∧ ts.oddColumn e.b.tag=false := byhave h := arr.2.2.2change (endOfRow ts e.a && ts.bottom e.a.tag)=true at backsimp only [chosenSuccessor,back,if_true] at hsimpa [and_assoc,P455Witness.Holds] using h.1/-- Column reached after j snake steps in a row with last column n. -/def column (n : Nat) (odd : Bool) (j : Nat) := if odd then n-j else j/-- Descend from the traveled end of a nonbottom row, reverse direction, andidentify each prospective cell in the lower row with its actual traceindex. Only the old row is initially known to be on the trace. -/theorem advance_row {r allow mark w ts} (law : Laws ts) (atCell : Nat → EdgeCertificate)(arrow : ∀ i, Arrow r allow mark w ts (atCell i))(continuous : ∀ i, (atCell i).b=(atCell (i+1)).a)(functional : ∀ i, Functional r allow mark w ts (atCell i).a)(index : Nat → Nat) (n : Nat) (odd : Bool)(edges : ∀ j, j<n → Holds r allow mark w (rightward ts (atCell (index j)).a (atCell (index (j+1))).a))(nonbottom : ∀ j, j≤n → ts.bottom (atCell (index j)).a.tag=false)(parity : ∀ j, j≤n → ts.oddRow (atCell (index j)).a.tag=odd)(left : ts.left (atCell (index 0)).a.tag=true) (right : ts.right (atCell (index n)).a.tag=true) :let last := column n (!odd) 0let start := index last+1∀ j, j≤n → (atCell (start+column n (!odd) j)).a=(atCell (index j)).down := bylet last := column n (!odd) 0let start := index last+1let row (j : Nat) := (atCell (index (column n (!odd) j))).downhave lastBound : last≤n := by cases odd <;> simp [last,column]have ending : endOfRow ts (atCell (index last)).a=true := byrw [endOfRow,parity last lastBound]cases odd <;> simp_all only [last,column,Bool.not_false,Bool.not_true,if_true,Bool.false_eq_true,if_false,Nat.sub_zero]obtain ⟨v,h⟩ := lower_row law atCell arrow functional index n edges nonbottomhave init : (atCell start).a=row 0 :=(continuous _).symm.trans (enters_down _ (arrow _) ending (nonbottom _ lastBound))have rowOdd (j) (le : j≤n) : ts.oddRow (row j).tag= !odd := byhave c : column n (!odd) j ≤ n := by cases odd <;> simp [column,le,Nat.sub_le]exact (law.vert _ _ (v _ c).1).2.2.2.2.2.trans (congrArg Bool.not (parity _ c))have adjacent (j) (le : j<n) : Holds r allow mark w(if !odd then rightward ts (row (j+1)) (row j) else rightward ts (row j) (row (j+1))) := bycases odd with| true => exact h j le| false =>have u := h (n-(j+1)) (by omega)have ix : n-(j+1)+1=n-j := by omegasimpa only [row,column,Bool.not_false,if_true,ix] using uhave trace := trace_row law atCell arrow continuous functional row n start (!odd) init rowOdd adjacentdsimp onlyintro j lehave c : column n (!odd) j ≤ n := by cases odd <;> simp [column,le,Nat.sub_le]have twice : column n (!odd) (column n (!odd) j)=j := by cases odd <;> simp [column] <;> omegasimpa only [row,twice,start,last] using trace (column n (!odd) j) cend P455GridRowsend/- Begin Problem455CatalogueBounds (from finite-semigroup-identity-bases). -/section/- Exact finite witness search for the two-mark catalogue. Syntacticallyunused fields are unbounded in the Lean index. Every successfulwitness has a representative using only occurring names and admittedtags, even when nodes and labels alias. -/namespace P455CatalogueBoundsopen P455Witness P455Paths P455CertificateReach P455EdgeProjection Problem455.Slotsabbrev W := List Natdef canonical (ts : Tiles) (e : EdgeCertificate) : EdgeCertificate :=⟨e.a,e.b,if ts.right e.a.tag then e.a else e.right,if ts.left e.a.tag then e.a else e.left,if ts.bottom e.a.tag then e.a else e.down,if ts.top e.a.tag then e.a else e.up,if ts.right e.a.tag || ts.bottom e.a.tag then e.a else e.diagonal⟩theorem query_canonical (ts : Tiles) (e : EdgeCertificate) :(canonical ts e).query ts = e.query ts := bycases rr : ts.right e.a.tag <;> cases ll : ts.left e.a.tag <;>cases dd : ts.bottom e.a.tag <;> cases uu : ts.top e.a.tag <;> cases oo : ts.oddRow e.a.tag <;>simp [canonical,EdgeCertificate.query,localCert,chosenSuccessor,endOfRow,flagQ,rr,ll,dd,uu,oo]theorem names_canonical (ts : Tiles) (e : EdgeCertificate) : names ts (canonical ts e)=names ts e := bycases rr : ts.right e.a.tag <;> cases ll : ts.left e.a.tag <;>cases dd : ts.bottom e.a.tag <;> cases uu : ts.top e.a.tag <;>simp [canonical,names,nodes,candidates,rr,ll,dd,uu,List.filter_cons]def fields (e : EdgeCertificate) := [e.a,e.b,e.right,e.left,e.down,e.up,e.diagonal]theorem original_active (ts : Tiles) (e : EdgeCertificate) {a : Node}(h : a∈fields (canonical ts e)) : Active ts e a := bysimp only [fields,canonical,List.mem_cons,List.not_mem_nil,or_false] at hrcases h with eq|eq|eq|eq|eq|eq|eq <;> rw [eq]· exact .anchor· exact .successor· cases f : ts.right e.a.tag <;> simp only [f,Bool.false_eq_true,if_false,if_true]· exact .right f· exact .anchor· cases f : ts.left e.a.tag <;> simp only [f,Bool.false_eq_true,if_false,if_true]· exact .left f· exact .anchor· cases f : ts.bottom e.a.tag <;> simp only [f,Bool.false_eq_true,if_false,if_true]· exact .down f· exact .anchor· cases f : ts.top e.a.tag <;> simp only [f,Bool.false_eq_true,if_false,if_true]· exact .up f· exact .anchor· cases rr : ts.right e.a.tag <;> cases dd : ts.bottom e.a.tag <;>simp only [rr,dd,Bool.or_false,Bool.or_true,Bool.false_eq_true,if_false,if_true]· exact .diagonal rr ddall_goals exact .anchordef pool (w : W) (tags : List Tag) := w.flatMap (fun x => w.flatMap (fun y => tags.map (Node.mk x y)))theorem record_in_pool {r allow mark w} (tags : List Tag) (finiteTags : ∀ t,allow t → t ∈ tags)(node : Node) (valid : Holds r allow mark w (typedNode node)) : node ∈ pool w tags := byobtain ⟨_,_,yes,bit,pr⟩ := validhave mem (z : Nat) (side : z=node.owner ∨ z=node.mate) : z∈w := byhave m : z ∈ select [node.owner,node.mate] w := byrw [pr]; rcases side with rfl|rfl <;> simp [profile,profilePrefix]exact (List.mem_filter.mp m).1exact List.mem_flatMap.mpr ⟨node.owner,mem _ (.inl rfl),List.mem_flatMap.mpr⟨node.mate,mem _ (.inr rfl),List.mem_map.mpr ⟨node.tag,finiteTags _ yes,rfl⟩⟩⟩/-- The exact name-set side condition and both marked name-pairs arekept. Arbitrary unused original nodes need not be encoded or bounded. -/theorem bounded_edge {r allow mark ts w} (cap : P455Closure.Cap r w)(tags : List Tag) (finiteTags : ∀ t,allow t → t∈tags) (e : EdgeCertificate)(read : Holds r allow mark w (e.query ts)) :∃ c : EdgeCertificate, c.a=e.a ∧ c.b=e.b ∧ names ts c=names ts e ∧Holds r allow mark w (c.query ts) ∧ ∀ n ∈ fields c, n ∈ pool w tags := byexact ⟨canonical ts e,rfl,rfl,names_canonical ..,(query_canonical ts e) ▸ read,fun n mem => record_in_pool tags finiteTags n (active_owner cap ts e read (original_active ts e mem)).2⟩/-- A catalogue position and its literal template are interchangeable forduplicate-free finite alphabets, including all five alphabets used bythe concrete model. Distinct isomorphic templates remain separate. -/theorem words_nodup {α : Type} (alphabet : List α) (nd : alphabet.Nodup) (bound : Nat) :(Problem455Finite.wordsUpTo alphabet bound).Nodup := byinduction bound with| zero => simp [Problem455Finite.wordsUpTo]| succ n ih =>apply List.nodup_cons.mprconstructor· simp [List.mem_flatMap]· apply List.pairwise_flatMap.mprconstructor· intro a _exact ih.map (fun _ _ eq => (List.cons.inj eq).2)· apply nd.impintro a b ab x hx y hy sameobtain ⟨u,_,rfl⟩ := List.mem_map.mp hxobtain ⟨v,_,rfl⟩ := List.mem_map.mp hyexact ab (List.cons.inj same).1theorem bounded_functionality {r allow ts mark w} (tags : List Tag)(finiteTags : ∀ t,allow t → t∈tags) (f : FunctionalityCertificate)(ok : Holds r allow mark w (f.query ts)) :f.anchor ∈ pool w tags ∧ f.b ∈ pool w tags ∧ f.c ∈ pool w tags := byexact ⟨record_in_pool tags finiteTags _ (marked_typed ok.1),record_in_pool tags finiteTags _ (neighbor_target_record ok.2.1),record_in_pool tags finiteTags _ (neighbor_target_record ok.2.2.1)⟩end P455CatalogueBoundsend/- Begin Problem455PaddedCounts (from finite-semigroup-identity-bases). -/sectionnamespace P455PaddedWordopen P455PaddedMatchings P455PaddedPorts P455RectangleRank Problem455.Slotsprivate theorem cell_role {i a : Nat} (h : a∈roles i) : a=owner i ∨ a=mate i := by simpa [roles] using htheorem absent_other {i j a : Nat} (r : a∈roles i) (different : i≠j) : a∉roles j := byintro m; have p := cell_role r; have q := cell_role m; unfold owner mate at p q; omegaprivate theorem range_count (i t : Nat) : (List.range t).count i=(if i<t then 1 else 0) := byby_cases h : i<t· simp [h,count_one List.nodup_range (List.mem_range.mpr h)]· simp [h,List.count_eq_zero.mpr (fun m=>h (List.mem_range.mp m))]private theorem weighted (f : Nat→List Nat) (i a v : Nat) (s : List Nat)(w : ∀ j,(f j).count a=(if j=i then v else 0)) : (s.flatMap f).count a=v*s.count i := byinduction s with| nil => simp| cons j s ih =>by_cases e : j=i· subst j; simp [List.flatMap_cons,List.count_append,w,ih,List.count_cons,Nat.mul_add,Nat.add_comm]· simp [List.flatMap_cons,List.count_append,w,ih,List.count_cons,e,Ne.symm e]theorem private_counts (i a : Nat) (role : a∈roles i) (t : Nat) :((List.range t).flatMap privateCell).count a=if i<t then 3 else 0 := byhave ne : owner i≠mate i := by unfold owner mate; omegahave ct (j : Nat) : (privateCell j).count a=if j=i then 3 else 0 := byby_cases e : j=i· subst j; rcases cell_role role with rfl|rfl <;> simp [privateCell,List.count_cons,ne,Ne.symm ne]· have no := absent_other role (Ne.symm e)have no' : a∉privateCell j := by simpa [roles,privateCell,or_assoc,or_left_comm,or_comm] using nosimp [List.count_eq_zero.mpr no',e]rw [weighted _ _ _ _ _ ct,range_count]; split <;> simptheorem mutable_counts (i a : Nat) (role : a∈roles i) (bits : Nat→Bool) (t : Nat) :((List.range t).flatMap (mutableCell bits)).count a=if i<t then 1 else 0 := byhave ne : owner i≠mate i := by unfold owner mate; omegahave ct (j : Nat) : (mutableCell bits j).count a=if j=i then 1 else 0 := byby_cases e : j=i· subst j; rcases cell_role role with rfl|rfl <;> cases b : bits i <;> simp [mutableCell,b,List.count_cons,ne,Ne.symm ne]· have no := absent_other role (Ne.symm e)have no' : a∉mutableCell bits j := by cases b : bits j <;> simpa [roles,mutableCell,b,or_comm] using nosimp [List.count_eq_zero.mpr no',e]rw [weighted _ _ _ _ _ ct,range_count,Nat.one_mul]theorem port_count {h w : Nat} (size : 1<w*h) (q i a : Nat) (role : a∈roles i) :(letters (matching h w q)).count a=if i<w*h then 2 else 0 := byrw [letters,count_role _ i a (cell_role role),count_phase]by_cases e : i<w*h· simp [e,count_one (matching_unique size q) ((matching_cells size q i).mpr e)]· simp [e,List.count_eq_zero.mpr (fun m=> e ((matching_cells size q i).mp m))]private theorem select_roles (s : List Nat) (i : Nat) :select (roles i) (s.flatMap roles)=(List.replicate (s.count i) (roles i)).flatten := byinduction s with| nil => rfl| cons a s ih =>rw [List.flatMap_cons,select_append,ih]by_cases e : a=i· subst a; simp [roles,select,List.count_cons,List.replicate_succ]· have no := select_nil (roles i) (roles a) (fun _ h => absent_other h e)simp [no,List.count_cons,e,Ne.symm e]theorem match_projection {h w : Nat} (size : 1<w*h) (q i : Nat) (lt : i<w*h) :select (roles i) (letters (matching h w q))=roles i++roles i := byrw [letters,select_roles,count_phase,count_one (matching_unique size q) ((matching_cells size q i).mpr lt)]simpprivate theorem count_uniform (xs : List Nat) (a v : Nat) (f : Nat→List Nat)(each : ∀ j∈xs,(f j).count a=v) : (xs.flatMap f).count a=xs.length*v := byinduction xs with| nil => simp| cons j t ih =>simp [List.flatMap_cons,List.count_append,each j List.mem_cons_self,ih (fun x hx=>each x (List.mem_cons_of_mem _ hx)),Nat.add_mul,Nat.add_comm]theorem chunks_count {h w : Nat} (size : 1<w*h) (q i a : Nat) (role : a∈roles i) :(portChunks h w q).count a=q*(if i<w*h then 2 else 0) := byunfold portChunksrw [count_uniform _ _ _ _ (fun j _ => port_count size j i a role),List.length_range]theorem suffix_count {h w k : Nat} (tag : Nat→List Bool) (i a : Nat) (role : a∈roles i) :(suffix h w k tag).count a=if i<w*h then k+1 else 0 := byunfold suffixhave ct (j : Nat) : (tagPhase (w*h) tag j).count a = if i<w*h then 1 else 0 := mutable_counts i a role _ _rw [List.count_append,count_uniform (List.range k) a _ (tagPhase (w*h) tag) (fun j _ => ct j),List.length_range,count_role _ i a (cell_role role)]by_cases e : i<w*h· simp [e,count_one (columns_unique h w) ((columns_cells h w i).mpr e)]· simp [e,List.count_eq_zero.mpr (fun m=> e ((columns_cells h w i).mp m))]theorem word_count {h w k : Nat} (size : 1<w*h) (tag : Nat→List Bool) (bits : Nat→Bool)(i a : Nat) (role : a∈roles i) :(word (w*h) (middle h w k tag) (tail (w*h)) bits).count a=if i<w*h then k+16 else 0 := bysimp only [word,middle,tail,List.count_append,private_counts i a role,chunks_count size 5 i a role,suffix_count tag i a role,mutable_counts i a role]split <;> omegatheorem capped {h w k : Nat} (size : 1<w*h) (tag : Nat→List Bool) (bits : Nat→Bool) :P455Quotient.Cap (k+16) (word (w*h) (middle h w k tag) (tail (w*h)) bits) := byintro ahave role : a∈roles (a/2) := by simp only [roles,List.mem_cons,List.not_mem_nil,or_false,owner,mate]; omegarw [word_count size tag bits _ a role]split <;> omegaend P455PaddedWordend/- Begin Problem455SingletonEvaluation (from finite-semigroup-identity-bases). -/sectionnamespace P455SingletonEvaluationopen P455Witness P455ContactLift P455CrossedSupport P455SourceFamilies P455SourceTheoremopen P455MarkedPath P455SlotSaturation P455SlotProduct P455RetainedVariant P455Compressionopen P455Uncrossed P455PortReflection P455EdgeSource Problem455.Slotsabbrev W := List Natdef Matches (n : Node) (x y : Nat) :=(n.owner = x ∧ n.mate = y) ∨ (n.owner = y ∧ n.mate = x)def MarksOnly (mark : Marking) (c : Certificate) :=∀ a b, mark a b → ∃ s : Bool, Matches (markedRecord c s) a btheorem designated_marks (c : Certificate) : MarksOnly (sourceMarks id c) c := byintro a b hitcases c with| slot s => exact ⟨false,.inl ⟨hit.1.symm,hit.2.symm⟩⟩| functionality f => exact ⟨false,.inl ⟨hit.1.symm,hit.2.symm⟩⟩| edge e =>rcases hit with h|h· exact ⟨false,.inl ⟨h.1.symm,h.2.symm⟩⟩· exact ⟨true,.inl ⟨h.1.symm,h.2.symm⟩⟩theorem pick_cross {c h mark x y} (only : MarksOnly mark c)(hit : ∃ a ∈ h x, ∃ b ∈ h y, mark a b ∨ mark b a) :∃ s, Crosses (markedRecord c s) h x y := byobtain ⟨a,ax,b,by',ab|ba⟩ := hit· obtain ⟨s,⟨p,q⟩|⟨p,q⟩⟩ := only a b ab· exact ⟨s,.inl ⟨p ▸ ax,q ▸ by'⟩⟩· exact ⟨s,.inr ⟨p ▸ by',q ▸ ax⟩⟩· obtain ⟨s,⟨p,q⟩|⟨p,q⟩⟩ := only b a ba· exact ⟨s,.inr ⟨p ▸ by',q ▸ ax⟩⟩· exact ⟨s,.inl ⟨p ▸ ax,q ▸ by'⟩⟩def Violation (r : Nat) (allow : Tag → Prop) (ts : Tiles) (w : W) (x y : Nat) :=∃ (c : Certificate) (s : Bool), Matches (markedRecord c s) x y ∧Holds r allow (sourceMarks id c) w (c.query r ts)theorem changed_anchor (c : Certificate) (s : Bool) (d : Nat → Nat) :markedRecord (transferred d c) s = sendNode d (markedRecord c s) := bycases c <;> cases s <;> rfltheorem reindexed_marks (c : Certificate) (d : Nat → Nat) :sourceMarks id (transferred d c) = sourceMarks d c := by cases c <;> rfltheorem compare_uniform {r allow mark T} (capT : P455Quotient.Cap r T)(ts : Tiles) (c : Certificate) (only : MarksOnly mark c)(tester : Holds r allow mark T (c.query r ts))(f : P455Closure.Frame Nat) (l k : W) (x y : Nat) (hp : f.p = [x]) (hq : f.q = [y])(fv : f.Valid r allow noMark) (capF : P455Closure.Cap r (side f l k false))(u₀ : W) (uf : UniformSlots r allow mark u₀ x y)(path : P455Quotient.Walk (P455Closure.Move r allow noMark) u₀ (side f l k false))(cmp : Compressed r (side f l k false))(val : Nat → P455Quotient.Q (rules r allow mark) T)(diff : P455Quotient.eval (rules r allow mark) capT val (ruleWord r allow noMark (side f l k false) x y) ≠P455Quotient.eval (rules r allow mark) capT val (ruleWord r allow noMark (side f l k true) x y)) :∃ b : Bool, Violation r allow ts (side f l k b) x y := bylet u := side f l klet R := rules r allow marklet names := retained r allow noMark (u false) x yhave mv : P455Closure.Move r allow noMark (u false) (u true) := ⟨f,false,l,k,fv,rfl,rfl,capF⟩have cbit (b : Bool) : P455Closure.Cap r (u b) := by cases b; exact capF; exact mv.cap_righthave fc (b : Bool) : ClosedFlip r allow (u b) x y := ⟨f,b,l,k,hp,hq,fv,rfl⟩obtain ⟨hr,cx,cy,_⟩ := flip_counts capF (fc false)have hi : 0 < r := by omegahave hx : x ∈ names := mem_retained.mpr ⟨List.count_pos_iff.mp (cx.symm ▸ hi),.inl (.inl (P455Paths.near_self ..))⟩have hy : y ∈ names := mem_retained.mpr ⟨List.count_pos_iff.mp (cy.symm ▸ hi),.inl (.inr (P455Paths.near_self ..))⟩obtain ⟨g,L,K,gp,gq,gv,both,_⟩ := P455CompressedFrame.canonical_pair f l k names hx hy hp hq fv false capFhave perm (b : Bool) : names.Perm (retained r allow noMark (u b) x y) := bycases b· exact List.Perm.refl _· exact same_retained mv x yhave eq0 (b : Bool) : ruleWord r allow noMark (u b) x y = side g L K b :=(small_congr_names _ (perm b).symm).trans (both b)have eqm (b : Bool) : ruleWord r allow mark (u b) x y = side g L K b := byunfold ruleWord; rw [retained_remark (mark' := noMark)]; exact eq0 bhave neq : P455Quotient.eval R capT val (side g L K false) ≠ P455Quotient.eval R capT val (side g L K true) := byrw [← eq0,← eq0]; exact diffobtain ⟨b,live,⟨h,represent⟩,_⟩ := difference_live_representatives capT g L K val neqhave reps := fun a ha => (represent a ha).2have nd : P455Quotient.eval R capT val (side g L K b) ≠ P455Quotient.eval R capT val (side g L K (!b)) := bycases b· exact neq· exact Ne.symm neqobtain ⟨s,cs⟩ := pick_cross only (difference_crosses capT g L K b x y gp gq gv val h reps nd)let v := ruleWord r allow mark (u b) x yhave repv : ∀ a ∈ v, P455Quotient.ofWord R T (h a) = val a := by rw [show v = _ from eqm b]; exact repshave livev : P455Quotient.eval R capT val v ≠ P455Quotient.zero R T := by rw [show v = _ from eqm b]; exact livehave pb : P455Quotient.Walk (P455Closure.Move r allow noMark) u₀ (u b) := bycases b; exact path; exact .snoc path mvhave cb : Compressed r (u b) := bycases b· exact cmp· intro a z linkexact cmp a z ((Problem455BlockBridge.move_link mv a z).mpr link)obtain ⟨_,_,_,_,_,_,_,_,_,_,read,_⟩ := crossed_gadget capT (u b) (cbit b) x y (fc b)(uniform_variant pb uf) h val repv livev ts c tester s false cslet names' := retained r allow mark (u b) x yobtain ⟨_,ax,ay,_⟩ := flip_counts (cbit b) (fc b)have eqNames : names.Perm names' := bychange names.Perm (retained r allow mark (u b) x y)rw [retained_remark (mark' := noMark)]; exact perm bhave xcnt : v.count x = r := (counts_retained _ _ _ (eqNames.mem_iff.mp hx)).trans axhave ycnt : v.count y = r := (counts_retained _ _ _ (eqNames.mem_iff.mp hy)).trans ayhave ev := P455Quotient.eval_rep R capT val v h repvhave good := (P455Quotient.nonzero_iff R).mp (ev ▸ livev)have cap := P455Quotient.good_cap R capT goodlet d := donor v h rrefine ⟨b,transferred d c,s,?_,?_⟩· rw [changed_anchor]rcases cs with ⟨o,m⟩|⟨o,m⟩· exact .inl ⟨donor_eq hi cap ⟨xcnt,o⟩,donor_eq hi cap ⟨ycnt,m⟩⟩· exact .inr ⟨donor_eq hi cap ⟨ycnt,o⟩,donor_eq hi cap ⟨xcnt,m⟩⟩· rw [reindexed_marks]; exact read cbtheorem compare {r allow mark T} (capT : P455Quotient.Cap r T)(ts : Tiles) (c : Certificate) (only : MarksOnly mark c)(tester : Holds r allow mark T (c.query r ts))(f : P455Closure.Frame Nat) (l k : W) (x y : Nat) (hp : f.p = [x]) (hq : f.q = [y])(fv : f.Valid r allow noMark) (capF : P455Closure.Cap r (side f l k false))(u₀ w : W) (cap₀ : P455Closure.Cap r u₀) (identity : Identity r allow u₀ w)(flip₀ : ClosedFlip r allow u₀ x y) (changed : select [x,y] u₀ ≠ select [x,y] w)(path : P455Quotient.Walk (P455Closure.Move r allow noMark) u₀ (side f l k false))(cmp : Compressed r (side f l k false))(val : Nat → P455Quotient.Q (rules r allow mark) T)(diff : P455Quotient.eval (rules r allow mark) capT val (ruleWord r allow noMark (side f l k false) x y) ≠P455Quotient.eval (rules r allow mark) capT val (ruleWord r allow noMark (side f l k true) x y)) :∃ b : Bool, Violation r allow ts (side f l k b) x y :=compare_uniform capT ts c only tester f l k x y hp hq fv capF u₀(uniform_of_identity cap₀ identity flip₀ changed) path cmp val diffend P455SingletonEvaluationend/- Begin Problem455GridAssembly (from finite-semigroup-identity-bases). -/sectionnamespace P455GridAssemblyopen P455GridRows P455Witness Problem455.Slotsabbrev W := List Natstructure Rectangle (allow : Tag → Prop) (ts : Tiles) whereheight : Natwidth : Nattile : Nat → Nat → Tagallowed : ∀ i j, i ≤ height → j ≤ width → allow (tile i j)horiz : ∀ i j, i ≤ height → j < width → ts.horizontal (tile i j) (tile i (j+1))vert : ∀ i j, i < height → j ≤ width → ts.vertical (tile i j) (tile (i+1) j)left : ∀ i j, i ≤ height → j ≤ width → (ts.left (tile i j) = true ↔ j=0)right : ∀ i j, i ≤ height → j ≤ width → (ts.right (tile i j) = true ↔ j=width)top : ∀ i j, i ≤ height → j ≤ width → (ts.top (tile i j) = true ↔ i=0)bottom : ∀ i j, i ≤ height → j ≤ width → (ts.bottom (tile i j) = true ↔ i=height)structure Row {r : Nat} {allow : Tag → Prop} {mark : Marking} {w : W} (ts : Tiles)(c : Nat → EdgeCertificate) (s n : Nat) (odd : Bool) : Prop whereparity : ∀ j, j≤n → ts.oddRow (c (s+column n odd j)).a.tag=oddleft : ts.left (c (s+column n odd 0)).a.tag=trueright : ts.right (c (s+column n odd n)).a.tag=truelinks : ∀ j, j<n → Holds r allow mark w(rightward ts (c (s+column n odd j)).a (c (s+column n odd (j+1))).a)private theorem min_bounded (p : Nat → Prop) (j : Nat) (yes : p j) :∃ a, p a ∧ ∀ b, b<a → ¬ p b := byinduction j using Nat.strongRecOn with| ind j ih =>by_cases e : ∃ k, k < j ∧ p k· obtain ⟨k,lt,ok⟩ := eexact ih k lt ok· exact ⟨j,yes,fun b lt pb => e ⟨b,lt,pb⟩⟩private theorem right_step {r allow mark w ts} (c : Nat → EdgeCertificate)(arr : ∀ i, Arrow r allow mark w ts (c i)) (cont : ∀ i,(c i).b=(c (i+1)).a)(i : Nat) (p : ts.oddRow (c i).a.tag=false) (q : ts.right (c i).a.tag=false) :Holds r allow mark w (rightward ts (c i).a (c (i+1)).a) := byhave ending : endOfRow ts (c i).a=false := by simp [endOfRow,p,q]have hs := (arr i).2.2.2simp only [chosenSuccessor,ending,Bool.false_and,Bool.false_eq_true,if_false,p] at hshave h := (arr i).2.2.1.1simp only [q,Bool.not_false,flagQ,if_true] at hrw [← cont, ← hs.1]exact hprivate theorem first_row {r allow mark w ts} (law : Laws ts) (c : Nat → EdgeCertificate)(arr : ∀ i, Arrow r allow mark w ts (c i)) (cont : ∀ i,(c i).b=(c (i+1)).a)(s : Nat) (left : ts.left (c s).a.tag=true) (par : ts.oddRow (c s).a.tag=false) :∃ n, @Row r allow mark w ts c s n false := byobtain ⟨j,ret⟩ := later_return c arr cont shave parity (a) (before : ∀ k, k<a → ts.right (c (s+k)).a.tag≠true) :ts.oddRow (c (s+a)).a.tag=false := byinduction a with| zero => simpa using par| succ a ih =>have p := ih (fun k lt => before k (by omega))have q : ts.right (c (s+a)).a.tag=false := byhave n := before a (by omega)cases b : ts.right (c (s+a)).a.tag <;> simp_allhave step := right_step c arr cont (s+a) p qexact (law.horiz _ _ step.1).2.2.2.2.1.symm.trans phave hasRight : ∃ a, ts.right (c (s+a)).a.tag=true := byapply Classical.byContradiction; intro missinghave noR (a) : ts.right (c (s+a)).a.tag≠true := fun ok => missing ⟨a,ok⟩have p := parity j (fun k _ => noR k)have q : ts.right (c (s+j)).a.tag=false := bycases b : ts.right (c (s+j)).a.tag <;> simp_allsimp [Return,endOfRow,p,q] at retobtain ⟨a,ha⟩ := hasRightobtain ⟨n,last,prior⟩ := min_bounded (fun i => ts.right (c (s+i)).a.tag=true) a harefine ⟨n,?_,?_,?_,?_⟩· intro k le; exact parity k (fun b lt => prior b (by omega))· simpa [column] using left· exact last· intro k lthave p := parity k (fun b lb => prior b (by omega))have q : ts.right (c (s+k)).a.tag=false := byhave off := prior k ltcases b : ts.right (c (s+k)).a.tag <;> simp_allexact right_step c arr cont (s+k) p qprivate theorem row_const (n : Nat) (f : Nat → Bool) (step : ∀ j, j<n → f j = f (j+1)) :∀ j, j≤n → f j = f 0 := byintro jinduction j with| zero => simp| succ j ih => intro le; exact (step j (by omega)).symm.trans (ih (by omega))private theorem next_row {r allow mark w ts} (law : Laws ts) (c : Nat → EdgeCertificate)(arr : ∀ i, Arrow r allow mark w ts (c i)) (cont : ∀ i,(c i).b=(c (i+1)).a)(funct : ∀ i, Functional r allow mark w ts (c i).a){s n odd} (row : @Row r allow mark w ts c s n odd)(nonbottom : ∀ j, j≤n → ts.bottom (c (s+column n odd j)).a.tag=false) :@Row r allow mark w ts c (s+n+1) n (!odd) ∧∀ j, j≤n → Holds r allow mark w(downward ts (c (s+column n odd j)).a (c ((s+n+1)+column n (!odd) j)).a) := bylet ix (j : Nat) := s+column n odd jhave tr := advance_row law c arr cont funct ix n odd row.links nonbottom row.parity row.left row.righthave en : ix (column n (!odd) 0)=s+n := by cases odd <;> simp [ix,column]simp only [en] at trobtain ⟨vs,hs⟩ := lower_row law c arr funct ix n row.links nonbottomhave down (j : Nat) (le : j≤n) : Holds r allow mark w(downward ts (c (ix j)).a (c ((s+n+1)+column n (!odd) j)).a) := byrw [tr j le]; exact vs j lerefine ⟨⟨?_,?_,?_,?_⟩,down⟩· intro j leexact (law.vert _ _ (down j le).1).2.2.2.2.2.trans (congrArg Bool.not (row.parity _ le))· exact (law.vert _ _ (down 0 (by omega)).1).2.2.1.trans row.left· exact (law.vert _ _ (down n (by omega)).1).2.2.2.1.trans row.right· intro j lt; rw [tr j (by omega),tr (j+1) (by omega)]; exact hs _ lt/-- A suffix of a rectangle indexed by its specified first row. Only thisfirst row may be top. Its actual top flag is supplied by the trace. -/private structure Strip (allow : Tag → Prop) (ts : Tiles) (n : Nat) (first : Nat → Tag) whereh : Natt : Nat → Nat → Taghead : ∀ j, j≤n → t 0 j=first jok : ∀ i j, i≤h → j≤n → allow (t i j)horizontal : ∀ i j, i≤h → j<n → ts.horizontal (t i j) (t i (j+1))vertical : ∀ i j, i<h → j≤n → ts.vertical (t i j) (t (i+1) j)l : ∀ i j, i≤h → j≤n → (ts.left (t i j)=true ↔ j=0)r : ∀ i j, i≤h → j≤n → (ts.right (t i j)=true ↔ j=n)b : ∀ i j, i≤h → j≤n → (ts.bottom (t i j)=true ↔ i=h)noTop : ∀ i j, 0<i → i≤h → j≤n → ts.top (t i j)=falseprivate theorem build {r allow mark w ts} (law : Laws ts) (c : Nat → EdgeCertificate)(arr : ∀ i, Arrow r allow mark w ts (c i)) (cont : ∀ i,(c i).b=(c (i+1)).a)(funct : ∀ i, Functional r allow mark w ts (c i).a)(J : Nat) (ret : Return ts (c J)=true) (fuel : Nat) :∀ s n odd, s≤J → J-s≤fuel → @Row r allow mark w ts c s n odd →Nonempty (Strip allow ts n (fun j => (c (s+column n odd j)).a.tag)) := byinduction fuel using Nat.strongRecOn with| ind fuel ih =>intro s n odd bound time rowlet tag (j : Nat) := (c (s+column n odd j)).a.taghave ok (j : Nat) : allow (tag j) := (arr _).1.2.2.1have H (j) (lt : j<n) : ts.horizontal (tag j) (tag (j+1)) := (row.links j lt).1have L (j) (le : j≤n) : ts.left (tag j)=true ↔ j=0 := bycases j with| zero => simp [tag,row.left]| succ j => simp [(law.horiz _ _ (H j (by omega))).2.1]have R (j) (le : j≤n) : ts.right (tag j)=true ↔ j=n := byby_cases eq : j=n· subst j; simp [tag,row.right]· have lt : j<n := by omegasimp [(law.horiz _ _ (H j lt)).1,eq]have B := row_const n (fun j => ts.bottom (tag j)) (fun j lt => (law.horiz _ _ (H j lt)).2.2.2.1)cases bot : ts.bottom (tag 0) with| true =>refine ⟨⟨0,fun _ => tag,fun _ _ => rfl,fun _ j _ _ => ok j,fun _ j _ lt => H j lt,fun _ _ lt _ => by omega,fun _ j _ => L j,fun _ j _ => R j,?_,fun _ _ pos le _ => by omega⟩⟩intro i j il jlhave bi := (B j jl).trans botsimp [bi,Nat.le_zero.mp il]| false =>have nonbottom (j : Nat) (le : j≤n) : ts.bottom (tag j)=false := (B j le).trans bothave nextLe : s+n+1≤J := byapply Classical.byContradiction; intro shorthave small : J-s≤n := by omegalet j := column n odd (J-s)have inRow : j≤n := by cases odd <;> simp [j,column,small,Nat.sub_le]have atJ : s+column n odd j=J := by cases odd <;> simp [j,column] <;> omegahave off := nonbottom j inRowchange ts.bottom (c (s+column n odd j)).a.tag=false at offrw [atJ] at offsimp [Return,off] at retobtain ⟨low,V⟩ := next_row law c arr cont funct row nonbottomobtain ⟨below⟩ := ih (J-(s+n+1)) (by omega) (s+n+1) n (!odd) nextLe (by omega) lowlet t : Nat → Nat → Tag| 0 => tag| i+1 => below.t irefine ⟨⟨below.h+1,t,fun _ _ => rfl,?_,?_,?_,?_,?_,?_,?_⟩⟩· intro i j le jl; cases i with| zero => exact ok j| succ i => exact below.ok i j (by omega) jl· intro i j le jl; cases i with| zero => exact H j jl| succ i => exact below.horizontal i j (by omega) jl· intro i j lt jl; cases i with| zero =>change ts.vertical (tag j) (below.t 0 j)rw [below.head _ jl]; exact (V j jl).1| succ i => exact below.vertical i j (by omega) jl· intro i j le jl; cases i with| zero => exact L j jl| succ i => exact below.l i j (by omega) jl· intro i j le jl; cases i with| zero => exact R j jl| succ i => exact below.r i j (by omega) jl· intro i j le jl; cases i with| zero => change ts.bottom (tag j)=true ↔ _; simp [nonbottom j jl]| succ i => exact (below.b i j (by omega) jl).trans (by omega)· intro i j pos le jlcases i with| zero => omega| succ i =>cases i with| zero =>change ts.top (below.t 0 j)=falserw [below.head _ jl]; exact (law.vert _ _ (V j jl).1).2.1| succ i => exact below.noTop _ j (by omega) (by omega) jl/-- Any indefinitely continued trace of actual arrows, with directionalfunctionality at each visited source, gives a positive legal rectangle.The hypotheses only concern the trace in the original word. -/theorem rectangle_of_trace {r allow mark w ts} (law : Laws ts) (c : Nat → EdgeCertificate)(arr : ∀ i, Arrow r allow mark w ts (c i)) (cont : ∀ i,(c i).b=(c (i+1)).a)(funct : ∀ i, Functional r allow mark w ts (c i).a) : Nonempty (Rectangle allow ts) := byobtain ⟨k,ret⟩ := later_return c arr cont 0simp only [Nat.zero_add] at rethave start := return_target _ (arr k) retrw [cont] at startlet s := k+1obtain ⟨n,row⟩ := first_row law c arr cont s start.2.1 start.2.2.1obtain ⟨off,ending⟩ := later_return c arr cont shave tops := row_const n (fun j => ts.top (c (s+j)).a.tag)(fun j lt => (law.horiz _ _ (row.links j lt).1).2.2.1)obtain ⟨box⟩ := build law c arr cont funct (s+off) ending off s n false (by omega) (by omega) rowrefine ⟨⟨box.h,n,box.t,box.ok,box.horizontal,box.vertical,box.l,box.r,?_,box.b⟩⟩intro i j le jlcases i with| zero =>rw [box.head j jl]have same := (tops j jl).trans (by simpa [s] using start.1)simpa [column] using (show ts.top (c (s+j)).a.tag=true ↔ 0=0 from by simp [same])| succ i => simp [box.noTop _ j (by omega) le jl]end P455GridAssemblyend/- Begin Problem455PaddedWordSlots (from finite-semigroup-identity-bases). -/sectionnamespace P455PaddedWordopen P455PaddedMatchings P455PaddedPorts P455RectangleRank Problem455.Slots P455Witnessdef text (h w k : Nat) (tag : Nat→Tag) (bit : Nat→Bool) := word (w*h) (middle h w k tag) (tail (w*h)) bittheorem range_cut {i n : Nat} (lt : i<n) :List.range n=List.range i ++ i :: List.range' (i+1) (n-(i+1)) := byhave app := List.range'_append_1 (s:=0) (m:=i+1) (n:=n-(i+1))rw [show i+1+(n-(i+1))=n by omega] at appsimpa [←List.range_eq_range',List.range_succ,List.append_assoc] using app.symmtheorem phase_cut {h w k : Nat} (tag : Nat→Tag) (bits : Nat→Bool) (p : Fin 5) :∃ post, text h w k tag bits=(((List.range (w*h)).flatMap privateCell) ++ portChunks h w p.val) ++ letters (matching h w p.val) ++ post := bylet rest := (List.range' (p.val+1) (5-(p.val+1))).flatMap fun a=>letters (matching h w a)refine ⟨rest ++ suffix h w k tag ++ (List.range (w*h)).flatMap (mutableCell bits) ++ tail (w*h),?_⟩have e : portChunks h w 5 = portChunks h w p.val ++ letters (matching h w p.val) ++ rest := byunfold portChunksconv => lhs; rw [range_cut p.isLt]simp [rest,List.flatMap_append,List.flatMap_cons,List.append_assoc]simp [text,word,middle,e,List.append_assoc]theorem phase_index {h w : Nat} (size : 1<w*h) (p : Fin 5) (i a : Nat)(lt : i<w*h) (role : a∈roles i) :(((List.range (w*h)).flatMap privateCell) ++ portChunks h w p.val).count a=3+2*p.val := bysimp only [List.count_append,private_counts i a role,chunks_count size p.val i a role,if_pos lt]; omegatheorem private_cut {h w k : Nat} (tag : Nat→Tag) (bits : Nat→Bool) {i : Nat} (lt : i<w*h) :∃ post,text h w k tag bits=(List.range i).flatMap privateCell ++ privateCell i ++ post := bylet rest := (List.range' (i+1) (w*h-(i+1))).flatMap privateCellrefine ⟨rest++middle h w k tag++(List.range (w*h)).flatMap (mutableCell bits)++tail (w*h),?_⟩have e : (List.range (w*h)).flatMap privateCell=(List.range i).flatMap privateCell ++ privateCell i ++ rest := byconv => lhs; rw [range_cut lt]simp [rest,List.flatMap_append,List.flatMap_cons,List.append_assoc]simp [text,word,e,List.append_assoc]theorem small_slots {h w k : Nat} (size : 1<w*h) (tag : Nat→Tag) (bits : Nat→Bool) :∀ a∈text h w k tag bits, ∀ d, slotStart d → Covered (text h w k tag bits) a d := byintro a mem d sllet i := a/2have role : a∈roles i := by simp only [roles,List.mem_cons,List.not_mem_nil,or_false,owner,mate,i]; omegahave lt : i<w*h := byhave positive := List.count_pos_iff.mpr memrw [text,word_count size tag bits i a role] at positivesplit at positive <;> omegaby_cases early : d=0 ∨ d=1· obtain ⟨post,cut⟩ := private_cut tag bits ltrw [cut]; exact private_slot_bound _ _ i a d role (by simp [private_counts i a role]) early· have place : ∃ p : Fin 5, d=3+2*p.val := byunfold slotStart at slrcases sl with e|e|e|e|e|e|e· exact (early (.inl e)).elim· exact (early (.inr e)).elim· exact ⟨0,e⟩· exact ⟨1,e⟩· exact ⟨2,e⟩· exact ⟨3,e⟩· exact ⟨4,e⟩obtain ⟨p,rfl⟩ := placeobtain ⟨post,cut⟩ := phase_cut tag bits prw [cut]; exact matching_slot_bound (matching_unique size _) i a _ role ((matching_cells size _ _).mpr lt)(phase_index size p i a lt role)def node (tag : Nat→Tag) (i : Nat) : Node := ⟨owner i,mate i,tag i⟩theorem port_iff {h w k : Nat} (size : 1<w*h) (tag : Nat→Tag) (bits : Nat→Bool)(allow : Tag→Prop) (mark : Marking) (p : Fin 5) {i j : Nat} (ne : i≠j) (li : i<w*h) (lj : j<w*h) :let H := Holds (k+16) allow mark (text h w k tag bits)H (orientedPort p.val (node tag i) (node tag j)) ↔ H (typedNode (node tag i)) ∧H (typedNode (node tag j)) ∧ H (earlyDisjoint (roles i) (roles j)) ∧ Block.pair i j∈matching h w p.val := byobtain ⟨post,cut⟩ := phase_cut tag bits pdsimp onlyrw [cut]exact oriented_port_iff (by omega) allow mark p _ _ ne (matching_unique size _) ((matching_cells size _ _).mpr li)((matching_cells size _ _).mpr lj) (fun a m=> (List.mem_append.mp m).elim(fun x=>phase_index size p i a li x) (fun x=>phase_index size p j a lj x))end P455PaddedWordend/- Begin Problem455GuardProduct (from finite-semigroup-identity-bases). -/sectionnamespace P455GuardProductopen P455Witness P455SlotProduct P455SourceFamilies P455CrossedSupportopen P455PortReflection P455SlotSaturation P455DefectRename P455FirstRewriteopen Problem455.Slotsabbrev W := List Natinductive Guard where| slot (s : SlotCertificate)| func (f : FunctionalityCertificate)def Guard.anchor : Guard → Node | .slot s => s.anchor | .func f => f.anchordef Guard.bit : Guard → Bool | .slot s => s.bit | .func f => f.bitdef Guard.isFunc : Guard → Bool | .slot _ => false | .func _ => truedef Guard.query (g : Guard) (r : Nat) (ts : Tiles) : Query := match g with| .slot s => s.query r | .func f => f.query tsdef Guard.withBit (g : Guard) (b : Bool) : Guard := match g with| .slot s => .slot {s with bit := b} | .func f => .func {f with bit := b}def width (isFunc : Bool) : Nat := if isFunc then 8 else 43def words (r : Nat) (kind : Bool) := Problem455Finite.wordsUpTo (List.range (width kind)) (width kind*r)structure Index (r : Nat) (allow : Tag → Prop) (ts : Tiles) wherekind : Boolpos : Fin (words r kind).lengtha : Fin (width kind)b : Fin (width kind)cap : P455Closure.Cap r ((words r kind).get pos)accepted : ∃ g : Guard, g.isFunc = kind ∧ g.anchor.owner = a.val ∧ g.anchor.mate = b.val ∧Holds r allow (pairMark a b) ((words r kind).get pos) (g.query r ts)def Index.T (i : Index r allow ts) := (words r i.kind).get i.posdef Index.R (i : Index r allow ts) := rules r allow (pairMark i.a i.b)abbrev Carrier (r : Nat) (allow : Tag → Prop) (ts : Tiles) :=(i : Index r allow ts) → P455Quotient.Q i.R i.Tdef product (r : Nat) (allow : Tag → Prop) (ts : Tiles) : Model (Carrier r allow ts) whereop := fun u v i => P455Quotient.mul i.R i.cap (u i) (v i)unit := fun i => P455Quotient.ofWord i.R i.T []assoc := fun u v w => funext (fun i => P455Quotient.mul_assoc i.R i.cap (u i) (v i) (w i))oneL := fun u => funext (fun i => (P455Quotient.unit_laws i.R i.cap (u i)).1)oneR := fun u => funext (fun i => (P455Quotient.unit_laws i.R i.cap (u i)).2)theorem observed {r allow ts u w} (valid : (product r allow ts).Valid u w)(i : Index r allow ts) (h : Nat → W) :P455Quotient.ofWord i.R i.T (u.flatMap h) = P455Quotient.ofWord i.R i.T (w.flatMap h) := bylet val : Nat → Carrier r allow ts := fun x j => P455Quotient.ofWord j.R j.T (h x)have comp (z : W) : (product r allow ts).eval val z i = P455Quotient.ofWord i.R i.T (z.flatMap h) := byinduction z with| nil => rfl| cons a z ih =>change P455Quotient.mul i.R i.cap (val a i) _ = _rw [ih]; rflexact (comp u).symm.trans ((congrFun (valid val) i).trans (comp w))theorem test_projects {r allow ts u w} (valid : (product r allow ts).Valid u w)(keep : W) {x y : Nat} (ho : x ∈ keep) (hm : y ∈ keep)(g : Guard) (n : Bool) (kind : g.isFunc = n) (len : keep.length ≤ width n)(xa : g.anchor.owner = keep.idxOf x) (yb : g.anchor.mate = keep.idxOf y)(capT : P455Closure.Cap r ((select keep u).map keep.idxOf))(test : Holds r allow (markNode g.anchor) ((select keep u).map keep.idxOf) (g.query r ts)) :select [x,y] u = select [x,y] w := bylet T := (select keep u).map keep.idxOfhave labels : ∀ a ∈ T, a < width n := byintro a ha; obtain ⟨b,hb,rfl⟩ := List.mem_map.mp haexact Nat.lt_of_lt_of_le (List.idxOf_lt_length_of_mem (kept hb)) lenobtain ⟨j,eq⟩ := List.get_of_mem (Problem455Finite.covered (List.range (width n)) _ T(capped_length _ T capT labels) (fun a ha => List.mem_range.mpr (labels a ha)))let a : Fin (width n) := ⟨keep.idxOf x, Nat.lt_of_lt_of_le (List.idxOf_lt_length_of_mem ho) len⟩let b : Fin (width n) := ⟨keep.idxOf y, Nat.lt_of_lt_of_le (List.idxOf_lt_length_of_mem hm) len⟩have fm : markNode g.anchor = pairMark a b := by unfold markNode pairMark; rw [xa,yb]let i : Index r allow ts := ⟨n,j,a,b,eq.symm ▸ capT,g,kind,xa,yb,eq.symm ▸ (fm ▸ test)⟩have coord := observed valid i (image keep)rw [image_word,image_word] at coordhave eqT : T = i.T := eq.symmchange P455Quotient.ofWord i.R i.T T = _ at coordrw [eqT] at coordhave good : P455Quotient.Good i.R i.T i.T := ⟨_,.refl _,[],[],by simp⟩have path := ((P455Quotient.same_nonzero_class i.R good).mp coord).2have pr : select [a.val,b.val] i.T = select [a.val,b.val] ((select keep w).map keep.idxOf) :=path.transport (P := fun z => select [a.val,b.val] i.T = select [a.val,b.val] z) rfl(fun mv old => old.trans (mv.marked_proj _ _ ⟨rfl,rfl⟩))rw [← eqT] at prchange select [keep.idxOf x,keep.idxOf y] ((select keep u).map keep.idxOf) = _ at prrw [← binary_select_map keep u ho hm, ← binary_select_map keep w ho hm] at prhave k (z : W) (c : Nat) (hc : c ∈ select [x,y] z) : c ∈ keep := byrcases (by simpa using kept hc : c=x ∨ c=y) with e|e· exact e ▸ ho· exact e ▸ hmhave decoded := congrArg (List.map (decode keep)) prsimpa only [decode_map (k u),decode_map (k w)] using decodedprivate theorem free_all (qs : List Query) (all : ∀ q ∈ qs, markFree q = true) : markFree (allQ qs) = true := byinduction qs with| nil => rfl| cons q qs ih => simp [allQ,markFree,all q (by simp),ih (fun t ht => all t (by simp [ht]))]private theorem free_sep (xs : W) : markFree (differentBlocks xs) = true := byinduction xs with| nil => rfl| cons a xs ih =>have every : markFree (allQ (xs.map (Query.separate a))) = true := byapply free_all; intro q h; obtain ⟨_,_,rfl⟩ := List.mem_map.mp h; rflsimp [differentBlocks,markFree,ih,every]theorem free_term (r o i : Nat) (d : SlotDefect) : markFree (terminalSlot r o i d) = true := bycases d with| deficient => rfl| overflow xs =>have terms : markFree (allQ (xs.map fun a => Query.both (.count a r) (.slot o i a))) = true := byapply free_all; intro q h; obtain ⟨_,_,rfl⟩ := List.mem_map.mp h; rflsimp [terminalSlot,allQ,markFree,terms,free_sep]private theorem free_route (s : SlotCertificate) (r a : Nat) (p : List P455Paths.Step) :markFree (route r a p (fun o => terminalSlot r o s.terminalIndex s.defect)) = true := byinduction p generalizing a with| nil => exact free_term ..| cons bc p ih =>have ct : markFree (contact r a bc.1 bc.2) = true := bycases c : bc.2 with| record tag rev => cases rev <;> rfl| port phase rev => rflsimp [route,markFree,ct,ih]def Guard.tail (g : Guard) (r : Nat) (ts : Tiles) : Query := match g with| .slot s => allQ [.fixed (s.steps.length ≤ 6),route r (picked s) s.steps (fun o => terminalSlot r o s.terminalIndex s.defect)]| .func f => allQ [neighbor ts f.anchor f.b f.dir,neighbor ts f.anchor f.c f.dir,.separate (if f.distinguishMate then f.b.mate else f.b.owner) (if f.distinguishMate then f.c.mate else f.c.owner)]theorem tail_free (g : Guard) (r : Nat) (ts : Tiles) : markFree (g.tail r ts) = true := bycases g with| slot s => simp [Guard.tail,allQ,markFree,free_route]| func f => simp [Guard.tail,allQ,markFree,free_neighbor]theorem split_query (g : Guard) (r : Nat) (ts : Tiles) (b : Bool) :(g.withBit b).query r ts = .both (markedNode g.anchor b) (g.tail r ts) := by cases g <;> rfltheorem replay {r allow ts u v} (path : P455Quotient.Walk (P455Closure.Move r allow noMark) u v)(g : Guard) (ok : Holds r allow (markNode g.anchor) u (g.query r ts)) :∃ b, Holds r allow (markNode g.anchor) v ((g.withBit b).query r ts) := byhave same : g.withBit g.bit = g := by cases g <;> rflhave parts := okrw [← same,split_query] at partsobtain ⟨ne,length,tag,_,eq⟩ := parts.1have recProof : Holds r allow noMark u (typedNode g.anchor) := ⟨ne,length,tag,g.bit,eq⟩have obs := path.transport recProof (fun mv old => (query_invariant mv _).mp old)obtain ⟨ne',length',tag',b,eq'⟩ := obshave tail : Holds r allow noMark u (g.tail r ts) := remark (tail_free ..) parts.2have last := path.transport tail (fun mv old => (query_invariant mv _).mp old)refine ⟨b,?_⟩rw [split_query]exact ⟨⟨ne',length',tag',.inl ⟨rfl,rfl⟩,eq'⟩,remark (tail_free ..) last⟩end P455GuardProductend/- Begin Problem455UniformCross (from finite-semigroup-identity-bases). -/sectionnamespace P455UniformCrossopen P455Witness P455SourceFamilies P455SourceTheorem P455OriginalWalkopen P455ContactLift P455CrossedSupport P455SingletonEvaluation Problem455.Slotstheorem crossed {r allow mark T} (capT : P455Quotient.Cap r T)(ts : Tiles) (c : Certificate) (tester : Holds r allow mark T (c.query r ts))(U : List Nat) (uniform : ∀ a ∈ U, U.count a = r) (cmp : Compressed r U)(x y : Nat) (flip : ClosedFlip r allow U x y)(val : Nat → P455Quotient.Q (rules r allow mark) T) (h : Nat → List Nat)(reps : ∀ a ∈ U, P455Quotient.ofWord (rules r allow mark) T (h a) = val a)(live : P455Quotient.eval (rules r allow mark) capT val U ≠ P455Quotient.zero (rules r allow mark) T)(s : Bool) (cross : Crosses (markedRecord c s) h x y) :Violation r allow ts U x y := byhave capU : P455Closure.Cap r U := byintro aby_cases ha : a ∈ U· exact Nat.le_of_eq (uniform a ha)· simp [List.count_eq_zero.mpr ha]obtain ⟨hr,cx,cy,_⟩ := flip_counts capU fliphave pos : 0 < r := by omegaobtain ⟨seed,side,img⟩ := choose_seed c s false crosshave source : Supplies U h r seed (startLabel c s false) :=⟨side.elim (fun eq => eq ▸ cx) (fun eq => eq ▸ cy),img⟩let ident := fun a : Nat => [a]have exp : P455Retained.Expansion U ident (fun _ => True) :=⟨fun _ _ _ => rfl, fun _ _ f => (f True.intro).elim⟩have back : U.flatMap ident = U := by simp [ident]have guard : OriginalGuard r allow mark (U.flatMap ident) (fun _ => True) seed 6 := byrw [back]intro t _refine ⟨True.intro,?_⟩intro i _ a occobtain ⟨j,seen⟩ := occexact ⟨True.intro,uniform a (stamped_mem_label _ _ (a,j) (seen.subset (by simp)))⟩obtain ⟨_,_,_,_,_,_,_,read,_⟩ := arbitrary_reps_original_gadget capT val U h reps live ts c testers false seed hr source exp (back.symm ▸ capU) guardrw [back] at readlet R := rules r allow markhave ev := P455Quotient.eval_rep R capT val U h repshave good := (P455Quotient.nonzero_iff R).mp (ev ▸ live)have capH := P455Quotient.good_cap R capT goodlet d := donor U h rrefine ⟨transferred d c,s,?_,?_⟩· rw [changed_anchor]rcases cross with ⟨xo,ym⟩|⟨yo,xm⟩· exact .inl ⟨donor_eq pos capH ⟨cx,xo⟩,donor_eq pos capH ⟨cy,ym⟩⟩· exact .inr ⟨donor_eq pos capH ⟨cy,yo⟩,donor_eq pos capH ⟨cx,xm⟩⟩· rw [reindexed_marks]; exact read cmptheorem crossed_word {r allow mark T} (capT : P455Quotient.Cap r T)(ts : Tiles) (c : Certificate) (tester : Holds r allow mark T (c.query r ts))(U : List Nat) (uniform : ∀ a ∈ U, U.count a = r) (cmp : Compressed r U)(x y : Nat) (flip : ClosedFlip r allow U x y) (h : Nat → List Nat)(good : P455Quotient.Good (rules r allow mark) T (U.flatMap h))(s : Bool) (cross : Crosses (markedRecord c s) h x y) : Violation r allow ts U x y := bylet R := rules r allow marklet val := fun a => P455Quotient.ofWord R T (h a)apply crossed capT ts c tester U uniform cmp x y flip val h (fun _ _ => rfl) _ s crossrw [P455Quotient.eval_rep R capT val U h (fun _ _ => rfl)]exact (P455Quotient.nonzero_iff R).mpr goodend P455UniformCrossend/- Begin Problem455PaddedAssembly (from finite-semigroup-identity-bases). -/sectionnamespace P455PaddedTilesopen P455Witnessvariable {n : Nat} {M : MachineTable n}private theorem neg_of_ne {a b : Bool} (h : a≠b) : b= !a := bycases a <;> cases b <;> simp_alltheorem system_laws (n : Nat) : P455GridRows.Laws (system n) wherehoriz := byrintro _ _ ⟨p,q,rfl,rfl,ok⟩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⟩vert := byrintro _ _ ⟨p,q,rfl,rfl,ok⟩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⟩private theorem odd_next (i : Nat) : odd (i+1)= !odd i := byby_cases p : i%2=1· simp [odd,p,show (i+1)%2≠1 by omega]· simp [odd,p,show (i+1)%2=1 by omega]private theorem flag_eq {b : Bool} {p : Prop} [Decidable p] (h : b=true ↔ p) : b=decide p := bycases b <;> by_cases hp : p <;> simp_alldef from_assembly (A : P455GridAssembly.Rectangle (allowed M) (system n)) :Rectangle M (A.width+1) (A.height+1) wherepositiveW := by omegapositiveH := by omegatag := A.tileeligible := fun _ iy _ jx => A.allowed _ _ (by omega) (by omega)right := fun _ iy _ jx => A.horiz _ _ (by omega) (by omega)down := fun _ iy _ jx => A.vert _ _ (by omega) (by omega)flags := byintro y iy x jxhave hy : y≤A.height := by omegahave hx : x≤A.width := by omegahave tops := A.top y x hy hxhave lefts := A.left y x hy hxrefine ⟨flag_eq lefts,flag_eq ((A.right y x hy hx).trans (by omega)),flag_eq tops,flag_eq ((A.bottom y x hy hx).trans (by omega)),?_,?_⟩· clear tops lefts iyinduction y with| zero =>obtain ⟨p,eq,ok⟩ := A.allowed 0 x (by omega) hxhave top := (A.top 0 x (by omega) hx).mpr rflrw [←eq] at top ⊢exact (ok.2.2.2.2.2.1 top).1| succ y ih =>have pr := (system_laws n).vert _ _ (A.vert y x (by omega) hx)rw [pr.2.2.2.2.2,ih (by omega),odd_next]· clear tops lefts jxinduction x with| zero =>obtain ⟨p,eq,ok⟩ := A.allowed y 0 hy (by omega)have left := (A.left y 0 hy (by omega)).mpr rflrw [←eq] at left ⊢exact ok.2.2.2.2.1 left| succ x ih =>have pr := (system_laws n).horiz _ _ (A.horiz y x hy (by omega))rw [pr.2.2.2.2.2,ih (by omega),odd_next]/-- Last row s is the accepting configuration. The trace uses width+1cells, including when the last column is zero. -/noncomputable def assembly_trace (A : P455GridAssembly.Rectangle (allowed M) (system n)) :AcceptingTrace M (A.width+1) A.height := bysimpa using read_trace (from_assembly A)/-- Infinite continuation of literal source-word arrows now yieldsa finite accepting trace of the specified transition table. -/theorem accepts_of_arrows {r : Nat} {mark : Marking} {w : List Nat} (c : Nat → EdgeCertificate)(edges : ∀ i, P455GridRows.Arrow r (allowed M) mark w (system n) (c i))(cont : ∀ i, (c i).b = (c (i+1)).a)(functional : ∀ i, P455GridRows.Functional r (allowed M) mark w (system n) (c i).a) :∃ width s, Nonempty (AcceptingTrace M width s) := byobtain ⟨R⟩ := P455GridAssembly.rectangle_of_trace (system_laws n) c edges cont functionalexact ⟨R.width+1,R.height,⟨assembly_trace R⟩⟩end P455PaddedTilesend/- Begin Problem455PaddedOrders (from finite-semigroup-identity-bases). -/sectionnamespace P455PaddedWordopen P455PaddedPorts P455PaddedMatchings P455RectangleRank P455Witness Problem455.Slotsprivate theorem in_stamp (n : Nat→Nat) (w : List Nat) {a j : Nat}(lo : n a≤j) (hi : j<n a+w.count a) : (a,j)∈stamp n w := byobtain ⟨p,t,e,ct⟩ := P455SlotOrigin.occurrence_cut w a (j-n a) (by omega)rw [e,stamp_append,stamp]apply List.mem_append_righthave idx : advance n p a=j := by simp [advance,ct]; omegarw [idx]; exact List.mem_cons_selftheorem sees_across (l t : List Nat) (a i b j : Nat) (inL : i<l.count a)(inR : l.count b≤j) (both : j<(l++t).count b) : sees (l++t) [(a,i),(b,j)] := byunfold sees eventsrw [stamp_append]have left : (a,i)∈stamp (fun _=>0) l := in_stamp _ l (by omega) (by simpa using inL)have right : (b,j)∈stamp (advance (fun _=>0) l) t := byapply in_stamp <;> simp [advance,List.count_append] at * <;> omegaexact ((List.singleton_sublist.mpr left).append (List.singleton_sublist.mpr right) :([(a,i)]++[(b,j)]).Sublist _)theorem early_order {h w k : Nat} (size : 1<w*h) (tag : Nat→Tag) (bits : Nat→Bool)(allow : Tag→Prop) (mark : Marking) {i j a b e f : Nat} (lt : i<j) (last : j<w*h)(ra : a∈roles i) (rb : b∈roles j) (ei : e<3) (fi : f<3) :Holds (k+16) allow mark (text h w k tag bits) (earlier a e b f) := byrefine ⟨?_,?_⟩· intro u mrcases (show u=(a,e) ∨ u=(b,f) by simpa using m) with rfl|rfl <;> dsimp <;> omega· obtain ⟨post,cut⟩ := private_cut tag bits lasthave total := word_count (k:=k) size tag bits j b rbrw [if_pos last] at totalchange (text h w k tag bits).count b=_ at totalrw [cut,List.append_assoc] at total ⊢apply sees_across· simpa [private_counts i a ra,lt] using ei· simp [private_counts j b rb]· omegatheorem early_groups {h w k : Nat} (size : 1<w*h) (tag : Nat→Tag) (bits : Nat→Bool)(allow : Tag→Prop) (mark : Marking) {i j : Nat} (ne : i≠j) (li : i<w*h) (lj : j<w*h) :Holds (k+16) allow mark (text h w k tag bits) (earlyDisjoint (roles i) (roles j)) := byby_cases e : i<j· apply Or.inlexact (P455PortReflection.earlyBefore_iff ..).mpr(fun _ ra _ rb => early_order size tag bits allow mark e lj ra rb (by decide) (by decide))· apply Or.inrexact (P455PortReflection.earlyBefore_iff ..).mpr(fun _ ra _ rb => early_order size tag bits allow mark (by omega : j<i) li ra rb (by decide) (by decide))theorem first_owner {h w k : Nat} (size : 1<w*h) (tag : Nat→Tag) (bits : Nat→Bool)(allow : Tag→Prop) (mark : Marking) {i j : Nat} (lt : i<j) (last : j<w*h) :Holds (k+16) allow mark (text h w k tag bits) (earlier (owner i) 0 (owner j) 0) :=early_order size tag bits allow mark lt last (by simp [roles]) (by simp [roles]) (by decide) (by decide)private theorem adjacent_column_cut {h w y x : Nat} (ly : y<h) (lx : x+1<w) :∃ l t, columnCells h w=l++idAt w y x::idAt w y (x+1)::t := bylet restRow := List.range' (x+1+1) (w-(x+1+1))have ec := range_cut lxrw [List.range_succ] at ecchange List.range w=(List.range x ++ [x]) ++ (x+1) :: restRow at echave er := range_cut lylet emit := fun z=>(List.range w).map (idAt w z)refine ⟨(List.range y).flatMap emit ++ (List.range x).map (idAt w y),restRow.map (idAt w y) ++ (List.range' (y+1) (h-(y+1))).flatMap emit,?_⟩unfold columnCellsrw [er,List.flatMap_append,List.flatMap_cons]change _ ++ (emit y ++ _) = _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) := byunfold emit; rw [ec]; simp [List.map_append,List.append_assoc]rw [row]; simp [List.append_assoc,emit]private theorem tags_counts {h w k : Nat} (tag : Nat→Tag) {i a : Nat} (role : a∈roles i) (lt : i<w*h) :((List.range k).flatMap (tagPhase (w*h) tag)).count a=k := byhave z := suffix_count (h:=h) (w:=w) (k:=k) tag i a rolerw [if_pos lt,suffix,List.count_append,count_role _ i a (by simpa [roles] using role),count_one (columns_unique h w) ((columns_cells h w i).mpr lt)] at zomega/-- True for the left-to-right adjacent coordinates on both row parities.Their numeric snake IDs may be increasing or decreasing. -/theorem column_order {h w k : Nat} (size : 1<w*h) (tag : Nat→Tag) (bits : Nat→Bool)(allow : Tag→Prop) (mark : Marking) {y x : Nat} (ly : y<h) (lx : x+1<w) :Holds (k+16) allow mark (text h w k tag bits)(earlier (owner (idAt w y x)) (13+k) (owner (idAt w y (x+1))) (13+k)) := bylet i := idAt w y xlet j := idAt w y (x+1)have ix : i<w*h := id_bound ly (by omega)have jx : j<w*h := id_bound ly lxobtain ⟨l,t,cut⟩ := adjacent_column_cut ly lxhave nd := columns_unique h wrw [cut] at ndhave dedup := List.pairwise_append.mp ndhave noJ : j∉l ++ [i] := byintro mrcases List.mem_append.mp m with m|m· exact dedup.2.2 j m j (by simp [i,j]) rfl· have ne := (List.nodup_cons.mp dedup.2.1).1have eq : j=i := by simpa using mexact ne (List.mem_cons.mpr (.inl eq.symm))let core := (List.range (w*h)).flatMap privateCell ++ portChunks h w 5 ++(List.range k).flatMap (tagPhase (w*h) tag)let L := core ++ (l++[i]).flatMap roleslet Z := (j::t).flatMap roles ++ (List.range (w*h)).flatMap (mutableCell bits) ++ tail (w*h)have whole : text h w k tag bits=L++Z := bychange columnCells h w=l++i::j::t at cutsimp [text,word,middle,suffix,cut,L,Z,core,List.flatMap_append,List.flatMap_cons,List.append_assoc]have occur (u : Nat) (hu : u<w*h) : core.count (owner u)=13+k := byhave role : owner u∈roles u := by simp [roles]simp [core,List.count_append,private_counts u _ role,chunks_count size 5 u _ role,tags_counts tag role hu,hu]; omegahave left : 13+k<L.count (owner i) := byhave one := List.count_pos_iff.mpr (show i∈l++[i] by simp)dsimp only [L]rw [List.count_append,count_role _ i _ (.inl rfl),occur i ix]; omegahave right : L.count (owner j)=13+k := bydsimp only [L]rw [List.count_append,count_role _ j _ (.inl rfl),occur j jx,List.count_eq_zero.mpr noJ,Nat.add_zero]have total := word_count (k:=k) size tag bits j (owner j) (by simp [roles])rw [if_pos jx] at totalchange (text h w k tag bits).count (owner j)=_ at totalchange Holds (k+16) allow mark (text h w k tag bits) (earlier (owner i) (13+k) (owner j) (13+k))rw [whole] at total ⊢refine ⟨?_,sees_across _ _ _ _ _ _ left (by omega) (by omega)⟩intro e mrcases (show e=(_,13+k) ∨ e=(_,13+k) by simpa using m) with rfl|rfl <;> dsimp <;> omegaend P455PaddedWordend/- Begin Problem455GuardRename (from fini